@voxgig/sdkgen 4.36.0 → 4.38.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 (129) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/dist/helpers/flowGuard.js +4 -4
  3. package/dist/helpers/flowGuard.js.map +1 -1
  4. package/dist/helpers/liveDiscovery.d.ts +7 -0
  5. package/dist/helpers/liveDiscovery.js +20 -0
  6. package/dist/helpers/liveDiscovery.js.map +1 -0
  7. package/dist/helpers/opShape.d.ts +2 -1
  8. package/dist/helpers/opShape.js +4 -0
  9. package/dist/helpers/opShape.js.map +1 -1
  10. package/dist/helpers/pointPath.d.ts +2 -1
  11. package/dist/helpers/pointPath.js +6 -0
  12. package/dist/helpers/pointPath.js.map +1 -1
  13. package/dist/helpers/testPolicy.d.ts +14 -4
  14. package/dist/helpers/testPolicy.js +152 -54
  15. package/dist/helpers/testPolicy.js.map +1 -1
  16. package/dist/sdkgen.d.ts +8 -6
  17. package/dist/sdkgen.js +11 -5
  18. package/dist/sdkgen.js.map +1 -1
  19. package/dist/tsconfig.tsbuildinfo +1 -1
  20. package/dist/utility.js +7 -3
  21. package/dist/utility.js.map +1 -1
  22. package/package.json +1 -1
  23. package/project/.sdk/src/cmp/c/TestDirect_c.ts +3 -2
  24. package/project/.sdk/src/cmp/cpp/TestDirect_cpp.ts +3 -2
  25. package/project/.sdk/src/cmp/cpp/TestEntity_cpp.ts +33 -10
  26. package/project/.sdk/src/cmp/csharp/TestDirect_csharp.ts +12 -12
  27. package/project/.sdk/src/cmp/csharp/TestEntity_csharp.ts +73 -28
  28. package/project/.sdk/src/cmp/go/Entity_go.ts +1 -1
  29. package/project/.sdk/src/cmp/go/MainEntity_go.ts +1 -1
  30. package/project/.sdk/src/cmp/go/Main_go.ts +7 -3
  31. package/project/.sdk/src/cmp/go/ReadmeModel_go.ts +3 -3
  32. package/project/.sdk/src/cmp/go/ReadmeRef_go.ts +1 -1
  33. package/project/.sdk/src/cmp/go/TestDirect_go.ts +12 -10
  34. package/project/.sdk/src/cmp/go/TestEntity_go.ts +67 -23
  35. package/project/.sdk/src/cmp/go-cli/fragment/words.fragment.go +1 -1
  36. package/project/.sdk/src/cmp/go-mcp/fragment/tools.fragment.go +1 -1
  37. package/project/.sdk/src/cmp/java/TestDirect_java.ts +12 -11
  38. package/project/.sdk/src/cmp/java/TestEntity_java.ts +71 -23
  39. package/project/.sdk/src/cmp/js/TestDirect_js.ts +13 -12
  40. package/project/.sdk/src/cmp/js/TestEntity_js.ts +41 -17
  41. package/project/.sdk/src/cmp/kotlin/TestDirect_kotlin.ts +12 -10
  42. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +64 -23
  43. package/project/.sdk/src/cmp/lua/TestDirect_lua.ts +9 -5
  44. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +61 -23
  45. package/project/.sdk/src/cmp/perl/TestDirect_perl.ts +9 -5
  46. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +58 -24
  47. package/project/.sdk/src/cmp/php/TestDirect_php.ts +9 -5
  48. package/project/.sdk/src/cmp/php/TestEntity_php.ts +61 -23
  49. package/project/.sdk/src/cmp/py/TestDirect_py.ts +10 -6
  50. package/project/.sdk/src/cmp/py/TestEntity_py.ts +59 -27
  51. package/project/.sdk/src/cmp/rb/TestDirect_rb.ts +9 -5
  52. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +59 -23
  53. package/project/.sdk/src/cmp/rust/EntityOperation_rust.ts +1 -1
  54. package/project/.sdk/src/cmp/rust/Main_rust.ts +3 -1
  55. package/project/.sdk/src/cmp/rust/ReadmeHowto_rust.ts +1 -1
  56. package/project/.sdk/src/cmp/rust/ReadmeModel_rust.ts +1 -1
  57. package/project/.sdk/src/cmp/rust/ReadmeQuick_rust.ts +1 -1
  58. package/project/.sdk/src/cmp/rust/ReadmeRef_rust.ts +1 -1
  59. package/project/.sdk/src/cmp/rust/ReadmeTopQuick_rust.ts +1 -1
  60. package/project/.sdk/src/cmp/rust/ReadmeTopTest_rust.ts +1 -1
  61. package/project/.sdk/src/cmp/rust/TestClean_rust.ts +1 -1
  62. package/project/.sdk/src/cmp/rust/TestDirect_rust.ts +9 -8
  63. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +57 -25
  64. package/project/.sdk/src/cmp/rust/fragment/Entity.fragment.rs +2 -2
  65. package/project/.sdk/src/cmp/scala/TestDirect_scala.ts +3 -2
  66. package/project/.sdk/src/cmp/scala/TestEntity_scala.ts +36 -9
  67. package/project/.sdk/src/cmp/ts/TestDirect_ts.ts +15 -32
  68. package/project/.sdk/src/cmp/ts/TestEntity_ts.ts +41 -17
  69. package/project/.sdk/tm/c/core/sdk.h +2 -2
  70. package/project/.sdk/tm/c/tests/transport_test.c +33 -0
  71. package/project/.sdk/tm/c/utility/fetcher.c +151 -2
  72. package/project/.sdk/tm/c/utility/make_url.c +8 -6
  73. package/project/.sdk/tm/clojure/src/sdk/core.clj +17 -10
  74. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +38 -0
  75. package/project/.sdk/tm/cpp/utility/pipeline.hpp +5 -4
  76. package/project/.sdk/tm/csharp/test/PrimaryUtilityTest.cs +69 -0
  77. package/project/.sdk/tm/csharp/utility/Fetcher.cs +3 -1
  78. package/project/.sdk/tm/csharp/utility/MakeUrl.cs +5 -4
  79. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +10 -6
  80. package/project/.sdk/tm/elixir/test/pipeline_test.exs +61 -0
  81. package/project/.sdk/tm/go/core/helpers.go +1 -1
  82. package/project/.sdk/tm/go/core/types.go +9 -1
  83. package/project/.sdk/tm/go/test/primary_utility_test.go +60 -0
  84. package/project/.sdk/tm/go/utility/fetcher.go +15 -4
  85. package/project/.sdk/tm/go/utility/make_url.go +4 -3
  86. package/project/.sdk/tm/java/test/PrimaryUtilityTest.java +47 -0
  87. package/project/.sdk/tm/java/utility/MakeUrl.java +5 -4
  88. package/project/.sdk/tm/js/src/utility/MakeUrlUtility.js +5 -3
  89. package/project/.sdk/tm/js/test/live-runner.js +4 -3
  90. package/project/.sdk/tm/js/test/utility/PrimaryUtility.test.js +40 -0
  91. package/project/.sdk/tm/kotlin/test/PrimaryUtilityTest.kt +41 -0
  92. package/project/.sdk/tm/kotlin/utility/MakeSpecUrl.kt +4 -3
  93. package/project/.sdk/tm/lua/test/primary_utility_test.lua +61 -0
  94. package/project/.sdk/tm/lua/utility/fetcher.lua +54 -6
  95. package/project/.sdk/tm/lua/utility/make_url.lua +5 -4
  96. package/project/.sdk/tm/ocaml/sdk_runtime.ml +5 -5
  97. package/project/.sdk/tm/perl/t/primary_utility.t +54 -0
  98. package/project/.sdk/tm/perl/utility/fetcher.pm +65 -11
  99. package/project/.sdk/tm/perl/utility/make_url.pm +4 -3
  100. package/project/.sdk/tm/php/test/PipelineTest.php +52 -0
  101. package/project/.sdk/tm/php/utility/Fetcher.php +81 -15
  102. package/project/.sdk/tm/php/utility/MakeUrl.php +5 -3
  103. package/project/.sdk/tm/py/pkg/utility/fetcher.py +1 -0
  104. package/project/.sdk/tm/py/pkg/utility/make_url.py +5 -4
  105. package/project/.sdk/tm/py/test/test_primary_utility.py +52 -0
  106. package/project/.sdk/tm/rb/test/primary_utility_test.rb +46 -0
  107. package/project/.sdk/tm/rb/utility/fetcher.rb +41 -5
  108. package/project/.sdk/tm/rb/utility/make_url.rb +5 -3
  109. package/project/.sdk/tm/rust/core/helpers.rs +1 -1
  110. package/project/.sdk/tm/rust/core/types.rs +2 -2
  111. package/project/.sdk/tm/rust/tests/primary_utility_test.rs +65 -0
  112. package/project/.sdk/tm/rust/utility/make_url.rs +7 -6
  113. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +47 -1
  114. package/project/.sdk/tm/scala/utility/Make.scala +8 -6
  115. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +59 -15
  116. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Make.swift +4 -4
  117. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/PrimaryUtilityTest.swift +72 -0
  118. package/project/.sdk/tm/ts/src/utility/MakeUrlUtility.ts +5 -3
  119. package/project/.sdk/tm/ts/test/live-runner.ts +4 -3
  120. package/project/.sdk/tm/ts/test/utility/PrimaryUtility.test.ts +40 -0
  121. package/project/.sdk/tm/zig/core/utility.zig +5 -5
  122. package/project/sdkgen-package.json +1 -1
  123. package/src/helpers/flowGuard.ts +4 -4
  124. package/src/helpers/liveDiscovery.ts +31 -0
  125. package/src/helpers/opShape.ts +6 -0
  126. package/src/helpers/pointPath.ts +8 -0
  127. package/src/helpers/testPolicy.ts +193 -55
  128. package/src/sdkgen.ts +13 -3
  129. package/src/utility.ts +10 -4
@@ -26,11 +26,12 @@ def make_url_util(ctx):
26
26
  # Sent with the request, never recorded as the entity's match.
27
27
  authquery = getattr(spec, "authquery", None) or []
28
28
 
29
- # A route the definition ends with a slash keeps it, for a Django REST server,
30
- # and a host with no path takes /, or luasocket reads a query as the host.
29
+ # A route ending in a slash keeps it, as defined or as passed to direct(), for
30
+ # Django, and a host with no path takes /, or luasocket reads a query as the host.
31
31
  orig = vs.getprop(ctx.point, "orig") if ctx.point is not None else None
32
- if isinstance(orig, str) and orig.endswith("/") and not spec.suffix \
33
- and not url.endswith("/"):
32
+ slashed = (isinstance(orig, str) and orig.endswith("/")) or \
33
+ (isinstance(spec.path, str) and spec.path.endswith("/"))
34
+ if slashed and not spec.suffix and not url.endswith("/"):
34
35
  url += "/"
35
36
  authority = url.find("://")
36
37
  if 0 < authority and not any(c in url[authority + 3:] for c in "/?#"):
@@ -16,6 +16,9 @@
16
16
  # subject ran - the resolver's CtxView takes care of presenting the
17
17
  # context object as the map omni walks, camelCase keys included.
18
18
 
19
+ import http.server
20
+ import threading
21
+
19
22
  import pytest
20
23
 
21
24
  from projectname_sdk import ProjectNameSDK
@@ -380,6 +383,55 @@ class TestPrimaryUtility:
380
383
  assert "blocked" in str(err).lower()
381
384
 
382
385
  # Nothing listens on port 9: a request the guard let through fails there.
386
+ # A Django route answers its slashless form with a relative Location. The
387
+ # transport follows each hop, and answers a "manual" fetch with the 3xx.
388
+ def test_fetcher_redirect(self):
389
+ pytest.importorskip("requests")
390
+ seen = []
391
+ moved = {"/redirect/r1": (301, "/redirect/r1/"), "/redirect/r1/": (308, "done")}
392
+
393
+ class Handler(http.server.BaseHTTPRequestHandler):
394
+ def log_message(self, *args):
395
+ pass
396
+
397
+ def do_GET(self):
398
+ seen.append(self.path)
399
+ hop = moved.get(self.path)
400
+ done = "/redirect/r1/done" == self.path
401
+ body = b'{"id":"r1"}' if done else b""
402
+ self.send_response(hop[0] if hop else 200 if done else 404)
403
+ if hop:
404
+ self.send_header("Location", hop[1])
405
+ self.send_header("Content-Type", "application/json")
406
+ self.send_header("Content-Length", str(len(body)))
407
+ self.send_header("Connection", "close")
408
+ self.end_headers()
409
+ self.wfile.write(body)
410
+
411
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
412
+ threading.Thread(target=server.serve_forever, daemon=True).start()
413
+ base = "http://127.0.0.1:%d" % server.server_address[1]
414
+ try:
415
+ live_client = ProjectNameSDK({"base": base})
416
+ live_utility = live_client._utility
417
+ ctx = live_utility.make_context({
418
+ "opname": "load",
419
+ "client": live_client,
420
+ "utility": live_utility,
421
+ }, None)
422
+
423
+ res, err = live_utility.fetcher(ctx, base + "/redirect/r1", {"method": "GET", "headers": {}})
424
+ assert err is None and res["status"] == 200
425
+ assert res["json"]() == {"id": "r1"}
426
+ assert seen == ["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"]
427
+
428
+ res, err = live_utility.fetcher(ctx, base + "/redirect/r1",
429
+ {"method": "GET", "headers": {}, "redirect": "manual"})
430
+ assert err is None and res["status"] == 301
431
+ finally:
432
+ server.shutdown()
433
+ server.server_close()
434
+
383
435
  def test_fetcher_getonly_guard(self, monkeypatch):
384
436
  live_client = ProjectNameSDK({"base": "http://127.0.0.1:9"})
385
437
  live_utility = live_client._utility
@@ -18,6 +18,7 @@
18
18
  # context object as the map omni walks, camelCase keys included.
19
19
 
20
20
  require "minitest/autorun"
21
+ require "socket"
21
22
  require "json"
22
23
  require_relative "../ProjectName_sdk"
23
24
  require_relative "omni"
@@ -278,6 +279,51 @@ class PrimaryUtilityTest < Minitest::Test
278
279
  assert_includes err.to_s.downcase, "blocked"
279
280
  end
280
281
 
282
+ # A Django route answers its slashless form with a relative Location. The
283
+ # transport follows each hop, and answers a "manual" fetch with the 3xx.
284
+ def test_fetcher_redirect
285
+ seen = Queue.new
286
+ moved = { "/redirect/r1" => [301, "/redirect/r1/"], "/redirect/r1/" => [308, "done"] }
287
+ server = TCPServer.new("127.0.0.1", 0)
288
+ thread = Thread.new do
289
+ loop do
290
+ sock = server.accept
291
+ path = sock.gets.to_s.split(" ")[1].to_s
292
+ nil until ["\r\n", "\n", nil].include?(sock.gets)
293
+ seen << path
294
+ hop = moved[path]
295
+ body = path == "/redirect/r1/done" ? '{"id":"r1"}' : ""
296
+ status = hop ? hop[0] : (body.empty? ? 404 : 200)
297
+ sock.write("HTTP/1.1 #{status} X\r\n#{hop ? "Location: #{hop[1]}\r\n" : ""}" \
298
+ "Content-Type: application/json\r\nContent-Length: #{body.bytesize}\r\n" \
299
+ "Connection: close\r\n\r\n#{body}")
300
+ sock.close
301
+ end
302
+ end
303
+ base = "http://127.0.0.1:#{server.addr[1]}"
304
+ live_client = ProjectNameSDK.new({ "base" => base })
305
+ live_utility = live_client.get_utility
306
+ ctx = live_utility.make_context.call({
307
+ "opname" => "load",
308
+ "client" => live_client,
309
+ "utility" => live_utility,
310
+ }, nil)
311
+
312
+ res, err = live_utility.fetcher.call(ctx, "#{base}/redirect/r1", { "method" => "GET", "headers" => {} })
313
+ assert_nil err
314
+ assert_equal 200, res["status"]
315
+ assert_equal({ "id" => "r1" }, res["json"].call)
316
+ assert_equal ["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"], Array.new(seen.size) { seen.pop }
317
+
318
+ res, err = live_utility.fetcher.call(ctx, "#{base}/redirect/r1",
319
+ { "method" => "GET", "headers" => {}, "redirect" => "manual" })
320
+ assert_nil err
321
+ assert_equal 301, res["status"]
322
+ ensure
323
+ thread&.kill
324
+ server&.close
325
+ end
326
+
281
327
  # Nothing listens on port 9: a request the guard let through fails there.
282
328
  def test_fetcher_getonly_guard
283
329
  live_client = ProjectNameSDK.new({ "base" => "http://127.0.0.1:9" })
@@ -56,6 +56,46 @@ module ProjectNameUtilities
56
56
  ctx.make_error("fetch_getonly_block", "[GET-ONLY GUARD] blocked #{method} #{path}")
57
57
  end
58
58
 
59
+ REDIRECT_STATUS = [301, 302, 303, 307, 308].freeze
60
+ REDIRECT_MAX = 5
61
+ CREDENTIAL_HEADERS = %w[authorization cookie proxy-authorization].freeze
62
+
63
+ def self.redirect_origin(url)
64
+ uri = URI.parse(url)
65
+ [uri.scheme, uri.host, uri.port]
66
+ end
67
+
68
+ # Net::HTTP never follows a redirect. A GET or HEAD follows one, unless the
69
+ # fetch definition says "manual", each hop passing the GET-only guard first;
70
+ # past REDIRECT_MAX hops the last 3xx is the answer. Another origin is not
71
+ # sent the request's credentials.
72
+ def self.follow_redirects(ctx, fullurl, fetchdef)
73
+ method = fetchdef["method"].to_s.upcase
74
+ follow = ["", "GET", "HEAD"].include?(method) && fetchdef["redirect"] != "manual"
75
+ url = fullurl
76
+ hops = 0
77
+ loop do
78
+ refused = getonly_refusal(ctx, url, fetchdef["method"])
79
+ return nil, refused if refused
80
+ res, err = DefaultHttpFetch.call(url, fetchdef)
81
+ location = res.is_a?(Hash) && res["headers"].is_a?(Hash) ? res["headers"]["location"] : nil
82
+ return res, err unless follow && location.is_a?(String) && hops < REDIRECT_MAX &&
83
+ REDIRECT_STATUS.include?(res["status"])
84
+ nxt = begin
85
+ URI.join(url, location.strip).tap { |u| u.fragment = nil }.to_s
86
+ rescue URI::Error
87
+ nil
88
+ end
89
+ return res, err if nxt.nil?
90
+ if redirect_origin(nxt) != redirect_origin(url)
91
+ headers = (fetchdef["headers"] || {}).reject { |k, _| CREDENTIAL_HEADERS.include?(k.to_s.downcase) }
92
+ fetchdef = fetchdef.merge("headers" => headers)
93
+ end
94
+ url = nxt
95
+ hops += 1
96
+ end
97
+ end
98
+
59
99
  DefaultHttpFetch = ->(fullurl, fetchdef) {
60
100
  method_str = fetchdef["method"] || "GET"
61
101
  body_str = fetchdef["body"]
@@ -149,11 +189,7 @@ module ProjectNameUtilities
149
189
 
150
190
  sys_fetch = VoxgigStruct.getpath(options, "system.fetch")
151
191
 
152
- if sys_fetch.nil?
153
- refused = ProjectNameUtilities.getonly_refusal(ctx, fullurl, fetchdef["method"])
154
- return nil, refused if refused
155
- return DefaultHttpFetch.call(fullurl, fetchdef)
156
- end
192
+ return ProjectNameUtilities.follow_redirects(ctx, fullurl, fetchdef) if sys_fetch.nil?
157
193
  return sys_fetch.call(fullurl, fetchdef) if sys_fetch.is_a?(Proc)
158
194
 
159
195
  return nil, ctx.make_error("fetch_invalid", "system.fetch is not a valid function")
@@ -14,10 +14,12 @@ module ProjectNameUtilities
14
14
  # Sent with the request, never recorded as the entity's match.
15
15
  authquery = (spec.respond_to?(:authquery) ? spec.authquery : nil) || []
16
16
 
17
- # A route the definition ends with a slash keeps it, for a Django REST server,
18
- # and a host with no path takes /, or luasocket reads a query as the host.
17
+ # A route ending in a slash keeps it, as defined or as passed to direct(), for
18
+ # Django, and a host with no path takes /, or luasocket reads a query as the host.
19
19
  orig = ctx.point ? VoxgigStruct.getprop(ctx.point, "orig") : nil
20
- if orig.is_a?(String) && orig.end_with?("/") && spec.suffix.to_s.empty? && !url.end_with?("/")
20
+ slashed = (orig.is_a?(String) && orig.end_with?("/")) ||
21
+ (spec.path.is_a?(String) && spec.path.end_with?("/"))
22
+ if slashed && spec.suffix.to_s.empty? && !url.end_with?("/")
21
23
  url += "/"
22
24
  end
23
25
  authority = url.index("://")
@@ -13,7 +13,7 @@ use crate::utility::voxgigstruct::major::Injection;
13
13
  use vs::Value;
14
14
 
15
15
  // UnsupportedOp is returned by entity stub methods for operations the
16
- // underlying API spec doesn't define. The static ProjectNameEntity trait
16
+ // underlying API spec doesn't define. The static ProjectNameEntityBase trait
17
17
  // requires every CRUD method on every entity, so absent ops must still be
18
18
  // callable — they error at runtime instead of failing to compile.
19
19
  pub fn unsupported_op(opname: &str, entityname: &str) -> ProjectNameError {
@@ -76,9 +76,9 @@ pub trait Entity {
76
76
  fn deleted(&self) -> bool;
77
77
  }
78
78
 
79
- /// ProjectNameEntity: the full CRUD contract every generated entity
79
+ /// ProjectNameEntityBase: the full CRUD contract every generated entity
80
80
  /// implements. Ops the API spec doesn't define are runtime-error stubs.
81
- pub trait ProjectNameEntity: Entity + Sized {
81
+ pub trait ProjectNameEntityBase: Entity + Sized {
82
82
  fn load(self: &Rc<Self>, reqmatch: Value, ctrl: Value) -> Result<Rc<Self>, ProjectNameError>;
83
83
  fn list(self: &Rc<Self>, reqmatch: Value, ctrl: Value) -> Result<Vec<Rc<Self>>, ProjectNameError>;
84
84
  fn create(self: &Rc<Self>, reqdata: Value, ctrl: Value) -> Result<Rc<Self>, ProjectNameError>;
@@ -376,6 +376,71 @@ fn primary_fetcher_blocked_test_mode() {
376
376
  );
377
377
  }
378
378
 
379
+ // A Django route answers its slashless form with a relative Location. The
380
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
381
+ #[test]
382
+ fn primary_fetcher_redirect() {
383
+ use std::io::{BufRead, BufReader, Write};
384
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
385
+ let base = format!("http://{}", listener.local_addr().unwrap());
386
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
387
+ let log = seen.clone();
388
+ std::thread::spawn(move || {
389
+ for stream in listener.incoming().take(4) {
390
+ let mut stream = stream.unwrap();
391
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
392
+ let mut line = String::new();
393
+ reader.read_line(&mut line).unwrap();
394
+ let path = line.split(' ').nth(1).unwrap_or("").to_string();
395
+ let mut header = String::from("-");
396
+ while !header.trim().is_empty() {
397
+ header.clear();
398
+ if 0 == reader.read_line(&mut header).unwrap_or(0) {
399
+ break;
400
+ }
401
+ }
402
+ let (status, location) = match path.as_str() {
403
+ "/redirect/r1" => (301, "Location: /redirect/r1/\r\n"),
404
+ "/redirect/r1/" => (308, "Location: done\r\n"),
405
+ "/redirect/r1/done" => (200, ""),
406
+ _ => (404, ""),
407
+ };
408
+ let body = if 200 == status { "{\"id\":\"r1\"}" } else { "" };
409
+ log.lock().unwrap().push(path);
410
+ let _ = write!(stream, "HTTP/1.1 {} X\r\n{}Content-Type: application/json\r\n\
411
+ Content-Length: {}\r\nConnection: close\r\n\r\n{}", status, location, body.len(), body);
412
+ }
413
+ });
414
+
415
+ let live_client = ProjectNameSDK::new(jo(vec![("base", Value::str(&base))]));
416
+ let live_utility = live_client.get_utility();
417
+ let ctx = live_utility.make_context(
418
+ CtxSpec {
419
+ opname: Some("load".to_string()),
420
+ client: Some(live_client.clone()),
421
+ utility: Some(live_utility.clone()),
422
+ ..Default::default()
423
+ },
424
+ None,
425
+ );
426
+ let url = format!("{}/redirect/r1", base);
427
+ let res = live_utility
428
+ .fetch(&ctx, &url, &jo(vec![("method", Value::str("GET")), ("headers", Value::empty_map())]))
429
+ .expect("expected the redirect followed");
430
+ assert!(matches!(getp(&res, "status"), Value::Num(n) if 200.0 == n), "{:?}", getp(&res, "status"));
431
+ assert_eq!(get_str(&res, "body").as_deref(), Some("{\"id\":\"r1\"}"));
432
+ assert_eq!(*seen.lock().unwrap(), vec!["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"]);
433
+
434
+ let manual = live_utility
435
+ .fetch(&ctx, &url, &jo(vec![
436
+ ("method", Value::str("GET")),
437
+ ("headers", Value::empty_map()),
438
+ ("redirect", Value::str("manual")),
439
+ ]))
440
+ .expect("expected the 301");
441
+ assert!(matches!(getp(&manual, "status"), Value::Num(n) if 301.0 == n), "{:?}", getp(&manual, "status"));
442
+ }
443
+
379
444
  // Nothing listens on port 9: a request the guard let through fails there.
380
445
  #[test]
381
446
  fn primary_fetcher_getonly_guard() {
@@ -49,6 +49,7 @@ pub fn make_url_util(ctx: &Rc<Context>) -> Result<String, ProjectNameError> {
49
49
  };
50
50
 
51
51
  let suffixless = suffix.is_empty();
52
+ let path_slash = path.ends_with('/');
52
53
  let mut url = vs::join(
53
54
  &Value::list(vec![
54
55
  Value::str(base.clone()),
@@ -60,12 +61,12 @@ pub fn make_url_util(ctx: &Rc<Context>) -> Result<String, ProjectNameError> {
60
61
  true,
61
62
  );
62
63
 
63
- // A route the definition ends with a slash keeps it, for a Django REST server,
64
- // and a host with no path takes /, or luasocket reads a query as the host.
65
- if let Value::Str(orig) = getp(&ctx.point.borrow().clone(), "orig") {
66
- if orig.ends_with('/') && suffixless && !url.ends_with('/') {
67
- url.push('/');
68
- }
64
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
65
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
66
+ let orig_slash = matches!(getp(&ctx.point.borrow().clone(), "orig"),
67
+ Value::Str(orig) if orig.ends_with('/'));
68
+ if (orig_slash || path_slash) && suffixless && !url.ends_with('/') {
69
+ url.push('/');
69
70
  }
70
71
  if let Some(authority) = url.find("://") {
71
72
  if 0 < authority && !url[authority + 3..].contains(|c| matches!(c, '/' | '?' | '#')) {
@@ -706,6 +706,51 @@ object SdkTestMain {
706
706
  // Small identity wrapper so IntConsumer/LongSupplier land in the map as-is.
707
707
  private def f0(o: Object): Object = o
708
708
 
709
+ // A Django route answers its slashless form with a relative Location. The
710
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
711
+ private def testRedirect(): Unit = {
712
+ val seen = java.util.Collections.synchronizedList(new ArrayList[String]())
713
+ val moved = Map("/redirect/r1" -> (301, "/redirect/r1/"), "/redirect/r1/" -> (308, "done"))
714
+ val server = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0)
715
+ server.createContext("/", (exchange: com.sun.net.httpserver.HttpExchange) => {
716
+ val path = exchange.getRequestURI.getRawPath
717
+ seen.add(path)
718
+ val hop = moved.get(path)
719
+ val body = if (path == "/redirect/r1/done") "{\"id\":\"r1\"}".getBytes("UTF-8") else Array[Byte]()
720
+ hop.foreach(h => exchange.getResponseHeaders.set("Location", h._2))
721
+ exchange.getResponseHeaders.set("Content-Type", "application/json")
722
+ exchange.sendResponseHeaders(hop.map(_._1).getOrElse(if (body.nonEmpty) 200 else 404),
723
+ if (body.nonEmpty) body.length.toLong else -1L)
724
+ exchange.getResponseBody.write(body)
725
+ exchange.close()
726
+ })
727
+ server.start()
728
+ val base = "http://127.0.0.1:" + server.getAddress.getPort
729
+ try {
730
+ val opts = new LinkedHashMap[String, Object]()
731
+ opts.put("base", base)
732
+ val client = new ProjectNameSDK(opts)
733
+ val utility = client.getUtility()
734
+ val cm = new LinkedHashMap[String, Object]()
735
+ cm.put("opname", "load")
736
+ val ctx = utility.makeContext(cm, client.getRootCtx())
737
+ def fetch(redirect: String): JMap[String, Object] = {
738
+ val fetchdef = new LinkedHashMap[String, Object]()
739
+ fetchdef.put("method", "GET")
740
+ fetchdef.put("headers", new LinkedHashMap[String, Object]())
741
+ if (redirect != null) fetchdef.put("redirect", redirect)
742
+ utility.fetcher(ctx, base + "/redirect/r1", fetchdef).asInstanceOf[JMap[String, Object]]
743
+ }
744
+
745
+ val res = fetch(null)
746
+ eq("redirect.status", Integer.valueOf(200), res.get("status"))
747
+ eq("redirect.body", "{\"id\":\"r1\"}", res.get("body"))
748
+ eq("redirect.hops", "[/redirect/r1, /redirect/r1/, /redirect/r1/done]", seen.toString)
749
+ eq("redirect.manual", Integer.valueOf(301), fetch("manual").get("status"))
750
+ }
751
+ finally server.stop(0)
752
+ }
753
+
709
754
  // Nothing listens on port 9: a request the guard let through fails there.
710
755
  // A JVM cannot set its own environment, so the probe runs in a child JVM.
711
756
  private def testGetOnlyGuard(): Unit = {
@@ -736,7 +781,8 @@ object SdkTestMain {
736
781
  "paging" -> testPaging, "streaming" -> testStreaming, "proxy" -> testProxy,
737
782
  "composition" -> testComposition, "featureAdd" -> testFeatureAdd,
738
783
  "featureOrder" -> testFeatureOrder, "entityCrud" -> testEntityCrud,
739
- "entityStream" -> testEntityStream, "getOnlyGuard" -> testGetOnlyGuard)
784
+ "entityStream" -> testEntityStream, "getOnlyGuard" -> testGetOnlyGuard,
785
+ "redirect" -> testRedirect)
740
786
 
741
787
  suites.foreach { case (name, fn) =>
742
788
  try fn()
@@ -678,13 +678,15 @@ object MakeUrl {
678
678
  joinParts.add(spec.suffix)
679
679
  var url = Struct.join(joinParts, "/", true)
680
680
 
681
- // A route the definition ends with a slash keeps it, for a Django REST server,
682
- // and a host with no path takes /, or luasocket reads a query as the host.
681
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
682
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
683
683
  val orig = if (ctx.point == null) null else Struct.getprop(ctx.point, "orig", null)
684
- orig match {
685
- case o: String if o.endsWith("/") && (spec.suffix == null || spec.suffix.isEmpty) && !url.endsWith("/") =>
686
- url = url + "/"
687
- case _ =>
684
+ val slashed = (orig match {
685
+ case o: String => o.endsWith("/")
686
+ case _ => false
687
+ }) || (spec.path != null && spec.path.endsWith("/"))
688
+ if (slashed && (spec.suffix == null || spec.suffix.isEmpty) && !url.endsWith("/")) {
689
+ url = url + "/"
688
690
  }
689
691
  val authority = url.indexOf("://")
690
692
  if (0 < authority && !url.substring(authority + 3).exists(c => 0 <= "/?#".indexOf(c))) {
@@ -18,15 +18,7 @@ private func cookielessConfiguration() -> URLSessionConfiguration {
18
18
  return cfg
19
19
  }
20
20
 
21
- private let defaultSession = URLSession(configuration: cookielessConfiguration())
22
-
23
- // Non-following twin of defaultSession. The station feature's
24
- // middleware sets `redirect: manual` on the fetch definition under a
25
- // hosts egress policy: a 3xx must come back as a response like any
26
- // other, because an automatic follow would carry injected credentials
27
- // to a Location no policy approved (the ts donor's fetch honours the
28
- // same key natively; redirect policy is per-delegate in URLSession,
29
- // hence a second session).
21
+ // Every 3xx comes back as a response: defaultHttpFetch follows redirects.
30
22
  private final class ManualRedirectDelegate: NSObject, URLSessionTaskDelegate {
31
23
  func urlSession(
32
24
  _ session: URLSession, task: URLSessionTask,
@@ -61,12 +53,66 @@ func getOnlyRefusal(_ fullurl: String, _ method: String) -> ProjectNameError? {
61
53
  "[GET-ONLY GUARD] blocked \(upper) \(path.isEmpty ? "/" : String(path))", nil)
62
54
  }
63
55
 
56
+ let redirectStatus: Set<Int64> = [301, 302, 303, 307, 308]
57
+ let redirectMax = 5
58
+
59
+ // The Location resolved against the URL that answered with it.
60
+ func resolveLocation(_ base: String, _ location: String) -> String? {
61
+ let trimmed = location.filter { !$0.isWhitespace }
62
+ guard let resolved = URL(string: trimmed, relativeTo: URL(string: base)) else { return nil }
63
+ return String(resolved.absoluteString.prefix { $0 != "#" })
64
+ }
65
+
66
+ private func redirectOrigin(_ url: String) -> String {
67
+ guard let parts = URLComponents(string: url) else { return url }
68
+ let scheme = parts.scheme?.lowercased() ?? ""
69
+ return "\(scheme)://\(parts.host?.lowercased() ?? ""):\(parts.port ?? (scheme == "https" ? 443 : 80))"
70
+ }
71
+
72
+ private func withoutCredentials(_ fetchdef: VMap) -> VMap {
73
+ let copy = VMap(fetchdef.entries)
74
+ if let headers = gp(fetchdef, "headers").asMap {
75
+ var kept = headers.entries
76
+ for key in kept.keys where ["authorization", "cookie", "proxy-authorization"].contains(key.lowercased()) {
77
+ _ = kept.removeValue(forKey: key)
78
+ }
79
+ copy.entries["headers"] = .map(VMap(kept))
80
+ }
81
+ return copy
82
+ }
83
+
84
+ // URLSession on Linux drops the trailing slash of a Location it follows, so
85
+ // redirects are followed here. A GET or HEAD follows one, unless the fetch
86
+ // definition says "manual", each hop passing the GET-only guard first; past
87
+ // redirectMax hops the last 3xx is the answer. Another origin is not sent the
88
+ // request's credentials.
64
89
  func defaultHttpFetch(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
65
- let method = gp(fetchdef, "method").asString ?? "GET"
66
- if let refused = getOnlyRefusal(fullurl, method.isEmpty ? "GET" : method) {
67
- throw refused
90
+ let raw = gp(fetchdef, "method").asString ?? "GET"
91
+ let method = raw.isEmpty ? "GET" : raw.uppercased()
92
+ let follow = (method == "GET" || method == "HEAD") && gp(fetchdef, "redirect").asString != "manual"
93
+ var url = fullurl
94
+ var def = fetchdef
95
+ var hops = 0
96
+ while true {
97
+ if let refused = getOnlyRefusal(url, method) {
98
+ throw refused
99
+ }
100
+ let res = try sendOnce(url, def)
101
+ guard follow, hops < redirectMax, let status = gp(res, "status").asInt,
102
+ redirectStatus.contains(status), let location = gp(gp(res, "headers"), "location").asString,
103
+ let next = resolveLocation(url, location)
104
+ else {
105
+ return res
106
+ }
107
+ if redirectOrigin(next) != redirectOrigin(url) {
108
+ def = withoutCredentials(def)
109
+ }
110
+ url = next
111
+ hops += 1
68
112
  }
113
+ }
69
114
 
115
+ private func sendOnce(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
70
116
  // A request that cannot be sent fails the operation.
71
117
  guard let url = URL(string: fullurl) else {
72
118
  throw ProjectNameError("fetch_transport", "the URL could not be parsed", nil)
@@ -116,9 +162,7 @@ func defaultHttpFetch(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
116
162
  }
117
163
  let box = FetchBox()
118
164
  let sem = DispatchSemaphore(value: 0)
119
- let session = gp(fetchdef, "redirect").asString == "manual"
120
- ? manualRedirectSession : defaultSession
121
- let task = session.dataTask(with: req) { d, r, e in
165
+ let task = manualRedirectSession.dataTask(with: req) { d, r, e in
122
166
  box.data = d; box.resp = r; box.err = e; sem.signal()
123
167
  }
124
168
  task.resume()
@@ -266,10 +266,10 @@ func makeUrlUtil(_ ctx: Context) throws -> String {
266
266
  // Sent with the request, never recorded as the entity's match.
267
267
  let authquery = spec.authquery
268
268
 
269
- // A route the definition ends with a slash keeps it, for a Django REST server,
270
- // and a host with no path takes /, or luasocket reads a query as the host.
271
- if let orig = gp(ctx.point, "orig").asString, orig.hasSuffix("/"), spec.suffix.isEmpty,
272
- !url.hasSuffix("/") {
269
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
270
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
271
+ let slashed = (gp(ctx.point, "orig").asString?.hasSuffix("/") ?? false) || spec.path.hasSuffix("/")
272
+ if slashed, spec.suffix.isEmpty, !url.hasSuffix("/") {
273
273
  url += "/"
274
274
  }
275
275
  if let authority = url.range(of: "://"), url.startIndex < authority.lowerBound,
@@ -425,6 +425,78 @@ final class PrimaryUtilityTest: XCTestCase {
425
425
  }
426
426
  }
427
427
 
428
+ // A Django route answers its slashless form with a relative Location. The
429
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
430
+ func testFetcherRedirect() throws {
431
+ #if os(Linux)
432
+ let fd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
433
+ #else
434
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
435
+ #endif
436
+ var addr = sockaddr_in()
437
+ addr.sin_family = sa_family_t(AF_INET)
438
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1")
439
+ var len = socklen_t(MemoryLayout<sockaddr_in>.size)
440
+ _ = withUnsafeMutablePointer(to: &addr) {
441
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, len) }
442
+ }
443
+ listen(fd, 8)
444
+ _ = withUnsafeMutablePointer(to: &addr) {
445
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &len) }
446
+ }
447
+ let base = "http://127.0.0.1:\(UInt16(bigEndian: addr.sin_port))"
448
+ defer { close(fd) }
449
+
450
+ let lock = NSLock()
451
+ var seen: [String] = []
452
+ let moved = ["/redirect/r1": "301 X\r\nLocation: /redirect/r1/", "/redirect/r1/": "308 X\r\nLocation: done"]
453
+ Thread.detachNewThread {
454
+ for _ in 0..<4 {
455
+ let conn = accept(fd, nil, nil)
456
+ if conn < 0 { return }
457
+ var head = ""
458
+ var buf = [UInt8](repeating: 0, count: 4096)
459
+ while !head.contains("\r\n\r\n") {
460
+ let got = buf.withUnsafeMutableBytes { read(conn, $0.baseAddress, $0.count) }
461
+ if got <= 0 { break }
462
+ head += String(decoding: buf[0..<got], as: UTF8.self)
463
+ }
464
+ let parts = head.split(separator: " ")
465
+ let path = 1 < parts.count ? String(parts[1]) : ""
466
+ lock.lock(); seen.append(path); lock.unlock()
467
+ let body = path == "/redirect/r1/done" ? "{\"id\":\"r1\"}" : ""
468
+ let status = moved[path] ?? (body.isEmpty ? "404 X" : "200 X")
469
+ let reply = Array(("HTTP/1.1 \(status)\r\nContent-Type: application/json\r\n" +
470
+ "Content-Length: \(body.utf8.count)\r\nConnection: close\r\n\r\n\(body)").utf8)
471
+ _ = reply.withUnsafeBytes { write(conn, $0.baseAddress, $0.count) }
472
+ close(conn)
473
+ }
474
+ }
475
+
476
+ let opts = VMap()
477
+ opts.entries["base"] = .string(base)
478
+ let liveClient = ProjectNameSDK(opts)
479
+ let liveUtility = liveClient.getUtility()
480
+ let ctx = liveUtility.makeContext(
481
+ ["opname": "load", "client": liveClient, "utility": liveUtility], nil)
482
+ func def(_ redirect: String?) -> VMap {
483
+ let fetchdef = VMap()
484
+ fetchdef.entries["method"] = .string("GET")
485
+ fetchdef.entries["headers"] = .map(VMap())
486
+ if let redirect = redirect { fetchdef.entries["redirect"] = .string(redirect) }
487
+ return fetchdef
488
+ }
489
+
490
+ let res = try liveUtility.fetcher(ctx, base + "/redirect/r1", def(nil))
491
+ XCTAssertEqual(gp(res, "status").asInt, 200)
492
+ XCTAssertEqual(gp(res, "body").asString, "{\"id\":\"r1\"}")
493
+ lock.lock(); let sent = seen; lock.unlock()
494
+ XCTAssertEqual(sent, ["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"])
495
+
496
+ let manual = try liveUtility.fetcher(ctx, base + "/redirect/r1", def("manual"))
497
+ XCTAssertEqual(gp(manual, "status").asInt, 301)
498
+ }
499
+
428
500
  // Nothing listens on port 9: a request the guard let through fails there.
429
501
  func testFetcherGetOnlyGuard() {
430
502
  let opts = VMap()
@@ -29,10 +29,12 @@ function makeUrl(ctx: Context): Error | string {
29
29
  // Sent with the request, never recorded as the entity's match.
30
30
  const authquery: string[] = spec.authquery || []
31
31
 
32
- // A route the definition ends with a slash keeps it, for a Django REST server,
33
- // and a host with no path takes /, or luasocket reads a query as the host.
32
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
33
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
34
34
  const orig = ctx.point?.orig
35
- if ('string' === typeof orig && orig.endsWith('/') && !spec.suffix && !url.endsWith('/')) {
35
+ const slashed = ('string' === typeof orig && orig.endsWith('/')) ||
36
+ ('string' === typeof spec.path && spec.path.endsWith('/'))
37
+ if (slashed && !spec.suffix && !url.endsWith('/')) {
36
38
  url += '/'
37
39
  }
38
40
  const authority = url.indexOf('://')