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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 6 additions & 29 deletions src/env.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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),
},

/**
Expand All @@ -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.
Expand Down
45 changes: 25 additions & 20 deletions src/lib/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<AppRouter>({
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()}` }),
}),
],
})
Loading