@withgateway/sdk 0.3.1 → 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.
Files changed (176) hide show
  1. package/README.md +8 -6
  2. package/dist/cli.js +4372 -2265
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +4362 -2256
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.d.mts +1 -1
  7. package/dist/files/index.d.ts +1 -1
  8. package/dist/files/index.js +259 -58
  9. package/dist/files/index.js.map +1 -1
  10. package/dist/files/index.mjs +249 -50
  11. package/dist/files/index.mjs.map +1 -1
  12. package/dist/hooks/index.d.mts +1 -1
  13. package/dist/hooks/index.d.ts +1 -1
  14. package/dist/hooks/index.js +124 -11
  15. package/dist/hooks/index.js.map +1 -1
  16. package/dist/hooks/index.mjs +124 -11
  17. package/dist/hooks/index.mjs.map +1 -1
  18. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  19. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  20. package/dist/{index-CBqbB_0J.d.ts → index-DUHmS74p.d.ts} +1 -1
  21. package/dist/{index-D-AMnAMa.d.mts → index-mJhG3vZU.d.mts} +1 -1
  22. package/dist/index.d.mts +5 -5
  23. package/dist/index.d.ts +5 -5
  24. package/dist/index.js +2240 -789
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +2150 -739
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{media-CbcAfQvd.d.mts → media-BIApiPzS.d.mts} +21 -2
  29. package/dist/{media-CbcAfQvd.d.ts → media-BIApiPzS.d.ts} +21 -2
  30. package/dist/traces/index.d.mts +1 -1
  31. package/dist/traces/index.d.ts +1 -1
  32. package/dist/traces/index.js +253 -52
  33. package/dist/traces/index.js.map +1 -1
  34. package/dist/traces/index.mjs +243 -44
  35. package/dist/traces/index.mjs.map +1 -1
  36. package/dist/tracing/index.d.mts +2 -2
  37. package/dist/tracing/index.d.ts +2 -2
  38. package/dist/tracing/index.js +75 -13
  39. package/dist/tracing/index.js.map +1 -1
  40. package/dist/tracing/index.mjs +75 -13
  41. package/dist/tracing/index.mjs.map +1 -1
  42. package/dist/worlds/index.d.mts +893 -482
  43. package/dist/worlds/index.d.ts +893 -482
  44. package/dist/worlds/index.js +1968 -669
  45. package/dist/worlds/index.js.map +1 -1
  46. package/dist/worlds/index.mjs +1960 -662
  47. package/dist/worlds/index.mjs.map +1 -1
  48. package/package.json +1 -1
  49. package/runtime/gatewaysdk/environment/_bundle.py +2 -27
  50. package/runtime/gatewaysdk/environment/_materialize.py +48 -88
  51. package/runtime/gatewaysdk/environment/_world.py +155 -237
  52. package/runtime/gatewaysdk/environment/backing.py +133 -0
  53. package/runtime/gatewaysdk/environment/core.py +2 -17
  54. package/runtime/gatewaysdk/environment/legacy_sqlite.py +288 -0
  55. package/runtime/gatewaysdk/environment/reward_keys.py +25 -0
  56. package/runtime/gatewaysdk/environment/runtime.py +8 -13
  57. package/runtime/gatewaysdk/environment/schema/__init__.py +4 -4
  58. package/runtime/gatewaysdk/environment/schema/admin_routes.py +86 -0
  59. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  60. package/runtime/gatewaysdk/environment/schema/api.py +347 -892
  61. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  62. package/runtime/gatewaysdk/environment/schema/batch.py +44 -39
  63. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +17 -5
  64. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  65. package/runtime/gatewaysdk/environment/schema/call_capture.py +309 -0
  66. package/runtime/gatewaysdk/environment/schema/call_log.py +503 -0
  67. package/runtime/gatewaysdk/environment/schema/call_redaction.py +526 -0
  68. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  69. package/runtime/gatewaysdk/environment/schema/compiler.py +334 -158
  70. package/runtime/gatewaysdk/environment/schema/conform.py +14 -39
  71. package/runtime/gatewaysdk/environment/schema/connector.py +113 -211
  72. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  73. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +1 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  75. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  76. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  77. package/runtime/gatewaysdk/environment/schema/data.py +60 -216
  78. package/runtime/gatewaysdk/environment/schema/database/__init__.py +24 -0
  79. package/runtime/gatewaysdk/environment/schema/database/audit.py +121 -0
  80. package/runtime/gatewaysdk/environment/schema/database/base.py +936 -0
  81. package/runtime/gatewaysdk/environment/schema/database/budget.py +33 -0
  82. package/runtime/gatewaysdk/environment/schema/database/connections.py +101 -0
  83. package/runtime/gatewaysdk/environment/schema/database/engines.py +8 -0
  84. package/runtime/gatewaysdk/environment/schema/database/guard.py +215 -0
  85. package/runtime/gatewaysdk/environment/schema/database/ingest.py +154 -0
  86. package/runtime/gatewaysdk/environment/schema/database/matching.py +58 -0
  87. package/runtime/gatewaysdk/environment/schema/database/provenance.py +30 -0
  88. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  89. package/runtime/gatewaysdk/environment/schema/database/rows.py +53 -0
  90. package/runtime/gatewaysdk/environment/schema/database/runtime_rows.py +39 -0
  91. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +393 -0
  92. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  93. package/runtime/gatewaysdk/environment/schema/domain_migration.py +236 -0
  94. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  95. package/runtime/gatewaysdk/environment/schema/envelope.py +227 -0
  96. package/runtime/gatewaysdk/environment/schema/extract.py +6 -13
  97. package/runtime/gatewaysdk/environment/schema/grading.py +90 -103
  98. package/runtime/gatewaysdk/environment/schema/handler_errors.py +163 -12
  99. package/runtime/gatewaysdk/environment/schema/host.py +237 -1795
  100. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  101. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  102. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  103. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  104. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  105. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  106. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  107. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  108. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  109. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  110. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  111. package/runtime/gatewaysdk/environment/schema/journal.py +437 -0
  112. package/runtime/gatewaysdk/environment/schema/lanes.py +53 -0
  113. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  114. package/runtime/gatewaysdk/environment/schema/local.py +58 -170
  115. package/runtime/gatewaysdk/environment/schema/mapping.py +5 -25
  116. package/runtime/gatewaysdk/environment/schema/openapi_import.py +112 -73
  117. package/runtime/gatewaysdk/environment/schema/openapi_paging.py +147 -0
  118. package/runtime/gatewaysdk/environment/schema/openapi_payloads.py +288 -0
  119. package/runtime/gatewaysdk/environment/schema/openapi_routes.py +97 -102
  120. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +113 -30
  121. package/runtime/gatewaysdk/environment/schema/platform.py +137 -187
  122. package/runtime/gatewaysdk/environment/schema/platform_import.py +2 -3
  123. package/runtime/gatewaysdk/environment/schema/platform_query.py +61 -5
  124. package/runtime/gatewaysdk/environment/schema/primary_key.py +61 -0
  125. package/runtime/gatewaysdk/environment/schema/proof.py +19 -12
  126. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  127. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  128. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  129. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  130. package/runtime/gatewaysdk/environment/schema/runtime.py +178 -308
  131. package/runtime/gatewaysdk/environment/schema/served_names.py +58 -0
  132. package/runtime/gatewaysdk/environment/schema/session_files.py +275 -0
  133. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  134. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  135. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +10 -11
  136. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +49 -16
  137. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +39 -9
  138. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +27 -27
  139. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +33 -33
  140. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +13 -7
  141. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +49 -1
  142. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  143. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/openapi-import.md +50 -21
  144. package/runtime/gatewaysdk/environment/schema/slack.py +4 -8
  145. package/runtime/gatewaysdk/environment/schema/snapshot.py +516 -140
  146. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  147. package/runtime/gatewaysdk/environment/schema/store_contract.py +8 -14
  148. package/runtime/gatewaysdk/environment/schema/tasks.py +267 -276
  149. package/runtime/gatewaysdk/environment/schema/tools_world.py +146 -242
  150. package/runtime/gatewaysdk/environment/schema/ui.py +24 -5
  151. package/runtime/gatewaysdk/environment/schema/ui_static/app.js +100 -130
  152. package/runtime/gatewaysdk/environment/schema/ui_static/index.html +1 -8
  153. package/runtime/gatewaysdk/environment/schema/validation.py +235 -41
  154. package/runtime/gatewaysdk/environment/schema/verbs.py +32 -36
  155. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  156. package/runtime/gatewaysdk/environment/schema/workers.py +345 -96
  157. package/runtime/gatewaysdk/environment/schema/world_host.py +953 -0
  158. package/runtime/gatewaysdk/environment/schema/world_sql.py +81 -0
  159. package/runtime/gatewaysdk/environment/schema/world_tests.py +80 -50
  160. package/runtime/gatewaysdk/environment/score.py +57 -0
  161. package/runtime/gatewaysdk/environment/secret_values.py +36 -0
  162. package/runtime/gatewaysdk/environment/world.py +43 -4
  163. package/runtime/gatewaysdk/environment/world_session_contract.py +46 -5
  164. package/skills/agents/connector-template-author.md +5 -1
  165. package/skills/benchmarks-getting-started/SKILL.md +10 -11
  166. package/skills/connector-schema-authoring/SKILL.md +49 -16
  167. package/skills/connector-schema-authoring/connector-worlds.md +142 -11
  168. package/skills/connector-schema-authoring/world-schema.md +103 -51
  169. package/skills/world-data-ingestion/ROWS.md +39 -9
  170. package/skills/world-data-ingestion/SKILL.md +27 -27
  171. package/skills/worlds-getting-started/SKILL.md +33 -33
  172. package/skills/worlds-getting-started/references/cli-mcp-map.md +13 -7
  173. package/skills/worlds-getting-started/references/gotchas.md +49 -1
  174. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
  175. package/skills/worlds-getting-started/references/openapi-import.md +50 -21
  176. package/runtime/gatewaysdk/environment/schema/store.py +0 -1013
@@ -44,6 +44,7 @@ base_url = "https://instance.service-now.com"
44
44
  # is the other supported scheme and is registered per instance. No credential
45
45
  # ships with the template; the served world accepts the host's session credential.
46
46
  scheme = "basic"
47
+ credential = "password"
47
48
  secret_env = "SERVICENOW_BASIC_AUTH"
48
49
 
49
50
  [capture]
@@ -98,7 +99,7 @@ not_found_status = 404
98
99
  invalid_status = 400
99
100
 
100
101
  [ui]
101
- # Rishi's pixel-faithful Next Experience twin, built from twins/servicenow/ui with
102
+ # The Next Experience twin, built from twins/servicenow/ui with
102
103
  # no source edits. `generated = false`: ui/static is a build artifact of that
103
104
  # directory, not the generated page, so compile leaves it alone. The SPA calls the api at the same origin
104
105
  # under /__world-api, which the World Host rewrites onto the routes below.
@@ -109,8 +110,6 @@ entry = "/"
109
110
  api_path = "/__world-api"
110
111
  generated = false
111
112
 
112
- # ------------------------------------------------------- the Table API (vendor)
113
-
114
113
  [[operations]]
115
114
  name = "list_table_records"
116
115
  path = "/api/now/table/{tableName}"
@@ -192,8 +191,6 @@ handler = "delete_table_record"
192
191
  status = 204
193
192
  sample = { tableName = "incident_task", sys_id = "eaaefd673662a9417c46de3a53e6b147" }
194
193
 
195
- # ------------------------------- the Next Experience shell (what the ui calls)
196
-
197
194
  [[operations]]
198
195
  name = "get_me"
199
196
  path = "/api/now/ui/me"
@@ -0,0 +1,54 @@
1
+ """How a world answers browsers: ``[api] cors = true`` says the vendor's API serves pages on any
2
+ origin, so a preflight is answered and every answer names any origin; without it a world sends
3
+ no CORS header and an OPTIONS request is routed like any other method."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from dataclasses import dataclass
9
+
10
+ ALLOW_ORIGIN = "Access-Control-Allow-Origin"
11
+ REQUESTED_HEADERS = "access-control-request-headers"
12
+ HEADER_NAMES = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:[ \t]*,[ \t]*[!#$%&'*+.^_`|~0-9A-Za-z-]+)*")
13
+ MAX_REQUESTED_CHARS = 1024
14
+
15
+ Preflight = tuple[int, None, dict[str, str]]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Cors:
20
+ """A vendor whose API serves no browser."""
21
+
22
+ @staticmethod
23
+ def of(declared: bool, methods: tuple[str, ...]) -> Cors:
24
+ """The world's CORS: :class:`OpenCors` over ``methods`` when declared, else none."""
25
+ return OpenCors(methods) if declared else Cors()
26
+
27
+ def preflight(self, method: str, headers: dict[str, str]) -> Preflight | None:
28
+ return None
29
+
30
+ def carried(self, extra: dict[str, str] | None) -> dict[str, str] | None:
31
+ return extra
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class OpenCors(Cors):
36
+ """A vendor whose API answers pages on any origin, without credentials. A preflight is
37
+ answered before any credential is checked, since a browser sends none with it: it names the
38
+ methods the world serves and, when they are a list of header names, the headers the page
39
+ asked to send. It reads nothing and writes nothing. Every other answer exposes its headers
40
+ (``Link``, the page headers) to the page."""
41
+
42
+ methods: tuple[str, ...]
43
+
44
+ def preflight(self, method: str, headers: dict[str, str]) -> Preflight | None:
45
+ if method != "OPTIONS":
46
+ return None
47
+ allowed = {ALLOW_ORIGIN: "*", "Access-Control-Allow-Methods": ", ".join(self.methods)}
48
+ requested = headers.get(REQUESTED_HEADERS, "")
49
+ if len(requested) <= MAX_REQUESTED_CHARS and HEADER_NAMES.fullmatch(requested):
50
+ allowed["Access-Control-Allow-Headers"] = requested
51
+ return 204, None, allowed
52
+
53
+ def carried(self, extra: dict[str, str] | None) -> dict[str, str] | None:
54
+ return {**(extra or {}), ALLOW_ORIGIN: "*", "Access-Control-Expose-Headers": "*"}
@@ -1,20 +1,325 @@
1
- """How a ``basic`` world's credential rides a request: as the Basic *user*,
2
- with an empty password (``Basic b64("<key>:")``). The host and the local
3
- server present it that way (``api.vendor_credential``), and the world
4
- (``WorldApp.authorized``) and the host's gate (``vendor_shaped_token``) read
5
- it back with :func:`basic_user`, so the two sides cannot drift."""
1
+ """How a vendor's credential rides a request: one :class:`AuthScheme` kind per
2
+ ``[auth] scheme`` of ``connector.toml``.
3
+
4
+ A kind knows where a value sits in a request (:meth:`AuthScheme.read`) and how
5
+ to put it there (:meth:`AuthScheme.carry`). The door (:mod:`.door`), the
6
+ credential the World Host presents to a world, capture and the conformance run
7
+ read and write a credential through it alone, so no two of them can disagree on
8
+ a shape. ``sdk-ts/src/hooks/vendorAuth.ts`` carries the same shapes to a live
9
+ vendor; ``conformance/vendor-auth.json`` pins both. A ``bearer`` value rides
10
+ ``Authorization`` after the first of the words the vendor takes (``prefixes``,
11
+ ``["Bearer"]`` unless declared). A ``basic`` value is the Basic *user* with an
12
+ empty password (``Basic b64("<key>:")``), or the password under any user when
13
+ the vendor reads it there (``credential = "password"``, ``Basic b64(":<key>")``);
14
+ a value that already holds a colon is the whole ``user:password``.
15
+ """
6
16
 
7
17
  from __future__ import annotations
8
18
 
9
19
  import base64
20
+ import re
21
+ from abc import ABC, abstractmethod
22
+ from dataclasses import dataclass
23
+ from typing import Any, Callable, ClassVar, Mapping
24
+
25
+ from .validation import fail, string_of, ttl_seconds_of
26
+
27
+ DEFAULT_TOKEN_PATH = "/oauth/token"
28
+ OAUTH2_KEYS = frozenset({"token_url", "client_id_env", "scope", "ttl_seconds"})
29
+ AUTH_WORD = re.compile(r"[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}")
30
+ BASIC_HALVES = ("user", "password")
10
31
 
32
+ Headers = Mapping[str, str]
33
+ Query = Mapping[str, list[str]]
34
+ Carried = tuple[dict[str, str], dict[str, str]]
11
35
 
12
- def basic_user(authorization: str) -> str | None:
13
- """The user of a ``Basic`` authorization header, or None when it is not one."""
36
+
37
+ def basic_pair(authorization: str) -> tuple[str, str] | None:
38
+ """The user and password of a ``Basic`` authorization header (the password empty
39
+ when it names none), or None when it is not one."""
14
40
  if not authorization.lower().startswith("basic "):
15
41
  return None
16
42
  try:
17
43
  decoded = base64.b64decode(authorization[6:].strip().encode("ascii"), validate=True).decode("utf-8")
18
44
  except (ValueError, UnicodeDecodeError):
19
45
  return None
20
- return decoded.split(":", 1)[0]
46
+ user, _, password = decoded.partition(":")
47
+ return user, password
48
+
49
+
50
+ class AuthScheme(ABC):
51
+ """Where a vendor's credential sits in a request. ``requires_credential``:
52
+ the vendor refuses a call without one; ``carries_minted``: a token the
53
+ world's declared ``[auth.login]`` mints may ride it."""
54
+
55
+ name: ClassVar[str]
56
+ keys: ClassVar[frozenset[str]] = frozenset()
57
+ requires_credential: ClassVar[bool] = True
58
+ carries_minted: ClassVar[bool] = True
59
+
60
+ @staticmethod
61
+ def parse(table: Mapping[str, Any], location: str = "/auth") -> AuthScheme:
62
+ """The kind ``table["scheme"]`` names, read from the rest of ``table``: the
63
+ one place a scheme's kind is decided. A setting of another kind is refused."""
64
+ kind = SCHEMES.get(string_of(dict(table), "scheme", location) or "")
65
+ if kind is None:
66
+ fail("spec", f"auth.scheme must be one of {', '.join(SCHEMES)}", f"{location}/scheme")
67
+ stray = sorted(SCHEME_KEYS.intersection(table) - kind.keys)
68
+ if stray:
69
+ owners = " or ".join(name for name, other in SCHEMES.items() if stray[0] in other.keys)
70
+ fail("spec", f"{stray[0]} belongs to auth.scheme {owners}", f"{location}/{stray[0]}")
71
+ return kind.from_table(table, location)
72
+
73
+ @classmethod
74
+ def from_table(cls, table: Mapping[str, Any], location: str) -> AuthScheme:
75
+ string_of(dict(table), "name", location, required=False)
76
+ return cls()
77
+
78
+ @abstractmethod
79
+ def read(self, headers: Headers, query: Query) -> str | None:
80
+ """The value a request carries this way (``headers`` lower-cased), or None."""
81
+
82
+ @abstractmethod
83
+ def carry(self, value: str) -> Carried:
84
+ """``(headers, query)`` carrying ``value`` this way, header names lower-cased."""
85
+
86
+ def security_scheme(self, token_path: str | None) -> dict:
87
+ """The OpenAPI security scheme a world's ``openapi.json`` declares for it."""
88
+ return {}
89
+
90
+ def capture_value(self, secret: Callable[[], str], mint: Callable[[], str]) -> str | None:
91
+ """What capture sends the live vendor: the connection's secret, unless this
92
+ kind exchanges it for a token first."""
93
+ return secret()
94
+
95
+ def token_request(
96
+ self, base_url: str, client_secret: Callable[[], str], environ: Mapping[str, str]
97
+ ) -> tuple[str, dict[str, str]]:
98
+ """The URL and form an RFC 6749 client-credentials exchange posts."""
99
+ fail("secret", "Only an oauth2 connection mints tokens", "/auth/scheme")
100
+
101
+ @property
102
+ def env_names(self) -> tuple[str, ...]:
103
+ """Environment variables capture reads for this kind beside ``secret_env``."""
104
+ return ()
105
+
106
+ @property
107
+ def secret_param(self) -> str | None:
108
+ """The query parameter a value rides in, which no log keeps."""
109
+ return None
110
+
111
+ @property
112
+ def secret_header(self) -> str | None:
113
+ """The header a value rides in (lower-cased), which no log keeps."""
114
+ return None
115
+
116
+
117
+ @dataclass(frozen=True)
118
+ class NoAuth(AuthScheme):
119
+ name: ClassVar[str] = "none"
120
+ requires_credential: ClassVar[bool] = False
121
+ carries_minted: ClassVar[bool] = False
122
+
123
+ @classmethod
124
+ def from_table(cls, table: Mapping[str, Any], location: str) -> NoAuth:
125
+ if "name" in table or "secret_env" in table:
126
+ fail("spec", "auth.scheme none takes no name or secret_env", location)
127
+ return cls()
128
+
129
+ def read(self, headers: Headers, query: Query) -> str | None:
130
+ return None
131
+
132
+ def carry(self, value: str) -> Carried:
133
+ return {}, {}
134
+
135
+ def capture_value(self, secret: Callable[[], str], mint: Callable[[], str]) -> str | None:
136
+ return None
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class BearerAuth(AuthScheme):
141
+ """``Authorization: <word> <value>``, the word one of ``prefixes`` in any case
142
+ (GitHub takes ``Bearer`` and ``token``); a call carries the first."""
143
+
144
+ name: ClassVar[str] = "bearer"
145
+ keys: ClassVar[frozenset[str]] = frozenset({"prefixes"})
146
+ prefixes: tuple[str, ...] = ("Bearer",)
147
+
148
+ @classmethod
149
+ def from_table(cls, table: Mapping[str, Any], location: str) -> BearerAuth:
150
+ string_of(dict(table), "name", location, required=False)
151
+ return cls(cls.prefixes_of(table, location))
152
+
153
+ @staticmethod
154
+ def prefixes_of(table: Mapping[str, Any], location: str) -> tuple[str, ...]:
155
+ words = table.get("prefixes", ["Bearer"])
156
+ valid = (
157
+ isinstance(words, list)
158
+ and bool(words)
159
+ and all(isinstance(w, str) and AUTH_WORD.fullmatch(w) for w in words)
160
+ )
161
+ if not valid or len({word.lower() for word in words}) != len(words):
162
+ fail(
163
+ "spec",
164
+ "prefixes lists the distinct words the vendor takes before the key in Authorization",
165
+ f"{location}/prefixes",
166
+ )
167
+ return tuple(words)
168
+
169
+ def read(self, headers: Headers, query: Query) -> str | None:
170
+ word, _, value = headers.get("authorization", "").partition(" ")
171
+ return value if word.lower() in {prefix.lower() for prefix in self.prefixes} else None
172
+
173
+ def carry(self, value: str) -> Carried:
174
+ return {"authorization": f"{self.prefixes[0]} {value}"}, {}
175
+
176
+ def security_scheme(self, token_path: str | None) -> dict:
177
+ return {"type": "http", "scheme": "bearer"}
178
+
179
+
180
+ @dataclass(frozen=True)
181
+ class HeaderAuth(AuthScheme):
182
+ name: ClassVar[str] = "header"
183
+ header: str
184
+
185
+ @classmethod
186
+ def from_table(cls, table: Mapping[str, Any], location: str) -> HeaderAuth:
187
+ return cls(string_of(dict(table), "name", location) or "")
188
+
189
+ def read(self, headers: Headers, query: Query) -> str | None:
190
+ return headers.get(self.header.lower())
191
+
192
+ def carry(self, value: str) -> Carried:
193
+ return {self.header.lower(): value}, {}
194
+
195
+ def security_scheme(self, token_path: str | None) -> dict:
196
+ return {"type": "apiKey", "in": "header", "name": self.header}
197
+
198
+ @property
199
+ def secret_header(self) -> str | None:
200
+ return self.header.lower()
201
+
202
+
203
+ @dataclass(frozen=True)
204
+ class BasicAuth(AuthScheme):
205
+ """``Authorization: Basic``, the key the user with an empty password, or with
206
+ ``credential = "password"`` the password under any user (Atlassian's
207
+ ``email:api_token``, ServiceNow's ``user:password``)."""
208
+
209
+ name: ClassVar[str] = "basic"
210
+ keys: ClassVar[frozenset[str]] = frozenset({"credential"})
211
+ credential: str = "user"
212
+
213
+ @classmethod
214
+ def from_table(cls, table: Mapping[str, Any], location: str) -> BasicAuth:
215
+ given = dict(table)
216
+ string_of(given, "name", location, required=False)
217
+ half = string_of(given, "credential", location, default="user", required=False)
218
+ if half not in BASIC_HALVES:
219
+ fail(
220
+ "spec",
221
+ "credential is the half of the Basic pair the key is: user or password",
222
+ f"{location}/credential",
223
+ )
224
+ return cls(half)
225
+
226
+ def read(self, headers: Headers, query: Query) -> str | None:
227
+ pair = basic_pair(headers.get("authorization", ""))
228
+ return None if pair is None else pair[BASIC_HALVES.index(self.credential)]
229
+
230
+ def carry(self, value: str) -> Carried:
231
+ halves = {"user": f"{value}:", "password": f":{value}"}
232
+ pair = value if ":" in value else halves[self.credential]
233
+ return {"authorization": "Basic " + base64.b64encode(pair.encode("utf-8")).decode("ascii")}, {}
234
+
235
+ def security_scheme(self, token_path: str | None) -> dict:
236
+ return {"type": "http", "scheme": "basic"}
237
+
238
+
239
+ @dataclass(frozen=True)
240
+ class QueryAuth(AuthScheme):
241
+ name: ClassVar[str] = "query"
242
+ param: str
243
+
244
+ @classmethod
245
+ def from_table(cls, table: Mapping[str, Any], location: str) -> QueryAuth:
246
+ return cls(string_of(dict(table), "name", location) or "")
247
+
248
+ def read(self, headers: Headers, query: Query) -> str | None:
249
+ values = query.get(self.param)
250
+ return values[0] if values else None
251
+
252
+ def carry(self, value: str) -> Carried:
253
+ return {}, {self.param: value}
254
+
255
+ def security_scheme(self, token_path: str | None) -> dict:
256
+ return {"type": "apiKey", "in": "query", "name": self.param}
257
+
258
+ @property
259
+ def secret_param(self) -> str | None:
260
+ return self.param
261
+
262
+
263
+ @dataclass(frozen=True, kw_only=True)
264
+ class OAuth2Auth(BearerAuth):
265
+ """RFC 6749 client credentials: calls carry a bearer the vendor's token route
266
+ minted. ``token_url`` is where capture exchanges ``client_id_env`` and the
267
+ secret (a path under ``base_url`` or an absolute URL); a world serves its own
268
+ token route on that path, or on ``/oauth/token`` when it is absolute. Its tokens
269
+ live as long as the session unless ``ttl_seconds`` declares a lifetime."""
270
+
271
+ name: ClassVar[str] = "oauth2"
272
+ keys: ClassVar[frozenset[str]] = OAUTH2_KEYS | {"prefixes"}
273
+ carries_minted: ClassVar[bool] = False
274
+ client_id_env: str
275
+ token_url: str = DEFAULT_TOKEN_PATH
276
+ scope: str | None = None
277
+ ttl_s: int | None = None
278
+
279
+ @classmethod
280
+ def from_table(cls, table: Mapping[str, Any], location: str) -> OAuth2Auth:
281
+ given = dict(table)
282
+ string_of(given, "name", location, required=False)
283
+ token_url = string_of(given, "token_url", location, default=DEFAULT_TOKEN_PATH, required=False) or ""
284
+ if not token_url.startswith(("/", "https://", "http://")):
285
+ fail("spec", "auth.token_url is a path under base_url or an absolute URL", f"{location}/token_url")
286
+ client_id_env = string_of(given, "client_id_env", location) or ""
287
+ return cls(
288
+ prefixes=cls.prefixes_of(given, location),
289
+ client_id_env=client_id_env,
290
+ token_url=token_url,
291
+ scope=string_of(given, "scope", location, required=False),
292
+ ttl_s=ttl_seconds_of(given, location),
293
+ )
294
+
295
+ @property
296
+ def env_names(self) -> tuple[str, ...]:
297
+ return (self.client_id_env,)
298
+
299
+ @property
300
+ def served_token_path(self) -> str:
301
+ return self.token_url if self.token_url.startswith("/") else DEFAULT_TOKEN_PATH
302
+
303
+ def capture_value(self, secret: Callable[[], str], mint: Callable[[], str]) -> str | None:
304
+ return mint()
305
+
306
+ def token_request(
307
+ self, base_url: str, client_secret: Callable[[], str], environ: Mapping[str, str]
308
+ ) -> tuple[str, dict[str, str]]:
309
+ client_id = environ.get(self.client_id_env)
310
+ if not client_id:
311
+ fail("secret", f"Set {self.client_id_env} to the connection's client id", "/auth/client_id_env")
312
+ form = {"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret()}
313
+ scope = {"scope": self.scope} if self.scope else {}
314
+ absolute = self.token_url.startswith(("https://", "http://"))
315
+ return (self.token_url if absolute else base_url + self.token_url), {**form, **scope}
316
+
317
+ def security_scheme(self, token_path: str | None) -> dict:
318
+ flow = {"tokenUrl": token_path or DEFAULT_TOKEN_PATH, "scopes": {self.scope or "api": "API access"}}
319
+ return {"type": "oauth2", "flows": {"clientCredentials": flow}}
320
+
321
+
322
+ SCHEMES: dict[str, type[AuthScheme]] = {
323
+ kind.name: kind for kind in (HeaderAuth, BearerAuth, BasicAuth, QueryAuth, OAuth2Auth, NoAuth)
324
+ }
325
+ SCHEME_KEYS = frozenset().union(*(kind.keys for kind in SCHEMES.values()))