@withgateway/sdk 0.3.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/cli.js +2221 -962
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +2212 -953
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +81 -19
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +79 -17
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +124 -11
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +124 -11
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
- package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +903 -221
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +868 -212
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +78 -16
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +76 -14
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +7 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +7 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +692 -410
- package/dist/worlds/index.d.ts +692 -410
- package/dist/worlds/index.js +740 -197
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +736 -193
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
- package/runtime/gatewaysdk/environment/_materialize.py +5 -25
- package/runtime/gatewaysdk/environment/_world.py +58 -65
- package/runtime/gatewaysdk/environment/backing.py +20 -24
- package/runtime/gatewaysdk/environment/core.py +1 -16
- package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
- package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
- package/runtime/gatewaysdk/environment/schema/api.py +174 -471
- package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
- package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
- package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
- package/runtime/gatewaysdk/environment/schema/call_capture.py +309 -0
- package/runtime/gatewaysdk/environment/schema/call_log.py +230 -18
- package/runtime/gatewaysdk/environment/schema/call_redaction.py +201 -19
- package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
- package/runtime/gatewaysdk/environment/schema/conform.py +6 -27
- package/runtime/gatewaysdk/environment/schema/connector.py +89 -152
- package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
- package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +1 -0
- package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
- package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
- package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
- package/runtime/gatewaysdk/environment/schema/data.py +14 -13
- package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
- package/runtime/gatewaysdk/environment/schema/database/guard.py +43 -36
- package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
- package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
- package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
- package/runtime/gatewaysdk/environment/schema/door.py +899 -0
- package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
- package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
- package/runtime/gatewaysdk/environment/schema/handler_errors.py +25 -4
- package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
- package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
- package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
- package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
- package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
- package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
- package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
- package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
- package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
- package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
- package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
- package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
- package/runtime/gatewaysdk/environment/schema/journal.py +437 -0
- package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
- package/runtime/gatewaysdk/environment/schema/local.py +31 -116
- package/runtime/gatewaysdk/environment/schema/platform.py +15 -17
- package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
- package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
- package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
- package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +129 -176
- package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
- package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
- package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +31 -6
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +13 -13
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +23 -23
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +11 -6
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +35 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
- package/runtime/gatewaysdk/environment/schema/snapshot.py +149 -29
- package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
- package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
- package/runtime/gatewaysdk/environment/schema/tools_world.py +84 -203
- package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
- package/runtime/gatewaysdk/environment/schema/verbs.py +32 -36
- package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
- package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
- package/runtime/gatewaysdk/environment/schema/world_host.py +953 -0
- package/runtime/gatewaysdk/environment/schema/world_tests.py +9 -11
- package/runtime/gatewaysdk/environment/world.py +1 -1
- package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
- package/skills/agents/connector-template-author.md +5 -1
- package/skills/benchmarks-getting-started/SKILL.md +8 -9
- package/skills/connector-schema-authoring/SKILL.md +31 -6
- package/skills/connector-schema-authoring/connector-worlds.md +129 -7
- package/skills/world-data-ingestion/ROWS.md +12 -8
- package/skills/world-data-ingestion/SKILL.md +13 -13
- package/skills/worlds-getting-started/SKILL.md +23 -23
- package/skills/worlds-getting-started/references/cli-mcp-map.md +11 -6
- package/skills/worlds-getting-started/references/gotchas.md +35 -2
- package/skills/worlds-getting-started/references/journal-checks.md +182 -0
|
@@ -0,0 +1,899 @@
|
|
|
1
|
+
"""The door of a world's HTTP surface: what a request must carry to reach a
|
|
2
|
+
session's world, the way the vendor asks for it.
|
|
3
|
+
|
|
4
|
+
``connector.toml``'s ``[auth]`` is read once into a :class:`VendorAuth`: the
|
|
5
|
+
carrier (:class:`~.credentials.AuthScheme`), the vendor's own login exchange when
|
|
6
|
+
it has one (``scheme = "oauth2"``'s RFC 6749 token route, or a declared
|
|
7
|
+
``[auth.login]``) and the routes a presigned link reaches (``[auth.downloads]``)::
|
|
8
|
+
|
|
9
|
+
[auth]
|
|
10
|
+
scheme = "bearer" # how calls carry the token the login mints
|
|
11
|
+
secret_env = "VENDOR_API_KEY"
|
|
12
|
+
|
|
13
|
+
[auth.login]
|
|
14
|
+
method = "POST" # the default
|
|
15
|
+
path = "/login" # under base_url's path, as routes are
|
|
16
|
+
credential = { json = "api_key" } # or { form = "password" } or { header = "X-Api-Key" }
|
|
17
|
+
required = ["username"] # what else the vendor demands, read from the same place
|
|
18
|
+
reply = '{"data": {"token": "{token}"}}' # default {"access_token", "token_type"}
|
|
19
|
+
ttl_seconds = 3600 # opt in to expiry; absent, a token lives as long as the session
|
|
20
|
+
|
|
21
|
+
[auth.downloads]
|
|
22
|
+
routes = ["download_results"] # GET routes a signed link reaches without the key
|
|
23
|
+
ttl_seconds = 900 # opt in to expiry; absent, a link lives as long as the session
|
|
24
|
+
|
|
25
|
+
A :class:`Door` holds one session's credential (the World Host's session token,
|
|
26
|
+
``worlds serve``'s pin) and admits a request two ways.
|
|
27
|
+
:meth:`Door.session_entry` is the World Host's gate: the request proves it
|
|
28
|
+
holds the credential the way the vendor takes it, in the platform's own header
|
|
29
|
+
(:data:`PLATFORM_HEADER`), or as the platform's ``Authorization: Bearer``, which
|
|
30
|
+
every world takes for good. :meth:`Door.vendor_entry` is the world's own check,
|
|
31
|
+
the vendor's rules alone, so a ``none`` world asks for nothing. Each refuses
|
|
32
|
+
everything else.
|
|
33
|
+
|
|
34
|
+
``[auth] mode = "open"`` (or a session opened with ``auth: "open"``) is a session
|
|
35
|
+
that asks for nothing: :meth:`Door.opened` is its door, reached only on the
|
|
36
|
+
session's capability hostname (:func:`open_label`, a 130-bit secret derived
|
|
37
|
+
from the session's credential), never on the session's own hostname, which keeps
|
|
38
|
+
asking for the credential.
|
|
39
|
+
|
|
40
|
+
A login's token is an HS256 JWT and a download link an HMAC over its path (and
|
|
41
|
+
its expiry when it has one), each under a key derived from the session's
|
|
42
|
+
credential: a supervisor and its version worker check them alike with nothing
|
|
43
|
+
shared, any process holding the session (a reopen, a handoff, a restart) checks
|
|
44
|
+
them the same, and one minted for another session never verifies. Nothing
|
|
45
|
+
expires unless the world declares ``ttl_seconds``; then an expired one is
|
|
46
|
+
refused. Every comparison of a presented secret runs in constant time.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import base64
|
|
52
|
+
import hashlib
|
|
53
|
+
import hmac
|
|
54
|
+
import json
|
|
55
|
+
import re
|
|
56
|
+
import secrets
|
|
57
|
+
import time
|
|
58
|
+
import urllib.parse
|
|
59
|
+
from abc import ABC, abstractmethod
|
|
60
|
+
from dataclasses import dataclass, field, replace
|
|
61
|
+
from enum import StrEnum
|
|
62
|
+
from functools import partial
|
|
63
|
+
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Mapping
|
|
64
|
+
|
|
65
|
+
from .credentials import AuthScheme, BearerAuth, Carried, Headers, OAuth2Auth, Query, basic_pair
|
|
66
|
+
from .request_body import form_fields, json_value
|
|
67
|
+
from .validation import (
|
|
68
|
+
FIELD_NAME,
|
|
69
|
+
METHODS,
|
|
70
|
+
OPERATION_NAME,
|
|
71
|
+
PLACEHOLDER,
|
|
72
|
+
fail,
|
|
73
|
+
names_of,
|
|
74
|
+
path_pattern,
|
|
75
|
+
route_path,
|
|
76
|
+
string_of,
|
|
77
|
+
table_of,
|
|
78
|
+
ttl_seconds_of,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
if TYPE_CHECKING:
|
|
82
|
+
from .connector import Operation, Spec
|
|
83
|
+
|
|
84
|
+
WORLD_AUTH_SENTINEL = "gateway-session"
|
|
85
|
+
PLATFORM_HEADER = "x-world-session"
|
|
86
|
+
ACCESS = "access"
|
|
87
|
+
REFRESH = "refresh"
|
|
88
|
+
VENDOR_MODE = "vendor"
|
|
89
|
+
OPEN_MODE = "open"
|
|
90
|
+
AUTH_MODES = (VENDOR_MODE, OPEN_MODE)
|
|
91
|
+
OPEN_LABEL_CHARS = 26
|
|
92
|
+
OPEN_PREFIX = "o-"
|
|
93
|
+
EXPIRES = "expires"
|
|
94
|
+
SIGNATURE = "signature"
|
|
95
|
+
TOKEN = "{token}"
|
|
96
|
+
EXPIRES_IN = "{expires_in}"
|
|
97
|
+
DEFAULT_REPLY = {"access_token": TOKEN, "token_type": "Bearer", "expires_in": EXPIRES_IN}
|
|
98
|
+
NEVER = "never"
|
|
99
|
+
INVALID_CLIENT: tuple[int, Any] = (400, {"error": "invalid_client"})
|
|
100
|
+
SESSION_REFUSAL: tuple[int, Any, str] = (401, {"error": "invalid session token"}, "application/json")
|
|
101
|
+
LOGIN_KEYS = frozenset({"method", "path", "credential", "required", "reply", "ttl_seconds", "status"})
|
|
102
|
+
DOWNLOAD_KEYS = frozenset({"routes", "ttl_seconds"})
|
|
103
|
+
FIELD_PATH = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*(\.[A-Za-z_][A-Za-z0-9_-]*)*$")
|
|
104
|
+
HEADER_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
|
|
105
|
+
EXPIRY = re.compile(r"^[0-9]{1,20}$")
|
|
106
|
+
_PLATFORM = BearerAuth()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def same(presented: str | None, expected: str) -> bool:
|
|
110
|
+
"""Constant-time equality of a presented secret and the expected one, whatever their characters."""
|
|
111
|
+
if presented is None:
|
|
112
|
+
return False
|
|
113
|
+
return hmac.compare_digest(_bytes(presented), _bytes(expected))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _bytes(text: str) -> bytes:
|
|
117
|
+
return text.encode("utf-8", "surrogatepass")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _b64(raw: bytes) -> str:
|
|
121
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _unb64(text: str) -> bytes:
|
|
125
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _derived(credential: str | None, purpose: str) -> bytes:
|
|
129
|
+
"""A key for one purpose derived from the session's credential, so the door needs
|
|
130
|
+
no secret of its own and every process holding the session derives the same one."""
|
|
131
|
+
seed = _bytes(credential or WORLD_AUTH_SENTINEL)
|
|
132
|
+
return hmac.new(seed, f"gateway-world-door/{purpose}".encode(), hashlib.sha256).digest()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def open_label(credential: str) -> str:
|
|
136
|
+
"""The secret half of an open session's capability hostname: 26 base32 characters
|
|
137
|
+
(130 bits) of an HMAC under the session's credential, so the platform and every
|
|
138
|
+
host holding the session name it alike, it survives a reopen, a handoff and a
|
|
139
|
+
restart with the credential, and it reveals nothing of the credential."""
|
|
140
|
+
digest = _derived(credential, "open-host")
|
|
141
|
+
return base64.b32encode(digest).decode("ascii").lower()[:OPEN_LABEL_CHARS]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _only(table: dict, allowed: frozenset[str], location: str) -> None:
|
|
145
|
+
unknown = sorted(set(table) - allowed)
|
|
146
|
+
if unknown:
|
|
147
|
+
fail(
|
|
148
|
+
"spec", f"{unknown[0]} is not a setting here; use {', '.join(sorted(allowed))}", f"{location}/{unknown[0]}"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _expiry(clock: Callable[[], float], ttl_s: int | None) -> dict[str, int]:
|
|
153
|
+
return {} if ttl_s is None else {"exp": int(clock()) + ttl_s}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _dotted(body: dict, path: str) -> Any:
|
|
157
|
+
value: Any = body
|
|
158
|
+
for part in path.split("."):
|
|
159
|
+
value = value.get(part) if isinstance(value, dict) else None
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _leaves(value: Any) -> list[Any]:
|
|
164
|
+
if isinstance(value, dict):
|
|
165
|
+
return [leaf for item in value.values() for leaf in _leaves(item)]
|
|
166
|
+
if isinstance(value, list):
|
|
167
|
+
return [leaf for item in value for leaf in _leaves(item)]
|
|
168
|
+
return [value]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _unclaimed(method: str, path: str, operations: Mapping[str, Operation], location: str, route: str) -> str:
|
|
172
|
+
"""``path`` for a route the door answers ahead of every operation: under base_url's
|
|
173
|
+
path and never ``/__``, each ``{name}`` once, and no declared ``method`` operation's,
|
|
174
|
+
which ``route`` would otherwise hide."""
|
|
175
|
+
if not path.startswith("/") or path.startswith("/__"):
|
|
176
|
+
fail("spec", "path is a path under base_url's, starting with / and never /__", location)
|
|
177
|
+
route_path(path, location)
|
|
178
|
+
taken = [op.name for op in operations.values() if method in op.methods and _overlaps(path, op.path)]
|
|
179
|
+
if taken:
|
|
180
|
+
fail("spec", f"{method} {path} is operation {taken[0]}'s route; the {route} would hide it", location)
|
|
181
|
+
return path
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _overlaps(path: str, other: str) -> bool:
|
|
185
|
+
"""Some request path reaches both declared paths: as many segments, each pair meeting."""
|
|
186
|
+
ours, theirs = path.split("/"), other.split("/")
|
|
187
|
+
return len(ours) == len(theirs) and all(_meet(segment, then) for segment, then in zip(ours, theirs))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _meet(segment: str, other: str) -> bool:
|
|
191
|
+
"""One segment of each could be the same text: the same, one fills the other's
|
|
192
|
+
``{placeholder}``, or both name one (refused as if they always could)."""
|
|
193
|
+
both = bool(PLACEHOLDER.search(segment) and PLACEHOLDER.search(other))
|
|
194
|
+
return both or bool(path_pattern(segment).match(other) or path_pattern(other).match(segment))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _filled(template: Any, token: str, ttl_s: int | None) -> Any:
|
|
198
|
+
if template == TOKEN:
|
|
199
|
+
return token
|
|
200
|
+
if template == EXPIRES_IN:
|
|
201
|
+
return ttl_s
|
|
202
|
+
if isinstance(template, dict):
|
|
203
|
+
kept = {key: value for key, value in template.items() if ttl_s is not None or value != EXPIRES_IN}
|
|
204
|
+
return {key: _filled(value, token, ttl_s) for key, value in kept.items()}
|
|
205
|
+
if isinstance(template, list):
|
|
206
|
+
return [_filled(value, token, ttl_s) for value in template if ttl_s is not None or value != EXPIRES_IN]
|
|
207
|
+
return template
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _lifetime(ttl_s: int | None) -> dict[str, int]:
|
|
211
|
+
return {} if ttl_s is None else {"expires_in": ttl_s}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class TokenMint:
|
|
215
|
+
"""Tokens a world mints for one session: HS256 JWTs carrying ``iss``, ``iat``,
|
|
216
|
+
``jti``, ``use`` and, when the world declares a lifetime, ``exp``, signed with
|
|
217
|
+
``key``. :meth:`verify` returns the claims of a token this mint signed for that
|
|
218
|
+
use, unexpired when it carries an expiry, else None, whatever a client sends."""
|
|
219
|
+
|
|
220
|
+
HEADER = _b64(b'{"alg":"HS256","typ":"JWT"}')
|
|
221
|
+
|
|
222
|
+
def __init__(self, key: bytes, issuer: str, clock: Callable[[], float]):
|
|
223
|
+
self.key = key
|
|
224
|
+
self.issuer = issuer
|
|
225
|
+
self.clock = clock
|
|
226
|
+
|
|
227
|
+
def mint(self, ttl_s: int | None, use: str = ACCESS, **claims: str) -> str:
|
|
228
|
+
now = int(self.clock())
|
|
229
|
+
body = {
|
|
230
|
+
"iss": self.issuer,
|
|
231
|
+
"iat": now,
|
|
232
|
+
**_expiry(self.clock, ttl_s),
|
|
233
|
+
"jti": secrets.token_urlsafe(9),
|
|
234
|
+
"use": use,
|
|
235
|
+
}
|
|
236
|
+
payload = _b64(json.dumps({**body, **claims}, separators=(",", ":")).encode("utf-8"))
|
|
237
|
+
return f"{self.HEADER}.{payload}.{self._sign(payload)}"
|
|
238
|
+
|
|
239
|
+
def verify(self, token: str, use: str = ACCESS) -> dict | None:
|
|
240
|
+
parts = token.split(".")
|
|
241
|
+
if len(parts) != 3 or parts[0] != self.HEADER or not same(parts[2], self._sign(parts[1])):
|
|
242
|
+
return None
|
|
243
|
+
claims = self._claims(parts[1])
|
|
244
|
+
if claims is None or claims.get("use") != use:
|
|
245
|
+
return None
|
|
246
|
+
return claims if self._live(claims) else None
|
|
247
|
+
|
|
248
|
+
def _live(self, claims: dict) -> bool:
|
|
249
|
+
if "exp" not in claims:
|
|
250
|
+
return True
|
|
251
|
+
expiry = claims["exp"]
|
|
252
|
+
return isinstance(expiry, int) and not isinstance(expiry, bool) and expiry > self.clock()
|
|
253
|
+
|
|
254
|
+
def _sign(self, payload: str) -> str:
|
|
255
|
+
return _b64(
|
|
256
|
+
hmac.new(self.key, f"{self.HEADER}.{payload}".encode("utf-8", "surrogatepass"), hashlib.sha256).digest()
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
@staticmethod
|
|
260
|
+
def _claims(payload: str) -> dict | None:
|
|
261
|
+
try:
|
|
262
|
+
claims = json.loads(_unb64(payload))
|
|
263
|
+
except (ValueError, UnicodeDecodeError, RecursionError):
|
|
264
|
+
return None
|
|
265
|
+
return claims if isinstance(claims, dict) else None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@dataclass(frozen=True)
|
|
269
|
+
class ExchangeRequest:
|
|
270
|
+
"""What an exchange route reads of its request: the raw body and the lower-cased headers."""
|
|
271
|
+
|
|
272
|
+
raw: bytes
|
|
273
|
+
headers: Headers
|
|
274
|
+
|
|
275
|
+
def json_object(self) -> dict | None:
|
|
276
|
+
value = json_value(self.raw) if self.raw else None
|
|
277
|
+
return value if isinstance(value, dict) else None
|
|
278
|
+
|
|
279
|
+
def form(self) -> dict[str, str]:
|
|
280
|
+
return form_fields(self.raw)
|
|
281
|
+
|
|
282
|
+
def oauth_form(self) -> dict[str, str]:
|
|
283
|
+
"""An RFC 6749 token request's parameters: a JSON body when it is labelled one,
|
|
284
|
+
else a form, the client id and secret of a Basic authorization filling in what
|
|
285
|
+
the form leaves out."""
|
|
286
|
+
content_type = (self.headers.get("content-type") or "").split(";")[0].strip().lower()
|
|
287
|
+
if content_type == "application/json":
|
|
288
|
+
return {key: str(value) for key, value in (self.json_object() or {}).items()}
|
|
289
|
+
return {**self._basic_client(), **{name: value for name, value in self.form().items() if value}}
|
|
290
|
+
|
|
291
|
+
def _basic_client(self) -> dict[str, str]:
|
|
292
|
+
pair = basic_pair(self.headers.get("authorization", ""))
|
|
293
|
+
return {} if pair is None else {"client_id": pair[0], "client_secret": pair[1]}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
class LoginMedium(ABC):
|
|
297
|
+
"""Where a declared login reads its credential and the fields it demands."""
|
|
298
|
+
|
|
299
|
+
key: ClassVar[str]
|
|
300
|
+
pattern: ClassVar[re.Pattern] = FIELD_PATH
|
|
301
|
+
|
|
302
|
+
@staticmethod
|
|
303
|
+
def parse(value: Any, location: str) -> tuple[LoginMedium, str]:
|
|
304
|
+
"""The medium ``credential = { json | form | header = "<name>" }`` names, and the
|
|
305
|
+
name: the one place a medium's kind is decided."""
|
|
306
|
+
table = table_of(value, location)
|
|
307
|
+
kind = MEDIA.get(next(iter(table))) if len(table) == 1 else None
|
|
308
|
+
if kind is None:
|
|
309
|
+
fail("spec", f"credential names one place: {{ {' | '.join(MEDIA)} = \"<field>\" }}", location)
|
|
310
|
+
name = table[kind.key]
|
|
311
|
+
if not isinstance(name, str) or not kind.pattern.match(name):
|
|
312
|
+
fail("spec", f"credential.{kind.key} names a {kind.key} field", f"{location}/{kind.key}")
|
|
313
|
+
return kind(), name
|
|
314
|
+
|
|
315
|
+
@abstractmethod
|
|
316
|
+
def reader(self, request: ExchangeRequest) -> Callable[[str], Any] | None:
|
|
317
|
+
"""A lookup of the medium's fields by name, or None when the request does not
|
|
318
|
+
carry the medium (a body that is not a JSON object)."""
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class JsonBody(LoginMedium):
|
|
322
|
+
key = "json"
|
|
323
|
+
|
|
324
|
+
def reader(self, request: ExchangeRequest) -> Callable[[str], Any] | None:
|
|
325
|
+
body = request.json_object()
|
|
326
|
+
return None if body is None else partial(_dotted, body)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
class FormBody(LoginMedium):
|
|
330
|
+
key = "form"
|
|
331
|
+
pattern = FIELD_NAME
|
|
332
|
+
|
|
333
|
+
def reader(self, request: ExchangeRequest) -> Callable[[str], Any] | None:
|
|
334
|
+
return request.form().get
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
class HeaderFields(LoginMedium):
|
|
338
|
+
key = "header"
|
|
339
|
+
pattern = HEADER_NAME
|
|
340
|
+
|
|
341
|
+
def reader(self, request: ExchangeRequest) -> Callable[[str], Any] | None:
|
|
342
|
+
return lambda name: request.headers.get(name.lower())
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
MEDIA: dict[str, type[LoginMedium]] = {kind.key: kind for kind in (JsonBody, FormBody, HeaderFields)}
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class Exchange(ABC):
|
|
349
|
+
"""A vendor route that trades the session's credential for a token the world's
|
|
350
|
+
later calls carry (:attr:`method` and :attr:`path` under base_url's path)."""
|
|
351
|
+
|
|
352
|
+
method: str
|
|
353
|
+
path: str
|
|
354
|
+
ttl_s: int | None
|
|
355
|
+
|
|
356
|
+
def matches(self, method: str, route_path: str) -> bool:
|
|
357
|
+
"""``route_path`` is this route's path, each ``{name}`` in it one segment (Workday's
|
|
358
|
+
``/ccx/oauth2/{tenant}/token``)."""
|
|
359
|
+
return method == self.method and path_pattern(self.path).match(route_path) is not None
|
|
360
|
+
|
|
361
|
+
def at(self, token_path: str | None) -> Exchange:
|
|
362
|
+
"""This exchange answering on the path ``[api] token_path`` settles."""
|
|
363
|
+
return self
|
|
364
|
+
|
|
365
|
+
def token_path(self, declared: str | None, operations: Mapping[str, Operation], location: str) -> str | None:
|
|
366
|
+
"""The path ``[api] token_path`` resolves to; only oauth2 takes one."""
|
|
367
|
+
if declared is not None:
|
|
368
|
+
fail("spec", "api.token_path belongs to auth.scheme oauth2", f"{location}/token_path")
|
|
369
|
+
return None
|
|
370
|
+
|
|
371
|
+
@abstractmethod
|
|
372
|
+
def answer(self, request: ExchangeRequest, door: Door) -> tuple[int, Any]:
|
|
373
|
+
"""The vendor's answer to one exchange request."""
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@dataclass(frozen=True)
|
|
377
|
+
class OAuth2Exchange(Exchange):
|
|
378
|
+
"""``scheme = "oauth2"``: the RFC 6749 token route. ``client_credentials`` (the
|
|
379
|
+
default) mints an access token; ``password`` (``email`` or ``username`` plus
|
|
380
|
+
``password``) an ``id_token`` that is also the access token, with a
|
|
381
|
+
``refresh_token``; ``refresh_token`` answers a fresh pair for any refresh token
|
|
382
|
+
the session minted, wherever the session runs now. With a credential pinned,
|
|
383
|
+
the client secret or password must be it. Tokens live as long as the session
|
|
384
|
+
unless ``[auth] ttl_seconds`` declares a lifetime for the access token."""
|
|
385
|
+
|
|
386
|
+
scope: str | None
|
|
387
|
+
default_path: str
|
|
388
|
+
path: str = ""
|
|
389
|
+
method: str = "POST"
|
|
390
|
+
ttl_s: int | None = None
|
|
391
|
+
|
|
392
|
+
@classmethod
|
|
393
|
+
def of(cls, scheme: OAuth2Auth, operations: Mapping[str, Operation], location: str) -> OAuth2Exchange:
|
|
394
|
+
path = _unclaimed("POST", scheme.served_token_path, operations, f"{location}/token_url", "token route")
|
|
395
|
+
return cls(scheme.scope, path, path, ttl_s=scheme.ttl_s)
|
|
396
|
+
|
|
397
|
+
def at(self, token_path: str | None) -> Exchange:
|
|
398
|
+
return replace(self, path=token_path or self.default_path)
|
|
399
|
+
|
|
400
|
+
def token_path(self, declared: str | None, operations: Mapping[str, Operation], location: str) -> str | None:
|
|
401
|
+
if declared is None:
|
|
402
|
+
return self.default_path
|
|
403
|
+
return _unclaimed("POST", declared, operations, f"{location}/token_path", "token route")
|
|
404
|
+
|
|
405
|
+
def answer(self, request: ExchangeRequest, door: Door) -> tuple[int, Any]:
|
|
406
|
+
form = request.oauth_form()
|
|
407
|
+
grants = {"client_credentials": self._client, "password": self._password, "refresh_token": self._refresh}
|
|
408
|
+
grant = grants.get(form.get("grant_type", "client_credentials"))
|
|
409
|
+
return INVALID_CLIENT if grant is None else grant(form, door)
|
|
410
|
+
|
|
411
|
+
def _client(self, form: dict[str, str], door: Door) -> tuple[int, Any]:
|
|
412
|
+
if not door.pins(form.get("client_secret")):
|
|
413
|
+
return INVALID_CLIENT
|
|
414
|
+
scope = form.get("scope") or self.scope
|
|
415
|
+
answer = {"access_token": door.mint.mint(self.ttl_s), "token_type": "Bearer", **_lifetime(self.ttl_s)}
|
|
416
|
+
return 200, {**answer, **({"scope": scope} if scope else {})}
|
|
417
|
+
|
|
418
|
+
def _password(self, form: dict[str, str], door: Door) -> tuple[int, Any]:
|
|
419
|
+
subject = form.get("email") or form.get("username")
|
|
420
|
+
password = form.get("password")
|
|
421
|
+
if not subject or not password or not door.pins(password):
|
|
422
|
+
return INVALID_CLIENT
|
|
423
|
+
return 200, self._identity(subject, door)
|
|
424
|
+
|
|
425
|
+
def _refresh(self, form: dict[str, str], door: Door) -> tuple[int, Any]:
|
|
426
|
+
claims = door.mint.verify(form.get("refresh_token") or "", REFRESH)
|
|
427
|
+
if claims is None:
|
|
428
|
+
return INVALID_CLIENT
|
|
429
|
+
return 200, self._identity(str(claims.get("sub") or ""), door)
|
|
430
|
+
|
|
431
|
+
def _identity(self, subject: str, door: Door) -> dict:
|
|
432
|
+
id_token = door.mint.mint(self.ttl_s, sub=subject)
|
|
433
|
+
return {
|
|
434
|
+
"id_token": id_token,
|
|
435
|
+
"access_token": id_token,
|
|
436
|
+
"refresh_token": door.mint.mint(None, REFRESH, sub=subject),
|
|
437
|
+
"token_type": "Bearer",
|
|
438
|
+
**_lifetime(self.ttl_s),
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
@dataclass(frozen=True)
|
|
443
|
+
class DeclaredLogin(Exchange):
|
|
444
|
+
"""``[auth.login]``: the vendor's own login route (module docstring). The session's
|
|
445
|
+
credential sits at ``credential`` in its ``medium``; a wrong or missing one is the
|
|
446
|
+
vendor's 401, a missing ``required`` field or an unreadable body its 400, and the
|
|
447
|
+
right one is answered ``reply`` with the minted token at ``"{token}"``."""
|
|
448
|
+
|
|
449
|
+
method: str
|
|
450
|
+
path: str
|
|
451
|
+
medium: LoginMedium
|
|
452
|
+
credential: str
|
|
453
|
+
required: tuple[str, ...]
|
|
454
|
+
reply: Any
|
|
455
|
+
ttl_s: int | None
|
|
456
|
+
status: int
|
|
457
|
+
|
|
458
|
+
@classmethod
|
|
459
|
+
def parse(cls, value: Any, operations: Mapping[str, Operation], location: str) -> DeclaredLogin:
|
|
460
|
+
table = table_of(value, location)
|
|
461
|
+
_only(table, LOGIN_KEYS, location)
|
|
462
|
+
method = (string_of(table, "method", location, default="POST", required=False) or "").upper()
|
|
463
|
+
if method not in METHODS:
|
|
464
|
+
fail("spec", f"method must be one of {', '.join(METHODS)}", f"{location}/method")
|
|
465
|
+
path = cls._path(table, method, operations, location)
|
|
466
|
+
medium, credential = LoginMedium.parse(table.get("credential"), f"{location}/credential")
|
|
467
|
+
required = names_of(table, "required", location, medium.pattern)
|
|
468
|
+
status = table.get("status", 200)
|
|
469
|
+
if isinstance(status, bool) or not isinstance(status, int) or not 200 <= status <= 299:
|
|
470
|
+
fail("spec", "status is the vendor's success status, 200 to 299", f"{location}/status")
|
|
471
|
+
ttl_s = ttl_seconds_of(table, location)
|
|
472
|
+
return cls(method, path, medium, credential, required, cls._reply(table, location), ttl_s, status)
|
|
473
|
+
|
|
474
|
+
@staticmethod
|
|
475
|
+
def _path(table: dict, method: str, operations: Mapping[str, Operation], location: str) -> str:
|
|
476
|
+
path = string_of(table, "path", location) or ""
|
|
477
|
+
if any(mark in path for mark in "{}"):
|
|
478
|
+
fail("spec", "path is a fixed path under base_url's, starting with / and never /__", f"{location}/path")
|
|
479
|
+
return _unclaimed(method, path, operations, f"{location}/path", "login")
|
|
480
|
+
|
|
481
|
+
@staticmethod
|
|
482
|
+
def _reply(table: dict, location: str) -> Any:
|
|
483
|
+
text = table.get("reply")
|
|
484
|
+
if text is None:
|
|
485
|
+
return DEFAULT_REPLY
|
|
486
|
+
try:
|
|
487
|
+
reply = json.loads(text) if isinstance(text, str) else None
|
|
488
|
+
except ValueError:
|
|
489
|
+
reply = None
|
|
490
|
+
if _leaves(reply).count(TOKEN) != 1:
|
|
491
|
+
fail(
|
|
492
|
+
"spec",
|
|
493
|
+
'reply is the vendor\'s JSON answer with "{token}" once, where the token goes',
|
|
494
|
+
f"{location}/reply",
|
|
495
|
+
)
|
|
496
|
+
return reply
|
|
497
|
+
|
|
498
|
+
def answer(self, request: ExchangeRequest, door: Door) -> tuple[int, Any]:
|
|
499
|
+
read = self.medium.reader(request)
|
|
500
|
+
if read is None:
|
|
501
|
+
return door.invalid
|
|
502
|
+
if not door.logs_in(read(self.credential)):
|
|
503
|
+
return door.refusal
|
|
504
|
+
if any(read(name) in (None, "") for name in self.required):
|
|
505
|
+
return door.invalid
|
|
506
|
+
return self.status, _filled(self.reply, door.mint.mint(self.ttl_s), self.ttl_s)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
@dataclass(frozen=True)
|
|
510
|
+
class SignedDownloads:
|
|
511
|
+
"""``[auth.downloads]``: GET routes a presigned link reaches without the key, the way
|
|
512
|
+
a vendor hands out a link to a file. A link is the route's path plus ``signature``
|
|
513
|
+
(an HMAC-SHA256 over that path and its expiry under the session's download key)
|
|
514
|
+
and, when it expires, ``expires`` (unix seconds), and nothing else: the route
|
|
515
|
+
names its object in the path, so a link reaches the one object it was signed
|
|
516
|
+
for. Without ``ttl_seconds`` a link lives as long as the session. The route still
|
|
517
|
+
answers the credential too."""
|
|
518
|
+
|
|
519
|
+
routes: tuple[str, ...]
|
|
520
|
+
patterns: tuple[re.Pattern, ...]
|
|
521
|
+
ttl_s: int | None
|
|
522
|
+
|
|
523
|
+
@classmethod
|
|
524
|
+
def parse(cls, value: Any, operations: Mapping[str, Operation], location: str) -> SignedDownloads:
|
|
525
|
+
table = table_of(value, location)
|
|
526
|
+
_only(table, DOWNLOAD_KEYS, location)
|
|
527
|
+
routes = names_of(table, "routes", location, OPERATION_NAME)
|
|
528
|
+
if not routes:
|
|
529
|
+
fail("spec", "routes names the GET operations a signed link reaches", f"{location}/routes")
|
|
530
|
+
for index, name in enumerate(routes):
|
|
531
|
+
cls._check(name, operations, f"{location}/routes/{index}")
|
|
532
|
+
ttl_s = ttl_seconds_of(table, location)
|
|
533
|
+
return cls(routes, tuple(operations[name].pattern for name in routes), ttl_s)
|
|
534
|
+
|
|
535
|
+
@staticmethod
|
|
536
|
+
def _check(name: str, operations: Mapping[str, Operation], location: str) -> None:
|
|
537
|
+
operation = operations.get(name)
|
|
538
|
+
if operation is None:
|
|
539
|
+
fail("spec", f"{name} is not an operation connector.toml declares", location)
|
|
540
|
+
if tuple(operation.methods) != ("GET",):
|
|
541
|
+
fail("spec", f"{name} answers {', '.join(operation.methods)}; a signed link reaches a GET route", location)
|
|
542
|
+
if operation.params:
|
|
543
|
+
fail("spec", f"{name} declares params; a signed link names its object in the path alone", location)
|
|
544
|
+
|
|
545
|
+
def covers(self, route_path: str) -> bool:
|
|
546
|
+
return any(pattern.match(route_path) for pattern in self.patterns)
|
|
547
|
+
|
|
548
|
+
def sign(self, key: bytes, route_path: str, expires: int | None) -> dict[str, str]:
|
|
549
|
+
stamp = {} if expires is None else {EXPIRES: str(expires)}
|
|
550
|
+
return {**stamp, SIGNATURE: self._signature(key, route_path, NEVER if expires is None else str(expires))}
|
|
551
|
+
|
|
552
|
+
def verify(self, key: bytes, route_path: str, query: Query, now: float) -> bool:
|
|
553
|
+
if set(query) - {EXPIRES} != {SIGNATURE} or any(len(values) != 1 for values in query.values()):
|
|
554
|
+
return False
|
|
555
|
+
expires = query.get(EXPIRES, [NEVER])[0]
|
|
556
|
+
if not self.covers(route_path) or not self._live(query, now):
|
|
557
|
+
return False
|
|
558
|
+
return same(query[SIGNATURE][0], self._signature(key, route_path, expires))
|
|
559
|
+
|
|
560
|
+
@staticmethod
|
|
561
|
+
def _live(query: Query, now: float) -> bool:
|
|
562
|
+
if EXPIRES not in query:
|
|
563
|
+
return True
|
|
564
|
+
expires = query[EXPIRES][0]
|
|
565
|
+
return bool(EXPIRY.match(expires)) and int(expires) > now
|
|
566
|
+
|
|
567
|
+
@staticmethod
|
|
568
|
+
def _signature(key: bytes, route_path: str, expires: str) -> str:
|
|
569
|
+
message = f"download\n{route_path}\n{expires}".encode("utf-8", "surrogatepass")
|
|
570
|
+
return hmac.new(key, message, hashlib.sha256).hexdigest()
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def auth_mode(value: Any, location: str = "/auth") -> str:
|
|
574
|
+
"""``[auth] mode`` or a session's ``auth``: ``vendor`` (the default, the credential
|
|
575
|
+
the vendor's way) or ``open`` (no credential, on the capability hostname alone)."""
|
|
576
|
+
if value not in AUTH_MODES:
|
|
577
|
+
fail("spec", f"auth.mode is one of {', '.join(AUTH_MODES)}", f"{location}/mode")
|
|
578
|
+
return value
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def session_mode(asked: str | None, token: str | None) -> str:
|
|
582
|
+
"""The auth mode a World Host opens a session in: ``open`` only when the platform asks for it,
|
|
583
|
+
never the world's ``[auth] mode`` (the platform resolves that), so a platform from before the
|
|
584
|
+
open door is never handed an open session; an open session needs the token its capability
|
|
585
|
+
hostname is derived from."""
|
|
586
|
+
mode = VENDOR_MODE if asked is None else auth_mode(asked, "/auth")
|
|
587
|
+
if mode == OPEN_MODE and token is None:
|
|
588
|
+
fail("host", "an open session needs its token; its capability hostname is derived from it")
|
|
589
|
+
return mode
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
EXCHANGES: dict[str, Callable[[Any, Mapping[str, Operation], str], Exchange]] = {OAuth2Auth.name: OAuth2Exchange.of}
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
@dataclass(frozen=True)
|
|
596
|
+
class VendorAuth:
|
|
597
|
+
"""A world's ``[auth]`` (module docstring): the carrier, the secret capture sends
|
|
598
|
+
(``secret_env``, more credential headers in ``extra_headers``), the vendor's login
|
|
599
|
+
exchange and its signed download routes."""
|
|
600
|
+
|
|
601
|
+
scheme: AuthScheme
|
|
602
|
+
secret_env: str | None = None
|
|
603
|
+
extra_headers: dict[str, str] = field(default_factory=dict)
|
|
604
|
+
exchange: Exchange | None = None
|
|
605
|
+
downloads: SignedDownloads | None = None
|
|
606
|
+
mode: str = VENDOR_MODE
|
|
607
|
+
|
|
608
|
+
@classmethod
|
|
609
|
+
def parse(cls, value: Any, operations: Mapping[str, Operation], location: str = "/auth") -> VendorAuth:
|
|
610
|
+
"""``[auth]`` read against the world's operations: the one place its scheme,
|
|
611
|
+
exchange and download routes are decided."""
|
|
612
|
+
table = table_of(value, location)
|
|
613
|
+
if table.get("scheme") == OPEN_MODE:
|
|
614
|
+
fail(
|
|
615
|
+
"spec",
|
|
616
|
+
'auth.scheme is how the vendor takes its key; a world whose sessions ask for none is auth.mode = "open"',
|
|
617
|
+
f"{location}/scheme",
|
|
618
|
+
)
|
|
619
|
+
scheme = AuthScheme.parse(table, location)
|
|
620
|
+
secret_env = string_of(table, "secret_env", location, required=scheme.requires_credential)
|
|
621
|
+
exchange = cls._exchange(table, scheme, operations, location)
|
|
622
|
+
downloads = table.get("downloads")
|
|
623
|
+
signed = None if downloads is None else SignedDownloads.parse(downloads, operations, f"{location}/downloads")
|
|
624
|
+
extra = cls._extra_headers(table, scheme, location)
|
|
625
|
+
return cls(scheme, secret_env, extra, exchange, signed, auth_mode(table.get("mode", VENDOR_MODE), location))
|
|
626
|
+
|
|
627
|
+
@staticmethod
|
|
628
|
+
def _exchange(
|
|
629
|
+
table: dict, scheme: AuthScheme, operations: Mapping[str, Operation], location: str
|
|
630
|
+
) -> Exchange | None:
|
|
631
|
+
if "login" not in table:
|
|
632
|
+
make = EXCHANGES.get(scheme.name)
|
|
633
|
+
return None if make is None else make(scheme, operations, location)
|
|
634
|
+
if not scheme.carries_minted:
|
|
635
|
+
fail(
|
|
636
|
+
"spec",
|
|
637
|
+
"[auth.login] mints a token calls carry as a bearer, a header, Basic or a query parameter; "
|
|
638
|
+
f"auth.scheme {scheme.name} carries none (oauth2 brings its own token route)",
|
|
639
|
+
f"{location}/login",
|
|
640
|
+
)
|
|
641
|
+
return DeclaredLogin.parse(table["login"], operations, f"{location}/login")
|
|
642
|
+
|
|
643
|
+
@staticmethod
|
|
644
|
+
def _extra_headers(table: dict, scheme: AuthScheme, location: str) -> dict[str, str]:
|
|
645
|
+
extra = table.get("headers", {})
|
|
646
|
+
if not isinstance(extra, dict) or not all(
|
|
647
|
+
isinstance(k, str) and k.strip() and isinstance(v, str) and v.strip() for k, v in extra.items()
|
|
648
|
+
):
|
|
649
|
+
fail("spec", "auth.headers maps header names to environment variable names", f"{location}/headers")
|
|
650
|
+
if scheme.secret_header and any(name.lower() == scheme.secret_header for name in extra):
|
|
651
|
+
fail("spec", "auth.headers repeats the secret header", f"{location}/headers")
|
|
652
|
+
return dict(extra)
|
|
653
|
+
|
|
654
|
+
@property
|
|
655
|
+
def env_names(self) -> tuple[str, ...]:
|
|
656
|
+
"""Every environment variable capture reads for the connection's credentials."""
|
|
657
|
+
return tuple(name for name in (self.secret_env, *self.scheme.env_names, *self.extra_headers.values()) if name)
|
|
658
|
+
|
|
659
|
+
@property
|
|
660
|
+
def secret_params(self) -> frozenset[str]:
|
|
661
|
+
"""Query parameters that carry a secret (the carrier's, a link's signature), which no log keeps."""
|
|
662
|
+
signed = {SIGNATURE} if self.downloads is not None else set()
|
|
663
|
+
carried = {self.scheme.secret_param} if self.scheme.secret_param else set()
|
|
664
|
+
return frozenset(signed | carried)
|
|
665
|
+
|
|
666
|
+
def token_path(self, declared: str | None, operations: Mapping[str, Operation], location: str) -> str | None:
|
|
667
|
+
"""Where the oauth2 token route answers (``[api] token_path``, else the scheme's own)."""
|
|
668
|
+
if self.exchange is None and declared is not None:
|
|
669
|
+
fail("spec", "api.token_path belongs to auth.scheme oauth2", f"{location}/token_path")
|
|
670
|
+
return None if self.exchange is None else self.exchange.token_path(declared, operations, location)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
class Entry(StrEnum):
|
|
674
|
+
"""How a request was let in. ``platform``: the session's credential as the
|
|
675
|
+
platform's bearer, so the host presents the world its own credential;
|
|
676
|
+
``vendor``: the credential, or a token the world minted, carried the vendor's
|
|
677
|
+
way; ``exchange``: the vendor's login route, which checks the credential itself;
|
|
678
|
+
``download``: a signed link; ``open``: a world whose vendor asks for nothing, or an
|
|
679
|
+
open session reached on its capability hostname."""
|
|
680
|
+
|
|
681
|
+
PLATFORM = "platform"
|
|
682
|
+
VENDOR = "vendor"
|
|
683
|
+
EXCHANGE = "exchange"
|
|
684
|
+
DOWNLOAD = "download"
|
|
685
|
+
OPEN = "open"
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
class Door:
|
|
689
|
+
"""One session's credential behind a world's ``[auth]`` (module docstring).
|
|
690
|
+
``refusal`` and ``invalid`` are the vendor's 401 and 400 ``(status, body)``;
|
|
691
|
+
``session_refusal`` is what the World Host answers a request its gate refuses:
|
|
692
|
+
the vendor's declared 401 with its content type, or the host's own."""
|
|
693
|
+
|
|
694
|
+
def __init__(
|
|
695
|
+
self,
|
|
696
|
+
auth: VendorAuth,
|
|
697
|
+
credential: str | None,
|
|
698
|
+
*,
|
|
699
|
+
issuer: str,
|
|
700
|
+
prefix: str = "",
|
|
701
|
+
token_path: str | None = None,
|
|
702
|
+
refusal: tuple[int, Any] = (401, {"error": "unauthorized"}),
|
|
703
|
+
invalid: tuple[int, Any] = (400, {"error": "invalid"}),
|
|
704
|
+
session_refusal: tuple[int, Any, str] = SESSION_REFUSAL,
|
|
705
|
+
clock: Callable[[], float] = time.time,
|
|
706
|
+
):
|
|
707
|
+
self.auth = auth
|
|
708
|
+
self.credential = credential
|
|
709
|
+
self.issuer = issuer
|
|
710
|
+
self.token_path = token_path
|
|
711
|
+
self.prefix = prefix
|
|
712
|
+
self.refusal = refusal
|
|
713
|
+
self.invalid = invalid
|
|
714
|
+
self.session_refusal = session_refusal
|
|
715
|
+
self.clock = clock
|
|
716
|
+
self.mint = TokenMint(_derived(credential, "login"), issuer, clock)
|
|
717
|
+
self._download_key = _derived(credential, "download")
|
|
718
|
+
self.exchange = None if auth.exchange is None else auth.exchange.at(token_path)
|
|
719
|
+
|
|
720
|
+
@classmethod
|
|
721
|
+
def of(cls, spec: Spec, settings: Any, credential: str | None, clock: Callable[[], float] = time.time) -> Door:
|
|
722
|
+
"""The door of ``spec``'s routes, refusing in the words ``settings`` (the
|
|
723
|
+
world's ``ApiSettings``) declares for the vendor."""
|
|
724
|
+
declared = (settings.unauthorized_status, settings.unauthorized, settings.error_content_type)
|
|
725
|
+
return cls(
|
|
726
|
+
spec.auth,
|
|
727
|
+
credential,
|
|
728
|
+
issuer=spec.slug,
|
|
729
|
+
prefix=urllib.parse.urlsplit(spec.base_url).path.rstrip("/"),
|
|
730
|
+
token_path=settings.token_path,
|
|
731
|
+
refusal=declared[:2],
|
|
732
|
+
invalid=(settings.invalid_status, settings.invalid),
|
|
733
|
+
session_refusal=declared if settings.unauthorized_declared else SESSION_REFUSAL,
|
|
734
|
+
clock=clock,
|
|
735
|
+
)
|
|
736
|
+
|
|
737
|
+
def route_path(self, path: str) -> str:
|
|
738
|
+
"""``path`` under base_url's path, the way routes are declared; a request may send either."""
|
|
739
|
+
prefix = self.prefix
|
|
740
|
+
return (path[len(prefix) :] or "/") if prefix and path.startswith(prefix) else path
|
|
741
|
+
|
|
742
|
+
def session_entry(self, method: str, path: str, query: str, headers: Headers) -> Entry | None:
|
|
743
|
+
"""How the World Host's gate admits a request, or None to refuse it: the
|
|
744
|
+
vendor's login route, which checks the credential itself and is sent on as it
|
|
745
|
+
came; else the session's credential in the platform's header (module
|
|
746
|
+
docstring), or carried the way the vendor takes it. A session with no
|
|
747
|
+
credential is open."""
|
|
748
|
+
route_path = self.route_path(path)
|
|
749
|
+
if self._exchanges(method, route_path):
|
|
750
|
+
return Entry.EXCHANGE
|
|
751
|
+
if self.credential is None or same(headers.get(PLATFORM_HEADER), self.credential):
|
|
752
|
+
return Entry.PLATFORM
|
|
753
|
+
admitted = self._vendor(method, route_path, headers, urllib.parse.parse_qs(query))
|
|
754
|
+
return Entry.PLATFORM if admitted is None and self.bearer_proves(headers) else admitted
|
|
755
|
+
|
|
756
|
+
def bearer_proves(self, headers: Headers) -> bool:
|
|
757
|
+
"""The platform's ``Authorization: Bearer`` of the session token proves the session
|
|
758
|
+
where the vendor's own way does not, on every world, for good."""
|
|
759
|
+
return same(_PLATFORM.read(headers, {}), self.credential)
|
|
760
|
+
|
|
761
|
+
def by_platform_bearer(self, entry: Entry, headers: Headers) -> bool:
|
|
762
|
+
"""``entry`` came in by the platform's bearer, not its header, on a world whose vendor
|
|
763
|
+
takes its key another way: the host counts these and forwards them in the header."""
|
|
764
|
+
asked = self.credential is not None and self.auth.scheme.requires_credential
|
|
765
|
+
return entry is Entry.PLATFORM and asked and not same(headers.get(PLATFORM_HEADER), self.credential)
|
|
766
|
+
|
|
767
|
+
def with_platform_header(self, headers: Headers) -> dict[str, str]:
|
|
768
|
+
"""``headers`` carrying the session's credential in the platform's own header, as the
|
|
769
|
+
host forwards a request its gate admitted to a version worker, whose gate then admits
|
|
770
|
+
it the same way whatever its clock reads."""
|
|
771
|
+
return {**headers, PLATFORM_HEADER: self.credential or ""}
|
|
772
|
+
|
|
773
|
+
def vendor_entry(self, method: str, path: str, query: str, headers: Headers) -> Entry | None:
|
|
774
|
+
"""How the world's own check admits a request, or None to refuse it: the vendor's
|
|
775
|
+
rules alone, so a world whose vendor asks for nothing admits what it is sent."""
|
|
776
|
+
route_path = self.route_path(path)
|
|
777
|
+
if self._exchanges(method, route_path):
|
|
778
|
+
return Entry.EXCHANGE
|
|
779
|
+
admitted = self._vendor(method, route_path, headers, urllib.parse.parse_qs(query))
|
|
780
|
+
unasked = admitted is None and not self.auth.scheme.requires_credential
|
|
781
|
+
return Entry.OPEN if unasked else admitted
|
|
782
|
+
|
|
783
|
+
def _exchanges(self, method: str, route_path: str) -> bool:
|
|
784
|
+
return self.exchange is not None and self.exchange.matches(method, route_path)
|
|
785
|
+
|
|
786
|
+
def _vendor(self, method: str, route_path: str, headers: Headers, query: Query) -> Entry | None:
|
|
787
|
+
if self._signed(method, route_path, query):
|
|
788
|
+
return Entry.DOWNLOAD
|
|
789
|
+
return Entry.VENDOR if self._carried(self.auth.scheme.read(headers, query)) else None
|
|
790
|
+
|
|
791
|
+
def _signed(self, method: str, route_path: str, query: Query) -> bool:
|
|
792
|
+
downloads = self.auth.downloads
|
|
793
|
+
return (
|
|
794
|
+
method == "GET"
|
|
795
|
+
and downloads is not None
|
|
796
|
+
and downloads.verify(self._download_key, route_path, query, self.clock())
|
|
797
|
+
)
|
|
798
|
+
|
|
799
|
+
def _carried(self, presented: str | None) -> bool:
|
|
800
|
+
if not presented:
|
|
801
|
+
return False
|
|
802
|
+
if self.exchange is not None:
|
|
803
|
+
return self.mint.verify(presented) is not None
|
|
804
|
+
return self.holds(presented)
|
|
805
|
+
|
|
806
|
+
def reachable(self, entry: Entry) -> tuple[str, ...] | None:
|
|
807
|
+
"""The routes a request admitted as ``entry`` may reach: a signed link reaches the
|
|
808
|
+
``[auth.downloads]`` routes alone, never a sibling route on the same path; any
|
|
809
|
+
other entry reaches every route (None)."""
|
|
810
|
+
downloads = self.auth.downloads
|
|
811
|
+
return downloads.routes if entry is Entry.DOWNLOAD and downloads is not None else None
|
|
812
|
+
|
|
813
|
+
@property
|
|
814
|
+
def capability(self) -> str | None:
|
|
815
|
+
"""The secret label of this session's capability hostname (:func:`open_label`),
|
|
816
|
+
None for a session with no credential, which has none."""
|
|
817
|
+
return None if self.credential is None else open_label(self.credential)
|
|
818
|
+
|
|
819
|
+
def opened(self) -> Door:
|
|
820
|
+
"""This session's door on its capability hostname: it asks for nothing, and mints
|
|
821
|
+
and checks with this door's keys, so a token or link minted on either verifies on
|
|
822
|
+
both."""
|
|
823
|
+
return OpenDoor(
|
|
824
|
+
self.auth,
|
|
825
|
+
self.credential,
|
|
826
|
+
issuer=self.issuer,
|
|
827
|
+
prefix=self.prefix,
|
|
828
|
+
token_path=self.token_path,
|
|
829
|
+
refusal=self.refusal,
|
|
830
|
+
invalid=self.invalid,
|
|
831
|
+
session_refusal=self.session_refusal,
|
|
832
|
+
clock=self.clock,
|
|
833
|
+
)
|
|
834
|
+
|
|
835
|
+
def logs_in(self, presented: Any) -> bool:
|
|
836
|
+
"""A declared login's credential field is this session's credential."""
|
|
837
|
+
return isinstance(presented, str) and self.holds(presented)
|
|
838
|
+
|
|
839
|
+
def holds(self, presented: str | None) -> bool:
|
|
840
|
+
"""``presented`` is this session's credential; with none pinned, any value is."""
|
|
841
|
+
return bool(presented) and self.pins(presented)
|
|
842
|
+
|
|
843
|
+
def pins(self, presented: str | None) -> bool:
|
|
844
|
+
"""``presented`` matches the pinned credential; with none pinned, nothing is checked."""
|
|
845
|
+
return self.credential is None or same(presented, self.credential)
|
|
846
|
+
|
|
847
|
+
def present(self) -> Carried:
|
|
848
|
+
"""``(headers, query)`` carrying this session's credential the vendor's way, as
|
|
849
|
+
the host presents it for a caller the platform's bearer admitted: a fresh token
|
|
850
|
+
when the vendor exchanges its credential first."""
|
|
851
|
+
value = self.credential or WORLD_AUTH_SENTINEL
|
|
852
|
+
carried = value if self.exchange is None else self.mint.mint(self.exchange.ttl_s)
|
|
853
|
+
return self.auth.scheme.carry(carried)
|
|
854
|
+
|
|
855
|
+
def answer_exchange(self, raw: bytes, headers: Headers) -> tuple[int, Any]:
|
|
856
|
+
"""The vendor's login route answered: a token for the session's credential, the
|
|
857
|
+
vendor's own refusal for anything else."""
|
|
858
|
+
assert self.exchange is not None, "only an exchange route is answered here"
|
|
859
|
+
return self.exchange.answer(ExchangeRequest(raw, headers), self)
|
|
860
|
+
|
|
861
|
+
def signed_query(self, route_path: str, ttl_s: int | None = None) -> str:
|
|
862
|
+
"""The query of a presigned link to ``route_path`` (``[auth.downloads]``), good for
|
|
863
|
+
``ttl_s`` seconds, else the declared ``ttl_seconds``, else as long as the session."""
|
|
864
|
+
downloads = self.auth.downloads
|
|
865
|
+
if downloads is None:
|
|
866
|
+
fail("handlers", "this world declares no [auth.downloads], so it signs no links", "/auth/downloads")
|
|
867
|
+
if not downloads.covers(route_path):
|
|
868
|
+
fail(
|
|
869
|
+
"handlers",
|
|
870
|
+
f"{route_path} is no route [auth.downloads] names ({', '.join(downloads.routes)})",
|
|
871
|
+
"/auth/downloads",
|
|
872
|
+
)
|
|
873
|
+
if ttl_s is not None:
|
|
874
|
+
ttl_seconds_of({"ttl_seconds": ttl_s}, "/auth/downloads")
|
|
875
|
+
lifetime = downloads.ttl_s if ttl_s is None else ttl_s
|
|
876
|
+
expires = None if lifetime is None else int(self.clock()) + lifetime
|
|
877
|
+
return urllib.parse.urlencode(downloads.sign(self._download_key, route_path, expires))
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
class OpenDoor(Door):
|
|
881
|
+
"""An open session's door on its capability hostname (:meth:`Door.opened`): the
|
|
882
|
+
hostname is the proof, so the gate admits every request as the platform's, the
|
|
883
|
+
world's own check admits it as ``open``, and the vendor's login answers whatever
|
|
884
|
+
credential a client sends, or none."""
|
|
885
|
+
|
|
886
|
+
def session_entry(self, method: str, path: str, query: str, headers: Headers) -> Entry | None:
|
|
887
|
+
return Entry.EXCHANGE if self._exchanges(method, self.route_path(path)) else Entry.PLATFORM
|
|
888
|
+
|
|
889
|
+
def vendor_entry(self, method: str, path: str, query: str, headers: Headers) -> Entry | None:
|
|
890
|
+
return Entry.EXCHANGE if self._exchanges(method, self.route_path(path)) else Entry.OPEN
|
|
891
|
+
|
|
892
|
+
def by_platform_bearer(self, entry: Entry, headers: Headers) -> bool:
|
|
893
|
+
return False
|
|
894
|
+
|
|
895
|
+
def logs_in(self, presented: Any) -> bool:
|
|
896
|
+
return True
|
|
897
|
+
|
|
898
|
+
def pins(self, presented: str | None) -> bool:
|
|
899
|
+
return True
|