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