Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

458 lines17.4 KB

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​
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 });
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 );
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 );
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 );
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 );
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 );
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 });
173​
174export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
175 scope: AuthEnvironmentScope,
176) {
177 const session = yield* EnvironmentAuthenticatedPrincipal;
178 if (!session.scopes.has(scope)) {
179 return yield* failEnvironmentScopeRequired(scope);
180 }
181 return session;
182});
183​
184export const environmentAuthenticatedAuthLayer = Layer.effect(
185 EnvironmentAuthenticatedAuth,
186 Effect.gen(function* () {
187 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
188 return (httpEffect) =>
189 Effect.gen(function* () {
190 const request = yield* HttpServerRequest.HttpServerRequest;
191 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
192 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
193 failEnvironmentAuthInvalid(
194 EnvironmentAuth.serverAuthCredentialReason(error),
195 EnvironmentAuth.serverAuthDpopFailureReason(error),
196 ),
197 ),
198 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
199 failEnvironmentInternal("internal_error", error),
200 ),
201 );
202 return yield* httpEffect.pipe(
203 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
204 ...session,
205 scopes: new Set(session.scopes),
206 }),
207 session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
208 );
209 }).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
210 }),
211);
212​
213export const authHttpApiLayer = HttpApiBuilder.group(
214 EnvironmentHttpApi,
215 "auth",
216 Effect.fnUntraced(function* (handlers) {
217 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
218 const sessions = yield* SessionStore.SessionStore;
219​
220 return handlers
221 .handle(
222 "session",
223 Effect.fn("environment.auth.session")(
224 function* (args) {
225 yield* annotateEnvironmentRequest(args.endpoint.name);
226 const request = yield* HttpServerRequest.HttpServerRequest;
227 return yield* serverAuth.getSessionState(request);
228 },
229 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
230 failEnvironmentInternal("internal_error", error),
231 ),
232 ),
233 )
234 .handle(
235 "browserSession",
236 Effect.fn("environment.auth.browserSession")(
237 function* (args) {
238 yield* annotateEnvironmentRequest(args.endpoint.name);
239 const request = yield* HttpServerRequest.HttpServerRequest;
240 const result = yield* serverAuth.createBrowserSession(
241 args.payload.credential,
242 deriveAuthClientMetadata({ request }),
243 );
244 const sessionCookies = yield* Effect.fromResult(
245 Cookies.set(Cookies.empty, sessions.cookieName, result.sessionToken, {
246 expires: DateTime.toDate(result.response.expiresAt),
247 httpOnly: true,
248 path: "/",
249 sameSite: "lax",
250 }),
251 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
252​
253 yield* HttpEffect.appendPreResponseHandler((_request, response) =>
254 Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
255 );
256 yield* appendCredentialResponseHeaders;
257 return result.response;
258 },
259 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
260 failEnvironmentAuthInvalid(
261 EnvironmentAuth.serverAuthCredentialReason(error),
262 EnvironmentAuth.serverAuthDpopFailureReason(error),
263 ),
264 ),
265 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
266 failEnvironmentInternal("browser_session_issuance_failed", error),
267 ),
268 ),
269 )
270 .handle(
271 "token",
272 Effect.fn("environment.auth.token")(
273 function* (args) {
274 yield* annotateEnvironmentRequest(args.endpoint.name);
275 const request = yield* HttpServerRequest.HttpServerRequest;
276 const requestedScopes =
277 args.payload.scope === undefined
278 ? undefined
279 : parseAllowedOAuthScope({
280 value: args.payload.scope,
281 allowedScopes: new Set<AuthEnvironmentScope>([
282 AuthOrchestrationReadScope,
283 AuthOrchestrationOperateScope,
284 AuthTerminalOperateScope,
285 AuthReviewWriteScope,
286 AuthAccessReadScope,
287 AuthAccessWriteScope,
288 AuthRelayReadScope,
289 AuthRelayWriteScope,
290 ]),
291 });
292 if (requestedScopes === null) {
293 return yield* failEnvironmentInvalidRequest("invalid_scope");
294 }
295 const proofKeyThumbprint = args.headers.dpop
296 ? yield* verifyRequestDpopProof({ request }).pipe(
297 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
298 appendDpopChallengeHeader.pipe(
299 Effect.andThen(
300 failEnvironmentAuthInvalid(
301 "invalid_credential",
302 EnvironmentAuth.serverAuthDpopFailureReason(error),
303 ),
304 ),
305 ),
306 ),
307 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
308 failEnvironmentInternal("access_token_issuance_failed", error),
309 ),
310 )
311 : undefined;
312 yield* appendCredentialResponseHeaders;
313 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
314 args.payload.subject_token,
315 requestedScopes,
316 deriveAuthClientMetadata({
317 request,
318 presented: {
319 ...(args.payload.client_label ? { label: args.payload.client_label } : {}),
320 ...(args.payload.client_device_type
321 ? { deviceType: args.payload.client_device_type }
322 : {}),
323 ...(args.payload.client_os ? { os: args.payload.client_os } : {}),
324 },
325 }),
326 proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
327 );
328 },
329 traceRelayRequest,
330 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
331 failEnvironmentAuthInvalid(
332 EnvironmentAuth.serverAuthCredentialReason(error),
333 EnvironmentAuth.serverAuthDpopFailureReason(error),
334 ),
335 ),
336 Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
337 failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
338 ),
339 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
340 failEnvironmentInternal("access_token_issuance_failed", error),
341 ),
342 ),
343 )
344 .handle(
345 "webSocketTicket",
346 Effect.fn("environment.auth.webSocketTicket")(
347 function* (args) {
348 yield* annotateEnvironmentRequest(args.endpoint.name);
349 const session = yield* EnvironmentAuthenticatedPrincipal;
350 yield* appendCredentialResponseHeaders;
351 return yield* serverAuth.issueWebSocketTicket(session);
352 },
353 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
354 failEnvironmentInternal("websocket_ticket_issuance_failed", error),
355 ),
356 ),
357 )
358 .handle(
359 "pairingCredential",
360 Effect.fn("environment.auth.pairingCredential")(
361 function* (args) {
362 yield* annotateEnvironmentRequest(args.endpoint.name);
363 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
364 const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
365 if (
366 delegatedScopes.length === 0 ||
367 new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
368 ) {
369 return yield* failEnvironmentInvalidRequest("invalid_scope");
370 }
371 for (const delegatedScope of delegatedScopes) {
372 if (!session.scopes.has(delegatedScope)) {
373 return yield* failEnvironmentScopeRequired(delegatedScope);
374 }
375 }
376 return yield* serverAuth.issuePairingCredential(args.payload);
377 },
378 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
379 failEnvironmentInternal("pairing_credential_issuance_failed", error),
380 ),
381 ),
382 )
383 .handle(
384 "pairingLinks",
385 Effect.fn("environment.auth.pairingLinks")(
386 function* (args) {
387 yield* annotateEnvironmentRequest(args.endpoint.name);
388 yield* requireEnvironmentScope(AuthAccessReadScope);
389 return yield* serverAuth.listPairingLinks();
390 },
391 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
392 failEnvironmentInternal("pairing_links_load_failed", error),
393 ),
394 ),
395 )
396 .handle(
397 "revokePairingLink",
398 Effect.fn("environment.auth.revokePairingLink")(
399 function* (args) {
400 yield* annotateEnvironmentRequest(args.endpoint.name);
401 yield* requireEnvironmentScope(AuthAccessWriteScope);
402 const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
403 return { revoked };
404 },
405 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
406 failEnvironmentInternal("pairing_link_revoke_failed", error),
407 ),
408 ),
409 )
410 .handle(
411 "clients",
412 Effect.fn("environment.auth.clients")(
413 function* (args) {
414 yield* annotateEnvironmentRequest(args.endpoint.name);
415 const session = yield* requireEnvironmentScope(AuthAccessReadScope);
416 return yield* serverAuth.listClientSessions(session.sessionId);
417 },
418 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
419 failEnvironmentInternal("client_sessions_load_failed", error),
420 ),
421 ),
422 )
423 .handle(
424 "revokeClient",
425 Effect.fn("environment.auth.revokeClient")(
426 function* (args) {
427 yield* annotateEnvironmentRequest(args.endpoint.name);
428 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
429 const revoked = yield* serverAuth.revokeClientSession(
430 session.sessionId,
431 args.payload.sessionId,
432 );
433 return { revoked };
434 },
435 Effect.catchTag("ServerAuthForbiddenOperationError", () =>
436 failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
437 ),
438 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
439 failEnvironmentInternal("client_session_revoke_failed", error),
440 ),
441 ),
442 )
443 .handle(
444 "revokeOtherClients",
445 Effect.fn("environment.auth.revokeOtherClients")(
446 function* (args) {
447 yield* annotateEnvironmentRequest(args.endpoint.name);
448 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
449 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
450 return { revokedCount };
451 },
452 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
453 failEnvironmentInternal("client_session_revoke_failed", error),
454 ),
455 ),
456 );
457 }),
458);