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 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 });
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 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 yield* appendSessionCookie(
277 sessions.cookieName,
278 result.sessionToken,
279 result.response.expiresAt,
280 );
281 yield* appendCredentialResponseHeaders;
282 return result.response;
283 },
284 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
285 failEnvironmentAuthInvalid(
286 EnvironmentAuth.serverAuthCredentialReason(error),
287 EnvironmentAuth.serverAuthDpopFailureReason(error),
288 ),
289 ),
290 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
291 failEnvironmentInternal("browser_session_issuance_failed", error),
292 ),
293 ),
294 )
295 .handle(
296 "token",
297 Effect.fn("environment.auth.token")(
298 function* (args) {
299 yield* annotateEnvironmentRequest(args.endpoint.name);
300 const request = yield* HttpServerRequest.HttpServerRequest;
301 const requestedScopes =
302 args.payload.scope === undefined
303 ? undefined
304 : parseAllowedOAuthScope({
305 value: args.payload.scope,
306 allowedScopes: new Set<AuthEnvironmentScope>([
307 AuthOrchestrationReadScope,
308 AuthOrchestrationOperateScope,
309 AuthTerminalOperateScope,
310 AuthReviewWriteScope,
311 AuthAccessReadScope,
312 AuthAccessWriteScope,
313 AuthRelayReadScope,
314 AuthRelayWriteScope,
315 ]),
316 });
317 if (requestedScopes === null) {
318 return yield* failEnvironmentInvalidRequest("invalid_scope");
319 }
320 const proofKeyThumbprint = args.headers.dpop
321 ? yield* verifyRequestDpopProof({ request }).pipe(
322 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
323 appendDpopChallengeHeader.pipe(
324 Effect.andThen(
325 failEnvironmentAuthInvalid(
326 "invalid_credential",
327 EnvironmentAuth.serverAuthDpopFailureReason(error),
328 ),
329 ),
330 ),
331 ),
332 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
333 failEnvironmentInternal("access_token_issuance_failed", error),
334 ),
335 )
336 : undefined;
337 yield* appendCredentialResponseHeaders;
338 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
339 args.payload.subject_token,
340 requestedScopes,
341 deriveAuthClientMetadata({
342 request,
343 presented: {
344 ...(args.payload.client_label ? { label: args.payload.client_label } : {}),
345 ...(args.payload.client_device_type
346 ? { deviceType: args.payload.client_device_type }
347 : {}),
348 ...(args.payload.client_os ? { os: args.payload.client_os } : {}),
349 },
350 }),
351 proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
352 );
353 },
354 traceRelayRequest,
355 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
356 failEnvironmentAuthInvalid(
357 EnvironmentAuth.serverAuthCredentialReason(error),
358 EnvironmentAuth.serverAuthDpopFailureReason(error),
359 ),
360 ),
361 Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
362 failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
363 ),
364 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
365 failEnvironmentInternal("access_token_issuance_failed", error),
366 ),
367 ),
368 )
369 .handle(
370 "webSocketTicket",
371 Effect.fn("environment.auth.webSocketTicket")(
372 function* (args) {
373 yield* annotateEnvironmentRequest(args.endpoint.name);
374 const session = yield* EnvironmentAuthenticatedPrincipal;
375 yield* appendCredentialResponseHeaders;
376 return yield* serverAuth.issueWebSocketTicket(session);
377 },
378 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
379 failEnvironmentInternal("websocket_ticket_issuance_failed", error),
380 ),
381 ),
382 )
383 .handle(
384 "pairingCredential",
385 Effect.fn("environment.auth.pairingCredential")(
386 function* (args) {
387 yield* annotateEnvironmentRequest(args.endpoint.name);
388 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
389 const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
390 if (
391 delegatedScopes.length === 0 ||
392 new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
393 ) {
394 return yield* failEnvironmentInvalidRequest("invalid_scope");
395 }
396 for (const delegatedScope of delegatedScopes) {
397 if (!session.scopes.has(delegatedScope)) {
398 return yield* failEnvironmentScopeRequired(delegatedScope);
399 }
400 }
401 return yield* serverAuth.issuePairingCredential(args.payload);
402 },
403 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
404 failEnvironmentInternal("pairing_credential_issuance_failed", error),
405 ),
406 ),
407 )
408 .handle(
409 "pairingLinks",
410 Effect.fn("environment.auth.pairingLinks")(
411 function* (args) {
412 yield* annotateEnvironmentRequest(args.endpoint.name);
413 yield* requireEnvironmentScope(AuthAccessReadScope);
414 return yield* serverAuth.listPairingLinks();
415 },
416 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
417 failEnvironmentInternal("pairing_links_load_failed", error),
418 ),
419 ),
420 )
421 .handle(
422 "revokePairingLink",
423 Effect.fn("environment.auth.revokePairingLink")(
424 function* (args) {
425 yield* annotateEnvironmentRequest(args.endpoint.name);
426 yield* requireEnvironmentScope(AuthAccessWriteScope);
427 const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
428 return { revoked };
429 },
430 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
431 failEnvironmentInternal("pairing_link_revoke_failed", error),
432 ),
433 ),
434 )
435 .handle(
436 "clients",
437 Effect.fn("environment.auth.clients")(
438 function* (args) {
439 yield* annotateEnvironmentRequest(args.endpoint.name);
440 const session = yield* requireEnvironmentScope(AuthAccessReadScope);
441 return yield* serverAuth.listClientSessions(session.sessionId);
442 },
443 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
444 failEnvironmentInternal("client_sessions_load_failed", error),
445 ),
446 ),
447 )
448 .handle(
449 "revokeClient",
450 Effect.fn("environment.auth.revokeClient")(
451 function* (args) {
452 yield* annotateEnvironmentRequest(args.endpoint.name);
453 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
454 const revoked = yield* serverAuth.revokeClientSession(
455 session.sessionId,
456 args.payload.sessionId,
457 );
458 return { revoked };
459 },
460 Effect.catchTag("ServerAuthForbiddenOperationError", () =>
461 failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
462 ),
463 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
464 failEnvironmentInternal("client_session_revoke_failed", error),
465 ),
466 ),
467 )
468 .handle(
469 "revokeOtherClients",
470 Effect.fn("environment.auth.revokeOtherClients")(
471 function* (args) {
472 yield* annotateEnvironmentRequest(args.endpoint.name);
473 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
474 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
475 return { revokedCount };
476 },
477 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
478 failEnvironmentInternal("client_session_revoke_failed", error),
479 ),
480 ),
481 );
482 }),
483);