Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -989,10 +989,15 @@ func Proxy(w http.ResponseWriter, r *http.Request) {
`route.go` も。
- `Relayer-*` ヘッダはどちらの場合もクライアントには届きません。
- プロキシに渡る CGI 環境は `route.go` と同じですが、ルート変数は
渡しません(マッチ前に走るため)。代わりに **`RELAYER_MATCHED_PATTERN`**
に、そのパスがマッチするであろうパターン(`/api/users/[id]`)、404 なら
空が入ります。`matcher` 相当の設定はなく、`r.URL.Path` を見て自分で
分岐します。
渡しません(マッチ前に走るため)。代わりにリクエストヘッダ
**`Relayer-Matched-Pattern`** に、そのパスがマッチするであろうパターン
(`/api/users/[id]`)、404 なら空が入ります。
`r.Header.Get("Relayer-Matched-Pattern")` で読みます。クライアントが同じ名前の
ヘッダを送っても置き換えられ、プロキシの後ろのルートにはこのヘッダは
渡りません。同じ値は環境変数 `RELAYER_MATCHED_PATTERN` にも入りますが、
こちらは非推奨です。環境変数はプロセス単位なので、複数のリクエストを
処理するハンドラはリクエストごとの値をそこから受け取れません。
`matcher` 相当の設定はなく、`r.URL.Path` を見て自分で分岐します。
- ミドルウェアはアプリに 1 つ: `middleware.php` **と** `middleware.go`
が両方あると、毎リクエスト両方のパスを含む `RuntimeException` に
なります。`relayer routes` の末尾に `middleware src/Pages/middleware.go
Expand Down
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -983,9 +983,15 @@ func Proxy(w http.ResponseWriter, r *http.Request) {
`route.php`, not a `route.go`.
- `Relayer-*` headers never reach the client in either case.
- The proxy gets the same CGI environment as a `route.go`, minus the route
variables (it runs before matching) plus **`RELAYER_MATCHED_PATTERN`**:
the pattern the path would match (`/api/users/[id]`), empty for a 404.
There is no `matcher` config; branch on `r.URL.Path` yourself.
variables (it runs before matching), plus the pattern the path would
match (`/api/users/[id]`, empty for a 404) in the request header
**`Relayer-Matched-Pattern`**: read it with
`r.Header.Get("Relayer-Matched-Pattern")`. A client-sent header of that
name is replaced, and the route behind the proxy does not see it. The
same value is still in the environment variable `RELAYER_MATCHED_PATTERN`,
which is deprecated: the environment belongs to the process, so a
handler that serves more than one request cannot get a per-request value
from it. There is no `matcher` config; branch on `r.URL.Path` yourself.
- One middleware per app: `middleware.php` **and** `middleware.go` both
present is a `RuntimeException` naming both files, on every request.
`relayer routes` ends with a `middleware src/Pages/middleware.go
Expand Down
2 changes: 1 addition & 1 deletion src/Router/Native/CgiRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
* {@see NativeProcessException} with the process's stderr attached; the
* dispatcher turns that into a JSON 500 and a log line.
*/
final class CgiRunner
final class CgiRunner implements NativeRunner
{
/** Default wall-clock budget for one handler process, in seconds. */
public const DEFAULT_TIMEOUT = 30;
Expand Down
7 changes: 4 additions & 3 deletions src/Router/Native/NativeDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@

/**
* Serves a matched native route (`route.go`): finds the binary
* `relayer native:build` produced for it, runs it through {@see CgiRunner}
* and writes the result — or a JSON `500` saying exactly why that did
* `relayer native:build` produced for it, runs it through a
* {@see NativeRunner} ({@see CgiRunner} unless told otherwise) and writes
* the result — or a JSON `500` saying exactly why that did
* not happen.
*
* Deliberately never builds anything: a request must not run `go build`.
Expand Down Expand Up @@ -53,7 +54,7 @@ final class NativeDispatcher
*/
public function __construct(
private readonly string $binDir,
private readonly CgiRunner $runner,
private readonly NativeRunner $runner,
private readonly bool $devHints = false,
private readonly ?LoggerInterface $logger = null,
) {}
Expand Down
40 changes: 30 additions & 10 deletions src/Router/Native/NativeProxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,18 @@
* could not be handed ({@see CgiRequestUri}), even when a guard has already
* routed the request on another path.
*
* Besides the route variables' absence, the environment is the same as a
* `route.go` gets, plus `RELAYER_MATCHED_PATTERN`: the pattern the
* request path would match (`/api/users/[id]`), or empty for a 404 — the
* proxy runs *before* dispatch, so this is the one piece of routing it
* can see without re-implementing the router.
* Besides the route variables' absence, the proxy sees what a `route.go`
* sees, plus the pattern the request path would match (`/api/users/[id]`,
* empty for a 404) — the proxy runs *before* dispatch, so this is the one
* piece of routing it can see without re-implementing the router. It
* arrives twice: as the request header `Relayer-Matched-Pattern`
* ({@see HEADER_MATCHED_PATTERN}), which is what a handler should read,
* and as the environment variable `RELAYER_MATCHED_PATTERN`, kept for
* proxies written against it. Only the header works for a handler that
* is not a process of its own per request, where the environment is
* shared by every request. A client-sent `Relayer-Matched-Pattern` is
* replaced, never passed through, and the header is added only to what
* the proxy sees: the route behind it gets the request without it.
*/
final class NativeProxy
{
Expand All @@ -57,7 +64,16 @@ final class NativeProxy
/** Response header prefix: `Relayer-Request-Header-X-User: 42` sets request header `X-User`. */
public const HEADER_REQUEST_HEADER_PREFIX = 'Relayer-Request-Header-';

/** Environment variable: the pattern the request would match, or empty. */
/** Request header the proxy reads: the pattern the request would match, or empty. */
public const HEADER_MATCHED_PATTERN = 'Relayer-Matched-Pattern';

/**
* Environment variable carrying the same value as {@see HEADER_MATCHED_PATTERN}.
*
* @deprecated read the `Relayer-Matched-Pattern` request header instead; the
* environment is per process, so a resident handler cannot see a
* per-request value here
*/
public const ENV_MATCHED_PATTERN = 'RELAYER_MATCHED_PATTERN';

/**
Expand All @@ -78,7 +94,7 @@ final class NativeProxy
public function __construct(
private readonly string $binary,
private readonly string $source,
private readonly CgiRunner $runner,
private readonly NativeRunner $runner,
private readonly Closure $matchedPattern,
private readonly bool $devHints = false,
private readonly ?LoggerInterface $logger = null,
Expand Down Expand Up @@ -134,10 +150,14 @@ public function handle(Request $request, Closure $next): void
return;
}

$pattern = ($this->matchedPattern)($request) ?? '';

try {
$run = $this->runner->run($this->binary, $request, [
self::ENV_MATCHED_PATTERN => ($this->matchedPattern)($request) ?? '',
]);
$run = $this->runner->run(
$this->binary,
$request->withHeader(self::HEADER_MATCHED_PATTERN, $pattern),
[self::ENV_MATCHED_PATTERN => $pattern],
);
} catch (NativeProcessException $e) {
$this->logger?->error('Native middleware failed: ' . $e->getMessage(), [
'binary' => $this->binary,
Expand Down
35 changes: 35 additions & 0 deletions src/Router/Native/NativeRunner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Polidog\Relayer\Router\Native;

use Polidog\Relayer\Http\Request;

/**
* Runs a built native handler (`route.go` / `middleware.go`) for one
* request and hands back its response.
*
* {@see NativeDispatcher} and {@see NativeProxy} depend on this rather than
* on how the handler is reached, so the transport can change without
* touching the dispatch rules around it (the not-built / stale checks, the
* continue protocol, the JSON 500s). {@see CgiRunner} — a process per
* request — is the one implementation today.
*
* Anything the framework hands the handler that is not part of the
* request itself (`RELAYER_ROUTE_PARAMS`, `RELAYER_MATCHED_PATTERN`, …)
* arrives as `$extra`. A runner must make sure no client input can
* override those names.
*/
interface NativeRunner
{
/**
* @param string $binary the built handler, as `relayer native:build` wrote it
* @param array<string, string> $extra framework-owned variables for the handler
*
* @throws NativeProcessException when the handler could not produce a response
* (did not start, failed, timed out, answered
* something that is not a response)
*/
public function run(string $binary, Request $request, array $extra = []): NativeRun;
}
84 changes: 84 additions & 0 deletions tests/Router/Native/NativeProxyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Polidog\Relayer\Http\Request;
use Polidog\Relayer\Router\Native\CgiResponse;
use Polidog\Relayer\Router\Native\CgiRunner;
use Polidog\Relayer\Router\Native\NativeProxy;
use Polidog\Relayer\Router\Native\NativeRun;
use Polidog\Relayer\Router\Native\NativeRunner;
use Polidog\Relayer\Tests\Fixtures\SpyLogger;

/**
Expand Down Expand Up @@ -153,6 +156,87 @@ public function testNoMatchPassesAnEmptyPattern(): void
self::assertSame('[]', $this->invoke($proxy, new Request('GET', '/nope'), static function (): void {}));
}

public function testMatchedPatternIsPassedAsARequestHeader(): void
{
$proxy = $this->proxy("printf 'Content-Type: text/plain\\r\\n\\r\\n%s' \"[\$HTTP_RELAYER_MATCHED_PATTERN]\"", '/api/users/[id]');

$out = $this->invoke($proxy, new Request('GET', '/api/users/1'), static function (): void {});

self::assertSame('[/api/users/[id]]', $out);
}

public function testNoMatchPassesAnEmptyPatternHeader(): void
{
// proc_open() drops empty environment values, so under CGI the
// header is absent rather than empty; Go's r.Header.Get() reads
// both as "".
$proxy = $this->proxy("printf 'Content-Type: text/plain\\r\\n\\r\\n%s' \"[\$HTTP_RELAYER_MATCHED_PATTERN]\"", null);

self::assertSame('[]', $this->invoke($proxy, new Request('GET', '/nope'), static function (): void {}));
}

public function testClientSentMatchedPatternHeaderIsReplaced(): void
{
$proxy = $this->proxy("printf 'Content-Type: text/plain\\r\\n\\r\\n%s' \"[\$HTTP_RELAYER_MATCHED_PATTERN]\"", null);

$request = new Request('GET', '/nope', headers: ['relayer-matched-pattern' => '/admin']);

self::assertSame('[]', $this->invoke($proxy, $request, static function (): void {}));
}

public function testMatchedPatternHeaderDoesNotReachTheRoute(): void
{
$proxy = $this->proxy("printf 'Relayer-Next: 1\\r\\n\\r\\n'", '/about');

$seen = null;
$this->invoke($proxy, new Request('GET', '/about'), static function (Request $request) use (&$seen): void {
$seen = $request;
});

self::assertInstanceOf(Request::class, $seen);
self::assertNull($seen->header(NativeProxy::HEADER_MATCHED_PATTERN));
}

public function testRunsThroughTheGivenRunner(): void
{
$runner = new class implements NativeRunner {
public ?string $binary = null;

public ?Request $request = null;

/** @var array<string, string> */
public array $extra = [];

public function run(string $binary, Request $request, array $extra = []): NativeRun
{
$this->binary = $binary;
$this->request = $request;
$this->extra = $extra;

return new NativeRun(new CgiResponse(200, [['Relayer-Next', '1']], ''), '');
}
};

$binary = $this->script('exit 1');
$proxy = new NativeProxy(
$binary,
$this->workDir . '/middleware.go',
$runner,
static fn (): string => '/api/users/[id]',
false,
$this->logger,
);

$out = $this->invoke($proxy, new Request('GET', '/api/users/1'), static function (): void {
echo 'continued';
});

self::assertSame('continued', $out);
self::assertSame($binary, $runner->binary);
self::assertSame('/api/users/[id]', $runner->request?->header(NativeProxy::HEADER_MATCHED_PATTERN));
self::assertSame([NativeProxy::ENV_MATCHED_PATTERN => '/api/users/[id]'], $runner->extra);
}

public function testRouteVariablesAreNotPassedToTheProxy(): void
{
$proxy = $this->proxy("printf 'Content-Type: text/plain\\r\\n\\r\\n%s' \"[\${RELAYER_ROUTE_PARAMS-unset}][\${RELAYER_ROUTE_PATTERN-unset}]\"");
Expand Down
2 changes: 2 additions & 0 deletions tests/Router/NativeMiddlewareDispatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ final class NativeMiddlewareDispatchTest extends TestCase
w.Header().Set("Relayer-Request-Header-X-User", "42")
w.Header().Set("X-Proxied-By", "go")
w.Header().Set("X-Matched", os.Getenv("RELAYER_MATCHED_PATTERN"))
w.Header().Set("X-Matched-Header", r.Header.Get("Relayer-Matched-Pattern"))
}
GO;

Expand Down Expand Up @@ -114,6 +115,7 @@ public function testRelayerNextContinuesToTheRouteWithTheInjectedHeader(): void
$headers = self::sentHeaders();
self::assertContains('X-Proxied-By: go', $headers);
self::assertContains('X-Matched: /api/whoami', $headers);
self::assertContains('X-Matched-Header: /api/whoami', $headers);
foreach ($headers as $header) {
self::assertStringNotContainsStringIgnoringCase('relayer-', $header);
}
Expand Down
Loading