@voxgig/sdkgen 4.50.0 → 4.51.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 (180) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/package.json +1 -1
  3. package/project/.sdk/model/feature/cache.aontu +6 -4
  4. package/project/.sdk/model/target/lua.aontu +6 -0
  5. package/project/.sdk/src/cmp/c/Config_c.ts +3 -134
  6. package/project/.sdk/src/cmp/c/TestClean_c.ts +14 -0
  7. package/project/.sdk/src/cmp/clojure/TestClean_clojure.ts +10 -5
  8. package/project/.sdk/src/cmp/cpp/TestClean_cpp.ts +13 -0
  9. package/project/.sdk/src/cmp/csharp/TestClean_csharp.ts +9 -0
  10. package/project/.sdk/src/cmp/elixir/TestClean_elixir.ts +11 -3
  11. package/project/.sdk/src/cmp/go/TestClean_go.ts +39 -3
  12. package/project/.sdk/src/cmp/java/TestClean_java.ts +8 -0
  13. package/project/.sdk/src/cmp/js/TestClean_js.ts +13 -5
  14. package/project/.sdk/src/cmp/kotlin/TestClean_kotlin.ts +22 -0
  15. package/project/.sdk/src/cmp/lua/TestClean_lua.ts +12 -3
  16. package/project/.sdk/src/cmp/ocaml/TestClean_ocaml.ts +18 -4
  17. package/project/.sdk/src/cmp/perl/TestClean_perl.ts +12 -3
  18. package/project/.sdk/src/cmp/php/TestClean_php.ts +10 -3
  19. package/project/.sdk/src/cmp/py/TestClean_py.ts +10 -3
  20. package/project/.sdk/src/cmp/rb/TestClean_rb.ts +10 -3
  21. package/project/.sdk/src/cmp/rust/TestClean_rust.ts +10 -0
  22. package/project/.sdk/src/cmp/scala/TestClean_scala.ts +34 -0
  23. package/project/.sdk/src/cmp/swift/TestClean_swift.ts +20 -10
  24. package/project/.sdk/src/cmp/ts/TestClean_ts.ts +13 -5
  25. package/project/.sdk/src/cmp/zig/TestClean_zig.ts +12 -0
  26. package/project/.sdk/tm/c/core/context.c +1 -0
  27. package/project/.sdk/tm/c/core/sdk.h +7 -4
  28. package/project/.sdk/tm/c/feature/cache.c +243 -13
  29. package/project/.sdk/tm/c/feature/secrets.c +27 -38
  30. package/project/.sdk/tm/c/tests/feature_test.c +104 -0
  31. package/project/.sdk/tm/c/utility/clean.c +26 -33
  32. package/project/.sdk/tm/c/utility/make_options.c +9 -8
  33. package/project/.sdk/tm/clojure/feature/secrets/sdk/feature/secrets.clj +14 -11
  34. package/project/.sdk/tm/clojure/src/sdk/client.clj +3 -1
  35. package/project/.sdk/tm/clojure/src/sdk/core.clj +19 -11
  36. package/project/.sdk/tm/clojure/src/sdk/features.clj +81 -10
  37. package/project/.sdk/tm/clojure/test/sdk/test/feature.clj +33 -0
  38. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +1 -0
  39. package/project/.sdk/tm/cpp/Makefile +5 -0
  40. package/project/.sdk/tm/cpp/core/types.hpp +11 -4
  41. package/project/.sdk/tm/cpp/feature/audit.hpp +6 -7
  42. package/project/.sdk/tm/cpp/feature/cache.hpp +188 -9
  43. package/project/.sdk/tm/cpp/feature/secrets.hpp +12 -0
  44. package/project/.sdk/tm/cpp/test/feature_test.cpp +99 -0
  45. package/project/.sdk/tm/cpp/utility/pipeline.hpp +9 -7
  46. package/project/.sdk/tm/csharp/core/Context.cs +4 -0
  47. package/project/.sdk/tm/csharp/feature/CacheFeature.cs +126 -12
  48. package/project/.sdk/tm/csharp/feature/SecretsFeature.cs +9 -27
  49. package/project/.sdk/tm/csharp/test/FeatureTest.cs +76 -0
  50. package/project/.sdk/tm/csharp/utility/Clean.cs +5 -10
  51. package/project/.sdk/tm/csharp/utility/Fetcher.cs +7 -1
  52. package/project/.sdk/tm/csharp/utility/MakeOptions.cs +5 -12
  53. package/project/.sdk/tm/elixir/lib/projectname/context.ex +2 -0
  54. package/project/.sdk/tm/elixir/lib/projectname/feature/cache.ex +146 -30
  55. package/project/.sdk/tm/elixir/lib/projectname/feature/secrets.ex +10 -56
  56. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +18 -12
  57. package/project/.sdk/tm/elixir/test/feature_test.exs +61 -0
  58. package/project/.sdk/tm/go/core/context.go +6 -0
  59. package/project/.sdk/tm/go/feature/cache_feature.go +131 -4
  60. package/project/.sdk/tm/go/feature/secrets_feature.go +17 -71
  61. package/project/.sdk/tm/go/test/feature_corpus_test.go +150 -2
  62. package/project/.sdk/tm/go/test/feature_test.go +61 -0
  63. package/project/.sdk/tm/go/utility/clean.go +5 -7
  64. package/project/.sdk/tm/go/utility/fetcher.go +11 -0
  65. package/project/.sdk/tm/go/utility/make_options.go +5 -7
  66. package/project/.sdk/tm/java/core/Context.java +9 -0
  67. package/project/.sdk/tm/java/feature/CacheFeature.java +123 -17
  68. package/project/.sdk/tm/java/feature/SecretsFeature.java +9 -92
  69. package/project/.sdk/tm/java/test/FeatureCorpusTest.java +141 -2
  70. package/project/.sdk/tm/java/test/FeatureTest.java +60 -0
  71. package/project/.sdk/tm/java/utility/Clean.java +6 -10
  72. package/project/.sdk/tm/java/utility/Fetcher.java +5 -1
  73. package/project/.sdk/tm/java/utility/MakeOptions.java +3 -1
  74. package/project/.sdk/tm/js/src/Context.js +4 -0
  75. package/project/.sdk/tm/js/src/feature/cache/CacheFeature.js +118 -11
  76. package/project/.sdk/tm/js/src/feature/cost/CostFeature.js +3 -2
  77. package/project/.sdk/tm/js/src/feature/metrics/MetricsFeature.js +1 -1
  78. package/project/.sdk/tm/js/src/feature/paging/PagingFeature.js +4 -4
  79. package/project/.sdk/tm/js/src/feature/rbac/RbacFeature.js +4 -4
  80. package/project/.sdk/tm/js/src/feature/secrets/SecretsFeature.js +16 -6
  81. package/project/.sdk/tm/js/src/feature/validate/ValidateFeature.js +2 -1
  82. package/project/.sdk/tm/js/src/utility/CleanUtility.js +1 -1
  83. package/project/.sdk/tm/js/src/utility/MakeOptionsUtility.js +6 -6
  84. package/project/.sdk/tm/js/test/feature/Corpus.test.js +100 -2
  85. package/project/.sdk/tm/js/test/feature/harness.js +3 -3
  86. package/project/.sdk/tm/js/test/pipeline.test.js +1 -1
  87. package/project/.sdk/tm/kotlin/core/Context.kt +3 -0
  88. package/project/.sdk/tm/kotlin/feature/CacheFeature.kt +102 -7
  89. package/project/.sdk/tm/kotlin/feature/SecretsFeature.kt +10 -20
  90. package/project/.sdk/tm/kotlin/test/FeatureTest.kt +59 -0
  91. package/project/.sdk/tm/kotlin/utility/CoreUtil.kt +5 -5
  92. package/project/.sdk/tm/kotlin/utility/Fetcher.kt +4 -0
  93. package/project/.sdk/tm/kotlin/utility/MakeOptions.kt +3 -1
  94. package/project/.sdk/tm/lua/core/context.lua +6 -0
  95. package/project/.sdk/tm/lua/feature/cache_feature.lua +212 -15
  96. package/project/.sdk/tm/lua/feature/secrets_feature.lua +15 -80
  97. package/project/.sdk/tm/lua/test/feature_test.lua +81 -0
  98. package/project/.sdk/tm/lua/utility/clean.lua +6 -9
  99. package/project/.sdk/tm/lua/utility/fetcher.lua +9 -0
  100. package/project/.sdk/tm/lua/utility/make_options.lua +5 -5
  101. package/project/.sdk/tm/ocaml/feature/secrets_feature.ml +21 -6
  102. package/project/.sdk/tm/ocaml/sdk_features.ml +106 -8
  103. package/project/.sdk/tm/ocaml/sdk_runtime.ml +13 -10
  104. package/project/.sdk/tm/ocaml/sdk_types.ml +2 -0
  105. package/project/.sdk/tm/ocaml/test/t_feature.ml +35 -1
  106. package/project/.sdk/tm/perl/core/context.pm +3 -0
  107. package/project/.sdk/tm/perl/feature/audit_feature.pm +4 -7
  108. package/project/.sdk/tm/perl/feature/cache_feature.pm +111 -15
  109. package/project/.sdk/tm/perl/feature/secrets_feature.pm +13 -18
  110. package/project/.sdk/tm/perl/t/feature.t +66 -0
  111. package/project/.sdk/tm/perl/t/feature_corpus.t +80 -4
  112. package/project/.sdk/tm/perl/utility/clean.pm +6 -8
  113. package/project/.sdk/tm/perl/utility/fetcher.pm +4 -0
  114. package/project/.sdk/tm/perl/utility/make_options.pm +5 -5
  115. package/project/.sdk/tm/php/core/Context.php +4 -0
  116. package/project/.sdk/tm/php/feature/CacheFeature.php +98 -13
  117. package/project/.sdk/tm/php/feature/SecretsFeature.php +18 -15
  118. package/project/.sdk/tm/php/test/FeatureCorpusTest.php +113 -3
  119. package/project/.sdk/tm/php/test/FeatureTest.php +68 -0
  120. package/project/.sdk/tm/php/utility/Clean.php +3 -10
  121. package/project/.sdk/tm/php/utility/Fetcher.php +8 -3
  122. package/project/.sdk/tm/php/utility/MakeOptions.php +5 -7
  123. package/project/.sdk/tm/py/pkg/core/context.py +4 -0
  124. package/project/.sdk/tm/py/pkg/feature/cache_feature.py +79 -13
  125. package/project/.sdk/tm/py/pkg/feature/secrets_feature.py +15 -66
  126. package/project/.sdk/tm/py/pkg/utility/clean.py +4 -10
  127. package/project/.sdk/tm/py/pkg/utility/make_options.py +8 -9
  128. package/project/.sdk/tm/py/test/feature/secrets/test_secrets.py +23 -9
  129. package/project/.sdk/tm/py/test/test_feature.py +50 -0
  130. package/project/.sdk/tm/py/test/test_feature_corpus.py +88 -3
  131. package/project/.sdk/tm/rb/core/context.rb +4 -1
  132. package/project/.sdk/tm/rb/feature/audit_feature.rb +6 -5
  133. package/project/.sdk/tm/rb/feature/cache_feature.rb +75 -11
  134. package/project/.sdk/tm/rb/feature/secrets_feature.rb +9 -64
  135. package/project/.sdk/tm/rb/test/feature_corpus_test.rb +85 -3
  136. package/project/.sdk/tm/rb/test/feature_test.rb +74 -0
  137. package/project/.sdk/tm/rb/utility/clean.rb +6 -7
  138. package/project/.sdk/tm/rb/utility/fetcher.rb +6 -0
  139. package/project/.sdk/tm/rb/utility/make_options.rb +5 -5
  140. package/project/.sdk/tm/rust/core/context.rs +8 -0
  141. package/project/.sdk/tm/rust/feature/cache.rs +120 -3
  142. package/project/.sdk/tm/rust/feature/secrets.rs +36 -98
  143. package/project/.sdk/tm/rust/tests/feature/secrets/main.rs +3 -3
  144. package/project/.sdk/tm/rust/tests/feature_test.rs +100 -0
  145. package/project/.sdk/tm/rust/utility/clean.rs +35 -43
  146. package/project/.sdk/tm/rust/utility/fetcher.rs +6 -0
  147. package/project/.sdk/tm/rust/utility/make_options.rs +8 -11
  148. package/project/.sdk/tm/scala/core/Context.scala +4 -0
  149. package/project/.sdk/tm/scala/feature/CacheFeature.scala +117 -11
  150. package/project/.sdk/tm/scala/feature/SecretsFeature.scala +11 -24
  151. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +28 -0
  152. package/project/.sdk/tm/scala/utility/Fetcher.scala +5 -0
  153. package/project/.sdk/tm/scala/utility/Make.scala +3 -1
  154. package/project/.sdk/tm/scala/utility/Misc.scala +5 -8
  155. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/core/Context.swift +3 -0
  156. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/CacheFeature.swift +122 -11
  157. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/SecretsFeature.swift +9 -13
  158. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +4 -0
  159. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/MakeOptions.swift +5 -4
  160. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/ResultUtil.swift +4 -5
  161. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/FeatureTest.swift +55 -0
  162. package/project/.sdk/tm/ts/src/Context.ts +4 -0
  163. package/project/.sdk/tm/ts/src/feature/cache/CacheFeature.ts +115 -4
  164. package/project/.sdk/tm/ts/src/feature/cost/CostFeature.ts +3 -2
  165. package/project/.sdk/tm/ts/src/feature/metrics/MetricsFeature.ts +1 -1
  166. package/project/.sdk/tm/ts/src/feature/paging/PagingFeature.ts +4 -4
  167. package/project/.sdk/tm/ts/src/feature/rbac/RbacFeature.ts +4 -4
  168. package/project/.sdk/tm/ts/src/feature/secrets/SecretsFeature.ts +14 -2
  169. package/project/.sdk/tm/ts/src/feature/validate/ValidateFeature.ts +2 -1
  170. package/project/.sdk/tm/ts/src/utility/CleanUtility.ts +1 -1
  171. package/project/.sdk/tm/ts/src/utility/MakeOptionsUtility.ts +6 -6
  172. package/project/.sdk/tm/ts/test/feature/Corpus.test.ts +101 -2
  173. package/project/.sdk/tm/ts/test/feature/harness.ts +3 -3
  174. package/project/.sdk/tm/ts/test/pipeline.test.ts +1 -1
  175. package/project/.sdk/tm/zig/core/context.zig +5 -0
  176. package/project/.sdk/tm/zig/core/utility.zig +11 -9
  177. package/project/.sdk/tm/zig/feature/cache.zig +144 -13
  178. package/project/.sdk/tm/zig/feature/secrets.zig +6 -1
  179. package/project/.sdk/tm/zig/test/feature_test.zig +65 -0
  180. package/project/sdkgen-package.json +1 -1
@@ -1,21 +1,23 @@
1
1
  # ProjectName SDK cache feature
2
2
 
3
3
  from __future__ import annotations
4
+ import hashlib
5
+ import hmac
6
+ import re
7
+ import secrets
4
8
  import time
5
9
 
6
10
  from projectname_sdk.feature.base_feature import ProjectNameBaseFeature
7
11
  from projectname_sdk.utility.media import header_value, is_json_media
8
12
 
9
13
 
10
- # Response caching for safe (read) requests. Wraps the active transport and
11
- # serves a fresh cached snapshot instead of hitting the network when the
12
- # same method+URL was fetched within `ttl` ms (default 5000). Only
13
- # successful (2xx) responses to cacheable methods (default: GET) are
14
- # stored, keyed by method+URL. The cache is bounded (`max` entries, default
15
- # 256, oldest evicted first) and every hit/miss is recorded on
16
- # `client._cache` for inspection. Response bodies are snapshotted on
17
- # capture so both the current caller and later hits can read the JSON body
18
- # repeatedly.
14
+ SAFE_METHODS = ("GET", "HEAD")
15
+ UNSTORED = ("no-store", "private", "no-cache")
16
+ MAX_AGE = re.compile(r'^max-age\s*=\s*"?(\d+)"?$')
17
+
18
+
19
+ # Response caching for safe (read) requests, per client: see the features
20
+ # reference for the key, the write invalidation and the Cache-Control rules.
19
21
  class ProjectNameCacheFeature(ProjectNameBaseFeature):
20
22
  def __init__(self):
21
23
  super().__init__()
@@ -25,6 +27,7 @@ class ProjectNameCacheFeature(ProjectNameBaseFeature):
25
27
  self.client = None
26
28
  self.options = {}
27
29
  self.store = {}
30
+ self.secret = b""
28
31
 
29
32
  def init(self, ctx, options):
30
33
  self.client = ctx.client
@@ -39,6 +42,7 @@ class ProjectNameCacheFeature(ProjectNameBaseFeature):
39
42
  return
40
43
 
41
44
  self.store = {}
45
+ self.secret = secrets.token_bytes(32)
42
46
 
43
47
  utility = ctx.utility
44
48
  inner = utility.fetcher
@@ -55,9 +59,15 @@ class ProjectNameCacheFeature(ProjectNameBaseFeature):
55
59
  methods = self.options.get("methods") or ["GET"]
56
60
 
57
61
  if method not in methods:
58
- return inner(ctx, url, fetchdef)
62
+ if method in SAFE_METHODS:
63
+ return inner(ctx, url, fetchdef)
64
+ try:
65
+ return inner(ctx, url, fetchdef)
66
+ finally:
67
+ self._invalidate(url)
59
68
 
60
- key = method + " " + url
69
+ headers = fetchdef.get("headers") if isinstance(fetchdef, dict) else None
70
+ key = method + " " + url + " " + self._digest(headers)
61
71
  now = self._now()
62
72
  hit = self.store.get(key)
63
73
 
@@ -69,15 +79,36 @@ class ProjectNameCacheFeature(ProjectNameBaseFeature):
69
79
 
70
80
  if err is None and self._cacheable(res):
71
81
  snapshot = self._snapshot(res)
72
- ttl = 5000 if self.options.get("ttl") is None else self.options.get("ttl")
82
+ ttl = cache_lifetime(snapshot["headers"],
83
+ 5000 if self.options.get("ttl") is None else self.options.get("ttl"))
84
+ if ttl <= 0:
85
+ self._track("bypass")
86
+ return self._replay(snapshot), None
87
+ self.store.pop(key, None)
73
88
  self._evict()
74
- self.store[key] = {"expiry": now + ttl, "snapshot": snapshot}
89
+ self.store[key] = {"expiry": now + ttl, "scope": url_scope(url), "snapshot": snapshot}
75
90
  self._track("miss")
76
91
  return self._replay(snapshot), None
77
92
 
78
93
  self._track("bypass")
79
94
  return res, err
80
95
 
96
+ def _digest(self, headers):
97
+ pairs = []
98
+ if isinstance(headers, dict):
99
+ for name, val in headers.items():
100
+ if val is not None:
101
+ pairs.append((str(name).lower(), val if isinstance(val, str) else str(val)))
102
+ text = "".join(name + ":" + val + "\n" for name, val in sorted(pairs))
103
+ return hmac.new(self.secret, text.encode("utf-8"), hashlib.sha256).hexdigest()
104
+
105
+ def _invalidate(self, url):
106
+ path = url_scope(url)
107
+ collection = url_parent(path)
108
+ for key in [k for k, e in self.store.items()
109
+ if scope_under(e["scope"], path) or e["scope"] == collection]:
110
+ del self.store[key]
111
+
81
112
  # A body the transport could not read as JSON passes through, for the operation to report.
82
113
  def _cacheable(self, res):
83
114
  if not isinstance(res, dict) or res.get("unreadable") is True:
@@ -143,3 +174,38 @@ class ProjectNameCacheFeature(ProjectNameBaseFeature):
143
174
  track = {"hit": 0, "miss": 0, "bypass": 0}
144
175
  client._cache = track
145
176
  track[kind] += 1
177
+
178
+
179
+ # The configured ttl capped by the response's Cache-Control; zero when the
180
+ # response may not be stored.
181
+ def cache_lifetime(headers, ttl):
182
+ control = ""
183
+ for name, val in (headers or {}).items():
184
+ if str(name).lower() == "cache-control":
185
+ control = str(val)
186
+ life = ttl
187
+ for part in control.lower().split(","):
188
+ directive = part.strip()
189
+ if directive in UNSTORED:
190
+ return 0
191
+ age = MAX_AGE.match(directive)
192
+ if age is not None:
193
+ life = min(life, int(age.group(1)) * 1000)
194
+ return life
195
+
196
+
197
+ def url_scope(url):
198
+ return re.split(r"[?#]", str(url), maxsplit=1)[0].rstrip("/")
199
+
200
+
201
+ def url_parent(scope):
202
+ scheme = scope.find("://")
203
+ root = 0 if scheme < 0 else scope.find("/", scheme + 3)
204
+ if root < 0:
205
+ return scope
206
+ cut = scope.rfind("/")
207
+ return scope[:max(cut, root)]
208
+
209
+
210
+ def scope_under(scope, prefix):
211
+ return scope == prefix or scope.startswith(prefix + "/")
@@ -3,13 +3,13 @@
3
3
  from __future__ import annotations
4
4
  import base64
5
5
  import json
6
- import urllib.error
7
6
  import urllib.parse
8
- import urllib.request
9
7
 
10
8
  from projectname_sdk.utility.voxgig_struct import voxgig_struct as vs
11
9
  from projectname_sdk.feature.base_feature import ProjectNameBaseFeature
12
10
  from projectname_sdk.feature.secrets.voxgig_sekreto import Sekreto, envkey
11
+ from projectname_sdk.utility.fetcher import fetcher_util
12
+ from projectname_sdk.core.error import ProjectNameError
13
13
  # The plugin DEFINITIONS the model selected for this feature, emitted by
14
14
  # config generically from the catalogue's active `plugin.def` entries.
15
15
  # Upstream sekreto's contract since the registry was retired: a kind not
@@ -335,21 +335,14 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
335
335
  base = str(options.get("base") or "").rstrip("/")
336
336
  url = base + "/" + str(x["path"]).lstrip("/")
337
337
 
338
- fetch = vs.getpath(options, "system.fetch")
339
-
340
- if not callable(fetch):
341
- # No custom transport supplied - the ordinary case.
342
- # make_options leaves system.fetch unset, so the exchange
343
- # gets its own raw HTTP path (stdlib urllib, mirroring the ts
344
- # reference whose system.fetch is initialized from the
345
- # platform fetcher). Local and minimal on purpose: see the
346
- # NOT-the-SDK-transport note below.
347
- fetch = _raw_exchange_fetch
348
-
349
- # Deliberately NOT the SDK transport. The transport is what this
350
- # feature wraps, and sending the token request back through it
351
- # would recurse on the first 401 - and would route the exchange
352
- # through the test mock, which knows nothing about it.
338
+ # The SDK's own transport, beneath every feature's wrapper: it holds
339
+ # the test feature's block and the GET-only guard, and the wrapped
340
+ # one would recurse on the first 401.
341
+ rootctx = getattr(self._client, "_rootctx", None)
342
+
343
+ def fetch(at, fd):
344
+ return fetcher_util(rootctx, at, fd)
345
+
353
346
  fetchdef = {
354
347
  "method": x["method"],
355
348
  "headers": {"content-type": "application/json"},
@@ -357,6 +350,9 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
357
350
  # Never followed by the client: a redirect would carry the
358
351
  # refresh token on.
359
352
  "redirect": "manual",
353
+ # Seconds; its own bound, as the timeout feature's wrapper is
354
+ # above this call.
355
+ "timeout": 30,
360
356
  }
361
357
 
362
358
  res, err = fetch(url, fetchdef)
@@ -373,6 +369,8 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
373
369
  res, err = fetch(at, fetchdef)
374
370
  hops += 1
375
371
 
372
+ if isinstance(err, ProjectNameError):
373
+ raise err
376
374
  if err is not None:
377
375
  raise Exception(
378
376
  "secrets: token exchange failed: " + str(err) + " from " + url)
@@ -527,52 +525,3 @@ def _moved(url, at, res):
527
525
  except ValueError:
528
526
  return None
529
527
  return nxt if same else None
530
-
531
-
532
- class _NoRedirect(urllib.request.HTTPRedirectHandler):
533
- def redirect_request(self, req, fp, code, msg, headers, newurl):
534
- return None
535
-
536
-
537
- # A 3xx then surfaces as HTTPError, the exchange's own failed answer.
538
- _NO_REDIRECT = urllib.request.build_opener(_NoRedirect)
539
-
540
-
541
- def _raw_exchange_fetch(fullurl, fetchdef):
542
- """Token-exchange transport of last resort: stdlib urllib, answering
543
- the same (res, err) shape the system.fetch seam promises. Exists so an
544
- exchange works with ordinary SDK options - requiring a custom
545
- transport for the COMMON case would reject every live token purchase
546
- before a request was made."""
547
- try:
548
- body = fetchdef.get("body")
549
- data = body.encode("utf-8") if isinstance(body, str) and body else None
550
- req = urllib.request.Request(
551
- fullurl,
552
- data=data,
553
- method=str(fetchdef.get("method") or "POST"),
554
- )
555
- for k, v in (fetchdef.get("headers") or {}).items():
556
- if isinstance(v, str):
557
- req.add_header(k, v)
558
- with _NO_REDIRECT.open(req, timeout=30) as res:
559
- raw = res.read()
560
- status = res.status
561
- headers = {k.lower(): v for k, v in res.headers.items()}
562
-
563
- def _json():
564
- try:
565
- return json.loads(raw.decode("utf-8"))
566
- except Exception:
567
- return None
568
-
569
- return {"status": status, "headers": headers, "json": _json}, None
570
- except urllib.error.HTTPError as e:
571
- # A non-2xx answer IS a response: hand back its status so the
572
- # caller reports "token exchange failed: <status>" rather than a
573
- # transport error.
574
- headers = {k.lower(): v for k, v in (e.headers or {}).items()}
575
- return {"status": e.code, "headers": headers,
576
- "json": lambda: None}, None
577
- except Exception as e:
578
- return None, e
@@ -68,17 +68,11 @@ def _prop(obj, name):
68
68
  return getattr(obj, name, None)
69
69
 
70
70
 
71
- def _options_of(ctx):
72
- return _prop(ctx, "options")
73
-
74
-
75
- # The derived block make_options builds; a context without options
76
- # (make_error is reached with a bare one) falls back to the schema defaults,
77
- # so nothing leaves raw for want of a constructor.
71
+ # The registry make_options builds; a context without one (make_error is
72
+ # reached with a bare one) falls back to the schema defaults, so nothing
73
+ # leaves raw for want of a constructor.
78
74
  def _clean_config(ctx):
79
- options = _options_of(ctx)
80
- derived = options.get("__derived__") if isinstance(options, dict) else None
81
- cfg = derived.get("clean") if isinstance(derived, dict) else None
75
+ cfg = _prop(ctx, "cleancfg")
82
76
  if isinstance(cfg, dict) and isinstance(cfg.get("values"), list):
83
77
  return cfg
84
78
  return make_clean_config(OPTSPEC.get("clean"))
@@ -7,11 +7,11 @@ from projectname_sdk.utility.clean import (
7
7
  clean_util, clean_add_util, clean_add_sensitive, make_clean_config, split_values)
8
8
 
9
9
 
10
- # A context carrying only the derived clean block, for the registry that
11
- # exists before the real options do.
10
+ # A context carrying only the clean registry, which exists before the real
11
+ # options do.
12
12
  class _CleanCtx:
13
13
  def __init__(self, cleancfg):
14
- self.options = {"__derived__": {"clean": cleancfg}}
14
+ self.cleancfg = cleancfg
15
15
 
16
16
 
17
17
 
@@ -232,12 +232,11 @@ def make_options_util(ctx):
232
232
  at = featureorder.index("test") + 1 if "test" in featureorder else 0
233
233
  featureorder.insert(at, "station")
234
234
 
235
- # The clean block stays MUTABLE: features register what they resolve
236
- # after construction.
237
- opts["__derived__"] = {
238
- "clean": cleancfg,
239
- "featureorder": featureorder,
240
- }
235
+ opts["__derived__"] = {"featureorder": featureorder}
236
+
237
+ # The registry stays MUTABLE, as features register what they resolve after
238
+ # construction, and sits beside the options: callers read those back.
239
+ ctx.cleancfg = cleancfg
241
240
 
242
241
  # Again over the merged result: the config's own defaults can carry one.
243
242
  _clean_add_options(cleanctx, {
@@ -33,6 +33,12 @@ import unittest
33
33
 
34
34
  import pytest
35
35
 
36
+ try:
37
+ import requests # noqa: F401
38
+ HAVE_REQUESTS = True
39
+ except ImportError:
40
+ HAVE_REQUESTS = False
41
+
36
42
  from projectname_sdk import ProjectNameSDK
37
43
  from projectname_sdk.config import shared_config
38
44
  from projectname_sdk.features import _has_feature
@@ -48,6 +54,10 @@ NOAUTH = "auth" not in shared_config().get("options", {})
48
54
  placing = pytest.mark.skipif(
49
55
  NOAUTH, reason="this SDK's config declares no auth, so it places no credential")
50
56
 
57
+ # The exchange goes through the SDK's default transport, which needs requests.
58
+ over_default_transport = pytest.mark.skipif(
59
+ not HAVE_REQUESTS, reason="the default transport needs the requests module")
60
+
51
61
 
52
62
  def cred_header():
53
63
  """The header the credential travels in: the DEFAULT client's
@@ -449,8 +459,9 @@ if __name__ == "__main__":
449
459
 
450
460
  # ---------------------------------------------------------------------
451
461
  # Review-hardening pins (vendor-tag rollout, PR review): the exchange
452
- # works with ORDINARY options (no custom transport, the stdlib fallback
453
- # carries the purchase), and an uncached miss retracts the credential.
462
+ # works with ORDINARY options (no custom transport: the SDK's own default
463
+ # transport carries the purchase), and an uncached miss retracts the
464
+ # credential.
454
465
 
455
466
  class _TokenEndpoint(http.server.BaseHTTPRequestHandler):
456
467
  refresh_seen = None
@@ -476,10 +487,11 @@ class _TokenEndpoint(http.server.BaseHTTPRequestHandler):
476
487
  @placing
477
488
  class TestSecretsReviewPins(unittest.TestCase):
478
489
 
479
- def test_exchange_uses_the_raw_fallback_and_marshals_the_body(self):
490
+ @over_default_transport
491
+ def test_exchange_uses_the_default_transport_and_marshals_the_body(self):
480
492
  # A refresh token full of JSON-hostile characters must arrive at
481
- # the endpoint as its literal value, through the feature's OWN
482
- # raw transport - ordinary options carry no system.fetch for it.
493
+ # the endpoint as its literal value, through the SDK's default
494
+ # transport - ordinary options carry no system.fetch for it.
483
495
  tricky = 're"fresh\\to\nken'
484
496
  _TokenEndpoint.refresh_seen = None
485
497
 
@@ -489,9 +501,9 @@ class TestSecretsReviewPins(unittest.TestCase):
489
501
  try:
490
502
  # NO system.fetch anywhere: with the seam set, the purchase
491
503
  # rightly prefers it - the point of this pin is the OTHER
492
- # case, ordinary options, where the feature's own stdlib
493
- # fallback must carry the exchange. Only PreSpec runs, so no
494
- # API call ever leaves; the one HTTP request is the purchase.
504
+ # case, ordinary options, where the default transport must
505
+ # carry the exchange. Only PreSpec runs, so no API call ever
506
+ # leaves; the one HTTP request is the purchase.
495
507
  sdk = secrets_sdk({
496
508
  "base": "http://127.0.0.1:%d/api" % srv.server_port,
497
509
  "feature": {"secrets": {
@@ -548,7 +560,8 @@ class TestSecretsReviewPins(unittest.TestCase):
548
560
  srv.shutdown()
549
561
  srv.server_close()
550
562
 
551
- # Real listeners and the raw fallback transport: a stub follows nothing.
563
+ # Real listeners and the default transport: a stub follows nothing.
564
+ @over_default_transport
552
565
  def test_a_redirect_answering_the_exchange_is_a_failure(self):
553
566
  with _origins() as o:
554
567
  answers = [[307, o["away"]], [308, o["away"]], [302, o["away"]],
@@ -577,6 +590,7 @@ class TestSecretsReviewPins(unittest.TestCase):
577
590
  self.assertEqual([], allowed, "a redirect was not a failed exchange")
578
591
  self.assertEqual(len(answers), refused)
579
592
 
593
+ @over_default_transport
580
594
  def test_with_the_option_a_redirect_on_the_exchange_s_own_origin_is_followed(self):
581
595
  with _origins() as o:
582
596
  # Each case: the status, the Location, and the path the exchange is
@@ -367,6 +367,56 @@ class TestCacheFeature:
367
367
  assert b["ctx"].response is sent[1]
368
368
  assert h.client._cache["bypass"] == 2
369
369
 
370
+ def test_keys_on_the_request_headers(self):
371
+ server, calls = recording_server()
372
+ h = make_client([{"name": "cache", "options": {"ttl": 10000}}],
373
+ server=server)
374
+ h.op(op="load", path="/w/1", headers={"x-tenant": "tenant-a"})
375
+ h.op(op="load", path="/w/1", headers={"X-Tenant": "tenant-b"})
376
+ assert len(calls) == 2
377
+ h.op(op="load", path="/w/1", headers={"x-tenant": "tenant-b"})
378
+ assert len(calls) == 2
379
+ cache = [f for f in h.client.features if f.name == "cache"][0]
380
+ assert "tenant-" not in "\n".join(cache.store.keys())
381
+
382
+ def test_a_write_drops_its_collection(self):
383
+ server, calls = recording_server()
384
+ h = make_client([{"name": "cache", "options": {"ttl": 10000}}],
385
+ server=server)
386
+ paths = ["/w/1", "/w", "/w/1/part", "/other/1", "/w/2"]
387
+ for path in paths:
388
+ h.op(op="load", path=path)
389
+ h.op(op="update", method="PUT", path="/w/1")
390
+ for path in paths:
391
+ h.op(op="load", path=path)
392
+ assert len(calls) == 9
393
+ assert h.client._cache["hit"] == 2
394
+
395
+ def test_cache_control_prevents_storing(self):
396
+ for control in ["no-store", "private", "No-Cache", "max-age=60, private"]:
397
+ server, calls = recording_server(
398
+ lambda _n, _fd: make_response(200, {"ok": True}, {"Cache-Control": control}))
399
+ h = make_client([{"name": "cache", "options": {"ttl": 10000}}],
400
+ server=server)
401
+ h.op(op="load", path="/w")
402
+ h.op(op="load", path="/w")
403
+ assert len(calls) == 2, control
404
+
405
+ def test_max_age_caps_the_ttl(self):
406
+ clock = make_clock()
407
+ server, calls = recording_server(
408
+ lambda _n, _fd: make_response(200, {"ok": True}, {"cache-control": "max-age=1"}))
409
+ h = make_client([{"name": "cache",
410
+ "options": {"ttl": 10000, "now": clock.now}}],
411
+ server=server)
412
+ h.op(op="load", path="/w")
413
+ clock.advance(500)
414
+ h.op(op="load", path="/w")
415
+ assert len(calls) == 1
416
+ clock.advance(600)
417
+ h.op(op="load", path="/w")
418
+ assert len(calls) == 2
419
+
370
420
  def test_inactive_cache_does_not_wrap(self):
371
421
  server, calls = recording_server()
372
422
  h = make_client([{"name": "cache", "options": {"active": False}}],
@@ -16,6 +16,7 @@
16
16
  import json
17
17
  import os
18
18
  import re
19
+ import time
19
20
 
20
21
  import pytest
21
22
 
@@ -158,9 +159,25 @@ def _candidates(client):
158
159
  return out
159
160
 
160
161
 
161
- def _invoke(client, op, ctrl):
162
+ def _invoke(client, op, ctrl, args=None):
162
163
  ent = getattr(client, op["accessor"])()
163
- return getattr(ent, op["op"])({}, ctrl)
164
+ return getattr(ent, op["op"])(dict(args or {}), ctrl)
165
+
166
+
167
+ ITEM_ARGS = {"id": "corpus-item"}
168
+
169
+
170
+ def _usable_item(accessor):
171
+ """A write of one entity (#ITEM) that completes when driven with ITEM_ARGS."""
172
+ for cand in _candidates(_client({})):
173
+ if cand["accessor"] != accessor or cand["op"] not in ("update", "patch", "remove"):
174
+ continue
175
+ try:
176
+ _invoke(_client({}), cand, {}, ITEM_ARGS)
177
+ except Exception:
178
+ continue
179
+ return cand
180
+ return None
164
181
 
165
182
 
166
183
  def _usable_ops(want):
@@ -183,6 +200,48 @@ def _usable_ops(want):
183
200
  return picked
184
201
 
185
202
 
203
+ READ_OPS = ("list", "load")
204
+ WRITE_OPS = ("create", "update", "patch", "remove")
205
+
206
+
207
+ def _usable_pair():
208
+ """A read and a write of one entity (#READ, #WRITE), each driven as
209
+ _usable_ops drives an op."""
210
+ found = {}
211
+ for cand in _candidates(_client({})):
212
+ role = "read" if cand["op"] in READ_OPS else "write" if cand["op"] in WRITE_OPS else None
213
+ seen = found.setdefault(cand["accessor"], {})
214
+ if role is None or role in seen:
215
+ continue
216
+ try:
217
+ _invoke(_client({}), cand, {})
218
+ except Exception:
219
+ continue
220
+ seen[role] = cand
221
+ if "read" in seen and "write" in seen:
222
+ return seen
223
+ return None
224
+
225
+
226
+ def _step(client, op, step, ctrl):
227
+ """One step: it may wait before its call, may add request headers for
228
+ its call, and may pass `args` as the operation's first argument."""
229
+ if step.get("wait") is not None:
230
+ time.sleep(step["wait"] / 1000.0)
231
+ options = client._rootctx.options
232
+ prior = options.get("headers")
233
+ if step.get("headers") is not None:
234
+ options["headers"] = dict(prior or {}, **step["headers"])
235
+ try:
236
+ return _invoke(client, op, ctrl, step.get("args"))
237
+ finally:
238
+ if step.get("headers") is not None:
239
+ if prior is None:
240
+ options.pop("headers", None)
241
+ else:
242
+ options["headers"] = prior
243
+
244
+
186
245
  def _resolve(node, tokens):
187
246
  """Replace #OPn throughout a case, keys included."""
188
247
  if isinstance(node, str):
@@ -315,6 +374,14 @@ class TestFeatureCorpus:
315
374
 
316
375
  ops = _usable_ops(2)
317
376
  by_key = {o["key"]: o for o in ops}
377
+ pair = _usable_pair()
378
+ if pair is not None:
379
+ by_key[pair["read"]["key"]] = pair["read"]
380
+ by_key[pair["write"]["key"]] = pair["write"]
381
+ pair["item"] = _usable_item(pair["read"]["accessor"])
382
+ if pair["item"] is not None:
383
+ by_key[pair["item"]["key"]] = pair["item"]
384
+ pair["other"] = next((o for o in ops if o["accessor"] != pair["read"]["accessor"]), None)
318
385
 
319
386
  ran = 0
320
387
  failed = []
@@ -326,6 +393,18 @@ class TestFeatureCorpus:
326
393
  raw.get("name"), need, len(ops)))
327
394
  continue
328
395
 
396
+ paired = re.search(r"#(READ|WRITE|ITEM|OTHER)\b", json.dumps(raw)) is not None
397
+ if paired and pair is None:
398
+ print('skip "{}": needs a read and a write of one entity, this SDK offers none'.format(
399
+ raw.get("name")))
400
+ continue
401
+ lacking = next((tok for tok, role in (("#ITEM", "item"), ("#OTHER", "other"))
402
+ if paired and pair[role] is None
403
+ and re.search(tok + r"\b", json.dumps(raw))), None)
404
+ if lacking is not None:
405
+ print('skip "{}": needs {}, which this SDK cannot drive'.format(raw.get("name"), lacking))
406
+ continue
407
+
329
408
  missing = _missing_feature(raw, have)
330
409
  if missing is not None:
331
410
  print('skip "{}": needs the {} feature, which this SDK does not generate'.format(
@@ -335,6 +414,12 @@ class TestFeatureCorpus:
335
414
  tokens = {}
336
415
  for i in range(need):
337
416
  tokens["#OP{}".format(i + 1)] = ops[i]["key"]
417
+ if paired:
418
+ tokens["#READ"] = pair["read"]["key"]
419
+ tokens["#WRITE"] = pair["write"]["key"]
420
+ for tok, role in (("#ITEM", "item"), ("#OTHER", "other")):
421
+ if pair[role] is not None:
422
+ tokens[tok] = pair[role]["key"]
338
423
  kase = _resolve(raw, tokens)
339
424
  label = kase.get("name")
340
425
  ran += 1
@@ -350,7 +435,7 @@ class TestFeatureCorpus:
350
435
  wanterr = step.get("err")
351
436
 
352
437
  try:
353
- _invoke(client, op, ctrl)
438
+ _step(client, op, step, ctrl)
354
439
  assert wanterr is None, \
355
440
  "{}: {} was expected to fail, and did not".format(label, step["op"])
356
441
  except AssertionError:
@@ -15,7 +15,7 @@ class ProjectNameContext
15
15
  OPMAP_LOCK = Mutex.new
16
16
 
17
17
  attr_accessor :id, :out, :client, :utility, :ctrl, :meta, :config,
18
- :entopts, :options, :entity, :shared, :opmap,
18
+ :entopts, :options, :cleancfg, :entity, :shared, :opmap,
19
19
  :data, :reqdata, :match, :reqmatch, :point,
20
20
  :spec, :result, :response, :op, :unexpected_fired
21
21
 
@@ -53,6 +53,9 @@ class ProjectNameContext
53
53
  o = ProjectNameHelpers.get_ctx_prop(ctxmap, "options")
54
54
  @options = o.is_a?(Hash) ? o : basectx&.options
55
55
 
56
+ # The clean registry, beside the options rather than in them.
57
+ @cleancfg = ProjectNameHelpers.get_ctx_prop(ctxmap, "cleancfg") || basectx&.cleancfg
58
+
56
59
  e = ProjectNameHelpers.get_ctx_prop(ctxmap, "entity")
57
60
  @entity = e || basectx&.entity
58
61
 
@@ -12,6 +12,8 @@
12
12
  require_relative 'base_feature'
13
13
 
14
14
  class ProjectNameAuditFeature < ProjectNameBaseFeature
15
+ AUDIT_SEEN_KEY = "audit_seen"
16
+
15
17
  def initialize
16
18
  super
17
19
  @version = "0.0.1"
@@ -21,7 +23,6 @@ class ProjectNameAuditFeature < ProjectNameBaseFeature
21
23
  @client = nil
22
24
  @options = {}
23
25
  @seq = 0
24
- @seen = {}
25
26
  end
26
27
 
27
28
  def init(ctx, options)
@@ -29,7 +30,6 @@ class ProjectNameAuditFeature < ProjectNameBaseFeature
29
30
  @options = options.is_a?(Hash) ? options : {}
30
31
  @active = @options["active"] == true
31
32
  @seq = 0
32
- @seen = {}
33
33
 
34
34
  return unless @active
35
35
 
@@ -53,9 +53,10 @@ class ProjectNameAuditFeature < ProjectNameBaseFeature
53
53
 
54
54
  def _emit(ctx, outcome)
55
55
  # One record per operation (PreDone + a following PreUnexpected on a
56
- # non-2xx must not double-log).
57
- return if @seen.key?(ctx)
58
- @seen[ctx] = true
56
+ # non-2xx must not double-log). The marker lives on the context, so it
57
+ # goes when the call does.
58
+ return if ctx.out[AUDIT_SEEN_KEY] == true
59
+ ctx.out[AUDIT_SEEN_KEY] = true
59
60
  @seq += 1
60
61
 
61
62
  record = ctx.utility.clean.call(ctx, {