Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

500 lines19.0 KB

1import {
2 AuthAccessReadScope,
3 AuthAccessWriteScope,
4 AuthStandardClientScopes,
5 AuthOrchestrationOperateScope,
6 AuthOrchestrationReadScope,
7 AuthRelayReadScope,
8 AuthRelayWriteScope,
9 AuthReviewWriteScope,
10 AuthTerminalOperateScope,
11 EnvironmentAuthInvalidError,
12 type EnvironmentAuthInvalidReason,
13 EnvironmentHttpApi,
14 EnvironmentInternalError,
15 type EnvironmentInternalErrorReason,
16 EnvironmentOperationForbiddenError,
17 EnvironmentRequestInvalidError,
18 type EnvironmentRequestInvalidReason,
19 EnvironmentResourceNotFoundError,
20 type EnvironmentResourceNotFoundReason,
21 EnvironmentScopeRequiredError,
22 EnvironmentAuthenticatedAuth,
23 EnvironmentAuthenticatedPrincipal,
24} from "@t3tools/contracts";
25import type { AuthEnvironmentScope, DpopFailureReason } from "@t3tools/contracts";
26import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
27import { causeErrorTag } from "@t3tools/shared/observability";
28import * as DateTime from "effect/DateTime";
29import * as Effect from "effect/Effect";
30import { identity } from "effect/Function";
31import * as Layer from "effect/Layer";
32import * as Cookies from "effect/unstable/http/Cookies";
33import * as HttpEffect from "effect/unstable/http/HttpEffect";
34import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
35import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
36​
37import * as EnvironmentAuth from "./EnvironmentAuth.ts";
38import * as SessionStore from "./SessionStore.ts";
39import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts";
40import { deriveAuthClientMetadata } from "./utils.ts";
41import { verifyRequestDpopProof } from "./dpop.ts";
42​
43const CREDENTIAL_RESPONSE_HEADERS = {
44 "cache-control": "no-store",
45 pragma: "no-cache",
46} as const;
47​
48const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>
49 Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),
50);
51​
52const appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>
53 Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")),
54);
55​
56const appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) =>
57 Effect.gen(function* () {
58 const request = yield* HttpServerRequest.HttpServerRequest;
59 const usesDpop =
60 (request.originalUrl.startsWith("/oauth/token") && request.headers.dpop !== undefined) ||
61 request.headers.authorization?.startsWith("DPoP ") === true;
62 if (usesDpop) {
63 yield* appendDpopChallengeHeader;
64 }
65 return yield* error;
66 });
67​
68const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(
69 Effect.map((span) => span.traceId),
70 Effect.orElseSucceed(() => "unavailable"),
71);
72​
73export function annotateEnvironmentRequest(endpoint: string) {
74 return Effect.gen(function* () {
75 const request = yield* HttpServerRequest.HttpServerRequest;
76 const url = HttpServerRequest.toURL(request);
77 const traceId = yield* currentEnvironmentTraceId;
78​
79 yield* Effect.addFinalizer((exit) =>
80 exit._tag === "Failure"
81 ? Effect.logWarning("environment api request failed", {
82 endpoint,
83 traceId,
84 errorTag: causeErrorTag(exit.cause),
85 cause: exit.cause,
86 })
87 : Effect.void,
88 );
89 yield* Effect.annotateLogsScoped({ "environment.endpoint": endpoint, traceId });
90 yield* Effect.annotateCurrentSpan({
91 "environment.endpoint": endpoint,
92 "http.request.method": request.method,
93 "url.path": url._tag === "Some" ? url.value.pathname : "unknown",
94 });
95 });
97​
98export function failEnvironmentAuthInvalid(
99 reason: EnvironmentAuthInvalidReason,
100 dpopFailureReason?: DpopFailureReason,
101) {
102 return currentEnvironmentTraceId.pipe(
103 Effect.flatMap((traceId) =>
104 Effect.fail(
105 new EnvironmentAuthInvalidError({
106 code: "auth_invalid",
107 reason,
108 ...(dpopFailureReason === undefined ? {} : { dpopFailureReason }),
109 traceId,
110 }),
111 ),
112 ),
113 );
115​
116export function failEnvironmentInvalidRequest(reason: EnvironmentRequestInvalidReason) {
117 return currentEnvironmentTraceId.pipe(
118 Effect.flatMap((traceId) =>
119 Effect.fail(new EnvironmentRequestInvalidError({ code: "invalid_request", reason, traceId })),
120 ),
121 );
123​
124export function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope) {
125 return currentEnvironmentTraceId.pipe(
126 Effect.flatMap((traceId) =>
127 Effect.fail(
128 new EnvironmentScopeRequiredError({
129 code: "insufficient_scope",
130 requiredScope,
131 traceId,
132 }),
133 ),
134 ),
135 );
137​
138function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_allowed") {
139 return currentEnvironmentTraceId.pipe(
140 Effect.flatMap((traceId) =>
141 Effect.fail(
142 new EnvironmentOperationForbiddenError({
143 code: "operation_forbidden",
144 reason,
145 traceId,
146 }),
147 ),
148 ),
149 );
151​
152export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) {
153 return currentEnvironmentTraceId.pipe(
154 Effect.flatMap((traceId) =>
155 Effect.fail(new EnvironmentResourceNotFoundError({ code: "not_found", reason, traceId })),
156 ),
157 );
159​
160export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
161 return Effect.gen(function* () {
162 const traceId = yield* currentEnvironmentTraceId;
163 if (error !== undefined) {
164 yield* Effect.logError("environment api operation failed", {
165 reason,
166 traceId,
167 cause: error,
168 });
169 }
170 return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
171 });
173​
174const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateTime.DateTime) =>
175 Effect.fromResult(
176 Cookies.set(Cookies.empty, cookieName, token, {
177 expires: DateTime.toDate(expiresAt),
178 httpOnly: true,
179 path: "/",
180 sameSite: "lax",
181 }),
182 ).pipe(
183 Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")),
184 Effect.flatMap((cookies) =>
185 HttpEffect.appendPreResponseHandler((_request, response) =>
186 Effect.succeed(HttpServerResponse.mergeCookies(response, cookies)),
187 ),
188 ),
189 );
190​
191export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
192 scope: AuthEnvironmentScope,
193) {
194 const session = yield* EnvironmentAuthenticatedPrincipal;
195 if (!session.scopes.has(scope)) {
196 return yield* failEnvironmentScopeRequired(scope);
197 }
198 return session;
199});
200​
201export const environmentAuthenticatedAuthLayer = Layer.effect(
202 EnvironmentAuthenticatedAuth,
203 Effect.gen(function* () {
204 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
205 return (httpEffect) =>
206 Effect.gen(function* () {
207 const request = yield* HttpServerRequest.HttpServerRequest;
208 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
209 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
210 failEnvironmentAuthInvalid(
211 EnvironmentAuth.serverAuthCredentialReason(error),
212 EnvironmentAuth.serverAuthDpopFailureReason(error),
213 ),
214 ),
215 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
216 failEnvironmentInternal("internal_error", error),
217 ),
218 );
219 return yield* httpEffect.pipe(
220 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
221 ...session,
222 scopes: new Set(session.scopes),
223 }),
224 session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
225 );
226 }).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
227 }),
228);
229​
230export const authHttpApiLayer = HttpApiBuilder.group(
231 EnvironmentHttpApi,
232 "auth",
233 Effect.fnUntraced(function* (handlers) {
234 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
235 const sessions = yield* SessionStore.SessionStore;
236​
237 return handlers
238 .handle(
239 "session",
240 Effect.fn("environment.auth.session")(
241 function* (args) {
242 yield* annotateEnvironmentRequest(args.endpoint.name);
243 const request = yield* HttpServerRequest.HttpServerRequest;
244 const result = yield* serverAuth.getSessionState(request);
245 const credential = EnvironmentAuth.selectRequestCredential(
246 request,
247 sessions.cookieName,
248 sessions.legacyCookieName,
249 );
250 if (
251 credential?.source === "legacy-cookie" &&
252 result.authenticated &&
253 result.sessionMethod === "browser-session-cookie" &&
254 result.expiresAt
255 ) {
256 yield* appendSessionCookie(sessions.cookieName, credential.token, result.expiresAt);
257 yield* appendCredentialResponseHeaders;
258 }
259 return result;
260 },
261 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
262 failEnvironmentInternal("internal_error", error),
263 ),
264 ),
265 )
266 .handle(
267 "browserSession",
268 Effect.fn("environment.auth.browserSession")(
269 function* (args) {
270 yield* annotateEnvironmentRequest(args.endpoint.name);
271 const request = yield* HttpServerRequest.HttpServerRequest;
272 const result = yield* serverAuth.createBrowserSession(
273 args.payload.credential,
274 deriveAuthClientMetadata({ request }),
275 );
276 const cookieName = result.cookieName ?? sessions.cookieName;
277 const selectedCookie = yield* Effect.fromResult(
278 Cookies.set(Cookies.empty, cookieName, result.sessionToken, {
279 expires: DateTime.toDate(result.response.expiresAt),
280 httpOnly: true,
281 path: "/",
282 sameSite: "lax",
283 }),
284 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
285 const sessionCookies = result.expireNormalCookie
286 ? yield* Effect.fromResult(
287 Cookies.expireCookie(selectedCookie, sessions.cookieName, {
288 httpOnly: true,
289 path: "/",
290 sameSite: "lax",
291 }),
292 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")))
293 : selectedCookie;
294​
295 yield* HttpEffect.appendPreResponseHandler((_request, response) =>
296 Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
297 );
298 yield* appendCredentialResponseHeaders;
299 return result.response;
300 },
301 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
302 failEnvironmentAuthInvalid(
303 EnvironmentAuth.serverAuthCredentialReason(error),
304 EnvironmentAuth.serverAuthDpopFailureReason(error),
305 ),
306 ),
307 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
308 failEnvironmentInternal("browser_session_issuance_failed", error),
309 ),
310 ),
311 )
312 .handle(
313 "token",
314 Effect.fn("environment.auth.token")(
315 function* (args) {
316 yield* annotateEnvironmentRequest(args.endpoint.name);
317 const request = yield* HttpServerRequest.HttpServerRequest;
318 const requestedScopes =
319 args.payload.scope === undefined
320 ? undefined
321 : parseAllowedOAuthScope({
322 value: args.payload.scope,
323 allowedScopes: new Set<AuthEnvironmentScope>([
324 AuthOrchestrationReadScope,
325 AuthOrchestrationOperateScope,
326 AuthTerminalOperateScope,
327 AuthReviewWriteScope,
328 AuthAccessReadScope,
329 AuthAccessWriteScope,
330 AuthRelayReadScope,
331 AuthRelayWriteScope,
332 ]),
333 });
334 if (requestedScopes === null) {
335 return yield* failEnvironmentInvalidRequest("invalid_scope");
336 }
337 const proofKeyThumbprint = args.headers.dpop
338 ? yield* verifyRequestDpopProof({ request }).pipe(
339 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
340 appendDpopChallengeHeader.pipe(
341 Effect.andThen(
342 failEnvironmentAuthInvalid(
343 "invalid_credential",
344 EnvironmentAuth.serverAuthDpopFailureReason(error),
345 ),
346 ),
347 ),
348 ),
349 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
350 failEnvironmentInternal("access_token_issuance_failed", error),
351 ),
352 )
353 : undefined;
354 yield* appendCredentialResponseHeaders;
355 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
356 args.payload.subject_token,
357 requestedScopes,
358 deriveAuthClientMetadata({
359 request,
360 presented: {
361 ...(args.payload.client_label ? { label: args.payload.client_label } : {}),
362 ...(args.payload.client_device_type
363 ? { deviceType: args.payload.client_device_type }
364 : {}),
365 ...(args.payload.client_os ? { os: args.payload.client_os } : {}),
366 },
367 }),
368 proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
369 );
370 },
371 traceRelayRequest,
372 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
373 failEnvironmentAuthInvalid(
374 EnvironmentAuth.serverAuthCredentialReason(error),
375 EnvironmentAuth.serverAuthDpopFailureReason(error),
376 ),
377 ),
378 Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
379 failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
380 ),
381 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
382 failEnvironmentInternal("access_token_issuance_failed", error),
383 ),
384 ),
385 )
386 .handle(
387 "webSocketTicket",
388 Effect.fn("environment.auth.webSocketTicket")(
389 function* (args) {
390 yield* annotateEnvironmentRequest(args.endpoint.name);
391 const session = yield* EnvironmentAuthenticatedPrincipal;
392 yield* appendCredentialResponseHeaders;
393 return yield* serverAuth.issueWebSocketTicket(session);
394 },
395 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
396 failEnvironmentInternal("websocket_ticket_issuance_failed", error),
397 ),
398 ),
399 )
400 .handle(
401 "pairingCredential",
402 Effect.fn("environment.auth.pairingCredential")(
403 function* (args) {
404 yield* annotateEnvironmentRequest(args.endpoint.name);
405 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
406 const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
407 if (
408 delegatedScopes.length === 0 ||
409 new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
410 ) {
411 return yield* failEnvironmentInvalidRequest("invalid_scope");
412 }
413 for (const delegatedScope of delegatedScopes) {
414 if (!session.scopes.has(delegatedScope)) {
415 return yield* failEnvironmentScopeRequired(delegatedScope);
416 }
417 }
418 return yield* serverAuth.issuePairingCredential(args.payload);
419 },
420 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
421 failEnvironmentInternal("pairing_credential_issuance_failed", error),
422 ),
423 ),
424 )
425 .handle(
426 "pairingLinks",
427 Effect.fn("environment.auth.pairingLinks")(
428 function* (args) {
429 yield* annotateEnvironmentRequest(args.endpoint.name);
430 yield* requireEnvironmentScope(AuthAccessReadScope);
431 return yield* serverAuth.listPairingLinks();
432 },
433 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
434 failEnvironmentInternal("pairing_links_load_failed", error),
435 ),
436 ),
437 )
438 .handle(
439 "revokePairingLink",
440 Effect.fn("environment.auth.revokePairingLink")(
441 function* (args) {
442 yield* annotateEnvironmentRequest(args.endpoint.name);
443 yield* requireEnvironmentScope(AuthAccessWriteScope);
444 const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
445 return { revoked };
446 },
447 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
448 failEnvironmentInternal("pairing_link_revoke_failed", error),
449 ),
450 ),
451 )
452 .handle(
453 "clients",
454 Effect.fn("environment.auth.clients")(
455 function* (args) {
456 yield* annotateEnvironmentRequest(args.endpoint.name);
457 const session = yield* requireEnvironmentScope(AuthAccessReadScope);
458 return yield* serverAuth.listClientSessions(session.sessionId);
459 },
460 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
461 failEnvironmentInternal("client_sessions_load_failed", error),
462 ),
463 ),
464 )
465 .handle(
466 "revokeClient",
467 Effect.fn("environment.auth.revokeClient")(
468 function* (args) {
469 yield* annotateEnvironmentRequest(args.endpoint.name);
470 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
471 const revoked = yield* serverAuth.revokeClientSession(
472 session.sessionId,
473 args.payload.sessionId,
474 );
475 return { revoked };
476 },
477 Effect.catchTag("ServerAuthForbiddenOperationError", () =>
478 failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
479 ),
480 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
481 failEnvironmentInternal("client_session_revoke_failed", error),
482 ),
483 ),
484 )
485 .handle(
486 "revokeOtherClients",
487 Effect.fn("environment.auth.revokeOtherClients")(
488 function* (args) {
489 yield* annotateEnvironmentRequest(args.endpoint.name);
490 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
491 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
492 return { revokedCount };
493 },
494 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
495 failEnvironmentInternal("client_session_revoke_failed", error),
496 ),
497 ),
498 );
499 }),
500);