@voxgig/sdkgen 4.48.1 → 4.49.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 (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 +8 -1
  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
@@ -38,6 +38,7 @@ package KOTLINPACKAGE.sdktest
38
38
  // answers when the option does not - is identical either way.
39
39
 
40
40
  import java.lang.reflect.Method
41
+ import java.util.Base64
41
42
  import java.util.concurrent.CountDownLatch
42
43
  import java.util.concurrent.TimeUnit
43
44
  import java.util.function.BiFunction
@@ -52,6 +53,7 @@ import org.junit.jupiter.api.Assertions.fail
52
53
  import org.junit.jupiter.api.Assumptions
53
54
  import org.junit.jupiter.api.BeforeEach
54
55
  import org.junit.jupiter.api.Test
56
+ import org.junit.jupiter.api.TestInfo
55
57
 
56
58
  import KOTLINPACKAGE.core.Config
57
59
  import KOTLINPACKAGE.core.Helpers
@@ -75,6 +77,7 @@ class SecretsTest {
75
77
  val hasAuth: Boolean,
76
78
  val body: String,
77
79
  val redirect: Any? = null,
80
+ val values: String = "",
78
81
  )
79
82
 
80
83
  class Wire {
@@ -106,6 +109,7 @@ class SecretsTest {
106
109
  // would make every earlier record show the newest token.
107
110
  var auth = ""
108
111
  var hasAuth = false
112
+ val values = mutableListOf<String>()
109
113
  val headers = fetchdef["headers"]
110
114
  if (headers is Map<*, *>) {
111
115
  for (e in headers.entries) {
@@ -113,10 +117,12 @@ class SecretsTest {
113
117
  hasAuth = true
114
118
  auth = e.value?.toString() ?: ""
115
119
  }
120
+ values.add(e.value?.toString() ?: "")
116
121
  }
117
122
  }
118
123
  val body = fetchdef["body"]
119
- recorded.add(Call(url, auth, hasAuth, if (body is String) body else "", fetchdef["redirect"]))
124
+ recorded.add(Call(url, auth, hasAuth, if (body is String) body else "", fetchdef["redirect"],
125
+ values.joinToString("\n")))
120
126
 
121
127
  if (url.endsWith("/$tokenpath")) {
122
128
  if (issued >= tokenok) {
@@ -167,6 +173,14 @@ class SecretsTest {
167
173
  val name = if (auth is Map<*, *>) auth["name"] else null
168
174
  if (name is String && "" != name) name.lowercase() else "authorization"
169
175
  }
176
+
177
+ // The form prepareAuth writes, from the DEFAULT client's auth: under
178
+ // Basic the token is the key half of the encoded pair, and a prefix is
179
+ // space-joined.
180
+ val CREDFORM: Pair<String, Boolean> by lazy {
181
+ val auth = ProjectNameSDK.testSDK(null, null).optionsMap()["auth"] as? Map<*, *>
182
+ Pair(auth?.get("prefix") as? String ?: "", true == auth?.get("basic"))
183
+ }
170
184
  }
171
185
 
172
186
  // A sekreto Provider built in code.
@@ -178,14 +192,17 @@ class SecretsTest {
178
192
  override fun describe(): String = label
179
193
  }
180
194
 
181
- // The credential header carries the SPEC's credential prefix, which a
182
- // TEMPLATE cannot know: an OpenAPI `http`/`bearer` scheme gives
183
- // `Bearer <token>`, an apiKey scheme the raw token. So assert on the
184
- // CREDENTIAL and let the prefix be whatever this SDK's API declares.
185
- private fun credentialIs(header: String?, token: String) {
186
- val got = header ?: ""
187
- assertTrue(got == token || got.endsWith(" $token"),
188
- "expected the $CREDHEADER header to carry $token, got: \"$got\"")
195
+ // The header value prepareAuth writes for a token.
196
+ private fun credential(token: String, secret: String = ""): String {
197
+ val value = if (CREDFORM.second)
198
+ Base64.getEncoder().encodeToString("$token:$secret".toByteArray(Charsets.UTF_8))
199
+ else token
200
+ return if ("" == CREDFORM.first) value else CREDFORM.first + " " + value
201
+ }
202
+
203
+ private fun credentialIs(header: String?, token: String, secret: String = "") {
204
+ assertEquals(credential(token, secret), header,
205
+ "expected the $CREDHEADER header to carry $token")
189
206
  }
190
207
 
191
208
  private fun map(vararg pairs: Pair<String, Any?>): MutableMap<String, Any?> =
@@ -317,8 +334,12 @@ class SecretsTest {
317
334
 
318
335
  // Read from the config, never from a probe: an SDK whose config declares no
319
336
  // auth places no credential, and these tests assert on the one it places.
337
+ // The auth-off test asserts it places none.
320
338
  @BeforeEach
321
- fun placesCredential() {
339
+ fun placesCredential(test: TestInfo) {
340
+ if (true == test.testMethod.map { it.name.startsWith("authOff") }.orElse(false)) {
341
+ return
342
+ }
322
343
  Assumptions.assumeTrue(
323
344
  true == Helpers.toMapAny(Config.sharedConfig()["options"])?.containsKey("auth"),
324
345
  "this SDK's config declares no auth, so it places no credential",
@@ -408,6 +429,18 @@ class SecretsTest {
408
429
  credentialIs(w.api()[0].auth, "CHAINKEY03")
409
430
  }
410
431
 
432
+ @Test
433
+ fun aResolvedKeyIsPlacedAsPrepareAuthPlacesItTheSecretKept() {
434
+ val w = Wire()
435
+ val client = secretsClient(w, map(
436
+ "secret" to "PASS01",
437
+ "feature" to chainOpts(working("CHAINKEY05")),
438
+ ))
439
+
440
+ driveEntityOp(client, w)
441
+ credentialIs(w.api()[0].auth, "CHAINKEY05", "PASS01")
442
+ }
443
+
411
444
  @Test
412
445
  fun customProviderObjectsAreAcceptedVerbatim() {
413
446
  val asked = mutableListOf<String>()
@@ -1079,6 +1112,19 @@ class SecretsTest {
1079
1112
  assertEquals(true, res["ok"], "the caller sees the successful retry")
1080
1113
  }
1081
1114
 
1115
+ @Test
1116
+ fun aTokenBoughtOnARefusalIsPlacedAsPrepareAuthPlacesIt() {
1117
+ val w = Wire()
1118
+ w.apistatus = listOf(401, 200)
1119
+ val client = exchangeClient(w, "REFRESH01", null, map("secret" to "PASS01"))
1120
+
1121
+ client.direct(map("path" to "/thing"))
1122
+
1123
+ assertEquals(2, w.api().size, "expected the request to be retried")
1124
+ credentialIs(w.api()[0].auth, "ACCESS01", "PASS01")
1125
+ credentialIs(w.api()[1].auth, "ACCESS02", "PASS01")
1126
+ }
1127
+
1082
1128
  @Test
1083
1129
  fun theRetryHappensOnceNotInALoop() {
1084
1130
  val w = Wire()
@@ -1240,18 +1286,27 @@ class SecretsTest {
1240
1286
  assertEquals("test-access_token", secretsFeatureOf(client)!!.credential())
1241
1287
  }
1242
1288
 
1243
- // Real listeners and the SDK's raw HTTP path: a stub follows nothing.
1244
- @Test
1245
- fun aRedirectAnsweringTheExchangeIsAFailureAndNothingFollowsIt() {
1246
- val elsewhere = java.util.Collections.synchronizedList(mutableListOf<String>())
1247
- val followed = java.util.Collections.synchronizedList(mutableListOf<String>())
1248
- var answer: Pair<Int, String> = 307 to ""
1289
+ // Two real listeners and the SDK's raw HTTP path: a stub follows nothing.
1290
+ // The origin answers the exchange as `answer` says and records what else
1291
+ // it gets.
1292
+ private class Origins {
1293
+ val elsewhere: MutableList<String> = java.util.Collections.synchronizedList(mutableListOf<String>())
1294
+ val followed: MutableList<String> = java.util.Collections.synchronizedList(mutableListOf<String>())
1295
+ val exchanged = java.util.concurrent.atomic.AtomicInteger()
1296
+ @Volatile var answer: Pair<Int, String> = 307 to ""
1297
+ var origin = ""
1298
+ var base = ""
1299
+ var away = ""
1300
+ }
1301
+
1302
+ private fun withOrigins(run: (Origins) -> Unit) {
1303
+ val o = Origins()
1249
1304
 
1250
1305
  val other = com.sun.net.httpserver.HttpServer.create(
1251
1306
  java.net.InetSocketAddress("127.0.0.1", 0), 0)
1252
1307
  other.createContext("/") { ex ->
1253
1308
  val body = String(ex.requestBody.readAllBytes(), Charsets.UTF_8)
1254
- elsewhere.add(ex.requestMethod + " " + ex.requestURI.rawPath + " " + body)
1309
+ o.elsewhere.add(ex.requestMethod + " " + ex.requestURI.rawPath + " " + body)
1255
1310
  val out = "{\"access_token\":\"ELSEWHERE01\"}".toByteArray()
1256
1311
  ex.responseHeaders.set("Content-Type", "application/json")
1257
1312
  ex.sendResponseHeaders(200, out.size.toLong())
@@ -1261,14 +1316,17 @@ class SecretsTest {
1261
1316
  val origin = com.sun.net.httpserver.HttpServer.create(
1262
1317
  java.net.InetSocketAddress("127.0.0.1", 0), 0)
1263
1318
  origin.createContext("/") { ex ->
1264
- ex.requestBody.readAllBytes()
1265
- val path = ex.requestURI.rawPath
1319
+ val body = String(ex.requestBody.readAllBytes(), Charsets.UTF_8)
1320
+ val query = ex.requestURI.rawQuery
1321
+ val path = ex.requestURI.rawPath + (if (query == null) "" else "?" + query)
1266
1322
  if ("/api/auth/token" == path) {
1323
+ o.exchanged.incrementAndGet()
1324
+ val answer = o.answer
1267
1325
  ex.responseHeaders.set("Location", answer.second)
1268
1326
  ex.sendResponseHeaders(answer.first, -1)
1269
1327
  ex.close()
1270
1328
  } else {
1271
- followed.add(ex.requestMethod + " " + path)
1329
+ o.followed.add((ex.requestMethod + " " + path + " " + body).trim())
1272
1330
  val out = "{\"access_token\":\"MOVED01\"}".toByteArray()
1273
1331
  ex.responseHeaders.set("Content-Type", "application/json")
1274
1332
  ex.sendResponseHeaders(200, out.size.toLong())
@@ -1279,41 +1337,59 @@ class SecretsTest {
1279
1337
  other.start()
1280
1338
  origin.start()
1281
1339
 
1282
- val base = "http://127.0.0.1:" + origin.address.port + "/api"
1283
- val away = "http://127.0.0.1:" + other.address.port + "/api/auth/token"
1340
+ o.origin = "http://127.0.0.1:" + origin.address.port
1341
+ o.base = o.origin + "/api"
1342
+ o.away = "http://127.0.0.1:" + other.address.port + "/api/auth/token"
1284
1343
 
1285
1344
  try {
1286
- val answers = listOf(307 to away, 308 to away, 302 to away, 307 to "/api/moved/token")
1345
+ run(o)
1346
+ } finally {
1347
+ origin.stop(0)
1348
+ other.stop(0)
1349
+ }
1350
+ }
1351
+
1352
+ private fun redirectClient(o: Origins, exchange: Map<String, Any?> = mapOf()): ProjectNameSDK =
1353
+ withSecrets { extend ->
1354
+ val x = map("active" to true, "refresh" to "REFRESH01")
1355
+ x.putAll(exchange)
1356
+ val opts = map(
1357
+ "base" to o.base,
1358
+ "allow" to map("op" to "direct,graphql"),
1359
+ "feature" to map("secrets" to map(
1360
+ "active" to true,
1361
+ "name" to "refresh_token",
1362
+ "exchange" to x,
1363
+ )),
1364
+ )
1365
+ if (extend) {
1366
+ opts["extend"] = mutableListOf<Any?>(SecretsFeature())
1367
+ }
1368
+ ProjectNameSDK(opts)
1369
+ }
1370
+
1371
+ // The direct call's result, and its error message (the result when none).
1372
+ private fun directOutcome(client: ProjectNameSDK): Pair<Map<String, Any?>?, String> =
1373
+ try {
1374
+ val res = client.direct(map("path" to "/thing"))
1375
+ val err = res["err"] as? Throwable
1376
+ res to (if (null != err) messageOf(err) else res.toString())
1377
+ } catch (e: RuntimeException) {
1378
+ null to messageOf(e)
1379
+ }
1380
+
1381
+ @Test
1382
+ fun aRedirectAnsweringTheExchangeIsAFailureAndNothingFollowsIt() {
1383
+ withOrigins { o ->
1384
+ val answers = listOf(307 to o.away, 308 to o.away, 302 to o.away, 307 to "/api/moved/token")
1287
1385
  val allowed = mutableListOf<String>()
1288
1386
  var refused = 0
1289
1387
 
1290
1388
  for (a in answers) {
1291
- answer = a
1292
- val client = withSecrets { extend ->
1293
- val opts = map(
1294
- "base" to base,
1295
- "allow" to map("op" to "direct,graphql"),
1296
- "feature" to map("secrets" to map(
1297
- "active" to true,
1298
- "name" to "refresh_token",
1299
- "exchange" to map("active" to true, "refresh" to "REFRESH01"),
1300
- )),
1301
- )
1302
- if (extend) {
1303
- opts["extend"] = mutableListOf<Any?>(SecretsFeature())
1304
- }
1305
- ProjectNameSDK(opts)
1306
- }
1307
-
1308
- val message = try {
1309
- val res = client.direct(map("path" to "/thing"))
1310
- val err = res["err"] as? Throwable
1311
- if (null != err) messageOf(err) else res.toString()
1312
- } catch (e: RuntimeException) {
1313
- messageOf(e)
1314
- }
1389
+ o.answer = a
1390
+ val message = directOutcome(redirectClient(o)).second
1315
1391
 
1316
- if (message.contains("token exchange failed: " + a.first + " from " + base + "/auth/token")) {
1392
+ if (message.contains("token exchange failed: " + a.first + " from " + o.base + "/auth/token")) {
1317
1393
  refused++
1318
1394
  } else {
1319
1395
  allowed.add("" + a.first + " to " + a.second + ": " + message)
@@ -1321,15 +1397,121 @@ class SecretsTest {
1321
1397
  }
1322
1398
 
1323
1399
  println("secrets: exchange refused " + refused + " redirect(s), " +
1324
- (elsewhere.size + followed.size) + " followed")
1400
+ (o.elsewhere.size + o.followed.size) + " followed")
1325
1401
 
1326
- assertEquals(listOf<String>(), elsewhere.toList(), "the exchange reached another origin")
1327
- assertEquals(listOf<String>(), followed.toList(), "a request followed a refused exchange")
1402
+ assertEquals(listOf<String>(), o.elsewhere.toList(), "the exchange reached another origin")
1403
+ assertEquals(listOf<String>(), o.followed.toList(), "a request followed a refused exchange")
1328
1404
  assertEquals(listOf<String>(), allowed, "a redirect was not a failed exchange")
1329
1405
  assertEquals(answers.size, refused)
1330
- } finally {
1331
- origin.stop(0)
1332
- other.stop(0)
1333
1406
  }
1334
1407
  }
1408
+
1409
+ @Test
1410
+ fun withTheOptionARedirectOnTheExchangesOwnOriginIsFollowedAndNoOther() {
1411
+ withOrigins { o ->
1412
+ val sent = " {\"refresh_token\":\"REFRESH01\"}"
1413
+ // Each case: the status, the Location, and the path the exchange is
1414
+ // asked again at, or null where the redirect is refused.
1415
+ val cases = listOf<Triple<Int, String, String?>>(
1416
+ Triple(307, "/api/moved/token", "/api/moved/token"),
1417
+ Triple(308, o.origin + "/api/moved/token", "/api/moved/token"),
1418
+ // A Location of a query alone keeps the path that answered.
1419
+ Triple(307, "?step=2", "/api/auth/token?step=2"),
1420
+ Triple(307, o.away, null),
1421
+ Triple(302, "/api/moved/token", null),
1422
+ Triple(307, "/api/auth/token", null),
1423
+ )
1424
+
1425
+ val wrong = mutableListOf<String>()
1426
+ var followed = 0
1427
+ var refused = 0
1428
+ var looped = 0
1429
+
1430
+ for ((status, location, path) in cases) {
1431
+ o.answer = status to location
1432
+ o.followed.clear()
1433
+ o.exchanged.set(0)
1434
+
1435
+ val (res, message) = directOutcome(redirectClient(o, mapOf("redirect" to "same-origin")))
1436
+ val seen = "" + status + " to " + location + ": " + message + " " + o.followed.toList()
1437
+
1438
+ if (path != null) {
1439
+ if (true == res?.get("ok") && 2 == o.followed.size && "POST " + path + sent == o.followed[0]) {
1440
+ followed++
1441
+ } else {
1442
+ wrong.add(seen)
1443
+ }
1444
+ } else if (o.followed.isEmpty() && message.contains(
1445
+ "token exchange failed: " + status + " from " + o.base + "/auth/token")) {
1446
+ refused++
1447
+ } else {
1448
+ wrong.add(seen)
1449
+ }
1450
+
1451
+ if ("/api/auth/token" == location) {
1452
+ looped = o.exchanged.get()
1453
+ }
1454
+ }
1455
+
1456
+ println("secrets: exchange opt-in followed " + followed +
1457
+ " redirect(s) on its own origin, refused " + refused + ", " +
1458
+ o.elsewhere.size + " elsewhere")
1459
+
1460
+ assertEquals(listOf<String>(), o.elsewhere.toList(), "the exchange reached another origin")
1461
+ assertEquals(listOf<String>(), wrong)
1462
+ assertEquals(3, followed)
1463
+ assertEquals(3, refused)
1464
+ // A redirect to itself stops at the hop limit.
1465
+ assertEquals(6, looped)
1466
+ }
1467
+ }
1468
+
1469
+ // -------------------------------------------------------------------
1470
+ // Off by the config where it declares no auth, else by `auth: null`:
1471
+ // either way the feature places no credential, buys no token and retries
1472
+ // nothing.
1473
+
1474
+ @Test
1475
+ fun authOffPlacesNoCredentialAndBuysNoToken() {
1476
+ val declared = true == Helpers.toMapAny(Config.sharedConfig()["options"])?.containsKey("auth")
1477
+ val secrets = listOf("OFFKEY01", "OFFKEY02", "OFFREFRESH01", "ACCESS01")
1478
+ val carries = { call: Call -> call.hasAuth || secrets.any { call.values.contains(it) } }
1479
+ val sent = mutableListOf<Call>()
1480
+ var bought = 0
1481
+
1482
+ val refresh = TestProvider({ name -> if ("refresh_token" == name) "OFFREFRESH01" else null })
1483
+ val scenarios = listOf(
1484
+ Triple("a key the chain resolves", map("feature" to chainOpts(working("OFFKEY01"))), listOf(200)),
1485
+ Triple("an explicit apikey", map("apikey" to "OFFKEY02",
1486
+ "feature" to map("secrets" to map("active" to true))), listOf(200)),
1487
+ Triple("a refusal", map("feature" to chainOpts(refresh, map(
1488
+ "name" to "refresh_token", "exchange" to map("active" to true)))), listOf(401)),
1489
+ )
1490
+
1491
+ for ((what, sdkopts, statuses) in scenarios) {
1492
+ val w = Wire()
1493
+ w.apistatus = statuses
1494
+ val opts = map("allow" to map("op" to "direct,graphql"))
1495
+ opts.putAll(sdkopts)
1496
+ if (declared) {
1497
+ opts["auth"] = null
1498
+ }
1499
+ val client = secretsClient(w, opts)
1500
+
1501
+ client.direct(map("path" to "/thing"))
1502
+
1503
+ assertEquals(1, w.api().size, "$what: a request was retried with auth off")
1504
+ assertEquals(0, w.token().size, "$what: a token was bought with auth off")
1505
+ assertFalse(carries(w.api()[0]), "$what: a credential was sent with auth off: " + w.wire())
1506
+ assertEquals("", secretsFeatureOf(client)?.credential(),
1507
+ "$what: the feature resolved a credential with auth off")
1508
+
1509
+ sent.addAll(w.api())
1510
+ bought += w.token().size
1511
+ }
1512
+
1513
+ println("secrets: auth off by " + (if (declared) "option" else "config") + ": " +
1514
+ sent.size + " request(s), " + sent.count(carries) + " credential(s), " +
1515
+ bought + " token(s)")
1516
+ }
1335
1517
  }
@@ -114,7 +114,7 @@ internal fun followRedirects(
114
114
  val next: URI
115
115
  try {
116
116
  from = URI.create(url)
117
- next = from.resolve(URI.create(location.trim()))
117
+ next = resolveLocation(from, location)
118
118
  } catch (e: RuntimeException) {
119
119
  return res
120
120
  }
@@ -167,6 +167,18 @@ internal fun followRedirects(
167
167
 
168
168
  // For a caller with no operation context, as the secrets exchange is: a
169
169
  // redirect follows the same rules, a credential told by the clean defaults.
170
+ // A reference of a query alone keeps the path, as RFC 3986 resolves it;
171
+ // URI.resolve follows RFC 2396 there and drops the last segment.
172
+ fun resolveLocation(from: URI, location: String): URI {
173
+ val loc = location.trim()
174
+ if (loc.startsWith("?")) {
175
+ val base = from.toString()
176
+ val cut = base.indexOfAny(charArrayOf('?', '#'))
177
+ return URI.create((if (cut < 0) base else base.substring(0, cut)) + loc)
178
+ }
179
+ return from.resolve(URI.create(loc))
180
+ }
181
+
170
182
  fun defaultHttpFetch(fullurl: String, fetchdef: MutableMap<String, Any?>): MutableMap<String, Any?> =
171
183
  followRedirects(null, fullurl, fetchdef)
172
184
 
@@ -10,6 +10,7 @@
10
10
  -- body so both the original caller and later hits can parse repeatedly.
11
11
 
12
12
  local BaseFeature = require("feature.base_feature")
13
+ local media = require("utility.media")
13
14
 
14
15
  local CacheFeature = {}
15
16
  CacheFeature.__index = CacheFeature
@@ -85,6 +86,12 @@ function CacheFeature:_through(ctx, fullurl, fetchdef, inner)
85
86
 
86
87
  local res, err = inner(ctx, fullurl, fetchdef)
87
88
 
89
+ -- A body that declares another type than JSON passes by, unread.
90
+ if self:_cacheable(res, err) and not self:_json(res) then
91
+ self:_track("bypass")
92
+ return res, err
93
+ end
94
+
88
95
  if self:_cacheable(res, err) then
89
96
  local snapshot = self:_snapshot(res)
90
97
  local ttl = self.options["ttl"] == nil and 5000 or self.options["ttl"]
@@ -112,6 +119,19 @@ function CacheFeature:_cacheable(res, err)
112
119
  end
113
120
 
114
121
 
122
+ function CacheFeature:_json(res)
123
+ local ctype = ""
124
+ if type(res["headers"]) == "table" then
125
+ for k, v in pairs(res["headers"]) do
126
+ if type(k) == "string" and string.lower(k) == "content-type" then
127
+ ctype = tostring(v)
128
+ end
129
+ end
130
+ end
131
+ return ctype == "" or media.is_json_media(ctype)
132
+ end
133
+
134
+
115
135
  function CacheFeature:_snapshot(res)
116
136
  local data = nil
117
137
  local jf = res["json"]
@@ -64,6 +64,7 @@ local helpers = require("core.helpers")
64
64
  local BaseFeature = require("feature.base_feature")
65
65
  local sekreto = require("feature.secrets.sekreto")
66
66
  local tls = require("utility.tls")
67
+ local base64 = require("utility.clean").base64
67
68
 
68
69
 
69
70
  local SecretsFeature = {}
@@ -82,6 +83,34 @@ setmetatable(SecretsFeature, { __index = BaseFeature })
82
83
  local NOTAPROVIDER = "sekreto: not a provider or a provider spec: "
83
84
 
84
85
 
86
+ local REDIRECT_MAX = 5
87
+
88
+
89
+ local function origin(u)
90
+ local parsed = require("socket.url").parse(u) or {}
91
+ local scheme = string.lower(parsed.scheme or "")
92
+ return scheme .. "://" .. string.lower(parsed.host or "") .. ":" ..
93
+ tostring(parsed.port or (scheme == "https" and 443 or 80))
94
+ end
95
+
96
+
97
+ -- Where a redirect keeping method and body (307 or 308) points, on the
98
+ -- exchange's own origin. Any other would drop the body or leave the origin.
99
+ local function moved(url, at, res)
100
+ local status = type(res) == "table" and helpers.to_int(vs.getprop(res, "status")) or -1
101
+ local headers = type(res) == "table" and vs.getprop(res, "headers") or nil
102
+ local location = type(headers) == "table" and headers["location"] or nil
103
+ if (status ~= 307 and status ~= 308) or type(location) ~= "string" or location == "" then
104
+ return nil
105
+ end
106
+ local ok, next = pcall(function()
107
+ local resolved = require("socket.url").absolute(at, (string.gsub(location, "%s", "")))
108
+ return origin(resolved) == origin(url) and resolved or nil
109
+ end)
110
+ return ok and next or nil
111
+ end
112
+
113
+
85
114
  local function optstr(map, key, dflt)
86
115
  local v = map ~= nil and map[key] or nil
87
116
  if type(v) == "string" and v ~= "" then
@@ -139,6 +168,11 @@ function SecretsFeature.new()
139
168
  -- read for `apikey` and for the `auth` suppression, never written.
140
169
  self._liveopts = nil
141
170
 
171
+ -- What prepare_auth was generated from: the config declares auth only
172
+ -- where it places a credential, and Basic only where it composes one.
173
+ self._declared = false
174
+ self._basic = false
175
+
142
176
  self._secretname = "apikey"
143
177
  self._cache = true
144
178
  self._sek = nil
@@ -180,6 +214,10 @@ function SecretsFeature:init(ctx, options)
180
214
  self._rootctx = ctx
181
215
  self.active = (self.options["active"] == true)
182
216
 
217
+ local declared = vs.getpath(ctx.config, "options.auth")
218
+ self._declared = type(declared) == "table"
219
+ self._basic = self._declared and declared["basic"] == true
220
+
183
221
  if not self.active then
184
222
  return
185
223
  end
@@ -207,6 +245,7 @@ function SecretsFeature:init(ctx, options)
207
245
  response = optstr(xopts, "response", "access_token"),
208
246
  statuses = statuses,
209
247
  retries = optnum(xopts, "retries", 1),
248
+ redirect = xopts["redirect"] == "same-origin" and "same-origin" or "refuse",
210
249
  }
211
250
  end
212
251
 
@@ -363,8 +402,15 @@ function SecretsFeature:_resolve()
363
402
  end
364
403
 
365
404
 
405
+ -- prepare_auth's decision: auth the config declares, not suppressed by
406
+ -- clearing `options.auth`.
407
+ function SecretsFeature:_authon()
408
+ return self._declared and type(self._liveopts["auth"]) == "table"
409
+ end
410
+
411
+
366
412
  function SecretsFeature:_resolve_once()
367
- if self._sek == nil then
413
+ if self._sek == nil or not self:_authon() then
368
414
  return nil
369
415
  end
370
416
 
@@ -450,12 +496,9 @@ end
450
496
  -- fetchdef, because the header was built before this request left and it
451
497
  -- carries the token that just failed.
452
498
  function SecretsFeature:_with_refresh(ctx, fullurl, fetchdef, inner)
453
- -- A suppressed `auth` is the documented way to send NO credential, and
454
- -- prepare_auth honours it by removing the header. A refusal of a
455
- -- deliberately unauthenticated request is not an expired token and
456
- -- cannot be fixed by buying one - retrying would transmit exactly the
457
- -- credential the caller suppressed.
458
- if self._liveopts["auth"] == nil then
499
+ -- A refusal of an unauthenticated request is not an expired token, and
500
+ -- retrying would transmit the credential that auth off withholds.
501
+ if not self:_authon() then
459
502
  return inner(ctx, fullurl, fetchdef)
460
503
  end
461
504
 
@@ -527,11 +570,11 @@ function SecretsFeature:_reauth(fetchdef, token)
527
570
  -- stores no nil, and validate then fills the default), so the only
528
571
  -- expressible suppression is clearing `client.options.auth` after
529
572
  -- construction; this is the live table, so it is honoured here too.
530
- local auth = self._liveopts["auth"]
531
- if type(auth) ~= "table" then
573
+ if not self:_authon() then
532
574
  headers["authorization"] = nil
533
575
  return
534
576
  end
577
+ local auth = self._liveopts["auth"]
535
578
 
536
579
  -- The header prepare_auth writes: auth.name, lower-cased.
537
580
  local name = auth["name"]
@@ -540,16 +583,33 @@ function SecretsFeature:_reauth(fetchdef, token)
540
583
  end
541
584
  name = string.lower(name)
542
585
 
586
+ local value = token
587
+ if self._basic and auth["basic"] == true then
588
+ value = self:_pair(token)
589
+ end
590
+
543
591
  local prefix = auth["prefix"]
544
592
  if type(prefix) ~= "string" then
545
593
  prefix = ""
546
594
  end
547
595
 
548
596
  if prefix == "" then
549
- headers[name] = token
597
+ headers[name] = value
550
598
  else
551
- headers[name] = prefix .. " " .. token
599
+ headers[name] = prefix .. " " .. value
600
+ end
601
+ end
602
+
603
+
604
+ -- Under Basic the token is the key half, as apikey is: prepare_auth's pair.
605
+ function SecretsFeature:_pair(token)
606
+ local secret = self._liveopts["secret"]
607
+ if type(secret) ~= "string" then
608
+ secret = ""
552
609
  end
610
+ local pair = base64(token .. ":" .. secret)
611
+ self:_register(pair)
612
+ return pair
553
613
  end
554
614
 
555
615
 
@@ -613,7 +673,7 @@ local function raw_exchange_fetch(fullurl, fetchdef)
613
673
  end
614
674
 
615
675
  local chunks = {}
616
- local res, code = http.request({
676
+ local res, code, rawheaders = http.request({
617
677
  url = fullurl,
618
678
  method = fetchdef["method"] or "POST",
619
679
  headers = headers,
@@ -628,9 +688,14 @@ local function raw_exchange_fetch(fullurl, fetchdef)
628
688
  end
629
689
 
630
690
  local raw = table.concat(chunks)
691
+ local resheaders = {}
692
+ for k, v in pairs(type(rawheaders) == "table" and rawheaders or {}) do
693
+ resheaders[string.lower(k)] = v
694
+ end
631
695
 
632
696
  return {
633
697
  status = code,
698
+ headers = resheaders,
634
699
  json = function()
635
700
  if #raw == 0 then
636
701
  return nil
@@ -676,13 +741,25 @@ function SecretsFeature:_buy_once()
676
741
  -- The body is ENCODED, never concatenated: a refresh token (or a
677
742
  -- configured request-field name) carrying a quote, backslash or newline
678
743
  -- must arrive as that literal value, not as malformed JSON.
679
- local res, err = fetch(url, {
744
+ local fetchdef = {
680
745
  method = x.method,
681
746
  headers = { ["content-type"] = "application/json" },
682
747
  body = json.encode({ [x.request] = self._refresh }),
683
- -- Never followed: a redirect would carry the refresh token on.
748
+ -- Never followed by the client: a redirect would carry the refresh token on.
684
749
  redirect = "manual",
685
- })
750
+ }
751
+ local res, err = fetch(url, fetchdef)
752
+
753
+ -- By option alone, and only while the exchange stays on its own origin.
754
+ local at = url
755
+ for _ = 1, x.redirect == "same-origin" and REDIRECT_MAX or 0 do
756
+ local next = err == nil and moved(url, at, res) or nil
757
+ if next == nil then
758
+ break
759
+ end
760
+ at = next
761
+ res, err = fetch(at, fetchdef)
762
+ end
686
763
 
687
764
  if err ~= nil then
688
765
  return nil, sekreto.SekretoError(