@voxgig/sdkgen 4.37.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 (107) 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/TestDirect_go.ts +12 -10
  29. package/project/.sdk/src/cmp/go/TestEntity_go.ts +67 -23
  30. package/project/.sdk/src/cmp/java/TestDirect_java.ts +12 -11
  31. package/project/.sdk/src/cmp/java/TestEntity_java.ts +71 -23
  32. package/project/.sdk/src/cmp/js/TestDirect_js.ts +13 -12
  33. package/project/.sdk/src/cmp/js/TestEntity_js.ts +41 -17
  34. package/project/.sdk/src/cmp/kotlin/TestDirect_kotlin.ts +12 -10
  35. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +64 -23
  36. package/project/.sdk/src/cmp/lua/TestDirect_lua.ts +9 -5
  37. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +61 -23
  38. package/project/.sdk/src/cmp/perl/TestDirect_perl.ts +9 -5
  39. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +58 -24
  40. package/project/.sdk/src/cmp/php/TestDirect_php.ts +9 -5
  41. package/project/.sdk/src/cmp/php/TestEntity_php.ts +61 -23
  42. package/project/.sdk/src/cmp/py/TestDirect_py.ts +10 -6
  43. package/project/.sdk/src/cmp/py/TestEntity_py.ts +59 -27
  44. package/project/.sdk/src/cmp/rb/TestDirect_rb.ts +9 -5
  45. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +59 -23
  46. package/project/.sdk/src/cmp/rust/TestDirect_rust.ts +9 -8
  47. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +56 -24
  48. package/project/.sdk/src/cmp/scala/TestDirect_scala.ts +3 -2
  49. package/project/.sdk/src/cmp/scala/TestEntity_scala.ts +36 -9
  50. package/project/.sdk/src/cmp/ts/TestDirect_ts.ts +15 -32
  51. package/project/.sdk/src/cmp/ts/TestEntity_ts.ts +41 -17
  52. package/project/.sdk/tm/c/tests/transport_test.c +33 -0
  53. package/project/.sdk/tm/c/utility/fetcher.c +151 -2
  54. package/project/.sdk/tm/c/utility/make_url.c +8 -6
  55. package/project/.sdk/tm/clojure/src/sdk/core.clj +17 -10
  56. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +38 -0
  57. package/project/.sdk/tm/cpp/utility/pipeline.hpp +5 -4
  58. package/project/.sdk/tm/csharp/test/PrimaryUtilityTest.cs +69 -0
  59. package/project/.sdk/tm/csharp/utility/Fetcher.cs +3 -1
  60. package/project/.sdk/tm/csharp/utility/MakeUrl.cs +5 -4
  61. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +10 -6
  62. package/project/.sdk/tm/elixir/test/pipeline_test.exs +61 -0
  63. package/project/.sdk/tm/go/test/primary_utility_test.go +60 -0
  64. package/project/.sdk/tm/go/utility/fetcher.go +15 -4
  65. package/project/.sdk/tm/go/utility/make_url.go +4 -3
  66. package/project/.sdk/tm/java/test/PrimaryUtilityTest.java +47 -0
  67. package/project/.sdk/tm/java/utility/MakeUrl.java +5 -4
  68. package/project/.sdk/tm/js/src/utility/MakeUrlUtility.js +5 -3
  69. package/project/.sdk/tm/js/test/live-runner.js +4 -3
  70. package/project/.sdk/tm/js/test/utility/PrimaryUtility.test.js +40 -0
  71. package/project/.sdk/tm/kotlin/test/PrimaryUtilityTest.kt +41 -0
  72. package/project/.sdk/tm/kotlin/utility/MakeSpecUrl.kt +4 -3
  73. package/project/.sdk/tm/lua/test/primary_utility_test.lua +61 -0
  74. package/project/.sdk/tm/lua/utility/fetcher.lua +54 -6
  75. package/project/.sdk/tm/lua/utility/make_url.lua +5 -4
  76. package/project/.sdk/tm/ocaml/sdk_runtime.ml +5 -5
  77. package/project/.sdk/tm/perl/t/primary_utility.t +54 -0
  78. package/project/.sdk/tm/perl/utility/fetcher.pm +65 -11
  79. package/project/.sdk/tm/perl/utility/make_url.pm +4 -3
  80. package/project/.sdk/tm/php/test/PipelineTest.php +52 -0
  81. package/project/.sdk/tm/php/utility/Fetcher.php +81 -15
  82. package/project/.sdk/tm/php/utility/MakeUrl.php +5 -3
  83. package/project/.sdk/tm/py/pkg/utility/fetcher.py +1 -0
  84. package/project/.sdk/tm/py/pkg/utility/make_url.py +5 -4
  85. package/project/.sdk/tm/py/test/test_primary_utility.py +52 -0
  86. package/project/.sdk/tm/rb/test/primary_utility_test.rb +46 -0
  87. package/project/.sdk/tm/rb/utility/fetcher.rb +41 -5
  88. package/project/.sdk/tm/rb/utility/make_url.rb +5 -3
  89. package/project/.sdk/tm/rust/tests/primary_utility_test.rs +65 -0
  90. package/project/.sdk/tm/rust/utility/make_url.rs +7 -6
  91. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +47 -1
  92. package/project/.sdk/tm/scala/utility/Make.scala +8 -6
  93. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +59 -15
  94. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Make.swift +4 -4
  95. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/PrimaryUtilityTest.swift +72 -0
  96. package/project/.sdk/tm/ts/src/utility/MakeUrlUtility.ts +5 -3
  97. package/project/.sdk/tm/ts/test/live-runner.ts +4 -3
  98. package/project/.sdk/tm/ts/test/utility/PrimaryUtility.test.ts +40 -0
  99. package/project/.sdk/tm/zig/core/utility.zig +5 -5
  100. package/project/sdkgen-package.json +1 -1
  101. package/src/helpers/flowGuard.ts +4 -4
  102. package/src/helpers/liveDiscovery.ts +31 -0
  103. package/src/helpers/opShape.ts +6 -0
  104. package/src/helpers/pointPath.ts +8 -0
  105. package/src/helpers/testPolicy.ts +193 -55
  106. package/src/sdkgen.ts +13 -3
  107. package/src/utility.ts +10 -4
@@ -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
@@ -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" })