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