diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.ts new file mode 100644 index 0000000000..0cf08e9295 --- /dev/null +++ b/apps/server/src/cloud/CliTokenManager.test.ts @@ -0,0 +1,121 @@ +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"] { + 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.", + ); + }), + ); +}); diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 00709370b2..8ea2f76c54 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -27,6 +27,8 @@ 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, @@ -46,48 +48,136 @@ 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", - { cause: Schema.Defect() }, + { + secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET), + cause: Schema.Defect(), + }, ) { override get message(): string { - return "Could not remove the stored T3 Connect CLI credential."; + return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`; } } export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass()( "CloudCliCredentialRefreshError", - { cause: Schema.Defect() }, + { + stage: CloudCliCredentialRefreshStage, + secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET), + tokenEndpoint: Schema.optional(Schema.String), + 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 { - return "Could not refresh the T3 Connect CLI credential."; + const tokenEndpoint = this.tokenEndpoint ? ` using ${this.tokenEndpoint}` : ""; + return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`; } } export class CloudCliCredentialReadError extends Schema.TaggedErrorClass()( "CloudCliCredentialReadError", - { cause: Schema.Defect() }, + { + stage: Schema.Literals(["read-credential", "decode-credential"]), + secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET), + 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 read the stored T3 Connect CLI credential."; + return `Could not inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`; } } export class CloudCliAuthorizationError extends Schema.TaggedErrorClass()( "CloudCliAuthorizationError", - { cause: Schema.Defect() }, + { + 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(), + }, ) { + 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 { - return "Could not authorize the T3 Connect CLI."; + 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}.`; } } export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass()( "CloudCliAuthorizationTimeoutError", - { cause: Schema.Defect() }, + { + redirectUri: Schema.String, + timeoutMillis: Schema.Number, + cause: Schema.Defect(), + }, ) { override get message(): string { - return "Timed out waiting for T3 Connect authorization."; + return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization at ${this.redirectUri}.`; } } @@ -103,18 +193,21 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type; export class CloudCliTokenManager extends Context.Service< CloudCliTokenManager, { - readonly get: Effect.Effect; - readonly getExisting: Effect.Effect, CloudCliTokenManagerError>; - readonly hasCredential: Effect.Effect; - readonly clear: Effect.Effect; + readonly get: Effect.Effect< + PersistedToken, + | CloudCliCredentialRefreshError + | CloudCliAuthorizationError + | CloudCliAuthorizationTimeoutError + >; + readonly getExisting: Effect.Effect< + Option.Option, + CloudCliCredentialRefreshError + >; + readonly hasCredential: Effect.Effect; + readonly clear: Effect.Effect; } >()("t3/cloud/CliTokenManager/CloudCliTokenManager") {} -const wrapError = - (makeError: (cause: unknown) => WrappedError) => - (effect: Effect.Effect): Effect.Effect => - effect.pipe(Effect.mapError(makeError)); - function stringToBytes(value: string): Uint8Array { return new TextEncoder().encode(value); } @@ -134,9 +227,15 @@ export const make = Effect.gen(function* () { return token; }); - const clear = secrets - .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET) - .pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause }))); + const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe( + Effect.mapError( + (cause) => + new CloudCliCredentialRemovalError({ + secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET, + cause, + }), + ), + ); const read = Effect.fn("cloud.cli_token.read")(function* () { const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET); @@ -162,21 +261,62 @@ export const make = Effect.gen(function* () { }); const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) { - const metadata = yield* cloudCliOAuthConfig; + const metadata = yield* cloudCliOAuthConfig.pipe( + Effect.mapError( + (cause) => + new CloudCliCredentialRefreshError({ + stage: "load-oauth-config", + secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET, + cause, + }), + ), + ); 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; - const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32)); - const challenge = Encoding.encodeBase64Url( - yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)), + 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 state = yield* crypto.randomUUIDv4; const callback = yield* Deferred.make(); const callbackRoute = HttpRouter.add( "GET", @@ -207,12 +347,23 @@ export const make = Effect.gen(function* () { }).pipe( Layer.provide( NodeHttpServer.layer(NodeHttp.createServer, { - host: "127.0.0.1", - port: 34338, + host: CLOUD_CLI_OAUTH_CALLBACK_HOST, + port: CLOUD_CLI_OAUTH_CALLBACK_PORT, 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); @@ -225,13 +376,16 @@ 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.catchTag("TimeoutError", (cause) => - Effect.fail( - new CloudCliAuthorizationTimeoutError({ - cause, - }), - ), - ), + Effect.catchTags({ + TimeoutError: (cause) => + Effect.fail( + new CloudCliAuthorizationTimeoutError({ + redirectUri: metadata.redirectUri, + timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT), + cause, + }), + ), + }), ); return yield* exchangeToken(metadata, { grant_type: "authorization_code", @@ -239,26 +393,45 @@ 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(); + const token = yield* read().pipe( + Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead), + ); 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(persist))); + return Option.some( + yield* refresh(token.value).pipe( + Effect.flatMap((refreshed) => + persist(refreshed).pipe( + Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist), + ), + ), + ), + ); }); - const getExisting = semaphore.withPermits(1)( - getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))), - ); + const getExisting = semaphore.withPermits(1)(getExistingNoLock()); const hasCredential = semaphore.withPermits(1)( read().pipe( Effect.map(Option.isSome), - wrapError((cause) => new CloudCliCredentialReadError({ cause })), + Effect.mapError(CloudCliCredentialReadError.fromCredentialRead), ), ); const get = semaphore.withPermits(1)( @@ -266,8 +439,14 @@ export const make = Effect.gen(function* () { const token = yield* getExistingNoLock(); return Option.isSome(token) ? token.value - : yield* Effect.scoped(login()).pipe(Effect.flatMap(persist)); - }).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))), + : yield* Effect.scoped(login()).pipe( + Effect.flatMap((authorized) => + persist(authorized).pipe( + Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist), + ), + ), + ); + }), ); return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear }); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index acb78ea242..f12cf48a83 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -770,14 +770,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi CloudRelayConfigurationError: (error) => failEnvironmentCloudInternalError(error.message)(error), CloudRelayRequestError: (error) => failEnvironmentCloudInternalError(error.message)(error), - CloudCliCredentialRemovalError: (error) => - failEnvironmentCloudInternalError(error.message)(error), CloudCliCredentialRefreshError: (error) => failEnvironmentCloudInternalError(error.message)(error), - CloudCliCredentialReadError: (error) => failEnvironmentCloudInternalError(error.message)(error), - CloudCliAuthorizationError: (error) => failEnvironmentCloudInternalError(error.message)(error), - CloudCliAuthorizationTimeoutError: (error) => - failEnvironmentCloudInternalError(error.message)(error), }), );