From d0b7370e846207c9a35b5bdfa0686d0542c1a55d Mon Sep 17 00:00:00 2001 From: Bianca Date: Mon, 26 Oct 2026 20:35:04 +0100 Subject: [PATCH] fix(backend): require the IdP token for every backend call PoliNetworkOrg/backend#97 removes the backend's anonymous path, so the website's fallback to anonymous calls goes: the IdP variables are required and every call carries the website client's token. Production already sets them. --- .env.example | 11 +++++------ README.md | 5 ++--- src/env.js | 35 ++++++----------------------------- src/lib/backend.ts | 45 +++++++++++++++++++++++++-------------------- 4 files changed, 38 insertions(+), 58 deletions(-) diff --git a/.env.example b/.env.example index 3e05a50e..a373e60e 100644 --- a/.env.example +++ b/.env.example @@ -11,12 +11,11 @@ BACKEND_URL=http://localhost:3000 -# PoliNetwork IdP (optional while the backend accepts anonymous calls). Set all of these, or none: -# with none set, backend calls stay anonymous. IDP_INTERNAL_URL is optional. -# IDP_PUBLIC_URL=https://auth.polinetwork.org +# PoliNetwork IdP: required, the backend refuses calls without a token. IDP_INTERNAL_URL is optional. +IDP_PUBLIC_URL=https://auth.polinetwork.org # IDP_INTERNAL_URL=http://auth-service.auth.svc.cluster.local:3000 -# OAUTH_BACKEND_RESOURCE_URI=https://backend.internal.polinetwork.org +OAUTH_BACKEND_RESOURCE_URI=https://backend.internal.polinetwork.org # The ID the IdP generated for the `website` client. -# OAUTH_WEBSITE_CLIENT_ID= +OAUTH_WEBSITE_CLIENT_ID= # The `website` client's private signing key as a single-line JWK, with `kid` and `alg` (EdDSA). -# OAUTH_WEBSITE_PRIVATE_JWK= +OAUTH_WEBSITE_PRIVATE_JWK= diff --git a/README.md b/README.md index 17abc01c..accd7f44 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,8 @@ First, it will be a rewrite of our homepage. ## Backend authentication -Backend calls are server-only (`src/lib/backend.ts`). When the PoliNetwork IdP is configured, they carry a -service token for the `website` client (scope `backend:public:read`); without it they are anonymous, which the -backend accepts only while it allows legacy anonymous calls. Set all of these or none (see `.env.example`): +Backend calls are server-only (`src/lib/backend.ts`) and carry a service token for the `website` client (scope +`backend:public:read`): the backend refuses calls without one. These variables are required (see `.env.example`): - `IDP_PUBLIC_URL`, and optionally `IDP_INTERNAL_URL` for in-cluster token requests - `OAUTH_BACKEND_RESOURCE_URI`: the backend's resource identifier, the token's audience diff --git a/src/env.js b/src/env.js index 3a267f27..7fb3f16f 100644 --- a/src/env.js +++ b/src/env.js @@ -1,14 +1,6 @@ import { createEnv } from "@t3-oss/env-nextjs" import { z } from "zod" -const IDP_REQUIRED_VARIABLES = /** @type {const} */ ([ - "IDP_PUBLIC_URL", - "OAUTH_BACKEND_RESOURCE_URI", - "OAUTH_WEBSITE_CLIENT_ID", - "OAUTH_WEBSITE_PRIVATE_JWK", -]) -const IDP_VARIABLES = /** @type {const} */ ([...IDP_REQUIRED_VARIABLES, "IDP_INTERNAL_URL"]) - export const env = createEnv({ /** * Specify your server-side environment variables schema here. This way you can ensure the app @@ -18,15 +10,15 @@ export const env = createEnv({ NODE_ENV: z.enum(["development", "test", "production"]).default("development"), BACKEND_URL: z.url().default("http://localhost:3000"), - // PoliNetwork IdP (RFC v3 §6, §13 Phase 4a). With these set, backend calls carry a service token - // for the `website` client; with none set, they stay anonymous (legacy path). - IDP_PUBLIC_URL: z.url().optional(), + // PoliNetwork IdP (RFC v3 §6). Backend calls carry a service token for the `website` client; the + // backend refuses calls without one. + IDP_PUBLIC_URL: z.url(), /** In-cluster address for token requests; identifiers always come from IDP_PUBLIC_URL. */ IDP_INTERNAL_URL: z.url().optional(), - OAUTH_BACKEND_RESOURCE_URI: z.url().optional(), - OAUTH_WEBSITE_CLIENT_ID: z.string().min(1).optional(), + OAUTH_BACKEND_RESOURCE_URI: z.url(), + OAUTH_WEBSITE_CLIENT_ID: z.string().min(1), /** The website client's private signing key as a JWK (JSON), with `kid` and `alg`. */ - OAUTH_WEBSITE_PRIVATE_JWK: z.string().min(1).optional(), + OAUTH_WEBSITE_PRIVATE_JWK: z.string().min(1), }, /** @@ -51,21 +43,6 @@ export const env = createEnv({ OAUTH_WEBSITE_CLIENT_ID: process.env.OAUTH_WEBSITE_CLIENT_ID, OAUTH_WEBSITE_PRIVATE_JWK: process.env.OAUTH_WEBSITE_PRIVATE_JWK, }, - /** - * The IdP variables are all or nothing: a partial set would silently fall back to anonymous calls. - * IDP_INTERNAL_URL is optional within the set. - */ - createFinalSchema: (shape, isServer) => - z.object(shape).superRefine((values, ctx) => { - if (!isServer || !IDP_VARIABLES.some((name) => values[name] !== undefined)) return - for (const name of IDP_REQUIRED_VARIABLES) - if (values[name] === undefined) - ctx.addIssue({ - code: "custom", - path: [name], - message: `${name} is missing: set all of ${IDP_REQUIRED_VARIABLES.join(", ")}, or none of the IdP variables`, - }) - }), /** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially * useful for Docker builds. diff --git a/src/lib/backend.ts b/src/lib/backend.ts index 593b9ca5..8ffb4651 100644 --- a/src/lib/backend.ts +++ b/src/lib/backend.ts @@ -17,9 +17,11 @@ function parsePrivateKey(value: string): ServiceTokenSourceOptions["privateKey"] } } -/** Client credentials for the `website` client, or null while the IdP is not configured. */ +/** + * Client credentials for the `website` client. env.js requires the IdP variables; they can only be missing in a build + * with `SKIP_ENV_VALIDATION`, where the token source is null and backend calls fail instead of going out without a token. + */ function createTokenSource() { - // env.js enforces all or none of these, so a partial configuration never reaches this point. const publicUrl = env.IDP_PUBLIC_URL const resource = env.OAUTH_BACKEND_RESOURCE_URI const clientId = env.OAUTH_WEBSITE_CLIENT_ID @@ -44,23 +46,26 @@ function createTokenSource() { const tokens = createTokenSource() const url = env.BACKEND_URL + TRPC_PATH +function requireTokens() { + if (!tokens) throw new Error("The PoliNetwork IdP variables are not set: the backend refuses calls without a token") + return tokens +} + export const trpc = createTRPCClient({ - links: tokens - ? [ - // A 401 is decided before the procedure runs, so retrying once with a new token is safe for - // mutations too. The backend may have rejected an expired or revoked token we still cached. - retryLink({ - retry: ({ error, attempts }) => { - if (attempts > 1 || error.data?.httpStatus !== 401) return false - tokens.invalidate() - return true - }, - }), - httpBatchLink({ - url, - transformer: SuperJSON, - headers: async () => ({ Authorization: `Bearer ${await tokens.getToken()}` }), - }), - ] - : [httpBatchLink({ url, transformer: SuperJSON })], + links: [ + // A 401 is decided before the procedure runs, so retrying once with a new token is safe for + // mutations too. The backend may have rejected an expired or revoked token we still cached. + retryLink({ + retry: ({ error, attempts }) => { + if (attempts > 1 || error.data?.httpStatus !== 401) return false + requireTokens().invalidate() + return true + }, + }), + httpBatchLink({ + url, + transformer: SuperJSON, + headers: async () => ({ Authorization: `Bearer ${await requireTokens().getToken()}` }), + }), + ], })