Authentication¶
The broker accepts calls only from authenticated clients and workers. This module opens a channel to the broker and proves who you are. Every other helper in this package works on the channel you get here.
How authentication works¶
Each client and worker has an API key and an API secret. The key names the account. The secret proves possession of the account, like a password. The broker issues these pairs; this module can also generate random ones for new accounts.
Authentication uses a challenge. The client sends its key. The broker replies with a random challenge value. The client answers with a response computed from the key, the secret, and the challenge. The secret itself never crosses the network. If the response is correct, the broker returns an auth token. The channel attaches that token to every later call.
Open an authenticated channel¶
get_authenticated_channel() connects and
authenticates in one call:
from momotor.rpc.auth.client import get_authenticated_channel
channel, auth_stub = await get_authenticated_channel(
'broker.example.com', None,
api_key='my-key', api_secret='my-secret',
)
It returns the authenticated channel and the auth stub. Build the stub you need from the channel:
from momotor.rpc.proto.client_grpc import ClientStub
client = ClientStub(channel)
Pass None as the port to use the default port: 50051, or 50052 when you
pass an ssl_context for TLS. If you already hold a token from an
earlier session, pass it as auth_token to reuse that session instead of
authenticating again.
Failed authentication raises a subclass of
RPCException. See Exception.
When you already have a plain grpclib.client.Channel, call
authenticate() on it instead. It performs
the challenge exchange and returns an
AuthenticatingChannel. That wrapper
adds the token to each request and passes every other call through to the
real channel.
Detect a dead connection¶
A channel can look open after the network or the broker has died. The
keepalive_time, keepalive_timeout, and
keepalive_permit_without_calls parameters of
get_authenticated_channel() control
transport pings that detect this. The defaults suit most programs.
Client connection recovery explains when to change them.
Added in version 6.0.1: The keepalive_timeout, keepalive_permit_without_calls, and
config parameters.
Generate keys and secrets¶
Server-side account code uses
gen_api_key() and
gen_api_secret() to create random
credentials. Client code does not need them.
Keys, secrets, salts, and authentication challenges use cryptographically
secure randomness from Python’s secrets module. API keys contain
24 characters, secrets contain 64 characters, and salts contain 8
characters, using the character sets defined in this module. Challenges
contain 512 bytes.
API reference¶
Client¶
- class momotor.rpc.auth.client.AuthenticatingChannel(channel, auth_token=None)¶
Wrapper for
grpclib.client.Channelthat adds an auth-token metadata to any request.Proxies all methods of
grpclib.client.Channel, and adds a few additional methods- request(name, cardinality, request_type, reply_type, *, timeout=None, deadline=None, metadata=None)¶
Wrapper for
request()ongrpclib.client.Channel.
- async momotor.rpc.auth.client.authenticate(channel, api_key, api_secret, *, stub=None)¶
Authenticate with the server. Returns an
AuthenticatingChannel.Any exception returned by the server is raised as a subclass of RPCException
- async momotor.rpc.auth.client.get_authenticated_channel(host, port, api_key, api_secret, auth_token=None, *, ssl_context=None, log_h2=False, keepalive_time=900, keepalive_timeout=None, keepalive_permit_without_calls=None, config=None, **channel_opts)¶
Connect to a broker and authenticate, possibly using an already existing token.
Returns a tuple with
the authenticated channel
the auth stub
If authentication fails, raises (a subclass of)
RPCExceptionProduces logging information on the
momotor.rpc.authlogger- Parameters:
host (
str) – Broker’s hostnameport (
int|None) – Broker’s port. If None, uses default ports 50051 or 50052, depending on ssl_context valueapi_key (
str) – API key to authenticate withapi_secret (
str) – API secret to authenticate withauth_token (
str|None) – (optional) existing authentication token to reuse sessionssl_context – SSL context to use
log_h2 – if True, enables logging of the h2 library
keepalive_time (
float|None) – Ping interval in seconds, 900 by default, None to disable. Overrides the interval in config.keepalive_timeout (
float|None) – Positive finite acknowledgement timeout in seconds. Defaults to config’s value, or 20 seconds.keepalive_permit_without_calls – Whether to ping without active RPCs. Defaults to config’s value, or False. Outstanding idle task requests count as active RPCs.
config (
Configuration|None) – Base grpclib configuration. Window sizes, TLS hostname overrides, and unspecified policy options are preserved. Unlimited pings and a minimum spacing no greater than the interval are selected for long-running RPCs.channel_opts – additional keyword arguments supplied to grpclib.channel.Channel
- Return type:
- Returns:
tuple containing: the authenticated channel and the auth stub
Added in version 6.0.1: The keepalive_timeout, keepalive_permit_without_calls and config parameters.
Utils¶
- momotor.rpc.auth.utils.calculate_challenge_response(api_key, api_secret, salt, challenge)¶
Calculate the response to a challenge request
- momotor.rpc.auth.utils.constant_time_compare(val1, val2)¶
Compare byte strings using
hmac.compare_digest().
- momotor.rpc.auth.utils.gen_api_key()¶
Generate a random API key
- Return type:
- Returns:
the generated key
- momotor.rpc.auth.utils.gen_api_secret()¶
Generate a random secret
- Return type:
- Returns:
the generated secret
- momotor.rpc.auth.utils.gen_challenge()¶
Generate a random challenge
- Return type:
- Returns:
the generated challenge
- momotor.rpc.auth.utils.gen_key(charset, length)¶
Generate a key of length using characters in charset
- momotor.rpc.auth.utils.gen_salt()¶
Generate a random salt
- Return type:
- Returns:
the generated salt
- momotor.rpc.auth.utils.API_KEY_CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'¶
Valid characters for an API key
- momotor.rpc.auth.utils.API_KEY_LENGTH = 24¶
Default length of an API key
- momotor.rpc.auth.utils.API_SECRET_CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$^&-_+./?'¶
Valid characters for an API secret
- momotor.rpc.auth.utils.API_SECRET_LENGTH = 64¶
Default length of an API secret
- momotor.rpc.auth.utils.CHALLENGE_LENGTH = 512¶
Length of the challenge
- momotor.rpc.auth.utils.SALT_CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$^&-_+./?'¶
Valid characters for the salt used
- momotor.rpc.auth.utils.SALT_LENGTH = 8¶
Length of the salt