Skip to content

Commit c17c4ee

Browse files
fix(server): unauthenticated token requests no longer write DPoP replay markers
`POST /oauth/token` recorded every valid-looking DPoP proof in the secret store before it looked at the subject token. Anyone who could reach the server could create a marker file per request, kept for a day. The proof is now checked first without being recorded, and recorded only once the subject credential is accepted, still before a session is issued. Replays are still rejected with a DPoP challenge. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 1721f18 commit c17c4ee

4 files changed

Lines changed: 157 additions & 44 deletions

File tree

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,11 @@ export class EnvironmentAuth extends Context.Service<
477477
requestMetadata: AuthClientMetadata,
478478
input?: {
479479
readonly proofKeyThumbprint?: string;
480+
/** Records the DPoP proof, run only after the credential is accepted. */
481+
readonly consumeProof?: Effect.Effect<
482+
void,
483+
ServerAuthInvalidCredentialError | ServerAuthInternalError
484+
>;
480485
},
481486
) => Effect.Effect<
482487
AuthAccessTokenResult,
@@ -963,11 +968,12 @@ export const make = Effect.gen(function* () {
963968
const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
964969
(credential, requestedScopes, requestMetadata, input) => {
965970
return resolveBootstrapGrant(credential, {
966-
...input,
971+
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
967972
...(requestedScopes !== undefined ? { requestedScopes } : {}),
968973
}).pipe(
969974
Effect.flatMap((grant) =>
970975
Effect.gen(function* () {
976+
if (input?.consumeProof) yield* input.consumeProof;
971977
const grantedScopes =
972978
requestedScopes === undefined
973979
? grant.scopes

‎apps/server/src/auth/dpop.ts‎

Lines changed: 55 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,12 @@ export const mapDpopReplayStoreError = (
5353
cause: error,
5454
});
5555

56-
export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: {
56+
/**
57+
* Checks a proof without recording it. `consume` records the proof's jti so it cannot be
58+
* replayed; run it only once the request is otherwise known to be valid, so that requests
59+
* anyone can send do not write replay state.
60+
*/
61+
export const checkRequestDpopProof = Effect.fn("dpop.checkRequestDpopProof")(function* (input: {
5762
readonly request: HttpServerRequest.HttpServerRequest;
5863
/** Overrides the `DPoP` header for requests that cannot carry one, such as a WebSocket upgrade. */
5964
readonly proof?: string;
@@ -86,42 +91,53 @@ export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(f
8691
});
8792
}
8893
const secretStore = yield* ServerSecretStore.ServerSecretStore;
89-
const replayKey = yield* Digest.Digest.pipe(
90-
Effect.flatMap((digest) =>
91-
digest.digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
92-
),
93-
Effect.map(Base64Url.encode),
94-
Effect.mapError(
95-
(cause) =>
96-
new ServerAuthDpopReplayKeyCalculationError({
97-
cause,
98-
}),
99-
),
100-
);
101-
yield* secretStore
102-
.create(
103-
`${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
104-
new TextEncoder().encode(
105-
[
106-
`thumbprint=${result.thumbprint}`,
107-
`jti=${result.jti}`,
108-
`iat=${result.iat}`,
109-
`consumedAt=${DateTime.formatIso(now)}`,
110-
].join("\n"),
111-
),
112-
)
113-
.pipe(
114-
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
115-
Effect.gen(function* () {
116-
const mapped = mapDpopReplayStoreError(error);
117-
if (mapped._tag === "ServerAuthInvalidCredentialError") {
118-
yield* Effect.annotateCurrentSpan({
119-
"environment.dpop.failure_code": mapped.dpopFailureReason,
120-
});
121-
}
122-
return yield* mapped;
123-
}),
124-
),
125-
);
126-
return result.thumbprint;
94+
const digest = yield* Digest.Digest;
95+
const consume: Effect.Effect<void, ServerAuthInvalidCredentialError | ServerAuthInternalError> =
96+
Effect.gen(function* () {
97+
const replayKey = yield* digest
98+
.digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`))
99+
.pipe(
100+
Effect.map(Base64Url.encode),
101+
Effect.mapError(
102+
(cause) =>
103+
new ServerAuthDpopReplayKeyCalculationError({
104+
cause,
105+
}),
106+
),
107+
);
108+
yield* secretStore
109+
.create(
110+
`${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
111+
new TextEncoder().encode(
112+
[
113+
`thumbprint=${result.thumbprint}`,
114+
`jti=${result.jti}`,
115+
`iat=${result.iat}`,
116+
`consumedAt=${DateTime.formatIso(now)}`,
117+
].join("\n"),
118+
),
119+
)
120+
.pipe(
121+
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
122+
Effect.gen(function* () {
123+
const mapped = mapDpopReplayStoreError(error);
124+
if (mapped._tag === "ServerAuthInvalidCredentialError") {
125+
yield* Effect.annotateCurrentSpan({
126+
"environment.dpop.failure_code": mapped.dpopFailureReason,
127+
});
128+
}
129+
return yield* mapped;
130+
}),
131+
),
132+
);
133+
});
134+
return { thumbprint: result.thumbprint, consume };
135+
});
136+
137+
export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (
138+
input: Parameters<typeof checkRequestDpopProof>[0],
139+
) {
140+
const proof = yield* checkRequestDpopProof(input);
141+
yield* proof.consume;
142+
return proof.thumbprint;
127143
});

‎apps/server/src/auth/http.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ import {
88
} from "@t3tools/contracts";
99
import { expect, it } from "@effect/vitest";
1010
import * as Context from "effect/Context";
11+
import * as DateTime from "effect/DateTime";
1112
import * as SecureRandom from "effect/crypto/SecureRandom";
1213
import * as Effect from "effect/Effect";
1314
import * as Layer from "effect/Layer";
15+
import * as PlatformError from "effect/PlatformError";
1416
import * as Redacted from "effect/Redacted";
1517
import * as Schema from "effect/Schema";
1618
import * as Etag from "effect/http/Etag";
@@ -23,6 +25,7 @@ import * as ServerConfig from "../config.ts";
2325
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
2426
import * as SqlitePersistence from "../persistence/Sqlite.ts";
2527
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
28+
import { makeDpopKey } from "./dpop.testkit.ts";
2629
import * as ServerSecretStore from "./ServerSecretStore.ts";
2730
import * as AuthHttp from "./http.ts";
2831
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
@@ -191,3 +194,78 @@ it.effect.each(["DPoP", "dpop"])("challenges a refused %s request with DPoP", (s
191194
);
192195
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
193196
);
197+
198+
// The web handler runs on its own runtime, so proofs need wall-clock time.
199+
it.live("records a token-endpoint DPoP proof only once the subject token is accepted", () =>
200+
Effect.gen(function* () {
201+
const random = yield* SecureRandom.SecureRandom;
202+
const written = new Set<string>();
203+
const recordingSecretStore = ServerSecretStore.ServerSecretStore.of({
204+
get: () => Effect.succeedNone,
205+
set: () => Effect.void,
206+
create: (name) =>
207+
written.has(name)
208+
? Effect.fail(
209+
new ServerSecretStore.SecretStorePersistError({
210+
resource: name,
211+
cause: PlatformError.systemError({
212+
_tag: "AlreadyExists",
213+
module: "FileSystem",
214+
method: "open",
215+
pathOrDescriptor: name,
216+
}),
217+
}),
218+
)
219+
: Effect.sync(() => void written.add(name)),
220+
getOrCreateRandom: () => Effect.die("Not used by these routes."),
221+
remove: () => Effect.void,
222+
});
223+
const requestContext = Context.make(SecureRandom.SecureRandom, random).pipe(
224+
Context.add(ServerSecretStore.ServerSecretStore, recordingSecretStore),
225+
);
226+
const url = "http://127.0.0.1/oauth/token";
227+
const key = makeDpopKey();
228+
const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000);
229+
const tokenRequest = (subjectToken: string, proof: string) =>
230+
new Request(url, {
231+
method: "POST",
232+
headers: { host: "127.0.0.1", dpop: proof },
233+
body: new URLSearchParams({
234+
grant_type: AuthTokenExchangeGrantType,
235+
subject_token: subjectToken,
236+
subject_token_type: AuthEnvironmentBootstrapTokenType,
237+
requested_token_type: AuthAccessTokenType,
238+
}),
239+
});
240+
return yield* Effect.acquireUseRelease(
241+
Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
242+
(environment) =>
243+
Effect.promise(async () => {
244+
const unknownToken = await environment.handler(
245+
tokenRequest("not-a-pairing-token", key.sign({ method: "POST", url, token: "", iat })),
246+
requestContext,
247+
);
248+
expect(unknownToken.status).toBe(401);
249+
expect(await unknownToken.json()).not.toHaveProperty("dpopFailureReason");
250+
expect(written.size).toBe(0);
251+
252+
const proof = key.sign({ method: "POST", url, token: "", iat });
253+
const accepted = await environment.handler(
254+
tokenRequest(DEV_TOKEN, proof),
255+
requestContext,
256+
);
257+
expect(accepted.status).toBe(200);
258+
expect(written.size).toBe(1);
259+
260+
const replayed = await environment.handler(
261+
tokenRequest(DEV_TOKEN, proof),
262+
requestContext,
263+
);
264+
expect(replayed.status).toBe(401);
265+
expect(replayed.headers.get("www-authenticate")).toBe("DPoP");
266+
expect(await replayed.json()).toMatchObject({ dpopFailureReason: "replay" });
267+
}),
268+
(environment) => Effect.promise(() => environment.dispose()),
269+
);
270+
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
271+
);

‎apps/server/src/auth/http.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import * as EnvironmentAuth from "./EnvironmentAuth.ts";
3636
import * as SessionStore from "./SessionStore.ts";
3737
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts";
3838
import { deriveAuthClientMetadata } from "./utils.ts";
39-
import { verifyRequestDpopProof } from "./dpop.ts";
39+
import { checkRequestDpopProof } from "./dpop.ts";
4040
import { requestUrl } from "../requestUrl.ts";
4141

4242
const CREDENTIAL_RESPONSE_HEADERS = {
@@ -364,8 +364,9 @@ export const layer = HttpApiBuilder.group(
364364
if (requestedScopes === null || requestedScopes?.length === 0) {
365365
return yield* failEnvironmentInvalidRequest("invalid_scope");
366366
}
367-
const proofKeyThumbprint = args.headers.dpop
368-
? yield* verifyRequestDpopProof({ request }).pipe(
367+
// Anyone can send a proof here, so it is recorded only once the subject token checks out.
368+
const proof = args.headers.dpop
369+
? yield* checkRequestDpopProof({ request }).pipe(
369370
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
370371
appendDpopChallengeHeader.pipe(
371372
Effect.andThen(
@@ -395,7 +396,19 @@ export const layer = HttpApiBuilder.group(
395396
...(args.payload.client_os ? { os: args.payload.client_os } : {}),
396397
},
397398
}),
398-
proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
399+
proof
400+
? {
401+
proofKeyThumbprint: proof.thumbprint,
402+
consumeProof: proof.consume.pipe(
403+
Effect.tapError((error) =>
404+
EnvironmentAuth.isServerAuthCredentialError(error)
405+
? appendDpopChallengeHeader
406+
: Effect.void,
407+
),
408+
Effect.provideService(HttpServerRequest.HttpServerRequest, request),
409+
),
410+
}
411+
: undefined,
399412
);
400413
},
401414
traceRelayRequest,

0 commit comments

Comments
 (0)