@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
@@ -81,6 +81,7 @@ class ProjectNameSecretsWire
81
81
  'url' => $fullurl,
82
82
  'auth' => $headers[self::credheader()] ?? null,
83
83
  'has' => array_key_exists(self::credheader(), $headers),
84
+ 'values' => implode("\n", array_map(fn($v) => is_scalar($v) ? (string)$v : '', $headers)),
84
85
  'body' => $fetchdef['body'] ?? null,
85
86
  'redirect' => $fetchdef['redirect'] ?? null,
86
87
  ];
@@ -134,8 +135,13 @@ class ProjectNameSecretsTest extends TestCase
134
135
 
135
136
  // Read from the config, never from a probe: an SDK whose config declares no
136
137
  // auth places no credential, and these tests assert on the one it places.
138
+ // The auth-off test asserts it places none.
137
139
  protected function setUp(): void
138
140
  {
141
+ $test = method_exists($this, 'name') ? $this->name() : $this->getName();
142
+ if ('testAuthOffPlacesNoCredentialAndBuysNoToken' === $test) {
143
+ return;
144
+ }
139
145
  if (!array_key_exists('auth', ProjectNameConfig::shared_config()['options'] ?? [])) {
140
146
  $this->markTestSkipped("this SDK's config declares no auth, so it places no credential");
141
147
  }
@@ -164,17 +170,23 @@ class ProjectNameSecretsTest extends TestCase
164
170
  // -----------------------------------------------------------------
165
171
  // Support.
166
172
 
167
- // The credential header carries the SPEC's credential prefix (if any),
168
- // which a TEMPLATE cannot know - so assert on the CREDENTIAL and let
169
- // the prefix be whatever this SDK's API declares.
170
- private function assertCredential(mixed $header, string $token): void
173
+ // The header value prepare_auth writes for a token, in the form the
174
+ // DEFAULT client's auth gives: under Basic the token is the key half of
175
+ // the encoded pair, and a prefix is space-joined.
176
+ private function credential(string $token, string $secret = ''): string
177
+ {
178
+ $auth = ProjectNameSDK::test(null, null)->options_map()['auth'] ?? [];
179
+ $prefix = is_string($auth['prefix'] ?? null) ? $auth['prefix'] : '';
180
+ $value = true === ($auth['basic'] ?? null)
181
+ ? base64_encode($token . ':' . $secret) : $token;
182
+ return '' === $prefix ? $value : $prefix . ' ' . $value;
183
+ }
184
+
185
+ private function assertCredential(mixed $header, string $token, string $secret = ''): void
171
186
  {
172
- $ok = $header === $token
173
- || (is_string($header) && str_ends_with($header, ' ' . $token));
174
- $this->assertTrue($ok,
187
+ $this->assertSame($this->credential($token, $secret), $header,
175
188
  'expected the ' . ProjectNameSecretsWire::credheader() .
176
- ' header to carry ' . $token .
177
- ', got: ' . var_export($header, true));
189
+ ' header to carry ' . $token);
178
190
  }
179
191
 
180
192
  private function secretsFeatureOf($client): ?ProjectNameSecretsFeature
@@ -395,6 +407,19 @@ class ProjectNameSecretsTest extends TestCase
395
407
  'the chain credential must never be written into the client options');
396
408
  }
397
409
 
410
+ public function testAResolvedKeyIsPlacedAsPrepareAuthPlacesItTheSecretKept(): void
411
+ {
412
+ $this->setenv('APIKEY', 'ENVKEY04');
413
+ $wire = new ProjectNameSecretsWire();
414
+ $client = $this->secretsClient($wire, [
415
+ 'secret' => 'PASS01',
416
+ 'feature' => $this->secretsOpts(),
417
+ ]);
418
+
419
+ $this->driveOp($client, $wire);
420
+ $this->assertCredential($wire->api()[0]['auth'], 'ENVKEY04', 'PASS01');
421
+ }
422
+
398
423
  // The same pin where it matters most: `auth: null` is the caller saying
399
424
  // NO credential may be sent. Nothing goes on the wire - and nothing is
400
425
  // parked in the options map either, where it would outlive the request
@@ -819,6 +844,28 @@ class ProjectNameSecretsTest extends TestCase
819
844
  $this->assertCredential($api[1]['auth'], 'ACCESS02');
820
845
  }
821
846
 
847
+ public function testATokenBoughtOnARefusalIsPlacedAsPrepareAuthPlacesIt(): void
848
+ {
849
+ $this->setenv('REFRESH_TOKEN', 'REFRESH01');
850
+ $wire = new ProjectNameSecretsWire();
851
+ $wire->apistatus = [401, 200];
852
+
853
+ $client = $this->secretsClient($wire, [
854
+ 'secret' => 'PASS01',
855
+ 'feature' => $this->secretsOpts([
856
+ 'name' => 'refresh_token',
857
+ 'exchange' => ['active' => true],
858
+ ]),
859
+ ]);
860
+
861
+ $this->driveOp($client, $wire);
862
+
863
+ $api = $wire->api();
864
+ $this->assertCount(2, $api, 'expected the request to be retried exactly once');
865
+ $this->assertCredential($api[0]['auth'], 'ACCESS01', 'PASS01');
866
+ $this->assertCredential($api[1]['auth'], 'ACCESS02', 'PASS01');
867
+ }
868
+
822
869
  // `auth: null` SUPPRESSES THE PURCHASE, not just the retry.
823
870
  //
824
871
  // resolve() runs before with_refresh's suppression check, so the
@@ -994,17 +1041,18 @@ class ProjectNameSecretsTest extends TestCase
994
1041
  $this->assertNull($leak, 'the stub outlived stop(): ' . (string)$leak);
995
1042
  }
996
1043
 
997
- // Real listeners and the SDK's raw HTTP function: a stub follows nothing.
998
- // Its own process, for the reason the test above gives.
999
- #[\PHPUnit\Framework\Attributes\RunInSeparateProcess]
1000
- #[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
1001
- public function testARedirectAnsweringTheExchangeIsAFailureAndNothingFollowsIt(): void
1044
+ // Real listeners and the SDK's raw HTTP function: a stub follows
1045
+ // nothing. The origin answers the exchange as its `answer.txt` says and
1046
+ // records what else it gets; `exchanged.txt` counts the exchanges.
1047
+ private function withOrigins(callable $run): void
1002
1048
  {
1003
1049
  $record = <<<'ROUTER'
1004
1050
  <?php
1005
- $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';
1051
+ // The request target, query included: only the bare token path is the exchange.
1052
+ $path = (string)($_SERVER['REQUEST_URI'] ?? '/');
1006
1053
  $answer = @file_get_contents(__DIR__ . '/answer.txt');
1007
1054
  if (false !== $answer && '/api/auth/token' === $path) {
1055
+ file_put_contents(__DIR__ . '/exchanged.txt', 'x', FILE_APPEND);
1008
1056
  [$status, $location] = explode(' ', $answer, 2);
1009
1057
  header('location: ' . $location, true, (int)$status);
1010
1058
  return;
@@ -1026,38 +1074,71 @@ ROUTER;
1026
1074
  if (0 === $oport || 0 === $aport) {
1027
1075
  $this->markTestSkipped('could not start the local HTTP stubs');
1028
1076
  }
1029
- $base = 'http://127.0.0.1:' . $oport . '/api';
1030
- $away = 'http://127.0.0.1:' . $aport . '/api/auth/token';
1077
+ $run((object)[
1078
+ 'origin' => $origin,
1079
+ 'other' => $other,
1080
+ 'at' => 'http://127.0.0.1:' . $oport,
1081
+ 'base' => 'http://127.0.0.1:' . $oport . '/api',
1082
+ 'away' => 'http://127.0.0.1:' . $aport . '/api/auth/token',
1083
+ ]);
1084
+ } finally {
1085
+ $origin->stop();
1086
+ $other->stop();
1087
+ }
1088
+ }
1089
+
1090
+ private function redirectClient(string $base, array $exchange = [])
1091
+ {
1092
+ return $this->withSecrets(function (bool $adopt) use ($base, $exchange) {
1093
+ $opts = [
1094
+ 'base' => $base,
1095
+ 'feature' => ['secrets' => [
1096
+ 'active' => true,
1097
+ 'name' => 'refresh_token',
1098
+ 'exchange' => array_merge(['active' => true, 'refresh' => 'REFRESH01'], $exchange),
1099
+ ]],
1100
+ ];
1101
+ if ($adopt) {
1102
+ $opts['extend'] = [new ProjectNameSecretsFeature()];
1103
+ }
1104
+ return new ProjectNameSDK($opts);
1105
+ });
1106
+ }
1107
+
1108
+ private function redirectProbe($client): array
1109
+ {
1110
+ try {
1111
+ $res = $client->direct(['path' => '/probe']);
1112
+ $message = is_array($res) && null !== ($res['err'] ?? null)
1113
+ ? (string)(($res['err'] instanceof \Throwable) ? $res['err']->getMessage() : $res['err'])
1114
+ : json_encode($res);
1115
+ return [$res, $message];
1116
+ } catch (\Throwable $e) {
1117
+ return [null, $e->getMessage()];
1118
+ }
1119
+ }
1120
+
1121
+ private static function lines(?string $text): array
1122
+ {
1123
+ return array_values(array_filter(explode("\n", (string)$text)));
1124
+ }
1125
+
1126
+ // Its own process, for the reason the test above gives.
1127
+ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess]
1128
+ #[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
1129
+ public function testARedirectAnsweringTheExchangeIsAFailureAndNothingFollowsIt(): void
1130
+ {
1131
+ $this->withOrigins(function (object $o) {
1132
+ $base = $o->base;
1133
+ $away = $o->away;
1031
1134
  $answers = [[307, $away], [308, $away], [302, $away], [307, '/api/moved/token']];
1032
1135
 
1033
1136
  $allowed = [];
1034
1137
  $refused = 0;
1035
1138
 
1036
1139
  foreach ($answers as [$status, $location]) {
1037
- $origin->put('answer.txt', $status . ' ' . $location);
1038
- $client = $this->withSecrets(function (bool $adopt) use ($base) {
1039
- $opts = [
1040
- 'base' => $base,
1041
- 'feature' => ['secrets' => [
1042
- 'active' => true,
1043
- 'name' => 'refresh_token',
1044
- 'exchange' => ['active' => true, 'refresh' => 'REFRESH01'],
1045
- ]],
1046
- ];
1047
- if ($adopt) {
1048
- $opts['extend'] = [new ProjectNameSecretsFeature()];
1049
- }
1050
- return new ProjectNameSDK($opts);
1051
- });
1052
-
1053
- try {
1054
- $res = $client->direct(['path' => '/probe']);
1055
- $message = is_array($res) && null !== ($res['err'] ?? null)
1056
- ? (string)(($res['err'] instanceof \Throwable) ? $res['err']->getMessage() : $res['err'])
1057
- : json_encode($res);
1058
- } catch (\Throwable $e) {
1059
- $message = $e->getMessage();
1060
- }
1140
+ $o->origin->put('answer.txt', $status . ' ' . $location);
1141
+ [, $message] = $this->redirectProbe($this->redirectClient($base));
1061
1142
 
1062
1143
  if (str_contains($message,
1063
1144
  'token exchange failed: ' . $status . ' from ' . $base . '/auth/token')) {
@@ -1067,8 +1148,8 @@ ROUTER;
1067
1148
  }
1068
1149
  }
1069
1150
 
1070
- $elsewhere = array_values(array_filter(explode("\n", (string)$other->read('seen.txt'))));
1071
- $followed = array_values(array_filter(explode("\n", (string)$origin->read('seen.txt'))));
1151
+ $elsewhere = self::lines($o->other->read('seen.txt'));
1152
+ $followed = self::lines($o->origin->read('seen.txt'));
1072
1153
 
1073
1154
  print("\nsecrets: exchange refused " . $refused . ' redirect(s), ' .
1074
1155
  (count($elsewhere) + count($followed)) . " followed\n");
@@ -1077,10 +1158,77 @@ ROUTER;
1077
1158
  $this->assertSame([], $followed, 'a request followed a refused exchange');
1078
1159
  $this->assertSame([], $allowed, 'a redirect was not a failed exchange');
1079
1160
  $this->assertSame(count($answers), $refused);
1080
- } finally {
1081
- $origin->stop();
1082
- $other->stop();
1083
- }
1161
+ });
1162
+ }
1163
+
1164
+ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess]
1165
+ #[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
1166
+ public function testWithTheOptionARedirectOnTheExchangesOwnOriginIsFollowedAndNoOther(): void
1167
+ {
1168
+ $this->withOrigins(function (object $o) {
1169
+ $sent = ' {"refresh_token":"REFRESH01"}';
1170
+ // Each case: the status, the Location, and the path the exchange
1171
+ // is asked again at, or null where the redirect is refused.
1172
+ $cases = [
1173
+ [307, '/api/moved/token', '/api/moved/token'],
1174
+ [308, $o->at . '/api/moved/token', '/api/moved/token'],
1175
+ // A Location of a query alone keeps the path that answered.
1176
+ [307, '?step=2', '/api/auth/token?step=2'],
1177
+ [307, $o->away, null],
1178
+ [302, '/api/moved/token', null],
1179
+ [307, '/api/auth/token', null],
1180
+ ];
1181
+
1182
+ $wrong = [];
1183
+ $followed = 0;
1184
+ $refused = 0;
1185
+ $looped = 0;
1186
+
1187
+ foreach ($cases as [$status, $location, $path]) {
1188
+ $o->origin->put('answer.txt', $status . ' ' . $location);
1189
+ $o->origin->put('seen.txt', '');
1190
+ $o->origin->put('exchanged.txt', '');
1191
+
1192
+ [$res, $message] = $this->redirectProbe(
1193
+ $this->redirectClient($o->base, ['redirect' => 'same-origin']));
1194
+ $seen = array_map(function (string $line) {
1195
+ $r = json_decode($line, true);
1196
+ return trim($r['method'] . ' ' . $r['path'] . ' ' . $r['body']);
1197
+ }, self::lines($o->origin->read('seen.txt')));
1198
+ $shown = $status . ' to ' . $location . ': ' . $message . ' ' . json_encode($seen);
1199
+
1200
+ if (null !== $path) {
1201
+ if (is_array($res) && true === ($res['ok'] ?? null) &&
1202
+ 2 === count($seen) && 'POST ' . $path . $sent === $seen[0]) {
1203
+ $followed++;
1204
+ } else {
1205
+ $wrong[] = $shown;
1206
+ }
1207
+ } elseif (0 === count($seen) && str_contains($message,
1208
+ 'token exchange failed: ' . $status . ' from ' . $o->base . '/auth/token')) {
1209
+ $refused++;
1210
+ } else {
1211
+ $wrong[] = $shown;
1212
+ }
1213
+
1214
+ if ('/api/auth/token' === $location) {
1215
+ $looped = strlen((string)$o->origin->read('exchanged.txt'));
1216
+ }
1217
+ }
1218
+
1219
+ $elsewhere = self::lines($o->other->read('seen.txt'));
1220
+
1221
+ print("\nsecrets: exchange opt-in followed " . $followed .
1222
+ ' redirect(s) on its own origin, refused ' . $refused . ', ' .
1223
+ count($elsewhere) . " elsewhere\n");
1224
+
1225
+ $this->assertSame([], $elsewhere, 'the exchange reached another origin');
1226
+ $this->assertSame([], $wrong);
1227
+ $this->assertSame(3, $followed);
1228
+ $this->assertSame(3, $refused);
1229
+ // A redirect to itself is followed up to the hop limit and no more.
1230
+ $this->assertSame(6, $looped);
1231
+ });
1084
1232
  }
1085
1233
 
1086
1234
  // -----------------------------------------------------------------
@@ -1108,6 +1256,66 @@ ROUTER;
1108
1256
  $this->assertSame(1, $calls, 'the refusal must not be retried');
1109
1257
  $this->assertCount(0, $wire->calls);
1110
1258
  }
1259
+
1260
+ // -----------------------------------------------------------------
1261
+ // Off by the config where it declares no auth, else by `auth: null`:
1262
+ // either way the feature places no credential, buys no token and
1263
+ // retries nothing.
1264
+
1265
+ public function testAuthOffPlacesNoCredentialAndBuysNoToken(): void
1266
+ {
1267
+ $declared = array_key_exists('auth', ProjectNameConfig::shared_config()['options'] ?? []);
1268
+ $by = $declared ? 'option' : 'config';
1269
+ $off = $declared ? ['auth' => null] : [];
1270
+ $secrets = ['OFFKEY01', 'OFFKEY02', 'OFFREFRESH01', 'ACCESS01'];
1271
+ $carries = function (array $call) use ($secrets): bool {
1272
+ if ($call['has']) {
1273
+ return true;
1274
+ }
1275
+ foreach ($secrets as $secret) {
1276
+ if (str_contains((string)$call['values'], $secret)) {
1277
+ return true;
1278
+ }
1279
+ }
1280
+ return false;
1281
+ };
1282
+ $sent = [];
1283
+ $bought = 0;
1284
+
1285
+ $scenarios = [
1286
+ ['a key the chain resolves', ['APIKEY' => 'OFFKEY01'], [], [], [200]],
1287
+ ['an explicit apikey', [], ['apikey' => 'OFFKEY02'], [], [200]],
1288
+ ['a refusal', ['REFRESH_TOKEN' => 'OFFREFRESH01'], [],
1289
+ ['name' => 'refresh_token', 'exchange' => ['active' => true]], [401]],
1290
+ ];
1291
+
1292
+ foreach ($scenarios as [$what, $env, $sdkopts, $fopts, $statuses]) {
1293
+ foreach ($env as $name => $value) {
1294
+ $this->setenv($name, $value);
1295
+ }
1296
+ $wire = new ProjectNameSecretsWire();
1297
+ $wire->apistatus = $statuses;
1298
+ $client = $this->secretsClient($wire,
1299
+ array_merge($sdkopts, $off, ['feature' => $this->secretsOpts($fopts)]));
1300
+
1301
+ $this->driveOp($client, $wire);
1302
+
1303
+ $this->assertCount(1, $wire->api(), $what . ': a request was retried with auth off');
1304
+ $this->assertCount(0, $wire->token(), $what . ': a token was bought with auth off');
1305
+ $this->assertFalse($carries($wire->api()[0]), $what . ': a credential was sent with auth off');
1306
+ $this->assertSame('', $this->secretsFeatureOf($client)->credential(),
1307
+ $what . ': the feature resolved a credential with auth off');
1308
+
1309
+ $sent = array_merge($sent, $wire->api());
1310
+ $bought += count($wire->token());
1311
+ foreach ($env as $name => $value) {
1312
+ $this->clearenv($name);
1313
+ }
1314
+ }
1315
+
1316
+ print("\nsecrets: auth off by " . $by . ': ' . count($sent) . ' request(s), ' .
1317
+ count(array_filter($sent, $carries)) . ' credential(s), ' . $bought . " token(s)\n");
1318
+ }
1111
1319
  }
1112
1320
 
1113
1321
  // A one-request-at-a-time HTTP stand-in, run as a child `php -S` process:
@@ -1194,8 +1402,10 @@ ROUTER;
1194
1402
  // harness that captures output must not end up waiting on the
1195
1403
  // server's.
1196
1404
  $pipes = [];
1405
+ // Windows names its null device NUL, and has no /dev/null to open.
1406
+ $null = '\\' === DIRECTORY_SEPARATOR ? 'NUL' : '/dev/null';
1197
1407
  $this->proc = @proc_open($cmd, [
1198
- 0 => ['file', '/dev/null', 'r'],
1408
+ 0 => ['file', $null, 'r'],
1199
1409
  1 => ['file', $this->dir . '/out.log', 'a'],
1200
1410
  2 => ['file', $this->dir . '/err.log', 'a'],
1201
1411
  ], $pipes, $this->dir);
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
  import time
5
5
 
6
6
  from projectname_sdk.feature.base_feature import ProjectNameBaseFeature
7
+ from projectname_sdk.utility.media import header_value, is_json_media
7
8
 
8
9
 
9
10
  # Response caching for safe (read) requests. Wraps the active transport and
@@ -84,7 +85,12 @@ class ProjectNameCacheFeature(ProjectNameBaseFeature):
84
85
  status = res.get("status")
85
86
  if not isinstance(status, (int, float)) or isinstance(status, bool):
86
87
  return False
87
- return 200 <= status < 300
88
+ return 200 <= status < 300 and self._json(res)
89
+
90
+ # A body that declares another type than JSON passes by, unread.
91
+ def _json(self, res):
92
+ ctype = header_value(res.get("headers"), "content-type")
93
+ return ctype == "" or is_json_media(ctype)
88
94
 
89
95
  def _snapshot(self, res):
90
96
  data = None
@@ -1,8 +1,10 @@
1
1
  # ProjectName SDK secrets feature
2
2
 
3
3
  from __future__ import annotations
4
+ import base64
4
5
  import json
5
6
  import urllib.error
7
+ import urllib.parse
6
8
  import urllib.request
7
9
 
8
10
  from projectname_sdk.utility.voxgig_struct import voxgig_struct as vs
@@ -90,6 +92,8 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
90
92
  self.active = True
91
93
 
92
94
  self._client = None
95
+ self._declared = False
96
+ self._basic = False
93
97
  self._sekreto = None
94
98
  self._secretname = "apikey"
95
99
  self._resolved = False
@@ -109,6 +113,13 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
109
113
 
110
114
  self._client = client
111
115
 
116
+ # What prepare_auth was generated from: the config declares auth only
117
+ # where it places a credential, and Basic only where it composes one.
118
+ configopts = vs.getprop(ctx.config, "options")
119
+ declared = vs.getprop(configopts, "auth") if isinstance(configopts, dict) else None
120
+ self._declared = isinstance(declared, dict)
121
+ self._basic = self._declared and declared.get("basic") is True
122
+
112
123
  name = fopts.get("name")
113
124
  self._secretname = name if isinstance(name, str) and "" != name \
114
125
  else "apikey"
@@ -131,6 +142,8 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
131
142
  "retries": xopts.get("retries")
132
143
  if isinstance(xopts.get("retries"), (int, float))
133
144
  and not isinstance(xopts.get("retries"), bool) else 1,
145
+ "redirect": "same-origin"
146
+ if "same-origin" == xopts.get("redirect") else "refuse",
134
147
  }
135
148
  else:
136
149
  self._exchange = None
@@ -199,6 +212,11 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
199
212
  def sekreto(self):
200
213
  return self._sekreto
201
214
 
215
+ # prepare_auth's decision: auth the config declares, not suppressed by
216
+ # `auth: None`.
217
+ def _authon(self):
218
+ return self._declared and self._client.options.get("auth") is not None
219
+
202
220
  # Every value this feature resolves or buys is a secret the SDK handles,
203
221
  # and none arrives under an option key the intake registration saw.
204
222
  def _register(self, value):
@@ -233,7 +251,7 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
233
251
  # bool is the whole of what resolve() needs to tell a cacheable HIT
234
252
  # from a miss it must not retain.
235
253
  def _resolve_once(self):
236
- if self._sekreto is None:
254
+ if self._sekreto is None or not self._authon():
237
255
  return False
238
256
 
239
257
  # Miss-vs-error: `try_` answers None for "no store has it" and
@@ -277,16 +295,6 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
277
295
  # another, which is the same path expiry takes anyway.
278
296
  return True
279
297
 
280
- # `auth: None` is the documented way to send NO credential, and a
281
- # purchase is a credential-bearing call: the refresh token goes to
282
- # the token endpoint in the request body. _with_refresh honours
283
- # suppression for the RETRY, but it runs after this - by then the
284
- # refresh token has already left the process, and no later check
285
- # can call it back. The suppression has to be honoured here, before
286
- # the first purchase, or it only ever half-held.
287
- if self._client.options_map().get("auth") is None:
288
- return False
289
-
290
298
  self._client.options["apikey"] = self._buy()
291
299
 
292
300
  return True
@@ -342,13 +350,28 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
342
350
  # feature wraps, and sending the token request back through it
343
351
  # would recurse on the first 401 - and would route the exchange
344
352
  # through the test mock, which knows nothing about it.
345
- res, err = fetch(url, {
353
+ fetchdef = {
346
354
  "method": x["method"],
347
355
  "headers": {"content-type": "application/json"},
348
356
  "body": json.dumps({x["request"]: self._refresh}),
349
- # Never followed: a redirect would carry the refresh token on.
357
+ # Never followed by the client: a redirect would carry the
358
+ # refresh token on.
350
359
  "redirect": "manual",
351
- })
360
+ }
361
+
362
+ res, err = fetch(url, fetchdef)
363
+
364
+ # By option alone, and only while the exchange stays on its own origin.
365
+ at = url
366
+ hops = 0
367
+ while "same-origin" == x["redirect"] and hops < _REDIRECT_MAX \
368
+ and err is None:
369
+ nxt = _moved(url, at, res)
370
+ if nxt is None:
371
+ break
372
+ at = nxt
373
+ res, err = fetch(at, fetchdef)
374
+ hops += 1
352
375
 
353
376
  if err is not None:
354
377
  raise Exception(
@@ -395,12 +418,9 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
395
418
  x = self._exchange
396
419
  max_retries = 0 if x is None else x["retries"]
397
420
 
398
- # `auth: None` is the documented way to send NO credential, and
399
- # prepare_auth honours it by removing the header. A refusal of a
400
- # deliberately unauthenticated request is not an expired token and
401
- # cannot be fixed by buying one - retrying would transmit exactly
402
- # the credential the caller suppressed.
403
- if self._client.options_map().get("auth") is None:
421
+ # A refusal of an unauthenticated request is not an expired token,
422
+ # and retrying would transmit the credential that auth off withholds.
423
+ if not self._authon():
404
424
  return inner(ctx, url, fetchdef)
405
425
 
406
426
  attempt = 0
@@ -451,13 +471,9 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
451
471
  not isinstance(fetchdef.get("headers"), dict):
452
472
  return
453
473
 
454
- auth = self._client.options_map().get("auth")
474
+ auth = self._client.options.get("auth")
455
475
 
456
- # Suppressed auth means NO header, the same answer prepare_auth
457
- # gives. Reached defensively - _with_refresh does not retry at all
458
- # when auth is None - but this is the function that writes the
459
- # credential, so it is where the rule has to hold.
460
- if auth is None:
476
+ if not self._authon():
461
477
  fetchdef["headers"].pop("authorization", None)
462
478
  return
463
479
 
@@ -466,9 +482,51 @@ class ProjectNameSecretsFeature(ProjectNameBaseFeature):
466
482
  name = name.lower() if isinstance(name, str) and "" != name \
467
483
  else "authorization"
468
484
 
485
+ value = token
486
+ if self._basic and isinstance(auth, dict) and auth.get("basic") is True:
487
+ value = self._pair(token)
488
+
469
489
  prefix = auth.get("prefix") if isinstance(auth, dict) else None
470
490
  fetchdef["headers"][name] = \
471
- prefix + " " + token if prefix else token
491
+ prefix + " " + value if prefix else value
492
+
493
+ # Under Basic the token is the key half, as apikey is: prepare_auth's pair.
494
+ def _pair(self, token):
495
+ secret = self._client.options.get("secret")
496
+ pair = base64.b64encode(
497
+ (str(token) + ":" + ("" if secret is None else str(secret))).encode("utf-8")
498
+ ).decode("ascii")
499
+ self._register(pair)
500
+ return pair
501
+
502
+
503
+ _REDIRECT_MAX = 5
504
+
505
+
506
+ def _origin(parts):
507
+ port = parts.port or {"http": 80, "https": 443}.get(parts.scheme)
508
+ return (parts.scheme, parts.hostname, port)
509
+
510
+
511
+ def _moved(url, at, res):
512
+ """Where a 307 or 308 points, when that is on the exchange's own
513
+ origin. Any other redirect would drop the body or leave the origin."""
514
+ status = res.get("status") if isinstance(res, dict) else None
515
+ if status not in (307, 308):
516
+ return None
517
+
518
+ headers = res.get("headers")
519
+ location = headers.get("location") if isinstance(headers, dict) else None
520
+ if not isinstance(location, str) or "" == location:
521
+ return None
522
+
523
+ try:
524
+ nxt = urllib.parse.urljoin(at, location)
525
+ same = _origin(urllib.parse.urlsplit(nxt)) == \
526
+ _origin(urllib.parse.urlsplit(url))
527
+ except ValueError:
528
+ return None
529
+ return nxt if same else None
472
530
 
473
531
 
474
532
  class _NoRedirect(urllib.request.HTTPRedirectHandler):
@@ -500,6 +558,7 @@ def _raw_exchange_fetch(fullurl, fetchdef):
500
558
  with _NO_REDIRECT.open(req, timeout=30) as res:
501
559
  raw = res.read()
502
560
  status = res.status
561
+ headers = {k.lower(): v for k, v in res.headers.items()}
503
562
 
504
563
  def _json():
505
564
  try:
@@ -507,11 +566,13 @@ def _raw_exchange_fetch(fullurl, fetchdef):
507
566
  except Exception:
508
567
  return None
509
568
 
510
- return {"status": status, "json": _json}, None
569
+ return {"status": status, "headers": headers, "json": _json}, None
511
570
  except urllib.error.HTTPError as e:
512
571
  # A non-2xx answer IS a response: hand back its status so the
513
572
  # caller reports "token exchange failed: <status>" rather than a
514
573
  # transport error.
515
- return {"status": e.code, "json": lambda: None}, None
574
+ headers = {k.lower(): v for k, v in (e.headers or {}).items()}
575
+ return {"status": e.code, "headers": headers,
576
+ "json": lambda: None}, None
516
577
  except Exception as e:
517
578
  return None, e