@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
@@ -407,6 +407,47 @@ class PrimaryUtilityTest {
407
407
  }
408
408
  }
409
409
 
410
+ // A Django route answers its slashless form with a relative Location. The
411
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
412
+ @Test
413
+ fun fetcherRedirect() {
414
+ val seen = java.util.Collections.synchronizedList(mutableListOf<String>())
415
+ val moved = mapOf("/redirect/r1" to (301 to "/redirect/r1/"), "/redirect/r1/" to (308 to "done"))
416
+ val server = com.sun.net.httpserver.HttpServer.create(java.net.InetSocketAddress("127.0.0.1", 0), 0)
417
+ server.createContext("/") { exchange ->
418
+ val path = exchange.requestURI.rawPath
419
+ seen.add(path)
420
+ val hop = moved[path]
421
+ val body = if (path == "/redirect/r1/done") "{\"id\":\"r1\"}".toByteArray() else ByteArray(0)
422
+ if (hop != null) exchange.responseHeaders.set("Location", hop.second)
423
+ exchange.responseHeaders.set("Content-Type", "application/json")
424
+ exchange.sendResponseHeaders(hop?.first ?: if (body.isNotEmpty()) 200 else 404,
425
+ if (body.isNotEmpty()) body.size.toLong() else -1L)
426
+ exchange.responseBody.write(body)
427
+ exchange.close()
428
+ }
429
+ server.start()
430
+ val base = "http://127.0.0.1:" + server.address.port
431
+ try {
432
+ val liveClient = ProjectNameSDK(fhMap("base", base))
433
+ val liveUtility = liveClient.getUtility()
434
+ val ctx = liveUtility.makeContext(
435
+ fhMap("opname", "load", "client", liveClient, "utility", liveUtility), null)
436
+
437
+ val res = liveUtility.fetcher(ctx, "$base/redirect/r1",
438
+ fhMap("method", "GET", "headers", linkedMapOf<String, Any?>())) as Map<*, *>
439
+ assertEquals(200, res["status"])
440
+ assertEquals("{\"id\":\"r1\"}", res["body"])
441
+ assertEquals(listOf("/redirect/r1", "/redirect/r1/", "/redirect/r1/done"), seen.toList())
442
+
443
+ val manual = liveUtility.fetcher(ctx, "$base/redirect/r1",
444
+ fhMap("method", "GET", "headers", linkedMapOf<String, Any?>(), "redirect", "manual")) as Map<*, *>
445
+ assertEquals(301, manual["status"])
446
+ } finally {
447
+ server.stop(0)
448
+ }
449
+ }
450
+
410
451
  // Nothing listens on port 9: a request the guard let through fails there.
411
452
  // A JVM cannot set its own environment, so the probe runs in a child JVM.
412
453
  @Test
@@ -114,11 +114,12 @@ fun makeUrl(ctx: Context): String {
114
114
  joinParts.add(spec.suffix)
115
115
  var url = Struct.join(joinParts, "/", true)
116
116
 
117
- // A route the definition ends with a slash keeps it, for a Django REST server,
118
- // and a host with no path takes /, or luasocket reads a query as the host.
117
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
118
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
119
119
  val point = ctx.point
120
120
  val orig = if (point == null) null else Struct.getprop(point, "orig", null)
121
- if (orig is String && orig.endsWith("/") && spec.suffix.isEmpty() && !url.endsWith("/")) {
121
+ val slashed = (orig is String && orig.endsWith("/")) || spec.path.endsWith("/")
122
+ if (slashed && spec.suffix.isEmpty() && !url.endsWith("/")) {
122
123
  url += "/"
123
124
  }
124
125
  val authority = url.indexOf("://")
@@ -504,6 +504,67 @@ describe("PrimaryUtility", function()
504
504
  end)
505
505
 
506
506
 
507
+ -- A Django route answers its slashless form with a relative Location. The
508
+ -- transport follows each hop, and answers a "manual" fetch with the 3xx.
509
+ -- Lua has no threads, so the server is a second interpreter.
510
+ local redirect_server = [[
511
+ local socket = require("socket")
512
+ local server = assert(socket.bind("127.0.0.1", 0))
513
+ server:settimeout(20)
514
+ io.stdout:write(select(2, server:getsockname()), "\n")
515
+ io.stdout:flush()
516
+ local moved = { ["/redirect/r1"] = { 301, "/redirect/r1/" }, ["/redirect/r1/"] = { 308, "done" } }
517
+ for _ = 1, 4 do
518
+ local sock = server:accept()
519
+ if not sock then break end
520
+ sock:settimeout(20)
521
+ local path = string.match(sock:receive("*l") or "", "^%S+ (%S+)") or ""
522
+ repeat local line = sock:receive("*l") until line == nil or line == ""
523
+ io.stdout:write(path, "\n")
524
+ local hop = moved[path]
525
+ local body = path == "/redirect/r1/done" and '{"id":"r1"}' or ""
526
+ sock:send("HTTP/1.1 " .. (hop and hop[1] or (body == "" and 404 or 200)) .. " X\r\n" ..
527
+ (hop and ("Location: " .. hop[2] .. "\r\n") or "") .. "Content-Type: application/json\r\n" ..
528
+ "Content-Length: " .. #body .. "\r\nConnection: close\r\n\r\n" .. body)
529
+ sock:close()
530
+ end
531
+ ]]
532
+
533
+ local has_socket = pcall(require, "socket.http")
534
+ ;(has_socket and it or pending)("fetcher-redirect", function()
535
+ local first = 0
536
+ while arg and arg[first - 1] ~= nil do first = first - 1 end
537
+ local lua = arg and first < 0 and arg[first] or "lua"
538
+ local script = os.tmpname()
539
+ local f = assert(io.open(script, "w"))
540
+ f:write(string.format("package.path = %q\npackage.cpath = %q\n", package.path, package.cpath), redirect_server)
541
+ f:close()
542
+ local child = assert(io.popen(string.format("%q %q", lua, script)))
543
+ local base = "http://127.0.0.1:" .. assert(child:read("*l"))
544
+
545
+ local live_client = sdk.new({ base = base })
546
+ local live_utility = live_client:get_utility()
547
+ local ctx = live_utility.make_context({
548
+ opname = "load",
549
+ client = live_client,
550
+ utility = live_utility,
551
+ }, nil)
552
+ local res, err = live_utility.fetcher(ctx, base .. "/redirect/r1", { method = "GET", headers = {} })
553
+ local manual, merr = live_utility.fetcher(ctx, base .. "/redirect/r1",
554
+ { method = "GET", headers = {}, redirect = "manual" })
555
+ local seen = child:read("*a")
556
+ child:close()
557
+ os.remove(script)
558
+
559
+ assert.is_nil(err)
560
+ assert.are.equal(200, res.status)
561
+ assert.are.same({ id = "r1" }, res.json())
562
+ assert.are.equal("/redirect/r1\n/redirect/r1/\n/redirect/r1/done\n/redirect/r1\n", seen)
563
+ assert.is_nil(merr)
564
+ assert.are.equal(301, manual.status)
565
+ end)
566
+
567
+
507
568
  -- Nothing listens on port 9: a request the guard let through fails there.
508
569
  -- Lua cannot set its own environment, so the test answers for os.getenv.
509
570
  it("fetcher-getonly-guard", function()
@@ -29,12 +29,7 @@ local function getonly_refusal(fullurl, method)
29
29
  "[GET-ONLY GUARD] blocked " .. method .. " " .. path)
30
30
  end
31
31
 
32
- local function default_http_fetch(fullurl, fetchdef)
33
- local refused = getonly_refusal(fullurl, fetchdef["method"])
34
- if refused then
35
- return nil, refused
36
- end
37
-
32
+ local function send_once(fullurl, fetchdef)
38
33
  -- Use LuaSocket or similar for real HTTP requests.
39
34
  -- This is the default live implementation.
40
35
  local http_ok, http = pcall(require, "socket.http")
@@ -76,6 +71,7 @@ local function default_http_fetch(fullurl, fetchdef)
76
71
  headers = headers,
77
72
  source = body_str and ltn12.source.string(body_str) or nil,
78
73
  sink = ltn12.sink.table(response_body),
74
+ redirect = false,
79
75
  })
80
76
 
81
77
  if not res then
@@ -117,6 +113,58 @@ local function default_http_fetch(fullurl, fetchdef)
117
113
  end
118
114
 
119
115
 
116
+ local REDIRECT_STATUS = { [301] = true, [302] = true, [303] = true, [307] = true, [308] = true }
117
+ local REDIRECT_MAX = 5
118
+ local CREDENTIAL_HEADERS = { authorization = true, cookie = true, ["proxy-authorization"] = true }
119
+
120
+ local function origin(u)
121
+ local parsed = require("socket.url").parse(u) or {}
122
+ local scheme = string.lower(parsed.scheme or "")
123
+ return scheme .. "://" .. string.lower(parsed.host or "") .. ":" ..
124
+ tostring(parsed.port or (scheme == "https" and 443 or 80))
125
+ end
126
+
127
+ -- luasocket follows no 308 and refuses a relative Location from https, so a
128
+ -- GET or HEAD follows a redirect here, unless the fetch definition says
129
+ -- "manual", each hop passing the GET-only guard first; past REDIRECT_MAX hops
130
+ -- the last 3xx is the answer. Another origin is not sent the credentials.
131
+ local function default_http_fetch(fullurl, fetchdef)
132
+ local method = string.upper(tostring(fetchdef["method"] or "GET"))
133
+ local follow = (method == "GET" or method == "HEAD") and fetchdef["redirect"] ~= "manual"
134
+ local url = fullurl
135
+ local hops = 0
136
+ while true do
137
+ local refused = getonly_refusal(url, fetchdef["method"])
138
+ if refused then
139
+ return nil, refused
140
+ end
141
+ local res, err = send_once(url, fetchdef)
142
+ local location = res ~= nil and res.headers ~= nil and res.headers["location"] or nil
143
+ if not follow or type(location) ~= "string" or hops >= REDIRECT_MAX
144
+ or not REDIRECT_STATUS[res.status] then
145
+ return res, err
146
+ end
147
+ local nexturl = string.gsub(require("socket.url").absolute(url, (string.gsub(location, "%s", ""))), "#.*$", "")
148
+ if origin(nexturl) ~= origin(url) then
149
+ local headers = {}
150
+ for k, v in pairs(fetchdef["headers"] or {}) do
151
+ if not CREDENTIAL_HEADERS[string.lower(k)] then
152
+ headers[k] = v
153
+ end
154
+ end
155
+ local copy = {}
156
+ for k, v in pairs(fetchdef) do
157
+ copy[k] = v
158
+ end
159
+ copy["headers"] = headers
160
+ fetchdef = copy
161
+ end
162
+ url = nexturl
163
+ hops = hops + 1
164
+ end
165
+ end
166
+
167
+
120
168
  local function fetcher_util(ctx, fullurl, fetchdef)
121
169
  if ctx.client.mode ~= "live" then
122
170
  return nil, ctx:make_error("fetch_mode_block",
@@ -24,11 +24,12 @@ local function make_url_util(ctx)
24
24
  authquery[name] = true
25
25
  end
26
26
 
27
- -- A route the definition ends with a slash keeps it, for a Django REST server,
28
- -- and a host with no path takes /, or luasocket reads a query as the host.
27
+ -- A route ending in a slash keeps it, as defined or as passed to direct(), for
28
+ -- Django, and a host with no path takes /, or luasocket reads a query as the host.
29
29
  local orig = ctx.point ~= nil and vs.getprop(ctx.point, "orig") or nil
30
- if type(orig) == "string" and orig:sub(-1) == "/" and (spec.suffix == nil or spec.suffix == "")
31
- and url:sub(-1) ~= "/" then
30
+ local slashed = (type(orig) == "string" and orig:sub(-1) == "/")
31
+ or (type(spec.path) == "string" and spec.path:sub(-1) == "/")
32
+ if slashed and (spec.suffix == nil or spec.suffix == "") and url:sub(-1) ~= "/" then
32
33
  url = url .. "/"
33
34
  end
34
35
  local authority = url:find("://", 1, true)
@@ -1351,12 +1351,12 @@ let make_url_util (ctx : ctx) : (string * sdk_error option) =
1351
1351
  | _, None -> ("", Some (ctx_make_error ctx "url_no_result" "Expected context result property to be defined."))
1352
1352
  | Some spec, Some result ->
1353
1353
  let url = ref (join ~sep:(Str "/") ~url:true (ja [Str spec.sp_base; Str spec.sp_prefix; Str spec.sp_path; Str spec.sp_suffix])) in
1354
- (* A route the definition ends with a slash keeps it, for a Django REST server,
1355
- * and a host with no path takes /, or luasocket reads a query as the host. *)
1354
+ (* A route ending in a slash keeps it, as defined or as passed to direct(), for
1355
+ * Django, and a host with no path takes /, or luasocket reads a query as the host. *)
1356
1356
  let ends_slash s = String.length s > 0 && '/' = s.[String.length s - 1] in
1357
- (match getp ctx.c_point "orig" with
1358
- | Str o when ends_slash o && spec.sp_suffix = "" && not (ends_slash !url) -> url := !url ^ "/"
1359
- | _ -> ());
1357
+ let orig_slash = match getp ctx.c_point "orig" with Str o -> ends_slash o | _ -> false in
1358
+ if (orig_slash || ends_slash spec.sp_path) && spec.sp_suffix = "" && not (ends_slash !url)
1359
+ then url := !url ^ "/";
1360
1360
  let ulen = String.length !url in
1361
1361
  let rec scheme_end i =
1362
1362
  if i + 3 > ulen then -1 else if String.sub !url i 3 = "://" then i else scheme_end (i + 1) in
@@ -430,6 +430,60 @@ runsection('makeError', sub {
430
430
  like("$err", qr/blocked/, 'fetcher blocked: error contains "blocked"');
431
431
  }
432
432
 
433
+ # A Django route answers its slashless form with a relative Location. The
434
+ # transport follows each hop, and answers a "manual" fetch with the 3xx.
435
+ SKIP: {
436
+ require IO::Socket::INET;
437
+ require POSIX;
438
+ my $server = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 5, ReuseAddr => 1);
439
+ pipe(my $seen_r, my $seen_w) or skip('no pipe', 6);
440
+ my $pid = fork();
441
+ skip('no fork', 6) unless defined $pid;
442
+ if (0 == $pid) {
443
+ close $seen_r;
444
+ $seen_w->autoflush(1);
445
+ my %moved = ('/redirect/r1' => [301, '/redirect/r1/'], '/redirect/r1/' => [308, 'done']);
446
+ for (1 .. 4) {
447
+ my $sock = $server->accept or last;
448
+ my (undef, $path) = split / /, (<$sock> // '');
449
+ while (defined(my $line = <$sock>)) { last if $line =~ /\A\r?\n\z/ }
450
+ print {$seen_w} "$path\n";
451
+ my $hop = $moved{$path // ''};
452
+ my $body = ($path // '') eq '/redirect/r1/done' ? '{"id":"r1"}' : '';
453
+ print {$sock} 'HTTP/1.1 ' . ($hop ? $hop->[0] : '' eq $body ? 404 : 200) . " X\r\n"
454
+ . ($hop ? "Location: $hop->[1]\r\n" : '') . "Content-Type: application/json\r\n"
455
+ . 'Content-Length: ' . length($body) . "\r\nConnection: close\r\n\r\n" . $body;
456
+ close $sock;
457
+ }
458
+ POSIX::_exit(0);
459
+ }
460
+ close $seen_w;
461
+ my $base = 'http://127.0.0.1:' . $server->sockport;
462
+ close $server;
463
+
464
+ my $live_client = ProjectNameSDK->new({ 'base' => $base });
465
+ my $live_utility = $live_client->get_utility;
466
+ my $ctx = $live_utility->{make_context}->({
467
+ 'opname' => 'load',
468
+ 'client' => $live_client,
469
+ 'utility' => $live_utility,
470
+ }, undef);
471
+
472
+ my ($res, $err) = $live_utility->{fetcher}->($ctx, "$base/redirect/r1", { 'method' => 'GET', 'headers' => {} });
473
+ ok(!defined $err, 'fetcher redirect: no error');
474
+ is($res && $res->{status}, 200, 'fetcher redirect: the last hop answers');
475
+ is_deeply($res && $res->{json}->(), { 'id' => 'r1' }, 'fetcher redirect: its body is read');
476
+
477
+ my ($manual, $merr) = $live_utility->{fetcher}->($ctx, "$base/redirect/r1",
478
+ { 'method' => 'GET', 'headers' => {}, 'redirect' => 'manual' });
479
+ ok(!defined $merr, 'fetcher redirect manual: no error');
480
+ is($manual && $manual->{status}, 301, 'fetcher redirect manual: answered by the 301');
481
+
482
+ my $seen = do { local $/; <$seen_r> };
483
+ waitpid($pid, 0);
484
+ is($seen, "/redirect/r1\n/redirect/r1/\n/redirect/r1/done\n/redirect/r1\n", 'fetcher redirect: each hop is sent');
485
+ }
486
+
433
487
  # Nothing listens on port 9: a request the guard let through fails there.
434
488
  {
435
489
  my $live_client = ProjectNameSDK->new({ 'base' => 'http://127.0.0.1:9' });
@@ -43,13 +43,74 @@ sub getonly_refusal {
43
43
  "[GET-ONLY GUARD] blocked $method $path");
44
44
  }
45
45
 
46
+ our @REDIRECT_STATUS = (301, 302, 303, 307, 308);
47
+ our $REDIRECT_MAX = 5;
48
+
49
+ # The Location resolved against the URL that answered with it (RFC 3986 5.2).
50
+ sub resolve_location {
51
+ my ($base, $loc) = @_;
52
+ $loc =~ s/\s+//g;
53
+ $loc =~ s/#.*//s;
54
+ return $loc if $loc =~ m{\A[A-Za-z][A-Za-z0-9+.-]*:};
55
+ my ($scheme, $auth, $path, $query) = $base =~ m{\A([^:/?#]+):(?://([^/?#]*))?([^?#]*)(\?[^#]*)?};
56
+ return undef unless defined $scheme;
57
+ return "$scheme:$loc" if $loc =~ m{\A//};
58
+ $path = '/' if '' eq $path;
59
+ my ($lpath, $lquery) = $loc =~ m{\A([^?]*)(\?.*)?\z}s;
60
+ if ('' eq $lpath) {
61
+ $lpath = $path;
62
+ $lquery = $query unless defined $lquery;
63
+ }
64
+ elsif ($lpath !~ m{\A/}) {
65
+ (my $dir = $path) =~ s{[^/]*\z}{};
66
+ $lpath = $dir . $lpath;
67
+ }
68
+ my @out;
69
+ for my $seg (split m{/}, $lpath, -1) {
70
+ if ('..' eq $seg) { pop @out if 1 < @out; }
71
+ elsif ('.' ne $seg) { push @out, $seg; }
72
+ }
73
+ push @out, '' if $lpath =~ m{(?:\A|/)\.\.?\z};
74
+ return "$scheme://" . ($auth // '') . join('/', @out) . ($lquery // '');
75
+ }
76
+
77
+ sub _origin {
78
+ my ($url) = @_;
79
+ my ($scheme, $host, $port) = lc($url) =~ m{\A([^:/?#]+)://(?:[^@/?#]*@)?(\[[^\]]*\]|[^:/?#]*)(?::(\d+))?};
80
+ return join ':', $scheme // '', $host // '', $port // ('https' eq ($scheme // '') ? 443 : 80);
81
+ }
82
+
83
+ # HTTP::Tiny cannot resolve a relative-path Location, so it follows none here.
84
+ # A GET or HEAD follows a redirect, unless the fetch definition says "manual",
85
+ # each hop passing the GET-only guard first; past $REDIRECT_MAX hops the last
86
+ # 3xx is the answer. Another origin is not sent the request's credentials.
46
87
  our $DefaultHttpFetch = sub {
47
88
  my ($fullurl, $fetchdef) = @_;
48
89
  $fetchdef = {} unless defined $fetchdef;
49
90
 
50
91
  my $method = uc(defined $fetchdef->{method} ? "$fetchdef->{method}" : 'GET');
51
- my $refused = getonly_refusal($fullurl, $method);
52
- return (undef, $refused) if $refused;
92
+ my $follow = ($method eq 'GET' || $method eq 'HEAD')
93
+ && !(defined $fetchdef->{redirect} && !ref $fetchdef->{redirect} && 'manual' eq $fetchdef->{redirect});
94
+ my $url = $fullurl;
95
+ for (my $hops = 0; ; $hops++) {
96
+ my $refused = getonly_refusal($url, $method);
97
+ return (undef, $refused) if $refused;
98
+ my ($res, $err) = _send_once($url, $fetchdef, $method);
99
+ my $location = $res ? $res->{headers}{location} : undef;
100
+ my $next = $follow && defined $location && !ref $location && $hops < $REDIRECT_MAX
101
+ && (grep { $_ == $res->{status} } @REDIRECT_STATUS) ? resolve_location($url, $location) : undef;
102
+ return ($res, $err) unless defined $next;
103
+ if (_origin($next) ne _origin($url)) {
104
+ my $headers = Voxgig::Struct::ismap($fetchdef->{headers}) ? $fetchdef->{headers} : {};
105
+ $fetchdef = { %$fetchdef, headers => { map { $_ => $headers->{$_} }
106
+ grep { lc($_) !~ /\A(?:authorization|cookie|proxy-authorization)\z/ } keys %$headers } };
107
+ }
108
+ $url = $next;
109
+ }
110
+ };
111
+
112
+ sub _send_once {
113
+ my ($fullurl, $fetchdef, $method) = @_;
53
114
  my $body = $fetchdef->{body};
54
115
  my $headers = Voxgig::Struct::ismap($fetchdef->{headers}) ? $fetchdef->{headers} : {};
55
116
 
@@ -83,14 +144,7 @@ our $DefaultHttpFetch = sub {
83
144
  $opts->{content} = $content;
84
145
  }
85
146
 
86
- # fetchdef.redirect 'manual' (the ts fetch vocabulary): return a 3xx
87
- # as-is instead of following it. HTTP::Tiny follows redirects by
88
- # default; the station feature's hosts policy sets this so a Location
89
- # off the allowlist can never pull an automatic credentialed follow-up.
90
- my %new_args;
91
- $new_args{max_redirect} = 0
92
- if defined $fetchdef->{redirect} && !ref $fetchdef->{redirect}
93
- && 'manual' eq $fetchdef->{redirect};
147
+ my %new_args = (max_redirect => 0);
94
148
  # Both keys: HTTP::Tiny lets the environment override its generic proxy.
95
149
  $new_args{http_proxy} = $new_args{https_proxy} = "$fetchdef->{proxy}"
96
150
  if defined $fetchdef->{proxy} && !ref $fetchdef->{proxy}
@@ -137,7 +191,7 @@ our $DefaultHttpFetch = sub {
137
191
  'body' => $res->{content},
138
192
  'unreadable' => $unreadable,
139
193
  }, undef);
140
- };
194
+ }
141
195
 
142
196
  $REGISTRY{fetcher} = sub {
143
197
  my ($ctx, $fullurl, $fetchdef) = @_;
@@ -32,10 +32,11 @@ $REGISTRY{make_url} = sub {
32
32
  # Sent with the request, never recorded as the entity's match.
33
33
  my %authquery = map { $_ => 1 } @{ $spec->{authquery} || [] };
34
34
 
35
- # A route the definition ends with a slash keeps it, for a Django REST server,
36
- # and a host with no path takes /, or luasocket reads a query as the host.
35
+ # A route ending in a slash keeps it, as defined or as passed to direct(), for
36
+ # Django, and a host with no path takes /, or luasocket reads a query as the host.
37
37
  my $orig = $ctx->{point} ? ProjectNameHelpers::gp($ctx->{point}, 'orig') : undef;
38
- $url .= '/' if defined $orig && !ref $orig && $orig =~ m{/\z}
38
+ my $slashed = grep { defined $_ && !ref $_ && m{/\z} } $orig, $spec->{path};
39
+ $url .= '/' if $slashed
39
40
  && !(defined $spec->{suffix} && '' ne $spec->{suffix}) && $url !~ m{/\z};
40
41
  my $authority = index($url, '://');
41
42
  $url .= '/' if 0 < $authority && substr($url, $authority + 3) !~ m{[/?#]};
@@ -511,6 +511,58 @@ class PipelineTest extends TestCase
511
511
  }
512
512
 
513
513
 
514
+ // A Django route answers its slashless form with a relative Location. The
515
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
516
+ // The server is a child process: PHP serves nothing while it waits.
517
+ public function test_fetcher_follows_a_relative_redirect(): void
518
+ {
519
+ if (!function_exists('proc_open')) {
520
+ $this->markTestSkipped('the server runs in a child process');
521
+ }
522
+ $server = <<<'SERVER'
523
+ $srv = stream_socket_server('tcp://127.0.0.1:0');
524
+ fwrite(STDOUT, explode(':', stream_socket_get_name($srv, false))[1] . "\n");
525
+ fflush(STDOUT);
526
+ $moved = ['/redirect/r1' => [301, '/redirect/r1/'], '/redirect/r1/' => [308, 'done']];
527
+ for ($i = 0; $i < 4 && ($sock = @stream_socket_accept($srv, 20)); $i++) {
528
+ $path = explode(' ', (string)fgets($sock))[1] ?? '';
529
+ while (!in_array(fgets($sock), ["\r\n", "\n", false], true)) {
530
+ }
531
+ fwrite(STDOUT, $path . "\n");
532
+ $hop = $moved[$path] ?? null;
533
+ $body = '/redirect/r1/done' === $path ? '{"id":"r1"}' : '';
534
+ fwrite($sock, 'HTTP/1.1 ' . ($hop[0] ?? ('' === $body ? 404 : 200)) . " X\r\n"
535
+ . (null === $hop ? '' : "Location: {$hop[1]}\r\n") . "Content-Type: application/json\r\n"
536
+ . 'Content-Length: ' . strlen($body) . "\r\nConnection: close\r\n\r\n" . $body);
537
+ fclose($sock);
538
+ }
539
+ SERVER;
540
+ $proc = proc_open([PHP_BINARY, '-r', $server], [1 => ['pipe', 'w']], $pipes);
541
+ try {
542
+ $base = 'http://127.0.0.1:' . trim((string)fgets($pipes[1]));
543
+ $client = new ProjectNameSDK(['base' => $base]);
544
+ $utility = $client->get_utility();
545
+ $ctx = ($utility->make_context)(['opname' => 'load', 'client' => $client,
546
+ 'utility' => $utility], null);
547
+
548
+ [$res, $err] = ($utility->fetcher)($ctx, $base . '/redirect/r1', ['method' => 'GET', 'headers' => []]);
549
+ $this->assertNull($err);
550
+ $this->assertSame(200, $res['status']);
551
+ $this->assertSame(['id' => 'r1'], ($res['json'])());
552
+
553
+ [$manual, $merr] = ($utility->fetcher)($ctx, $base . '/redirect/r1',
554
+ ['method' => 'GET', 'headers' => [], 'redirect' => 'manual']);
555
+ $this->assertNull($merr);
556
+ $this->assertSame(301, $manual['status']);
557
+ $this->assertSame("/redirect/r1\n/redirect/r1/\n/redirect/r1/done\n/redirect/r1\n",
558
+ stream_get_contents($pipes[1]));
559
+ } finally {
560
+ proc_terminate($proc);
561
+ proc_close($proc);
562
+ }
563
+ }
564
+
565
+
514
566
  // The guard writes to STDERR, so it is read from a child process. Nothing
515
567
  // listens on port 9: a request the guard let through fails there.
516
568
  public function test_get_only_guard_prints_no_query_credential(): void
@@ -46,13 +46,89 @@ class ProjectNameFetcher
46
46
  return new ProjectNameError('fetch_getonly_block', "[GET-ONLY GUARD] blocked {$method} {$path}");
47
47
  }
48
48
 
49
+ public const REDIRECT_STATUS = [301, 302, 303, 307, 308];
50
+ public const REDIRECT_MAX = 5;
51
+
52
+ // Neither transport below follows a redirect. A GET or HEAD follows one
53
+ // here, unless the fetch definition says "manual", each hop passing the
54
+ // GET-only guard first; past REDIRECT_MAX hops the last 3xx is the answer.
55
+ // Another origin is not sent the request's credentials.
49
56
  public static function defaultHttpFetch(string $fullurl, array $fetchdef): array
50
57
  {
51
58
  $method_str = strtoupper($fetchdef['method'] ?? 'GET');
52
- $refused = self::getOnlyRefusal($fullurl, $method_str);
53
- if (null !== $refused) {
54
- return [null, $refused];
59
+ $follow = in_array($method_str, ['GET', 'HEAD'], true) && ($fetchdef['redirect'] ?? null) !== 'manual';
60
+ $url = $fullurl;
61
+ for ($hops = 0; ; $hops++) {
62
+ $refused = self::getOnlyRefusal($url, $method_str);
63
+ if (null !== $refused) {
64
+ return [null, $refused];
65
+ }
66
+ [$res, $err] = self::sendOnce($url, $method_str, $fetchdef);
67
+ $location = is_array($res) ? ($res['headers']['location'] ?? null) : null;
68
+ $next = $follow && is_string($location) && $hops < self::REDIRECT_MAX
69
+ && in_array($res['status'], self::REDIRECT_STATUS, true)
70
+ ? self::resolveLocation($url, $location) : null;
71
+ if (null === $next) {
72
+ return [$res, $err];
73
+ }
74
+ if (self::origin($next) !== self::origin($url)) {
75
+ $fetchdef['headers'] = array_filter($fetchdef['headers'] ?? [],
76
+ fn($k) => !in_array(strtolower((string)$k), ['authorization', 'cookie', 'proxy-authorization'], true),
77
+ ARRAY_FILTER_USE_KEY);
78
+ }
79
+ $url = $next;
80
+ }
81
+ }
82
+
83
+ // The Location resolved against the URL that answered with it (RFC 3986 5.2).
84
+ public static function resolveLocation(string $base, string $loc): ?string
85
+ {
86
+ $loc = preg_replace('/#.*$/s', '', preg_replace('/\s+/', '', $loc));
87
+ if (preg_match('/^[A-Za-z][A-Za-z0-9+.-]*:/', $loc)) {
88
+ return $loc;
89
+ }
90
+ if (!preg_match('~^([^:/?#]+):(?://([^/?#]*))?([^?#]*)(\?[^#]*)?~', $base, $m)) {
91
+ return null;
92
+ }
93
+ [$scheme, $auth, $path, $query] = [$m[1], $m[2] ?? '', $m[3] ?? '', $m[4] ?? ''];
94
+ if (str_starts_with($loc, '//')) {
95
+ return $scheme . ':' . $loc;
96
+ }
97
+ $path = '' === $path ? '/' : $path;
98
+ $qat = strpos($loc, '?');
99
+ $lpath = false === $qat ? $loc : substr($loc, 0, $qat);
100
+ $lquery = false === $qat ? null : substr($loc, $qat);
101
+ if ('' === $lpath) {
102
+ $lpath = $path;
103
+ $lquery = $lquery ?? $query;
104
+ } elseif ('/' !== $lpath[0]) {
105
+ $lpath = substr($path, 0, strrpos($path, '/') + 1) . $lpath;
55
106
  }
107
+ $out = [];
108
+ foreach (explode('/', $lpath) as $seg) {
109
+ if ('..' === $seg) {
110
+ if (1 < count($out)) {
111
+ array_pop($out);
112
+ }
113
+ } elseif ('.' !== $seg) {
114
+ $out[] = $seg;
115
+ }
116
+ }
117
+ if (preg_match('~(^|/)\.\.?$~', $lpath)) {
118
+ $out[] = '';
119
+ }
120
+ return $scheme . '://' . $auth . implode('/', $out) . ($lquery ?? '');
121
+ }
122
+
123
+ private static function origin(string $url): string
124
+ {
125
+ $p = parse_url(strtolower($url));
126
+ $scheme = $p['scheme'] ?? '';
127
+ return $scheme . '://' . ($p['host'] ?? '') . ':' . ($p['port'] ?? ('https' === $scheme ? 443 : 80));
128
+ }
129
+
130
+ private static function sendOnce(string $fullurl, string $method_str, array $fetchdef): array
131
+ {
56
132
  $body_str = $fetchdef['body'] ?? null;
57
133
  if (is_resource($body_str)) {
58
134
  $body_str = stream_get_contents($body_str);
@@ -76,8 +152,7 @@ class ProjectNameFetcher
76
152
  // Prefer cURL when available — its header capture is reliable across
77
153
  // PHP versions, while file_get_contents + custom stream wrappers
78
154
  // don't propagate $http_response_header for user-defined wrappers
79
- // in PHP 8.3+. (cURL is configured with FOLLOWLOCATION off, so the
80
- // manual-redirect annotation below holds there by construction.)
155
+ // in PHP 8.3+.
81
156
  if (function_exists('curl_init')) {
82
157
  return self::curlFetch($fullurl, $method_str, $body_str, $header_lines);
83
158
  }
@@ -86,19 +161,10 @@ class ProjectNameFetcher
86
161
  'http' => [
87
162
  'method' => $method_str,
88
163
  'ignore_errors' => true,
164
+ 'follow_location' => 0,
89
165
  ],
90
166
  ];
91
167
 
92
- // Honour a redirect annotation on the fetch definition (set by the
93
- // station feature's middleware under a hosts policy): "manual"
94
- // surfaces a 3xx as an ordinary response instead of auto-following
95
- // it — the http stream wrapper otherwise replays the request,
96
- // headers included, against whatever host Location names, carrying
97
- // injected credentials to a host no policy approved.
98
- if (($fetchdef['redirect'] ?? null) === 'manual') {
99
- $opts['http']['follow_location'] = 0;
100
- }
101
-
102
168
  if (is_string($body_str)) {
103
169
  $opts['http']['content'] = $body_str;
104
170
  }
@@ -23,10 +23,12 @@ class ProjectNameMakeUrl
23
23
  // Sent with the request, never recorded as the entity's match.
24
24
  $authquery = $spec->authquery ?? [];
25
25
 
26
- // A route the definition ends with a slash keeps it, for a Django REST server,
27
- // and a host with no path takes /, or luasocket reads a query as the host.
26
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
27
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
28
28
  $orig = $ctx->point ? \Voxgig\Struct\Struct::getprop($ctx->point, 'orig') : null;
29
- if (is_string($orig) && str_ends_with($orig, '/') && '' === $spec->suffix && !str_ends_with($url, '/')) {
29
+ $slashed = (is_string($orig) && str_ends_with($orig, '/'))
30
+ || (is_string($spec->path) && str_ends_with($spec->path, '/'));
31
+ if ($slashed && '' === $spec->suffix && !str_ends_with($url, '/')) {
30
32
  $url .= '/';
31
33
  }
32
34
  $authority = strpos($url, '://');
@@ -30,6 +30,7 @@ def _session():
30
30
  with _SESSION_LOCK:
31
31
  if _SESSION is None:
32
32
  session = requests.Session()
33
+ session.max_redirects = 5
33
34
  session.cookies.set_policy(DefaultCookiePolicy(allowed_domains=[]))
34
35
  _SESSION = session
35
36
  return _SESSION