@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.
Files changed (123) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +2221 -962
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +2212 -953
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.js +81 -19
  7. package/dist/files/index.js.map +1 -1
  8. package/dist/files/index.mjs +79 -17
  9. package/dist/files/index.mjs.map +1 -1
  10. package/dist/hooks/index.d.mts +1 -1
  11. package/dist/hooks/index.d.ts +1 -1
  12. package/dist/hooks/index.js +124 -11
  13. package/dist/hooks/index.js.map +1 -1
  14. package/dist/hooks/index.mjs +124 -11
  15. package/dist/hooks/index.mjs.map +1 -1
  16. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  17. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  18. package/dist/index.d.mts +2 -2
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +903 -221
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +868 -212
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/traces/index.js +78 -16
  25. package/dist/traces/index.js.map +1 -1
  26. package/dist/traces/index.mjs +76 -14
  27. package/dist/traces/index.mjs.map +1 -1
  28. package/dist/tracing/index.js +7 -1
  29. package/dist/tracing/index.js.map +1 -1
  30. package/dist/tracing/index.mjs +7 -1
  31. package/dist/tracing/index.mjs.map +1 -1
  32. package/dist/worlds/index.d.mts +692 -410
  33. package/dist/worlds/index.d.ts +692 -410
  34. package/dist/worlds/index.js +740 -197
  35. package/dist/worlds/index.js.map +1 -1
  36. package/dist/worlds/index.mjs +736 -193
  37. package/dist/worlds/index.mjs.map +1 -1
  38. package/package.json +1 -1
  39. package/runtime/gatewaysdk/environment/_materialize.py +5 -25
  40. package/runtime/gatewaysdk/environment/_world.py +58 -65
  41. package/runtime/gatewaysdk/environment/backing.py +20 -24
  42. package/runtime/gatewaysdk/environment/core.py +1 -16
  43. package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
  44. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  45. package/runtime/gatewaysdk/environment/schema/api.py +174 -471
  46. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  47. package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
  48. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  49. package/runtime/gatewaysdk/environment/schema/call_capture.py +309 -0
  50. package/runtime/gatewaysdk/environment/schema/call_log.py +230 -18
  51. package/runtime/gatewaysdk/environment/schema/call_redaction.py +201 -19
  52. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  53. package/runtime/gatewaysdk/environment/schema/conform.py +6 -27
  54. package/runtime/gatewaysdk/environment/schema/connector.py +89 -152
  55. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  56. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +1 -0
  57. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  58. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  59. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  60. package/runtime/gatewaysdk/environment/schema/data.py +14 -13
  61. package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
  62. package/runtime/gatewaysdk/environment/schema/database/guard.py +43 -36
  63. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  64. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
  65. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  66. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  67. package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
  68. package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
  69. package/runtime/gatewaysdk/environment/schema/handler_errors.py +25 -4
  70. package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
  71. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  72. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  73. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  74. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  75. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  76. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  77. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  78. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  79. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  80. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  81. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  82. package/runtime/gatewaysdk/environment/schema/journal.py +437 -0
  83. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  84. package/runtime/gatewaysdk/environment/schema/local.py +31 -116
  85. package/runtime/gatewaysdk/environment/schema/platform.py +15 -17
  86. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  87. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  88. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  89. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  90. package/runtime/gatewaysdk/environment/schema/runtime.py +129 -176
  91. package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
  92. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  93. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  94. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
  95. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +31 -6
  96. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
  97. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +13 -13
  98. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +23 -23
  99. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +11 -6
  100. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +35 -2
  101. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  102. package/runtime/gatewaysdk/environment/schema/snapshot.py +149 -29
  103. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  104. package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
  105. package/runtime/gatewaysdk/environment/schema/tools_world.py +84 -203
  106. package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
  107. package/runtime/gatewaysdk/environment/schema/verbs.py +32 -36
  108. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  109. package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
  110. package/runtime/gatewaysdk/environment/schema/world_host.py +953 -0
  111. package/runtime/gatewaysdk/environment/schema/world_tests.py +9 -11
  112. package/runtime/gatewaysdk/environment/world.py +1 -1
  113. package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
  114. package/skills/agents/connector-template-author.md +5 -1
  115. package/skills/benchmarks-getting-started/SKILL.md +8 -9
  116. package/skills/connector-schema-authoring/SKILL.md +31 -6
  117. package/skills/connector-schema-authoring/connector-worlds.md +129 -7
  118. package/skills/world-data-ingestion/ROWS.md +12 -8
  119. package/skills/world-data-ingestion/SKILL.md +13 -13
  120. package/skills/worlds-getting-started/SKILL.md +23 -23
  121. package/skills/worlds-getting-started/references/cli-mcp-map.md +11 -6
  122. package/skills/worlds-getting-started/references/gotchas.md +35 -2
  123. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
@@ -16,6 +16,11 @@ or a field named only for what it holds (:data:`NAMED_BY_HOLDER`: ``value``,
16
16
  ``pan``), which elsewhere name other things (``boarding_pass``);
17
17
  * it is a ``number``, ``no`` or ``pan`` under a ``card``.
18
18
 
19
+ Every string kept is scrubbed in place (:meth:`CallRedaction.scrub`), the rest
20
+ of it kept: the session's credential as sent and percent-encoded, the value of a
21
+ query parameter the world's ``[auth]`` carries a secret in (a query key, a signed
22
+ link's ``signature``) wherever a link holding it sits, and a JSON Web Token.
23
+
19
24
  A value is a credential by its shape, whatever its field: a provider key, an
20
25
  AWS key id or a bearer header (:data:`~gatewaysdk.environment.secret_values.SECRET_VALUE`,
21
26
  the browser recorder's rule), the further token shapes of
@@ -30,8 +35,9 @@ Each string or number so named or shaped reads :data:`REDACTED`; the key stays,
30
35
  so a grader can still ask whether it was sent. Booleans, nulls and every other
31
36
  field are kept as sent, so a grader reads what the agent asked, with what
32
37
  no reply can carry read as text: an unpaired surrogate as U+FFFD, a NaN or an
33
- infinity as ``"NaN"``, ``"Infinity"``, ``"-Infinity"``. A query-auth world's own
34
- credential parameter is dropped. A request holding more than
38
+ infinity as ``"NaN"``, ``"Infinity"``, ``"-Infinity"``. A query parameter the
39
+ world's ``[auth]`` carries a secret in (a query-auth key, a signed link's
40
+ signature) is dropped. A request holding more than
35
41
  :data:`MAX_LOGGED_VALUES` values, keys and key parts, or :data:`MAX_LOGGED_CHARS`
36
42
  characters of text, its keys included, is too large to keep
37
43
  (:class:`RequestTooLarge`): its whole request shares one :class:`RequestBudget`.
@@ -43,15 +49,18 @@ import re
43
49
  import urllib.parse
44
50
  from dataclasses import dataclass, replace
45
51
  from functools import cached_property
46
- from typing import Any, Iterator
52
+ from typing import Any, Callable, Iterable, Iterator
47
53
 
48
54
  from ..secret_values import SECRET_TOKEN, SECRET_VALUE, basic_credentials
49
55
  from .connector import PLACEHOLDER, Operation, Spec
56
+ from .door import open_label
50
57
  from .handler_errors import carried_scalar
51
58
 
52
59
  REDACTED = "[redacted]"
53
60
  MAX_LOGGED_VALUES = 100_000
54
61
  MAX_LOGGED_CHARS = 1 << 20
62
+ SCRUB_MARGIN = 8 * 1024
63
+ MIN_SCRUBBED_SECRET = 16
55
64
 
56
65
  CREDENTIAL_WORDS = frozenset(
57
66
  {
@@ -161,7 +170,31 @@ KEPT_SUFFIXES = (
161
170
  "deltatoken",
162
171
  "preauthorization",
163
172
  )
173
+ KEPT_HEADERS = frozenset(
174
+ {
175
+ "accept",
176
+ "cache-control",
177
+ "content-encoding",
178
+ "content-length",
179
+ "content-type",
180
+ "host",
181
+ "idempotency-key",
182
+ "origin",
183
+ "user-agent",
184
+ "x-forwarded-proto",
185
+ "x-request-id",
186
+ }
187
+ )
188
+ KEPT_HEADER_PREFIXES = ("accept-", "if-", "sec-fetch-")
189
+ HEADER_NAME_CHARS = 256
164
190
  _WORD = re.compile(r"[A-Z]?[a-z]+\d*|[A-Z]+\d*(?![a-z])|\d+")
191
+ _QUERY_LEAD = r"(?:[?&;]|%(?:25)?26|%(?:25)?3[Ff]|\\u0026|\\u003[Ff])"
192
+ _QUERY_EQUALS = r"(?:=|%(?:25)?3[Dd]|\\u003[Dd])"
193
+ _QUERY_VALUE = r"[^&#\"'\s\\<>,;)]*"
194
+ _EMBEDDED_TOKEN = re.compile(
195
+ r"(?:(?<![-_A-Za-z0-9])|(?<=%[0-9A-Fa-f]{2})|(?<=\\u00[0-9A-Fa-f]{2}))"
196
+ r"eyJ[-_A-Za-z0-9]{8,}\.eyJ[-_A-Za-z0-9]{8,}\.[-_A-Za-z0-9]+"
197
+ )
165
198
  _CARD_DIGITS = re.compile(r"^\d(?:[ -]?\d){12,18}$")
166
199
 
167
200
 
@@ -194,6 +227,11 @@ def _card_digits(text: str) -> bool:
194
227
  return bool(_CARD_DIGITS.match(text)) and _luhn(re.sub(r"[ -]", "", text))
195
228
 
196
229
 
230
+ def _secret_segment(segment: str, secret: str | None) -> bool:
231
+ decoded = urllib.parse.unquote(segment)
232
+ return _shaped_like_a_secret(decoded) or (bool(secret) and secret in decoded)
233
+
234
+
197
235
  def _shaped_like_a_secret(value: Any) -> bool:
198
236
  if not isinstance(value, str):
199
237
  return False
@@ -269,7 +307,10 @@ class RequestBudget:
269
307
  keys and key parts, and :data:`MAX_LOGGED_CHARS` characters of text, its
270
308
  keys included, an integer counted by its bytes. Each is charged before it is read, so a request past it costs
271
309
  no more than the budget; what it spent is what the logged entry holds, which
272
- the call log charges to its own, per-session budget."""
310
+ the call log charges to its own, per-session budget. It refuses rather than
311
+ fills, so it is never :attr:`full`."""
312
+
313
+ full = False
273
314
 
274
315
  def __init__(self) -> None:
275
316
  self.values = MAX_LOGGED_VALUES
@@ -284,6 +325,43 @@ class RequestBudget:
284
325
  if self.values < 0 or self.chars < 0:
285
326
  raise RequestTooLarge
286
327
 
328
+ def text(self, value: str) -> str:
329
+ return value
330
+
331
+
332
+ class PrefixBudget(RequestBudget):
333
+ """A walk that keeps a value's leading part in the order JSON writes it: it
334
+ never refuses, and once ``size`` values or characters are spent it is
335
+ :attr:`full`, so the walk adds nothing more and records in :attr:`cut` that
336
+ something was left. What it walked writes at least ``size`` characters of
337
+ JSON, so the first ``size`` bytes of the part it kept are the first ``size``
338
+ bytes of the whole."""
339
+
340
+ def __init__(self, size: int) -> None:
341
+ self.size = size
342
+ self.values = size
343
+ self.chars = size
344
+ self.cut = False
345
+
346
+ @property
347
+ def full(self) -> bool:
348
+ return self.values <= 0 or self.chars <= 0
349
+
350
+ def spent(self) -> tuple[int, int]:
351
+ return self.size - self.values, self.size - self.chars
352
+
353
+ def spend(self, values: int, chars: int) -> None:
354
+ self.values -= values
355
+ self.chars -= chars
356
+
357
+ def text(self, value: str) -> str:
358
+ """``value`` to its first ``size`` characters and :data:`SCRUB_MARGIN` more: no
359
+ more of one string can be kept, and the margin holds whole any secret the
360
+ kept part ends inside, so a scrub finds it."""
361
+ kept = value[: self.size + SCRUB_MARGIN]
362
+ self.cut = self.cut or len(kept) < len(value)
363
+ return kept
364
+
287
365
 
288
366
  def _size(value: Any) -> int:
289
367
  """What a scalar holds beyond one value: a string's characters, an integer's bytes."""
@@ -294,42 +372,146 @@ def _size(value: Any) -> int:
294
372
  return 0
295
373
 
296
374
 
297
- def _kept(value: Any, name: FieldName, budget: RequestBudget) -> Any:
375
+ def _kept(value: Any, name: FieldName, budget: RequestBudget, scrub: Callable[[str], str]) -> Any:
298
376
  budget.spend(1, _size(value))
299
377
  if isinstance(value, dict):
300
- return {carried_scalar(key): _kept(item, name.child(key), budget) for key, item in _keys(value, budget)}
378
+ return {carried_scalar(key): _kept(item, name.child(key), budget, scrub) for key, item in _keys(value, budget)}
301
379
  if isinstance(value, list):
302
380
  item_name = name.child("*")
303
- return [_kept(item, item_name, budget) for item in value]
381
+ return [_kept(item, item_name, budget, scrub) for item in _items(value, budget)]
304
382
  if _scalar(value) and name.redacts(value):
305
383
  return REDACTED
306
- return carried_scalar(value)
384
+ return carried_scalar(scrub(budget.text(value)) if isinstance(value, str) else value)
385
+
386
+
387
+ def _spellings(secret: str | None) -> list[str]:
388
+ """``secret`` as it may sit in a body: as sent, and percent-encoded the two ways a URL
389
+ carries it, and the capability label an open session's hostname derives from it; longest
390
+ first, so one spelling never leaves part of another. A secret shorter than
391
+ :data:`MIN_SCRUBBED_SECRET` (a local pin such as ``conform``; a World Host token has 32
392
+ characters) is ordinary text and has none."""
393
+ if not secret or len(secret) < MIN_SCRUBBED_SECRET:
394
+ return []
395
+ forms = {secret, urllib.parse.quote(secret, safe=""), urllib.parse.quote_plus(secret), open_label(secret)}
396
+ return sorted(forms, key=len, reverse=True)
307
397
 
308
398
 
309
399
  def _keys(value: dict, budget: RequestBudget) -> Iterator[tuple[str, Any]]:
310
- for key, item in value.items():
400
+ for key, item in _items(value.items(), budget):
311
401
  text = str(key)
312
402
  budget.spend(text.count(".") + 1, len(text))
313
403
  yield text, item
314
404
 
315
405
 
316
- class CallRedaction:
317
- """The call log's redaction (module docstring), for one world: ``credential_param``
318
- is a query-auth world's credential parameter, dropped from every logged query."""
406
+ def _items(items: Iterable[Any], budget: RequestBudget) -> Iterator[Any]:
407
+ for item in items:
408
+ if budget.full:
409
+ budget.cut = True
410
+ return
411
+ yield item
412
+
319
413
 
320
- def __init__(self, credential_param: str | None = None):
321
- self.credential_param = credential_param
414
+ class CallRedaction:
415
+ """The call log's redaction (module docstring), for one session of one world:
416
+ ``credential_params`` are the query parameters its ``[auth]`` carries a secret in
417
+ (a query-auth world's key, a signed link's signature), dropped from every logged
418
+ query; ``credential_header`` the header its scheme carries a key or a minted token
419
+ in, whatever it is named, kept as :data:`REDACTED` wherever headers are kept;
420
+ ``secret`` the session's credential, which no string kept holds."""
421
+
422
+ def __init__(
423
+ self,
424
+ credential_params: frozenset[str] = frozenset(),
425
+ credential_header: str | None = None,
426
+ secret: str | None = None,
427
+ ):
428
+ self.credential_params = credential_params
429
+ self.credential_header = (credential_header or "").lower()
430
+ self.secret = secret
431
+ self._spellings = _spellings(secret)
432
+ self._names = tuple(sorted(credential_params))
433
+ alternatives = "|".join(re.escape(name) for name in self._names)
434
+ lead = f"({_QUERY_LEAD}(?:{alternatives}){_QUERY_EQUALS}){_QUERY_VALUE}"
435
+ self._carried = re.compile(lead) if alternatives else None
322
436
 
323
437
  @classmethod
324
- def of(cls, spec: Spec) -> CallRedaction:
325
- return cls(spec.auth_name if spec.scheme == "query" else None)
438
+ def of(cls, spec: Spec | None, secret: str | None = None) -> CallRedaction:
439
+ if spec is None:
440
+ return cls(secret=secret)
441
+ return cls(spec.auth.secret_params, spec.auth.scheme.secret_header, secret)
442
+
443
+ def value(self, value: Any, budget: RequestBudget | None = None) -> Any:
444
+ return _kept(value, ROOT, budget or RequestBudget(), self.scrub)
445
+
446
+ def prefix(self, value: Any, size: int) -> tuple[Any, bool]:
447
+ """``value`` redacted as far as its first ``size`` values or characters
448
+ (:class:`PrefixBudget`), and whether any of it was left out."""
449
+ budget = PrefixBudget(size)
450
+ return _kept(value, ROOT, budget, self.scrub), budget.cut
451
+
452
+ def headers(self, headers: dict[str, str], secret: str | None, size: int) -> dict[str, str]:
453
+ """A request's headers as the request ledger keeps them, the first ``size``
454
+ characters of them, every name kept to its first :data:`HEADER_NAME_CHARS`. A
455
+ value is kept only under a name that says what it is (:data:`KEPT_HEADERS`,
456
+ :data:`KEPT_HEADER_PREFIXES`) and then still redacted by its shape; every other
457
+ value, however a vendor names its key, the world's own credential header and any
458
+ value carrying ``secret`` (the session's token) read :data:`REDACTED`."""
459
+ kept, _ = self.prefix(dict(headers), size)
460
+ return {
461
+ name[:HEADER_NAME_CHARS]: self._header(name, headers.get(name, ""), value, secret)
462
+ for name, value in kept.items()
463
+ }
464
+
465
+ def _header(self, name: str, sent: str, kept: Any, secret: str | None) -> Any:
466
+ lowered = name.lower()
467
+ described = lowered in KEPT_HEADERS or lowered.startswith(KEPT_HEADER_PREFIXES)
468
+ carried = bool(secret) and secret in sent
469
+ return kept if described and lowered != self.credential_header and not carried else REDACTED
470
+
471
+ def scrub(self, text: str) -> str:
472
+ """``text`` with every secret it embeds read :data:`REDACTED` in place: the
473
+ session's credential as sent and percent-encoded, an open session's capability
474
+ label (its hostname as a request or a link names it), the value of each query
475
+ parameter the world's ``[auth]`` carries a secret in (in a link a world echoes
476
+ or an agent passes on) and a JSON Web Token. Each is found in time linear in
477
+ ``text``."""
478
+ for spelling in self._spellings:
479
+ text = text.replace(spelling, REDACTED)
480
+ if self._carried is not None and any(name in text for name in self._names):
481
+ text = self._carried.sub(rf"\1{REDACTED}", text)
482
+ return _EMBEDDED_TOKEN.sub(REDACTED, text) if "eyJ" in text else text
326
483
 
327
484
  @staticmethod
328
- def value(value: Any, budget: RequestBudget | None = None) -> Any:
329
- return _kept(value, ROOT, budget or RequestBudget())
485
+ def path_without_secret(path: str, secret: str | None) -> str:
486
+ """``path`` with each segment carrying ``secret`` (the session's token) read :data:`REDACTED`."""
487
+ if not secret:
488
+ return path
489
+ return "/".join(REDACTED if secret in urllib.parse.unquote(part) else part for part in path.split("/"))
490
+
491
+ @staticmethod
492
+ def without_secret(value: Any, secret: str | None) -> Any:
493
+ """``value`` with every string carrying ``secret`` (the session's token), at any
494
+ depth, read :data:`REDACTED`."""
495
+ if not secret:
496
+ return value
497
+ if isinstance(value, str):
498
+ return REDACTED if secret in value else value
499
+ if isinstance(value, dict):
500
+ return {key: CallRedaction.without_secret(item, secret) for key, item in value.items()}
501
+ if isinstance(value, list):
502
+ return [CallRedaction.without_secret(item, secret) for item in value]
503
+ return value
504
+
505
+ def raw_path(self, path: str, secret: str | None) -> str:
506
+ """A path no route matched, so no argument is named: each segment shaped like a
507
+ secret, or carrying ``secret`` (the session's token), reads :data:`REDACTED`,
508
+ and every other one is scrubbed (:meth:`scrub`)."""
509
+ return "/".join(
510
+ REDACTED if _secret_segment(segment, secret) else self.scrub(segment) for segment in path.split("/")
511
+ )
330
512
 
331
513
  def query(self, query_all: dict, budget: RequestBudget | None = None) -> dict:
332
- kept = {k: (v[0] if len(v) == 1 else list(v)) for k, v in query_all.items() if k != self.credential_param}
514
+ kept = {k: (v[0] if len(v) == 1 else list(v)) for k, v in query_all.items() if k not in self.credential_params}
333
515
  return self.value(kept, budget)
334
516
 
335
517
  def path(self, operation: Operation, path: str, args: dict) -> str:
@@ -4,11 +4,11 @@ The TypeScript twin is ``worldData/cast.ts``; ``tests/conformance/csv_cast.json`
4
4
  them to the same answers. ``integer`` and ``number`` parse as numbers (a number is
5
5
  always a float), ``boolean`` takes true/false/1/0 in any case, ``array`` and
6
6
  ``object`` parse as JSON of that shape, ``string`` is the text as given. An empty
7
- cell is ``None`` when the field's type admits null, left out when the field is
8
- optional, the empty string for a required string, and refused for any other
9
- required field. A union type (``integer | string``) tries each member in order,
10
- ``string`` last. A cell that fits none is refused, naming the field and the cell;
11
- a column the schema does not name stays text (the gate refuses it, as it always did).
7
+ cell is ``None`` when the field's type admits null, the empty string for a required
8
+ string, and left out otherwise. A union type (``integer | string``) tries each member
9
+ in order, ``string`` last. A cell that fits none stays its text, as does a column the
10
+ schema does not name: the contract's check then refuses the row, naming its entity,
11
+ key and field, as it refuses a JSON row, so a file reports every bad row at once.
12
12
 
13
13
  Standard library only, so the bridge and the api bundle can load it.
14
14
  """
@@ -23,8 +23,6 @@ from dataclasses import dataclass
23
23
  from pathlib import Path
24
24
  from typing import Any
25
25
 
26
- from .validation import fail
27
-
28
26
  INTEGER_TEXT = re.compile(r"^[+-]?\d+$")
29
27
  NUMBER_TEXT = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
30
28
  BOOLEANS = {"true": True, "false": False, "1": True, "0": False}
@@ -51,21 +49,6 @@ class FieldType:
51
49
  return described
52
50
 
53
51
 
54
- def _article(kind: str) -> str:
55
- return "an" if kind[:1].lower() in "aeiou" else "a"
56
-
57
-
58
- def refuse(where: str, field: str, cell: str | None, kind: str) -> None:
59
- """The row-level refusal a cell that will not cast earns (same words as the TypeScript twin)."""
60
- if cell is None:
61
- fail("rows", f"{where}: {field} is empty; the field is a required {kind}", where)
62
- fail(
63
- "rows",
64
- f"{where}: {field} = {json.dumps(cell)} is not {_article(kind)} {kind}",
65
- where,
66
- )
67
-
68
-
69
52
  def type_members(kind: str | None) -> list[str]:
70
53
  """The typed members of a field's ``type`` (``"integer | null"`` -> integer, null); an
71
54
  unknown word (a ``$ref`` name) is dropped."""
@@ -123,10 +106,11 @@ class FieldCaster:
123
106
  self.required = required
124
107
  self.members = type_members(kind)
125
108
 
126
- def cast(self, cell: str | None, where: str) -> Any:
127
- """The typed value; :data:`OMIT` to leave the field out of the row."""
109
+ def cast(self, cell: str | None) -> Any:
110
+ """The typed value; :data:`OMIT` to leave the field out of the row; the cell as given when
111
+ it fits no member, for the contract's check to refuse."""
128
112
  if cell is None:
129
- return self._empty(where)
113
+ return self._empty()
130
114
  if not self.members:
131
115
  return cell
132
116
  text = cell.strip()
@@ -134,18 +118,14 @@ class FieldCaster:
134
118
  value = _CAST.get(member, _no_cast)(text)
135
119
  if value is not _MISSING:
136
120
  return value
137
- if "string" in self.members:
138
- return cell
139
- refuse(where, self.name, cell, self.type or "value")
121
+ return cell
140
122
 
141
- def _empty(self, where: str) -> Any:
123
+ def _empty(self) -> Any:
142
124
  if not self.members or "null" in self.members:
143
125
  return None
144
- if not self.required:
145
- return OMIT
146
- if "string" in self.members:
126
+ if self.required and "string" in self.members:
147
127
  return ""
148
- refuse(where, self.name, None, self.type or "value")
128
+ return OMIT
149
129
 
150
130
 
151
131
  #: What :meth:`FieldCaster.cast` answers for an empty optional cell: the field stays out of the row.
@@ -158,11 +138,11 @@ class RowCaster:
158
138
  def __init__(self, fields: Iterable[FieldType]):
159
139
  self._fields = {f.name: FieldCaster(f.name, f.type, f.required) for f in fields}
160
140
 
161
- def row(self, record: dict[str, str | None], where: str) -> dict:
141
+ def row(self, record: dict[str, str | None]) -> dict:
162
142
  row: dict = {}
163
143
  for name, cell in record.items():
164
144
  caster = self._fields.get(name)
165
- value = cell if caster is None else caster.cast(cell, where)
145
+ value = cell if caster is None else caster.cast(cell)
166
146
  if value is not OMIT:
167
147
  row[name] = value
168
148
  return row
@@ -26,7 +26,6 @@ body the document's example does not supply.
26
26
 
27
27
  from __future__ import annotations
28
28
 
29
- import base64
30
29
  import json
31
30
  import threading
32
31
  import urllib.error
@@ -34,11 +33,12 @@ import urllib.parse
34
33
  import urllib.request
35
34
  from dataclasses import dataclass, field
36
35
  from pathlib import Path
37
- from typing import Any
36
+ from typing import Any, Literal
38
37
 
39
38
  from .._toml import tomllib
40
39
  from .api import WorldState, load_api_settings, serve
41
40
  from .connector import SPEC, Operation, load_spec
41
+ from .door import Door
42
42
  from .validation import fail
43
43
 
44
44
  PIN = "conform"
@@ -306,7 +306,7 @@ class Outcome:
306
306
  documented: bool
307
307
  status: int | None = None
308
308
  expected: list[str] = field(default_factory=list)
309
- schema: str = "unchecked" # ok | violations | no-schema | unchecked
309
+ schema: Literal["ok", "violations", "no-schema", "unchecked"] = "unchecked"
310
310
  problems: list[str] = field(default_factory=list)
311
311
  request: dict = field(default_factory=dict)
312
312
 
@@ -341,27 +341,6 @@ class Report:
341
341
  return {"world": self.world, "summary": self.summary, "operations": [o.__dict__ for o in self.outcomes]}
342
342
 
343
343
 
344
- def _credentials(base: str, spec, settings) -> dict[str, str]:
345
- """Headers that get the conformance run through the world's own auth, using the pin."""
346
- if spec.scheme == "none":
347
- return {}
348
- if spec.scheme == "header":
349
- return {spec.auth_name or "": PIN}
350
- if spec.scheme == "bearer":
351
- return {"Authorization": f"Bearer {PIN}"}
352
- if spec.scheme == "basic":
353
- return {"Authorization": "Basic " + base64.b64encode(PIN.encode()).decode()}
354
- if spec.scheme == "query":
355
- return {}
356
- form = urllib.parse.urlencode(
357
- {"grant_type": "client_credentials", "client_id": "conform", "client_secret": PIN}
358
- ).encode()
359
- prefix = urllib.parse.urlsplit(spec.base_url).path.rstrip("/")
360
- request = urllib.request.Request(base + prefix + (settings.token_path or "/oauth/token"), data=form, method="POST")
361
- with urllib.request.urlopen(request, timeout=10) as reply:
362
- return {"Authorization": "Bearer " + json.loads(reply.read())["access_token"]}
363
-
364
-
365
344
  def request_samples(world: str | Path) -> dict[str, tuple[dict[str, str], Any]]:
366
345
  """Per operation, the ``[operations.api] sample_headers`` (header -> value) and
367
346
  ``sample_body`` (a table or array, sent as JSON) declared in ``connector.toml``.
@@ -468,7 +447,7 @@ def conform(world: str | Path, openapi: list[str | Path], *, max_operations: int
468
447
  state: WorldState = server.world_state # type: ignore[attr-defined]
469
448
  outcomes: list[Outcome] = []
470
449
  try:
471
- headers = _credentials(base, spec, settings)
450
+ door = Door.of(spec, settings, PIN)
472
451
  for operation in list(spec.operations.values())[:max_operations]:
473
452
  located = None
474
453
  checker = None
@@ -485,8 +464,8 @@ def conform(world: str | Path, openapi: list[str | Path], *, max_operations: int
485
464
  responses = documented.get("responses") or {}
486
465
  outcome.expected = [code for code in responses if code.startswith("2")] or ["200"]
487
466
  args, params = _sample_args(operation, spec, settings, state, checker, documented)
488
- if spec.scheme == "query":
489
- params[spec.auth_name or ""] = PIN
467
+ headers, credential_query = door.present()
468
+ params.update(credential_query)
490
469
  path = operation.path
491
470
  for name, value in args.items():
492
471
  path = path.replace("{" + name + "}", urllib.parse.quote(value, safe=""))