[codex] align server auth Effect services (#3180)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and GitHub committed 2026-06-20 01:34:52 -07:00
1 parent b19fc1b87b
commit 97e5cd3bf7
22 files changed
+1436 -766

No files matched your search

@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
import * as ServerConfig from "../config.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
const makeServerSecretStoreLayer = () =>
@@ -65,8 +65,8 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
}).pipe(
Effect.flatMap(() =>
Effect.fail(
new ServerSecretStore.SecretStoreError({
message: "Concurrent keypair creation won.",
new ServerSecretStore.SecretStorePersistError({
resource: "environment signing key pair",
cause: PlatformError.systemError({
_tag: "AlreadyExists",
module: "FileSystem",
@@ -79,7 +79,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
),
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
} satisfies ServerSecretStore.ServerSecretStoreShape;
} satisfies ServerSecretStore.ServerSecretStore["Service"];
assert.deepEqual(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore), {
privateKey: "winner-private",
+17 -18
View File
@@ -27,47 +27,46 @@ function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
const keyPairPersistenceError = (message: string, cause?: unknown) =>
new ServerSecretStore.SecretStoreError({ message, cause });
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.ServerSecretStoreShape,
secrets: ServerSecretStore.ServerSecretStore["Service"],
) {
const encoded = yield* secrets.get(CLOUD_LINK_KEY_PAIR);
if (Option.isNone(encoded)) {
return Option.none<EnvironmentKeyPair>();
}
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
Effect.mapError((cause) =>
keyPairPersistenceError("Failed to decode environment signing key pair.", cause),
),
Effect.mapError(keyPairDecodeError),
);
return Option.some(decoded);
});
const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(function* (
secrets: ServerSecretStore.ServerSecretStoreShape,
secrets: ServerSecretStore.ServerSecretStore["Service"],
keyPair: EnvironmentKeyPair,
) {
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
Effect.mapError((cause) =>
keyPairPersistenceError("Failed to encode environment signing key pair.", cause),
),
Effect.mapError(keyPairEncodeError),
);
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
Effect.as(keyPair),
Effect.catchTag("SecretStoreError", (error) =>
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
keyPairPersistenceError(
"Failed to read environment signing key pair after concurrent creation.",
),
),
onNone: () => Effect.fail(keyPairConcurrentReadError()),
}),
),
)
@@ -77,7 +76,7 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
});
export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function* (
secrets: ServerSecretStore.ServerSecretStoreShape,
secrets: ServerSecretStore.ServerSecretStore["Service"],
) {
const existing = yield* readEnvironmentKeyPair(secrets);
if (Option.isSome(existing)) {
+26 -2
View File
@@ -16,8 +16,8 @@ import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStoreError({
message: "Failed to persist cloud replay guard.",
new ServerSecretStore.SecretStorePersistError({
resource: "cloud replay guard",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -40,6 +40,30 @@ function makeSecretStore(
};
}
it("preserves messages surfaced by cloud 500 responses", () => {
const cause = new Error("cloud operation failed");
expect([
new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
]).toEqual([
"Could not verify the linked cloud account.",
"Could not read the linked cloud account.",
"Cloud linked user is not installed for this environment.",
"Failed to sign cloud link JWT.",
"Cloud mint public key is not installed for this environment.",
"Cloud relay issuer is not installed for this environment.",
"Failed to sign cloud health JWT.",
"Failed to sign cloud mint JWT.",
]);
});
describe("consumeCloudReplayGuards", () => {
it.effect("reports already-created guards as replay conflicts", () =>
Effect.gen(function* () {
+113 -119
View File
@@ -68,7 +68,7 @@ import {
RELAY_URL_SECRET,
} from "./config.ts";
import { relayUrlConfig } from "./publicConfig.ts";
import * as CliState from "./CliState.ts";
import { setCliDesiredCloudLink } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
import { traceRelayRequest } from "./traceRelayRequest.ts";
@@ -98,7 +98,7 @@ const failEnvironmentCloudInternalError =
);
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
failEnvironmentCloudInternalError(error.message)(error.cause);
failEnvironmentCloudInternalError(error.message)(error);
const requireRelayUrl = relayUrlConfig.pipe(
Effect.mapError(
@@ -126,7 +126,7 @@ export function consumeCloudReplayGuards(input: {
input.names.map((name) =>
input.secrets.create(name, input.value).pipe(
Effect.as(true),
Effect.catchTag("SecretStoreError", (error) =>
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
@@ -211,8 +211,7 @@ function validateLinkedCloudUser(input: {
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Could not verify the linked cloud account.",
new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({
cause,
}),
),
@@ -239,19 +238,14 @@ function readInstalledCloudUserId(
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Could not read the linked cloud account.",
new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({
cause,
}),
),
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud linked user is not installed for this environment.",
}),
),
: Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})),
),
);
}
@@ -394,8 +388,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud link JWT.",
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
cause,
}),
),
@@ -416,15 +409,17 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
yield* appendCloudCredentialResponseHeaders;
return proof satisfies RelayEnvironmentLinkProof;
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
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."),
),
Effect.catchTags({
PlatformError: failEnvironmentCloudInternalError("Could not generate environment link proof."),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not generate environment link proof.",
),
}),
);
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
@@ -477,17 +472,17 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
yield* requireEnvironmentScope(AuthRelayWriteScope);
return yield* applyCloudRelayConfig(dependencies, payload);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
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."),
),
Effect.catchTags({
SchemaError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist environment relay configuration.",
),
}),
);
const relayClientRequest = <A>(
@@ -581,7 +576,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
},
schema: RelayEnvironmentLinkResponse,
});
yield* CliState.setCliDesiredCloudLink(true);
yield* setCliDesiredCloudLink(true);
return yield* applyCloudRelayConfig(dependencies, {
relayUrl,
relayIssuer: link.relayIssuer,
@@ -591,15 +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({
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
CloudCliCredentialReadError: failCloudCliTokenManagerError,
CloudCliAuthorizationError: failCloudCliTokenManagerError,
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Connect link state.",
),
}),
);
@@ -637,8 +633,8 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
yield* requireEnvironmentScope(AuthRelayReadScope);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTag(
"SecretStoreError",
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
),
);
@@ -659,11 +655,11 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
],
{ concurrency: 7 },
);
yield* CliState.setCliDesiredCloudLink(false);
yield* setCliDesiredCloudLink(false);
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
},
Effect.catchTag(
"SecretStoreError",
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
),
);
@@ -680,42 +676,40 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTag(
"SecretStoreError",
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
),
);
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {
const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud mint public key is not installed for this environment.",
}),
),
),
);
const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets.get(RELAY_URL_SECRET).pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud relay issuer is not installed for this environment.",
}),
),
),
),
),
);
const cloudMintPublicKey = yield* dependencies.secrets
.get(CLOUD_MINT_PUBLIC_KEY)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
),
);
const relayIssuer = yield* dependencies.secrets
.get(RELAY_ISSUER_SECRET)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets
.get(RELAY_URL_SECRET)
.pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
),
),
),
);
const environmentId = yield* dependencies.environment.getEnvironmentId;
const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
const now = yield* DateTime.now;
@@ -777,8 +771,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud health JWT.",
new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
cause,
}),
),
@@ -794,45 +787,47 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
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."),
),
Effect.catchTags({
PlatformError: failEnvironmentCloudInternalError("Could not answer cloud health request."),
SecretStoreError: failEnvironmentCloudInternalError("Could not answer cloud health request."),
}),
);
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {
const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud mint public key is not installed for this environment.",
}),
),
),
);
const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets.get(RELAY_URL_SECRET).pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud relay issuer is not installed for this environment.",
}),
),
),
),
),
);
const cloudMintPublicKey = yield* dependencies.secrets
.get(CLOUD_MINT_PUBLIC_KEY)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),
),
);
const relayIssuer = yield* dependencies.secrets
.get(RELAY_ISSUER_SECRET)
.pipe(
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets
.get(RELAY_URL_SECRET)
.pipe(
Effect.flatMap((fallbackBytes) =>
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),
),
),
),
);
const environmentId = yield* dependencies.environment.getEnvironmentId;
const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);
const now = yield* DateTime.now;
@@ -899,8 +894,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud mint JWT.",
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
cause,
}),
),
@@ -914,17 +908,17 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
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."),
),
Effect.catchTags({
PlatformError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not issue cloud connection credential.",
),
}),
);
export const connectHttpApiLayer = HttpApiBuilder.group(