Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 9878545ccb Structure desktop local auth failures
Co-authored-by: codex <[email protected]>
2026-06-20 08:33:36 -07:00
17 changed files with 494 additions and 1361 deletions

No files matched your search

@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { RemoteEnvironmentAuthInvalidJsonError } from "@t3tools/client-runtime/authorization";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -28,12 +29,29 @@ const config: DesktopBackendManager.DesktopBackendStartConfig = {
captureOutput: true,
};
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const testLayer = (httpClient: HttpClient.HttpClient) =>
DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, Layer.succeed(HttpClient.HttpClient, httpClient))),
);
describe("DesktopLocalEnvironmentAuth", () => {
it.effect("exchanges the desktop bootstrap credential only once", () =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
const layer = testLayer(
HttpClient.make((request) =>
Ref.update(requestCount, (count) => count + 1).pipe(
Effect.as(
@@ -54,30 +72,41 @@ describe("DesktopLocalEnvironmentAuth", () => {
),
),
);
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
}).pipe(Effect.provide(testLayer));
}).pipe(Effect.provide(layer));
assert.strictEqual(first, "desktop-bearer-token");
assert.strictEqual(second, "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}),
);
it.effect("preserves the backend origin and bootstrap failure cause", () =>
Effect.gen(function* () {
const layer = testLayer(
HttpClient.make((request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ unexpected: true }))),
),
);
const error = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* auth.getBearerToken;
}).pipe(Effect.provide(layer), Effect.flip);
assert.instanceOf(
error,
DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuthSessionBootstrapError,
);
assert.strictEqual(error.backendOrigin, "http://127.0.0.1:3773");
assert.strictEqual(
error.message,
"Failed to create the local desktop bearer session for http://127.0.0.1:3773.",
);
assert.instanceOf(error.cause, RemoteEnvironmentAuthInvalidJsonError);
}),
);
});
@@ -21,10 +21,13 @@ export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema
export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
"DesktopLocalEnvironmentAuthSessionBootstrapError",
{ cause: Schema.Defect() },
{
backendOrigin: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to create the local desktop bearer session.";
return `Failed to create the local desktop bearer session for ${this.backendOrigin}.`;
}
}
@@ -60,6 +63,7 @@ export const make = Effect.gen(function* () {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = configOption.value;
const backendOrigin = config.httpBaseUrl.origin;
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
credential: config.bootstrap.desktopBootstrapToken,
@@ -72,6 +76,7 @@ export const make = Effect.gen(function* () {
Effect.mapError(
(cause) =>
new DesktopLocalEnvironmentAuthSessionBootstrapError({
backendOrigin,
cause,
}),
),
@@ -114,16 +114,6 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
.pipe(Effect.flip);
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
if (error._tag === "ServerAuthScopeNotGrantedError") {
expect(error.requestedScopes).toEqual(["orchestration:read", "access:write"]);
expect(error.grantedScopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
]);
}
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
@@ -262,20 +252,4 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
),
),
);
it.effect("retains both session ids when rejecting self-revocation", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const issued = yield* serverAuth.issueSession();
const error = yield* serverAuth
.revokeClientSession(issued.sessionId, issued.sessionId)
.pipe(Effect.flip);
expect(error._tag).toBe("ServerAuthForbiddenOperationError");
if (error._tag === "ServerAuthForbiddenOperationError") {
expect(error.currentSessionId).toBe(issued.sessionId);
expect(error.targetSessionId).toBe(issued.sessionId);
}
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
});
+90 -167
View File
@@ -85,50 +85,44 @@ export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedE
export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
"ServerAuthSessionCredentialValidationError",
{
credentialKind: Schema.Literals(["session", "websocket-ticket"]),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to validate ${this.credentialKind} credential.`;
return "Failed to validate session credential.";
}
}
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
"ServerAuthAuthenticatedSessionIssueError",
{
subject: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue authenticated session for ${this.subject}.`;
return "Failed to issue authenticated session.";
}
}
export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
"ServerAuthAuthenticatedAccessTokenIssueError",
{
subject: Schema.String,
scopes: Schema.Array(Schema.String),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue authenticated access token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
return "Failed to issue authenticated access token.";
}
}
export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
"ServerAuthPairingLinkCreationError",
{
subject: Schema.String,
scopes: Schema.Array(Schema.String),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to create pairing link for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
return "Failed to create pairing link.";
}
}
@@ -146,25 +140,22 @@ export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<Ser
export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
"ServerAuthPairingLinkRevocationError",
{
pairingLinkId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke pairing link ${this.pairingLinkId}.`;
return "Failed to revoke pairing link.";
}
}
export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
"ServerAuthSessionTokenIssueError",
{
subject: Schema.String,
scopes: Schema.Array(Schema.String),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue session token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
return "Failed to issue session token.";
}
}
@@ -182,63 +173,55 @@ export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerA
export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
"ServerAuthSessionRevocationError",
{
sessionId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke session ${this.sessionId}.`;
return "Failed to revoke session.";
}
}
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
"ServerAuthOtherSessionsRevocationError",
{
excludedSessionId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke sessions other than ${this.excludedSessionId}.`;
return "Failed to revoke other sessions.";
}
}
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
"ServerAuthWebSocketTokenIssueError",
{
sessionId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue websocket token for session ${this.sessionId}.`;
return "Failed to issue websocket token.";
}
}
export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
"ServerAuthDpopReplayStateRecordError",
{
proofKeyThumbprint: Schema.String,
proofId: Schema.String,
replayKey: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to record replay state for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
return "Failed to record DPoP proof replay state.";
}
}
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
"ServerAuthDpopReplayKeyCalculationError",
{
proofKeyThumbprint: Schema.String,
proofId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to calculate replay key for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
return "Failed to calculate DPoP replay key.";
}
}
@@ -377,6 +360,11 @@ export const ServerAuthCredentialError = Schema.Union([
ServerAuthInvalidCredentialError,
]);
export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
export const serverAuthCredentialReason = (
error: ServerAuthCredentialError,
): "missing_credential" | "invalid_credential" =>
error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
"ServerAuthInvalidScopeError",
@@ -389,13 +377,10 @@ export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerA
export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
"ServerAuthScopeNotGrantedError",
{
requestedScopes: Schema.Array(Schema.String),
grantedScopes: Schema.Array(Schema.String),
},
{},
) {
override get message(): string {
return `Requested scopes [${this.requestedScopes.join(", ")}] exceed granted scopes [${this.grantedScopes.join(", ")}].`;
return "The requested authentication scope was not granted.";
}
}
@@ -404,35 +389,28 @@ export const ServerAuthInvalidRequestError = Schema.Union([
ServerAuthScopeNotGrantedError,
]);
export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
export const serverAuthInvalidRequestReason = (
error: ServerAuthInvalidRequestError,
): "invalid_scope" | "scope_not_granted" =>
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
"ServerAuthForbiddenOperationError",
{
currentSessionId: Schema.String,
targetSessionId: Schema.String,
},
{},
) {
override get message(): string {
return `Authentication session ${this.currentSessionId} cannot revoke itself.`;
return "The current authentication session cannot revoke itself.";
}
}
export type ServerAuthAuthenticationInternalError =
| ServerAuthSessionCredentialValidationError
| ServerAuthDpopReplayStateRecordError
| ServerAuthDpopReplayKeyCalculationError;
export type ServerAuthAuthenticationError =
| ServerAuthCredentialError
| ServerAuthAuthenticationInternalError;
export class EnvironmentAuth extends Context.Service<
EnvironmentAuth,
{
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
readonly getSessionState: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthSessionState, ServerAuthAuthenticationInternalError>;
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
readonly createBrowserSession: (
credential: string,
requestMetadata: AuthClientMetadata,
@@ -441,9 +419,7 @@ export class EnvironmentAuth extends Context.Service<
readonly response: AuthBrowserSessionResult;
readonly sessionToken: string;
},
| ServerAuthInvalidCredentialError
| ServerAuthBootstrapCredentialValidationError
| ServerAuthAuthenticatedSessionIssueError
ServerAuthInvalidCredentialError | ServerAuthInternalError
>;
readonly exchangeBootstrapCredentialForAccessToken: (
credential: string,
@@ -454,10 +430,7 @@ export class EnvironmentAuth extends Context.Service<
},
) => Effect.Effect<
AuthAccessTokenResult,
| ServerAuthInvalidCredentialError
| ServerAuthScopeNotGrantedError
| ServerAuthBootstrapCredentialValidationError
| ServerAuthAuthenticatedAccessTokenIssueError
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
>;
readonly createPairingLink: (input?: {
readonly ttl?: Duration.Duration;
@@ -465,61 +438,56 @@ export class EnvironmentAuth extends Context.Service<
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedPairingLink, ServerAuthPairingLinkCreationError>;
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthPairingLinkCreationError>;
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
readonly issueStartupPairingCredential: () => Effect.Effect<
AuthPairingCredentialResult,
ServerAuthPairingLinkCreationError
ServerAuthInternalError
>;
readonly listPairingLinks: (input?: {
readonly excludeSubjects?: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthPairingLinksListError>;
readonly revokePairingLink: (
id: string,
) => Effect.Effect<boolean, ServerAuthPairingLinkRevocationError>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly issueSession: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, ServerAuthSessionTokenIssueError>;
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
ServerAuthSessionsListError
ServerAuthInternalError
>;
readonly revokeSession: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, ServerAuthSessionRevocationError>;
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly revokeOtherSessionsExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
) => Effect.Effect<number, ServerAuthInternalError>;
readonly listClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthSessionsListError>;
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
readonly revokeClientSession: (
currentSessionId: AuthSessionId,
targetSessionId: AuthSessionId,
) => Effect.Effect<
boolean,
ServerAuthForbiddenOperationError | ServerAuthSessionRevocationError
>;
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
) => Effect.Effect<number, ServerAuthInternalError>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly issueWebSocketTicket: (
session: Pick<AuthenticatedSession, "sessionId">,
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthWebSocketTokenIssueError>;
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
readonly issueStartupPairingUrl: (
baseUrl: string,
) => Effect.Effect<string, ServerAuthPairingLinkCreationError>;
) => Effect.Effect<string, ServerAuthInternalError>;
}
>()("t3/auth/EnvironmentAuth") {}
@@ -546,7 +514,7 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
export function toBootstrapExchangeError(
cause: PairingGrantStore.BootstrapCredentialError,
): ServerAuthInvalidCredentialError | ServerAuthBootstrapCredentialValidationError {
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
return new ServerAuthBootstrapCredentialValidationError({ cause });
}
@@ -558,17 +526,12 @@ export function toBootstrapExchangeError(
const mapSessionVerificationErrors = <A, R>(
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
credentialKind: ServerAuthSessionCredentialValidationError["credentialKind"],
): Effect.Effect<
A,
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError,
R
> =>
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
effect.pipe(
Effect.mapError((cause) =>
SessionStore.isSessionCredentialInvalidError(cause)
? new ServerAuthInvalidCredentialError({ cause })
: new ServerAuthSessionCredentialValidationError({ credentialKind, cause }),
: new ServerAuthSessionCredentialValidationError({ cause }),
),
);
@@ -602,7 +565,7 @@ export const make = Effect.gen(function* () {
token: string,
): Effect.Effect<
AuthenticatedSession,
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError
ServerAuthInvalidCredentialError | ServerAuthInternalError
> =>
sessions.verify(token).pipe(
Effect.tapError((cause) =>
@@ -622,12 +585,12 @@ export const make = Effect.gen(function* () {
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
(effect) => mapSessionVerificationErrors(effect, "session"),
mapSessionVerificationErrors,
);
const authenticateRequest = (
request: HttpServerRequest.HttpServerRequest,
): Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError> => {
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
const cookieToken = request.cookies[sessions.cookieName];
const bearerToken = parseBearerToken(request);
const dpopToken = parseDpopToken(request);
@@ -679,18 +642,12 @@ export const make = Effect.gen(function* () {
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
}) satisfies AuthSessionState,
),
Effect.catchTags({
ServerAuthMissingCredentialError: () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
ServerAuthInvalidCredentialError: () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
}),
Effect.catchIf(isServerAuthCredentialError, () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
),
Effect.withSpan("EnvironmentAuth.getSessionState"),
);
@@ -712,13 +669,7 @@ export const make = Effect.gen(function* () {
},
})
.pipe(
Effect.mapError(
(cause) =>
new ServerAuthAuthenticatedSessionIssueError({
subject: grant.subject,
cause,
}),
),
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
),
),
Effect.map(
@@ -744,10 +695,7 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
const grantedScopes = requestedScopes ?? grant.scopes;
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
return yield* new ServerAuthScopeNotGrantedError({
requestedScopes: grantedScopes,
grantedScopes: grant.scopes,
});
return yield* new ServerAuthScopeNotGrantedError({});
}
return yield* sessions
.issue({
@@ -767,12 +715,7 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError(
(cause) =>
new ServerAuthAuthenticatedAccessTokenIssueError({
subject: grant.subject,
scopes: grantedScopes,
cause,
}),
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
),
);
}),
@@ -822,33 +765,28 @@ export const make = Effect.gen(function* () {
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
"EnvironmentAuth.createPairingLink",
)(function* (input) {
const scopes = input?.scopes ?? AuthStandardClientScopes;
const subject = input?.subject ?? "one-time-token";
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials
.issueOneTimeToken({
scopes,
subject,
)(
function* (input) {
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials.issueOneTimeToken({
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
})
.pipe(
Effect.mapError(
(cause) => new ServerAuthPairingLinkCreationError({ subject, scopes, cause }),
),
);
return {
id: issued.id,
credential: issued.credential,
scopes,
subject,
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
});
});
return {
id: issued.id,
credential: issued.credential,
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
},
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
);
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
@@ -868,20 +806,16 @@ export const make = Effect.gen(function* () {
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
bootstrapCredentials.revoke(id).pipe(
Effect.mapError(
(cause) => new ServerAuthPairingLinkRevocationError({ pairingLinkId: id, cause }),
),
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
);
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => {
const subject = input?.subject ?? DEFAULT_SESSION_SUBJECT;
const scopes = input?.scopes ?? AuthAdministrativeScopes;
return sessions
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
sessions
.issue({
subject,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
method: "bearer-access-token",
scopes,
scopes: input?.scopes ?? AuthAdministrativeScopes,
client: {
...(input?.label ? { label: input.label } : {}),
deviceType: "bot",
@@ -896,17 +830,14 @@ export const make = Effect.gen(function* () {
token: issued.token,
method: "bearer-access-token",
scopes: issued.scopes,
subject,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
client: issued.client,
expiresAt: DateTime.toUtc(issued.expiresAt),
}) satisfies IssuedBearerSession,
),
Effect.mapError(
(cause) => new ServerAuthSessionTokenIssueError({ subject, scopes, cause }),
),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueSession"),
);
};
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
sessions.listActive().pipe(
@@ -917,7 +848,7 @@ export const make = Effect.gen(function* () {
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
sessions.revoke(sessionId).pipe(
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ sessionId, cause })),
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeSession"),
);
@@ -925,10 +856,7 @@ export const make = Effect.gen(function* () {
sessionId,
) =>
sessions.revokeAllExcept(sessionId).pipe(
Effect.mapError(
(cause) =>
new ServerAuthOtherSessionsRevocationError({ excludedSessionId: sessionId, cause }),
),
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
);
@@ -963,10 +891,7 @@ export const make = Effect.gen(function* () {
"EnvironmentAuth.revokeClientSession",
)(function* (currentSessionId, targetSessionId) {
if (currentSessionId === targetSessionId) {
return yield* new ServerAuthForbiddenOperationError({
currentSessionId,
targetSessionId,
});
return yield* new ServerAuthForbiddenOperationError({});
}
return yield* revokeSession(targetSessionId);
});
@@ -992,9 +917,7 @@ export const make = Effect.gen(function* () {
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
sessions.issueWebSocketToken(session.sessionId).pipe(
Effect.mapError(
(cause) => new ServerAuthWebSocketTokenIssueError({ sessionId: session.sessionId, cause }),
),
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
Effect.map(
(issued) =>
({
@@ -1024,7 +947,7 @@ export const make = Effect.gen(function* () {
scopes: session.scopes,
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
(effect) => mapSessionVerificationErrors(effect, "websocket-ticket"),
mapSessionVerificationErrors,
);
}
}
+3 -46
View File
@@ -45,31 +45,6 @@ const makePermissionDeniedSecretStoreLayer = () =>
Layer.provideMerge(PermissionDeniedFileSystemLayer),
);
const DirectoryCreateFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
makeDirectory: (path) =>
Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: String(path),
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makeDirectoryCreateFailureSecretStoreLayer = (config: ServerConfig.ServerConfig["Service"]) =>
ServerSecretStore.layer.pipe(
Layer.provide(Layer.succeed(ServerConfig.ServerConfig, config)),
Layer.provideMerge(DirectoryCreateFailureFileSystemLayer),
);
const RenameFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
@@ -171,20 +146,6 @@ const makeConcurrentCreateSecretStoreLayer = () =>
);
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
it.effect("preserves directory context when secret-store initialization fails", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(makeServerConfigLayer()));
const error = yield* Layer.build(makeDirectoryCreateFailureSecretStoreLayer(config)).pipe(
Effect.scoped,
Effect.flip,
);
assert.instanceOf(error, ServerSecretStore.SecretStoreDirectoryCreateError);
assert.match(error.directoryPath, /secrets$/u);
assert.instanceOf(error.cause, PlatformError.PlatformError);
}),
);
it.effect("returns Option.none when a secret file does not exist", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
@@ -271,8 +232,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
assert.equal(error.secretName, "session-signing-key");
assert.match(error.secretPath, /session-signing-key\.bin$/u);
assert.include(error.message, "Failed to read secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
@@ -287,9 +247,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
);
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
assert.equal(error.operation, "set");
assert.equal(error.secretName, "session-signing-key");
assert.match(error.secretPath, /session-signing-key\.bin$/u);
assert.include(error.message, "Failed to persist secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
@@ -302,8 +260,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
assert.equal(error.secretName, "session-signing-key");
assert.match(error.secretPath, /session-signing-key\.bin$/u);
assert.include(error.message, "Failed to remove secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
+62 -117
View File
@@ -11,136 +11,114 @@ import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
const storedSecretErrorContext = {
secretName: Schema.String,
secretPath: Schema.String,
const secretStoreErrorContext = {
resource: Schema.String,
cause: Schema.Defect(),
};
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
"SecretStoreDirectoryCreateError",
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
"SecretStoreSecureError",
{
directoryPath: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to create secret store directory ${this.directoryPath}.`;
}
}
export class SecretStoreDirectorySecureError extends Schema.TaggedErrorClass<SecretStoreDirectorySecureError>()(
"SecretStoreDirectorySecureError",
{
directoryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to secure secret store directory ${this.directoryPath}.`;
return `Failed to secure ${this.resource}.`;
}
}
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
"SecretStoreReadError",
{
...storedSecretErrorContext,
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to read secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to read ${this.resource}.`;
}
}
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
"SecretStoreTemporaryPathGenerationError",
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
"SecretStoreTemporaryPathError",
{
secretName: Schema.String,
secretPath: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to create temporary path for ${this.resource}.`;
}
}
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
"SecretStorePersistError",
{
operation: Schema.Literals(["create", "set"]),
...storedSecretErrorContext,
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to persist ${this.resource}.`;
}
}
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
"SecretStoreRandomGenerationError",
{
secretName: Schema.String,
byteCount: Schema.Number,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`;
return `Failed to generate random bytes for ${this.resource}.`;
}
}
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
"SecretStoreConcurrentReadError",
{
secretName: Schema.String,
resource: Schema.String,
},
) {
override get message(): string {
return `Failed to read secret ${this.secretName} after concurrent creation.`;
return `Failed to read ${this.resource} after concurrent creation.`;
}
}
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
"SecretStoreRemoveError",
{
...storedSecretErrorContext,
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to remove ${this.resource}.`;
}
}
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
"SecretStoreDecodeError",
{
secretName: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to decode secret ${this.secretName}.`;
return `Failed to decode ${this.resource}.`;
}
}
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
"SecretStoreEncodeError",
{
secretName: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to encode secret ${this.secretName}.`;
return `Failed to encode ${this.resource}.`;
}
}
export const SecretStoreError = Schema.Union([
SecretStoreDirectoryCreateError,
SecretStoreDirectorySecureError,
SecretStoreSecureError,
SecretStoreReadError,
SecretStoreTemporaryPathGenerationError,
SecretStoreTemporaryPathError,
SecretStorePersistError,
SecretStoreRandomGenerationError,
SecretStoreConcurrentReadError,
@@ -160,26 +138,14 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
export class ServerSecretStore extends Context.Service<
ServerSecretStore,
{
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreReadError>;
readonly set: (
name: string,
value: Uint8Array,
) => Effect.Effect<void, SecretStoreTemporaryPathGenerationError | SecretStorePersistError>;
readonly create: (
name: string,
value: Uint8Array,
) => Effect.Effect<void, SecretStorePersistError>;
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
name: string,
bytes: number,
) => Effect.Effect<
Uint8Array,
| SecretStoreReadError
| SecretStoreRandomGenerationError
| SecretStorePersistError
| SecretStoreConcurrentReadError
>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
) => Effect.Effect<Uint8Array, SecretStoreError>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
>()("t3/auth/ServerSecretStore") {}
@@ -189,20 +155,12 @@ export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig.ServerConfig;
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new SecretStoreDirectoryCreateError({
directoryPath: serverConfig.secretsDir,
cause,
}),
),
);
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
Effect.mapError(
(cause) =>
new SecretStoreDirectorySecureError({
directoryPath: serverConfig.secretsDir,
new SecretStoreSecureError({
resource: `secrets directory ${serverConfig.secretsDir}`,
cause,
}),
),
@@ -210,33 +168,29 @@ export const make = Effect.gen(function* () {
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
const get: ServerSecretStore["Service"]["get"] = (name) => {
const secretPath = resolveSecretPath(name);
return fileSystem.readFile(secretPath).pipe(
const get: ServerSecretStore["Service"]["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
: Effect.fail(
new SecretStoreReadError({
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
),
Effect.withSpan("ServerSecretStore.get"),
);
};
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
const secretPath = resolveSecretPath(name);
return crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new SecretStoreTemporaryPathGenerationError({
secretName: name,
secretPath,
new SecretStoreTemporaryPathError({
resource: `secret ${name}`,
cause,
}),
),
@@ -254,9 +208,7 @@ export const make = Effect.gen(function* () {
Effect.flatMap(() =>
Effect.fail(
new SecretStorePersistError({
operation: "set",
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
@@ -285,9 +237,7 @@ export const make = Effect.gen(function* () {
Effect.mapError(
(cause) =>
new SecretStorePersistError({
operation: "create",
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
@@ -304,32 +254,30 @@ export const make = Effect.gen(function* () {
Effect.mapError(
(cause) =>
new SecretStoreRandomGenerationError({
secretName: name,
byteCount: bytes,
resource: `secret ${name}`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTags({
SecretStorePersistError: (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreConcurrentReadError({
secretName: name,
}),
),
}),
),
)
: Effect.fail(error),
}),
Effect.catchIf(isSecretStoreError, (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreConcurrentReadError({
resource: `secret ${name}`,
}),
),
}),
),
)
: Effect.fail(error),
),
),
),
),
@@ -338,23 +286,20 @@ export const make = Effect.gen(function* () {
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
);
const remove: ServerSecretStore["Service"]["remove"] = (name) => {
const secretPath = resolveSecretPath(name);
return fileSystem.remove(secretPath).pipe(
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
fileSystem.remove(resolveSecretPath(name)).pipe(
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.void
: Effect.fail(
new SecretStoreRemoveError({
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
),
Effect.withSpan("ServerSecretStore.remove"),
);
};
return ServerSecretStore.of({
get,
+4 -19
View File
@@ -6,9 +6,7 @@ import { mapDpopReplayStoreError } from "./dpop.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new SecretStorePersistError({
operation: "create",
secretName: "DPoP proof",
secretPath: "dpop-proof.bin",
resource: "DPoP proof",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -17,16 +15,10 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
}),
});
const replayContext = {
proofKeyThumbprint: "proof-key-thumbprint",
proofId: "proof-id",
replayKey: "replay-key",
};
describe("mapDpopReplayStoreError", () => {
it("reports replay conflicts as invalid credentials", () => {
const cause = storeFailure("AlreadyExists");
const error = mapDpopReplayStoreError(cause, replayContext);
const error = mapDpopReplayStoreError(cause);
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
if (error._tag === "ServerAuthInvalidCredentialError") {
@@ -35,18 +27,11 @@ describe("mapDpopReplayStoreError", () => {
});
it("reports replay-store availability failures as internal errors", () => {
const cause = storeFailure("PermissionDenied");
const error = mapDpopReplayStoreError(cause, replayContext);
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
expect(error.message).toBe(
"Failed to record replay state for DPoP proof proof-id (proof-key-thumbprint).",
);
expect(error.proofKeyThumbprint).toBe(replayContext.proofKeyThumbprint);
expect(error.proofId).toBe(replayContext.proofId);
expect(error.replayKey).toBe(replayContext.replayKey);
expect(error.cause).toBe(cause);
expect(error.message).toBe("Failed to record DPoP proof replay state.");
}
});
});
+4 -15
View File
@@ -9,6 +9,7 @@ import {
ServerAuthDpopReplayKeyCalculationError,
ServerAuthDpopReplayStateRecordError,
ServerAuthInvalidCredentialError,
type ServerAuthInternalError,
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
@@ -30,19 +31,13 @@ export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest)
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
context: {
readonly proofKeyThumbprint: string;
readonly proofId: string;
readonly replayKey: string;
},
): ServerAuthInvalidCredentialError | ServerAuthDpopReplayStateRecordError =>
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? new ServerAuthInvalidCredentialError({
diagnostic: "DPoP proof replayed.",
cause: error,
})
: new ServerAuthDpopReplayStateRecordError({
...context,
cause: error,
});
@@ -76,8 +71,6 @@ export const verifyRequestDpopProof = (input: {
Effect.mapError(
(cause) =>
new ServerAuthDpopReplayKeyCalculationError({
proofKeyThumbprint: result.thumbprint,
proofId: result.jti,
cause,
}),
),
@@ -95,12 +88,8 @@ export const verifyRequestDpopProof = (input: {
),
)
.pipe(
Effect.mapError((error) =>
mapDpopReplayStoreError(error, {
proofKeyThumbprint: result.thumbprint,
proofId: result.jti,
replayKey,
}),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
Effect.fail(mapDpopReplayStoreError(error)),
),
);
return result.thumbprint;
+58 -86
View File
@@ -151,22 +151,6 @@ export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason,
});
}
const failAuthenticationInternal = (error: EnvironmentAuth.ServerAuthAuthenticationInternalError) =>
failEnvironmentInternal("internal_error", error);
export const catchEnvironmentAuthenticationErrors = <A, R>(
effect: Effect.Effect<A, EnvironmentAuth.ServerAuthAuthenticationError, R>,
) =>
effect.pipe(
Effect.catchTags({
ServerAuthMissingCredentialError: () => failEnvironmentAuthInvalid("missing_credential"),
ServerAuthInvalidCredentialError: () => failEnvironmentAuthInvalid("invalid_credential"),
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
}),
);
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
scope: AuthEnvironmentScope,
) {
@@ -184,8 +168,13 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
return (httpEffect) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const session = yield* catchEnvironmentAuthenticationErrors(
serverAuth.authenticateHttpRequest(request),
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
return yield* httpEffect.pipe(
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
@@ -194,11 +183,7 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
}),
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
);
}).pipe(
Effect.catchTags({
EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized,
}),
);
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
}),
);
@@ -218,11 +203,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const request = yield* HttpServerRequest.HttpServerRequest;
return yield* serverAuth.getSessionState(request);
},
Effect.catchTags({
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
),
)
.handle(
@@ -250,14 +233,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* appendCredentialResponseHeaders;
return result.response;
},
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
failEnvironmentAuthInvalid("invalid_credential"),
ServerAuthBootstrapCredentialValidationError: (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
ServerAuthAuthenticatedSessionIssueError: (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
),
),
)
.handle(
@@ -287,16 +268,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
}
const proofKeyThumbprint = args.headers.dpop
? yield* verifyRequestDpopProof({ request }).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
appendDpopChallengeHeader.pipe(
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
),
ServerAuthDpopReplayStateRecordError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
ServerAuthDpopReplayKeyCalculationError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
appendDpopChallengeHeader.pipe(
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
),
)
: undefined;
yield* appendCredentialResponseHeaders;
@@ -317,16 +296,15 @@ export const authHttpApiLayer = HttpApiBuilder.group(
);
},
traceRelayRequest,
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
failEnvironmentAuthInvalid("invalid_credential"),
ServerAuthScopeNotGrantedError: () =>
failEnvironmentInvalidRequest("scope_not_granted"),
ServerAuthBootstrapCredentialValidationError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
ServerAuthAuthenticatedAccessTokenIssueError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
),
),
)
.handle(
@@ -338,10 +316,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* appendCredentialResponseHeaders;
return yield* serverAuth.issueWebSocketTicket(session);
},
Effect.catchTags({
ServerAuthWebSocketTokenIssueError: (error) =>
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
),
),
)
.handle(
@@ -364,10 +341,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
}
return yield* serverAuth.issuePairingCredential(args.payload);
},
Effect.catchTags({
ServerAuthPairingLinkCreationError: (error) =>
failEnvironmentInternal("pairing_credential_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_credential_issuance_failed", error),
),
),
)
.handle(
@@ -378,10 +354,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listPairingLinks();
},
Effect.catchTags({
ServerAuthPairingLinksListError: (error) =>
failEnvironmentInternal("pairing_links_load_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_links_load_failed", error),
),
),
)
.handle(
@@ -393,10 +368,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
return { revoked };
},
Effect.catchTags({
ServerAuthPairingLinkRevocationError: (error) =>
failEnvironmentInternal("pairing_link_revoke_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_link_revoke_failed", error),
),
),
)
.handle(
@@ -407,10 +381,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listClientSessions(session.sessionId);
},
Effect.catchTags({
ServerAuthSessionsListError: (error) =>
failEnvironmentInternal("client_sessions_load_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_sessions_load_failed", error),
),
),
)
.handle(
@@ -425,12 +398,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
);
return { revoked };
},
Effect.catchTags({
ServerAuthForbiddenOperationError: () =>
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
ServerAuthSessionRevocationError: (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
}),
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
)
.handle(
@@ -442,10 +415,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
return { revokedCount };
},
Effect.catchTags({
ServerAuthOtherSessionsRevocationError: (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
);
}),
@@ -1,121 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
function makeSecretStore(
overrides: Partial<ServerSecretStore.ServerSecretStore["Service"]>,
): ServerSecretStore.ServerSecretStore["Service"] {
return {
get: unusedSecretStoreOperation,
set: unusedSecretStoreOperation,
create: unusedSecretStoreOperation,
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
...overrides,
};
}
function makeTokenManager(secretStore: ServerSecretStore.ServerSecretStore["Service"]) {
return CliTokenManager.make.pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ServerSecretStore.ServerSecretStore, secretStore),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unused HTTP client")),
),
),
),
);
}
describe("CloudCliTokenManager", () => {
it.effect("retains secret context and cause when credential removal fails", () => {
const failure = new ServerSecretStore.SecretStoreRemoveError({
secretName: "cloud-cli-oauth-token",
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
cause: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "remove",
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
}),
});
return Effect.gen(function* () {
const tokens = yield* makeTokenManager(
makeSecretStore({ remove: () => Effect.fail(failure) }),
);
const error = yield* Effect.flip(tokens.clear);
expect(error).toMatchObject({
_tag: "CloudCliCredentialRemovalError",
secretName: "cloud-cli-oauth-token",
cause: failure,
});
expect(error.message).toBe(
"Could not remove the stored T3 Connect CLI credential cloud-cli-oauth-token.",
);
});
});
it.effect("classifies credential read failures without replacing the cause", () => {
const failure = new ServerSecretStore.SecretStoreReadError({
secretName: "cloud-cli-oauth-token",
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
cause: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
}),
});
return Effect.gen(function* () {
const tokens = yield* makeTokenManager(makeSecretStore({ get: () => Effect.fail(failure) }));
const error = yield* Effect.flip(tokens.hasCredential);
expect(error).toMatchObject({
_tag: "CloudCliCredentialReadError",
stage: "read-credential",
secretName: "cloud-cli-oauth-token",
cause: failure,
});
expect(error.message).toBe(
"Could not inspect the stored T3 Connect CLI credential cloud-cli-oauth-token during read-credential.",
);
});
});
it.effect("classifies malformed persisted credentials as refresh decode failures", () =>
Effect.gen(function* () {
const tokens = yield* makeTokenManager(
makeSecretStore({
get: () =>
Effect.succeed(Option.some(new TextEncoder().encode("not valid credential JSON"))),
}),
);
const error = yield* Effect.flip(tokens.getExisting);
expect(error).toMatchObject({
_tag: "CloudCliCredentialRefreshError",
stage: "decode-credential",
secretName: "cloud-cli-oauth-token",
cause: { _tag: "SchemaError" },
});
expect(error.message).toBe(
"Could not refresh the T3 Connect CLI credential cloud-cli-oauth-token during decode-credential.",
);
}),
);
});
+47 -226
View File
@@ -27,8 +27,6 @@ import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const CLOUD_CLI_OAUTH_CALLBACK_HOST = "127.0.0.1";
const CLOUD_CLI_OAUTH_CALLBACK_PORT = 34338;
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
@@ -48,136 +46,48 @@ const OAuthTokenResponse = Schema.Struct({
token_type: Schema.String,
});
type CredentialReadFailure = ServerSecretStore.SecretStoreReadError | Schema.SchemaError;
type CredentialPersistFailure =
| Schema.SchemaError
| ServerSecretStore.SecretStoreTemporaryPathGenerationError
| ServerSecretStore.SecretStorePersistError;
const CloudCliCredentialRefreshStage = Schema.Literals([
"read-credential",
"decode-credential",
"load-oauth-config",
"exchange-token",
"encode-credential",
"persist-credential",
]);
const CloudCliAuthorizationStage = Schema.Literals([
"load-oauth-config",
"prepare-pkce",
"start-callback-server",
"exchange-token",
"encode-credential",
"persist-credential",
]);
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
"CloudCliCredentialRemovalError",
{
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
override get message(): string {
return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`;
return "Could not remove the stored T3 Connect CLI credential.";
}
}
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
"CloudCliCredentialRefreshError",
{
stage: CloudCliCredentialRefreshStage,
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
tokenEndpoint: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialRefreshError {
return new CloudCliCredentialRefreshError({
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliCredentialRefreshError {
return new CloudCliCredentialRefreshError({
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
override get message(): string {
const tokenEndpoint = this.tokenEndpoint ? ` using ${this.tokenEndpoint}` : "";
return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`;
return "Could not refresh the T3 Connect CLI credential.";
}
}
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
"CloudCliCredentialReadError",
{
stage: Schema.Literals(["read-credential", "decode-credential"]),
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialReadError {
return new CloudCliCredentialReadError({
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
override get message(): string {
return `Could not inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`;
return "Could not read the stored T3 Connect CLI credential.";
}
}
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
"CloudCliAuthorizationError",
{
stage: CloudCliAuthorizationStage,
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
tokenEndpoint: Schema.optional(Schema.String),
redirectUri: Schema.optional(Schema.String),
callbackHost: Schema.optional(Schema.String),
callbackPort: Schema.optional(Schema.Number),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliAuthorizationError {
return new CloudCliAuthorizationError({
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
override get message(): string {
const tokenEndpoint = this.tokenEndpoint ? ` using ${this.tokenEndpoint}` : "";
const redirectUri = this.redirectUri ? ` with callback ${this.redirectUri}` : "";
const callbackAddress =
this.callbackHost && this.callbackPort !== undefined
? ` on ${this.callbackHost}:${this.callbackPort}`
: "";
return `Could not authorize the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}${redirectUri}${callbackAddress}.`;
return "Could not authorize the T3 Connect CLI.";
}
}
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
"CloudCliAuthorizationTimeoutError",
{
redirectUri: Schema.String,
timeoutMillis: Schema.Number,
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
override get message(): string {
return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization at ${this.redirectUri}.`;
return "Timed out waiting for T3 Connect authorization.";
}
}
@@ -193,21 +103,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
{
readonly get: Effect.Effect<
PersistedToken,
| CloudCliCredentialRefreshError
| CloudCliAuthorizationError
| CloudCliAuthorizationTimeoutError
>;
readonly getExisting: Effect.Effect<
Option.Option<PersistedToken>,
CloudCliCredentialRefreshError
>;
readonly hasCredential: Effect.Effect<boolean, CloudCliCredentialReadError>;
readonly clear: Effect.Effect<void, CloudCliCredentialRemovalError>;
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
}
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
const wrapError =
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
effect.pipe(Effect.mapError(makeError));
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
@@ -227,15 +134,9 @@ export const make = Effect.gen(function* () {
return token;
});
const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe(
Effect.mapError(
(cause) =>
new CloudCliCredentialRemovalError({
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
}),
),
);
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -261,62 +162,21 @@ export const make = Effect.gen(function* () {
});
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
const metadata = yield* cloudCliOAuthConfig.pipe(
Effect.mapError(
(cause) =>
new CloudCliCredentialRefreshError({
stage: "load-oauth-config",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
}),
),
);
const metadata = yield* cloudCliOAuthConfig;
return yield* exchangeToken(metadata, {
grant_type: "refresh_token",
refresh_token: token.refreshToken,
client_id: metadata.clientId,
}).pipe(
Effect.mapError(
(cause) =>
new CloudCliCredentialRefreshError({
stage: "exchange-token",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
tokenEndpoint: metadata.tokenEndpoint,
cause,
}),
),
);
});
});
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig.pipe(
Effect.mapError(
(cause) =>
new CloudCliAuthorizationError({
stage: "load-oauth-config",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
}),
),
);
const { challenge, state, verifier } = yield* Effect.gen(function* () {
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
return { challenge, state, verifier };
}).pipe(
Effect.mapError(
(cause) =>
new CloudCliAuthorizationError({
stage: "prepare-pkce",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
redirectUri: metadata.redirectUri,
cause,
}),
),
const metadata = yield* cloudCliOAuthConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
"GET",
@@ -347,23 +207,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Layer.provide(
NodeHttpServer.layer(NodeHttp.createServer, {
host: CLOUD_CLI_OAUTH_CALLBACK_HOST,
port: CLOUD_CLI_OAUTH_CALLBACK_PORT,
host: "127.0.0.1",
port: 34338,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
Effect.mapError(
(cause) =>
new CloudCliAuthorizationError({
stage: "start-callback-server",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
redirectUri: metadata.redirectUri,
callbackHost: CLOUD_CLI_OAUTH_CALLBACK_HOST,
callbackPort: CLOUD_CLI_OAUTH_CALLBACK_PORT,
cause,
}),
),
);
const authorizationUrl = new URL(metadata.authorizationEndpoint);
authorizationUrl.searchParams.set("client_id", metadata.clientId);
@@ -376,16 +225,13 @@ export const make = Effect.gen(function* () {
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTags({
TimeoutError: (cause) =>
Effect.fail(
new CloudCliAuthorizationTimeoutError({
redirectUri: metadata.redirectUri,
timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
cause,
}),
),
}),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(
new CloudCliAuthorizationTimeoutError({
cause,
}),
),
),
);
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
@@ -393,45 +239,26 @@ export const make = Effect.gen(function* () {
redirect_uri: metadata.redirectUri,
client_id: metadata.clientId,
code_verifier: verifier,
}).pipe(
Effect.mapError(
(cause) =>
new CloudCliAuthorizationError({
stage: "exchange-token",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
tokenEndpoint: metadata.tokenEndpoint,
redirectUri: metadata.redirectUri,
cause,
}),
),
);
});
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
const token = yield* read().pipe(
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead),
);
const token = yield* read();
if (Option.isNone(token)) return token;
const now = yield* Clock.currentTimeMillis;
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
return token;
}
return Option.some(
yield* refresh(token.value).pipe(
Effect.flatMap((refreshed) =>
persist(refreshed).pipe(
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist),
),
),
),
);
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
});
const getExisting = semaphore.withPermits(1)(getExistingNoLock());
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
Effect.mapError(CloudCliCredentialReadError.fromCredentialRead),
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
),
);
const get = semaphore.withPermits(1)(
@@ -439,14 +266,8 @@ export const make = Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(
Effect.flatMap((authorized) =>
persist(authorized).pipe(
Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist),
),
),
);
}),
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
+1 -23
View File
@@ -66,9 +66,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
Effect.flatMap(() =>
Effect.fail(
new ServerSecretStore.SecretStorePersistError({
operation: "create",
secretName: "cloud-link-ed25519-key-pair",
secretPath: "cloud-link-ed25519-key-pair.bin",
resource: "environment signing key pair",
cause: PlatformError.systemError({
_tag: "AlreadyExists",
module: "FileSystem",
@@ -89,24 +87,4 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
});
}),
);
it.effect("retains the secret name and decode cause for malformed keypairs", () =>
Effect.gen(function* () {
const secretStore = {
get: () => Effect.succeed(Option.some(new TextEncoder().encode("not-json"))),
set: unusedSecretStoreOperation,
create: unusedSecretStoreOperation,
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
} satisfies ServerSecretStore.ServerSecretStore["Service"];
const error = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore).pipe(
Effect.flip,
);
assert.instanceOf(error, ServerSecretStore.SecretStoreDecodeError);
assert.equal(error.secretName, "cloud-link-ed25519-key-pair");
assert.exists(error.cause);
}),
);
});
+25 -32
View File
@@ -27,6 +27,17 @@ function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
const KEY_PAIR_RESOURCE = "environment signing key pair";
const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>
new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });
const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>
new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });
const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>
new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });
const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
secrets: ServerSecretStore.ServerSecretStore["Service"],
) {
@@ -35,13 +46,7 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
return Option.none<EnvironmentKeyPair>();
}
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
Effect.mapError(
(cause) =>
new ServerSecretStore.SecretStoreDecodeError({
secretName: CLOUD_LINK_KEY_PAIR,
cause,
}),
),
Effect.mapError(keyPairDecodeError),
);
return Option.some(decoded);
});
@@ -51,34 +56,22 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
keyPair: EnvironmentKeyPair,
) {
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
Effect.mapError(
(cause) =>
new ServerSecretStore.SecretStoreEncodeError({
secretName: CLOUD_LINK_KEY_PAIR,
cause,
}),
),
Effect.mapError(keyPairEncodeError),
);
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
Effect.as(keyPair),
Effect.catchTags({
SecretStorePersistError: (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new ServerSecretStore.SecretStoreConcurrentReadError({
secretName: CLOUD_LINK_KEY_PAIR,
}),
),
}),
),
)
: Effect.fail(error),
}),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () => Effect.fail(keyPairConcurrentReadError()),
}),
),
)
: Effect.fail(error),
),
);
});
+39 -138
View File
@@ -1,35 +1,23 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Tracer from "effect/Tracer";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientError from "effect/unstable/http/HttpClientError";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import {
CloudRelayRequestError,
consumeCloudReplayGuards,
reconcileDesiredCloudLink,
} from "./http.ts";
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStorePersistError({
operation: "create",
secretName: "cloud replay guard",
secretPath: "cloud-replay-guard.bin",
resource: "cloud replay guard",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -52,55 +40,6 @@ function makeSecretStore(
};
}
function reconcileWith(input: {
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
readonly httpClient?: HttpClient.HttpClient;
readonly env?: Readonly<Record<string, string>>;
}) {
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
getEnvironmentId: unusedSecretStoreOperation(),
getDescriptor: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
applyConfig: unusedSecretStoreOperation,
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
),
Effect.provideService(
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getExisting: input.getExisting,
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
HttpClient.HttpClient,
input.httpClient ?? HttpClient.make(() => unusedSecretStoreOperation()),
),
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
),
),
);
}
it("preserves messages surfaced by cloud 500 responses", () => {
const cause = new Error("cloud operation failed");
@@ -154,45 +93,6 @@ describe("consumeCloudReplayGuards", () => {
);
});
describe("CloudRelayRequestError", () => {
it("classifies response failures without deriving its message from the cause", () => {
const request = HttpClientRequest.post(
"https://relay.example.test/v1/client/environment-links",
);
const response = HttpClientResponse.fromWeb(
request,
new Response("sensitive upstream response", { status: 502 }),
);
const upstreamCause = new Error("sensitive upstream response details");
const cause = new HttpClientError.HttpClientError({
reason: new HttpClientError.StatusCodeError({
request,
response,
cause: upstreamCause,
}),
});
const error = CloudRelayRequestError.fromClientFailure({
operation: "create-environment-link",
url: request.url,
cause,
});
expect(error).toMatchObject({
operation: "create-environment-link",
phase: "check-response-status",
method: "POST",
url: request.url,
responseStatus: 502,
cause,
});
expect(error.message).toBe(
"T3 Connect relay create-environment-link failed during check-response-status with response status 502.",
);
expect(error.message).not.toContain(upstreamCause.message);
});
});
describe("relay request tracing", () => {
it.effect("does not accept an unauthenticated request trace parent", () =>
Effect.gen(function* () {
@@ -260,47 +160,48 @@ describe("relay request tracing", () => {
describe("reconcileDesiredCloudLink", () => {
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
);
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 connect link` to authorize this environment.",
});
}),
);
it.effect("redacts relay transport failures behind a stable structural message", () => {
const transportCause = new Error("upstream included a sensitive database password");
const httpClient = HttpClient.make((request) =>
Effect.fail(
new HttpClientError.HttpClientError({
reason: new HttpClientError.TransportError({ request, cause: transportCause }),
}).pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
getEnvironmentId: unusedSecretStoreOperation(),
getDescriptor: unusedSecretStoreOperation(),
}),
),
);
return Effect.gen(function* () {
const error = yield* Effect.flip(
reconcileWith({
getExisting: Effect.succeed(
Option.some({
accessToken: "access-token",
refreshToken: "refresh-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
}),
),
httpClient,
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
Effect.provideService(
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
applyConfig: unusedSecretStoreOperation,
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
),
Effect.provideService(
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
);
expect(error).toMatchObject({
_tag: "EnvironmentHttpInternalServerError",
message: "T3 Connect relay create-link-challenge failed during send-request.",
});
expect(error.message).not.toContain(transportCause.message);
});
});
),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => unusedSecretStoreOperation()),
),
Effect.provide(NodeServices.layer),
),
);
});
+90 -319
View File
@@ -48,13 +48,8 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import * as HttpBody from "effect/unstable/http/HttpBody";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientError from "effect/unstable/http/HttpClientError";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
@@ -90,104 +85,6 @@ const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
pragma: "no-cache",
} as const;
const CloudRelayRequestOperation = Schema.Literals([
"create-link-challenge",
"create-environment-link",
]);
const CloudRelayRequestPhase = Schema.Literals([
"encode-request",
"send-request",
"check-response-status",
"decode-response",
]);
export class CloudRelayConfigurationError extends Schema.TaggedErrorClass<CloudRelayConfigurationError>()(
"CloudRelayConfigurationError",
{
configKey: Schema.Literal("T3CODE_RELAY_URL"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `${this.configKey} must be configured as a secure absolute HTTPS origin.`;
}
}
export class CloudRelayRequestError extends Schema.TaggedErrorClass<CloudRelayRequestError>()(
"CloudRelayRequestError",
{
operation: CloudRelayRequestOperation,
phase: CloudRelayRequestPhase,
method: Schema.Literal("POST"),
url: Schema.String,
responseStatus: Schema.optional(Schema.Number),
cause: Schema.Defect(),
},
) {
static fromClientFailure(input: {
readonly operation: CloudRelayRequestError["operation"];
readonly url: string;
readonly cause: HttpBody.HttpBodyError | HttpClientError.HttpClientError | Schema.SchemaError;
readonly responseStatus?: number;
}): CloudRelayRequestError {
if (input.cause._tag === "SchemaError") {
return new CloudRelayRequestError({
operation: input.operation,
phase: "decode-response",
method: "POST",
url: input.url,
...(input.responseStatus === undefined ? {} : { responseStatus: input.responseStatus }),
cause: input.cause,
});
}
if (!HttpClientError.isHttpClientError(input.cause)) {
return new CloudRelayRequestError({
operation: input.operation,
phase: "encode-request",
method: "POST",
url: input.url,
cause: input.cause,
});
}
const phase: CloudRelayRequestError["phase"] = (() => {
switch (input.cause.reason._tag) {
case "EncodeError":
return "encode-request";
case "TransportError":
case "InvalidUrlError":
return "send-request";
case "StatusCodeError":
return "check-response-status";
case "DecodeError":
case "EmptyBodyError":
return "decode-response";
}
})();
return new CloudRelayRequestError({
operation: input.operation,
phase,
method: "POST",
url: input.url,
...(input.cause.response === undefined
? input.responseStatus === undefined
? {}
: { responseStatus: input.responseStatus }
: { responseStatus: input.cause.response.status }),
cause: input.cause,
});
}
override get message(): string {
const responseStatus =
this.responseStatus === undefined ? "" : ` with response status ${this.responseStatus}`;
return `T3 Connect relay ${this.operation} failed during ${this.phase}${responseStatus}.`;
}
}
const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
(_request, response) =>
Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
@@ -200,12 +97,14 @@ const failEnvironmentCloudInternalError =
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
);
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
failEnvironmentCloudInternalError(error.message)(error);
const requireRelayUrl = relayUrlConfig.pipe(
Effect.mapError(
(cause) =>
new CloudRelayConfigurationError({
configKey: "T3CODE_RELAY_URL",
cause,
() =>
new EnvironmentHttpInternalServerError({
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
}),
),
);
@@ -227,12 +126,11 @@ export function consumeCloudReplayGuards(input: {
input.names.map((name) =>
input.secrets.create(name, input.value).pipe(
Effect.as(true),
Effect.catchTags({
SecretStorePersistError: (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
}),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
),
),
),
{ concurrency: input.names.length },
@@ -309,7 +207,7 @@ function validateRelayConfigPayload(
function validateLinkedCloudUser(input: {
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
readonly cloudUserId: string;
}) {
}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
@@ -334,7 +232,9 @@ function validateLinkedCloudUser(input: {
);
}
function readInstalledCloudUserId(secrets: ServerSecretStore.ServerSecretStore["Service"]) {
function readInstalledCloudUserId(
secrets: ServerSecretStore.ServerSecretStore["Service"],
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
@@ -509,26 +409,17 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
yield* appendCloudCredentialResponseHeaders;
return proof satisfies RelayEnvironmentLinkProof;
},
Effect.catchTags({
ServerAuthCloudLinkJwtSigningError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
SecretStoreReadError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
SecretStoreDecodeError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
SecretStoreEncodeError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
PlatformError: failEnvironmentCloudInternalError("Could not generate environment link proof."),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not generate environment link proof."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not generate environment link proof."),
),
);
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
@@ -581,28 +472,22 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
yield* requireEnvironmentScope(AuthRelayWriteScope);
return yield* applyCloudRelayConfig(dependencies, payload);
},
Effect.catchTags({
ServerAuthLinkedCloudAccountVerificationError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
SecretStoreRemoveError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
SchemaError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
),
Effect.catchTag(
"SchemaError",
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
),
);
const relayClientRequest = <A>(
dependencies: CloudHttpDependencies,
input: {
readonly operation: CloudRelayRequestError["operation"];
readonly url: string;
readonly token: string;
readonly payload: unknown;
@@ -612,46 +497,14 @@ const relayClientRequest = <A>(
HttpClientRequest.post(input.url).pipe(
HttpClientRequest.bearerToken(input.token),
HttpClientRequest.bodyJson(input.payload),
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
cause,
}),
),
Effect.flatMap((request) =>
dependencies.httpClient.execute(request).pipe(
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
cause,
}),
),
),
),
Effect.flatMap((response) =>
HttpClientResponse.filterStatusOk(response).pipe(
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
cause,
}),
),
),
),
Effect.flatMap((response) =>
HttpClientResponse.schemaBodyJson(input.schema)(response).pipe(
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
responseStatus: response.status,
cause,
}),
),
),
Effect.flatMap(dependencies.httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
Effect.mapError(
(cause) =>
new EnvironmentHttpInternalServerError({
message: `T3 Connect relay request failed: ${String(cause)}`,
}),
),
withRelayClientTracing,
);
@@ -686,7 +539,6 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
);
const relayUrl = yield* requireRelayUrl;
const challenge = yield* relayClientRequest(dependencies, {
operation: "create-link-challenge",
url: `${relayUrl}/v1/client/environment-link-challenges`,
token: token.accessToken,
payload: {
@@ -714,7 +566,6 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
localOrigin,
);
const link = yield* relayClientRequest(dependencies, {
operation: "create-environment-link",
url: `${relayUrl}/v1/client/environment-links`,
token: token.accessToken,
payload: {
@@ -735,43 +586,16 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
endpointRuntime: link.endpointRuntime,
});
},
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
),
Effect.catchTags({
ServerAuthLinkedCloudAccountVerificationError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudLinkJwtSigningError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
SecretStoreReadError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SecretStoreRemoveError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SecretStoreDecodeError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SecretStoreEncodeError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
SchemaError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
PlatformError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
CloudRelayConfigurationError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
CloudRelayRequestError: (error) => failEnvironmentCloudInternalError(error.message)(error),
CloudCliCredentialRefreshError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
CloudCliCredentialReadError: failCloudCliTokenManagerError,
CloudCliAuthorizationError: failCloudCliTokenManagerError,
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
}),
);
@@ -809,11 +633,10 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
yield* requireEnvironmentScope(AuthRelayReadScope);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTags({
SecretStoreReadError: failEnvironmentCloudInternalError(
"Could not read environment relay configuration.",
),
}),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
),
);
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
@@ -835,17 +658,10 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
yield* setCliDesiredCloudLink(false);
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
},
Effect.catchTags({
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"Could not remove environment relay configuration.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not remove environment relay configuration.",
),
SecretStoreRemoveError: failEnvironmentCloudInternalError(
"Could not remove environment relay configuration.",
),
}),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
),
);
const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
@@ -860,17 +676,10 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTags({
SecretStoreReadError: failEnvironmentCloudInternalError(
"Could not persist environment cloud preferences.",
),
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"Could not persist environment cloud preferences.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not persist environment cloud preferences.",
),
}),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
),
);
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
@@ -978,34 +787,17 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTags({
ServerAuthLinkedCloudAccountReadError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthLinkedCloudAccountMissingError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudMintPublicKeyMissingError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudRelayIssuerMissingError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudHealthJwtSigningError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
SecretStoreReadError: failEnvironmentCloudInternalError(
"Could not answer cloud health request.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not answer cloud health request.",
),
SecretStoreDecodeError: failEnvironmentCloudInternalError(
"Could not answer cloud health request.",
),
SecretStoreEncodeError: failEnvironmentCloudInternalError(
"Could not answer cloud health request.",
),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
"Could not answer cloud health request.",
),
PlatformError: failEnvironmentCloudInternalError("Could not answer cloud health request."),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not answer cloud health request."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not answer cloud health request."),
),
);
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
@@ -1116,38 +908,17 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTags({
ServerAuthLinkedCloudAccountReadError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthLinkedCloudAccountMissingError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudMintPublicKeyMissingError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudRelayIssuerMissingError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthPairingLinkCreationError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
ServerAuthCloudMintJwtSigningError: (error) =>
failEnvironmentCloudInternalError(error.message)(error),
SecretStoreReadError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
SecretStorePersistError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
SecretStoreDecodeError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
SecretStoreEncodeError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
PlatformError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
),
);
export const connectHttpApiLayer = HttpApiBuilder.group(
+9 -3
View File
@@ -35,8 +35,9 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
import {
annotateEnvironmentRequest,
catchEnvironmentAuthenticationErrors,
failEnvironmentScopeRequired,
failEnvironmentAuthInvalid,
failEnvironmentInternal,
} from "./auth/http.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
@@ -79,8 +80,13 @@ const authenticateRawRouteWithScope = (
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const session = yield* catchEnvironmentAuthenticationErrors(
serverAuth.authenticateHttpRequest(request),
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
if (!session.scopes.includes(scope)) {
return yield* failEnvironmentScopeRequired(scope);
+8 -3
View File
@@ -105,7 +105,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
import * as VcsProcess from "./vcs/VcsProcess.ts";
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { catchEnvironmentAuthenticationErrors } from "./auth/http.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
const isWorkspacePathOutsideRootError = Schema.is(WorkspacePaths.WorkspacePathOutsideRootError);
@@ -1725,8 +1725,13 @@ export const websocketRpcRouteLayer = Layer.unwrap(
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sessions = yield* SessionStore.SessionStore;
const session = yield* catchEnvironmentAuthenticationErrors(
serverAuth.authenticateWebSocketUpgrade(request),
const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
disableTracing: true,