@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
@@ -28,7 +28,8 @@
28
28
  // This file lives in the `feature/` container on purpose: it is per-feature
29
29
  // source, and travels with the feature.
30
30
 
31
- import java.util.{ArrayList, LinkedHashMap, List => JList, Map => JMap}
31
+ import java.nio.charset.StandardCharsets
32
+ import java.util.{ArrayList, Base64, LinkedHashMap, List => JList, Map => JMap}
32
33
  import java.util.function.{BiFunction, Supplier}
33
34
 
34
35
  import scala.collection.mutable.ListBuffer
@@ -68,23 +69,29 @@ object SecretsTestMain {
68
69
  private def eqi(name: String, exp: Int, act: Int): Unit =
69
70
  check(name, exp == act, "expected " + exp + ", got " + act)
70
71
 
71
- // The credential header carries the SPEC's credential prefix, which a
72
- // TEMPLATE cannot know: an OpenAPI `http`/`bearer` scheme gives `Bearer
73
- // <token>`, an apiKey scheme the raw token. So assert on the CREDENTIAL and
74
- // let the prefix be whatever this SDK's API declares - pinning the whole
75
- // header value passes only for a prefix-less API, and this file ships to
76
- // every project that selects the feature.
77
- // HTTP Basic carries base64(key:secret) instead, and scala ships this suite
78
- // untrimmed, so it also runs for a Basic API.
79
- private def credentialIs(name: String, header: String, token: String): Unit = {
80
- val got = if (header == null) "" else header
81
- val basic = got.startsWith("Basic ") && (try {
82
- new String(java.util.Base64.getDecoder.decode(got.substring(6)), "UTF-8").startsWith(token + ":")
83
- } catch { case _: IllegalArgumentException => false })
84
- check(name, got == token || got.endsWith(" " + token) || basic,
85
- "expected the " + CREDHEADER + " header to carry " + token + ", got \"" + got + "\"")
72
+ // The form prepareAuth writes, from the DEFAULT client's auth: under Basic
73
+ // the token is the key half of the encoded pair, and a prefix is
74
+ // space-joined.
75
+ private lazy val CREDFORM: (String, Boolean) =
76
+ ProjectNameSDK.testSDK(null, null).optionsMap().get("auth") match {
77
+ case auth: JMap[_, _] =>
78
+ (auth.get("prefix") match { case s: String => s; case _ => "" },
79
+ java.lang.Boolean.TRUE == auth.get("basic"))
80
+ case _ => ("", false)
81
+ }
82
+
83
+ // The header value prepareAuth writes for a token.
84
+ private def credential(token: String, secret: String): String = {
85
+ val value =
86
+ if (CREDFORM._2) Base64.getEncoder.encodeToString((token + ":" + secret).getBytes(StandardCharsets.UTF_8))
87
+ else token
88
+ if ("" == CREDFORM._1) value else CREDFORM._1 + " " + value
86
89
  }
87
90
 
91
+ private def credentialIs(name: String, header: String, token: String, secret: String = ""): Unit =
92
+ eqs(name, credential(token, secret), if (header == null) "" else header,
93
+ "the " + CREDHEADER + " header carries " + token)
94
+
88
95
  // ---- the recording transport --------------------------------------------
89
96
  //
90
97
  // system.fetch for a LIVE client: one status per API call (the last
@@ -115,6 +122,7 @@ object SecretsTestMain {
115
122
  case s: String => s
116
123
  case _ => ""
117
124
  })
125
+ call.put("values", headers.values().toArray.map(v => String.valueOf(v)).mkString("\n"))
118
126
  call.put("body", fetchdef.get("body") match { case s: String => s; case _ => "" })
119
127
  call.put("redirect", fetchdef.get("redirect"))
120
128
  calls.add(call)
@@ -396,6 +404,16 @@ object SecretsTestMain {
396
404
  client.optionsMap().get("apikey") match { case s: String => s; case _ => "" })
397
405
  }
398
406
 
407
+ private def testResolvedKeyPaired(): Unit = {
408
+ val w = new Wire()
409
+ val client = secretsClient(w,
410
+ "secret" -> "PASS01",
411
+ "feature" -> secretsOpts(memchain("APIKEY" -> "CHAINKEY05")))
412
+
413
+ check("chain.paired.drive", driveOneCall(client, w), "no entity op reached the transport")
414
+ if (w.api().nonEmpty) credentialIs("chain.paired", w.authof(w.api().head), "CHAINKEY05", "PASS01")
415
+ }
416
+
399
417
  private def testCustomProvider(): Unit = {
400
418
  val w = new Wire()
401
419
  val prov = working("CUSTOM01")
@@ -907,6 +925,21 @@ object SecretsTestMain {
907
925
  "the caller sees the successful retry, got " + res)
908
926
  }
909
927
 
928
+ private def testExchangeRetryPaired(): Unit = {
929
+ val w = new Wire()
930
+ w.apistatus = List(401, 200)
931
+
932
+ val client = secretsClient(w, "secret" -> "PASS01",
933
+ "allow" -> jmap("op" -> "direct"), "feature" -> exchangeOpts())
934
+ client.direct(jmap("path" -> "/thing"))
935
+
936
+ eqi("exchange.paired.retried", 2, w.api().length)
937
+ if (2 <= w.api().length) {
938
+ credentialIs("exchange.paired.first", w.authof(w.api()(0)), "ACCESS01", "PASS01")
939
+ credentialIs("exchange.paired.retry", w.authof(w.api()(1)), "ACCESS02", "PASS01")
940
+ }
941
+ }
942
+
910
943
  private def testExchangeOnePurchaseManyRequests(): Unit = {
911
944
  val w = new Wire()
912
945
  val client = secretsClient(w, "allow" -> jmap("op" -> "direct"), "feature" -> exchangeOpts())
@@ -1010,17 +1043,27 @@ object SecretsTestMain {
1010
1043
  "an empty chain must refuse rather than send unauthenticated, got " + res)
1011
1044
  }
1012
1045
 
1013
- // Real listeners and the SDK's raw HTTP path: a stub follows nothing.
1014
- private def testExchangeRedirectRefused(): Unit = {
1046
+ // Two real listeners and the SDK's raw HTTP path: a stub follows nothing.
1047
+ // The origin answers the exchange as `answer` says and records what else
1048
+ // it gets.
1049
+ private final class Origins {
1015
1050
  val elsewhere = java.util.Collections.synchronizedList(new ArrayList[String]())
1016
1051
  val followed = java.util.Collections.synchronizedList(new ArrayList[String]())
1052
+ val exchanged = new java.util.concurrent.atomic.AtomicInteger()
1017
1053
  @volatile var answer: (Int, String) = (307, "")
1054
+ var origin = ""
1055
+ var base = ""
1056
+ var away = ""
1057
+ }
1058
+
1059
+ private def withOrigins(run: Origins => Unit): Unit = {
1060
+ val o = new Origins()
1018
1061
 
1019
1062
  val other = com.sun.net.httpserver.HttpServer.create(
1020
1063
  new java.net.InetSocketAddress("127.0.0.1", 0), 0)
1021
1064
  other.createContext("/", (ex: com.sun.net.httpserver.HttpExchange) => {
1022
1065
  val body = new String(ex.getRequestBody.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)
1023
- elsewhere.add(ex.getRequestMethod + " " + ex.getRequestURI.getRawPath + " " + body)
1066
+ o.elsewhere.add(ex.getRequestMethod + " " + ex.getRequestURI.getRawPath + " " + body)
1024
1067
  val out = "{\"access_token\":\"ELSEWHERE01\"}".getBytes
1025
1068
  ex.getResponseHeaders.set("Content-Type", "application/json")
1026
1069
  ex.sendResponseHeaders(200, out.length.toLong)
@@ -1030,14 +1073,17 @@ object SecretsTestMain {
1030
1073
  val origin = com.sun.net.httpserver.HttpServer.create(
1031
1074
  new java.net.InetSocketAddress("127.0.0.1", 0), 0)
1032
1075
  origin.createContext("/", (ex: com.sun.net.httpserver.HttpExchange) => {
1033
- ex.getRequestBody.readAllBytes()
1034
- val path = ex.getRequestURI.getRawPath
1076
+ val body = new String(ex.getRequestBody.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)
1077
+ val query = ex.getRequestURI.getRawQuery
1078
+ val path = ex.getRequestURI.getRawPath + (if (query == null) "" else "?" + query)
1035
1079
  if ("/api/auth/token" == path) {
1080
+ o.exchanged.incrementAndGet()
1081
+ val answer = o.answer
1036
1082
  ex.getResponseHeaders.set("Location", answer._2)
1037
1083
  ex.sendResponseHeaders(answer._1, -1)
1038
1084
  ex.close()
1039
1085
  } else {
1040
- followed.add(ex.getRequestMethod + " " + path)
1086
+ o.followed.add((ex.getRequestMethod + " " + path + " " + body).trim)
1041
1087
  val out = "{\"access_token\":\"MOVED01\"}".getBytes
1042
1088
  ex.getResponseHeaders.set("Content-Type", "application/json")
1043
1089
  ex.sendResponseHeaders(200, out.length.toLong)
@@ -1048,60 +1094,123 @@ object SecretsTestMain {
1048
1094
  other.start()
1049
1095
  origin.start()
1050
1096
 
1051
- val base = "http://127.0.0.1:" + origin.getAddress.getPort + "/api"
1052
- val away = "http://127.0.0.1:" + other.getAddress.getPort + "/api/auth/token"
1097
+ o.origin = "http://127.0.0.1:" + origin.getAddress.getPort
1098
+ o.base = o.origin + "/api"
1099
+ o.away = "http://127.0.0.1:" + other.getAddress.getPort + "/api/auth/token"
1053
1100
 
1054
- try {
1055
- val answers = List((307, away), (308, away), (302, away), (307, "/api/moved/token"))
1056
- val allowed = ListBuffer.empty[String]
1057
- var refused = 0
1058
-
1059
- for (a <- answers) {
1060
- answer = a
1061
- val client = withSecrets { extend =>
1062
- val opts = jmap(
1063
- "base" -> base,
1064
- "allow" -> jmap("op" -> "direct"),
1065
- "feature" -> jmap("secrets" -> jmap(
1066
- "active" -> java.lang.Boolean.TRUE,
1067
- "name" -> "refresh_token",
1068
- "exchange" -> jmap("active" -> java.lang.Boolean.TRUE, "refresh" -> "REFRESH01"))))
1069
- if (extend) opts.put("extend", jlist(new SecretsFeature()))
1070
- new ProjectNameSDK(opts)
1071
- }
1101
+ try run(o)
1102
+ finally {
1103
+ origin.stop(0)
1104
+ other.stop(0)
1105
+ }
1106
+ }
1072
1107
 
1073
- val message =
1074
- try {
1075
- val res = client.direct(jmap("path" -> "/thing"))
1076
- res.get("err") match {
1077
- case err: Throwable => errtext(err)
1078
- case _ => String.valueOf(res)
1079
- }
1080
- }
1081
- catch { case err: RuntimeException => errtext(err) }
1082
-
1083
- if (message.contains("token exchange failed: " + a._1 + " from " + base + "/auth/token")) {
1084
- refused += 1
1085
- } else {
1086
- allowed += (a._1.toString + " to " + a._2 + ": " + message)
1087
- }
1108
+ private def redirectClient(o: Origins, exchange: (String, Object)*): ProjectNameSDK =
1109
+ withSecrets { extend =>
1110
+ val x = jmap("active" -> java.lang.Boolean.TRUE, "refresh" -> "REFRESH01")
1111
+ for ((k, v) <- exchange) x.put(k, v)
1112
+ val opts = jmap(
1113
+ "base" -> o.base,
1114
+ "allow" -> jmap("op" -> "direct"),
1115
+ "feature" -> jmap("secrets" -> jmap(
1116
+ "active" -> java.lang.Boolean.TRUE,
1117
+ "name" -> "refresh_token",
1118
+ "exchange" -> x)))
1119
+ if (extend) opts.put("extend", jlist(new SecretsFeature()))
1120
+ new ProjectNameSDK(opts)
1121
+ }
1122
+
1123
+ // The direct call's result, and its error message (the result when none).
1124
+ private def directOutcome(client: ProjectNameSDK): (JMap[String, Object], String) =
1125
+ try {
1126
+ val res = client.direct(jmap("path" -> "/thing"))
1127
+ res.get("err") match {
1128
+ case err: Throwable => (res, errtext(err))
1129
+ case _ => (res, String.valueOf(res))
1088
1130
  }
1131
+ }
1132
+ catch { case err: RuntimeException => (null, errtext(err)) }
1133
+
1134
+ private def testExchangeRedirectRefused(): Unit = withOrigins { o =>
1135
+ val answers = List((307, o.away), (308, o.away), (302, o.away), (307, "/api/moved/token"))
1136
+ val allowed = ListBuffer.empty[String]
1137
+ var refused = 0
1089
1138
 
1090
- println("secrets: exchange refused " + refused + " redirect(s), " +
1091
- (elsewhere.size() + followed.size()) + " followed")
1139
+ for (a <- answers) {
1140
+ o.answer = a
1141
+ val message = directOutcome(redirectClient(o))._2
1092
1142
 
1093
- check("exchange.redirect.elsewhere", elsewhere.isEmpty,
1094
- "the exchange reached another origin: " + elsewhere)
1095
- check("exchange.redirect.followed", followed.isEmpty,
1096
- "a request followed a refused exchange: " + followed)
1097
- check("exchange.redirect.allowed", allowed.isEmpty,
1098
- "a redirect was not a failed exchange: " + allowed.mkString("; "))
1099
- eqi("exchange.redirect.refused", answers.length, refused)
1143
+ if (message.contains("token exchange failed: " + a._1 + " from " + o.base + "/auth/token")) {
1144
+ refused += 1
1145
+ } else {
1146
+ allowed += (a._1.toString + " to " + a._2 + ": " + message)
1147
+ }
1100
1148
  }
1101
- finally {
1102
- origin.stop(0)
1103
- other.stop(0)
1149
+
1150
+ println("secrets: exchange refused " + refused + " redirect(s), " +
1151
+ (o.elsewhere.size() + o.followed.size()) + " followed")
1152
+
1153
+ check("exchange.redirect.elsewhere", o.elsewhere.isEmpty,
1154
+ "the exchange reached another origin: " + o.elsewhere)
1155
+ check("exchange.redirect.followed", o.followed.isEmpty,
1156
+ "a request followed a refused exchange: " + o.followed)
1157
+ check("exchange.redirect.allowed", allowed.isEmpty,
1158
+ "a redirect was not a failed exchange: " + allowed.mkString("; "))
1159
+ eqi("exchange.redirect.refused", answers.length, refused)
1160
+ }
1161
+
1162
+ private def testExchangeRedirectSameOrigin(): Unit = withOrigins { o =>
1163
+ val sent = " {\"refresh_token\":\"REFRESH01\"}"
1164
+ // Each case: the status, the Location, and the path the exchange is
1165
+ // asked again at, or null where the redirect is refused.
1166
+ val cases: List[(Int, String, String)] = List(
1167
+ (307, "/api/moved/token", "/api/moved/token"),
1168
+ (308, o.origin + "/api/moved/token", "/api/moved/token"),
1169
+ // A Location of a query alone keeps the path that answered.
1170
+ (307, "?step=2", "/api/auth/token?step=2"),
1171
+ (307, o.away, null),
1172
+ (302, "/api/moved/token", null),
1173
+ (307, "/api/auth/token", null),
1174
+ )
1175
+
1176
+ val wrong = ListBuffer.empty[String]
1177
+ var followed = 0
1178
+ var refused = 0
1179
+ var looped = 0
1180
+
1181
+ for ((status, location, path) <- cases) {
1182
+ o.answer = (status, location)
1183
+ o.followed.clear()
1184
+ o.exchanged.set(0)
1185
+
1186
+ val (res, message) = directOutcome(redirectClient(o, "redirect" -> "same-origin"))
1187
+ val seen = status.toString + " to " + location + ": " + message + " " + o.followed
1188
+
1189
+ if (path != null) {
1190
+ if (res != null && java.lang.Boolean.TRUE == res.get("ok") &&
1191
+ 2 == o.followed.size() && ("POST " + path + sent) == o.followed.get(0)) followed += 1
1192
+ else wrong += seen
1193
+ } else if (o.followed.isEmpty && message.contains(
1194
+ "token exchange failed: " + status + " from " + o.base + "/auth/token")) {
1195
+ refused += 1
1196
+ } else {
1197
+ wrong += seen
1198
+ }
1199
+
1200
+ if ("/api/auth/token" == location) looped = o.exchanged.get()
1104
1201
  }
1202
+
1203
+ println("secrets: exchange opt-in followed " + followed +
1204
+ " redirect(s) on its own origin, refused " + refused + ", " +
1205
+ o.elsewhere.size() + " elsewhere")
1206
+
1207
+ check("exchange.sameorigin.elsewhere", o.elsewhere.isEmpty,
1208
+ "the exchange reached another origin: " + o.elsewhere)
1209
+ check("exchange.sameorigin.wrong", wrong.isEmpty, wrong.mkString("; "))
1210
+ eqi("exchange.sameorigin.followed", 3, followed)
1211
+ eqi("exchange.sameorigin.refused", 3, refused)
1212
+ // A redirect to itself stops at the hop limit.
1213
+ eqi("exchange.sameorigin.looped", 6, looped)
1105
1214
  }
1106
1215
 
1107
1216
  // TEST MODE BUYS NOTHING and needs no token endpoint.
@@ -1115,18 +1224,61 @@ object SecretsTestMain {
1115
1224
  eqs("exchange.testmode.token", "test-access_token", secretsFeatureOf(client).credential())
1116
1225
  }
1117
1226
 
1227
+ // Off by the config where it declares no auth, else by `auth: null`: either
1228
+ // way the feature places no credential, buys no token and retries nothing.
1229
+ private def testAuthOff(declared: Boolean): Unit = {
1230
+ val secrets = List("OFFKEY01", "OFFKEY02", "OFFREFRESH01", "ACCESS01")
1231
+ def carries(call: JMap[String, Object]): Boolean = {
1232
+ val values = String.valueOf(call.get("values"))
1233
+ java.lang.Boolean.TRUE == call.get("has") || secrets.exists(s => values.contains(s))
1234
+ }
1235
+ val sent = ListBuffer.empty[JMap[String, Object]]
1236
+ var bought = 0
1237
+
1238
+ val scenarios: List[(String, List[(String, Object)], List[Int])] = List(
1239
+ ("a key the chain resolves",
1240
+ List("feature" -> secretsOpts(memchain("APIKEY" -> "OFFKEY01"))), List(200)),
1241
+ ("an explicit apikey",
1242
+ List("apikey" -> "OFFKEY02", "feature" -> secretsOpts(jlist())), List(200)),
1243
+ ("a refusal", List("feature" -> secretsOpts(memchain("REFRESH_TOKEN" -> "OFFREFRESH01"),
1244
+ "name" -> "refresh_token", "exchange" -> jmap("active" -> java.lang.Boolean.TRUE))), List(401)),
1245
+ )
1246
+
1247
+ for ((what, opts, statuses) <- scenarios) {
1248
+ val w = new Wire()
1249
+ w.apistatus = statuses
1250
+ val off: List[(String, Object)] = if (declared) List("auth" -> null) else Nil
1251
+ val client = secretsClient(w, (("allow" -> jmap("op" -> "direct")) :: opts ++ off)*)
1252
+
1253
+ client.direct(jmap("path" -> "/thing"))
1254
+
1255
+ eqi("authoff.noretry: " + what, 1, w.api().length)
1256
+ eqi("authoff.nobuy: " + what, 0, w.token().length)
1257
+ check("authoff.nocred: " + what, w.api().nonEmpty && !carries(w.api().head),
1258
+ "a credential was sent with auth off: " + w.report())
1259
+ eqs("authoff.unresolved: " + what, "", secretsFeatureOf(client).credential())
1260
+
1261
+ sent ++= w.api()
1262
+ bought += w.token().length
1263
+ }
1264
+
1265
+ println("secrets: auth off by " + (if (declared) "option" else "config") + ": " +
1266
+ sent.length + " request(s), " + sent.count(carries) + " credential(s), " +
1267
+ bought + " token(s)")
1268
+ }
1269
+
1118
1270
  // =========================================================================
1119
1271
 
1120
1272
  def main(args: Array[String]): Unit = {
1121
1273
  // Read from the config, never from a probe: an SDK whose config declares
1122
1274
  // no auth places no credential, and these tests assert on the one it places.
1123
- if (!SCALAPACKAGE.core.Config.sharedConfig().get("options").asInstanceOf[JMap[String, Object]]
1124
- .containsKey("auth")) {
1275
+ val declared = SCALAPACKAGE.core.Config.sharedConfig().get("options").asInstanceOf[JMap[String, Object]]
1276
+ .containsKey("auth")
1277
+ if (!declared) {
1125
1278
  println("SKIP secrets: this SDK's config declares no auth, so it places no credential")
1126
- return
1127
1279
  }
1128
1280
 
1129
- val cases: List[(String, () => Unit)] = List(
1281
+ val placing: List[(String, () => Unit)] = List(
1130
1282
  "inactive" -> testInactive,
1131
1283
  "optionWins" -> testOptionWins,
1132
1284
  "omittedDefers" -> testOmittedDefers,
@@ -1152,8 +1304,13 @@ object SecretsTestMain {
1152
1304
  "exchangeAuthNullNotRetried" -> testExchangeAuthNullNotRetried,
1153
1305
  "exchangeNoRefresh" -> testExchangeNoRefresh,
1154
1306
  "exchangeRedirectRefused" -> testExchangeRedirectRefused,
1307
+ "exchangeRedirectSameOrigin" -> testExchangeRedirectSameOrigin,
1155
1308
  "exchangeTestMode" -> testExchangeTestMode,
1309
+ "resolvedKeyPaired" -> testResolvedKeyPaired,
1310
+ "exchangeRetryPaired" -> testExchangeRetryPaired,
1156
1311
  )
1312
+ val cases: List[(String, () => Unit)] =
1313
+ (if (declared) placing else Nil) :+ ("authOff" -> (() => testAuthOff(declared)))
1157
1314
 
1158
1315
  for ((name, body) <- cases) {
1159
1316
  try body()
@@ -96,7 +96,7 @@ object Fetcher {
96
96
  var next: URI = null
97
97
  try {
98
98
  from = URI.create(fullurl)
99
- next = from.resolve(URI.create(location.asInstanceOf[String].trim))
99
+ next = resolveLocation(from, location.asInstanceOf[String])
100
100
  }
101
101
  catch { case _: RuntimeException => return res }
102
102
 
@@ -140,6 +140,18 @@ object Fetcher {
140
140
  followRedirects(ctx, next.toString, nextdef, hops + 1)
141
141
  }
142
142
 
143
+ // A reference of a query alone keeps the path, as RFC 3986 resolves it;
144
+ // URI.resolve follows RFC 2396 there and drops the last segment.
145
+ def resolveLocation(from: URI, location: String): URI = {
146
+ val loc = location.trim
147
+ if (loc.startsWith("?")) {
148
+ val base = from.toString
149
+ val cut = base.indexWhere(c => c == '?' || c == '#')
150
+ URI.create((if (cut < 0) base else base.substring(0, cut)) + loc)
151
+ }
152
+ else from.resolve(URI.create(loc))
153
+ }
154
+
143
155
  // For a caller with no operation context, as the secrets exchange is: a
144
156
  // redirect follows the same rules, a credential told by the clean defaults.
145
157
  def defaultHttpFetch(fullurl: String, fetchdef: JMap[String, Object]): JMap[String, Object] =
@@ -11,10 +11,5 @@ public final class Control {
11
11
  public var actor: String = ""
12
12
  public var paging: VMap? = nil
13
13
 
14
- // Outbound streaming marker: the entity `stream` method sets this to the
15
- // caller-supplied streamable payload so the request builder / transport can
16
- // stream it as the request body.
17
- public var streamOut: Value? = nil
18
-
19
14
  public init() {}
20
15
  }
@@ -87,6 +87,12 @@ public final class CacheFeature: BaseFeature {
87
87
  err = error
88
88
  }
89
89
 
90
+ // A body that declares another type than JSON passes by, unread.
91
+ if err == nil && CacheFeature.storable(res) && !CacheFeature.json(res) {
92
+ bypass += 1
93
+ return res
94
+ }
95
+
90
96
  if err == nil && CacheFeature.storable(res) {
91
97
  let snap = CacheFeature.snapshot(res)
92
98
  let ttl = foptInt(options, "ttl", 5000)
@@ -113,6 +119,11 @@ public final class CacheFeature: BaseFeature {
113
119
  return has && status >= 200 && status < 300 && gp(res, "unreadable") != .bool(true)
114
120
  }
115
121
 
122
+ private static func json(_ res: Value) -> Bool {
123
+ let type = Response.headerValue(gp(res, "headers"), "content-type")
124
+ return type.isEmpty || isJsonMedia(.string(type))
125
+ }
126
+
116
127
  private static func snapshot(_ res: Value) -> CacheSnapshot {
117
128
  let snap = CacheSnapshot()
118
129
 
@@ -78,6 +78,11 @@ public final class SecretsFeature: BaseFeature {
78
78
  // the client holds). READ ONLY: this feature never writes to it.
79
79
  private var liveopts: VMap = VMap()
80
80
 
81
+ // What prepareAuth was generated from: the config declares auth only
82
+ // where it places a credential, and Basic only where it composes one.
83
+ private var declared = false
84
+ private var basic = false
85
+
81
86
  private var secretname = "apikey"
82
87
  private var cache = true
83
88
  private var sek: Sekreto?
@@ -114,8 +119,11 @@ public final class SecretsFeature: BaseFeature {
114
119
  let response: String
115
120
  let statuses: [Int]
116
121
  let retries: Int
122
+ let sameOrigin: Bool
117
123
  }
118
124
 
125
+ private static let redirectMax = 5
126
+
119
127
  // One shared in-flight resolution: late arrivals wait on `done` and read
120
128
  // `err`.
121
129
  private final class SecretsCall {
@@ -171,6 +179,10 @@ public final class SecretsFeature: BaseFeature {
171
179
  liveopts = ctx.options ?? VMap()
172
180
  active = foptBool(options, "active", false)
173
181
 
182
+ let authdecl = gp(gp(ctx.config, "options"), "auth").asMap
183
+ declared = nil != authdecl
184
+ basic = true == gp(authdecl, "basic").asBool
185
+
174
186
  if !active {
175
187
  return
176
188
  }
@@ -196,7 +208,8 @@ public final class SecretsFeature: BaseFeature {
196
208
  request: foptStr(xopts, "request", "refresh_token"),
197
209
  response: foptStr(xopts, "response", "access_token"),
198
210
  statuses: statuses,
199
- retries: foptInt(xopts, "retries", 1))
211
+ retries: foptInt(xopts, "retries", 1),
212
+ sameOrigin: "same-origin" == foptStr(xopts, "redirect", "refuse"))
200
213
  }
201
214
 
202
215
  // WRAP FIRST, BUILD SECOND. The transport wrapper is the fail-closed
@@ -355,8 +368,14 @@ public final class SecretsFeature: BaseFeature {
355
368
  }
356
369
  }
357
370
 
371
+ // prepareAuth's decision: auth the config declares, not suppressed by
372
+ // `auth: null`.
373
+ private func authon() -> Bool {
374
+ return declared && !isNil(gp(liveopts, "auth"))
375
+ }
376
+
358
377
  private func resolveonce() throws {
359
- guard let s = sek else {
378
+ guard let s = sek, authon() else {
360
379
  return
361
380
  }
362
381
 
@@ -439,12 +458,9 @@ public final class SecretsFeature: BaseFeature {
439
458
  // request left, and it carries the token that just failed.
440
459
  private func withrefresh(_ ctx: Context, _ url: String, _ fetchdef: VMap,
441
460
  _ inner: FetcherFunc) throws -> Value {
442
- // `auth: null` is the documented way to send NO credential, and
443
- // prepareAuth honours it by removing the header. A refusal of a
444
- // deliberately unauthenticated request is not an expired token and
445
- // cannot be fixed by buying one - retrying would transmit exactly the
446
- // credential the caller suppressed.
447
- if isNil(gp(liveopts, "auth")) {
461
+ // A refusal of an unauthenticated request is not an expired token, and
462
+ // retrying would transmit the credential that auth off withholds.
463
+ if !authon() {
448
464
  return try inner(ctx, url, fetchdef)
449
465
  }
450
466
 
@@ -521,7 +537,7 @@ public final class SecretsFeature: BaseFeature {
521
537
  // where the rule has to hold. The options map is FROZEN after
522
538
  // construction (this feature never writes it), so the raw read is safe
523
539
  // on any thread.
524
- guard let auth = gp(liveopts, "auth").asMap else {
540
+ guard authon(), let auth = gp(liveopts, "auth").asMap else {
525
541
  headers.entries.removeValue(forKey: "authorization")
526
542
  return
527
543
  }
@@ -530,10 +546,20 @@ public final class SecretsFeature: BaseFeature {
530
546
  let rawname = gp(auth, "name").asString ?? ""
531
547
  let name = "" == rawname ? "authorization" : rawname.lowercased()
532
548
 
549
+ let value = basic && true == gp(auth, "basic").asBool ? pair(token) : token
550
+
533
551
  let prefix = gp(auth, "prefix").asString ?? ""
534
552
  // Empty prefix (raw apiKey credential) must not add a leading space -
535
553
  // prepareAuth's rule, repeated here because this is the other writer.
536
- headers.entries[name] = .string("" == prefix ? token : prefix + " " + token)
554
+ headers.entries[name] = .string("" == prefix ? value : prefix + " " + value)
555
+ }
556
+
557
+ // Under Basic the token is the key half, as apikey is: prepareAuth's pair.
558
+ private func pair(_ token: String) -> String {
559
+ let secret = gp(liveopts, "secret").asString ?? ""
560
+ let pair = Data((token + ":" + secret).utf8).base64EncodedString()
561
+ register(pair)
562
+ return pair
537
563
  }
538
564
 
539
565
  // buy an access token with the refresh token. Concurrent callers share the
@@ -624,7 +650,7 @@ public final class SecretsFeature: BaseFeature {
624
650
  fetchdef.entries["method"] = .string(x.method)
625
651
  fetchdef.entries["headers"] = .map(vm(("content-type", .string("application/json"))))
626
652
  fetchdef.entries["body"] = .string(body)
627
- // Never followed: a redirect would carry the refresh token on.
653
+ // Never followed by the client: a redirect would carry the refresh token on.
628
654
  fetchdef.entries["redirect"] = .string("manual")
629
655
 
630
656
  // Deliberately NOT the SDK transport. The transport is what this feature
@@ -636,11 +662,22 @@ public final class SecretsFeature: BaseFeature {
636
662
  // rawExchangeFetch twin, unlike go); a supplied system.fetch is honoured
637
663
  // so a test can intercept the purchase.
638
664
  let sysFetch = gpath(options, "system", "fetch")
639
- let res: Value
640
- if let fn = sysFetch.asNative as? SystemFetch {
641
- res = fn(url, fetchdef)
642
- } else {
643
- res = try defaultHttpFetch(url, fetchdef)
665
+ func fetch(_ at: String) throws -> Value {
666
+ if let fn = sysFetch.asNative as? SystemFetch {
667
+ return fn(at, fetchdef)
668
+ }
669
+ return try defaultHttpFetch(at, fetchdef)
670
+ }
671
+
672
+ var res = try fetch(url)
673
+
674
+ // By option alone, and only while the exchange stays on its own origin.
675
+ var at = url
676
+ var hops = 0
677
+ while x.sameOrigin, hops < SecretsFeature.redirectMax, let next = SecretsFeature.moved(url, at, res) {
678
+ at = next
679
+ res = try fetch(at)
680
+ hops += 1
644
681
  }
645
682
 
646
683
  let (status, _) = fresStatus(res)
@@ -668,6 +705,29 @@ public final class SecretsFeature: BaseFeature {
668
705
  return token
669
706
  }
670
707
 
708
+ // Where a redirect that keeps method and body points, when that is on the
709
+ // exchange's own origin. Any other would drop the body or leave the origin.
710
+ private static func moved(_ url: String, _ at: String, _ res: Value) -> String? {
711
+ let (status, _) = fresStatus(res)
712
+ let (location, has) = fresHeader(res, "location")
713
+ guard 307 == status || 308 == status, has, "" != location,
714
+ let next = resolveLocation(at, location),
715
+ let own = origin(url), own == origin(next)
716
+ else {
717
+ return nil
718
+ }
719
+ return next
720
+ }
721
+
722
+ private static func origin(_ url: String) -> String? {
723
+ guard let parts = URLComponents(string: url), let scheme = parts.scheme?.lowercased(),
724
+ let host = parts.host?.lowercased()
725
+ else {
726
+ return nil
727
+ }
728
+ return "\(scheme)://\(host):\(parts.port ?? (scheme == "https" ? 443 : 80))"
729
+ }
730
+
671
731
  // An SDK Value (a plain map from the options) as the plugin host's own
672
732
  // value model, which is what sekreto's `specof` reads. QUALIFIED, because
673
733
  // this file sees both libraries' `Value` and the SDK's own wins unqualified.