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
2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"start": "next start",
"lint": "eslint",
"test": "vitest run",
"coverage": "vitest run src/components/project-trace-readiness.test.ts --coverage --coverage.provider=v8 --coverage.reporter=json-summary --coverage.reporter=json --coverage.include=src/components/project-trace-readiness.ts",
"coverage": "vitest run --coverage --coverage.provider=v8 --coverage.reporter=json-summary --coverage.reporter=json --coverage.include='src/**/*.ts' --coverage.include='src/**/*.tsx' --coverage.exclude='src/**/*.test.ts' --coverage.exclude='src/**/*.test.tsx' --coverage.exclude='src/test/**'",
"typecheck": "tsc --noEmit",
"full:smoke": "node scripts/full-product-ui-smoke.mjs",
"pilot:smoke": "node scripts/pilot-ui-smoke.mjs",
Expand Down
61 changes: 59 additions & 2 deletions frontend/src/app/api/[...path]/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { createFetchBackedNodeRequest } from "@/test/fetch-backed-node-request";

const { backendDnsLookupMock, httpsRequestMock } = vi.hoisted(() => ({
backendDnsLookupMock: vi.fn(),
httpsRequestMock: vi.fn(),
}));

vi.mock("node:dns/promises", () => ({
lookup: backendDnsLookupMock,
}));

vi.mock("node:https", () => ({
request: httpsRequestMock,
}));

import { GET, POST, PUT } from "./route";

const ORIGINAL_ENV = { ...process.env };
Expand All @@ -11,6 +26,12 @@ describe("/api runtime proxy route", () => {
vi.unstubAllEnvs();
process.env = { ...ORIGINAL_ENV };
vi.stubEnv("BACKEND_INTERNAL_URL", "https://api.naruon.net");
backendDnsLookupMock.mockReset();
backendDnsLookupMock.mockResolvedValue([
{ address: "8.8.8.8", family: 4 },
]);
httpsRequestMock.mockReset();
httpsRequestMock.mockImplementation(createFetchBackedNodeRequest());
});

afterEach(() => {
Expand Down Expand Up @@ -61,6 +82,39 @@ describe("/api runtime proxy route", () => {
user_header: null,
request_body: '{"state":"open"}',
});
expect(httpsRequestMock).toHaveBeenCalledWith(
expect.objectContaining({
agent: false,
family: 4,
hostname: "8.8.8.8",
path: "/api/tasks?limit=1",
servername: "api.naruon.net",
}),
expect.any(Function),
);
});

it("rejects a backend hostname that resolves to the metadata network", async () => {
backendDnsLookupMock.mockResolvedValue([
{ address: "169.254.169.254", family: 4 },
]);
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(console, "error").mockImplementation(() => undefined);

const response = await GET(
new NextRequest("https://frontend.naruon.net/api/tasks"),
{
params: Promise.resolve({ path: ["tasks"] }),
},
);

expect(response.status).toBe(503);
expect(backendDnsLookupMock).toHaveBeenCalledWith("api.naruon.net", {
all: true,
verbatim: true,
});
expect(fetchMock).not.toHaveBeenCalled();
});

it("rejects unsupported query parameters before proxying", async () => {
Expand Down Expand Up @@ -335,7 +389,10 @@ describe("/api runtime proxy route", () => {
});

it("preserves a validated global IPv6 backend authority", async () => {
vi.stubEnv("BACKEND_INTERNAL_URL", "https://[2001:db8::1]:8443");
vi.stubEnv(
"BACKEND_INTERNAL_URL",
"https://[2001:4860:4860::8888]:8443",
);
const fetchMock = vi.fn(async (input: URL | RequestInfo) =>
Response.json({ target_url: String(input) }),
);
Expand All @@ -347,7 +404,7 @@ describe("/api runtime proxy route", () => {
);

await expect(response.json()).resolves.toEqual({
target_url: "https://[2001:db8::1]:8443/api/tasks",
target_url: "https://[2001:4860:4860::8888]:8443/api/tasks",
});
});
});
6 changes: 2 additions & 4 deletions frontend/src/app/api/[...path]/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";

import { fetchTrustedBackend } from "@/lib/backend-request";
import { trustedBackendOrigin } from "@/lib/backend-url";
import { SESSION_COOKIE_NAME, normalizeSessionToken } from "@/lib/session-cookie";

Expand Down Expand Up @@ -278,10 +279,7 @@ async function proxyApiRequest(

let response: Response;
try {
// `target` is rebuilt by trustedBackendOrigin() from operator-only runtime
// configuration, then constrained to the validated API path/query above.
// codeql[js/request-forgery]
response = await fetch(target, init);
response = await fetchTrustedBackend(target, init);
} catch (error) {
// If the backend isn't available (e.g. during build), return a 503 instead of throwing
console.error("proxy_fetch_failed", proxyFailureDetails(error));
Expand Down
28 changes: 25 additions & 3 deletions frontend/src/app/auth/oidc/callback/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { createFetchBackedNodeRequest } from "@/test/fetch-backed-node-request";

import { POST } from "./route";

const { postOidcTokenRequestMock } = vi.hoisted(() => ({
Expand All @@ -9,10 +11,23 @@ const { postOidcTokenRequestMock } = vi.hoisted(() => ({
>(),
}));

const { backendDnsLookupMock, httpsRequestMock } = vi.hoisted(() => ({
backendDnsLookupMock: vi.fn(),
httpsRequestMock: vi.fn(),
}));

vi.mock("@/lib/oidc-token-client", () => ({
postOidcTokenRequest: postOidcTokenRequestMock,
}));

vi.mock("node:dns/promises", () => ({
lookup: backendDnsLookupMock,
}));

vi.mock("node:https", () => ({
request: httpsRequestMock,
}));

const ORIGINAL_ENV = { ...process.env };

function oidcStateCookie(state: string, verifier: string, returnTo: string) {
Expand All @@ -33,6 +48,12 @@ describe("/auth/oidc/callback route", () => {
vi.stubEnv("NEXT_PUBLIC_OIDC_ISSUER_URL", "https://login.example.com/realms/naruon/");
vi.stubEnv("NEXT_PUBLIC_OIDC_CLIENT_ID", "naruon-web");
vi.stubEnv("NEXT_PUBLIC_OIDC_REDIRECT_URI", "https://app.example.com/auth/callback");
backendDnsLookupMock.mockReset();
backendDnsLookupMock.mockResolvedValue([
{ address: "8.8.8.8", family: 4 },
]);
httpsRequestMock.mockReset();
httpsRequestMock.mockImplementation(createFetchBackedNodeRequest());
postOidcTokenRequestMock.mockReset();
postOidcTokenRequestMock.mockResolvedValue({
access_token: "test-header.test-payload.test-signature",
Expand Down Expand Up @@ -85,9 +106,10 @@ describe("/auth/oidc/callback route", () => {
expect(setCookie).toContain("Max-Age=0");
expect(setCookie).not.toContain("verifier-123");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0]?.[1]).toEqual(expect.objectContaining({
cache: "no-store",
redirect: "manual",
expect(httpsRequestMock.mock.calls[0]?.[0]).toEqual(expect.objectContaining({
agent: false,
method: "GET",
servername: "api.naruon.net",
signal: expect.any(AbortSignal),
}));
expect(postOidcTokenRequestMock).toHaveBeenCalledTimes(1);
Expand Down
55 changes: 48 additions & 7 deletions frontend/src/app/auth/session/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { createFetchBackedNodeRequest } from "@/test/fetch-backed-node-request";

const { backendDnsLookupMock, httpRequestMock, httpsRequestMock } = vi.hoisted(() => ({
backendDnsLookupMock: vi.fn(),
httpRequestMock: vi.fn(),
httpsRequestMock: vi.fn(),
}));

vi.mock("node:dns/promises", () => ({
lookup: backendDnsLookupMock,
}));

vi.mock("node:http", async (importOriginal) => ({
...(await importOriginal<typeof import("node:http")>()),
request: httpRequestMock,
}));

vi.mock("node:https", () => ({
request: httpsRequestMock,
}));

import { DELETE, GET, POST } from "./route";

const ORIGINAL_ENV = { ...process.env };
Expand All @@ -27,6 +48,14 @@ describe("/auth/session route", () => {
vi.unstubAllGlobals();
process.env = { ...ORIGINAL_ENV };
vi.stubEnv("BACKEND_INTERNAL_URL", "https://api.naruon.net");
backendDnsLookupMock.mockReset();
backendDnsLookupMock.mockResolvedValue([
{ address: "8.8.8.8", family: 4 },
]);
httpRequestMock.mockReset();
httpRequestMock.mockImplementation(createFetchBackedNodeRequest());
httpsRequestMock.mockReset();
httpsRequestMock.mockImplementation(createFetchBackedNodeRequest());
});

afterEach(() => {
Expand Down Expand Up @@ -79,6 +108,16 @@ describe("/auth/session route", () => {
expect(setCookie).not.toContain("access_token");
expect(setCookie).not.toContain("attacker-fixed-session");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(httpsRequestMock).toHaveBeenCalledWith(
expect.objectContaining({
agent: false,
family: 4,
hostname: "8.8.8.8",
path: "/api/auth/session",
servername: "api.naruon.net",
}),
expect.any(Function),
);
});

it("stores a session when browser origin matches the forwarded host", async () => {
Expand Down Expand Up @@ -301,11 +340,11 @@ describe("/auth/session route", () => {
authenticated: true,
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const [input, init] = fetchMock.mock.calls[0];
const [input] = fetchMock.mock.calls[0];
expect(String(input)).toBe("http://127.0.0.1:8000/api/auth/session");
expect(init).toEqual(expect.objectContaining({
cache: "no-store",
redirect: "manual",
expect(httpRequestMock.mock.calls[0]?.[0]).toEqual(expect.objectContaining({
agent: false,
method: "GET",
signal: expect.any(AbortSignal),
}));
});
Expand Down Expand Up @@ -344,12 +383,14 @@ describe("/auth/session route", () => {
authenticated: true,
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const [input, init] = fetchMock.mock.calls[0];
const [input] = fetchMock.mock.calls[0];
expect(String(input)).toBe(
"https://[2001:4860:4860::8888]:8443/api/auth/session",
);
expect(init).toEqual(expect.objectContaining({
redirect: "manual",
expect(httpsRequestMock.mock.calls[0]?.[0]).toEqual(expect.objectContaining({
agent: false,
method: "GET",
servername: undefined,
signal: expect.any(AbortSignal),
}));
});
Expand Down
Loading
Loading