The Open Framework for Building Agents
fix(eve): auth - advertise configured routeAuth challenges (#1001)
Andrew Barbac0e368a91e48
diff --git a/.changeset/httpbasic-basic-challenge.md b/.changeset/httpbasic-basic-challenge.mdnew file mode 100644index 000000000..46ef9d187--- /dev/null+++ b/.changeset/httpbasic-basic-challenge.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Routes protected by `httpBasic()` now advertise a standards-compliant `WWW-Authenticate: Basic` challenge on 401, using an optional realm that defaults to `"eve"`; HTTP Basic credentials are normalized to Unicode NFC to match the advertised UTF-8 encoding. `routeAuth` collects challenges from the configured auth strategies instead of always emitting `Bearer`.diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex 5599ca506..eb502b198 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -41,7 +41,7 @@ export default eveChannel({- returns `null` / `undefined`: skip to the next entry- **throws**: reject with a specific status-If every entry skips, the request gets a `401`. An empty array `auth: []` rejects everything.+If every entry skips, the request gets a `401` whose `WWW-Authenticate` header advertises the challenge scheme(s) the configured entries declare — `Basic` for `httpBasic()`, `Bearer` for the token-based helpers (`jwtHmac`, `jwtEcdsa`, `oidc`, `vercelOidc`), both when you mix them, and `Bearer` as a fallback for entries that don't declare a scheme (custom `AuthFn`s, or an empty array). See [`withAuthChallenges`](#custom-verifiers) to declare a scheme on a custom `AuthFn`.```tsimport { type AuthFn, localDev, vercelOidc } from "eve/channels/auth";@@ -96,6 +96,8 @@ Any other thrown error follows the normal channel failure path. When building a| `jwtEcdsa(...)` | You verify asymmetric JWTs minted by another system. || `oidc(...)` | You want eve to verify OIDC-issued tokens from an arbitrary issuer. |+`httpBasic(credentials, { realm })` accepts an optional `realm`, rendered on the `WWW-Authenticate: Basic` challenge (e.g. `Basic realm="agent", charset="UTF-8"`) so browsers label their native login prompt. It defaults to `"eve"`, ensuring every Basic challenge includes the required realm. Usernames and passwords are normalized to Unicode NFC before comparison, matching the advertised UTF-8 credential encoding.+Exercise caution for agents that process non-public, sensitive, regulated, or production data unless you have implemented other access controls.### `localDev()`@@ -131,6 +133,17 @@ vercelOidc({When none of the shipped helpers fit, write your own `AuthFn` (the array example above) or call the low-level verifiers directly. Each verifier is the pure function sitting behind the matching strategy helper, and returns `{ ok: true, sessionAuth }` or `{ ok: false }`:+A custom `AuthFn` doesn't declare a `WWW-Authenticate` scheme by default, so `routeAuth` falls back to `Bearer` for it. Wrap it with `withAuthChallenges(fn, challenges)` to declare the scheme(s) it actually satisfies, so a mixed `auth` array produces an accurate 401:++```ts+import { withAuthChallenges, type AuthFn } from "eve/channels/auth";++const apiKeyAuth: AuthFn<Request> = withAuthChallenges(+ (request) => (isValidApiKey(request) ? apiKeySessionAuth : null),+ [{ scheme: "Bearer" }],+);+```+| Verifier | Behind | Input || -------------------------------------- | -------------- | -------------------------------- || `verifyHttpBasic(header, credentials)` | `httpBasic()` | raw `Authorization` header value |diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.tsindex a03a336a2..1c2ee86c6 100644--- a/packages/eve/src/public/channels/auth.test.ts+++ b/packages/eve/src/public/channels/auth.test.ts@@ -17,6 +17,7 @@ import {none,placeholderAuth,routeAuth,+ type UnauthorizedChallenge,UnauthenticatedError,vercelOidc,vercelSubject,@@ -24,6 +25,7 @@ import {verifyJwtEcdsa,verifyJwtHmac,verifyVercelOidc,+ withAuthChallenges,} from "#public/channels/auth.js";const TEST_ROUTE_URL = `https://example.com${EVE_CREATE_SESSION_ROUTE_PATH}`;@@ -53,6 +55,15 @@ describe("verifyHttpBasic", () => {expect(result.ok).toBe(false);});+ it("normalizes credentials to NFC before comparison", () => {+ const result = verifyHttpBasic(+ `Basic ${Buffer.from("caf\u00e9:s\u00e9cret", "utf8").toString("base64")}`,+ { username: "cafe\u0301", password: "se\u0301cret" },+ );++ expect(result.ok).toBe(true);+ });+it("rejects requests with no authorization header", () => {const result = verifyHttpBasic(null, { username: "ops", password: "top-secret" });expect(result.ok).toBe(false);@@ -536,6 +547,156 @@ describe("routeAuth", () => {expect(result).toEqual(SAMPLE_CONTEXT);});++ // ---------------------------------------------------------------------------+ // Declared challenges (vercel/eve#909): the 401 `www-authenticate` header+ // must reflect the auth strategies actually configured on the route,+ // rather than always defaulting to `Bearer`.+ // ---------------------------------------------------------------------------++ it("advertises a Basic challenge when the route is protected only by httpBasic", async () => {+ const request = makeRequest();+ const result = await routeAuth(request, [+ httpBasic({ password: "top-secret", username: "ops" }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.status).toBe(401);+ expect(result.headers.get("www-authenticate")).toBe('Basic realm="eve", charset="UTF-8"');+ }+ });++ it("renders the realm before charset in the Basic challenge", async () => {+ const request = makeRequest();+ const result = await routeAuth(request, [+ httpBasic({ password: "top-secret", username: "ops" }, { realm: "agent" }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe('Basic realm="agent", charset="UTF-8"');+ }+ });++ it("preserves an explicitly empty Basic realm", async () => {+ const result = await routeAuth(makeRequest(), [+ httpBasic({ password: "top-secret", username: "ops" }, { realm: "" }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe('Basic realm="", charset="UTF-8"');+ }+ });++ it("advertises Bearer for a lone jwtHmac strategy", async () => {+ const request = makeRequest();+ const result = await routeAuth(request, [+ jwtHmac({+ algorithm: "HS256",+ audiences: ["weather-agent"],+ issuer: "https://internal.example",+ secret: "shared-secret",+ }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe("Bearer");+ }+ });++ it("advertises both Basic and Bearer for a mixed httpBasic + jwtHmac route", async () => {+ const request = makeRequest();+ const result = await routeAuth(request, [+ httpBasic({ password: "top-secret", username: "ops" }),+ jwtHmac({+ algorithm: "HS256",+ audiences: ["weather-agent"],+ issuer: "https://internal.example",+ secret: "shared-secret",+ }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ const header = result.headers.get("www-authenticate");+ expect(header).toContain('Basic realm="eve", charset="UTF-8"');+ expect(header).toContain("Bearer");+ }+ });++ it("dedupes repeated Bearer challenges from multiple bearer strategies", async () => {+ const request = makeRequest();+ const result = await routeAuth(request, [+ vercelOidc(),+ jwtHmac({+ algorithm: "HS256",+ audiences: ["weather-agent"],+ issuer: "https://internal.example",+ secret: "shared-secret",+ }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe("Bearer");+ }+ });++ it("does not emit www-authenticate on a successful authentication", async () => {+ const result = await routeAuth(makeRequest(), [+ httpBasic({ password: "top-secret", username: "ops" }),+ none(),+ ]);++ expect(result).not.toBeInstanceOf(Response);+ expect(result).toMatchObject({ principalType: "anonymous" });+ });++ it("gives precedence to a thrown UnauthenticatedError over collected challenges", async () => {+ const request = makeRequest();+ const result = await routeAuth(request, [+ () => {+ throw new UnauthenticatedError({ message: "custom rejection" });+ },+ httpBasic({ password: "top-secret", username: "ops" }),+ ]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.status).toBe(401);+ // The thrown error's own response wins outright: `UnauthenticatedError`+ // declares no challenges of its own, so it carries no Basic challenge+ // from the strategy that never ran (nor any www-authenticate header).+ expect(result.headers.has("www-authenticate")).toBe(false);+ await expect(result.json()).resolves.toMatchObject({ error: "custom rejection" });+ }+ });++ it("falls back to Bearer when no configured strategy declares a challenge", async () => {+ const result = await routeAuth(makeRequest(), [() => null, () => undefined]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe("Bearer");+ }+ });++ it("advertises a challenge declared on a custom AuthFn via withAuthChallenges", async () => {+ const challenges: readonly UnauthorizedChallenge[] = [+ { scheme: "Basic", parameters: { realm: "x" } },+ ];+ const customAuthFn = withAuthChallenges<Request>(() => null, challenges);++ const result = await routeAuth(makeRequest(), [customAuthFn]);++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe('Basic realm="x"');+ }+ });});describe("placeholderAuth", () => {diff --git a/packages/eve/src/public/channels/auth.ts b/packages/eve/src/public/channels/auth.tsindex 5da56ca4d..265f570d0 100644--- a/packages/eve/src/public/channels/auth.ts+++ b/packages/eve/src/public/channels/auth.ts@@ -58,8 +58,9 @@ export interface HttpBasicCredentials {* Verifies an HTTP Basic credential against the supplied username and* password. Returns `{ ok: true, sessionAuth }` on success or `{ ok: false }`* on a missing or mismatched credential. The password is compared with- * constant-time hash equality so a timing side channel cannot leak it; the- * username is compared directly.+ * constant-time hash equality so a timing side channel cannot leak it. Both+ * values are normalized to Unicode NFC before comparison, matching the+ * `charset="UTF-8"` challenge advertised by {@link httpBasic}.*/export function verifyHttpBasic(authorizationHeader: string | null,@@ -495,11 +496,86 @@ export type AuthFn<TEvent = Request> = (event: TEvent,) => SessionAuthContext | null | undefined | Promise<SessionAuthContext | null | undefined>;+/**+ * Symbol-keyed property carrying the `www-authenticate` challenges an+ * {@link AuthFn} would satisfy, attached via {@link withAuthChallenges}.+ * Reading it back off the function (rather than widening `AuthFn`'s call+ * signature) lets {@link routeAuth} discover the right challenge scheme(s)+ * for a 401 without every strategy needing to change shape.+ */+const AUTH_CHALLENGES_SYMBOL = Symbol.for("eve.channels.auth.challenges");++/**+ * Attaches declared `www-authenticate` challenges to an {@link AuthFn}+ * without changing its call signature or behavior. {@link routeAuth} reads+ * the declared challenges back when every entry in the walk skips, so the+ * resulting 401 advertises the scheme(s) the configured strategies actually+ * accept (e.g. `Basic` for {@link httpBasic}) instead of a fixed default.+ *+ * Built-in strategies (`httpBasic`, `jwtHmac`, `jwtEcdsa`, `oidc`,+ * `vercelOidc`) already declare their challenge. Use this directly when+ * authoring a custom `AuthFn`:+ *+ * ```ts+ * const apiKey = withAuthChallenges(+ * (request) => (isValidApiKey(request) ? sessionAuth : null),+ * [{ scheme: "Bearer" }],+ * );+ * ```+ */+export function withAuthChallenges<TEvent>(+ fn: AuthFn<TEvent>,+ challenges: readonly UnauthorizedChallenge[],+): AuthFn<TEvent> {+ const wrapped: AuthFn<TEvent> = (event) => fn(event);+ Object.defineProperty(wrapped, AUTH_CHALLENGES_SYMBOL, {+ value: challenges,+ });+ return wrapped;+}++/**+ * Reads the challenges {@link withAuthChallenges} attached to `fn`, or+ * `undefined` when `fn` declared none (e.g. {@link none}, {@link localDev},+ * {@link placeholderAuth}, or a custom `AuthFn` that never opted in).+ */+function getDeclaredChallenges<TEvent>(+ fn: AuthFn<TEvent>,+): readonly UnauthorizedChallenge[] | undefined {+ return (fn as Partial<Record<typeof AUTH_CHALLENGES_SYMBOL, readonly UnauthorizedChallenge[]>>)[+ AUTH_CHALLENGES_SYMBOL+ ];+}++/**+ * Collects the deduped, ordered set of challenges declared across `list` via+ * {@link withAuthChallenges}. Dedupes by the rendered `www-authenticate`+ * string so e.g. two `jwtHmac()` entries only contribute one `Bearer`.+ */+function collectDeclaredChallenges(+ list: readonly AuthFn<Request>[],+): readonly UnauthorizedChallenge[] {+ const seenRendered = new Set<string>();+ const challenges: UnauthorizedChallenge[] = [];+ for (const fn of list) {+ for (const challenge of getDeclaredChallenges(fn) ?? []) {+ const rendered = formatChallenge(challenge);+ if (seenRendered.has(rendered)) continue;+ seenRendered.add(rendered);+ challenges.push(challenge);+ }+ }+ return challenges;+}+/*** Walks an `AuthFn` (or array) in order against `request`. The first entry* returning a {@link SessionAuthContext} wins; entries returning `null` or* `undefined` are skipped. If the walk exhausts without a winner (including- * the empty-array case), returns a 401 {@link createUnauthorizedResponse}.+ * the empty-array case), returns a 401 {@link createUnauthorizedResponse}+ * whose `www-authenticate` challenges are collected from the entries'+ * declared schemes (see {@link withAuthChallenges}), falling back to+ * `Bearer` when none declared any.** Channel factories that share this resolution policy (e.g. `eveChannel`, or* a custom `defineChannel` route handler) should call `routeAuth` rather than@@ -530,7 +606,10 @@ export async function routeAuth(throw error;}- return createUnauthorizedResponse({ challenges: [{ scheme: "Bearer" }] });+ const declaredChallenges = collectDeclaredChallenges(list);+ return createUnauthorizedResponse({+ challenges: declaredChallenges.length > 0 ? declaredChallenges : [{ scheme: "Bearer" }],+ });}/**@@ -912,22 +991,26 @@ function assertVercelSubjectSegment(field: "teamSlug" | "projectName", value: st/*** Returns an HTTP route auth callback backed by Vercel OIDC. See* {@link verifyVercelOidc} for the always-on current-project bypass and how- * `subjects` extends acceptance to other Vercel projects.+ * `subjects` extends acceptance to other Vercel projects. Declares a+ * `Bearer` {@link withAuthChallenges} challenge for {@link routeAuth}'s 401.*/export function vercelOidc(opts: VerifyVercelOidcOptions = {}): AuthFn<Request> {- return async (request) => {- const token = extractBearerToken(request.headers.get("authorization"));- const currentVercelProject =- opts.currentVercelProject ??- (token !== null && isLocalDevelopmentVercelOidcRequest(request)- ? await resolveVercelOidcCurrentProject(request)- : undefined);- const result = await verifyVercelOidc(- token,- currentVercelProject === undefined ? opts : { ...opts, currentVercelProject },- );- return result.ok ? result.sessionAuth : null;- };+ return withAuthChallenges(+ async (request) => {+ const token = extractBearerToken(request.headers.get("authorization"));+ const currentVercelProject =+ opts.currentVercelProject ??+ (token !== null && isLocalDevelopmentVercelOidcRequest(request)+ ? await resolveVercelOidcCurrentProject(request)+ : undefined);+ const result = await verifyVercelOidc(+ token,+ currentVercelProject === undefined ? opts : { ...opts, currentVercelProject },+ );+ return result.ok ? result.sessionAuth : null;+ },+ [{ scheme: "Bearer" }],+ );}function isLocalDevelopmentVercelOidcRequest(request: Request): boolean {@@ -938,44 +1021,95 @@ function isLocalDevelopmentVercelOidcRequest(request: Request): boolean {return isLoopbackRequest(request);}-/** Returns an {@link AuthFn} that verifies HTTP Basic credentials via {@link verifyHttpBasic}. */-export function httpBasic(credentials: HttpBasicCredentials): AuthFn<Request> {- return (request) => {- const result = verifyHttpBasic(request.headers.get("authorization"), credentials);- return result.ok ? result.sessionAuth : null;+/**+ * Options accepted by {@link httpBasic}.+ */+export interface HttpBasicAuthOptions {+ /**+ * Optional `realm` parameter advertised on the `WWW-Authenticate: Basic`+ * challenge (e.g. browsers show it in the native login prompt). Defaults+ * to `"eve"`.+ */+ readonly realm?: string;+}++/**+ * Returns an {@link AuthFn} that verifies HTTP Basic credentials via+ * {@link verifyHttpBasic}. Declares a `Basic` {@link withAuthChallenges}+ * challenge so a {@link routeAuth} 401 advertises `WWW-Authenticate: Basic`+ * (with `realm` first, when given, then `charset="UTF-8"`) instead of the+ * `Bearer` fallback.+ */+export function httpBasic(+ credentials: HttpBasicCredentials,+ options?: HttpBasicAuthOptions,+): AuthFn<Request> {+ const parameters: Record<string, string> = {+ realm: options?.realm ?? "eve",+ charset: "UTF-8",};+ return withAuthChallenges(+ (request) => {+ const result = verifyHttpBasic(request.headers.get("authorization"), credentials);+ return result.ok ? result.sessionAuth : null;+ },+ [+ {+ parameters,+ scheme: "Basic",+ },+ ],+ );}-/** Returns an {@link AuthFn} that verifies an HMAC-signed bearer JWT via {@link verifyJwtHmac}. */+/**+ * Returns an {@link AuthFn} that verifies an HMAC-signed bearer JWT via+ * {@link verifyJwtHmac}. Declares a `Bearer` {@link withAuthChallenges}+ * challenge for {@link routeAuth}'s 401.+ */export function jwtHmac(config: VerifyJwtHmacConfig): AuthFn<Request> {- return async (request) => {- const token = extractBearerToken(request.headers.get("authorization"));- const result = await verifyJwtHmac(token, config);- return result.ok ? result.sessionAuth : null;- };+ return withAuthChallenges(+ async (request) => {+ const token = extractBearerToken(request.headers.get("authorization"));+ const result = await verifyJwtHmac(token, config);+ return result.ok ? result.sessionAuth : null;+ },+ [{ scheme: "Bearer" }],+ );}-/** Returns an {@link AuthFn} that verifies an ECDSA-signed bearer JWT via {@link verifyJwtEcdsa}. */+/**+ * Returns an {@link AuthFn} that verifies an ECDSA-signed bearer JWT via+ * {@link verifyJwtEcdsa}. Declares a `Bearer` {@link withAuthChallenges}+ * challenge for {@link routeAuth}'s 401.+ */export function jwtEcdsa(config: VerifyJwtEcdsaConfig): AuthFn<Request> {- return async (request) => {- const token = extractBearerToken(request.headers.get("authorization"));- const result = await verifyJwtEcdsa(token, config);- return result.ok ? result.sessionAuth : null;- };+ return withAuthChallenges(+ async (request) => {+ const token = extractBearerToken(request.headers.get("authorization"));+ const result = await verifyJwtEcdsa(token, config);+ return result.ok ? result.sessionAuth : null;+ },+ [{ scheme: "Bearer" }],+ );}/*** Returns an {@link AuthFn} that verifies an OIDC bearer token on the inbound* request via {@link verifyOidc}. Use {@link vercelOidc} instead for* Vercel-issued tokens: it preconfigures the issuer, audience, and runtime- * principal flag.+ * principal flag. Declares a `Bearer` {@link withAuthChallenges} challenge+ * for {@link routeAuth}'s 401.*/export function oidc(config: VerifyOidcConfig): AuthFn<Request> {- return async (request) => {- const token = extractBearerToken(request.headers.get("authorization"));- const result = await verifyOidc(token, config);- return result.ok ? result.sessionAuth : null;- };+ return withAuthChallenges(+ async (request) => {+ const token = extractBearerToken(request.headers.get("authorization"));+ const result = await verifyOidc(token, config);+ return result.ok ? result.sessionAuth : null;+ },+ [{ scheme: "Bearer" }],+ );}// ---------------------------------------------------------------------------diff --git a/packages/eve/src/runtime/governance/auth/http-basic.ts b/packages/eve/src/runtime/governance/auth/http-basic.tsindex 2d805dd7e..d6cd2dce3 100644--- a/packages/eve/src/runtime/governance/auth/http-basic.ts+++ b/packages/eve/src/runtime/governance/auth/http-basic.ts@@ -20,13 +20,18 @@ export function authenticateHttpBasicStrategy(input: {};}- if (credentials.username !== input.strategy.username) {+ if (normalizeCredential(credentials.username) !== normalizeCredential(input.strategy.username)) {return {kind: "not-authenticated",};}- if (!timingSafeStringEquals(credentials.password, input.strategy.password)) {+ if (+ !timingSafeStringEquals(+ normalizeCredential(credentials.password),+ normalizeCredential(input.strategy.password),+ )+ ) {return {kind: "not-authenticated",};@@ -80,6 +85,10 @@ function parseBasicAuthorizationHeader(value: string): {};}+function normalizeCredential(value: string): string {+ return value.normalize("NFC");+}+function timingSafeStringEquals(left: string, right: string): boolean {return timingSafeEqual(hashString(left), hashString(right));}