Structure server secret store errors

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-20 02:09:59 -07:00
1 parent 4ec16654a6
commit 47c042422c
6 files changed
+224 -93

No files matched your search

+46 -3
View File
@@ -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())),
+117 -62
View File
@@ -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>()(
"SecretStoreSecureError",
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
"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>()(
"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>()(
"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>()(
"SecretStoreTemporaryPathError",
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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<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 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 getOrCreateRandom: (
name: string,
bytes: number,
) => Effect.Effect<Uint8Array, SecretStoreError>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
) => Effect.Effect<
Uint8Array,
| SecretStoreReadError
| SecretStoreRandomGenerationError
| SecretStorePersistError
| SecretStoreConcurrentReadError
>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
}
>()("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,
+3 -1
View File
@@ -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",
+23 -1
View File
@@ -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);
}),
);
});
+32 -25
View File
@@ -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<EnvironmentKeyPair>();
}
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),
}),
);
});
+3 -1
View File
@@ -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",