@voxgig/sdkgen 4.48.1 → 4.49.1

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 (119) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/package.json +1 -1
  3. package/project/.sdk/model/feature/secrets.aontu +3 -0
  4. package/project/.sdk/src/cmp/c/Config_c.ts +6 -1
  5. package/project/.sdk/src/cmp/c/fragment/Entity.fragment.c +0 -10
  6. package/project/.sdk/src/cmp/clojure/fragment/Entity.fragment.clj +0 -9
  7. package/project/.sdk/src/cmp/csharp/fragment/EntityBase.fragment.cs +0 -11
  8. package/project/.sdk/src/cmp/go/fragment/Entity.fragment.go +0 -7
  9. package/project/.sdk/src/cmp/java/fragment/EntityBase.fragment.java +0 -10
  10. package/project/.sdk/src/cmp/js/fragment/EntityBase.fragment.js +2 -11
  11. package/project/.sdk/src/cmp/kotlin/fragment/EntityBase.fragment.kt +0 -10
  12. package/project/.sdk/src/cmp/lua/fragment/Entity.fragment.lua +0 -11
  13. package/project/.sdk/src/cmp/ocaml/Entity_ocaml.ts +2 -10
  14. package/project/.sdk/src/cmp/perl/fragment/Entity.fragment.pm +0 -13
  15. package/project/.sdk/src/cmp/php/fragment/Entity.fragment.php +0 -10
  16. package/project/.sdk/src/cmp/py/fragment/Entity.fragment.py +0 -10
  17. package/project/.sdk/src/cmp/rb/fragment/Entity.fragment.rb +0 -10
  18. package/project/.sdk/src/cmp/rust/fragment/Entity.fragment.rs +0 -12
  19. package/project/.sdk/src/cmp/scala/fragment/EntityBase.fragment.scala +0 -10
  20. package/project/.sdk/src/cmp/swift/fragment/EntityBase.fragment.swift +0 -9
  21. package/project/.sdk/src/cmp/ts/fragment/EntityBase.fragment.ts +0 -7
  22. package/project/.sdk/src/cmp/zig/fragment/Entity.fragment.zig +1 -14
  23. package/project/.sdk/tm/c/feature/cache.c +16 -1
  24. package/project/.sdk/tm/c/feature/secrets.c +149 -18
  25. package/project/.sdk/tm/c/tests/feature/secrets/secrets_test.c +319 -70
  26. package/project/.sdk/tm/c/tests/feature_test.c +31 -0
  27. package/project/.sdk/tm/clojure/feature/secrets/sdk/feature/secrets.clj +74 -29
  28. package/project/.sdk/tm/clojure/src/sdk/core.clj +55 -6
  29. package/project/.sdk/tm/clojure/src/sdk/features.clj +16 -2
  30. package/project/.sdk/tm/clojure/test/sdk/test/feature/secrets.clj +191 -48
  31. package/project/.sdk/tm/clojure/test/sdk/test/feature.clj +16 -0
  32. package/project/.sdk/tm/cpp/core/types.hpp +1 -11
  33. package/project/.sdk/tm/cpp/feature/cache.hpp +14 -1
  34. package/project/.sdk/tm/cpp/feature/secrets.hpp +133 -18
  35. package/project/.sdk/tm/cpp/test/feature/secrets/secrets_test.cpp +175 -8
  36. package/project/.sdk/tm/cpp/test/feature_test.cpp +27 -0
  37. package/project/.sdk/tm/csharp/core/Control.cs +0 -5
  38. package/project/.sdk/tm/csharp/feature/CacheFeature.cs +16 -0
  39. package/project/.sdk/tm/csharp/feature/SecretsFeature.cs +77 -38
  40. package/project/.sdk/tm/csharp/test/FeatureTest.cs +29 -0
  41. package/project/.sdk/tm/csharp/test/feature/secrets/SecretsFeatureTest.cs +315 -68
  42. package/project/.sdk/tm/elixir/lib/projectname/entity_base.ex +0 -13
  43. package/project/.sdk/tm/elixir/lib/projectname/feature/cache.ex +32 -10
  44. package/project/.sdk/tm/elixir/lib/projectname/feature/secrets.ex +78 -22
  45. package/project/.sdk/tm/elixir/test/feature/secrets/secrets_test.exs +178 -19
  46. package/project/.sdk/tm/elixir/test/feature_test.exs +20 -0
  47. package/project/.sdk/tm/go/feature/cache_feature.go +14 -1
  48. package/project/.sdk/tm/go/feature/secrets_feature.go +110 -15
  49. package/project/.sdk/tm/go/test/feature/secrets/secrets_feature_test.go +373 -87
  50. package/project/.sdk/tm/go/test/feature_test.go +32 -0
  51. package/project/.sdk/tm/go/utility/media.go +2 -2
  52. package/project/.sdk/tm/java/core/Control.java +0 -5
  53. package/project/.sdk/tm/java/feature/CacheFeature.java +12 -0
  54. package/project/.sdk/tm/java/feature/SecretsFeature.java +104 -34
  55. package/project/.sdk/tm/java/test/FeatureTest.java +25 -0
  56. package/project/.sdk/tm/java/test/PrimaryUtilityTest.java +39 -0
  57. package/project/.sdk/tm/java/test/feature/secrets/SecretsFeatureTest.java +267 -53
  58. package/project/.sdk/tm/java/utility/Fetcher.java +18 -2
  59. package/project/.sdk/tm/java/utility/Media.java +2 -2
  60. package/project/.sdk/tm/js/src/feature/cache/CacheFeature.js +13 -0
  61. package/project/.sdk/tm/js/src/feature/secrets/SecretsFeature.js +79 -29
  62. package/project/.sdk/tm/js/test/feature/secrets/Secrets.test.js +282 -93
  63. package/project/.sdk/tm/js/test/feature.test.js +17 -0
  64. package/project/.sdk/tm/kotlin/core/Control.kt +0 -5
  65. package/project/.sdk/tm/kotlin/feature/CacheFeature.kt +12 -0
  66. package/project/.sdk/tm/kotlin/feature/SecretsFeature.kt +84 -24
  67. package/project/.sdk/tm/kotlin/test/FeatureTest.kt +24 -0
  68. package/project/.sdk/tm/kotlin/test/PrimaryUtilityTest.kt +35 -0
  69. package/project/.sdk/tm/kotlin/test/feature/secrets/SecretsTest.kt +236 -54
  70. package/project/.sdk/tm/kotlin/utility/Fetcher.kt +13 -1
  71. package/project/.sdk/tm/lua/feature/cache_feature.lua +20 -0
  72. package/project/.sdk/tm/lua/feature/secrets_feature.lua +92 -15
  73. package/project/.sdk/tm/lua/test/feature/secrets/secrets_feature_test.lua +208 -43
  74. package/project/.sdk/tm/lua/test/feature_test.lua +18 -0
  75. package/project/.sdk/tm/lua/utility/clean.lua +1 -0
  76. package/project/.sdk/tm/ocaml/feature/secrets_feature.ml +100 -14
  77. package/project/.sdk/tm/ocaml/sdk_features.ml +7 -1
  78. package/project/.sdk/tm/ocaml/test/feature/secrets/t_secrets.ml +143 -7
  79. package/project/.sdk/tm/ocaml/test/t_feature.ml +15 -0
  80. package/project/.sdk/tm/perl/feature/cache_feature.pm +13 -0
  81. package/project/.sdk/tm/perl/feature/secrets_feature.pm +87 -32
  82. package/project/.sdk/tm/perl/t/feature/secrets/secrets.t +177 -24
  83. package/project/.sdk/tm/perl/t/feature.t +24 -0
  84. package/project/.sdk/tm/php/feature/CacheFeature.php +13 -0
  85. package/project/.sdk/tm/php/feature/SecretsFeature.php +79 -23
  86. package/project/.sdk/tm/php/test/FeatureTest.php +23 -0
  87. package/project/.sdk/tm/php/test/feature/secrets/SecretsTest.php +258 -48
  88. package/project/.sdk/tm/py/pkg/feature/cache_feature.py +7 -1
  89. package/project/.sdk/tm/py/pkg/feature/secrets_feature.py +90 -29
  90. package/project/.sdk/tm/py/test/feature/secrets/test_secrets.py +313 -80
  91. package/project/.sdk/tm/py/test/test_feature.py +18 -0
  92. package/project/.sdk/tm/rb/feature/cache_feature.rb +12 -0
  93. package/project/.sdk/tm/rb/feature/secrets_feature.rb +68 -21
  94. package/project/.sdk/tm/rb/test/feature/secrets/secrets_feature_test.rb +214 -43
  95. package/project/.sdk/tm/rb/test/feature_test.rb +20 -0
  96. package/project/.sdk/tm/rust/feature/cache.rs +15 -1
  97. package/project/.sdk/tm/rust/feature/secrets.rs +103 -23
  98. package/project/.sdk/tm/rust/tests/feature/secrets/main.rs +357 -67
  99. package/project/.sdk/tm/rust/tests/feature_test.rs +41 -0
  100. package/project/.sdk/tm/scala/core/Control.scala +0 -5
  101. package/project/.sdk/tm/scala/feature/CacheFeature.scala +12 -0
  102. package/project/.sdk/tm/scala/feature/SecretsFeature.scala +88 -22
  103. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +61 -1
  104. package/project/.sdk/tm/scala/sdktest/feature/secrets/SecretsTestMain.scala +230 -73
  105. package/project/.sdk/tm/scala/utility/Fetcher.scala +13 -1
  106. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/core/Control.swift +0 -5
  107. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/CacheFeature.swift +11 -0
  108. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/SecretsFeature.swift +76 -16
  109. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/FeatureTest.swift +21 -0
  110. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/feature/secrets/SecretsFeatureTest.swift +257 -73
  111. package/project/.sdk/tm/ts/src/feature/cache/CacheFeature.ts +13 -0
  112. package/project/.sdk/tm/ts/src/feature/secrets/SecretsFeature.ts +77 -17
  113. package/project/.sdk/tm/ts/test/feature/secrets/Secrets.test.ts +282 -87
  114. package/project/.sdk/tm/ts/test/feature.test.ts +17 -0
  115. package/project/.sdk/tm/zig/feature/cache.zig +15 -1
  116. package/project/.sdk/tm/zig/feature/secrets.zig +109 -32
  117. package/project/.sdk/tm/zig/test/feature/secrets/secrets_test.zig +232 -9
  118. package/project/.sdk/tm/zig/test/feature_test.zig +33 -0
  119. package/project/sdkgen-package.json +1 -1
@@ -573,6 +573,27 @@ final class FeatureCacheTest: XCTestCase {
573
573
  XCTAssertEqual(rec.calls.count, 3)
574
574
  }
575
575
 
576
+ func testBodyOfAnotherTypeThanJsonPassesByUnread() {
577
+ if Fh.skipWithout("cache") { return }
578
+ let rec = FhRecorder()
579
+ var sent: [VMap?] = []
580
+ rec.reply = { _, _ in
581
+ let res = Fh.response(200, .noval, vm(("content-type", .string("audio/wav"))))
582
+ res.asMap?.entries["body"] = .string("RIFF")
583
+ sent.append(res.asMap?.entries["headers"]?.asMap)
584
+ return res
585
+ }
586
+ let f = CacheFeature()
587
+ let h = Fh.make(rec.fetch, (f, nil))
588
+ let a = h.op(FhOpSpec(op: "load", path: "/w/1/audio"))
589
+ let b = h.op(FhOpSpec(op: "load", path: "/w/1/audio"))
590
+ XCTAssertEqual(rec.calls.count, 2, "the body was stored")
591
+ XCTAssertTrue(a.ctx?.response?.headers.asMap === sent[0],
592
+ "the cache handed on a copy it had read")
593
+ XCTAssertTrue(sent.count == 2 && b.ctx?.response?.headers.asMap === sent[1])
594
+ XCTAssertEqual(f.bypass, 2)
595
+ }
596
+
576
597
  func testInactiveDoesNotWrap() {
577
598
  if Fh.skipWithout("cache") { return }
578
599
  let rec = FhRecorder()
@@ -52,6 +52,13 @@ let secretsCredHeader: String = {
52
52
  return "" == name ? "authorization" : name.lowercased()
53
53
  }()
54
54
 
55
+ // The form prepareAuth writes, from the DEFAULT client's auth: under Basic the
56
+ // token is the key half of the encoded pair, and a prefix is space-joined.
57
+ let secretsCredForm: (prefix: String, basic: Bool) = {
58
+ let auth = gp(ProjectNameSDK.testSDK(nil, nil).optionsMap(), "auth")
59
+ return (gp(auth, "prefix").asString ?? "", true == gp(auth, "basic").asBool)
60
+ }()
61
+
55
62
  // -------------------------------------------------------------------
56
63
  // The recording transport: system.fetch for a LIVE client, scripting one
57
64
  // status per API call (the last repeating) and a token endpoint for the
@@ -64,6 +71,7 @@ final class SecretsWire {
64
71
  let hasAuth: Bool
65
72
  let body: String
66
73
  let redirect: String
74
+ var values: String = ""
67
75
  }
68
76
 
69
77
  private let lock = NSLock()
@@ -97,15 +105,20 @@ final class SecretsWire {
97
105
  // make every earlier record show the newest token.
98
106
  var auth = ""
99
107
  var hasAuth = false
108
+ var values: [String] = []
100
109
  if let headers = gp(fetchdef, "headers").asMap {
101
- for (k, v) in headers.entries where k.lowercased() == secretsCredHeader {
102
- hasAuth = true
103
- auth = v.asString ?? stringify(v)
110
+ for (k, v) in headers.entries {
111
+ if k.lowercased() == secretsCredHeader {
112
+ hasAuth = true
113
+ auth = v.asString ?? stringify(v)
114
+ }
115
+ values.append(v.asString ?? stringify(v))
104
116
  }
105
117
  }
106
118
  let body = gp(fetchdef, "body").asString ?? ""
107
119
  let redirect = gp(fetchdef, "redirect").asString ?? ""
108
- recorded.append(Call(url: url, auth: auth, hasAuth: hasAuth, body: body, redirect: redirect))
120
+ recorded.append(Call(url: url, auth: auth, hasAuth: hasAuth, body: body, redirect: redirect,
121
+ values: values.joined(separator: "\n")))
109
122
 
110
123
  if url.hasSuffix("/" + tokenpath) {
111
124
  if issued >= tokenok {
@@ -186,15 +199,17 @@ final class SecretsFeatureTest: XCTestCase {
186
199
  // -------------------------------------------------------------------
187
200
  // Support.
188
201
 
189
- // The credential header carries the SPEC's credential prefix, which a
190
- // TEMPLATE cannot know: an OpenAPI `http`/`bearer` scheme gives
191
- // `Bearer <token>`, an apiKey scheme the raw token. So assert on the
192
- // CREDENTIAL and let the prefix be whatever this SDK's API declares.
193
- private func credentialIs(_ header: String, _ token: String,
202
+ // The header value prepareAuth writes for a token.
203
+ private func credential(_ token: String, _ secret: String = "") -> String {
204
+ let value = secretsCredForm.basic
205
+ ? Data((token + ":" + secret).utf8).base64EncodedString() : token
206
+ return "" == secretsCredForm.prefix ? value : secretsCredForm.prefix + " " + value
207
+ }
208
+
209
+ private func credentialIs(_ header: String, _ token: String, _ secret: String = "",
194
210
  file: StaticString = #filePath, line: UInt = #line) {
195
- XCTAssertTrue(header == token || header.hasSuffix(" " + token),
196
- "expected the \(secretsCredHeader) header to carry \(token), got: \"\(header)\"",
197
- file: file, line: line)
211
+ XCTAssertEqual(credential(token, secret), header,
212
+ "expected the \(secretsCredHeader) header to carry \(token)", file: file, line: line)
198
213
  }
199
214
 
200
215
  private func secretsOf(_ client: ProjectNameSDK) -> SecretsFeature? {
@@ -336,9 +351,11 @@ final class SecretsFeatureTest: XCTestCase {
336
351
 
337
352
  // Read from the config, never from a probe: an SDK whose config declares no
338
353
  // auth places no credential, and these tests assert on the one it places.
354
+ // The auth-off test asserts it places none.
339
355
  override func setUpWithError() throws {
340
356
  try super.setUpWithError()
341
- guard nil != gp(SdkConfig.sharedConfig(), "options").asMap?.entries["auth"] else {
357
+ guard nil != gp(SdkConfig.sharedConfig(), "options").asMap?.entries["auth"]
358
+ || name.contains("testAuthOff") else {
342
359
  throw XCTSkip("this SDK's config declares no auth, so it places no credential")
343
360
  }
344
361
  }
@@ -422,6 +439,20 @@ final class SecretsFeatureTest: XCTestCase {
422
439
  credentialIs(w.api()[0].auth, "CHAINKEY03")
423
440
  }
424
441
 
442
+ func testAResolvedKeyIsPlacedAsPrepareAuthPlacesItTheSecretKept() {
443
+ let w = SecretsWire()
444
+ let client = secretsClient(w, [
445
+ ("secret", .string("PASS01")),
446
+ ("feature", chainOpts(working("CHAINKEY05"))),
447
+ ])
448
+
449
+ driveEntityOp(client, w)
450
+ XCTAssertFalse(w.api().isEmpty, "no request reached the wire")
451
+ if !w.api().isEmpty {
452
+ credentialIs(w.api()[0].auth, "CHAINKEY05", "PASS01")
453
+ }
454
+ }
455
+
425
456
  func testCustomProviderObjectsAreAcceptedVerbatim() {
426
457
  let asklock = NSLock()
427
458
  var asked: [String] = []
@@ -924,6 +955,23 @@ final class SecretsFeatureTest: XCTestCase {
924
955
  credentialIs(w.api()[1].auth, "ACCESS02")
925
956
  }
926
957
 
958
+ func testATokenBoughtOnARefusalIsPlacedAsPrepareAuthPlacesIt() {
959
+ let w = SecretsWire()
960
+ w.apistatus = [401, 200]
961
+ let client = secretsClient(w, [
962
+ ("secret", .string("PASS01")),
963
+ ("feature", chainOpts(working("REFRESH01"), [exchangeOn()])),
964
+ ])
965
+
966
+ _ = client.direct(vm(("path", .string("/thing"))))
967
+
968
+ XCTAssertEqual(2, w.api().count, "expected the refused request to be retried once: " + w.wire())
969
+ if 2 == w.api().count {
970
+ credentialIs(w.api()[0].auth, "ACCESS01", "PASS01")
971
+ credentialIs(w.api()[1].auth, "ACCESS02", "PASS01")
972
+ }
973
+ }
974
+
927
975
  func testAnExplicitApikeyIsTheStartingAccessTokenWhenExchanging() {
928
976
  // With the exchange on, `apikey` is an access token the caller already
929
977
  // holds: it is SPENT first, and the API decides whether it is stale.
@@ -997,11 +1045,8 @@ final class SecretsFeatureTest: XCTestCase {
997
1045
  XCTAssertEqual(.bool(false), res.entries["ok"])
998
1046
  XCTAssertEqual(1, w.api().count, "a suppressed-auth 401 must not be retried: " + w.wire())
999
1047
  XCTAssertFalse(w.api()[0].hasAuth, "auth null must keep the header off, got: " + w.api()[0].auth)
1000
- // Resolution still ran once (the chain was consulted and the access
1001
- // token bought, as go's resolveonce does whatever `auth` says); what
1002
- // the suppression forbids is the REBUY after the refusal.
1003
- XCTAssertEqual(1, w.token().count,
1004
- "a suppressed-auth 401 must not buy another token: " + w.wire())
1048
+ XCTAssertEqual(0, w.token().count,
1049
+ "a suppressed-auth request must buy no token: " + w.wire())
1005
1050
  }
1006
1051
 
1007
1052
  func testExchangeInTestModeBuysNothing() {
@@ -1048,8 +1093,20 @@ final class SecretsFeatureTest: XCTestCase {
1048
1093
  "the refresh token did not survive the body encoding: " + w.token()[0].body)
1049
1094
  }
1050
1095
 
1051
- // Real listeners and the SDK's own raw fetch: a stub follows nothing.
1052
- func testARedirectAnsweringTheExchangeIsAFailureAndNothingFollowsIt() {
1096
+ // Real listeners: the origin answers the exchange as `answer` says and
1097
+ // records whatever else it gets; the other records everything.
1098
+ private final class RedirectOrigins {
1099
+ let lock = NSLock()
1100
+ var elsewhere: [String] = []
1101
+ var followed: [String] = []
1102
+ var exchanged = 0
1103
+ var answer: (Int, String) = (307, "")
1104
+ var origin = ""
1105
+ var away = ""
1106
+ var base: String { origin + "/api" }
1107
+ }
1108
+
1109
+ private func withOrigins(_ run: (RedirectOrigins) -> Void) {
1053
1110
  func listener() -> (Int32, String) {
1054
1111
  #if os(Linux)
1055
1112
  let fd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
@@ -1077,13 +1134,11 @@ final class SecretsFeatureTest: XCTestCase {
1077
1134
  return (fd, "http://127.0.0.1:\(UInt16(bigEndian: addr.sin_port))")
1078
1135
  }
1079
1136
 
1137
+ let o = RedirectOrigins()
1080
1138
  let (originfd, originbase) = listener()
1081
1139
  let (otherfd, otherbase) = listener()
1082
-
1083
- let lock = NSLock()
1084
- var elsewhere: [String] = []
1085
- var followed: [String] = []
1086
- var answer: (Int, String) = (307, "")
1140
+ o.origin = originbase
1141
+ o.away = otherbase + "/api/auth/token"
1087
1142
 
1088
1143
  for (fd, isorigin) in [(originfd, true), (otherfd, false)] {
1089
1144
  Thread.detachNewThread {
@@ -1120,19 +1175,20 @@ final class SecretsFeatureTest: XCTestCase {
1120
1175
  var status = "200 X"
1121
1176
  var location = ""
1122
1177
  var reply = ""
1123
- lock.lock()
1178
+ o.lock.lock()
1124
1179
  if target == "/stop" {
1125
1180
  } else if !isorigin {
1126
- elsewhere.append(method + " " + target + " " + sent)
1181
+ o.elsewhere.append(method + " " + target + " " + sent)
1127
1182
  reply = "{\"access_token\":\"ELSEWHERE01\"}"
1128
1183
  } else if target == "/api/auth/token" {
1129
- status = "\(answer.0) X"
1130
- location = "Location: " + answer.1 + "\r\n"
1184
+ o.exchanged += 1
1185
+ status = "\(o.answer.0) X"
1186
+ location = "Location: " + o.answer.1 + "\r\n"
1131
1187
  } else {
1132
- followed.append(method + " " + target)
1188
+ o.followed.append((method + " " + target + " " + sent).trimmingCharacters(in: .whitespaces))
1133
1189
  reply = "{\"access_token\":\"MOVED01\"}"
1134
1190
  }
1135
- lock.unlock()
1191
+ o.lock.unlock()
1136
1192
 
1137
1193
  let out = Array(("HTTP/1.1 \(status)\r\nContent-Type: application/json\r\n" + location +
1138
1194
  "Content-Length: \(reply.utf8.count)\r\nConnection: close\r\n\r\n\(reply)").utf8)
@@ -1150,55 +1206,183 @@ final class SecretsFeatureTest: XCTestCase {
1150
1206
  close(otherfd)
1151
1207
  }
1152
1208
 
1153
- let base = originbase + "/api"
1154
- let away = otherbase + "/api/auth/token"
1155
- let answers: [(Int, String)] = [(307, away), (308, away), (302, away), (307, "/api/moved/token")]
1156
-
1157
- var allowed: [String] = []
1158
- var refused = 0
1159
-
1160
- for next in answers {
1161
- lock.lock()
1162
- answer = next
1163
- lock.unlock()
1164
-
1165
- let client = withSecrets { extend in
1166
- let fopts = VMap()
1167
- fopts.entries["active"] = .bool(true)
1168
- fopts.entries["name"] = .string("refresh_token")
1169
- fopts.entries["exchange"] = .map(vm(
1170
- ("active", .bool(true)), ("refresh", .string("REFRESH01"))))
1171
- let opts = VMap()
1172
- opts.entries["base"] = .string(base)
1173
- opts.entries["allow"] = .map(vm(
1174
- ("op", .string("create,update,load,list,remove,command,direct,graphql"))))
1175
- opts.entries["feature"] = .map(vm(("secrets", .map(fopts))))
1176
- if extend {
1177
- opts.entries["extend"] = .list([.nat(SecretsFeature())])
1178
- }
1179
- return ProjectNameSDK(opts)
1209
+ run(o)
1210
+ }
1211
+
1212
+ private func redirectClient(_ o: RedirectOrigins, _ redirect: String? = nil) -> ProjectNameSDK {
1213
+ return withSecrets { extend in
1214
+ let xopts = vm(("active", .bool(true)), ("refresh", .string("REFRESH01")))
1215
+ if let redirect = redirect {
1216
+ xopts.entries["redirect"] = .string(redirect)
1217
+ }
1218
+ let fopts = VMap()
1219
+ fopts.entries["active"] = .bool(true)
1220
+ fopts.entries["name"] = .string("refresh_token")
1221
+ fopts.entries["exchange"] = .map(xopts)
1222
+ let opts = VMap()
1223
+ opts.entries["base"] = .string(o.base)
1224
+ opts.entries["allow"] = .map(vm(
1225
+ ("op", .string("create,update,load,list,remove,command,direct,graphql"))))
1226
+ opts.entries["feature"] = .map(vm(("secrets", .map(fopts))))
1227
+ if extend {
1228
+ opts.entries["extend"] = .list([.nat(SecretsFeature())])
1180
1229
  }
1230
+ return ProjectNameSDK(opts)
1231
+ }
1232
+ }
1181
1233
 
1182
- let res = client.direct(vm(("path", .string("/thing"))))
1183
- let message = messageOf(errOf(res))
1234
+ // Real listeners and the SDK's own raw fetch: a stub follows nothing.
1235
+ func testARedirectAnsweringTheExchangeIsAFailureAndNothingFollowsIt() {
1236
+ withOrigins { o in
1237
+ let base = o.base
1238
+ let answers: [(Int, String)] = [(307, o.away), (308, o.away), (302, o.away), (307, "/api/moved/token")]
1184
1239
 
1185
- if message.contains("token exchange failed: \(next.0) from " + base + "/auth/token") {
1186
- refused += 1
1187
- } else {
1188
- allowed.append("\(next.0) to \(next.1): " + message)
1240
+ var allowed: [String] = []
1241
+ var refused = 0
1242
+
1243
+ for next in answers {
1244
+ o.lock.lock()
1245
+ o.answer = next
1246
+ o.lock.unlock()
1247
+
1248
+ let res = redirectClient(o).direct(vm(("path", .string("/thing"))))
1249
+ let message = messageOf(errOf(res))
1250
+
1251
+ if message.contains("token exchange failed: \(next.0) from " + base + "/auth/token") {
1252
+ refused += 1
1253
+ } else {
1254
+ allowed.append("\(next.0) to \(next.1): " + message)
1255
+ }
1189
1256
  }
1257
+
1258
+ o.lock.lock()
1259
+ let reached = o.elsewhere
1260
+ let after = o.followed
1261
+ o.lock.unlock()
1262
+
1263
+ print("secrets: exchange refused \(refused) redirect(s), \(reached.count + after.count) followed")
1264
+
1265
+ XCTAssertEqual([], reached, "the exchange reached another origin")
1266
+ XCTAssertEqual([], after, "a request followed a refused exchange")
1267
+ XCTAssertEqual([], allowed, "a redirect was not a failed exchange")
1268
+ XCTAssertEqual(answers.count, refused)
1190
1269
  }
1270
+ }
1191
1271
 
1192
- lock.lock()
1193
- let reached = elsewhere
1194
- let after = followed
1195
- lock.unlock()
1272
+ func testWithTheOptionARedirectOnTheExchangesOwnOriginIsFollowedAndNoOther() {
1273
+ withOrigins { o in
1274
+ let sent = " {\"refresh_token\":\"REFRESH01\"}"
1275
+ // Each case: the status, the Location, and the path the exchange is
1276
+ // asked again at, or nil where the redirect is refused.
1277
+ let cases: [(Int, String, String?)] = [
1278
+ (307, "/api/moved/token", "/api/moved/token"),
1279
+ (308, o.origin + "/api/moved/token", "/api/moved/token"),
1280
+ // A Location of a query alone keeps the path that answered.
1281
+ (307, "?step=2", "/api/auth/token?step=2"),
1282
+ (307, o.away, nil),
1283
+ (302, "/api/moved/token", nil),
1284
+ (307, "/api/auth/token", nil),
1285
+ ]
1286
+
1287
+ var wrong: [String] = []
1288
+ var followed = 0
1289
+ var refused = 0
1290
+ var looped = 0
1291
+
1292
+ for (status, location, path) in cases {
1293
+ o.lock.lock()
1294
+ o.answer = (status, location)
1295
+ o.followed = []
1296
+ o.exchanged = 0
1297
+ o.lock.unlock()
1298
+
1299
+ let res = redirectClient(o, "same-origin").direct(vm(("path", .string("/thing"))))
1300
+ let message = messageOf(errOf(res))
1301
+
1302
+ o.lock.lock()
1303
+ let seen = o.followed
1304
+ let exchanged = o.exchanged
1305
+ o.lock.unlock()
1306
+
1307
+ let report = "\(status) to \(location): " + message + " [" + seen.joined(separator: " | ") + "]"
1308
+
1309
+ if let path = path {
1310
+ let asked = "POST " + path + sent
1311
+ if true == res.entries["ok"]?.asBool && 2 == seen.count && asked == seen[0] {
1312
+ followed += 1
1313
+ } else {
1314
+ wrong.append(report)
1315
+ }
1316
+ } else if seen.isEmpty &&
1317
+ message.contains("token exchange failed: \(status) from " + o.base + "/auth/token") {
1318
+ refused += 1
1319
+ } else {
1320
+ wrong.append(report)
1321
+ }
1196
1322
 
1197
- print("secrets: exchange refused \(refused) redirect(s), \(reached.count + after.count) followed")
1323
+ if "/api/auth/token" == location {
1324
+ looped = exchanged
1325
+ }
1326
+ }
1327
+
1328
+ o.lock.lock()
1329
+ let reached = o.elsewhere
1330
+ o.lock.unlock()
1331
+
1332
+ print("secrets: exchange opt-in followed \(followed) redirect(s) on its own origin, " +
1333
+ "refused \(refused), \(reached.count) elsewhere")
1334
+
1335
+ XCTAssertEqual([], reached, "the exchange reached another origin")
1336
+ XCTAssertEqual([], wrong)
1337
+ XCTAssertEqual(3, followed)
1338
+ XCTAssertEqual(3, refused)
1339
+ // A redirect to itself stops at the hop limit.
1340
+ XCTAssertEqual(6, looped)
1341
+ }
1342
+ }
1343
+
1344
+ // ===================================================================
1345
+ // Off by the config where it declares no auth, else by `auth: null`:
1346
+ // either way the feature places no credential, buys no token and retries
1347
+ // nothing.
1348
+
1349
+ func testAuthOffPlacesNoCredentialAndBuysNoToken() {
1350
+ let declared = nil != gp(SdkConfig.sharedConfig(), "options").asMap?.entries["auth"]
1351
+ let secrets = ["OFFKEY01", "OFFKEY02", "OFFREFRESH01", "ACCESS01"]
1352
+ let carries = { (call: SecretsWire.Call) -> Bool in
1353
+ call.hasAuth || secrets.contains { call.values.contains($0) }
1354
+ }
1355
+ var sent: [SecretsWire.Call] = []
1356
+ var bought = 0
1357
+
1358
+ let scenarios: [(String, [(String, Value)], Int)] = [
1359
+ ("a key the chain resolves", [("feature", chainOpts(working("OFFKEY01")))], 200),
1360
+ ("an explicit apikey", [("apikey", .string("OFFKEY02")),
1361
+ ("feature", .map(vm(("secrets", .map(vm(("active", .bool(true))))))))], 200),
1362
+ ("a refusal", [("feature", chainOpts(working("OFFREFRESH01"), [exchangeOn()]))], 401),
1363
+ ]
1364
+
1365
+ let off: [(String, Value)] = declared ? [("auth", .null)] : []
1366
+
1367
+ for (what, opts, status) in scenarios {
1368
+ let w = SecretsWire()
1369
+ w.apistatus = [status]
1370
+ let client = secretsClient(w, opts + off)
1371
+
1372
+ _ = client.direct(vm(("path", .string("/thing"))))
1373
+
1374
+ XCTAssertEqual(1, w.api().count, what + ": a request was retried with auth off: " + w.wire())
1375
+ XCTAssertEqual(0, w.token().count, what + ": a token was bought with auth off: " + w.wire())
1376
+ XCTAssertFalse(w.api().first.map(carries) ?? true,
1377
+ what + ": a credential was sent with auth off: " + w.wire())
1378
+ XCTAssertEqual("", secretsOf(client)?.credential(),
1379
+ what + ": the feature resolved a credential with auth off")
1380
+
1381
+ sent += w.api()
1382
+ bought += w.token().count
1383
+ }
1198
1384
 
1199
- XCTAssertEqual([], reached, "the exchange reached another origin")
1200
- XCTAssertEqual([], after, "a request followed a refused exchange")
1201
- XCTAssertEqual([], allowed, "a redirect was not a failed exchange")
1202
- XCTAssertEqual(answers.count, refused)
1385
+ print("secrets: auth off by \(declared ? "option" : "config"): \(sent.count) request(s), " +
1386
+ "\(sent.filter(carries).count) credential(s), \(bought) token(s)")
1203
1387
  }
1204
1388
  }
@@ -3,6 +3,7 @@ import type { Context, FeatureOptions } from '../../types'
3
3
  import type { ProjectNameSDK } from '../../ProjectNameSDK'
4
4
 
5
5
  import { BaseFeature } from '../base/BaseFeature'
6
+ import { headerValue, isJsonMedia } from '../../utility/MediaUtility'
6
7
 
7
8
 
8
9
  class CacheFeature extends BaseFeature {
@@ -55,6 +56,12 @@ class CacheFeature extends BaseFeature {
55
56
 
56
57
  const res = await inner(ctx, url, fetchdef)
57
58
 
59
+ // A body that declares another type than JSON passes by, unread.
60
+ if (this._cacheable(res) && !this._json(res)) {
61
+ this._track('bypass')
62
+ return res
63
+ }
64
+
58
65
  if (this._cacheable(res)) {
59
66
  const snapshot = await this._snapshot(res)
60
67
 
@@ -86,6 +93,12 @@ class CacheFeature extends BaseFeature {
86
93
  }
87
94
 
88
95
 
96
+ _json(this: any, res: any): boolean {
97
+ const type = headerValue(res.headers, 'content-type')
98
+ return '' === type || isJsonMedia(type)
99
+ }
100
+
101
+
89
102
  async _snapshot(this: any, res: any): Promise<any> {
90
103
  let data: any = undefined
91
104
  let text: any = undefined
@@ -10,11 +10,42 @@ import { Sekreto, envkey } from './sekreto'
10
10
  import { FEATURE_PLUGINS } from '../../Config'
11
11
 
12
12
 
13
+ const REDIRECT_MAX = 5
14
+
15
+
16
+ // The next URL of a redirect that keeps its method, when that URL is on the
17
+ // exchange's own origin. Any other redirect would drop the body or leave it.
18
+ function moved(url: string, at: string, res: any): string | undefined {
19
+ const status = null == res ? 0 : res.status
20
+ if (307 !== status && 308 !== status) {
21
+ return undefined
22
+ }
23
+
24
+ const headers = res.headers
25
+ const location = null == headers ? undefined :
26
+ 'function' === typeof headers.get ? headers.get('location') : headers.location
27
+
28
+ if ('string' !== typeof location || '' === location) {
29
+ return undefined
30
+ }
31
+
32
+ try {
33
+ const next = new URL(location, at)
34
+ return next.origin === new URL(url).origin ? next.href : undefined
35
+ }
36
+ catch (_err) {
37
+ return undefined
38
+ }
39
+ }
40
+
41
+
13
42
  class SecretsFeature extends BaseFeature {
14
43
  version = '0.1.0'
15
44
  name = 'secrets'
16
45
 
17
46
  _client: any
47
+ _declared: boolean = false
48
+ _basic: boolean = false
18
49
  _sekreto?: Sekreto
19
50
  _secretname: string = 'apikey'
20
51
  _resolving?: Promise<void>
@@ -30,6 +61,13 @@ class SecretsFeature extends BaseFeature {
30
61
  const options = ctx.options
31
62
 
32
63
  this._client = client
64
+
65
+ // What PrepareAuth was generated from: the config declares auth only
66
+ // where it places a credential, and Basic only where it composes one.
67
+ const declared = ctx.config?.options?.auth
68
+ this._declared = null != declared
69
+ this._basic = true === declared?.basic
70
+
33
71
  this._secretname = 'string' === typeof (fopts as any).name &&
34
72
  '' !== (fopts as any).name ? (fopts as any).name : 'apikey'
35
73
 
@@ -41,6 +79,7 @@ class SecretsFeature extends BaseFeature {
41
79
  response: 'string' === typeof xopts.response ? xopts.response : 'access_token',
42
80
  statuses: Array.isArray(xopts.statuses) ? xopts.statuses : [401],
43
81
  retries: 'number' === typeof xopts.retries ? xopts.retries : 1,
82
+ redirect: 'same-origin' === xopts.redirect ? 'same-origin' : 'refuse',
44
83
  } : null
45
84
 
46
85
  const providers: any[] = []
@@ -89,6 +128,12 @@ class SecretsFeature extends BaseFeature {
89
128
  }
90
129
 
91
130
 
131
+ // PrepareAuth's decision: auth the config declares, not suppressed by `auth: null`.
132
+ _authon(): boolean {
133
+ return this._declared && null != this._client._options.auth
134
+ }
135
+
136
+
92
137
  _register(value: any): void {
93
138
  const ctx = this._client._rootctx
94
139
  if (null != ctx && null != ctx.utility && 'function' === typeof ctx.utility.cleanAdd) {
@@ -127,7 +172,7 @@ class SecretsFeature extends BaseFeature {
127
172
  // boolean is the whole of what resolve() needs to tell a cacheable HIT
128
173
  // from a miss it must not retain.
129
174
  private async _resolveonce(): Promise<boolean> {
130
- if (null == this._sekreto) {
175
+ if (null == this._sekreto || !this._authon()) {
131
176
  return false
132
177
  }
133
178
 
@@ -158,10 +203,6 @@ class SecretsFeature extends BaseFeature {
158
203
  return true
159
204
  }
160
205
 
161
- if (null == this._client.options().auth) {
162
- return false
163
- }
164
-
165
206
  this._client._options.apikey = await this._buy()
166
207
 
167
208
  return true
@@ -214,13 +255,26 @@ class SecretsFeature extends BaseFeature {
214
255
  throw new Error("secrets: no fetch implementation for the token exchange")
215
256
  }
216
257
 
217
- const res = await fetch(url, {
258
+ const fetchdef = {
218
259
  method: x.method,
219
260
  headers: { "content-type": "application/json" },
220
261
  body: JSON.stringify({ [x.request]: this._refresh }),
221
- // Never followed: a redirect would carry the refresh token on.
262
+ // Never followed by the client: a redirect would carry the refresh token on.
222
263
  redirect: 'manual',
223
- })
264
+ }
265
+
266
+ let res = await fetch(url, fetchdef)
267
+
268
+ // By option alone, and only while the exchange stays on its own origin.
269
+ let at = url
270
+ for (let hops = 0; 'same-origin' === x.redirect && hops < REDIRECT_MAX; hops++) {
271
+ const next = moved(url, at, res)
272
+ if (null == next) {
273
+ break
274
+ }
275
+ at = next
276
+ res = await fetch(at, fetchdef)
277
+ }
224
278
 
225
279
  const status = null == res ? 0 : res.status
226
280
 
@@ -249,7 +303,7 @@ class SecretsFeature extends BaseFeature {
249
303
  const x = this._exchange
250
304
  const max = null == x ? 0 : x.retries
251
305
 
252
- if (null == this._client.options().auth) {
306
+ if (!this._authon()) {
253
307
  return inner(ctx, url, fetchdef)
254
308
  }
255
309
 
@@ -305,23 +359,29 @@ class SecretsFeature extends BaseFeature {
305
359
  return
306
360
  }
307
361
 
308
- const auth = this._client.options().auth
309
-
310
- // Suppressed auth means NO header, the same answer prepareAuth gives.
311
- // Reached defensively - _withRefresh does not retry at all when auth
312
- // is null - but this is the function that writes the credential, so
313
- // it is where the rule has to hold.
314
- if (null == auth) {
362
+ if (!this._authon()) {
315
363
  delete fetchdef.headers.authorization
316
364
  return
317
365
  }
318
366
 
367
+ const auth = this._client._options.auth
368
+
319
369
  // The header prepareAuth wrote: auth.name, lower-cased.
320
370
  const name = "string" === typeof auth.name && "" !== auth.name ?
321
371
  auth.name.toLowerCase() : "authorization"
322
372
 
373
+ const value = this._basic && true === auth.basic ? this._pair(token) : token
323
374
  const prefix = auth.prefix
324
- fetchdef.headers[name] = prefix ? prefix + " " + token : token
375
+ fetchdef.headers[name] = prefix ? prefix + " " + value : value
376
+ }
377
+
378
+
379
+ // Under Basic the token is the key half, as apikey is: prepareAuth's pair.
380
+ _pair(this: any, token: string): string {
381
+ const secret = this._client._options.secret
382
+ const pair = Buffer.from(token + ":" + (null == secret ? "" : secret)).toString("base64")
383
+ this._register(pair)
384
+ return pair
325
385
  }
326
386
  }
327
387