Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions apps/server/src/provider/Drivers/ClaudeCredential.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import {
HttpClient,
HttpClientError,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";

import { claudeOAuthTokenFromEnvironment, verifyClaudeOAuthToken } from "./ClaudeCredential.ts";

function httpClientLayer(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, respond(request))),
),
);
}

const transportFailureLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.fail(
new HttpClientError.HttpClientError({
reason: new HttpClientError.TransportError({ request, cause: new Error("offline") }),
}),
),
),
);

describe("claudeOAuthTokenFromEnvironment", () => {
it("returns the configured token", () => {
assert.strictEqual(
claudeOAuthTokenFromEnvironment({ CLAUDE_CODE_OAUTH_TOKEN: "sk-ant-oat01-test" }),
"sk-ant-oat01-test",
);
});

it("treats blank and missing values alike", () => {
assert.strictEqual(claudeOAuthTokenFromEnvironment({}), undefined);
assert.strictEqual(
claudeOAuthTokenFromEnvironment({ CLAUDE_CODE_OAUTH_TOKEN: " " }),
undefined,
);
});

it("trims surrounding whitespace so a copy-pasted token still matches", () => {
assert.strictEqual(
claudeOAuthTokenFromEnvironment({ CLAUDE_CODE_OAUTH_TOKEN: " sk-ant-oat01-test\n" }),
"sk-ant-oat01-test",
);
});
});

describe("verifyClaudeOAuthToken", () => {
it.effect("reports a live token and sends bearer auth", () =>
Effect.gen(function* () {
let seen: HttpClientRequest.HttpClientRequest | undefined;
const verdict = yield* verifyClaudeOAuthToken("sk-ant-oat01-test").pipe(
Effect.provide(
httpClientLayer((request) => {
seen = request;
return Response.json({ data: [] });
}),
),
);
assert.strictEqual(verdict, "live");
assert.strictEqual(seen?.headers["authorization"], "Bearer sk-ant-oat01-test");
assert.strictEqual(seen?.headers["anthropic-version"], "2023-06-01");
}),
);

it.effect("never asks Anthropic about an unresolved secret reference", () =>
Effect.gen(function* () {
// Nothing resolved this into a credential, so a 401 would be Anthropic
// answering a question about a string that was never a token.
let requests = 0;
const verdict = yield* verifyClaudeOAuthToken("op://Vault/item/credential").pipe(
Effect.provide(
httpClientLayer(() => {
requests += 1;
return new Response("no", { status: 401 });
}),
),
);
assert.strictEqual(verdict, "unknown");
assert.strictEqual(requests, 0);
}),
);

it.effect("never asks Anthropic about a value that is not a credential", () =>
Effect.gen(function* () {
let requests = 0;
const verdict = yield* verifyClaudeOAuthToken("${MY_TOKEN}").pipe(
Effect.provide(
httpClientLayer(() => {
requests += 1;
return new Response("no", { status: 401 });
}),
),
);
assert.strictEqual(verdict, "unknown");
assert.strictEqual(requests, 0);
}),
);

it.effect("never asks Anthropic about a placeholder wearing the credential prefix", () =>
Effect.gen(function* () {
let requests = 0;
const verdict = yield* verifyClaudeOAuthToken("sk-ant-oat01-${MY_TOKEN}").pipe(
Effect.provide(
httpClientLayer(() => {
requests += 1;
return new Response("no", { status: 401 });
}),
),
);
assert.strictEqual(verdict, "unknown");
assert.strictEqual(requests, 0);
}),
);

it.effect("reports a rejected token on 401", () =>
Effect.gen(function* () {
const verdict = yield* verifyClaudeOAuthToken("sk-ant-oat01-stale").pipe(
Effect.provide(httpClientLayer(() => new Response("unauthorized", { status: 401 }))),
);
assert.strictEqual(verdict, "rejected");
}),
);

it.effect("stays unknown when the account merely lacks scope", () =>
Effect.gen(function* () {
const verdict = yield* verifyClaudeOAuthToken("sk-ant-oat01-scoped-out").pipe(
Effect.provide(httpClientLayer(() => new Response("forbidden", { status: 403 }))),
);
assert.strictEqual(verdict, "unknown");
}),
);

it.effect("stays unknown when Anthropic is down", () =>
Effect.gen(function* () {
const verdict = yield* verifyClaudeOAuthToken("sk-ant-oat01-fine").pipe(
Effect.provide(httpClientLayer(() => new Response("boom", { status: 503 }))),
);
assert.strictEqual(verdict, "unknown");
}),
);

it.effect("stays unknown when the request never leaves the machine", () =>
Effect.gen(function* () {
const verdict = yield* verifyClaudeOAuthToken("sk-ant-oat01-fine").pipe(
Effect.provide(transportFailureLayer),
);
assert.strictEqual(verdict, "unknown");
}),
);
});
93 changes: 93 additions & 0 deletions apps/server/src/provider/Drivers/ClaudeCredential.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* ClaudeCredential: liveness check for a configured Claude OAuth token.
*
* The capability probe reports which credential the CLI *found*, never whether
* Anthropic still honours it. An expired or revoked setup token still reads as
* `tokenSource: "CLAUDE_CODE_OAUTH_TOKEN"`, so Settings would keep claiming the
* provider is authenticated right up until a turn fails. This module closes
* that gap with one cheap authenticated GET.
*
* `GET /v1/models` is used because it is the only first-party endpoint that
* accepts the token, costs no message quota, and answers the only question
* worth asking: does Anthropic still accept this credential.
*
* Only a value that looks like an Anthropic credential is ever sent. Anything
* else is a question for someone other than Anthropic, and a `401` earned by an
* unresolved secret reference or a placeholder would blame the token for a
* problem that is not the token's.
*
* @module provider/Drivers/ClaudeCredential
*/
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";

/**
* Result of asking Anthropic about a token.
*
* `unknown` is the deliberate catch-all: a proxy, an outage, or a captive
* network must never sign a working install out of Settings, so only an
* explicit rejection is treated as one.
*/
export type ClaudeCredentialVerdict = "live" | "rejected" | "unknown";

const ANTHROPIC_MODELS_URL = "https://api.anthropic.com/v1/models?limit=1";
/**
* `sk-ant-` is shared by Anthropic setup tokens (`sk-ant-oat01-`) and API keys
* (`sk-ant-api03-`). The tail is spelled out because the prefix alone accepts
* `sk-ant-oat01-${MY_TOKEN}`, and a placeholder that happens to carry the
* prefix is still a placeholder. Anything outside the character set key
* material is written with is treated as not a credential, which costs at most
* an unknown verdict and never a wrong one.
*/
const ANTHROPIC_CREDENTIAL = /^sk-ant-[A-Za-z0-9._~+/=-]+$/;
const ANTHROPIC_VERSION_HEADER = "2023-06-01";
const VERIFY_TIMEOUT = Duration.seconds(10);

/**
* The OAuth token a Claude instance was configured with, if any.
*
* Reads the same variable the CLI itself reads, so an instance whose
* environment carries an `op://` reference is checked with whatever that
* reference resolved to.
*/
export function claudeOAuthTokenFromEnvironment(
environment: NodeJS.ProcessEnv,
): string | undefined {
const token = environment["CLAUDE_CODE_OAUTH_TOKEN"]?.trim();
return token ? token : undefined;
}

/**
* Ask Anthropic whether it still accepts `token`.
*
* Never fails: a value that is not an Anthropic credential, transport errors,
* timeouts, and every non-401 status all collapse to `unknown` so the caller
* can leave the existing status alone.
*/
export const verifyClaudeOAuthToken = Effect.fn("verifyClaudeOAuthToken")(function* (
token: string,
): Effect.fn.Return<ClaudeCredentialVerdict, never, HttpClient.HttpClient> {
if (!ANTHROPIC_CREDENTIAL.test(token)) {
return "unknown";
}
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.get(ANTHROPIC_MODELS_URL).pipe(
HttpClientRequest.setHeader("authorization", `Bearer ${token}`),
HttpClientRequest.setHeader("anthropic-version", ANTHROPIC_VERSION_HEADER),
HttpClientRequest.setHeader("accept", "application/json"),
);
const response = yield* client.execute(request).pipe(
Effect.timeoutOption(VERIFY_TIMEOUT),
Effect.orElseSucceed(() => Option.none()),
);
if (Option.isNone(response)) {
return "unknown";
}
const { status } = response.value;
if (status === 401) {
return "rejected";
}
return status >= 200 && status < 300 ? "live" : "unknown";
Comment thread
yordis marked this conversation as resolved.
});
1 change: 1 addition & 0 deletions apps/server/src/provider/Drivers/ClaudeDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.provideService(Path.Path, path),
);

Expand Down
54 changes: 53 additions & 1 deletion apps/server/src/provider/Layers/ClaudeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Result from "effect/Result";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
createModelCapabilities,
Expand Down Expand Up @@ -39,6 +40,10 @@ import {
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import {
claudeOAuthTokenFromEnvironment,
verifyClaudeOAuthToken,
} from "../Drivers/ClaudeCredential.ts";
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
Expand Down Expand Up @@ -608,6 +613,31 @@ export function claudeAuthStatus(
: "unauthenticated";
}

/** `tokenSource` the SDK reports when the CLI took its token from the environment. */
const CLAUDE_OAUTH_TOKEN_SOURCE = "CLAUDE_CODE_OAUTH_TOKEN";

/**
* Whether Anthropic has stopped accepting the token this instance was given.
*
* Gated on the CLI having actually chosen the environment token, so an install
* that authenticates some other way is never judged by a variable it ignores.
* Anything short of an outright rejection answers `false`: an offline machine
* should show a stale status, not a wrong one.
*/
const isConfiguredClaudeTokenRejected = Effect.fn("isConfiguredClaudeTokenRejected")(function* (
tokenSource: string | undefined,
environment: NodeJS.ProcessEnv,
): Effect.fn.Return<boolean, never, HttpClient.HttpClient> {
if (tokenSource !== CLAUDE_OAUTH_TOKEN_SOURCE) {
return false;
}
const token = claudeOAuthTokenFromEnvironment(environment);
if (!token) {
return false;
}
return (yield* verifyClaudeOAuthToken(token)) === "rejected";
});

// ── SDK capability probe ────────────────────────────────────────────

// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the
Expand Down Expand Up @@ -850,7 +880,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
> {
const resolvedEnvironment = environment ?? process.env;
const checkedAt = DateTime.formatIso(yield* DateTime.now);
Expand Down Expand Up @@ -1001,6 +1034,25 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}

if (yield* isConfiguredClaudeTokenRejected(capabilities.tokenSource, resolvedEnvironment)) {
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
skills,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unauthenticated" },
message:
"Anthropic rejected this instance's CLAUDE_CODE_OAUTH_TOKEN. Generate a fresh token with `claude setup-token`.",
},
});
}

const authMetadata =
claudeAuthMetadata({
subscriptionType: capabilities.subscriptionType,
Expand Down
Loading
Loading