Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

interfaces.py 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. import abc
  27. from typing import Union, Dict, Any, Optional, List, Tuple, Callable
  28. # FIXME: see ISecurityModule.__iter__
  29. # from collections.abc import Iterator
  30. from autobahn.util import public
  31. from autobahn.wamp.types import Challenge, SessionDetails, CloseDetails, CallResult, RegisterOptions, \
  32. SubscribeOptions, Registration, Subscription, Publication, ComponentConfig, TransportDetails
  33. from autobahn.wamp.message import Message, Welcome
  34. __all__ = (
  35. 'IObjectSerializer',
  36. 'ISerializer',
  37. 'IMessage',
  38. 'ITransport',
  39. 'ITransportHandler',
  40. 'ISession',
  41. 'IAuthenticator',
  42. 'IKey',
  43. 'ICryptosignKey',
  44. 'IEthereumKey',
  45. 'ISecurityModule',
  46. 'IPayloadCodec',
  47. )
  48. @public
  49. class IObjectSerializer(abc.ABC):
  50. """
  51. Raw Python object serialization and deserialization. Object serializers are
  52. used by classes implementing WAMP serializers, that is instances of
  53. :class:`autobahn.wamp.interfaces.ISerializer`.
  54. """
  55. @public
  56. @property
  57. @abc.abstractmethod
  58. def NAME(self) -> str:
  59. """
  60. Object serializer name (read-only).
  61. """
  62. @public
  63. @property
  64. @abc.abstractmethod
  65. def BINARY(self) -> bool:
  66. """
  67. Flag (read-only) to indicate if serializer requires a binary clean
  68. transport or if UTF8 transparency is sufficient.
  69. """
  70. @public
  71. @abc.abstractmethod
  72. def serialize(self, obj: Any) -> bytes:
  73. """
  74. Serialize an object to a byte string.
  75. :param obj: Object (any serializable type) to serialize.
  76. :returns: Serialized bytes.
  77. """
  78. @public
  79. @abc.abstractmethod
  80. def unserialize(self, payload: bytes) -> List[Any]:
  81. """
  82. Deserialize objects from a byte string.
  83. :param payload: Objects to deserialize.
  84. :returns: List of deserialized (raw) objects.
  85. """
  86. @public
  87. class ISerializer(abc.ABC):
  88. """
  89. WAMP message serialization and deserialization.
  90. """
  91. @public
  92. @property
  93. @abc.abstractmethod
  94. def MESSAGE_TYPE_MAP(self) -> Dict[int, 'IMessage']:
  95. """
  96. Mapping of WAMP message type codes to WAMP message classes.
  97. """
  98. @public
  99. @property
  100. @abc.abstractmethod
  101. def SERIALIZER_ID(self) -> str:
  102. """
  103. The WAMP serialization format ID as used for WebSocket, e.g. ``"json"`` (or ``"json.batched"``) for JSON.
  104. """
  105. @public
  106. @property
  107. @abc.abstractmethod
  108. def RAWSOCKET_SERIALIZER_ID(self) -> int:
  109. """
  110. The WAMP serialization format ID as used for RawSocket, e.g. ``1`` for JSON.
  111. """
  112. @public
  113. @property
  114. @abc.abstractmethod
  115. def MIME_TYPE(self) -> str:
  116. """
  117. The WAMP serialization format MIME type, e.g. ``"application/json"`` for JSON.
  118. """
  119. @public
  120. @abc.abstractmethod
  121. def serialize(self, message: 'IMessage') -> Tuple[bytes, bool]:
  122. """
  123. Serializes a WAMP message to bytes for sending over a WAMP transport.
  124. :param message: The WAMP message to be serialized.
  125. :returns: A pair ``(payload, is_binary)``.
  126. """
  127. @public
  128. @abc.abstractmethod
  129. def unserialize(self, payload: bytes, is_binary: Optional[bool] = None) -> List['IMessage']:
  130. """
  131. Deserialize bytes from a transport and parse into WAMP messages.
  132. :param payload: Byte string from wire.
  133. :param is_binary: Type of payload. True if payload is a binary string, else
  134. the payload is UTF-8 encoded Unicode text.
  135. :returns: List of WAMP messages.
  136. """
  137. @public
  138. class IMessage(abc.ABC):
  139. """
  140. A WAMP message, e.g. one of the messages defined in the WAMP specification
  141. `here <https://wamp-proto.org/_static/gen/wamp_latest_ietf.html#rfc.section.6.5>`_.
  142. """
  143. @public
  144. @property
  145. @abc.abstractmethod
  146. def MESSAGE_TYPE(self) -> int:
  147. """
  148. WAMP message type code.
  149. """
  150. # the following requires Python 3.3+ and exactly this order of decorators
  151. # http://stackoverflow.com/questions/4474395/staticmethod-and-abc-abstractmethod-will-it-blend
  152. @public
  153. @staticmethod
  154. @abc.abstractmethod
  155. def parse(wmsg) -> 'IMessage':
  156. """
  157. Factory method that parses a unserialized raw message (as returned byte
  158. :func:`autobahn.interfaces.ISerializer.unserialize`) into an instance
  159. of this class.
  160. :returns: The parsed WAMP message.
  161. """
  162. @public
  163. @abc.abstractmethod
  164. def serialize(self, serializer: ISerializer) -> bytes:
  165. """
  166. Serialize this object into a wire level bytes representation and cache
  167. the resulting bytes. If the cache already contains an entry for the given
  168. serializer, return the cached representation directly.
  169. :param serializer: The wire level serializer to use.
  170. :returns: The serialized bytes.
  171. """
  172. @public
  173. @abc.abstractmethod
  174. def uncache(self):
  175. """
  176. Resets the serialization cache for this message.
  177. """
  178. IMessage.register(Message)
  179. @public
  180. class ITransport(abc.ABC):
  181. """
  182. A WAMP transport is a bidirectional, full-duplex, reliable, ordered,
  183. message-based channel.
  184. """
  185. @public
  186. @abc.abstractmethod
  187. def send(self, message: IMessage):
  188. """
  189. Send a WAMP message over the transport to the peer. If the transport is
  190. not open, this raises :class:`autobahn.wamp.exception.TransportLost`.
  191. Returns a deferred/future when the message has been processed and more
  192. messages may be sent. When send() is called while a previous deferred/future
  193. has not yet fired, the send will fail immediately.
  194. :param message: The WAMP message to send over the transport.
  195. """
  196. @public
  197. @abc.abstractmethod
  198. def isOpen(self) -> bool:
  199. """
  200. Check if the transport is open for messaging.
  201. :returns: ``True``, if the transport is open.
  202. """
  203. @public
  204. @property
  205. @abc.abstractmethod
  206. def transport_details(self) -> Optional[TransportDetails]:
  207. """
  208. Return details about the transport (when the transport is open).
  209. """
  210. @public
  211. @abc.abstractmethod
  212. def close(self):
  213. """
  214. Close the transport regularly. The transport will perform any
  215. closing handshake if applicable. This should be used for any
  216. application initiated closing.
  217. """
  218. @public
  219. @abc.abstractmethod
  220. def abort(self):
  221. """
  222. Abort the transport abruptly. The transport will be destroyed as
  223. fast as possible, and without playing nice to the peer. This should
  224. only be used in case of fatal errors, protocol violations or possible
  225. detected attacks.
  226. """
  227. @public
  228. class ITransportHandler(abc.ABC):
  229. @public
  230. @abc.abstractmethod
  231. def onOpen(self, transport: ITransport):
  232. """
  233. Callback fired when transport is open. May run asynchronously. The transport
  234. is considered running and is_open() would return true, as soon as this callback
  235. has completed successfully.
  236. :param transport: The WAMP transport.
  237. """
  238. @public
  239. @abc.abstractmethod
  240. def onMessage(self, message: IMessage):
  241. """
  242. Callback fired when a WAMP message was received. May run asynchronously. The callback
  243. should return or fire the returned deferred/future when it's done processing the message.
  244. In particular, an implementation of this callback must not access the message afterwards.
  245. :param message: The WAMP message received.
  246. """
  247. @public
  248. @abc.abstractmethod
  249. def onClose(self, wasClean: bool):
  250. """
  251. Callback fired when the transport has been closed.
  252. :param wasClean: Indicates if the transport has been closed regularly.
  253. """
  254. # ISession.register collides with the abc.ABCMeta.register method
  255. class _ABC(abc.ABC):
  256. abc_register = abc.ABC.register
  257. @public
  258. class ISession(_ABC):
  259. """
  260. Interface for WAMP sessions.
  261. """
  262. @public
  263. @property
  264. @abc.abstractmethod
  265. def config(self) -> ComponentConfig:
  266. """
  267. Configuration for session.
  268. """
  269. @public
  270. @property
  271. @abc.abstractmethod
  272. def transport(self) -> Optional[ITransport]:
  273. """
  274. When the transport this session is attached to is currently open, this property
  275. can be read from. The property should be considered read-only. When the transport
  276. is gone, this property is set to None.
  277. """
  278. @public
  279. @property
  280. @abc.abstractmethod
  281. def session_details(self) -> Optional[SessionDetails]:
  282. """
  283. Return details about the session, the same as initially provided to the
  284. :meth:`ISession.onJoin` callback on an implementation.
  285. """
  286. @public
  287. @abc.abstractmethod
  288. def onUserError(self, fail, msg):
  289. """
  290. This is called when we try to fire a callback, but get an
  291. exception from user code -- for example, a registered publish
  292. callback or a registered method. By default, this prints the
  293. current stack-trace and then error-message to stdout.
  294. ApplicationSession-derived objects may override this to
  295. provide logging if they prefer. The Twisted implemention does
  296. this. (See :class:`autobahn.twisted.wamp.ApplicationSession`)
  297. :param fail: The failure that occurred.
  298. :type fail: instance implementing txaio.IFailedFuture
  299. :param msg: an informative message from the library. It is
  300. suggested you log this immediately after the exception.
  301. :type msg: str
  302. """
  303. @public
  304. @abc.abstractmethod
  305. def onConnect(self):
  306. """
  307. Callback fired when the transport this session will run over has been established.
  308. """
  309. @public
  310. @abc.abstractmethod
  311. def join(self,
  312. realm: str,
  313. authmethods: Optional[List[str]] = None,
  314. authid: Optional[str] = None,
  315. authrole: Optional[str] = None,
  316. authextra: Optional[Dict[str, Any]] = None,
  317. resumable: Optional[bool] = None,
  318. resume_session: Optional[int] = None,
  319. resume_token: Optional[str] = None):
  320. """
  321. Attach the session to the given realm. A session is open as soon as it is attached to a realm.
  322. """
  323. @public
  324. @abc.abstractmethod
  325. def onChallenge(self, challenge: Challenge) -> str:
  326. """
  327. Callback fired when the peer demands authentication.
  328. May return a Deferred/Future.
  329. :param challenge: The authentication challenge.
  330. """
  331. @public
  332. @abc.abstractmethod
  333. def onWelcome(self, welcome: Welcome) -> Optional[str]:
  334. """
  335. Callback fired after the peer has successfully authenticated. If
  336. this returns anything other than None/False, the session is
  337. aborted and the return value is used as an error message.
  338. May return a Deferred/Future.
  339. .. note::
  340. Before we let user code see the session -- that is, before we fire "join"
  341. we give authentication instances a chance to abort the session. Usually
  342. this would be for "mutual authentication" scenarios. For example, WAMP-SCRAM
  343. uses this to confirm the server-signature.
  344. :param welcome: The WELCOME message received from the server
  345. :return: None, or an error message (using a fixed error URI
  346. ``wamp.error.cannot_authenticate``).
  347. """
  348. @public
  349. @abc.abstractmethod
  350. def onJoin(self, details: SessionDetails):
  351. """
  352. Callback fired when WAMP session has been established.
  353. May return a Deferred/Future.
  354. :param details: Session information.
  355. """
  356. @public
  357. @abc.abstractmethod
  358. def leave(self, reason: Optional[str] = None, message: Optional[str] = None):
  359. """
  360. Actively close this WAMP session.
  361. :param reason: An optional URI for the closing reason. If you
  362. want to permanently log out, this should be ``wamp.close.logout``.
  363. :param message: An optional (human-readable) closing message, intended for
  364. logging purposes.
  365. :return: may return a Future/Deferred that fires when we've disconnected
  366. """
  367. @public
  368. @abc.abstractmethod
  369. def onLeave(self, details: CloseDetails):
  370. """
  371. Callback fired when WAMP session has is closed
  372. :param details: Close information for session.
  373. """
  374. @public
  375. @abc.abstractmethod
  376. def disconnect(self):
  377. """
  378. Close the underlying transport.
  379. """
  380. @public
  381. @abc.abstractmethod
  382. def onDisconnect(self):
  383. """
  384. Callback fired when underlying transport has been closed.
  385. """
  386. @public
  387. @abc.abstractmethod
  388. def is_connected(self) -> bool:
  389. """
  390. Check if the underlying transport is connected.
  391. """
  392. @public
  393. @abc.abstractmethod
  394. def is_attached(self) -> bool:
  395. """
  396. Check if the session has currently joined a realm.
  397. """
  398. @public
  399. @abc.abstractmethod
  400. def set_payload_codec(self, payload_codec: Optional['IPayloadCodec']):
  401. """
  402. Set a payload codec on the session. To remove a previously set payload codec,
  403. set the codec to ``None``.
  404. Payload codecs are used with WAMP payload transparency mode.
  405. :param payload_codec: The payload codec that should process application
  406. payload of the given encoding.
  407. """
  408. @public
  409. @abc.abstractmethod
  410. def get_payload_codec(self) -> Optional['IPayloadCodec']:
  411. """
  412. Get the current payload codec (if any) for the session.
  413. Payload codecs are used with WAMP payload transparency mode.
  414. :returns: The current payload codec or ``None`` if no codec is active.
  415. """
  416. @public
  417. @abc.abstractmethod
  418. def define(self, exception: Exception, error: Optional[str] = None):
  419. """
  420. Defines an exception for a WAMP error in the context of this WAMP session.
  421. :param exception: The exception class to define an error mapping for.
  422. :param error: The URI (or URI pattern) the exception class should be mapped for.
  423. Iff the ``exception`` class is decorated, this must be ``None``.
  424. """
  425. @public
  426. @abc.abstractmethod
  427. def call(self, procedure: str, *args, **kwargs) -> Union[Any, CallResult]:
  428. """
  429. Call a remote procedure.
  430. This will return a Deferred/Future, that when resolved, provides the actual result
  431. returned by the called remote procedure.
  432. - If the result is a single positional return value, it'll be returned "as-is".
  433. - If the result contains multiple positional return values or keyword return values,
  434. the result is wrapped in an instance of :class:`autobahn.wamp.types.CallResult`.
  435. - If the call fails, the returned Deferred/Future will be rejected with an instance
  436. of :class:`autobahn.wamp.exception.ApplicationError`.
  437. If ``kwargs`` contains an ``options`` keyword argument that is an instance of
  438. :class:`autobahn.wamp.types.CallOptions`, this will provide specific options for
  439. the call to perform.
  440. When the *Caller* and *Dealer* implementations support canceling of calls, the call may
  441. be canceled by canceling the returned Deferred/Future.
  442. :param procedure: The URI of the remote procedure to be called, e.g. ``"com.myapp.hello"``.
  443. :param args: Any positional arguments for the call.
  444. :param kwargs: Any keyword arguments for the call.
  445. :returns: A Deferred/Future for the call result.
  446. """
  447. @public
  448. @abc.abstractmethod
  449. def register(self, endpoint: Union[Callable, Any], procedure: Optional[str] = None,
  450. options: Optional[RegisterOptions] = None, prefix: Optional[str] = None,
  451. check_types: Optional[bool] = None) -> Union[Registration, List[Registration]]:
  452. """
  453. Register a procedure for remote calling.
  454. When ``endpoint`` is a callable (function, method or object that implements ``__call__``),
  455. then ``procedure`` must be provided and an instance of
  456. :tx:`twisted.internet.defer.Deferred` (when running on **Twisted**) or an instance
  457. of :py:class:`asyncio.Future` (when running on **asyncio**) is returned.
  458. - If the registration *succeeds* the returned Deferred/Future will *resolve* to
  459. an object that implements :class:`autobahn.wamp.interfaces.IRegistration`.
  460. - If the registration *fails* the returned Deferred/Future will *reject* with an
  461. instance of :class:`autobahn.wamp.exception.ApplicationError`.
  462. When ``endpoint`` is an object, then each of the object's methods that is decorated
  463. with :func:`autobahn.wamp.register` is automatically registered and a (single)
  464. DeferredList or Future is returned that gathers all individual underlying Deferreds/Futures.
  465. :param endpoint: The endpoint called under the procedure.
  466. :param procedure: When ``endpoint`` is a callable, the URI (or URI pattern)
  467. of the procedure to register for. When ``endpoint`` is an object,
  468. the argument is ignored (and should be ``None``).
  469. :param options: Options for registering.
  470. :param prefix: if not None, this specifies a prefix to prepend
  471. to all URIs registered for this class. So if there was an
  472. @wamp.register('method_foo') on a method and
  473. prefix='com.something.' then a method
  474. 'com.something.method_foo' would ultimately be registered.
  475. :param check_types: Enable automatic type checking against (Python 3.5+) type hints
  476. specified on the ``endpoint`` callable. Types are checked at run-time on each
  477. invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
  478. is forwarded to the callee code in ``onUserError`` override method of
  479. :class:`autobahn.wamp.protocol.ApplicationSession`. An error
  480. of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
  481. returned to the caller (via the router).
  482. :returns: A registration or a list of registrations (or errors)
  483. """
  484. @public
  485. @abc.abstractmethod
  486. def publish(self, topic: str, *args, **kwargs) -> Optional[Publication]:
  487. """
  488. Publish an event to a topic.
  489. If ``kwargs`` contains an ``options`` keyword argument that is an instance of
  490. :class:`autobahn.wamp.types.PublishOptions`, this will provide
  491. specific options for the publish to perform.
  492. .. note::
  493. By default, publications are non-acknowledged and the publication can
  494. fail silently, e.g. because the session is not authorized to publish
  495. to the topic.
  496. When publication acknowledgement is requested via ``options.acknowledge == True``,
  497. this function returns a Deferred/Future:
  498. - If the publication succeeds the Deferred/Future will resolve to an object
  499. that implements :class:`autobahn.wamp.interfaces.IPublication`.
  500. - If the publication fails the Deferred/Future will reject with an instance
  501. of :class:`autobahn.wamp.exception.ApplicationError`.
  502. :param topic: The URI of the topic to publish to, e.g. ``"com.myapp.mytopic1"``.
  503. :param args: Arbitrary application payload for the event (positional arguments).
  504. :param kwargs: Arbitrary application payload for the event (keyword arguments).
  505. :returns: Acknowledgement for acknowledge publications - otherwise nothing.
  506. """
  507. @public
  508. @abc.abstractmethod
  509. def subscribe(self, handler: Union[Callable, Any], topic: Optional[str] = None,
  510. options: Optional[SubscribeOptions] = None, check_types: Optional[bool] = None) -> \
  511. Union[Subscription, List[Subscription]]:
  512. """
  513. Subscribe to a topic for receiving events.
  514. When ``handler`` is a callable (function, method or object that implements ``__call__``),
  515. then `topic` must be provided and an instance of
  516. :tx:`twisted.internet.defer.Deferred` (when running on **Twisted**) or an instance
  517. of :class:`asyncio.Future` (when running on **asyncio**) is returned.
  518. - If the subscription succeeds the Deferred/Future will resolve to an object
  519. that implements :class:`autobahn.wamp.interfaces.ISubscription`.
  520. - If the subscription fails the Deferred/Future will reject with an instance
  521. of :class:`autobahn.wamp.exception.ApplicationError`.
  522. When ``handler`` is an object, then each of the object's methods that is decorated
  523. with :func:`autobahn.wamp.subscribe` is automatically subscribed as event handlers,
  524. and a list of Deferreds/Futures is returned that each resolves or rejects as above.
  525. :param handler: The event handler to receive events.
  526. :param topic: When ``handler`` is a callable, the URI (or URI pattern)
  527. of the topic to subscribe to. When ``handler`` is an object, this
  528. value is ignored (and should be ``None``).
  529. :param options: Options for subscribing.
  530. :param check_types: Enable automatic type checking against (Python 3.5+) type hints
  531. specified on the ``endpoint`` callable. Types are checked at run-time on each
  532. invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
  533. is forwarded to the subscriber code in ``onUserError`` override method of
  534. :class:`autobahn.wamp.protocol.ApplicationSession`.
  535. :returns: A single Deferred/Future or a list of such objects
  536. """
  537. class IAuthenticator(abc.ABC):
  538. """
  539. Experimental authentication API.
  540. """
  541. @abc.abstractmethod
  542. def on_challenge(self, session: ISession, challenge: Challenge):
  543. """
  544. Formulate a challenge response for the given session and Challenge
  545. instance. This is sent to the server in the AUTHENTICATE
  546. message.
  547. """
  548. @abc.abstractmethod
  549. def on_welcome(self, authextra: Optional[Dict[str, Any]]) -> Optional[str]:
  550. """
  551. This hook is called when the onWelcome/on_welcome hook is invoked
  552. in the protocol, with the 'authextra' dict extracted from the
  553. Welcome message. Usually this is used to verify the final
  554. message from the server (e.g. for mutual authentication).
  555. :return: None if the session is successful or an error-message
  556. """
  557. @public
  558. class IKey(abc.ABC):
  559. """
  560. Interface to an asymmetric verification key, e.g. a WAMP-Cryptosign client or server authentication
  561. public key (with Ed25519), or a WAMP-XBR data transaction signature public key or address (with Ethereum).
  562. The key implementation can use various methods, such as a key read from a file, database table
  563. or a key residing in a hardware device.
  564. """
  565. @property
  566. @abc.abstractmethod
  567. def security_module(self) -> Optional['ISecurityModule']:
  568. """
  569. When this key is hosted by a security module, return a reference.
  570. If the key is freestanding (exists of its own outside any security
  571. module or key store), return ``None``.
  572. :return: The security module of the key if the key is hosted.
  573. """
  574. @property
  575. @abc.abstractmethod
  576. def key_no(self) -> Optional[int]:
  577. """
  578. When this key is hosted by a security module, return an identifier
  579. to refer to this key within the security module.
  580. If the key is freestanding (exists of its own outside any security
  581. module or key store), return ``None``.
  582. :return: The identifier of this key within the security
  583. module if this key is hosted.
  584. """
  585. @property
  586. @abc.abstractmethod
  587. def key_type(self) -> str:
  588. """
  589. Type of key and signature scheme, currently one of:
  590. * ``ed25519``: Ed25519, that is **EdDSA** signing algo with **Curve25519** elliptic curve and **SHA-512** hash,
  591. used with WAMP-cryptosign session authentication
  592. * ``eth``: Ethereum, that is **ECDSA** signing algo, **secp256k1** elliptic curve and **Keccak-256** hash,
  593. used with WAMP-XBR data and transaction signatures
  594. :return: Key type, one of ``ed25519`` or ``eth``.
  595. """
  596. @abc.abstractmethod
  597. def public_key(self, binary: bool = False) -> Union[str, bytes]:
  598. """
  599. Returns the public key part of a signing key or the (public) verification key.
  600. :param binary: If the return type should be binary instead of hex
  601. :return: The public key in hex or byte encoding.
  602. """
  603. @abc.abstractmethod
  604. def can_sign(self) -> bool:
  605. """
  606. Check if the key can be used to sign and create new signatures, or only to verify signatures.
  607. :returns: ``True``, if the key can be used for signing.
  608. """
  609. @abc.abstractmethod
  610. def sign(self, data: bytes) -> bytes:
  611. """
  612. Sign the given data, only available if ``can_sign == True``. This method (always) runs asynchronously.
  613. :param data: The data to be signed.
  614. :return: The signature, that is a future object that resolves to bytes.
  615. """
  616. @abc.abstractmethod
  617. def recover(self, data: bytes, signature: bytes) -> bytes:
  618. """
  619. Recover the signer from the data signed, and the signature given. This method (always) runs asynchronously.
  620. :param data: The data that was signed.
  621. :param signature: The signature over the data.
  622. :return: The signer public key that signed the data to create the signature given.
  623. """
  624. @public
  625. class ICryptosignKey(IKey):
  626. """
  627. Interface to a WAMP-Cryptosign client authentication (or server verification) key.
  628. """
  629. @abc.abstractmethod
  630. def sign_challenge(self, challenge: Challenge, channel_id: Optional[bytes] = None,
  631. channel_id_type: Optional[str] = None) -> bytes:
  632. """
  633. Sign the data from the given WAMP challenge message, and the optional TLS channel ID
  634. using this key and return a valid signature that can be used in a WAMP-cryptosign
  635. authentication handshake.
  636. :param challenge: The WAMP challenge message as sent or received during the WAMP-cryptosign
  637. authentication handshake. This can be used by WAMP clients to compute the signature
  638. returned in the handshake, or by WAMP routers to verify the signature returned by clients,
  639. during WAMP-cryptosign client authentication.
  640. :param channel_id: Optional TLS channel ID. Using this binds the WAMP session authentication
  641. to the underlying TLS channel, and thus prevents authentication-forwarding attacks.
  642. :param channel_id_type: Optional TLS channel ID type, e.g. ``"tls-unique"``.
  643. :return: The signature, that is a future object that resolves to bytes.
  644. """
  645. @abc.abstractmethod
  646. def verify_challenge(self, challenge: Challenge, signature: bytes, channel_id: Optional[bytes] = None,
  647. channel_id_type: Optional[str] = None) -> bool:
  648. """
  649. Verify the data from the given WAMP challenge message, and the optional TLS channel ID
  650. to be signed by this key.
  651. :param challenge: The WAMP challenge message as sent or received during the WAMP-cryptosign
  652. authentication handshake. This can be used by WAMP clients to compute the signature
  653. returned within the handshake, or by WAMP routers to verify the signature returned by clients,
  654. during WAMP-cryptosign client authentication.
  655. :param signature: The signature to verify.
  656. :param channel_id: Optional TLS channel ID. Using this binds the WAMP session authentication
  657. to the underlying TLS channel, and thus prevents authentication-forwarding attacks.
  658. :param channel_id_type: Optional TLS channel ID type, e.g. ``"tls-unique"``.
  659. :return: Returns ``True`` if the signature over the data matches this key.
  660. """
  661. @public
  662. class IEthereumKey(IKey):
  663. """
  664. Interface to an Ethereum signing (or transaction verification) key, used for WAMP-XBR transaction
  665. signing (or verification).
  666. """
  667. @abc.abstractmethod
  668. def address(self, binary: bool = False) -> Union[str, bytes]:
  669. """
  670. Returns the Ethereum (public) address of the key (which is derived from
  671. the public key).
  672. :param binary: Return address as 160 bits (20 bytes) binary instead of
  673. the ``0x`` prefixed hex, check-summed address as a string.
  674. :return: The address in hex or byte encoding.
  675. """
  676. @abc.abstractmethod
  677. def sign_typed_data(self, data: Dict[str, Any]) -> bytes:
  678. """
  679. Sign the given typed data according to `EIP712 <https://eips.ethereum.org/EIPS/eip-712>`_
  680. and create an Ethereum signature.
  681. :param data: The data to be signed. This must follow EIP712.
  682. :return: The signature, that is a future object that resolves to bytes.
  683. """
  684. @abc.abstractmethod
  685. def verify_typed_data(self, data: Dict[str, Any], signature: bytes, signer_address: Union[str, bytes]) -> bool:
  686. """
  687. Verify the given typed data according to `EIP712 <https://eips.ethereum.org/EIPS/eip-712>`_
  688. to be signed by this key.
  689. :param data: The data to be signed. This must follow EIP712.
  690. :param signature: The signature to be verified.
  691. :param signer_address: Address against which the signature is verified.
  692. :return: Returns ``True`` if the signature over the data matches this key.
  693. """
  694. @public
  695. class ISecurityModule(abc.ABC):
  696. """
  697. Interface for key security modules, which
  698. * include filesystem and HSM backed persistent key implementations, and
  699. * provides secure key signature generation and verification with
  700. * two key types and signature schemes
  701. The two key types and signature schemes support WAMP-cryptosign based authentication
  702. for WAMP sessions, and WAMP-XBR based signed transactions and data encryption.
  703. References:
  704. * `SE050 APDU Specification (AN12413) <https://www.nxp.com/docs/en/application-note/AN12413.pdf>`_
  705. * https://neuromancer.sk/std/secg/secp256r1
  706. * https://neuromancer.sk/std/secg/secp256k1
  707. * https://asecuritysite.com/curve25519/eddsa2
  708. * https://asecuritysite.com/secp256k1/ecdsa
  709. * https://safecurves.cr.yp.to/
  710. * https://www.ietf.org/rfc/rfc3279.txt
  711. * https://crypto.stackexchange.com/questions/70927/naming-convention-for-nist-elliptic-curves-in-openssl
  712. * https://www.johndcook.com/blog/2018/08/21/a-tale-of-two-elliptic-curves/
  713. """
  714. @abc.abstractmethod
  715. def __len__(self) -> int:
  716. """
  717. Get number of key pairs currently stored within the security module.
  718. :return: Current number of keys stored in security module.
  719. """
  720. @abc.abstractmethod
  721. def __contains__(self, key_no: int) -> bool:
  722. """
  723. :param key_no:
  724. :return:
  725. """
  726. # FIXME: the following works on CPy 3.9+, but fails on CPy 3.7 and PyPy 3.8
  727. # AttributeError: type object 'Iterator' has no attribute '__class_getitem__'
  728. # See also:
  729. # - https://docs.python.org/3/library/abc.html#abc.ABCMeta.__subclasshook__
  730. # - https://docs.python.org/3/library/stdtypes.html#container.__iter__
  731. #
  732. # @abc.abstractmethod
  733. # def __iter__(self) -> Iterator[Union[ICryptosignKey, IEthereumKey]]:
  734. # """
  735. # Return an iterator object over all keys accessible in this security module.
  736. #
  737. # :return:
  738. # """
  739. @abc.abstractmethod
  740. def __getitem__(self, key_no: int) -> Union[ICryptosignKey, IEthereumKey]:
  741. """
  742. Get a key from the security module given the key number.
  743. :param key_no: Number of key to get.
  744. :return: The key, either a :class:`ICryptosignKey` or :class:`IEthereumKey` instance.
  745. """
  746. @abc.abstractmethod
  747. def __setitem__(self, key_no: int, key: Union[ICryptosignKey, IEthereumKey]) -> None:
  748. """
  749. :param key_no:
  750. :param key:
  751. :return:
  752. """
  753. @abc.abstractmethod
  754. def __delitem__(self, key_no: int) -> None:
  755. """
  756. :param key_no:
  757. :return:
  758. """
  759. @abc.abstractmethod
  760. def open(self):
  761. """
  762. Open this security module. This method (always) runs asynchronously.
  763. """
  764. @abc.abstractmethod
  765. def close(self):
  766. """
  767. Close this security module. This method (always) runs asynchronously.
  768. """
  769. @property
  770. @abc.abstractmethod
  771. def is_open(self) -> bool:
  772. """
  773. Check if the security module is currently opened. Security module operations
  774. can only be run when the module is opened.
  775. :return: Flag indicating whether the security module is currently opened.
  776. """
  777. @property
  778. @abc.abstractmethod
  779. def can_lock(self) -> bool:
  780. """
  781. Flag indicating whether this security module can be locked, e.g. by a
  782. user passphrase or PIN.
  783. :return: Flag indicating whether the security module can be locked/unlocked at all.
  784. """
  785. @property
  786. @abc.abstractmethod
  787. def is_locked(self) -> bool:
  788. """
  789. Check if this security module is currently locked.
  790. :return: Flag indicating whether the security module is currently locked.
  791. """
  792. @abc.abstractmethod
  793. def lock(self):
  794. """
  795. Lock this security module. This method (always) runs asynchronously.
  796. """
  797. @abc.abstractmethod
  798. def unlock(self):
  799. """
  800. Unlock this security module. This method (always) runs asynchronously.
  801. """
  802. @abc.abstractmethod
  803. def create_key(self, key_type: str) -> int:
  804. """
  805. Create a new public-private asymmetric key pair, stored within the security module.
  806. :param key_type: Type of key to generate, e.g. ``"cryptosign"`` or ``"ethereum"``.
  807. :return: ID of new key.
  808. """
  809. @abc.abstractmethod
  810. def delete_key(self, key_no: int):
  811. """
  812. Delete an existing key pair stored within the security module.
  813. :param key_no: ID of key to delete.
  814. """
  815. @abc.abstractmethod
  816. def get_random(self, octets: int) -> bytes:
  817. """
  818. Generate random bytes within the security module.
  819. :param octets: Number of bytes (octets) to generate.
  820. :return: Random bytes, generated within the security module, e.g. in a HW RNG.
  821. """
  822. @abc.abstractmethod
  823. def get_counter(self, counter_no: int) -> int:
  824. """
  825. Return current value of the given persistent counter.
  826. :param counter_no: Counter to access.
  827. :return: Current value of counter, or ``0`` to indicate the counter does not
  828. exist (was never incremented).
  829. """
  830. @abc.abstractmethod
  831. def increment_counter(self, counter_no: int) -> int:
  832. """
  833. Increment the given persistent counter and return the new value.
  834. :param counter_no: Counter to increment and access.
  835. :return: New value of counter, e.g. ``1`` once a counter was first incremented.
  836. """
  837. @public
  838. class IPayloadCodec(abc.ABC):
  839. """
  840. WAMP payload codecs are used with WAMP payload transparency mode.
  841. In payload transparency mode, application payloads are transmitted "raw",
  842. as binary strings, without any processing at the WAMP router.
  843. Payload transparency can be used eg for these use cases:
  844. * end-to-end encryption of application payloads (WAMP-cryptobox)
  845. * using serializers with custom user types, where the serializer and
  846. the serializer implementation has native support for serializing
  847. custom types (such as CBOR)
  848. * transmitting MQTT payloads within WAMP, when the WAMP router is
  849. providing a MQTT-WAMP bridge
  850. """
  851. @public
  852. @abc.abstractmethod
  853. def encode(self, is_originating, uri, args=None, kwargs=None):
  854. """
  855. Encodes application payload.
  856. :param is_originating: Flag indicating whether the encoding
  857. is to be done from an originator (a caller or publisher).
  858. :type is_originating: bool
  859. :param uri: The WAMP URI associated with the WAMP message for which
  860. the payload is to be encoded (eg topic or procedure).
  861. :type uri: str
  862. :param args: Positional application payload.
  863. :type args: list or None
  864. :param kwargs: Keyword-based application payload.
  865. :type kwargs: dict or None
  866. :returns: The encoded application payload or None to
  867. signal no encoding should be used.
  868. :rtype: instance of :class:`autobahn.wamp.types.EncodedPayload`
  869. """
  870. @public
  871. @abc.abstractmethod
  872. def decode(self, is_originating, uri, encoded_payload):
  873. """
  874. Decode application payload.
  875. :param is_originating: Flag indicating whether the encoding
  876. is to be done from an originator (a caller or publisher).
  877. :type is_originating: bool
  878. :param uri: The WAMP URI associated with the WAMP message for which
  879. the payload is to be encoded (eg topic or procedure).
  880. :type uri: str
  881. :param encoded_payload: The encoded application payload to be decoded.
  882. :type encoded_payload: instance of :class:`autobahn.wamp.types.EncodedPayload`
  883. :returns: A tuple with the decoded positional and keyword-based
  884. application payload: ``(uri, args, kwargs)``
  885. :rtype: tuple
  886. """