Skip to content
Merged
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
6 changes: 5 additions & 1 deletion .github/workflows/alt-frontend-sv-unit-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ on:
paths:
- 'alt-frontend-sv/**'
- 'nginx/conf.d/default.conf'
- 'plecto/manifest.toml'
- 'scripts/lint/frontend.sh'
- 'scripts/altharness/internal/lang/frontend.go'
- 'scripts/altharness/alt-harness'
Expand All @@ -18,6 +19,7 @@ on:
paths:
- 'alt-frontend-sv/**'
- 'nginx/conf.d/default.conf'
- 'plecto/manifest.toml'
- 'scripts/lint/frontend.sh'
- 'scripts/altharness/internal/lang/frontend.go'
- 'scripts/altharness/alt-harness'
Expand Down Expand Up @@ -50,10 +52,12 @@ jobs:
with:
persist-credentials: false
fetch-depth: 1
# nginx is included for src/lib/server/nginx-connect-streaming-config.test.ts.
# nginx and plecto are included for nginx-connect-streaming-config.test.ts
# and src/params/frontendPath.manifest.test.ts.
sparse-checkout: |
alt-frontend-sv
nginx
plecto
scripts/lint
scripts/altharness
sparse-checkout-cone-mode: true
Expand Down
168 changes: 168 additions & 0 deletions alt-frontend-sv/src/params/frontendPath.manifest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { EDGE_NON_FRONTEND_PREFIXES, isFrontendPath } from "./frontendPath";

interface PlectoRoute {
line: number;
upstream: string;
pathPrefix: string;
}

function stripTomlComment(rawLine: string): string {
let inQuotes = false;
let escaped = false;
for (let i = 0; i < rawLine.length; i++) {
const ch = rawLine[i];
if (escaped) {
escaped = false;
continue;
}
if (ch === "\\" && inQuotes) {
escaped = true;
continue;
}
if (ch === '"') {
inQuotes = !inQuotes;
continue;
}
if (ch === "#" && !inQuotes) {
return rawLine.slice(0, i);
}
}
return rawLine;
}

function parsePlectoRoutes(tomlContent: string): PlectoRoute[] {
const lines = tomlContent.split(/\r?\n/);
const routes: Array<{
line: number;
upstream?: string;
pathPrefix?: string;
}> = [];
let currentRoute: {
line: number;
upstream?: string;
pathPrefix?: string;
} | null = null;
let currentSubtable: string | null = null;

for (let idx = 0; idx < lines.length; idx++) {
const lineNum = idx + 1;
const line = stripTomlComment(lines[idx] ?? "").trim();
if (!line) continue;

if (line === "[[route]]") {
currentRoute = { line: lineNum };
routes.push(currentRoute);
currentSubtable = "route";
continue;
}

if (line.startsWith("[[")) {
currentRoute = null;
currentSubtable = null;
continue;
}

const tableMatch = /^\[([^\]]+)\]$/.exec(line);
if (tableMatch) {
const tableName = tableMatch[1]?.trim() ?? "";
if (currentRoute && tableName.startsWith("route.")) {
currentSubtable = tableName;
} else {
currentRoute = null;
currentSubtable = null;
}
continue;
}

if (!currentRoute) continue;

if (currentSubtable === "route") {
const upstreamMatch = /^upstream\s*=\s*"([^"]+)"$/.exec(line);
if (upstreamMatch?.[1]) {
currentRoute.upstream = upstreamMatch[1];
}
} else if (currentSubtable === "route.match") {
const prefixMatch = /^path_prefix\s*=\s*"([^"]+)"$/.exec(line);
if (prefixMatch?.[1]) {
currentRoute.pathPrefix = prefixMatch[1];
}
}
}

if (routes.length === 0) {
throw new Error("Expected at least one [[route]] table in manifest.toml");
}

return routes.map((route) => {
if (!route.upstream) {
throw new Error(
`[[route]] at manifest.toml:${route.line} is missing an upstream field`,
);
}
if (!route.pathPrefix) {
throw new Error(
`[[route]] at manifest.toml:${route.line} (upstream=${route.upstream}) is missing [route.match].path_prefix`,
);
}
return {
line: route.line,
upstream: route.upstream,
pathPrefix: route.pathPrefix,
};
});
}

function normalizeRoutePrefix(pathPrefix: string): string {
return pathPrefix.replace(/^\/+|\/+$/g, "");
}

const manifestPath = resolve(process.cwd(), "../plecto/manifest.toml");

describe("frontendPath matcher <-> plecto/manifest.toml drift guard", () => {
const routes = parsePlectoRoutes(readFileSync(manifestPath, "utf8"));
const nonFrontendRoutes = routes.filter(
(route) => route.upstream !== "alt-frontend-sv",
);

it("rejects every non-frontend route prefix declared in plecto/manifest.toml", () => {
expect(nonFrontendRoutes.length).toBeGreaterThan(0);

for (const route of nonFrontendRoutes) {
const normalized = normalizeRoutePrefix(route.pathPrefix);
expect(
normalized.length,
`route at plecto/manifest.toml:${route.line} (${route.upstream}) has empty normalized prefix`,
).toBeGreaterThan(0);

expect(
isFrontendPath(normalized),
`non-frontend route "${route.pathPrefix}" (upstream="${route.upstream}", plecto/manifest.toml:${route.line}) must be rejected by isFrontendPath`,
).toBe(false);

expect(
isFrontendPath(`${normalized}/nested`),
`nested path under non-frontend route "${route.pathPrefix}" (upstream="${route.upstream}", plecto/manifest.toml:${route.line}) must be rejected by isFrontendPath`,
).toBe(false);
}
});

it("ensures every EDGE_NON_FRONTEND_PREFIXES entry matches at least one non-frontend route in plecto/manifest.toml", () => {
const normalizedNonFrontend = nonFrontendRoutes.map((route) =>
normalizeRoutePrefix(route.pathPrefix),
);

for (const prefix of EDGE_NON_FRONTEND_PREFIXES) {
const covered = normalizedNonFrontend.some(
(routePrefix) =>
routePrefix === prefix || routePrefix.startsWith(`${prefix}/`),
);
expect(
covered,
`EDGE_NON_FRONTEND_PREFIXES entry "${prefix}" does not match any non-frontend route in plecto/manifest.toml`,
).toBe(true);
}
});
});
49 changes: 49 additions & 0 deletions alt-frontend-sv/src/params/frontendPath.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { isFrontendPath, matchFrontendPath } from "./frontendPath";
import { params } from "./index";

describe("frontendPath param matcher", () => {
describe("edge-routed non-frontend prefixes (excluded)", () => {
it.each([
"ory",
"ory/",
"ory/self-service/registration/browser",
"ory/self-service/login/browser",
"ory/self-service/logout",
"ory/sessions/whoami",
"api/v1/sse",
"api/v1/sse/",
"api/v1/sse/stream",
"v1/images/proxy",
"v1/images/proxy/",
"v1/images/proxy/sig/aHR0cHM6Ly9leGFtcGxlLmNvbQ",
])("rejects %s so SvelteKit falls back to native navigation", (input) => {
expect(isFrontendPath(input)).toBe(false);
expect(matchFrontendPath(input)).toBeUndefined();

const result = params.frontendPath["~standard"].validate(input);
expect(result).toHaveProperty("issues");
});
});

describe("frontend catch-all paths (matched -> 404)", () => {
it.each([
"nonexistent",
"a/b/c/d",
"orytest",
"story",
"history",
"api/v1/sse-other",
"api/v1/other",
"v1/images/proxy-other",
"v1/images",
"",
])("accepts %s so the catch-all route renders 404", (input) => {
expect(isFrontendPath(input)).toBe(true);
expect(matchFrontendPath(input)).toBe(input);

const result = params.frontendPath["~standard"].validate(input);
expect(result).toEqual({ value: input });
});
});
});
25 changes: 25 additions & 0 deletions alt-frontend-sv/src/params/frontendPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Non-frontend path prefixes routed away from alt-frontend-sv by the edge
* proxy (plecto/manifest.toml). Excluding them from the root catch-all route
* lets SvelteKit's client router fall back to native full-page navigation
* instead of fetching a non-existent __data.json endpoint from another service.
*
* - "ory": Ory Kratos self-service authentication flows (upstream = "kratos")
* - "api/v1/sse": legacy browser-direct SSE endpoint (upstream = "alt-backend")
* - "v1/images/proxy": signed OGP image proxy (upstream = "alt-backend")
*/
export const EDGE_NON_FRONTEND_PREFIXES = [
"ory",
"api/v1/sse",
"v1/images/proxy",
] as const;

export function isFrontendPath(param: string): boolean {
return !EDGE_NON_FRONTEND_PREFIXES.some(
(prefix) => param === prefix || param.startsWith(`${prefix}/`),
);
}

export function matchFrontendPath(param: string): string | undefined {
return isFrontendPath(param) ? param : undefined;
}
6 changes: 6 additions & 0 deletions alt-frontend-sv/src/params/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineParams } from "@sveltejs/kit/params";
import { matchFrontendPath } from "./frontendPath.ts";

export const params = defineParams({
frontendPath: matchFrontendPath,
});
103 changes: 102 additions & 1 deletion alt-frontend-sv/tests/e2e/auth/route-guard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ test.describe("route guard — rejected session cookie", () => {

test.describe("route guard — unknown paths", () => {
test("returns 404 for a path outside the route tree", async ({ page }) => {
// The `[...path]` catch-all throws error(404); without it an unknown path
// The `[...path=frontendPath]` catch-all throws error(404); without it an unknown path
// falls into the guard and looks like an auth problem instead.
const response = await page.request.get("/no-such-page", {
maxRedirects: 0,
Expand All @@ -136,3 +136,104 @@ test.describe("route guard — unknown paths", () => {
expect(response.status()).toBe(404);
});
});

test.describe("same-origin /ory native navigation from landing page", () => {
const MOCK_KRATOS_ORIGIN = "http://127.0.0.1:4001";

async function setupSameOriginOryProxy(
page: import("@playwright/test").Page,
origin: string,
) {
const oryRequests: Array<{
pathname: string;
isNavigation: boolean;
resourceType: string;
}> = [];

// Mirror the edge proxy topology where KRATOS_PUBLIC_URL is same-origin
// (`${origin}/ory`) instead of the direct cross-origin mock port (`:4001`).
await page.route(
/\/(register|auth\/login)\/__data\.json/,
async (route) => {
const response = await route.fetch();
const body = await response.text();
const rewritten = body.replaceAll(MOCK_KRATOS_ORIGIN, `${origin}/ory`);
await route.fulfill({
response,
body: rewritten,
});
},
);

await page.route(`${origin}/ory/**`, async (route) => {
const request = route.request();
const url = new URL(request.url());
oryRequests.push({
pathname: url.pathname,
isNavigation: request.isNavigationRequest(),
resourceType: request.resourceType(),
});

// Kratos answers 404 to SvelteKit __data.json probes.
if (url.pathname.endsWith("/__data.json")) {
await route.fulfill({ status: 404, body: "Not Found" });
return;
}

const kratosPath = url.pathname.replace(/^\/ory/, "") || "/";
const upstreamResponse = await route.fetch({
url: `${MOCK_KRATOS_ORIGIN}${kratosPath}${url.search}`,
maxRedirects: 0,
});
await route.fulfill({ response: upstreamResponse });
});

return oryRequests;
}

test("clicking Register performs a full document navigation to /ory/self-service/registration/browser", async ({
page,
baseURL,
}) => {
const origin = new URL(
baseURL ?? `http://127.0.0.1:${process.env.ALT_E2E_PORT || "4174"}`,
).origin;
const oryRequests = await setupSameOriginOryProxy(page, origin);

await page.goto("./");
await page.getByRole("link", { name: "Register" }).click();

await expect(page).toHaveURL(/\/register\?flow=/);
expect(
oryRequests.filter((r) => r.pathname.endsWith("/__data.json")),
).toEqual([]);
expect(oryRequests).toContainEqual({
pathname: "/ory/self-service/registration/browser",
isNavigation: true,
resourceType: "document",
});
});

test("clicking Login performs a full document navigation to /ory/self-service/login/browser", async ({
page,
baseURL,
}) => {
const origin = new URL(
baseURL ?? `http://127.0.0.1:${process.env.ALT_E2E_PORT || "4174"}`,
).origin;
const oryRequests = await setupSameOriginOryProxy(page, origin);

await page.goto("./");
await page.getByRole("link", { name: "Login" }).click();

await expect(page).toHaveURL(/\/auth\/login\?flow=/);
expect(
oryRequests.filter((r) => r.pathname.endsWith("/__data.json")),
).toEqual([]);
expect(oryRequests).toContainEqual({
pathname: "/ory/self-service/login/browser",
isNavigation: true,
resourceType: "document",
});
});
});
Loading
Loading