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

http.ts

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