diff --git a/hub/.env.example b/hub/.env.example index be4128b9a..3bcb19e87 100644 --- a/hub/.env.example +++ b/hub/.env.example @@ -133,5 +133,5 @@ TEST_DATABASE_URL=postgresql://replica:replica@127.0.0.1:5432/postgres # LOCAL_REPLICA_BUILD_ACTION_ROOT=/absolute/path/to/replica/actions/build # LOCAL_BUILD_TEMPORARY_ROOT=/absolute/path/to/temporary/builds -# Trust forwarded client addresses only behind this exact protected proxy-chain length. +# Set the exact protected proxy-chain length (1-10) for HTTPS sign-in. Use 0 for direct HTTP loopback access. # HUB_TRUSTED_PROXY_HOPS=0 diff --git a/hub/docs/authentication.md b/hub/docs/authentication.md index 3c55189a3..c01fb286b 100644 --- a/hub/docs/authentication.md +++ b/hub/docs/authentication.md @@ -6,6 +6,8 @@ Hub exposes same-request GitHub and Microsoft Entra sign-in flows. An installati The start primitive selects the configured provider revision, snapshots the global session revocation revision, creates opaque state, browser binding, PKCE verifier, and nonce, and persists one short-lived authorization attempt. PostgreSQL owns attempt creation, expiry, locking, and one-use consumption time. The stored attempt contains digests plus encrypted verifier and nonce state, not raw state, browser binding, or provider tokens. +On HTTPS, Hub uses the host-only `__Host-hub_auth_browser` cookie for the browser binding. Restart a sign-in or sensitive authorization that was already in progress when upgrading from a release that used `hub_auth_browser` on HTTPS. HTTP loopback development still uses `hub_auth_browser`. + GitHub and Entra adapters are defined in code, not discovered from database records. Startup validates every complete adapter before one serializable transaction creates, selects, enables, or disables provider revisions. Operators do not seed provider rows. Failed validation or reconciliation leaves every current provider selection unchanged. An incomplete GitHub App configuration disables GitHub until repaired; a complete but invalid configuration fails startup. Removing or disabling a previously selected provider disables its authority and advances the global session revocation revision. Re-enabling it requires the next consecutive provider revision, even when its validated configuration is otherwise unchanged, so previous-version replicas also reject pre-removal attempts. Increment `GITHUB_PROVIDER_REVISION` for every GitHub App configuration or credential change, and before re-enabling a disabled provider. The digest covers public settings, not secret values. Keep the revision unchanged for an ordinary restart with the same validated enabled provider settings. @@ -97,7 +99,13 @@ The callback must receive the original Hub session cookie and prove the same ext ## Browser session -Hub creates a fresh opaque session value only after admission succeeds. The browser receives the value in an `HttpOnly`, `SameSite=Lax` cookie with a bounded lifetime; HTTPS origins also set `Secure`. The database stores only its SHA-256 digest. +Hub creates a fresh opaque session value only after admission succeeds. The browser receives it in an `HttpOnly`, `SameSite=Lax` cookie with a bounded lifetime. On HTTPS, the sign-in callback must arrive at the configured Hub host over HTTPS. It sets `__Host-hub_session` with `Secure`, `Path=/`, and no `Domain`, so the browser confines the cookie to that host. HTTP loopback development still uses `hub_session`. The database stores only the session value's SHA-256 digest. + +If ingress terminates TLS, preserve the public Hub `Host` and configure the [trusted proxy chain](deployment.md#image-and-runtime) so Hub recognizes the original HTTPS connection. Hub refuses to start with HTTPS sign-in enabled and no trusted proxy hops. Verify a fresh provider sign-in after updating Hub; `/api/ready` does not exercise the callback. + +Existing `hub_session` cookies still work for ordinary Hub use until the session expires or ends. On HTTPS, Hub never falls back to the legacy cookie when the protected cookie is present, even if the protected session is invalid. On HTTP, Hub reads only `hub_session`. A fresh HTTPS sign-in sets the protected cookie and removes the old one rather than exchanging it. HTTPS sign-out ends the distinct sessions presented under both names before clearing the cookies. + +Do not serve requests from old and new Hub versions at the same time. An older Hub that only reads `hub_session` does not recognize or clear the protected cookie. After rollback, users who received the protected cookie must sign in again. Before restoring a release that reads it, allow protected sessions issued before the rollback to expire (at most 12 hours from the last issuance), or use an approved global sign-out. Otherwise a browser can return with a still-valid protected session that the older release could not end. The cookie change does not require a database rollback. Every current-session restore rereads the global revocation revision, session expiry and termination state, membership lifecycle, and active assignments, then returns the current effective member or administrator role. Provider-owned authority is active only while its provider remains enabled and its revision remains selected. A retained cookie stops authorizing access after sign-out, expiry, suspension, removal, assignment revocation, provider removal, or a global revision change. Provider revision replacement removes authority from the old revision and stops the cookie only when no other active authority remains. @@ -159,7 +167,7 @@ Start and sign-out requests require the exact configured application origin. Aut Home sign-in forms submit native, form-encoded requests without a legacy `authenticity_token` field. The start routes accept only the optional `switch_account=true` choice and reject unknown fields. Exact-origin checks protect these submissions against cross-site requests; OAuth state and the browser-binding cookie protect the callback. -The address digest uses the trusted client address. Behind a protected proxy, configure `HUB_TRUSTED_PROXY_HOPS` to the exact proxy-chain length; leaving it at zero intentionally treats the proxy as the client and shares one rate-limit budget across traffic from that proxy. +The address digest uses the trusted client address. For HTTPS sign-in, set `HUB_TRUSTED_PROXY_HOPS` to the exact protected proxy-chain length (1–10). Leave it at zero for direct HTTP loopback access. Consumed attempts remain available as short-lived protocol state for ten minutes after consumption so a trusted same-request consumer can reread them. Cleanup removes expired unconsumed attempts and consumed attempts after that fixed retention window; this is not authentication history. diff --git a/hub/docs/build-previews.md b/hub/docs/build-previews.md index bcde6cb45..8be8d555f 100644 --- a/hub/docs/build-previews.md +++ b/hub/docs/build-previews.md @@ -6,6 +6,8 @@ The preview layer consumes the shared `BuildArtifact` contract: each immutable p The optional private reader opens a successful GitHub prototype Build in a separate tab. The Hub launch link opens that exact Build without changing permissions. Use the private Hub review link below to share from the prototype page. Each recipient must sign in to Hub and already have access. A fresh reader root URL can point back to Hub, but a reader URL does not grant access and direct asset requests without a preview session return 404. +Launch and confirmation require the [protected HTTPS Hub session cookie](authentication.md#browser-session). If you signed in before Hub started issuing it, sign out and back in, then reopen the preview link. Existing sessions still work for ordinary Hub use. + The canonical reader path is `/previews/github///`. The run ID is the workflow run that owns the retained dist, not a later screenshot or retry run. Hub does not offer a private preview link if the run identifies more than one Build in the repository. Launch checks the identity again. Compiled output must already use the full mount path for its router and assets. Set the build or publish action's `base-path` input to the same value to record it in `dist/replica-preview-base.json`; use the same path for a separate screenshot job. The action does not recompile or rewrite the bundle. Local Builds, templates, and Builds missing the matching marker are not eligible for standalone launch. The reader serves only `dist/`, with an entry-point fallback for extensionless document routes. Existing Build links, reviews, screenshots, and public link revocation are unchanged. Existing isolated preview hosts resolve a declared mount within the already authorized Build; root-based Builds still use their original paths. ### Runtime settings diff --git a/hub/docs/deployment.md b/hub/docs/deployment.md index c2617cad6..6111d8e09 100644 --- a/hub/docs/deployment.md +++ b/hub/docs/deployment.md @@ -36,7 +36,7 @@ Publishing is an explicit operator step, not a side effect of CI. From the appro | `ENTRA_OIDC_MANAGED_IDENTITY_CLIENT_ID` | User-assigned managed identity client ID when the selected mode is `managed-identity`. | | `HUB_AUTHENTICATION_ENCRYPTION_KEY` | Base64-encoded 32-byte key used only for short-lived authorization-attempt verifier state. | | `HUB_BOOTSTRAP_SECRET` | Reusable high-entropy secret, at least 32 characters, for administrator enrollment. | -| `HUB_TRUSTED_PROXY_HOPS` | Exact protected proxy-chain length, default 0. Configure this for the deployment ingress before enabling authentication. | +| `HUB_TRUSTED_PROXY_HOPS` | Exact protected proxy-chain length (1–10) for HTTPS sign-in. Defaults to 0 for direct HTTP loopback access. | Incomplete GitHub settings disable its provider and log setting names, not values; a complete but invalid GitHub configuration stops startup before changing provider authority. An administrator can open `/settings/github/setup` to see the callback, setup, and webhook URLs, which GitHub values are configured, and to test the App connection and sync repositories. GitHub delivers App webhooks to `/api/github/webhooks`; see [GitHub repository access](authentication.md#github-repository-access), including GitHub-only recovery. See [GitHub App](../../infrastructure/README.md#github-app) for Key Vault storage and rotation. Logging and optional tracing retain their existing [logging](logging.md) and [telemetry](telemetry.md) contracts. diff --git a/hub/server/create-app/index.test.ts b/hub/server/create-app/index.test.ts index b63a1cbbd..d6dfaa57e 100644 --- a/hub/server/create-app/index.test.ts +++ b/hub/server/create-app/index.test.ts @@ -1,4 +1,4 @@ -import { randomBytes, randomUUID } from "node:crypto" +import { createHash, randomBytes, randomUUID } from "node:crypto" import { once } from "node:events" import { mkdir, rm, writeFile } from "node:fs/promises" import { createServer } from "node:http" @@ -195,10 +195,12 @@ describe("createApp()", () => { defaultBranch: "main", localPath: null, } - const restore = vi.fn().mockResolvedValue(viewer) + const restore = vi + .fn() + .mockResolvedValue(viewer) const authentication: AuthenticationRouteDependencies = { currentSession: { restore }, - signOut: { applicationOrigin: "https://hub.example.com", secureCookie: false, end: vi.fn() }, + signOut: { applicationOrigin: "http://127.0.0.1:5173", secureCookie: false, end: vi.fn() }, } const getRepositoryPermission = vi.fn().mockResolvedValue("admin") const hasUnread = vi.fn(lookup) @@ -230,12 +232,20 @@ describe("createApp()", () => { ) const { port } = server.address() as AddressInfo const base = `http://127.0.0.1:${port}/api/workspace` - const headers = { cookie: "hub_session=github-session" } + const protectedCookie = "__Host-hub_session=hosted-session" + const headers = { cookie: `${protectedCookie}; hub_session=github-session` } expect((await fetch(`${base}?view=navigation`)).status).toBe(401) + expect( + (await fetch(`${base}?view=navigation`, { headers: { cookie: protectedCookie } })).status, + ).toBe(401) + expect(restore).not.toHaveBeenCalled() const navigation = await fetch(`${base}?view=navigation`, { headers }) expect(navigation.status).toBe(200) expect(restore).toHaveBeenCalled() + expect(new Set(restore.mock.calls.map(([digest]) => digest))).toEqual( + new Set([createHash("sha256").update("github-session").digest("hex")]), + ) expect(getRepositoryPermission).not.toHaveBeenCalled() const workspace: unknown = await navigation.json() expect(workspace).toMatchObject({ @@ -396,11 +406,13 @@ describe("createApp()", () => { startPage: "/", }) const readAvailableLink = vi.fn() + const hasUnread = vi.fn().mockResolvedValue(true) const authentication: AuthenticationRouteDependencies = { currentSession: { restore }, - signOut: { applicationOrigin: "https://hub.example.com", secureCookie: false, end: vi.fn() }, + signOut: { applicationOrigin: "https://hub.example.com", secureCookie: true, end: vi.fn() }, } const product: ProductRouteDependencies = { + reviewInbox: { hasUnread, list: vi.fn(), find: vi.fn(), setRead: vi.fn() }, reviewComments: { listPrototypeThreads, createThread: vi.fn(), @@ -508,7 +520,7 @@ describe("createApp()", () => { ], }) - restore.mockResolvedValue({ + const hostedViewer = { membershipId: randomUUID(), userId: randomUUID(), provider: "github", @@ -516,11 +528,16 @@ describe("createApp()", () => { login: "octocat", name: "The Octocat", role: "MEMBER", + } + restore.mockResolvedValue(hostedViewer) + const hostedSession = randomBytes(32).toString("base64url") + const hostedWorkspace = await fetch(`${base}/api/workspace?view=navigation`, { + headers: { cookie: `__Host-hub_session=${hostedSession}` }, }) - const hostedWorkspace = await fetch(`${base}/api/workspace`, { - headers: { cookie: "hub_session=github-session" }, - }) + expect(hostedWorkspace.status).toBe(200) expect(await hostedWorkspace.json()).toMatchObject({ + viewer: { id: hostedViewer.userId }, + inboxHasUnread: true, repositories: [ { id: repositoryId, @@ -532,6 +549,12 @@ describe("createApp()", () => { }, ], }) + expect(hasUnread).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + sessionDigest: createHash("sha256").update(hostedSession).digest("hex"), + }), + expect.arrayContaining([expect.objectContaining({ id: remoteRepositoryId })]), + ) } finally { await new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())) diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 9d3f48b7e..a61d9cd84 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -3,6 +3,7 @@ import { resolve } from "node:path" import { authenticationSecurity } from "../integrations/express/authentication-security/index.ts" import { handleError } from "../integrations/express/handle-error/index.ts" +import { secureHubSessionCookieSetting } from "../integrations/express/hub-session-cookie-name/index.ts" import { respondNotFound } from "../integrations/express/respond-not-found/index.ts" import { createRequestLogger } from "../integrations/pino/create-request-logger/index.ts" import { routes } from "../routes/index.ts" @@ -31,6 +32,7 @@ export function createApp({ const app = express() app.disable("x-powered-by") app.set("trust proxy", trustedProxyHops) + app.set(secureHubSessionCookieSetting, authentication?.signOut.secureCookie === true) app.use(createRequestLogger(logger)) app.use( [ diff --git a/hub/server/domains/admission/provider-evidence-ordering.db.test.ts b/hub/server/domains/admission/provider-evidence-ordering.db.test.ts index 6ed9caa62..8afbaa68f 100644 --- a/hub/server/domains/admission/provider-evidence-ordering.db.test.ts +++ b/hub/server/domains/admission/provider-evidence-ordering.db.test.ts @@ -1,6 +1,6 @@ import { randomBytes } from "node:crypto" import { once } from "node:events" -import { createServer } from "node:http" +import { createServer, request as httpRequest, type IncomingMessage } from "node:http" import type { AddressInfo } from "node:net" import { exportJWK, generateKeyPair, SignJWT } from "jose" import { describe, expect, it, vi } from "vitest" @@ -22,10 +22,27 @@ interface TokenEvidence { role: "ADMINISTRATOR" | "MEMBER" | null } -function cookieValue(response: Response, name: string) { - const header = response.headers.get("set-cookie") ?? "" - const match = header.match(new RegExp(`(?:^|,\\s*)${name}=([^;,]*)`)) - return match ? decodeURIComponent(match[1]!) : null +function requestThroughProxy(url: URL, method: "GET" | "POST", headers: Record) { + return new Promise((resolve, reject) => { + const request = httpRequest( + url, + { + method, + headers: { + host: new URL(applicationOrigin).host, + "x-forwarded-proto": "https", + ...headers, + }, + }, + (response) => { + response.on("error", reject) + response.on("end", () => resolve(response)) + response.resume() + }, + ) + request.on("error", reject) + request.end() + }) } function environment() { @@ -107,7 +124,7 @@ async function openServer(tokens: Map) { throw new Error(`Unexpected provider request: ${url}`) }) const dependencies = await createAuthenticationRouteDependencies(environment(), request) - const server = createServer(createApp({ authentication: dependencies })) + const server = createServer(createApp({ authentication: dependencies, trustedProxyHops: 1 })) server.listen(0, "127.0.0.1") await once(server, "listening") const { port } = server.address() as AddressInfo @@ -127,17 +144,17 @@ async function openServer(tokens: Map) { } async function startAuthentication(baseUrl: string) { - const response = await fetch(`${baseUrl}/api/auth/entra/start`, { - headers: { origin: applicationOrigin }, - method: "POST", - redirect: "manual", + const response = await requestThroughProxy(new URL("/api/auth/entra/start", baseUrl), "POST", { + origin: applicationOrigin, }) - const location = response.headers.get("location") - const browserBinding = cookieValue(response, "hub_auth_browser") + const location = response.headers.location + const browserCookie = response.headers["set-cookie"] + ?.find((cookie) => cookie.startsWith("__Host-hub_auth_browser=")) + ?.split(";")[0] const state = location ? new URL(location).searchParams.get("state") : null const nonce = location ? new URL(location).searchParams.get("nonce") : null - if (!browserBinding || !nonce || !state) throw new Error("Authentication start was incomplete.") - return { browserBinding, nonce, state } + if (!browserCookie || !nonce || !state) throw new Error("Authentication start was incomplete.") + return { browserCookie, nonce, state } } function completeAuthentication( @@ -145,16 +162,9 @@ function completeAuthentication( attempt: Awaited>, code: string, ) { - return fetch( - `${baseUrl}/api/auth/entra/callback?code=${encodeURIComponent(code)}&state=${encodeURIComponent(attempt.state)}`, - { - headers: { - cookie: `hub_auth_browser=${encodeURIComponent(attempt.browserBinding)}`, - host: "hub.example.test", - }, - redirect: "manual", - }, - ) + const url = new URL("/api/auth/entra/callback", baseUrl) + url.search = new URLSearchParams({ code, state: attempt.state }).toString() + return requestThroughProxy(url, "GET", { cookie: attempt.browserCookie }) } async function activeProviderRole() { @@ -238,7 +248,7 @@ describe("provider evidence ordering", () => { const initialAttempt = await startAuthentication(server.baseUrl) tokens.get("initial")!.nonce = initialAttempt.nonce const initial = await completeAuthentication(server.baseUrl, initialAttempt, "initial") - expect(initial.headers.get("location")).toBe("/?authentication=success") + expect(initial.headers.location).toBe("/?authentication=success") const staleAttempt = await startAuthentication(server.baseUrl) const currentAttempt = await startAuthentication(server.baseUrl) @@ -249,13 +259,13 @@ describe("provider evidence ordering", () => { await barrier.started const current = await completeAuthentication(server.baseUrl, currentAttempt, "current") - expect(current.headers.get("location")).toBe( + expect(current.headers.location).toBe( scenario.current === null ? "/?authentication=denied" : "/?authentication=success", ) barrier.release() const stale = await staleCompletion - expect(stale.headers.get("location")).toBe("/?authentication=denied") + expect(stale.headers.location).toBe("/?authentication=denied") await expect(activeProviderRole()).resolves.toEqual( scenario.expected === null ? null : { role: scenario.expected }, ) @@ -368,7 +378,7 @@ describe("provider evidence ordering", () => { initialAttempt, "initial", ) - expect(initialResponse.headers.get("location")).toBe("/?authentication=success") + expect(initialResponse.headers.location).toBe("/?authentication=success") const firstAttempt = await startAuthentication(server.baseUrl) const secondAttempt = await startAuthentication(server.baseUrl) @@ -379,11 +389,11 @@ describe("provider evidence ordering", () => { await barrier.started const firstResponse = await completeAuthentication(server.baseUrl, firstAttempt, "first") - expect(firstResponse.headers.get("location")).toBe(firstLocation) + expect(firstResponse.headers.location).toBe(firstLocation) barrier.release() const secondResponse = await secondCompletion - expect(secondResponse.headers.get("location")).toBe(secondLocation) + expect(secondResponse.headers.location).toBe(secondLocation) await expect(activeProviderRole()).resolves.toEqual( expectedRole === null ? null : { role: expectedRole }, ) @@ -418,7 +428,7 @@ describe("provider evidence ordering", () => { const attempt = await startAuthentication(server.baseUrl) tokens.get(code)!.nonce = attempt.nonce const response = await completeAuthentication(server.baseUrl, attempt, code) - expect(response.headers.get("location")).toBe("/?authentication=success") + expect(response.headers.location).toBe("/?authentication=success") } await expect(activeProviderRole()).resolves.toEqual({ role: "ADMINISTRATOR" }) diff --git a/hub/server/domains/github-builds/import-github-workflow-run/index.db.test.ts b/hub/server/domains/github-builds/import-github-workflow-run/index.db.test.ts index 6f3ebd83b..7d61fa689 100644 --- a/hub/server/domains/github-builds/import-github-workflow-run/index.db.test.ts +++ b/hub/server/domains/github-builds/import-github-workflow-run/index.db.test.ts @@ -6,7 +6,6 @@ import { describe, expect, it, onTestFinished, vi } from "vitest" import { createApp } from "../../../create-app" import type { AzureBlobArtifactSettings } from "../../../integrations/azure-blob/create-azure-blob-artifact-storage/types" -import { hubSessionCookieName } from "../../../integrations/express/hub-session-cookie-name" import type { GitHubWorkflowArtifact, GitHubWorkflowRun, @@ -346,7 +345,7 @@ describe("importGitHubWorkflowRun", () => { const launch = `${settings.hubOrigin}/api/private-preview/launch/${repositoryId}/${id}` const session = randomBytes(32).toString("base64url") const sessionDigest = createHash("sha256").update(session).digest("hex") - const hubCookie = `${hubSessionCookieName}=${session}` + const hubCookie = `__Host-hub_session=${session}` const viewer = { userId: randomUUID(), membershipId: randomUUID(), diff --git a/hub/server/index.test.ts b/hub/server/index.test.ts index 7c5a5ee3b..1b14e2d11 100644 --- a/hub/server/index.test.ts +++ b/hub/server/index.test.ts @@ -153,6 +153,7 @@ describe("server runtime", () => { const disableAuthenticationProviders = vi.fn().mockResolvedValue(undefined) const githubSetup = { readStatus: vi.fn() } configureSharedSettings() + vi.stubEnv("HUB_TRUSTED_PROXY_HOPS", undefined) vi.mocked(parseRuntimeConfig).mockReturnValue({ ...apiConfiguration, databaseUrl: "postgresql://hub.example.test/replica", @@ -170,7 +171,12 @@ describe("server runtime", () => { expect(disableAuthenticationProviders).toHaveBeenCalledOnce() expect(runApi).toHaveBeenCalledWith( - expect.objectContaining({ authentication: undefined, githubSetup, product: undefined }), + expect.objectContaining({ + authentication: undefined, + githubSetup, + product: undefined, + trustedProxyHops: 0, + }), ) }) @@ -283,6 +289,7 @@ describe("server runtime", () => { vi.stubEnv("HUB_AUTHENTICATION_ENCRYPTION_KEY", "") vi.stubEnv("HUB_BOOTSTRAP_SECRET", "") vi.stubEnv("HUB_LOCAL_SIGN_IN", "true") + vi.stubEnv("HUB_TRUSTED_PROXY_HOPS", undefined) vi.stubEnv("NODE_ENV", "development") vi.mocked(parseRuntimeConfig).mockReturnValue({ ...apiConfiguration, @@ -327,7 +334,13 @@ describe("server runtime", () => { { scopeGitHubMembers: false }, ) expect(runApi).toHaveBeenCalledWith( - expect.objectContaining({ authentication, copilotConnection, learnings, product }), + expect.objectContaining({ + authentication, + copilotConnection, + learnings, + product, + trustedProxyHops: 0, + }), ) }) @@ -343,6 +356,68 @@ describe("server runtime", () => { ) }) + it.each([ + { provider: "GitHub", mode: "api", hops: undefined, label: "omitted" }, + { provider: "Entra", mode: "combined", hops: "0", label: "zero" }, + ] as const)( + "rejects HTTPS authentication before creating $provider providers in $mode mode with $label proxy hops", + async ({ provider, mode, hops }) => { + const createAuthenticationRouteDependencies = vi + .fn() + .mockRejectedValue(new Error("Unexpected provider creation")) + const disableAuthenticationProviders = vi.fn() + configureSharedSettings() + if (provider === "GitHub") { + configureGitHubApp() + } else { + vi.stubEnv("ENTRA_OIDC_CLIENT_AUTHENTICATION", "client-secret") + vi.stubEnv("ENTRA_OIDC_CLIENT_ID", "00000000-0000-4000-8000-000000000001") + vi.stubEnv("ENTRA_OIDC_CLIENT_SECRET", "synthetic-client-secret") + vi.stubEnv( + "ENTRA_OIDC_ISSUER", + "https://login.microsoftonline.com/00000000-0000-4000-8000-000000000002/v2.0", + ) + vi.stubEnv("ENTRA_OIDC_PROVIDER_REVISION", "1") + } + vi.stubEnv("HUB_TRUSTED_PROXY_HOPS", hops) + vi.mocked(parseRuntimeConfig).mockReturnValue({ + ...apiConfiguration, + mode, + databaseUrl: "postgresql://hub.example.test/replica", + }) + vi.doMock("./routes/api/auth/create-authentication-route-dependencies/index.ts", () => ({ + createAuthenticationRouteDependencies, + disableAuthenticationProviders, + })) + + await expect(import("./index.ts")).rejects.toThrow("Unexpected process exit: 1") + + expect(createAuthenticationRouteDependencies).not.toHaveBeenCalled() + expect(disableAuthenticationProviders).not.toHaveBeenCalled() + expect(logger.fatal).toHaveBeenCalledWith(expect.stringContaining("HUB_TRUSTED_PROXY_HOPS")) + expect(runApi).not.toHaveBeenCalled() + expect(startServerProcesses).not.toHaveBeenCalled() + }, + ) + + it("starts the scheduled worker without HTTPS authentication proxy hops", async () => { + configureSharedSettings() + configureGitHubApp() + vi.stubEnv("HUB_TRUSTED_PROXY_HOPS", "0") + vi.mocked(parseRuntimeConfig).mockReturnValue({ + ...apiConfiguration, + mode: "scheduled", + databaseUrl: "postgresql://hub.example.test/replica", + }) + + await expect(import("./index.ts")).resolves.toBeDefined() + + expect(runJobWorker).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ name: "scheduled" }), + ) + expect(runApi).not.toHaveBeenCalled() + }) + it.each(["api", "combined"] as const)( "disables durable providers without registering authentication routes in a database-backed %s runtime", async (mode) => { @@ -418,6 +493,7 @@ describe("server runtime", () => { } configureSharedSettings() configureGitHubApp() + vi.stubEnv("HUB_TRUSTED_PROXY_HOPS", "1") const copilotConnection = { applicationOrigin: "https://hub.example.test", } @@ -482,6 +558,7 @@ describe("server runtime", () => { githubSetup, learnings, product, + trustedProxyHops: 1, }), ) }) diff --git a/hub/server/index.ts b/hub/server/index.ts index 679b22cc1..fe02d3116 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -143,14 +143,24 @@ try { ) } if (authenticationConfiguration.applicationOrigin) { + let sharedContext: ReturnType try { - createSharedAuthenticationContext(authenticationEnvironment) + sharedContext = createSharedAuthenticationContext(authenticationEnvironment) } catch (error) { throw new AuthenticationConfigurationError( "HUB_APPLICATION_ORIGIN, HUB_AUTHENTICATION_ENCRYPTION_KEY, and HUB_BOOTSTRAP_SECRET must be valid before setup. See the authentication guide.", { cause: error }, ) } + if ( + authenticationConfiguration.providerConfigured && + sharedContext.secureCookie && + trustedProxyHops === 0 + ) { + throw new AuthenticationConfigurationError( + "HTTPS authentication requires HUB_TRUSTED_PROXY_HOPS between 1 and 10.", + ) + } } if (configuration.databaseUrl) { const databaseUrl = configuration.databaseUrl diff --git a/hub/server/integrations/express/browser-authentication-cookie-name/index.ts b/hub/server/integrations/express/browser-authentication-cookie-name/index.ts index 202d7c0a2..eabee4f57 100644 --- a/hub/server/integrations/express/browser-authentication-cookie-name/index.ts +++ b/hub/server/integrations/express/browser-authentication-cookie-name/index.ts @@ -1 +1,3 @@ -export const browserAuthenticationCookieName = "hub_auth_browser" +export function browserAuthenticationCookieName(secure: boolean): string { + return secure ? "__Host-hub_auth_browser" : "hub_auth_browser" +} diff --git a/hub/server/integrations/express/clear-hub-session-cookies/index.ts b/hub/server/integrations/express/clear-hub-session-cookies/index.ts new file mode 100644 index 000000000..a3a5f5af4 --- /dev/null +++ b/hub/server/integrations/express/clear-hub-session-cookies/index.ts @@ -0,0 +1,12 @@ +import { clearAuthenticationCookie } from "../clear-authentication-cookie/index.ts" +import { + hubSessionCookieName, + secureHubSessionCookieName, +} from "../hub-session-cookie-name/index.ts" + +export function clearHubSessionCookies(secure: boolean): string[] { + return [ + clearAuthenticationCookie(hubSessionCookieName, secure), + ...(secure ? [clearAuthenticationCookie(secureHubSessionCookieName, true)] : []), + ] +} diff --git a/hub/server/integrations/express/hub-session-cookie-name/index.ts b/hub/server/integrations/express/hub-session-cookie-name/index.ts index 75580ca9c..43f3c0a07 100644 --- a/hub/server/integrations/express/hub-session-cookie-name/index.ts +++ b/hub/server/integrations/express/hub-session-cookie-name/index.ts @@ -1 +1,3 @@ export const hubSessionCookieName = "hub_session" +export const secureHubSessionCookieName = "__Host-hub_session" +export const secureHubSessionCookieSetting = "secure Hub session cookie" diff --git a/hub/server/integrations/express/read-cookie/index.ts b/hub/server/integrations/express/read-cookie/index.ts index dc3915f2f..6a6fc8303 100644 --- a/hub/server/integrations/express/read-cookie/index.ts +++ b/hub/server/integrations/express/read-cookie/index.ts @@ -1,17 +1,26 @@ import type { Request } from "express" -export function readCookie(request: Pick, name: string): string | null { - const header = request.headers.cookie - if (!header) return null - for (const pair of header.split(";")) { +function findCookie(pairs: string[], name: string): string | undefined { + for (const pair of pairs) { const separator = pair.indexOf("=") if (separator < 0) continue - if (pair.slice(0, separator).trim() !== name) continue - try { - return decodeURIComponent(pair.slice(separator + 1).trim()) - } catch { - return null - } + if (pair.slice(0, separator).trim() === name) return pair.slice(separator + 1).trim() + } +} + +export function readCookie( + request: Pick, + name: string, + fallbackName?: string, +): string | null { + const header = request.headers.cookie + if (!header) return null + const pairs = header.split(";") + const value = + findCookie(pairs, name) ?? (fallbackName ? findCookie(pairs, fallbackName) : undefined) + try { + return value === undefined ? null : decodeURIComponent(value) + } catch { + return null } - return null } diff --git a/hub/server/integrations/express/read-hub-session-cookie/index.ts b/hub/server/integrations/express/read-hub-session-cookie/index.ts new file mode 100644 index 000000000..00fa05483 --- /dev/null +++ b/hub/server/integrations/express/read-hub-session-cookie/index.ts @@ -0,0 +1,17 @@ +import type { Request } from "express" + +import { + hubSessionCookieName, + secureHubSessionCookieName, + secureHubSessionCookieSetting, +} from "../hub-session-cookie-name/index.ts" +import { readCookie } from "../read-cookie/index.ts" + +export function readHubSessionCookie( + request: Pick & Partial>, + secure = request.app?.get(secureHubSessionCookieSetting) === true, +): string | null { + return secure + ? readCookie(request, secureHubSessionCookieName, hubSessionCookieName) + : readCookie(request, hubSessionCookieName) +} diff --git a/hub/server/integrations/express/redirect-authentication-start/index.ts b/hub/server/integrations/express/redirect-authentication-start/index.ts index f228902f4..88c3a99a9 100644 --- a/hub/server/integrations/express/redirect-authentication-start/index.ts +++ b/hub/server/integrations/express/redirect-authentication-start/index.ts @@ -19,7 +19,7 @@ export function redirectAuthenticationStart( response.setHeader("Set-Cookie", [ createAuthenticationCookie({ expiresAt: result.expiresAt, - name: browserAuthenticationCookieName, + name: browserAuthenticationCookieName(secureCookie), secure: secureCookie, value: result.browserBinding, }), diff --git a/hub/server/routes/api/administrators/authorizations/start/post/index.ts b/hub/server/routes/api/administrators/authorizations/start/post/index.ts index df401d1c1..035cb3f3c 100644 --- a/hub/server/routes/api/administrators/authorizations/start/post/index.ts +++ b/hub/server/routes/api/administrators/authorizations/start/post/index.ts @@ -59,7 +59,7 @@ export function post(dependencies: AdministratorRouteDependencies): RequestHandl "Set-Cookie", createAuthenticationCookie({ expiresAt: started.expiresAt, - name: browserAuthenticationCookieName, + name: browserAuthenticationCookieName(provider.secureCookie), secure: provider.secureCookie, value: started.browserBinding, }), diff --git a/hub/server/routes/api/administrators/index.test.ts b/hub/server/routes/api/administrators/index.test.ts index a0785be45..ca6e050ab 100644 --- a/hub/server/routes/api/administrators/index.test.ts +++ b/hub/server/routes/api/administrators/index.test.ts @@ -211,7 +211,11 @@ describe("administratorRoutes()", () => { }) it("binds fresh authorization to the live session, identity, operation, and targets", async () => { - const { authentication, github } = routeDependencies() + const { administrators, authentication, github } = routeDependencies() + const origin = "https://hub.example.test" + administrators.applicationOrigin = origin + Object.assign(authentication.signOut, { applicationOrigin: origin, secureCookie: true }) + Object.assign(github.dependencies, { applicationOrigin: origin, secureCookie: true }) const targetMembershipIds = [randomUUID(), randomUUID()] await withServer(authentication, async (baseUrl) => { @@ -219,7 +223,7 @@ describe("administratorRoutes()", () => { method: "POST", headers: sessionHeaders({ "content-type": "application/json", - origin: applicationOrigin, + origin, }), body: JSON.stringify({ operation: "DESIGNATE_ADMINISTRATORS", @@ -235,6 +239,9 @@ describe("administratorRoutes()", () => { authorizationUrl: "https://github.com/login/oauth/authorize", expiresAt: "2030-01-01T00:00:00.000Z", }) + expect(response.headers.getSetCookie()).toEqual([ + expect.stringMatching(/^__Host-hub_auth_browser=browser-binding-with-required-length;/), + ]) expect(github.start).toHaveBeenCalledWith({ actorMembershipId: session.membershipId, externalIdentityId: session.externalIdentityId, diff --git a/hub/server/routes/api/administrators/read-administrator-session/index.ts b/hub/server/routes/api/administrators/read-administrator-session/index.ts index 2b24ea299..8b81fde66 100644 --- a/hub/server/routes/api/administrators/read-administrator-session/index.ts +++ b/hub/server/routes/api/administrators/read-administrator-session/index.ts @@ -1,15 +1,14 @@ import type { Request } from "express" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import type { AdministratorRouteDependencies } from "../../auth/types.ts" export async function readAdministratorSession( request: Request, dependencies: Pick, ) { - const sessionValue = readCookie(request, hubSessionCookieName) + const sessionValue = readHubSessionCookie(request) return sessionValue ? dependencies.findSession(hashAuthenticationValue(sessionValue)) : Promise.resolve(null) diff --git a/hub/server/routes/api/auth/callback/get/index.ts b/hub/server/routes/api/auth/callback/get/index.ts index 7550ba3a1..7485de512 100644 --- a/hub/server/routes/api/auth/callback/get/index.ts +++ b/hub/server/routes/api/auth/callback/get/index.ts @@ -17,8 +17,12 @@ import { import { clearAuthenticationCookie } from "../../../../../integrations/express/clear-authentication-cookie/index.ts" import { createAuthenticationCookie } from "../../../../../integrations/express/create-authentication-cookie/index.ts" import { githubRepositoryDenialCookieName } from "../../../../../integrations/express/github-repository-denial-cookie-name/index.ts" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" +import { + hubSessionCookieName, + secureHubSessionCookieName, +} from "../../../../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { AuthenticationCallbackDependencies } from "../../types.ts" const querySchema = z @@ -31,12 +35,20 @@ const querySchema = z .strict() const browserBindingSchema = z.string().min(32).max(200) -export function get(dependencies: AuthenticationCallbackDependencies): RequestHandler { +export function get( + dependencies: AuthenticationCallbackDependencies, + applicationOrigin: string, +): RequestHandler { + const host = new URL(applicationOrigin).host + const browserCookie = browserAuthenticationCookieName(dependencies.secureCookie) return async (request, response, next) => { + if (dependencies.secureCookie && (!request.secure || request.get("host") !== host)) { + response.sendStatus(404) + return + } + const query = querySchema.safeParse(request.query) - const browserBinding = browserBindingSchema.safeParse( - readCookie(request, browserAuthenticationCookieName), - ) + const browserBinding = browserBindingSchema.safeParse(readCookie(request, browserCookie)) if ( !query.success || !browserBinding.success || @@ -44,7 +56,7 @@ export function get(dependencies: AuthenticationCallbackDependencies): RequestHa ) { response.setHeader( "Set-Cookie", - clearAuthenticationCookie(browserAuthenticationCookieName, dependencies.secureCookie), + clearAuthenticationCookie(browserCookie, dependencies.secureCookie), ) response.redirect(303, "/?authentication=denied") return @@ -64,7 +76,7 @@ export function get(dependencies: AuthenticationCallbackDependencies): RequestHa } githubLogin = completed.githubLogin if (completed.purpose === "ADMINISTRATOR_MANAGEMENT") { - const hubSessionValue = readCookie(request, hubSessionCookieName) + const hubSessionValue = readHubSessionCookie(request) if ( !completed.sensitiveAuthorizationId || !hubSessionValue || @@ -77,7 +89,7 @@ export function get(dependencies: AuthenticationCallbackDependencies): RequestHa } response.setHeader( "Set-Cookie", - clearAuthenticationCookie(browserAuthenticationCookieName, dependencies.secureCookie), + clearAuthenticationCookie(browserCookie, dependencies.secureCookie), ) const operation = await dependencies.verifyAdministratorAuthorization({ authorizationAttemptId: completed.proof.authorizationAttemptId, @@ -115,13 +127,16 @@ export function get(dependencies: AuthenticationCallbackDependencies): RequestHa ? readCanvasSignInReturn(request, browserBinding.data) : null response.setHeader("Set-Cookie", [ - clearAuthenticationCookie(browserAuthenticationCookieName, dependencies.secureCookie), + clearAuthenticationCookie(browserCookie, dependencies.secureCookie), ...(returnTo ? [clearAuthenticationCookie(canvasSignInReturnCookie, dependencies.secureCookie)] : []), + ...(dependencies.secureCookie + ? [clearAuthenticationCookie(hubSessionCookieName, true)] + : []), createAuthenticationCookie({ expiresAt: admitted.expiresAt, - name: hubSessionCookieName, + name: dependencies.secureCookie ? secureHubSessionCookieName : hubSessionCookieName, secure: dependencies.secureCookie, value: sessionValue, }), @@ -131,14 +146,14 @@ export function get(dependencies: AuthenticationCallbackDependencies): RequestHa if (error instanceof AdmissionUnavailableError) { response.setHeader( "Set-Cookie", - clearAuthenticationCookie(browserAuthenticationCookieName, dependencies.secureCookie), + clearAuthenticationCookie(browserCookie, dependencies.secureCookie), ) response.setHeader("Retry-After", "1") response .status(503) .type("text/plain") .send( - readCookie(request, hubSessionCookieName) + readHubSessionCookie(request) ? "Verification is temporarily unavailable. Return to Hub settings and start the administrator action again." : "Sign-in is temporarily unavailable. Return to Replica Hub and start sign-in again.", ) @@ -147,9 +162,7 @@ export function get(dependencies: AuthenticationCallbackDependencies): RequestHa if (error instanceof AdmissionDeniedError || error instanceof AuthenticationProofError) { const noAccess = error instanceof AdmissionDeniedError && error.reason === "no_repository_access" - const cookies = [ - clearAuthenticationCookie(browserAuthenticationCookieName, dependencies.secureCookie), - ] + const cookies = [clearAuthenticationCookie(browserCookie, dependencies.secureCookie)] if ( noAccess && githubLogin && diff --git a/hub/server/routes/api/auth/index.test.ts b/hub/server/routes/api/auth/index.test.ts index 2ad421eea..9d8244ce2 100644 --- a/hub/server/routes/api/auth/index.test.ts +++ b/hub/server/routes/api/auth/index.test.ts @@ -1,6 +1,6 @@ +import { createHash, randomBytes, randomUUID } from "node:crypto" import { once } from "node:events" -import { createHash, randomUUID } from "node:crypto" -import { createServer } from "node:http" +import { createServer, request as httpRequest, type IncomingMessage } from "node:http" import type { AddressInfo } from "node:net" import { describe, expect, it, vi } from "vitest" @@ -21,7 +21,10 @@ import { createGitHubUserAuthenticationAdapter } from "../../../integrations/git import { createLogger } from "../../../integrations/pino/create-logger" import type { AuthenticationRouteDependencies } from "./types" -function routeDependencies() { +const httpsApplicationOrigin = "https://hub.example.test" + +function routeDependencies(applicationOrigin = "http://127.0.0.1:5173") { + const secureCookie = new URL(applicationOrigin).protocol === "https:" const encryptionKey = Buffer.alloc(32, 1) const checkRateLimit = vi.fn().mockResolvedValue({ allowed: true, auditFailed: false }) const startSignIn = vi.fn() @@ -35,15 +38,15 @@ function routeDependencies() { const dependencies: AuthenticationRouteDependencies = { github: { signIn: { - applicationOrigin: "http://127.0.0.1:5173", + applicationOrigin, checkRateLimit, - secureCookie: false, + secureCookie, start: startSignIn, }, administratorEnrollment: { - applicationOrigin: "http://127.0.0.1:5173", + applicationOrigin, checkRateLimit, - secureCookie: false, + secureCookie, start: startEnrollment, verifyBootstrapSecret, writeBootstrapDenial: vi.fn().mockResolvedValue(undefined), @@ -53,7 +56,7 @@ function routeDependencies() { checkRateLimit, createGitHubRepositoryDenialNotice: (login) => createGitHubRepositoryDenialNotice(login, encryptionKey), - secureCookie: false, + secureCookie, complete: completeProof, verifyAdministratorAuthorization, admit: admitSession, @@ -65,8 +68,8 @@ function routeDependencies() { restore: restoreSession, }, signOut: { - applicationOrigin: "http://127.0.0.1:5173", - secureCookie: false, + applicationOrigin, + secureCookie, end: endSession, }, } @@ -102,6 +105,43 @@ async function withServer( } } +function requestThroughProxy( + url: string, + headers: Record, + method: "GET" | "POST" = "GET", +) { + return new Promise((resolve, reject) => { + const request = httpRequest( + url, + { + method, + headers: { + host: new URL(httpsApplicationOrigin).host, + "x-forwarded-proto": "https", + ...headers, + }, + }, + (response) => { + response.on("error", reject) + response.on("end", () => resolve(response)) + response.resume() + }, + ) + request.on("error", reject) + request.end() + }) +} + +function expectClearedSessionCookie(cookies: string[], name: string, secure = true) { + const matches = cookies.filter((cookie) => cookie.startsWith(`${name}=`)) + expect(matches).toHaveLength(1) + const [pair, ...attributes] = matches[0]!.split(/;\s*/) + expect(pair).toBe(`${name}=`) + expect(attributes).toEqual(expect.arrayContaining(["Max-Age=0", "Path=/"])) + expect(attributes.includes("Secure")).toBe(secure) + expect(matches[0]).not.toMatch(/;\s*Domain=/i) +} + describe("authenticationRoutes()", () => { it("reports only the explicitly configured provider routes", async () => { const { dependencies } = routeDependencies() @@ -185,7 +225,11 @@ describe("authenticationRoutes()", () => { const location = new URL(response.headers.get("location")!) expect(location.origin + location.pathname).toBe(publicConfiguration.authorizationEndpoint) expect(location.searchParams.get("prompt")).toBe(prompt) - expect(response.headers.get("set-cookie")).toContain("hub_auth_browser=") + const binding = response.headers + .getSetCookie() + .find((cookie) => cookie.startsWith("hub_auth_browser=")) + expect(binding).toBeDefined() + expect(binding).not.toContain("Secure") expect(checkRateLimit).toHaveBeenCalledOnce() }) }) @@ -366,6 +410,56 @@ describe("authenticationRoutes()", () => { }, ) + it.each([ + { provider: "github", path: "start", body: "" }, + { provider: "entra", path: "start", body: "" }, + { provider: "github", path: "admin-enrollment/start", body: "bootstrap_secret=test-secret" }, + { provider: "entra", path: "admin-enrollment/start", body: "bootstrap_secret=test-secret" }, + ])( + "issues a host-only HTTPS browser binding at $provider/$path", + async ({ provider, path, body }) => { + const { dependencies, startSignIn, startEnrollment, verifyBootstrapSecret } = + routeDependencies(httpsApplicationOrigin) + dependencies.entra = dependencies.github + const result = { + authorizationUrl: "https://provider.example.test/authorize", + browserBinding: "b".repeat(32), + expiresAt: new Date("2030-01-01T00:00:00Z"), + } + startSignIn.mockResolvedValue(result) + startEnrollment.mockResolvedValue(result) + verifyBootstrapSecret.mockReturnValue(true) + + await withServer(dependencies, async (baseUrl) => { + const response = await fetch(`${baseUrl}/api/auth/${provider}/${path}`, { + method: "POST", + headers: { + origin: httpsApplicationOrigin, + "content-type": "application/x-www-form-urlencoded", + }, + body, + redirect: "manual", + }) + + expect(response.status).toBe(303) + expect(response.headers.get("location")).toBe(result.authorizationUrl) + const cookies = response.headers.getSetCookie() + const binding = cookies.find((cookie) => cookie.startsWith("__Host-hub_auth_browser=")) + expect(binding?.split(/;\s*/)).toEqual( + expect.arrayContaining([ + `__Host-hub_auth_browser=${result.browserBinding}`, + "Secure", + "HttpOnly", + "SameSite=Lax", + "Path=/", + ]), + ) + expect(binding).not.toMatch(/;\s*Domain=/i) + expect(cookies.some((cookie) => cookie.startsWith("hub_auth_browser="))).toBe(false) + }) + }, + ) + it("uses the trusted proxy address only when the exact hop count is configured", async () => { const { dependencies, checkRateLimit } = routeDependencies() await withServer( @@ -641,6 +735,11 @@ describe("authenticationRoutes()", () => { }) expect(response.headers.get("location")).toBe("/?authentication=success") + const cookies = response.headers.getSetCookie() + const sessionCookie = cookies.find((cookie) => cookie.startsWith("hub_session=")) + expect(sessionCookie).toMatch(/^hub_session=[^;]+;/) + expect(sessionCookie).not.toMatch(/;\s*Secure(?:;|$)/i) + expect(cookies.some((cookie) => cookie.startsWith("__Host-hub_session="))).toBe(false) expect(completeProof).toHaveBeenCalledWith({ browserBinding, code: "provider-code", @@ -649,6 +748,142 @@ describe("authenticationRoutes()", () => { }) }) + it.each(["github", "entra"] as const)( + "issues a fresh host-only session on the HTTPS %s callback without Origin", + async (provider) => { + const { dependencies, completeProof, admitSession } = + routeDependencies(httpsApplicationOrigin) + dependencies.entra = dependencies.github + const browserBinding = "b".repeat(32) + completeProof.mockResolvedValue({ + purpose: "SIGN_IN", + proof: { authorizationAttemptId: "attempt-id", externalIdentityId: "identity-id" }, + }) + admitSession.mockResolvedValue({ expiresAt: new Date("2030-01-01T00:00:00Z") }) + const legacy = randomBytes(32).toString("base64url") + const previous = randomBytes(32).toString("base64url") + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy( + `${baseUrl}/api/auth/${provider}/callback?code=provider-code&state=${"s".repeat(32)}`, + { + cookie: `__Host-hub_auth_browser=${browserBinding}; hub_session=${legacy}; __Host-hub_session=${previous}`, + }, + ) + + expect(response.statusCode).toBe(303) + expect(response.headers.location).toBe("/?authentication=success") + const cookies = response.headers["set-cookie"] ?? [] + const protectedSessions = cookies.filter((cookie) => + cookie.startsWith("__Host-hub_session="), + ) + expect(protectedSessions).toHaveLength(1) + const [pair, ...attributes] = protectedSessions[0]!.split(/;\s*/) + const issued = pair?.match(/^__Host-hub_session=(.+)$/)?.[1] + expect(issued).toBeTruthy() + expect(issued).not.toBe(legacy) + expect(issued).not.toBe(previous) + expect(attributes).toEqual( + expect.arrayContaining(["Secure", "HttpOnly", "SameSite=Lax", "Path=/"]), + ) + expect(protectedSessions[0]).not.toMatch(/;\s*Domain=/i) + expectClearedSessionCookie(cookies, "hub_session") + expectClearedSessionCookie(cookies, "__Host-hub_auth_browser") + expect(completeProof).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ browserBinding }), + ) + const sessionDigest = createHash("sha256").update(issued!).digest("hex") + expect(admitSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ sessionDigest }), + ) + }, + { trustedProxyHops: 1 }, + ) + }, + ) + + it("requires a fresh HTTPS sign-in when an in-flight callback has only the legacy binding", async () => { + const { dependencies, completeProof, admitSession } = routeDependencies(httpsApplicationOrigin) + completeProof.mockResolvedValue({ + purpose: "SIGN_IN", + proof: { authorizationAttemptId: "attempt-id", externalIdentityId: "identity-id" }, + }) + admitSession.mockResolvedValue({ expiresAt: new Date("2030-01-01T00:00:00Z") }) + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy( + `${baseUrl}/api/auth/github/callback?code=provider-code&state=${"s".repeat(32)}`, + { cookie: `hub_auth_browser=${"b".repeat(32)}` }, + ) + + expect(response.statusCode).toBe(303) + expect(response.headers.location).toBe("/?authentication=denied") + const cookies = response.headers["set-cookie"] ?? [] + expectClearedSessionCookie(cookies, "__Host-hub_auth_browser") + expect(cookies.some((cookie) => cookie.startsWith("__Host-hub_session="))).toBe(false) + expect(completeProof).not.toHaveBeenCalled() + expect(admitSession).not.toHaveBeenCalled() + }, + { trustedProxyHops: 1 }, + ) + }) + + it.each([ + { + reason: "a different Host port", + host: "hub.example.test:8443", + protocol: "https", + trustedProxyHops: 1, + }, + { + reason: "insecure transport", + host: "hub.example.test", + protocol: "http", + trustedProxyHops: 1, + }, + { + reason: "an untrusted HTTPS indication", + host: "hub.example.test", + protocol: "https", + trustedProxyHops: 0, + }, + ])( + "rejects the HTTPS callback with $reason before sign-in", + async ({ host, protocol, trustedProxyHops }) => { + const { dependencies, completeProof, admitSession } = + routeDependencies(httpsApplicationOrigin) + completeProof.mockResolvedValue({ + purpose: "SIGN_IN", + proof: { authorizationAttemptId: "attempt-id", externalIdentityId: "identity-id" }, + }) + admitSession.mockResolvedValue({ expiresAt: new Date("2030-01-01T00:00:00Z") }) + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy( + `${baseUrl}/api/auth/github/callback?code=provider-code&state=${"s".repeat(32)}`, + { + host, + "x-forwarded-proto": protocol, + cookie: `__Host-hub_auth_browser=${"b".repeat(32)}`, + }, + ) + + expect(response.statusCode).toBe(404) + expect(completeProof).not.toHaveBeenCalled() + expect(admitSession).not.toHaveBeenCalled() + expect(response.headers["set-cookie"]).toBeUndefined() + }, + { trustedProxyHops }, + ) + }, + ) + it("redirects to a fresh sign-in state when admission authority is busy", async () => { const { dependencies, completeProof, admitSession } = routeDependencies() completeProof.mockResolvedValue({ @@ -683,8 +918,9 @@ describe("authenticationRoutes()", () => { it("continues fresh administrator authorization without issuing a new Hub session", async () => { const { admitSession, completeProof, dependencies, verifyAdministratorAuthorization } = - routeDependencies() + routeDependencies(httpsApplicationOrigin) const sensitiveAuthorizationId = "00000000-0000-4000-8000-000000000020" + const browserBinding = "b".repeat(32) completeProof.mockResolvedValue({ purpose: "ADMINISTRATOR_MANAGEMENT", sensitiveAuthorizationId, @@ -694,31 +930,37 @@ describe("authenticationRoutes()", () => { }, }) - await withServer(dependencies, async (baseUrl) => { - const response = await fetch( - `${baseUrl}/api/auth/github/callback?code=provider-code&state=${"s".repeat(32)}`, - { - headers: { - cookie: `hub_auth_browser=${"b".repeat(32)}; hub_session=retained-session`, + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy( + `${baseUrl}/api/auth/github/callback?code=provider-code&state=${"s".repeat(32)}`, + { + cookie: `__Host-hub_auth_browser=${browserBinding}; __Host-hub_session=retained-session`, }, - redirect: "manual", - }, - ) + ) - expect(response.status).toBe(303) - expect(response.headers.get("location")).toBe( - `/settings/administrators/confirm?authorizationId=${sensitiveAuthorizationId}`, - ) - expect(verifyAdministratorAuthorization).toHaveBeenCalledWith({ - authorizationAttemptId: "00000000-0000-4000-8000-000000000010", - externalIdentityId: "00000000-0000-4000-8000-000000000012", - providerAssignment: undefined, - sessionDigest: createHash("sha256").update("retained-session").digest("hex"), - sensitiveAuthorizationId, - }) - expect(admitSession).not.toHaveBeenCalled() - expect(response.headers.get("set-cookie")).not.toContain("hub_session=") - }) + expect(response.statusCode).toBe(303) + expect(response.headers.location).toBe( + `/settings/administrators/confirm?authorizationId=${sensitiveAuthorizationId}`, + ) + expect(completeProof).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ browserBinding }), + ) + expect(verifyAdministratorAuthorization).toHaveBeenCalledWith({ + authorizationAttemptId: "00000000-0000-4000-8000-000000000010", + externalIdentityId: "00000000-0000-4000-8000-000000000012", + providerAssignment: undefined, + sessionDigest: createHash("sha256").update("retained-session").digest("hex"), + sensitiveAuthorizationId, + }) + expect(admitSession).not.toHaveBeenCalled() + const cookies = response.headers["set-cookie"] ?? [] + expectClearedSessionCookie(cookies, "__Host-hub_auth_browser") + expect(cookies.some((cookie) => /^(?:__Host-)?hub_session=/.test(cookie))).toBe(false) + }, + { trustedProxyHops: 1 }, + ) }) it("returns a busy administrator callback to the active session with retry guidance", async () => { @@ -1027,6 +1269,135 @@ describe("authenticationRoutes()", () => { }) }) + it("restores only the legacy session for HTTP configuration even over a trusted HTTPS proxy", async () => { + const { dependencies, restoreSession } = routeDependencies() + restoreSession.mockResolvedValue({ + membershipId: randomUUID(), + userId: randomUUID(), + provider: "local", + sessionProvider: "local", + login: "local-test", + name: "Local developer", + role: "ADMINISTRATOR", + }) + + await withServer( + dependencies, + async (baseUrl) => { + const protectedOnly = await requestThroughProxy(`${baseUrl}/api/auth/session`, { + cookie: "__Host-hub_session=protected-session", + }) + expect(protectedOnly.statusCode).toBe(401) + expect(restoreSession).not.toHaveBeenCalled() + + const both = await requestThroughProxy(`${baseUrl}/api/auth/session`, { + cookie: "__Host-hub_session=protected-session; hub_session=local-session", + }) + expect(both.statusCode).toBe(200) + expect(restoreSession).toHaveBeenCalledExactlyOnceWith( + createHash("sha256").update("local-session").digest("hex"), + ) + }, + { trustedProxyHops: 1 }, + ) + }) + + it.each([ + { scenario: "legacy when protected is absent", order: ["legacy"], selected: "legacy" }, + { scenario: "protected after legacy", order: ["legacy", "protected"], selected: "protected" }, + { scenario: "protected before legacy", order: ["protected", "legacy"], selected: "protected" }, + ] as const)("restores $scenario without reissuing a cookie", async ({ order, selected }) => { + const { dependencies, restoreSession } = routeDependencies(httpsApplicationOrigin) + const sessions = { + legacy: randomBytes(32).toString("base64url"), + protected: randomBytes(32).toString("base64url"), + } + const pairs = { + legacy: `hub_session=${sessions.legacy}`, + protected: `__Host-hub_session=${sessions.protected}`, + } + restoreSession.mockResolvedValue({ + membershipId: randomUUID(), + userId: randomUUID(), + provider: "github", + login: "member", + name: null, + role: "MEMBER", + }) + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy(`${baseUrl}/api/auth/session`, { + cookie: order.map((name) => pairs[name]).join("; "), + }) + + expect(response.statusCode).toBe(200) + expect(response.headers["set-cookie"]).toBeUndefined() + expect(restoreSession).toHaveBeenCalledExactlyOnceWith( + createHash("sha256").update(sessions[selected]).digest("hex"), + ) + }, + { trustedProxyHops: 1 }, + ) + }) + + it.each([ + { reason: "empty", value: "" }, + { reason: "malformed", value: "%" }, + ])("does not fall back when the protected session cookie is $reason", async ({ value }) => { + const { dependencies, restoreSession } = routeDependencies(httpsApplicationOrigin) + const legacy = randomBytes(32).toString("base64url") + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy(`${baseUrl}/api/auth/session`, { + cookie: `__Host-hub_session=${value}; hub_session=${legacy}`, + }) + + expect(response.statusCode).toBe(401) + expect(restoreSession).not.toHaveBeenCalled() + expect(response.headers["set-cookie"]).toBeUndefined() + }, + { trustedProxyHops: 1 }, + ) + }) + + it("does not fall back when the protected session is unrecognized and legacy is current", async () => { + const { dependencies, restoreSession } = routeDependencies(httpsApplicationOrigin) + const legacy = randomBytes(32).toString("base64url") + const legacyDigest = createHash("sha256").update(legacy).digest("hex") + const unknown = randomBytes(32).toString("base64url") + const viewer = { + membershipId: randomUUID(), + userId: randomUUID(), + provider: "github", + login: "member", + name: null, + role: "MEMBER", + } + restoreSession.mockImplementation((digest: string) => + Promise.resolve(digest === legacyDigest ? viewer : null), + ) + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy(`${baseUrl}/api/auth/session`, { + cookie: `__Host-hub_session=${unknown}; hub_session=${legacy}`, + }) + + expect(response.statusCode).toBe(401) + expect(response.headers["set-cookie"]).toBeUndefined() + expect(restoreSession).toHaveBeenCalledExactlyOnceWith( + createHash("sha256").update(unknown).digest("hex"), + ) + }, + { trustedProxyHops: 1 }, + ) + }) + it.each(["octocat", null])( "reports a revoked GitHub session without changing its cookie (login: %s)", async (login) => { @@ -1112,7 +1483,7 @@ describe("authenticationRoutes()", () => { method: "POST", headers: { accept: "text/html,application/xhtml+xml", - cookie: "hub_session=session-value", + cookie: "__Host-hub_session=protected-session; hub_session=session-value", origin: dependencies.signOut.applicationOrigin, }, redirect: "manual", @@ -1120,8 +1491,10 @@ describe("authenticationRoutes()", () => { expect(response.status).toBe(303) expect(response.headers.get("location")).toBe("/") - expect(response.headers.get("set-cookie")).toContain("Max-Age=0") - expect(endSession).toHaveBeenCalledWith( + const cookies = response.headers.getSetCookie() + expect(cookies).toHaveLength(1) + expectClearedSessionCookie(cookies, "hub_session", false) + expect(endSession).toHaveBeenCalledExactlyOnceWith( createHash("sha256").update("session-value").digest("hex"), ) }) @@ -1143,20 +1516,85 @@ describe("authenticationRoutes()", () => { }) }) - it("keeps the session cookie when sign-out authority is busy", async () => { - const { dependencies, endSession } = routeDependencies() - endSession.mockRejectedValue(new SessionTerminationConflictError()) + it.each([ + { scenario: "distinct", legacy: "legacy-session", protectedSession: "protected-session" }, + { scenario: "the same", legacy: "current-session", protectedSession: "current-session" }, + ])( + "ends $scenario presented sessions and clears both cookie names on HTTPS sign-out", + async ({ legacy, protectedSession }) => { + const { dependencies, endSession } = routeDependencies(httpsApplicationOrigin) + endSession.mockResolvedValue(true) + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy( + `${baseUrl}/api/auth/session/sign-out`, + { + cookie: `hub_session=${legacy}; __Host-hub_session=${protectedSession}`, + origin: httpsApplicationOrigin, + }, + "POST", + ) + + expect(response.statusCode).toBe(204) + const presented = [...new Set([legacy, protectedSession])] + expect(endSession).toHaveBeenCalledTimes(presented.length) + for (const value of presented) { + expect(endSession).toHaveBeenCalledWith( + createHash("sha256").update(value).digest("hex"), + ) + } + const cookies = response.headers["set-cookie"] ?? [] + expectClearedSessionCookie(cookies, "__Host-hub_session") + expectClearedSessionCookie(cookies, "hub_session") + }, + { trustedProxyHops: 1 }, + ) + }, + ) + + it.each([ + { reason: "a different Origin", origin: "https://other.example.test" }, + { reason: "no Origin", origin: undefined }, + ])("rejects HTTPS sign-out with $reason", async ({ origin }) => { + const { dependencies, endSession } = routeDependencies(httpsApplicationOrigin) + const protectedSession = randomBytes(32).toString("base64url") + + await withServer( + dependencies, + async (baseUrl) => { + const response = await requestThroughProxy( + `${baseUrl}/api/auth/session/sign-out`, + { cookie: `__Host-hub_session=${protectedSession}`, ...(origin ? { origin } : {}) }, + "POST", + ) + + expect(response.statusCode).toBe(403) + expect(endSession).not.toHaveBeenCalled() + expect(response.headers["set-cookie"]).toBeUndefined() + }, + { trustedProxyHops: 1 }, + ) + }) + + it("keeps both HTTPS cookies when ending one of two sessions succeeds and the other is busy", async () => { + const { dependencies, endSession } = routeDependencies(httpsApplicationOrigin) + endSession + .mockResolvedValueOnce(true) + .mockRejectedValueOnce(new SessionTerminationConflictError()) await withServer(dependencies, async (baseUrl) => { const response = await fetch(`${baseUrl}/api/auth/session/sign-out`, { method: "POST", headers: { accept: "application/json", - cookie: "hub_session=session-value", + cookie: "__Host-hub_session=protected-session; hub_session=legacy-session", origin: dependencies.signOut.applicationOrigin, }, }) expect(response.status).toBe(503) + expect(endSession).toHaveBeenCalledTimes(2) expect(response.headers.get("retry-after")).toBe("1") expect(response.headers.get("set-cookie")).toBeNull() expect(await response.json()).toEqual({ @@ -1166,20 +1604,26 @@ describe("authenticationRoutes()", () => { }) it("returns a busy native sign-out to the active session with retry guidance", async () => { - const { dependencies, endSession } = routeDependencies() - endSession.mockRejectedValue(new SessionTerminationConflictError()) + const { dependencies, endSession } = routeDependencies(httpsApplicationOrigin) + const legacyDigest = createHash("sha256").update("legacy-session").digest("hex") + endSession.mockImplementation((digest: string) => + digest === legacyDigest + ? Promise.reject(new SessionTerminationConflictError()) + : Promise.resolve(true), + ) await withServer(dependencies, async (baseUrl) => { const response = await fetch(`${baseUrl}/api/auth/session/sign-out`, { method: "POST", headers: { accept: "text/html", - cookie: "hub_session=session-value", + cookie: "__Host-hub_session=protected-session; hub_session=legacy-session", origin: dependencies.signOut.applicationOrigin, }, redirect: "manual", }) expect(response.status).toBe(503) + expect(endSession).toHaveBeenCalledExactlyOnceWith(legacyDigest) expect(response.headers.get("content-type")).toContain("text/plain") expect(response.headers.get("retry-after")).toBe("1") expect(response.headers.get("set-cookie")).toBeNull() diff --git a/hub/server/routes/api/auth/session/get/index.ts b/hub/server/routes/api/auth/session/get/index.ts index 0d5b2d638..01f7959a8 100644 --- a/hub/server/routes/api/auth/session/get/index.ts +++ b/hub/server/routes/api/auth/session/get/index.ts @@ -2,8 +2,8 @@ import type { RequestHandler } from "express" import { hashAuthenticationValue } from "../../../../../domains/authentication/hash-authentication-value/index.ts" import { githubRepositoryDenialCookieName } from "../../../../../integrations/express/github-repository-denial-cookie-name/index.ts" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../types.ts" export function get( @@ -23,7 +23,7 @@ export function get( return } } - const value = readCookie(request, hubSessionCookieName) + const value = readHubSessionCookie(request) if (!value) { response.status(401).json({ authenticated: false }) return diff --git a/hub/server/routes/api/auth/session/sign-out/post/index.ts b/hub/server/routes/api/auth/session/sign-out/post/index.ts index 6bf8d1495..c6f40195f 100644 --- a/hub/server/routes/api/auth/session/sign-out/post/index.ts +++ b/hub/server/routes/api/auth/session/sign-out/post/index.ts @@ -2,20 +2,26 @@ import type { RequestHandler } from "express" import { SessionTerminationConflictError } from "../../../../../../domains/admission/errors.ts" import { hashAuthenticationValue } from "../../../../../../domains/authentication/hash-authentication-value/index.ts" -import { clearAuthenticationCookie } from "../../../../../../integrations/express/clear-authentication-cookie/index.ts" -import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" +import { clearHubSessionCookies } from "../../../../../../integrations/express/clear-hub-session-cookies/index.ts" +import { + hubSessionCookieName, + secureHubSessionCookieName, +} from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../../../../../integrations/express/read-cookie/index.ts" import type { SignOutDependencies } from "../../../types.ts" export function post(dependencies: SignOutDependencies): RequestHandler { return async (request, response, next) => { - const value = readCookie(request, hubSessionCookieName) + // Keep the protected session usable for a retry if ending the legacy session fails. + const values = new Set([ + readCookie(request, hubSessionCookieName), + dependencies.secureCookie ? readCookie(request, secureHubSessionCookieName) : null, + ]) try { - if (value) await dependencies.end(hashAuthenticationValue(value)) - response.setHeader( - "Set-Cookie", - clearAuthenticationCookie(hubSessionCookieName, dependencies.secureCookie), - ) + for (const value of values) { + if (value) await dependencies.end(hashAuthenticationValue(value)) + } + response.setHeader("Set-Cookie", clearHubSessionCookies(dependencies.secureCookie)) if ((request.get("accept") ?? "").includes("text/html")) { response.redirect(303, "/") return diff --git a/hub/server/routes/api/canvas/index.ts b/hub/server/routes/api/canvas/index.ts index ace9b8458..83592e362 100644 --- a/hub/server/routes/api/canvas/index.ts +++ b/hub/server/routes/api/canvas/index.ts @@ -10,8 +10,7 @@ import { createCanvasConnections } from "../../../domains/canvas/connections/ind import { canvasDigest, userCodePattern } from "../../../domains/canvas/credentials/index.ts" import { createCanvasPairings } from "../../../domains/canvas/pairings/index.ts" import { requireOrigin } from "../../../integrations/express/require-origin/index.ts" -import { hubSessionCookieName } from "../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../integrations/github/errors.ts" import { DecisionModelError } from "../../../domains/decision-model/errors.ts" import { reserveAuthenticationRateLimit } from "../../../repositories/authentication-rate-limits/reserve-authentication-rate-limit/index.ts" @@ -131,7 +130,7 @@ export function canvasRoutes( } async function browser(request: Request, services: Dependencies) { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) return cookie ? services.authority.browser(canvasDigest(cookie)) : null } diff --git a/hub/server/routes/api/copilot-connection/authorizations/start/post/index.ts b/hub/server/routes/api/copilot-connection/authorizations/start/post/index.ts index 7ddf35dde..d351b45a9 100644 --- a/hub/server/routes/api/copilot-connection/authorizations/start/post/index.ts +++ b/hub/server/routes/api/copilot-connection/authorizations/start/post/index.ts @@ -69,7 +69,7 @@ export function post(dependencies: CopilotConnectionRouteDependencies): RequestH "Set-Cookie", createAuthenticationCookie({ expiresAt: started.expiresAt, - name: browserAuthenticationCookieName, + name: browserAuthenticationCookieName(provider.secureCookie), secure: provider.secureCookie, value: started.browserBinding, }), diff --git a/hub/server/routes/api/copilot-connection/index.test.ts b/hub/server/routes/api/copilot-connection/index.test.ts index 7e74dfffa..f424b568a 100644 --- a/hub/server/routes/api/copilot-connection/index.test.ts +++ b/hub/server/routes/api/copilot-connection/index.test.ts @@ -168,11 +168,15 @@ describe("copilotConnectionRoutes()", () => { it("requires explicit confirmation and binds fresh authorization to the saved generation", async () => { const { authentication, copilotConnection, github } = routeDependencies() + const origin = "https://hub.example.test" + copilotConnection.applicationOrigin = origin + Object.assign(authentication.signOut, { applicationOrigin: origin, secureCookie: true }) + Object.assign(github.dependencies, { applicationOrigin: origin, secureCookie: true }) await withServer(authentication, copilotConnection, async (baseUrl) => { const denied = await fetch(`${baseUrl}/api/copilot-connection/authorizations/start`, { method: "POST", - headers: sessionHeaders({ "content-type": "application/json", origin: applicationOrigin }), + headers: sessionHeaders({ "content-type": "application/json", origin }), body: JSON.stringify({ operation: "CONNECT_COPILOT" }), }) @@ -181,11 +185,14 @@ describe("copilotConnectionRoutes()", () => { const response = await fetch(`${baseUrl}/api/copilot-connection/authorizations/start`, { method: "POST", - headers: sessionHeaders({ "content-type": "application/json", origin: applicationOrigin }), + headers: sessionHeaders({ "content-type": "application/json", origin }), body: JSON.stringify({ confirmed: true, operation: "CONNECT_COPILOT" }), }) expect(response.status).toBe(200) + expect(response.headers.getSetCookie()).toEqual([ + expect.stringMatching(/^__Host-hub_auth_browser=browser-binding-with-required-length;/), + ]) expect(github.start).toHaveBeenCalledWith({ actorMembershipId: session.membershipId, expectedCopilotGeneration: 7n, diff --git a/hub/server/routes/api/copilot-connection/read-session-digest/index.ts b/hub/server/routes/api/copilot-connection/read-session-digest/index.ts index bc215e22f..253fd0608 100644 --- a/hub/server/routes/api/copilot-connection/read-session-digest/index.ts +++ b/hub/server/routes/api/copilot-connection/read-session-digest/index.ts @@ -1,10 +1,9 @@ import type { Request } from "express" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" export function readSessionDigest(request: Request) { - const value = readCookie(request, hubSessionCookieName) + const value = readHubSessionCookie(request) return value ? hashAuthenticationValue(value) : null } diff --git a/hub/server/routes/api/decision-model/read-decision-model-session/index.ts b/hub/server/routes/api/decision-model/read-decision-model-session/index.ts index 584c5f685..8ae7b12f2 100644 --- a/hub/server/routes/api/decision-model/read-decision-model-session/index.ts +++ b/hub/server/routes/api/decision-model/read-decision-model-session/index.ts @@ -1,7 +1,6 @@ import type { Request } from "express" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import { readProductSession } from "../../product/read-product-session/index.ts" import type { DecisionModelRouteDependencies } from "../types.ts" @@ -9,5 +8,5 @@ export function readDecisionModelSession( request: Request, dependencies: DecisionModelRouteDependencies, ) { - return readProductSession(readCookie(request, hubSessionCookieName), dependencies.currentSession) + return readProductSession(readHubSessionCookie(request), dependencies.currentSession) } diff --git a/hub/server/routes/api/learnings/read-learning-session-digest/index.ts b/hub/server/routes/api/learnings/read-learning-session-digest/index.ts index 086586af0..cb5538282 100644 --- a/hub/server/routes/api/learnings/read-learning-session-digest/index.ts +++ b/hub/server/routes/api/learnings/read-learning-session-digest/index.ts @@ -1,10 +1,9 @@ import type { Request } from "express" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" export function readLearningSessionDigest(request: Request): string | null { - const value = readCookie(request, hubSessionCookieName) + const value = readHubSessionCookie(request) return value ? hashAuthenticationValue(value) : null } diff --git a/hub/server/routes/api/learnings/read-learning-session/index.ts b/hub/server/routes/api/learnings/read-learning-session/index.ts index b2b5047df..124defe13 100644 --- a/hub/server/routes/api/learnings/read-learning-session/index.ts +++ b/hub/server/routes/api/learnings/read-learning-session/index.ts @@ -1,10 +1,9 @@ -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import type { Request } from "express" import { readProductSession } from "../../product/read-product-session/index.ts" import type { LearningsRouteDependencies } from "../types.ts" export function readLearningSession(request: Request, dependencies: LearningsRouteDependencies) { - return readProductSession(readCookie(request, hubSessionCookieName), dependencies.currentSession) + return readProductSession(readHubSessionCookie(request), dependencies.currentSession) } diff --git a/hub/server/routes/api/product-index/index.db.test.ts b/hub/server/routes/api/product-index/index.db.test.ts index 43203d89f..7217c4574 100644 --- a/hub/server/routes/api/product-index/index.db.test.ts +++ b/hub/server/routes/api/product-index/index.db.test.ts @@ -1448,6 +1448,7 @@ describe("real product index", () => { } for (const [key, value] of Object.entries(entra)) vi.stubEnv(key, value) vi.stubEnv("RUNTIME_MODE", "api") + vi.stubEnv("HUB_TRUSTED_PROXY_HOPS", "1") vi.stubEnv("OTEL_SDK_DISABLED", "true") vi.stubEnv("REPLICA_LEARNING_ROOT", "storage/learning") vi.stubGlobal( diff --git a/hub/server/routes/api/public-sharing/links/delete/index.ts b/hub/server/routes/api/public-sharing/links/delete/index.ts index d5938ddeb..18f066f5f 100644 --- a/hub/server/routes/api/public-sharing/links/delete/index.ts +++ b/hub/server/routes/api/public-sharing/links/delete/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import type { ProductRouteDependencies } from "../../../product/types.ts" @@ -18,7 +17,7 @@ export function del( return async (request, response, next) => { try { if (sharing.hosted) response.setHeader("Cache-Control", "private, no-store") - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/public-sharing/links/get/index.ts b/hub/server/routes/api/public-sharing/links/get/index.ts index 8a31e7ecf..bfabd94d3 100644 --- a/hub/server/routes/api/public-sharing/links/get/index.ts +++ b/hub/server/routes/api/public-sharing/links/get/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import type { ProductRouteDependencies } from "../../../product/types.ts" @@ -20,7 +19,7 @@ export function get( return async (request, response, next) => { try { if (sharing.hosted) response.setHeader("Cache-Control", "private, no-store") - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/public-sharing/links/post/index.ts b/hub/server/routes/api/public-sharing/links/post/index.ts index 59a138961..bca543791 100644 --- a/hub/server/routes/api/public-sharing/links/post/index.ts +++ b/hub/server/routes/api/public-sharing/links/post/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import type { ProductRouteDependencies } from "../../../product/types.ts" @@ -26,7 +25,7 @@ export function post( return async (request, response, next) => { try { if (sharing.hosted) response.setHeader("Cache-Control", "private, no-store") - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/public-sharing/settings/get/index.ts b/hub/server/routes/api/public-sharing/settings/get/index.ts index a840b5234..91aac99ce 100644 --- a/hub/server/routes/api/public-sharing/settings/get/index.ts +++ b/hub/server/routes/api/public-sharing/settings/get/index.ts @@ -1,7 +1,6 @@ import type { RequestHandler } from "express" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import type { PublicSharingRouteDependencies } from "../../types.ts" @@ -12,7 +11,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const current = await readProductSession(readCookie(request, hubSessionCookieName), session) + const current = await readProductSession(readHubSessionCookie(request), session) if (!current) { response.status(401).json({ error: "Sign in to continue." }) return diff --git a/hub/server/routes/api/public-sharing/settings/patch/index.ts b/hub/server/routes/api/public-sharing/settings/patch/index.ts index 74ebcf7b8..48e6b0c84 100644 --- a/hub/server/routes/api/public-sharing/settings/patch/index.ts +++ b/hub/server/routes/api/public-sharing/settings/patch/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import { respondPublicSharingError } from "../../respond-public-sharing-error/index.ts" @@ -21,7 +20,7 @@ export function patch( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/analytics/callback/index.ts b/hub/server/routes/api/repositories/analytics/callback/index.ts index 8cc5211ee..5b1e522d1 100644 --- a/hub/server/routes/api/repositories/analytics/callback/index.ts +++ b/hub/server/routes/api/repositories/analytics/callback/index.ts @@ -4,8 +4,8 @@ import { z } from "zod" import type { RepositoryAnalyticsProof } from "../../../../../domains/analytics/hosted-authorization/types.ts" import { hashAuthenticationValue } from "../../../../../domains/authentication/hash-authentication-value/index.ts" import { clearAuthenticationCookie } from "../../../../../integrations/express/clear-authentication-cookie/index.ts" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { AnalyticsRouteDependencies } from "../types.ts" export const analyticsBrowserCookie = "hub_analytics_auth_browser" @@ -34,7 +34,7 @@ export function repositoryAnalyticsCallback( (query.data.iss !== undefined && query.data.iss !== proof.callbackIssuer) ) return next() - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const result = await authorization.complete(proof, { browserBinding: binding.data, state: query.data.state, diff --git a/hub/server/routes/api/repositories/analytics/index.ts b/hub/server/routes/api/repositories/analytics/index.ts index 70f4b508c..6d1162810 100644 --- a/hub/server/routes/api/repositories/analytics/index.ts +++ b/hub/server/routes/api/repositories/analytics/index.ts @@ -8,10 +8,9 @@ import type { RepositoryAnalyticsProof } from "../../../../domains/analytics/hos import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" import { AuthenticationProofError } from "../../../../domains/authentication/errors.ts" import { AnalyticsEventName, AnalyticsProvider } from "../../../../generated/prisma/enums.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" import { createAuthenticationCookie } from "../../../../integrations/express/create-authentication-cookie/index.ts" import { rateLimit } from "../../../../integrations/express/authentication-rate-limit/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import { requireOrigin } from "../../../../integrations/express/require-origin/index.ts" import { GitHubProviderRequestError } from "../../../../integrations/github/errors.ts" import type { CurrentSessionDependencies } from "../../auth/types.ts" @@ -55,7 +54,7 @@ export function mountRepositoryAnalytics( response.status(404).json({ error: "Repository or destination not found." }) return } - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const viewer = await readProductSession(cookie, session) if (!cookie || !viewer) { response.status(401).json({ error: "Sign in to continue." }) @@ -180,7 +179,7 @@ export function mountRepositoryAnalytics( try { const repositoryId = uuid.safeParse(request.params.repositoryId) const id = uuid.safeParse(request.params.authorizationId) - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) if (!repositoryId.success || !id.success || !cookie || !hostedAuthorization) { response.status(404).json({ error: "Analytics authorization is no longer available." }) return diff --git a/hub/server/routes/api/repositories/authors/get/index.ts b/hub/server/routes/api/repositories/authors/get/index.ts index 2016b606d..ef2630a92 100644 --- a/hub/server/routes/api/repositories/authors/get/index.ts +++ b/hub/server/routes/api/repositories/authors/get/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import { readProductWithCurrentAuthority } from "../../../product/read-product-with-current-authority/index.ts" @@ -19,7 +18,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/prototype-management/get/index.ts b/hub/server/routes/api/repositories/prototype-management/get/index.ts index 552383d3b..e037ac25a 100644 --- a/hub/server/routes/api/repositories/prototype-management/get/index.ts +++ b/hub/server/routes/api/repositories/prototype-management/get/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../../integrations/github/errors.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" @@ -15,7 +14,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/prototypes/builds/access/get/index.ts b/hub/server/routes/api/repositories/prototypes/builds/access/get/index.ts index 773348375..3312941fa 100644 --- a/hub/server/routes/api/repositories/prototypes/builds/access/get/index.ts +++ b/hub/server/routes/api/repositories/prototypes/builds/access/get/index.ts @@ -4,8 +4,7 @@ import { z } from "zod" import { createBuildPreviewOrigin } from "../../../../../../../domains/build-preview/create-build-preview-origin/index.ts" import { createPreviewGrant } from "../../../../../../../domains/build-preview/create-preview-grant/index.ts" import { hashAuthenticationValue } from "../../../../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../../../auth/types.ts" import { readProductSession } from "../../../../../product/read-product-session/index.ts" import { readProductWithCurrentAuthority } from "../../../../../product/read-product-with-current-authority/index.ts" @@ -29,7 +28,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/prototypes/builds/get/index.ts b/hub/server/routes/api/repositories/prototypes/builds/get/index.ts index 94582fc72..87fe5e294 100644 --- a/hub/server/routes/api/repositories/prototypes/builds/get/index.ts +++ b/hub/server/routes/api/repositories/prototypes/builds/get/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../../auth/types.ts" import { readProductSession } from "../../../../product/read-product-session/index.ts" import { readProductWithCurrentAuthority } from "../../../../product/read-product-with-current-authority/index.ts" @@ -33,7 +32,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/prototypes/review-comments/get/index.ts b/hub/server/routes/api/repositories/prototypes/review-comments/get/index.ts index 405dc918e..bff9973ee 100644 --- a/hub/server/routes/api/repositories/prototypes/review-comments/get/index.ts +++ b/hub/server/routes/api/repositories/prototypes/review-comments/get/index.ts @@ -1,7 +1,6 @@ import type { RequestHandler } from "express" -import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../../auth/types.ts" import { readProductWithCurrentAuthority } from "../../../../product/read-product-with-current-authority/index.ts" import type { @@ -38,7 +37,7 @@ export function get( } const read = await readProductWithCurrentAuthority( current, - readCookie(request, hubSessionCookieName), + readHubSessionCookie(request), session, async (viewer) => (await isRepositoryVisible(viewer, identifiers.repositoryId)) diff --git a/hub/server/routes/api/repositories/prototypes/show/get/index.ts b/hub/server/routes/api/repositories/prototypes/show/get/index.ts index 942e91520..b5fc3dc46 100644 --- a/hub/server/routes/api/repositories/prototypes/show/get/index.ts +++ b/hub/server/routes/api/repositories/prototypes/show/get/index.ts @@ -3,8 +3,7 @@ import { z } from "zod" import { hashAuthenticationValue } from "../../../../../../domains/authentication/hash-authentication-value/index.ts" import { PrototypeViewError } from "../../../../../../domains/prototypes/read-prototype-with-introduction/index.ts" -import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../../../integrations/github/errors.ts" import type { CurrentSessionDependencies } from "../../../../auth/types.ts" import { readProductSession } from "../../../../product/read-product-session/index.ts" @@ -33,7 +32,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/prototypes/show/patch/index.ts b/hub/server/routes/api/repositories/prototypes/show/patch/index.ts index a804ac7dd..ca6cb196a 100644 --- a/hub/server/routes/api/repositories/prototypes/show/patch/index.ts +++ b/hub/server/routes/api/repositories/prototypes/show/patch/index.ts @@ -3,8 +3,7 @@ import { z } from "zod" import { hashAuthenticationValue } from "../../../../../../domains/authentication/hash-authentication-value/index.ts" import { PrototypeMetadataError } from "../../../../../../domains/prototypes/errors.ts" -import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../../../integrations/github/errors.ts" import type { CurrentSessionDependencies } from "../../../../auth/types.ts" import { readProductSession } from "../../../../product/read-product-session/index.ts" @@ -27,7 +26,7 @@ export function patch( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) if (!cookie || !(await readProductSession(cookie, session))) { response.status(401).json({ error: "Sign in to continue." }) return diff --git a/hub/server/routes/api/repositories/show/get/index.ts b/hub/server/routes/api/repositories/show/get/index.ts index 4e9efc9bf..f6512516a 100644 --- a/hub/server/routes/api/repositories/show/get/index.ts +++ b/hub/server/routes/api/repositories/show/get/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import { readProductWithCurrentAuthority } from "../../../product/read-product-with-current-authority/index.ts" @@ -26,7 +25,7 @@ export function get( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/templates/index.ts b/hub/server/routes/api/repositories/templates/index.ts index 11a75c045..8f8dee1e6 100644 --- a/hub/server/routes/api/repositories/templates/index.ts +++ b/hub/server/routes/api/repositories/templates/index.ts @@ -11,8 +11,7 @@ import { templateReturnPath, } from "../../../../domains/build-preview/read-template-manifest/index.ts" import { templateScreenshotPath } from "../../../../domains/build-preview/template-screenshot-path/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../integrations/github/errors.ts" import type { BuildPreviewRouteDependencies } from "../../../build-preview/types.ts" import type { CurrentSessionDependencies } from "../../auth/types.ts" @@ -112,7 +111,7 @@ export function templateRoutes( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!cookie || !initial) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/review-comments/create-review-realtime-access/index.test.ts b/hub/server/routes/api/review-comments/create-review-realtime-access/index.test.ts new file mode 100644 index 000000000..cd9921740 --- /dev/null +++ b/hub/server/routes/api/review-comments/create-review-realtime-access/index.test.ts @@ -0,0 +1,52 @@ +import { createHash, randomUUID } from "node:crypto" +import { IncomingMessage } from "node:http" +import { Socket } from "node:net" +import { describe, expect, it, vi } from "vitest" + +import type { ProductRouteDependencies } from "../../product/types" + +import { createReviewRealtimeAccess } from "." + +describe("createReviewRealtimeAccess()", () => { + it.each([ + { + applicationOrigin: "http://127.0.0.1:5173", + secureCookie: false, + expectedValue: "legacy-session", + }, + { + applicationOrigin: "https://hub.example.test", + secureCookie: true, + expectedValue: "protected-session", + }, + ])( + "uses the configured authentication scheme at $applicationOrigin", + async ({ applicationOrigin, secureCookie, expectedValue }) => { + const restore = vi.fn().mockResolvedValue({ + membershipId: randomUUID(), + userId: randomUUID(), + provider: "github", + sessionProvider: "github", + login: "member", + name: null, + role: "MEMBER", + }) + const access = createReviewRealtimeAccess( + { + currentSession: { restore }, + signOut: { applicationOrigin, secureCookie, end: vi.fn() }, + }, + {} as ProductRouteDependencies, + ) + const request = new IncomingMessage(new Socket()) + request.headers = { + origin: applicationOrigin, + cookie: "hub_session=legacy-session; __Host-hub_session=protected-session", + } + const digest = createHash("sha256").update(expectedValue).digest("hex") + + expect(await access.authenticate?.(request, new AbortController().signal)).toBe(digest) + expect(restore).toHaveBeenCalledExactlyOnceWith(digest) + }, + ) +}) diff --git a/hub/server/routes/api/review-comments/create-review-realtime-access/index.ts b/hub/server/routes/api/review-comments/create-review-realtime-access/index.ts index edba16276..7f851df69 100644 --- a/hub/server/routes/api/review-comments/create-review-realtime-access/index.ts +++ b/hub/server/routes/api/review-comments/create-review-realtime-access/index.ts @@ -1,8 +1,7 @@ import { z } from "zod" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import type { RealtimeOptions } from "../../../../integrations/ws/types.ts" import type { AuthenticationRouteDependencies } from "../../auth/types.ts" import type { ProductRouteDependencies } from "../../product/types.ts" @@ -33,7 +32,7 @@ export function createReviewRealtimeAccess( return { async authenticate(request, signal) { if (request.headers.origin !== authentication.signOut.applicationOrigin) return null - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request, authentication.signOut.secureCookie) if (!cookie || signal.aborted) return null const digest = hashAuthenticationValue(cookie) const current = await authentication.currentSession.restore(digest) diff --git a/hub/server/routes/api/review-comments/read-review-session/index.ts b/hub/server/routes/api/review-comments/read-review-session/index.ts index 3311ca861..fc03279f1 100644 --- a/hub/server/routes/api/review-comments/read-review-session/index.ts +++ b/hub/server/routes/api/review-comments/read-review-session/index.ts @@ -1,12 +1,11 @@ import type { Request } from "express" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../auth/types.ts" export async function readReviewSession(request: Request, session: CurrentSessionDependencies) { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) if (!cookie) return null const sessionDigest = hashAuthenticationValue(cookie) const current = await session.restore(sessionDigest) diff --git a/hub/server/routes/api/security-audits/get/index.ts b/hub/server/routes/api/security-audits/get/index.ts index 280af462e..e34fb5eb4 100644 --- a/hub/server/routes/api/security-audits/get/index.ts +++ b/hub/server/routes/api/security-audits/get/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../integrations/github/errors.ts" import { listSecurityAudits } from "../../../../repositories/security-audits/list-security-audits/index.ts" import type { @@ -97,7 +96,7 @@ export function get( let result if ("session" in dependencies && repositoryId) { const { session, product } = dependencies - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) const id = repositoryId const read = diff --git a/hub/server/routes/api/session-revocation/authorizations/continue/post/index.ts b/hub/server/routes/api/session-revocation/authorizations/continue/post/index.ts index 591b69eda..1b5b24ab9 100644 --- a/hub/server/routes/api/session-revocation/authorizations/continue/post/index.ts +++ b/hub/server/routes/api/session-revocation/authorizations/continue/post/index.ts @@ -5,8 +5,7 @@ import { SessionRevocationDeniedError, SessionRevocationUnavailableError, } from "../../../../../../domains/session-revocation/errors.ts" -import { clearAuthenticationCookie } from "../../../../../../integrations/express/clear-authentication-cookie/index.ts" -import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" +import { clearHubSessionCookies } from "../../../../../../integrations/express/clear-hub-session-cookies/index.ts" import type { SessionRevocationRouteDependencies } from "../../../../auth/types.ts" import { readAdministratorSession } from "../../../../administrators/read-administrator-session/index.ts" @@ -30,10 +29,7 @@ export function post(dependencies: SessionRevocationRouteDependencies): RequestH authorizationId: body.data.authorizationId, hubSessionId: session.id, }) - response.setHeader( - "Set-Cookie", - clearAuthenticationCookie(hubSessionCookieName, dependencies.secureCookie), - ) + response.setHeader("Set-Cookie", clearHubSessionCookies(dependencies.secureCookie)) response.json({ result }) } catch (error) { if (error instanceof SessionRevocationUnavailableError) { diff --git a/hub/server/routes/api/session-revocation/authorizations/start/post/index.ts b/hub/server/routes/api/session-revocation/authorizations/start/post/index.ts index 18b87aa8f..7a39ab1a0 100644 --- a/hub/server/routes/api/session-revocation/authorizations/start/post/index.ts +++ b/hub/server/routes/api/session-revocation/authorizations/start/post/index.ts @@ -45,7 +45,7 @@ export function post(dependencies: SessionRevocationRouteDependencies): RequestH "Set-Cookie", createAuthenticationCookie({ expiresAt: started.expiresAt, - name: browserAuthenticationCookieName, + name: browserAuthenticationCookieName(provider.secureCookie), secure: provider.secureCookie, value: started.browserBinding, }), diff --git a/hub/server/routes/api/session-revocation/index.test.ts b/hub/server/routes/api/session-revocation/index.test.ts index 996884bc5..8703d40c3 100644 --- a/hub/server/routes/api/session-revocation/index.test.ts +++ b/hub/server/routes/api/session-revocation/index.test.ts @@ -156,13 +156,24 @@ describe("sessionRevocationRoutes()", () => { async (_label, providerKey, dependencyKey) => { const dependencies = routeDependencies(providerKey) const provider = dependencies[dependencyKey as "github" | "local"] + const secureCookie = providerKey === "github" + const origin = secureCookie ? "https://hub.example.test" : applicationOrigin + Object.assign(dependencies.authentication.signOut, { + applicationOrigin: origin, + secureCookie, + }) + Object.assign(dependencies.authentication.sessionRevocation!, { + applicationOrigin: origin, + secureCookie, + }) + Object.assign(provider.dependencies, { applicationOrigin: origin, secureCookie }) await withServer(dependencies.authentication, async (baseUrl) => { const unconfirmed = await fetch(`${baseUrl}/api/session-revocation/authorizations/start`, { method: "POST", headers: sessionHeaders({ "content-type": "application/json", - origin: applicationOrigin, + origin, }), body: JSON.stringify({ confirmed: false }), }) @@ -173,11 +184,15 @@ describe("sessionRevocationRoutes()", () => { method: "POST", headers: sessionHeaders({ "content-type": "application/json", - origin: applicationOrigin, + origin, }), body: JSON.stringify({ confirmed: true }), }) expect(confirmed.status).toBe(200) + const name = secureCookie ? "__Host-hub_auth_browser" : "hub_auth_browser" + expect(confirmed.headers.getSetCookie()).toEqual([ + expect.stringMatching(new RegExp(`^${name}=browser-binding-with-required-length;`)), + ]) expect(provider.start).toHaveBeenCalledWith({ actorMembershipId: session.membershipId, externalIdentityId: session.externalIdentityId, diff --git a/hub/server/routes/api/settings/github/authorize-github-setup/index.ts b/hub/server/routes/api/settings/github/authorize-github-setup/index.ts index a9af023be..c9ab5affd 100644 --- a/hub/server/routes/api/settings/github/authorize-github-setup/index.ts +++ b/hub/server/routes/api/settings/github/authorize-github-setup/index.ts @@ -2,8 +2,7 @@ import { createHash } from "node:crypto" import type { Request, Response } from "express" import { hashAuthenticationValue } from "../../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { GitHubSetupRouteDependencies } from "../types.ts" export const bootstrapSecretHeader = "x-hub-bootstrap-secret" @@ -14,7 +13,7 @@ export async function authorizeGitHubSetup( response: Response, dependencies: GitHubSetupRouteDependencies, ) { - const sessionValue = readCookie(request, hubSessionCookieName) + const sessionValue = readHubSessionCookie(request) const bootstrapSecret = request.get(bootstrapSecretHeader) if (bootstrapSecret) { const subjectDigest = createHash("sha256") diff --git a/hub/server/routes/api/workspace/get/index.ts b/hub/server/routes/api/workspace/get/index.ts index d8efe3175..e194a03ef 100644 --- a/hub/server/routes/api/workspace/get/index.ts +++ b/hub/server/routes/api/workspace/get/index.ts @@ -5,8 +5,7 @@ import { z } from "zod" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" import { authorizeRepositoryReview } from "../../../../domains/review-comments/authorize-repository-review/index.ts" -import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../integrations/express/read-hub-session-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../integrations/github/errors.ts" import { canWriteRepository } from "../../../../utils/can-write-repository/index.ts" import type { CurrentSessionDependencies } from "../../auth/types.ts" @@ -28,7 +27,7 @@ export function get( return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const initial = await readProductSession(cookie, session) if (!initial || !cookie) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/workspace/welcome/patch/index.ts b/hub/server/routes/api/workspace/welcome/patch/index.ts index 9f1c8b0c7..db8411430 100644 --- a/hub/server/routes/api/workspace/welcome/patch/index.ts +++ b/hub/server/routes/api/workspace/welcome/patch/index.ts @@ -1,8 +1,7 @@ import type { RequestHandler } from "express" import { hashAuthenticationValue } from "../../../../../domains/authentication/hash-authentication-value/index.ts" -import { hubSessionCookieName } from "../../../../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../../../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../../../../integrations/express/read-hub-session-cookie/index.ts" import type { CurrentSessionDependencies } from "../../../auth/types.ts" import { readProductSession } from "../../../product/read-product-session/index.ts" import type { WorkspaceProductRouteDependencies } from "../../../product/types.ts" @@ -13,7 +12,7 @@ export function patch( ): RequestHandler { return async (request, response, next) => { try { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) const current = await readProductSession(cookie, session) if ( !cookie || diff --git a/hub/server/routes/index.ts b/hub/server/routes/index.ts index 0654eae68..0420b6c95 100644 --- a/hub/server/routes/index.ts +++ b/hub/server/routes/index.ts @@ -452,7 +452,10 @@ export function routes(app: Express, dependencies: RouteDependencies = {}): void authentication.github.repositoryAnalyticsProof, product?.analytics?.hostedAuthorization, ), - handleAuthenticationCallbackGet(authentication.github.callback), + handleAuthenticationCallbackGet( + authentication.github.callback, + authentication.github.signIn.applicationOrigin, + ), ) } if (authentication.entra) { @@ -473,7 +476,10 @@ export function routes(app: Express, dependencies: RouteDependencies = {}): void app.get( "/api/auth/entra/callback", rateLimit(authentication.entra.callback, "callback"), - handleAuthenticationCallbackGet(authentication.entra.callback), + handleAuthenticationCallbackGet( + authentication.entra.callback, + authentication.entra.signIn.applicationOrigin, + ), ) } if (authentication.local) { @@ -487,7 +493,10 @@ export function routes(app: Express, dependencies: RouteDependencies = {}): void app.get( "/api/auth/local/callback", rateLimit(authentication.local.callback, "callback"), - handleAuthenticationCallbackGet(authentication.local.callback), + handleAuthenticationCallbackGet( + authentication.local.callback, + authentication.local.signIn.applicationOrigin, + ), ) } app.get( diff --git a/hub/server/routes/private-preview/index.test.ts b/hub/server/routes/private-preview/index.test.ts index 144cb517c..d913151c9 100644 --- a/hub/server/routes/private-preview/index.test.ts +++ b/hub/server/routes/private-preview/index.test.ts @@ -139,7 +139,9 @@ describe("private preview Hub routes", () => { createApp({ logger: createLogger({ level: "silent" }), trustedProxyHops: 1 }), ) - const launch = await request(address.launch, { cookie: "hub_session=synthetic" }) + const launch = await request(address.launch, { + cookie: `__Host-hub_session=${randomBytes(32).toString("base64url")}`, + }) const exchange = await request(readerExchangePath, { "content-type": "application/json" }, "{}") expect(launch.status).toBe(404) @@ -152,7 +154,7 @@ describe("private preview Hub routes", () => { const session = randomBytes(32).toString("base64url") const sessionDigest = createHash("sha256").update(session).digest("hex") const challenge = randomBytes(32).toString("hex") - const headers = { cookie: `hub_session=${session}` } + const headers = { cookie: `__Host-hub_session=${session}` } const anonymous = await request(address.launch) expect(anonymous.status).toBe(401) @@ -178,6 +180,18 @@ describe("private preview Hub routes", () => { expect(authority.issue).not.toHaveBeenCalled() }) + it("rejects a legacy-only session before checking private launch authority", async () => { + const { request, authority } = await startHub() + const session = randomBytes(32).toString("base64url") + + const launch = await request(address.launch, { cookie: `hub_session=${session}` }) + + expect(launch.status).toBe(401) + expect(launch.headers.location).toBeUndefined() + expect(authority.launch).not.toHaveBeenCalled() + expect(authority.issue).not.toHaveBeenCalled() + }) + it("sends the grant to the Reader only after a same-origin Hub confirmation", async () => { const { request, grant, authority } = await startHub() const session = randomBytes(32).toString("base64url") @@ -187,7 +201,7 @@ describe("private preview Hub routes", () => { const handoff = await request( address.launch, { - cookie: `hub_session=${session}`, + cookie: `__Host-hub_session=${session}`, origin: hubOrigin, "content-type": "application/x-www-form-urlencoded", }, @@ -211,32 +225,39 @@ describe("private preview Hub routes", () => { { reason: "a different origin on the same site", origin: "https://other.example.com", - signedIn: true, + cookieName: "__Host-hub_session", }, - { reason: "no origin", origin: undefined, signedIn: true }, - { reason: "no Hub session", origin: hubOrigin, signedIn: false }, - ])("rejects confirmation with $reason without issuing a grant", async ({ origin, signedIn }) => { - const { request, authority } = await startHub() - const challenge = randomBytes(32).toString("hex") - const headers: Record = { "content-type": "application/x-www-form-urlencoded" } - if (origin) headers.origin = origin - if (signedIn) headers.cookie = `hub_session=${randomBytes(32).toString("base64url")}` - - const confirmation = await request( - address.launch, - headers, - new URLSearchParams({ challenge }).toString(), - ) + { reason: "no origin", origin: undefined, cookieName: "__Host-hub_session" }, + { reason: "no Hub session", origin: hubOrigin, cookieName: undefined }, + { reason: "only a legacy session", origin: hubOrigin, cookieName: "hub_session" }, + ])( + "rejects confirmation with $reason without issuing a grant", + async ({ origin, cookieName }) => { + const { request, authority } = await startHub() + const challenge = randomBytes(32).toString("hex") + const headers: Record = { + "content-type": "application/x-www-form-urlencoded", + } + if (origin) headers.origin = origin + if (cookieName) headers.cookie = `${cookieName}=${randomBytes(32).toString("base64url")}` + + const confirmation = await request( + address.launch, + headers, + new URLSearchParams({ challenge }).toString(), + ) - expect(confirmation.status).toBe(404) - expect(authority.issue).not.toHaveBeenCalled() - }) + expect(confirmation.status).toBe(404) + expect(authority.launch).not.toHaveBeenCalled() + expect(authority.issue).not.toHaveBeenCalled() + }, + ) it("does not serve canonical preview files on the Hub origin", async () => { const { request, authority } = await startHub() const response = await request(`${address.mount}index.html`, { - cookie: "hub_session=synthetic", + cookie: `__Host-hub_session=${randomBytes(32).toString("base64url")}`, accept: "text/html", }) @@ -293,7 +314,7 @@ describe("private preview Hub routes", () => { expect(responses.map(({ status }) => status)).toEqual([200, 200]) expect(responses.map(({ body }) => body)).toEqual([bytes.toString(), bytes.toString()]) - const launchHeaders = { cookie: "hub_session=synthetic" } + const launchHeaders = { cookie: `__Host-hub_session=${randomBytes(32).toString("base64url")}` } expect((await request(address.launch, { ...launchHeaders, host })).status).toBe(404) expect(authority.launch).not.toHaveBeenCalled() @@ -307,7 +328,7 @@ describe("private preview Hub routes", () => { const launch = await request(address.launch, { host: "unconfigured.example.com", - cookie: "hub_session=synthetic", + cookie: `__Host-hub_session=${randomBytes(32).toString("base64url")}`, }) expect(launch.status).toBe(404) diff --git a/hub/server/routes/private-preview/index.ts b/hub/server/routes/private-preview/index.ts index 9701fc495..3f5bff5f2 100644 --- a/hub/server/routes/private-preview/index.ts +++ b/hub/server/routes/private-preview/index.ts @@ -5,7 +5,7 @@ import { z } from "zod" import { hashAuthenticationValue } from "../../domains/authentication/hash-authentication-value/index.ts" import { previewDigestPattern, previewTokenPattern } from "../../domains/private-preview/types.ts" import { authenticationSecurity } from "../../integrations/express/authentication-security/index.ts" -import { hubSessionCookieName } from "../../integrations/express/hub-session-cookie-name/index.ts" +import { secureHubSessionCookieName } from "../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../integrations/express/read-cookie/index.ts" import { privatePreviewAddress } from "../../utils/private-preview-address/index.ts" import type { PrivatePreviewRouteDependencies } from "./types.ts" @@ -46,12 +46,14 @@ export function mountPrivatePreview( router.get("/launch/:repositoryId/:runId", async (request, response) => { const address = privatePreviewAddress(request.params.repositoryId, request.params.runId) if (!address || request.method !== "GET") return response.sendStatus(404) - const session = readCookie(request, hubSessionCookieName) + const session = readCookie(request, secureHubSessionCookieName) if (!session) { return response .status(401) .type("text") - .send("Sign in to Hub, then reopen this preview link.") + .send( + "Sign in to Hub, then reopen this preview link. If already signed in, sign out first.", + ) } const challenge = request.query.challenge if ( @@ -107,7 +109,7 @@ export function mountPrivatePreview( express.urlencoded({ extended: false, limit: "1kb", parameterLimit: 1, inflate: false }), async (request, response) => { const address = privatePreviewAddress(request.params.repositoryId, request.params.runId) - const session = readCookie(request, hubSessionCookieName) + const session = readCookie(request, secureHubSessionCookieName) const confirmation = z .strictObject({ challenge: z.string().regex(previewDigestPattern) }) .safeParse(request.body) diff --git a/infrastructure/azure/post/configure/index.test.ts b/infrastructure/azure/post/configure/index.test.ts index b98669f1f..26afc912e 100644 --- a/infrastructure/azure/post/configure/index.test.ts +++ b/infrastructure/azure/post/configure/index.test.ts @@ -299,8 +299,9 @@ it("validates the authoritative origin and explicit proxy hops while preserving .mockResolvedValueOnce("https://unbound.example.com") .mockResolvedValueOnce("https://bound.example.com") .mockResolvedValueOnce("") + .mockResolvedValueOnce("0") .mockResolvedValueOnce("11") - .mockResolvedValueOnce("2") + .mockResolvedValueOnce("10") const desired = await configurePostSetup(test.context, "sign-in", test.inputs, test.deployment) @@ -311,7 +312,7 @@ it("validates the authoritative origin and explicit proxy hops while preserving hub_application_origin: "https://bound.example.com", runtime_environment_variables: { ...original.runtime_environment_variables, - HUB_TRUSTED_PROXY_HOPS: "2", + HUB_TRUSTED_PROXY_HOPS: "10", }, }) expect(test.inputs).toEqual(original) diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index 98b8e9013..002746e26 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -459,13 +459,13 @@ export async function configurePostSetup( } next.runtime_environment_variables.HUB_TRUSTED_PROXY_HOPS = await field( "proxyHops", - "Verified protected proxy hop count (0-10). Enter the actual ingress chain; post-setup does not guess it.", + "Verified protected proxy hop count (1-10). Enter the actual ingress chain; post-setup does not guess it.", inputs.runtime_environment_variables?.HUB_TRUSTED_PROXY_HOPS ?? deployment.environment.HUB_TRUSTED_PROXY_HOPS ?? "", (value) => { - if (!/^(?:[0-9]|10)$/.test(value)) - throw new InputValidationError("Enter the verified proxy hop count from 0 to 10.") + if (!/^(?:[1-9]|10)$/.test(value)) + throw new InputValidationError("Enter the verified proxy hop count from 1 to 10.") return value }, )