Open History to see the last commit
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 Clock from "effect/Clock";
29import * as DateTime from "effect/DateTime";
30import * as Effect from "effect/Effect";
31import * as Layer from "effect/Layer";
32import * as Cookies from "effect/http/Cookies";
33import * as HttpEffect from "effect/http/HttpEffect";
34import { HttpServerRequest, HttpServerResponse } from "effect/http";
35import * as HttpApiBuilder from "effect/http-api/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 });
96}
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 );
114}
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 );
122}
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 );
136}
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 );
150}
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 );
158}
159
160/**
161 * `<img>` and WebSocket cannot set headers, so media routes (device hub,
162 * preview stream) authenticate the way the `/ws` upgrade does: a cookie for browser
163 * sessions, or a short-lived `wsTicket` minted over authenticated HTTP for
164 * bearer and DPoP clients. The upgrade authenticator already implements that
165 * fallback order, so it is used for plain requests as well.
166 */
167export const authenticateMediaRequest = (requiredScope: AuthEnvironmentScope) =>
168 Effect.gen(function* () {
169 const request = yield* HttpServerRequest.HttpServerRequest;
170 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
171 const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
172 Effect.catch((error) =>
173 Effect.gen(function* () {
174 if (EnvironmentAuth.isServerAuthCredentialError(error)) {
175 return yield* failEnvironmentAuthInvalid(
176 EnvironmentAuth.serverAuthCredentialReason(error),
177 EnvironmentAuth.serverAuthDpopFailureReason(error),
178 );
179 }
180 return yield* failEnvironmentInternal("internal_error", error);
181 }),
182 ),
183 );
184 if (!session.scopes.includes(requiredScope)) {
185 return yield* failEnvironmentScopeRequired(requiredScope);
186 }
187 return session;
188 });
189
190export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
191 return Effect.gen(function* () {
192 const traceId = yield* currentEnvironmentTraceId;
193 if (error !== undefined) {
194 yield* Effect.logError("environment api operation failed", {
195 reason,
196 traceId,
197 cause: error,
198 });
199 }
200 return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
201 });
202}
203
204const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateTime.DateTime) =>
205 Effect.fromResult(
206 Cookies.set(Cookies.empty, cookieName, token, {
207 expires: DateTime.toDate(expiresAt),
208 httpOnly: true,
209 path: "/",
210 sameSite: "lax",
211 }),
212 ).pipe(
213 Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")),
214 Effect.flatMap((cookies) =>
215 HttpEffect.appendPreResponseHandler((_request, response) =>
216 Effect.succeed(HttpServerResponse.mergeCookies(response, cookies)),
217 ),
218 ),
219 );
220
221export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
222 scope: AuthEnvironmentScope,
223) {
224 const session = yield* EnvironmentAuthenticatedPrincipal;
225 if (!session.scopes.has(scope)) {
226 return yield* failEnvironmentScopeRequired(scope);
227 }
228 return session;
229});
230
231export const layerAuthenticatedAuth = Layer.effect(
232 EnvironmentAuthenticatedAuth,
233 Effect.gen(function* () {
234 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
235 return (httpEffect) =>
236 Effect.gen(function* () {
237 const request = yield* HttpServerRequest.HttpServerRequest;
238 const startTime = yield* Clock.currentTimeNanos;
239 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
240 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
241 failEnvironmentAuthInvalid(
242 EnvironmentAuth.serverAuthCredentialReason(error),
243 EnvironmentAuth.serverAuthDpopFailureReason(error),
244 ),
245 ),
246 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
247 failEnvironmentInternal("internal_error", error),
248 ),
249 );
250 const endTime = yield* Clock.currentTimeNanos;
251 const handler = httpEffect.pipe(
252 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
253 ...session,
254 scopes: new Set(session.scopes),
255 }),
256 );
257 return yield* session.subject === "cloud-connect"
258 ? traceAuthenticatedRelayRequest(handler, { startTime, endTime })
259 : handler;
260 }).pipe(Effect.catchTags({ EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized }));
261 }),
262);
263
264export const layer = HttpApiBuilder.group(
265 EnvironmentHttpApi,
266 "auth",
267 Effect.fnUntraced(function* (handlers) {
268 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
269 const sessions = yield* SessionStore.SessionStore;
270
271 return handlers
272 .handle(
273 "session",
274 Effect.fn("environment.auth.session")(
275 function* (args) {
276 yield* annotateEnvironmentRequest(args.endpoint.name);
277 const request = yield* HttpServerRequest.HttpServerRequest;
278 const result = yield* serverAuth.getSessionState(request);
279 const credential = EnvironmentAuth.selectRequestCredential(
280 request,
281 sessions.cookieName,
282 sessions.legacyCookieName,
283 );
284 if (
285 credential?.source === "legacy-cookie" &&
286 result.authenticated &&
287 result.sessionMethod === "browser-session-cookie" &&
288 result.expiresAt
289 ) {
290 yield* appendSessionCookie(sessions.cookieName, credential.token, result.expiresAt);
291 yield* appendCredentialResponseHeaders;
292 }
293 return result;
294 },
295 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
296 failEnvironmentInternal("internal_error", error),
297 ),
298 ),
299 )
300 .handle(
301 "browserSession",
302 Effect.fn("environment.auth.browserSession")(
303 function* (args) {
304 yield* annotateEnvironmentRequest(args.endpoint.name);
305 const request = yield* HttpServerRequest.HttpServerRequest;
306 const result = yield* serverAuth.createBrowserSession(
307 args.payload.credential,
308 deriveAuthClientMetadata({ request }),
309 );
310 const cookieName = result.cookieName ?? sessions.cookieName;
311 const selectedCookie = yield* Effect.fromResult(
312 Cookies.set(Cookies.empty, cookieName, result.sessionToken, {
313 expires: DateTime.toDate(result.response.expiresAt),
314 httpOnly: true,
315 path: "/",
316 sameSite: "lax",
317 }),
318 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
319 const sessionCookies = result.expireNormalCookie
320 ? yield* Effect.fromResult(
321 Cookies.expireCookie(selectedCookie, sessions.cookieName, {
322 httpOnly: true,
323 path: "/",
324 sameSite: "lax",
325 }),
326 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")))
327 : selectedCookie;
328
329 yield* HttpEffect.appendPreResponseHandler((_request, response) =>
330 Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
331 );
332 yield* appendCredentialResponseHeaders;
333 return result.response;
334 },
335 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
336 failEnvironmentAuthInvalid(
337 EnvironmentAuth.serverAuthCredentialReason(error),
338 EnvironmentAuth.serverAuthDpopFailureReason(error),
339 ),
340 ),
341 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
342 failEnvironmentInternal("browser_session_issuance_failed", error),
343 ),
344 ),
345 )
346 .handle(
347 "token",
348 Effect.fn("environment.auth.token")(
349 function* (args) {
350 yield* annotateEnvironmentRequest(args.endpoint.name);
351 const request = yield* HttpServerRequest.HttpServerRequest;
352 const requestedScopes =
353 args.payload.scope === undefined
354 ? undefined
355 : parseAllowedOAuthScope({
356 value: args.payload.scope,
357 allowedScopes: new Set<AuthEnvironmentScope>([
358 AuthOrchestrationReadScope,
359 AuthOrchestrationOperateScope,
360 AuthTerminalOperateScope,
361 AuthReviewWriteScope,
362 AuthAccessReadScope,
363 AuthAccessWriteScope,
364 AuthRelayReadScope,
365 AuthRelayWriteScope,
366 ]),
367 });
368 if (requestedScopes === null) {
369 return yield* failEnvironmentInvalidRequest("invalid_scope");
370 }
371 const proofKeyThumbprint = args.headers.dpop
372 ? yield* verifyRequestDpopProof({ request }).pipe(
373 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
374 appendDpopChallengeHeader.pipe(
375 Effect.andThen(
376 failEnvironmentAuthInvalid(
377 "invalid_credential",
378 EnvironmentAuth.serverAuthDpopFailureReason(error),
379 ),
380 ),
381 ),
382 ),
383 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
384 failEnvironmentInternal("access_token_issuance_failed", error),
385 ),
386 )
387 : undefined;
388 yield* appendCredentialResponseHeaders;
389 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
390 args.payload.subject_token,
391 requestedScopes,
392 deriveAuthClientMetadata({
393 request,
394 presented: {
395 ...(args.payload.client_label ? { label: args.payload.client_label } : {}),
396 ...(args.payload.client_device_type
397 ? { deviceType: args.payload.client_device_type }
398 : {}),
399 ...(args.payload.client_os ? { os: args.payload.client_os } : {}),
400 },
401 }),
402 proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
403 );
404 },
405 traceRelayRequest,
406 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
407 failEnvironmentAuthInvalid(
408 EnvironmentAuth.serverAuthCredentialReason(error),
409 EnvironmentAuth.serverAuthDpopFailureReason(error),
410 ),
411 ),
412 Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
413 failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
414 ),
415 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
416 failEnvironmentInternal("access_token_issuance_failed", error),
417 ),
418 ),
419 )
420 .handle(
421 "webSocketTicket",
422 Effect.fn("environment.auth.webSocketTicket")(
423 function* (args) {
424 yield* annotateEnvironmentRequest(args.endpoint.name);
425 const session = yield* EnvironmentAuthenticatedPrincipal;
426 yield* appendCredentialResponseHeaders;
427 return yield* serverAuth.issueWebSocketTicket(session);
428 },
429 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
430 failEnvironmentInternal("websocket_ticket_issuance_failed", error),
431 ),
432 ),
433 )
434 .handle(
435 "pairingCredential",
436 Effect.fn("environment.auth.pairingCredential")(
437 function* (args) {
438 yield* annotateEnvironmentRequest(args.endpoint.name);
439 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
440 const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
441 if (
442 delegatedScopes.length === 0 ||
443 new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
444 ) {
445 return yield* failEnvironmentInvalidRequest("invalid_scope");
446 }
447 for (const delegatedScope of delegatedScopes) {
448 if (!session.scopes.has(delegatedScope)) {
449 return yield* failEnvironmentScopeRequired(delegatedScope);
450 }
451 }
452 return yield* serverAuth.issuePairingCredential(args.payload);
453 },
454 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
455 failEnvironmentInternal("pairing_credential_issuance_failed", error),
456 ),
457 ),
458 )
459 .handle(
460 "pairingLinks",
461 Effect.fn("environment.auth.pairingLinks")(
462 function* (args) {
463 yield* annotateEnvironmentRequest(args.endpoint.name);
464 yield* requireEnvironmentScope(AuthAccessReadScope);
465 return yield* serverAuth.listPairingLinks();
466 },
467 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
468 failEnvironmentInternal("pairing_links_load_failed", error),
469 ),
470 ),
471 )
472 .handle(
473 "revokePairingLink",
474 Effect.fn("environment.auth.revokePairingLink")(
475 function* (args) {
476 yield* annotateEnvironmentRequest(args.endpoint.name);
477 yield* requireEnvironmentScope(AuthAccessWriteScope);
478 const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
479 return { revoked };
480 },
481 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
482 failEnvironmentInternal("pairing_link_revoke_failed", error),
483 ),
484 ),
485 )
486 .handle(
487 "clients",
488 Effect.fn("environment.auth.clients")(
489 function* (args) {
490 yield* annotateEnvironmentRequest(args.endpoint.name);
491 const session = yield* requireEnvironmentScope(AuthAccessReadScope);
492 return yield* serverAuth.listClientSessions(session.sessionId);
493 },
494 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
495 failEnvironmentInternal("client_sessions_load_failed", error),
496 ),
497 ),
498 )
499 .handle(
500 "revokeClient",
501 Effect.fn("environment.auth.revokeClient")(
502 function* (args) {
503 yield* annotateEnvironmentRequest(args.endpoint.name);
504 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
505 const revoked = yield* serverAuth.revokeClientSession(
506 session.sessionId,
507 args.payload.sessionId,
508 );
509 return { revoked };
510 },
511 Effect.catchTags({
512 ServerAuthForbiddenOperationError: () =>
513 failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
514 }),
515 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
516 failEnvironmentInternal("client_session_revoke_failed", error),
517 ),
518 ),
519 )
520 .handle(
521 "revokeOtherClients",
522 Effect.fn("environment.auth.revokeOtherClients")(
523 function* (args) {
524 yield* annotateEnvironmentRequest(args.endpoint.name);
525 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
526 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
527 return { revokedCount };
528 },
529 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
530 failEnvironmentInternal("client_session_revoke_failed", error),
531 ),
532 ),
533 );
534 }),
535);