Public: anyone can read this; the crew can change it.
Auth scheme `bearer` in any letter case resolves the caller, and the 401 challenge tells the truth #14998
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14988-auth-scheme-bearer-in-any-letter-case-re → main 2 commits fork
3 files
changed +114
−6
src/http/oauth.ts +4 −1
| @@ -25,6 +25,7 @@ import { clientBucket } from "./peer.ts"; | ||
| 25 | 25 | import { readBounded } from "./limits.ts"; |
| 26 | 26 | import { boundedBody, json, retryAfterOf, tryAgain } from "./respond.ts"; |
| 27 | 27 | import type { Router } from "./router.ts"; |
| 28 | import { bearerSecret } from "./token_header.ts"; | |
| 28 | 29 | import { authorizePage, authorizeSubmit } from "../web/pages/oauth.ts"; |
| 29 | 30 | |
| 30 | 31 | /** Registrations per address per minute. */ |
| @@ -65,7 +66,9 @@ export const resourceMetadataUrl = (origin: string): string => | ||
| 65 | 66 | * was sent and refused, so "sign in" and "re-authorize" are told apart. |
| 66 | 67 | */ |
| 67 | 68 | export const bearerChallenge = (origin: string, request?: Request): string => { |
| 68 | const sent = /^Bearer\s+\S/i.test(request?.headers.get("authorization") ?? ""); | |
| 69 | // Exactly the header the caller resolution reads as a bearer: a challenge | |
| 70 | // never says `invalid_token` about a header that was never tried (#14988). | |
| 71 | const sent = bearerSecret(request?.headers.get("authorization") ?? "") !== null; | |
| 69 | 72 | return ( |
| 70 | 73 | `Bearer realm="forge", resource_metadata="${resourceMetadataUrl(origin)}", scope="${OAUTH_SCOPES.join(" ")}"` + |
| 71 | 74 | (sent ? `, error="invalid_token"` : "") |
src/http/token_header.ts +20 −5
| @@ -3,21 +3,36 @@ | ||
| 3 | 3 | * and `token <secret>`, the scheme a Gitea client sends. Nothing else is a |
| 4 | 4 | * token header, and a header with the scheme but no secret is not one either, |
| 5 | 5 | * so a malformed header never reaches `verifyToken` with a guessed slice. |
| 6 | * | |
| 7 | * A scheme is matched in any letter case (RFC 9110 §11.1): `bearer x` is the | |
| 8 | * same header as `Bearer x`, so it resolves the same caller (#14988). | |
| 6 | 9 | */ |
| 7 | 10 | |
| 8 | const SCHEMES = ["Bearer ", "token "] as const; | |
| 11 | const SCHEMES = ["bearer ", "token "] as const; | |
| 12 | type Scheme = (typeof SCHEMES)[number]; | |
| 13 | ||
| 14 | const hasScheme = (header: string, scheme: Scheme): boolean => | |
| 15 | header.slice(0, scheme.length).toLowerCase() === scheme; | |
| 16 | ||
| 17 | function secretAfter(header: string, scheme: Scheme): string | null { | |
| 18 | if (!hasScheme(header, scheme)) return null; | |
| 19 | const secret = header.slice(scheme.length).trim(); | |
| 20 | return secret === "" ? null : secret; | |
| 21 | } | |
| 9 | 22 | |
| 10 | 23 | /** The secret, or `null` when the header is not a token header or holds none. */ |
| 11 | 24 | export function tokenSecret(header: string): string | null { |
| 12 | 25 | for (const scheme of SCHEMES) { |
| 13 | if (!header.startsWith(scheme)) continue; | |
| 14 | const secret = header.slice(scheme.length).trim(); | |
| 15 | return secret === "" ? null : secret; | |
| 26 | if (hasScheme(header, scheme)) return secretAfter(header, scheme); | |
| 16 | 27 | } |
| 17 | 28 | return null; |
| 18 | 29 | } |
| 19 | 30 | |
| 31 | /** The secret of a `Bearer` header alone, or `null`. */ | |
| 32 | export const bearerSecret = (header: string): string | null => | |
| 33 | secretAfter(header, "bearer "); | |
| 34 | ||
| 20 | 35 | /** Whether the header names a token scheme at all, empty secret or not. */ |
| 21 | 36 | export function isTokenScheme(header: string): boolean { |
| 22 | return SCHEMES.some((scheme) => header.startsWith(scheme)); | |
| 37 | return SCHEMES.some((scheme) => hasScheme(header, scheme)); | |
| 23 | 38 | } |
test/bearer-scheme-case.test.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { createToken } from "../src/core/tokens.ts"; | |
| 7 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 8 | import { bearerChallenge } from "../src/http/oauth.ts"; | |
| 9 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 10 | import { bearerSecret, isTokenScheme, tokenSecret } from "../src/http/token_header.ts"; | |
| 11 | import { quietLogs } from "./helpers/globals.ts"; | |
| 12 | ||
| 13 | /** | |
| 14 | * An auth scheme is case-insensitive (RFC 9110 §11.1), so `bearer x` is the | |
| 15 | * caller `Bearer x` is; and the 401 challenge says `invalid_token` exactly | |
| 16 | * when a bearer was tried and refused, never about one that was not (#14988). | |
| 17 | */ | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | const withAuth = (authorization: string) => | |
| 22 | new Request("http://forge.test/api/v1/user", { headers: { authorization } }); | |
| 23 | ||
| 24 | test("the scheme is read in any letter case", () => { | |
| 25 | for (const scheme of ["Bearer", "bearer", "BEARER", "bEaReR"]) { | |
| 26 | expect(tokenSecret(`${scheme} abc`)).toBe("abc"); | |
| 27 | expect(bearerSecret(`${scheme} abc`)).toBe("abc"); | |
| 28 | expect(isTokenScheme(`${scheme} `)).toBe(true); | |
| 29 | } | |
| 30 | expect(tokenSecret("TOKEN abc")).toBe("abc"); | |
| 31 | expect(bearerSecret("token abc")).toBeNull(); | |
| 32 | expect(bearerSecret("bearer ")).toBeNull(); | |
| 33 | expect(tokenSecret("bearerabc")).toBeNull(); | |
| 34 | expect(tokenSecret("Basic abc")).toBeNull(); | |
| 35 | }); | |
| 36 | ||
| 37 | test("the challenge says invalid_token only about a bearer that was tried", () => { | |
| 38 | const origin = "http://forge.test"; | |
| 39 | expect(bearerChallenge(origin, withAuth("bearer nope"))).toContain('error="invalid_token"'); | |
| 40 | expect(bearerChallenge(origin, withAuth("Bearer nope"))).toContain('error="invalid_token"'); | |
| 41 | // Not a header the caller resolution reads: nothing was tried. | |
| 42 | expect(bearerChallenge(origin, withAuth("Bearer\tnope"))).not.toContain("invalid_token"); | |
| 43 | expect(bearerChallenge(origin, withAuth("Bearer "))).not.toContain("invalid_token"); | |
| 44 | expect(bearerChallenge(origin)).not.toContain("invalid_token"); | |
| 45 | }); | |
| 46 | ||
| 47 | describe("a bearer in any letter case resolves the caller", () => { | |
| 48 | let dir = ""; | |
| 49 | let app: App; | |
| 50 | let servers: Servers; | |
| 51 | let token = ""; | |
| 52 | ||
| 53 | beforeAll(async () => { | |
| 54 | dir = await mkdtemp(join(tmpdir(), "forge-bearer-case-")); | |
| 55 | app = createApp({ dataDir: dir, port: 0 }); | |
| 56 | servers = await serve(app); | |
| 57 | const made = await createUser(app.db, { | |
| 58 | origin: "seed", | |
| 59 | trusted: true, | |
| 60 | username: "alice", | |
| 61 | email: "[email protected]", | |
| 62 | password: "a-good-passphrase", | |
| 63 | }); | |
| 64 | if (!made.ok) throw new Error(made.error); | |
| 65 | token = createToken(app.db, getUserByName(app.db, "alice")!.id, "t", "ro").token; | |
| 66 | }); | |
| 67 | ||
| 68 | afterAll(async () => { | |
| 69 | servers.stop(); | |
| 70 | app.close(); | |
| 71 | await rm(dir, { recursive: true, force: true, maxRetries: 5 }); | |
| 72 | }); | |
| 73 | ||
| 74 | const get = (authorization: string) => | |
| 75 | fetch(`${servers.url}/api/v1/user`, { headers: { authorization } }); | |
| 76 | ||
| 77 | test("bearer, BEARER and Bearer are the same account", async () => { | |
| 78 | for (const scheme of ["Bearer", "bearer", "BEARER"]) { | |
| 79 | const r = await get(`${scheme} ${token}`); | |
| 80 | expect(r.status).toBe(200); | |
| 81 | expect(((await r.json()) as { username: string }).username).toBe("alice"); | |
| 82 | } | |
| 83 | }); | |
| 84 | ||
| 85 | test("a refused lowercase bearer is told invalid_token", async () => { | |
| 86 | const r = await get("bearer forge_not-a-real-token"); | |
| 87 | expect(r.status).toBe(401); | |
| 88 | expect(r.headers.get("www-authenticate") ?? "").toContain('error="invalid_token"'); | |
| 89 | }); | |
| 90 | }); |
new above
offline