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
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 });
172}
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 layerAuthenticatedAuth = 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 startTime = yield* Clock.currentTimeNanos;
209 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
210 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
211 failEnvironmentAuthInvalid(
212 EnvironmentAuth.serverAuthCredentialReason(error),
213 EnvironmentAuth.serverAuthDpopFailureReason(error),
214 ),
215 ),
216 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
217 failEnvironmentInternal("internal_error", error),
218 ),
219 );
220 const endTime = yield* Clock.currentTimeNanos;
221 const handler = httpEffect.pipe(
222 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
223 ...session,
224 scopes: new Set(session.scopes),
225 }),
226 );
227 return yield* session.subject === "cloud-connect"
228 ? traceAuthenticatedRelayRequest(handler, { startTime, endTime })
229 : handler;
230 }).pipe(Effect.catchTags({ EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized }));
231 }),
232);
233
234export const layer = HttpApiBuilder.group(
235 EnvironmentHttpApi,
236 "auth",
237 Effect.fnUntraced(function* (handlers) {
238 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
239 const sessions = yield* SessionStore.SessionStore;
240
241 return handlers
242 .handle(
243 "session",
244 Effect.fn("environment.auth.session")(
245 function* (args) {
246 yield* annotateEnvironmentRequest(args.endpoint.name);
247 const request = yield* HttpServerRequest.HttpServerRequest;
248 const result = yield* serverAuth.getSessionState(request);
249 const credential = EnvironmentAuth.selectRequestCredential(
250 request,
251 sessions.cookieName,
252 sessions.legacyCookieName,
253 );
254 if (
255 credential?.source === "legacy-cookie" &&
256 result.authenticated &&
257 result.sessionMethod === "browser-session-cookie" &&
258 result.expiresAt
259 ) {
260 yield* appendSessionCookie(sessions.cookieName, credential.token, result.expiresAt);
261 yield* appendCredentialResponseHeaders;
262 }
263 return result;
264 },
265 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
266 failEnvironmentInternal("internal_error", error),
267 ),
268 ),
269 )
270 .handle(
271 "browserSession",
272 Effect.fn("environment.auth.browserSession")(
273 function* (args) {
274 yield* annotateEnvironmentRequest(args.endpoint.name);
275 const request = yield* HttpServerRequest.HttpServerRequest;
276 const result = yield* serverAuth.createBrowserSession(
277 args.payload.credential,
278 deriveAuthClientMetadata({ request }),
279 );
280 const cookieName = result.cookieName ?? sessions.cookieName;
281 const selectedCookie = yield* Effect.fromResult(
282 Cookies.set(Cookies.empty, cookieName, result.sessionToken, {
283 expires: DateTime.toDate(result.response.expiresAt),
284 httpOnly: true,
285 path: "/",
286 sameSite: "lax",
287 }),
288 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
289 const sessionCookies = result.expireNormalCookie
290 ? yield* Effect.fromResult(
291 Cookies.expireCookie(selectedCookie, sessions.cookieName, {
292 httpOnly: true,
293 path: "/",
294 sameSite: "lax",
295 }),
296 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")))
297 : selectedCookie;
298
299 yield* HttpEffect.appendPreResponseHandler((_request, response) =>
300 Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
301 );
302 yield* appendCredentialResponseHeaders;
303 return result.response;
304 },
305 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
306 failEnvironmentAuthInvalid(
307 EnvironmentAuth.serverAuthCredentialReason(error),
308 EnvironmentAuth.serverAuthDpopFailureReason(error),
309 ),
310 ),
311 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
312 failEnvironmentInternal("browser_session_issuance_failed", error),
313 ),
314 ),
315 )
316 .handle(
317 "token",
318 Effect.fn("environment.auth.token")(
319 function* (args) {
320 yield* annotateEnvironmentRequest(args.endpoint.name);
321 const request = yield* HttpServerRequest.HttpServerRequest;
322 const requestedScopes =
323 args.payload.scope === undefined
324 ? undefined
325 : parseAllowedOAuthScope({
326 value: args.payload.scope,
327 allowedScopes: new Set<AuthEnvironmentScope>([
328 AuthOrchestrationReadScope,
329 AuthOrchestrationOperateScope,
330 AuthTerminalOperateScope,
331 AuthReviewWriteScope,
332 AuthAccessReadScope,
333 AuthAccessWriteScope,
334 AuthRelayReadScope,
335 AuthRelayWriteScope,
336 ]),
337 });
338 if (requestedScopes === null) {
339 return yield* failEnvironmentInvalidRequest("invalid_scope");
340 }
341 const proofKeyThumbprint = args.headers.dpop
342 ? yield* verifyRequestDpopProof({ request }).pipe(
343 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
344 appendDpopChallengeHeader.pipe(
345 Effect.andThen(
346 failEnvironmentAuthInvalid(
347 "invalid_credential",
348 EnvironmentAuth.serverAuthDpopFailureReason(error),
349 ),
350 ),
351 ),
352 ),
353 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
354 failEnvironmentInternal("access_token_issuance_failed", error),
355 ),
356 )
357 : undefined;
358 yield* appendCredentialResponseHeaders;
359 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
360 args.payload.subject_token,
361 requestedScopes,
362 deriveAuthClientMetadata({
363 request,
364 presented: {
365 ...(args.payload.client_label ? { label: args.payload.client_label } : {}),
366 ...(args.payload.client_device_type
367 ? { deviceType: args.payload.client_device_type }
368 : {}),
369 ...(args.payload.client_os ? { os: args.payload.client_os } : {}),
370 },
371 }),
372 proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
373 );
374 },
375 traceRelayRequest,
376 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
377 failEnvironmentAuthInvalid(
378 EnvironmentAuth.serverAuthCredentialReason(error),
379 EnvironmentAuth.serverAuthDpopFailureReason(error),
380 ),
381 ),
382 Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
383 failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
384 ),
385 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
386 failEnvironmentInternal("access_token_issuance_failed", error),
387 ),
388 ),
389 )
390 .handle(
391 "webSocketTicket",
392 Effect.fn("environment.auth.webSocketTicket")(
393 function* (args) {
394 yield* annotateEnvironmentRequest(args.endpoint.name);
395 const session = yield* EnvironmentAuthenticatedPrincipal;
396 yield* appendCredentialResponseHeaders;
397 return yield* serverAuth.issueWebSocketTicket(session);
398 },
399 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
400 failEnvironmentInternal("websocket_ticket_issuance_failed", error),
401 ),
402 ),
403 )
404 .handle(
405 "pairingCredential",
406 Effect.fn("environment.auth.pairingCredential")(
407 function* (args) {
408 yield* annotateEnvironmentRequest(args.endpoint.name);
409 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
410 const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
411 if (
412 delegatedScopes.length === 0 ||
413 new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
414 ) {
415 return yield* failEnvironmentInvalidRequest("invalid_scope");
416 }
417 for (const delegatedScope of delegatedScopes) {
418 if (!session.scopes.has(delegatedScope)) {
419 return yield* failEnvironmentScopeRequired(delegatedScope);
420 }
421 }
422 return yield* serverAuth.issuePairingCredential(args.payload);
423 },
424 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
425 failEnvironmentInternal("pairing_credential_issuance_failed", error),
426 ),
427 ),
428 )
429 .handle(
430 "pairingLinks",
431 Effect.fn("environment.auth.pairingLinks")(
432 function* (args) {
433 yield* annotateEnvironmentRequest(args.endpoint.name);
434 yield* requireEnvironmentScope(AuthAccessReadScope);
435 return yield* serverAuth.listPairingLinks();
436 },
437 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
438 failEnvironmentInternal("pairing_links_load_failed", error),
439 ),
440 ),
441 )
442 .handle(
443 "revokePairingLink",
444 Effect.fn("environment.auth.revokePairingLink")(
445 function* (args) {
446 yield* annotateEnvironmentRequest(args.endpoint.name);
447 yield* requireEnvironmentScope(AuthAccessWriteScope);
448 const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
449 return { revoked };
450 },
451 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
452 failEnvironmentInternal("pairing_link_revoke_failed", error),
453 ),
454 ),
455 )
456 .handle(
457 "clients",
458 Effect.fn("environment.auth.clients")(
459 function* (args) {
460 yield* annotateEnvironmentRequest(args.endpoint.name);
461 const session = yield* requireEnvironmentScope(AuthAccessReadScope);
462 return yield* serverAuth.listClientSessions(session.sessionId);
463 },
464 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
465 failEnvironmentInternal("client_sessions_load_failed", error),
466 ),
467 ),
468 )
469 .handle(
470 "revokeClient",
471 Effect.fn("environment.auth.revokeClient")(
472 function* (args) {
473 yield* annotateEnvironmentRequest(args.endpoint.name);
474 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
475 const revoked = yield* serverAuth.revokeClientSession(
476 session.sessionId,
477 args.payload.sessionId,
478 );
479 return { revoked };
480 },
481 Effect.catchTags({
482 ServerAuthForbiddenOperationError: () =>
483 failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
484 }),
485 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
486 failEnvironmentInternal("client_session_revoke_failed", error),
487 ),
488 ),
489 )
490 .handle(
491 "revokeOtherClients",
492 Effect.fn("environment.auth.revokeOtherClients")(
493 function* (args) {
494 yield* annotateEnvironmentRequest(args.endpoint.name);
495 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
496 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
497 return { revokedCount };
498 },
499 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
500 failEnvironmentInternal("client_session_revoke_failed", error),
501 ),
502 ),
503 );
504 }),
505);