From 47c042422cfc303009fb69648c810529fc0e55e1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 20 Jun 2026 02:09:59 -0700 Subject: [PATCH] Structure server secret store errors Co-authored-by: codex --- .../server/src/auth/ServerSecretStore.test.ts | 49 ++++- apps/server/src/auth/ServerSecretStore.ts | 179 ++++++++++++------ apps/server/src/auth/dpop.test.ts | 4 +- apps/server/src/cloud/environmentKeys.test.ts | 24 ++- apps/server/src/cloud/environmentKeys.ts | 57 +++--- apps/server/src/cloud/http.test.ts | 4 +- 6 files changed, 224 insertions(+), 93 deletions(-) diff --git a/apps/server/src/auth/ServerSecretStore.test.ts b/apps/server/src/auth/ServerSecretStore.test.ts index d4411fb9f3..50fca258a0 100644 --- a/apps/server/src/auth/ServerSecretStore.test.ts +++ b/apps/server/src/auth/ServerSecretStore.test.ts @@ -45,6 +45,31 @@ 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* () { @@ -146,6 +171,20 @@ 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; @@ -232,7 +271,8 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => { const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32)); assert.instanceOf(error, ServerSecretStore.SecretStoreReadError); - assert.include(error.message, "Failed to read secret session-signing-key."); + assert.equal(error.secretName, "session-signing-key"); + assert.match(error.secretPath, /session-signing-key\.bin$/u); assert.instanceOf(error.cause, PlatformError.PlatformError); assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied"); }).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())), @@ -247,7 +287,9 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => { ); assert.instanceOf(error, ServerSecretStore.SecretStorePersistError); - assert.include(error.message, "Failed to persist secret session-signing-key."); + assert.equal(error.operation, "set"); + assert.equal(error.secretName, "session-signing-key"); + assert.match(error.secretPath, /session-signing-key\.bin$/u); assert.instanceOf(error.cause, PlatformError.PlatformError); assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied"); }).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())), @@ -260,7 +302,8 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => { const error = yield* Effect.flip(secretStore.remove("session-signing-key")); assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError); - assert.include(error.message, "Failed to remove secret session-signing-key."); + assert.equal(error.secretName, "session-signing-key"); + assert.match(error.secretPath, /session-signing-key\.bin$/u); assert.instanceOf(error.cause, PlatformError.PlatformError); assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied"); }).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())), diff --git a/apps/server/src/auth/ServerSecretStore.ts b/apps/server/src/auth/ServerSecretStore.ts index 5e9890c1ea..bbd567a941 100644 --- a/apps/server/src/auth/ServerSecretStore.ts +++ b/apps/server/src/auth/ServerSecretStore.ts @@ -11,114 +11,136 @@ import * as Schema from "effect/Schema"; import * as ServerConfig from "../config.ts"; -const secretStoreErrorContext = { - resource: Schema.String, +const storedSecretErrorContext = { + secretName: Schema.String, + secretPath: Schema.String, cause: Schema.Defect(), }; -export class SecretStoreSecureError extends Schema.TaggedErrorClass()( - "SecretStoreSecureError", +export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass()( + "SecretStoreDirectoryCreateError", { - ...secretStoreErrorContext, + directoryPath: Schema.String, + cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to secure ${this.resource}.`; + return `Failed to create secret store directory ${this.directoryPath}.`; + } +} + +export class SecretStoreDirectorySecureError extends Schema.TaggedErrorClass()( + "SecretStoreDirectorySecureError", + { + directoryPath: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to secure secret store directory ${this.directoryPath}.`; } } export class SecretStoreReadError extends Schema.TaggedErrorClass()( "SecretStoreReadError", { - ...secretStoreErrorContext, + ...storedSecretErrorContext, }, ) { override get message(): string { - return `Failed to read ${this.resource}.`; + return `Failed to read secret ${this.secretName} at ${this.secretPath}.`; } } -export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass()( - "SecretStoreTemporaryPathError", +export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass()( + "SecretStoreTemporaryPathGenerationError", { - ...secretStoreErrorContext, + secretName: Schema.String, + secretPath: Schema.String, + cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to create temporary path for ${this.resource}.`; + return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`; } } export class SecretStorePersistError extends Schema.TaggedErrorClass()( "SecretStorePersistError", { - ...secretStoreErrorContext, + operation: Schema.Literals(["create", "set"]), + ...storedSecretErrorContext, }, ) { override get message(): string { - return `Failed to persist ${this.resource}.`; + return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`; } } export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass()( "SecretStoreRandomGenerationError", { - ...secretStoreErrorContext, + secretName: Schema.String, + byteCount: Schema.Number, + cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to generate random bytes for ${this.resource}.`; + return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`; } } export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass()( "SecretStoreConcurrentReadError", { - resource: Schema.String, + secretName: Schema.String, }, ) { override get message(): string { - return `Failed to read ${this.resource} after concurrent creation.`; + return `Failed to read secret ${this.secretName} after concurrent creation.`; } } export class SecretStoreRemoveError extends Schema.TaggedErrorClass()( "SecretStoreRemoveError", { - ...secretStoreErrorContext, + ...storedSecretErrorContext, }, ) { override get message(): string { - return `Failed to remove ${this.resource}.`; + return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`; } } export class SecretStoreDecodeError extends Schema.TaggedErrorClass()( "SecretStoreDecodeError", { - ...secretStoreErrorContext, + secretName: Schema.String, + cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to decode ${this.resource}.`; + return `Failed to decode secret ${this.secretName}.`; } } export class SecretStoreEncodeError extends Schema.TaggedErrorClass()( "SecretStoreEncodeError", { - ...secretStoreErrorContext, + secretName: Schema.String, + cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to encode ${this.resource}.`; + return `Failed to encode secret ${this.secretName}.`; } } export const SecretStoreError = Schema.Union([ - SecretStoreSecureError, + SecretStoreDirectoryCreateError, + SecretStoreDirectorySecureError, SecretStoreReadError, - SecretStoreTemporaryPathError, + SecretStoreTemporaryPathGenerationError, SecretStorePersistError, SecretStoreRandomGenerationError, SecretStoreConcurrentReadError, @@ -138,14 +160,26 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean => export class ServerSecretStore extends Context.Service< ServerSecretStore, { - readonly get: (name: string) => Effect.Effect, SecretStoreError>; - readonly set: (name: string, value: Uint8Array) => Effect.Effect; - readonly create: (name: string, value: Uint8Array) => Effect.Effect; + readonly get: (name: string) => Effect.Effect, SecretStoreReadError>; + readonly set: ( + name: string, + value: Uint8Array, + ) => Effect.Effect; + readonly create: ( + name: string, + value: Uint8Array, + ) => Effect.Effect; readonly getOrCreateRandom: ( name: string, bytes: number, - ) => Effect.Effect; - readonly remove: (name: string) => Effect.Effect; + ) => Effect.Effect< + Uint8Array, + | SecretStoreReadError + | SecretStoreRandomGenerationError + | SecretStorePersistError + | SecretStoreConcurrentReadError + >; + readonly remove: (name: string) => Effect.Effect; } >()("t3/auth/ServerSecretStore") {} @@ -155,12 +189,20 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const serverConfig = yield* ServerConfig.ServerConfig; - yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }); + yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe( + Effect.mapError( + (cause) => + new SecretStoreDirectoryCreateError({ + directoryPath: serverConfig.secretsDir, + cause, + }), + ), + ); yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe( Effect.mapError( (cause) => - new SecretStoreSecureError({ - resource: `secrets directory ${serverConfig.secretsDir}`, + new SecretStoreDirectorySecureError({ + directoryPath: serverConfig.secretsDir, cause, }), ), @@ -168,29 +210,33 @@ export const make = Effect.gen(function* () { const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`); - const get: ServerSecretStore["Service"]["get"] = (name) => - fileSystem.readFile(resolveSecretPath(name)).pipe( + const get: ServerSecretStore["Service"]["get"] = (name) => { + const secretPath = resolveSecretPath(name); + return fileSystem.readFile(secretPath).pipe( Effect.map((bytes) => Option.some(Uint8Array.from(bytes))), Effect.catch((cause) => cause.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail( new SecretStoreReadError({ - resource: `secret ${name}`, + secretName: name, + secretPath, cause, }), ), ), Effect.withSpan("ServerSecretStore.get"), ); + }; const set: ServerSecretStore["Service"]["set"] = (name, value) => { const secretPath = resolveSecretPath(name); return crypto.randomUUIDv4.pipe( Effect.mapError( (cause) => - new SecretStoreTemporaryPathError({ - resource: `secret ${name}`, + new SecretStoreTemporaryPathGenerationError({ + secretName: name, + secretPath, cause, }), ), @@ -208,7 +254,9 @@ export const make = Effect.gen(function* () { Effect.flatMap(() => Effect.fail( new SecretStorePersistError({ - resource: `secret ${name}`, + operation: "set", + secretName: name, + secretPath, cause, }), ), @@ -237,7 +285,9 @@ export const make = Effect.gen(function* () { Effect.mapError( (cause) => new SecretStorePersistError({ - resource: `secret ${name}`, + operation: "create", + secretName: name, + secretPath, cause, }), ), @@ -254,30 +304,32 @@ export const make = Effect.gen(function* () { Effect.mapError( (cause) => new SecretStoreRandomGenerationError({ - resource: `secret ${name}`, + secretName: name, + byteCount: bytes, cause, }), ), Effect.flatMap((generated) => create(name, generated).pipe( Effect.as(Uint8Array.from(generated)), - 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), - ), + 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), + }), ), ), ), @@ -286,20 +338,23 @@ export const make = Effect.gen(function* () { Effect.withSpan("ServerSecretStore.getOrCreateRandom"), ); - const remove: ServerSecretStore["Service"]["remove"] = (name) => - fileSystem.remove(resolveSecretPath(name)).pipe( + const remove: ServerSecretStore["Service"]["remove"] = (name) => { + const secretPath = resolveSecretPath(name); + return fileSystem.remove(secretPath).pipe( Effect.catch((cause) => cause.reason._tag === "NotFound" ? Effect.void : Effect.fail( new SecretStoreRemoveError({ - resource: `secret ${name}`, + secretName: name, + secretPath, cause, }), ), ), Effect.withSpan("ServerSecretStore.remove"), ); + }; return ServerSecretStore.of({ get, diff --git a/apps/server/src/auth/dpop.test.ts b/apps/server/src/auth/dpop.test.ts index 81610a2201..d01417cebf 100644 --- a/apps/server/src/auth/dpop.test.ts +++ b/apps/server/src/auth/dpop.test.ts @@ -6,7 +6,9 @@ import { mapDpopReplayStoreError } from "./dpop.ts"; const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") => new SecretStorePersistError({ - resource: "DPoP proof", + operation: "create", + secretName: "DPoP proof", + secretPath: "dpop-proof.bin", cause: PlatformError.systemError({ _tag: tag, module: "FileSystem", diff --git a/apps/server/src/cloud/environmentKeys.test.ts b/apps/server/src/cloud/environmentKeys.test.ts index 48c44ccc48..a2fef8c8b0 100644 --- a/apps/server/src/cloud/environmentKeys.test.ts +++ b/apps/server/src/cloud/environmentKeys.test.ts @@ -66,7 +66,9 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it Effect.flatMap(() => Effect.fail( new ServerSecretStore.SecretStorePersistError({ - resource: "environment signing key pair", + operation: "create", + secretName: "cloud-link-ed25519-key-pair", + secretPath: "cloud-link-ed25519-key-pair.bin", cause: PlatformError.systemError({ _tag: "AlreadyExists", module: "FileSystem", @@ -87,4 +89,24 @@ 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); + }), + ); }); diff --git a/apps/server/src/cloud/environmentKeys.ts b/apps/server/src/cloud/environmentKeys.ts index 1d0cde91bf..3e20983aef 100644 --- a/apps/server/src/cloud/environmentKeys.ts +++ b/apps/server/src/cloud/environmentKeys.ts @@ -27,17 +27,6 @@ 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"], ) { @@ -46,7 +35,13 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* ( return Option.none(); } const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe( - Effect.mapError(keyPairDecodeError), + Effect.mapError( + (cause) => + new ServerSecretStore.SecretStoreDecodeError({ + secretName: CLOUD_LINK_KEY_PAIR, + cause, + }), + ), ); return Option.some(decoded); }); @@ -56,22 +51,34 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio keyPair: EnvironmentKeyPair, ) { const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe( - Effect.mapError(keyPairEncodeError), + Effect.mapError( + (cause) => + new ServerSecretStore.SecretStoreEncodeError({ + secretName: CLOUD_LINK_KEY_PAIR, + cause, + }), + ), ); return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe( Effect.as(keyPair), - 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), - ), + 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), + }), ); }); diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index ed2e5a4cf7..0075f70a79 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -17,7 +17,9 @@ import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayR const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") => new ServerSecretStore.SecretStorePersistError({ - resource: "cloud replay guard", + operation: "create", + secretName: "cloud replay guard", + secretPath: "cloud-replay-guard.bin", cause: PlatformError.systemError({ _tag: tag, module: "FileSystem",