An open-source, faster Devin alternative
TypeScript
Harden CLI login recovery and edge limits
Igor Zalutski691cd1a293c8
diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.tsindex c0143a16..3b1f6849 100644--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts@@ -112,6 +112,12 @@ function testEnv(db = new FakeDB()): Env {OPENCOMPUTER_DB: db,SESSIONS_KV: {},CREDIT_ACCOUNT: {},+ CLI_AUTH_START_RATE_LIMIT: {+ limit: vi.fn(async () => ({ success: true })),+ },+ CLI_AUTH_EXCHANGE_RATE_LIMIT: {+ limit: vi.fn(async () => ({ success: true })),+ },SESSION_JWT_SECRET: "test-session-secret",WORKOS_API_KEY: "sk_test",WORKOS_CLIENT_ID: "client_test",@@ -134,6 +140,7 @@ function request(path: string, init?: RequestInit): Request {}afterEach(() => {+ vi.useRealTimers();vi.unstubAllGlobals();vi.restoreAllMocks();});@@ -232,6 +239,99 @@ describe("CLI device authorization edge contract", () => {expect(providerFetch).not.toHaveBeenCalled();});+ it("rate-limits start and exchange independently before contacting WorkOS", async () => {+ const providerFetch = vi.fn();+ vi.stubGlobal("fetch", providerFetch);+ const env = testEnv();+ env.CLI_AUTH_START_RATE_LIMIT = {+ limit: vi.fn(async ({ key }) => ({ success: key !== "203.0.113.10" })),+ };++ const start = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ headers: { "cf-connecting-ip": "203.0.113.10" },+ }), env, ctx);+ expect(start.status).toBe(429);+ expect(start.headers.get("retry-after")).toBe("60");+ expect(await start.json()).toEqual({ error: "rate_limited" });++ env.CLI_AUTH_START_RATE_LIMIT = {+ limit: vi.fn(async () => ({ success: true })),+ };+ env.CLI_AUTH_EXCHANGE_RATE_LIMIT = {+ limit: vi.fn(async ({ key }) => ({ success: key !== "203.0.113.10" })),+ };+ const exchange = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "cf-connecting-ip": "203.0.113.10",+ },+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI" }),+ }), env, ctx);+ expect(exchange.status).toBe(429);+ expect(exchange.headers.get("retry-after")).toBe("60");+ expect(await exchange.json()).toEqual({ error: "rate_limited" });+ expect(providerFetch).not.toHaveBeenCalled();+ });++ it("fails closed when the CLI auth limiter is unavailable", async () => {+ const providerFetch = vi.fn();+ vi.stubGlobal("fetch", providerFetch);+ const env = testEnv();+ env.CLI_AUTH_START_RATE_LIMIT = {+ limit: vi.fn(async () => {+ throw new Error("limiter unavailable");+ }),+ };+ const resp = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ }), env, ctx);+ expect(resp.status).toBe(503);+ expect(await resp.json()).toEqual({ error: "cli_login_unavailable" });+ expect(providerFetch).not.toHaveBeenCalled();+ });++ it("bounds a stalled WorkOS request and maps the timeout to 503", async () => {+ vi.useFakeTimers();+ const providerFetch = vi.fn(async (_url: string, init?: RequestInit) =>+ await new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted")));+ })+ );+ vi.stubGlobal("fetch", providerFetch);++ const responsePromise = worker.fetch(request("/auth/cli/device", {+ method: "POST",+ }), testEnv(), ctx);+ await vi.advanceTimersByTimeAsync(10_000);+ const resp = await responsePromise;+ expect(resp.status).toBe(503);+ expect(await resp.json()).toEqual({ error: "auth_provider_unavailable" });+ expect(providerFetch.mock.calls[0][1]?.signal?.aborted).toBe(true);+ });++ it("keeps the WorkOS deadline active while reading the provider body", async () => {+ vi.useFakeTimers();+ const providerFetch = vi.fn(async (_url: string, init?: RequestInit) =>+ new Response(new ReadableStream({+ start(controller) {+ init?.signal?.addEventListener("abort", () => controller.error(new Error("aborted")));+ },+ }))+ );+ vi.stubGlobal("fetch", providerFetch);++ const responsePromise = worker.fetch(request("/auth/cli/device", {+ method: "POST",+ }), testEnv(), ctx);+ await vi.advanceTimersByTimeAsync(10_000);+ const resp = await responsePromise;+ expect(resp.status).toBe(503);+ expect(await resp.json()).toEqual({ error: "auth_provider_unavailable" });+ expect(providerFetch.mock.calls[0][1]?.signal?.aborted).toBe(true);+ });+it.each([["authorization_pending", 202, { status: "authorization_pending", retry_after: 5 }],["slow_down", 202, { status: "authorization_pending", retry_after: 10 }],@@ -309,6 +409,23 @@ describe("CLI device authorization edge contract", () => {expect(logs).not.toContain("[email protected]");});+ it("owns the empty CLI credential-name fallback at the edge", async () => {+ const db = new FakeDB();+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },+ })));+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ device_code: "opaque", credential_name: "" }),+ }), testEnv(db), ctx);+ expect(resp.status).toBe(200);+ const body = await resp.json<{ credential: { name: string } }>();+ expect(body.credential.name).toBe("oc CLI");+ const insert = db.executed.find((entry) => entry.sql.includes("INSERT INTO api_keys"));+ expect(insert?.args[5]).toBe("oc CLI");+ });+it("selects a WorkOS-mapped membership before the personal fallback", async () => {const mappedOrgID = "33333333-3333-4333-8333-333333333333";const db = new FakeDB([diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 025df5f3..b9064ccc 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -46,6 +46,11 @@ export interface Env extends DashboardEnv {CF_ADMIN_SECRET: string;STRIPE_WEBHOOK_SECRET: string;EVENT_SECRET: string;+ // Coarse distributed abuse limits for the two unauthenticated WorkOS device+ // endpoints. These are separate because one login normally polls exchange+ // several times after a single start request.+ CLI_AUTH_START_RATE_LIMIT: RateLimit;+ CLI_AUTH_EXCHANGE_RATE_LIMIT: RateLimit;// Dedicated HMAC secret for the Sessions API's minimal Agent Hook exposure// alert. It is intentionally not shared with other internal routes.OC_SECURITY_NOTIFICATION_SECRET?: string;@@ -1325,8 +1330,10 @@ async function provisionWorkOSIdentity(try {await createAutumnCustomer(env, { id: orgID, name: orgName, email: profile.email });provider = "autumn";- } catch (e) {- console.error(`signup: autumn customer create failed for ${orgID}, falling back to legacy`, e);+ } catch {+ // The provider response can echo signup PII. Preserve the actionable+ // org/class without logging its raw error body.+ console.error(`signup: autumn customer create failed for ${orgID}, falling back to legacy`);}}await env.OPENCOMPUTER_DB.prepare(@@ -1445,6 +1452,8 @@ const CLI_AUTH_MAX_DEVICE_CODE = 2048;const CLI_AUTH_MAX_CREDENTIAL_NAME = 100;const CLI_AUTH_DEFAULT_RETRY_SEC = 5;const CLI_AUTH_MAX_PROVIDER_BODY_BYTES = 64 * 1024;+const CLI_AUTH_PROVIDER_TIMEOUT_MS = 10_000;+const CLI_AUTH_RATE_LIMIT_RETRY_SEC = 60;function cliAuthJSON(body: unknown, status = 200): Response {return new Response(JSON.stringify(body), {@@ -1460,6 +1469,12 @@ function cliAuthError(error: string, status: number): Response {return cliAuthJSON({ error }, status);}+function cliAuthRateLimitError(): Response {+ const response = cliAuthError("rate_limited", 429);+ response.headers.set("retry-after", String(CLI_AUTH_RATE_LIMIT_RETRY_SEC));+ return response;+}+function recordCLIAuth(event: "cli_auth_start" | "cli_auth_exchange" | "cli_auth_revoke",requestID: string,@@ -1494,10 +1509,47 @@ function boundedInteger(value: unknown, min: number, max: number): value is numbfunction normalizeCLICredentialName(value: unknown): string | null {if (typeof value !== "string" || /[\u0000-\u001f\u007f]/.test(value)) return null;const normalized = value.trim().replace(/\s+/g, " ");- if (!normalized || normalized.length > CLI_AUTH_MAX_CREDENTIAL_NAME) return null;+ if (!normalized) return "oc CLI";+ if (normalized.length > CLI_AUTH_MAX_CREDENTIAL_NAME) return null;return normalized;}+function cliAuthCallerKey(req: Request): string {+ const value = req.headers.get("CF-Connecting-IP")?.trim();+ return value && value.length <= 64 ? value : "unknown";+}++async function consumeCLIAuthRateLimit(+ req: Request,+ limiter: RateLimit | undefined,+): Promise<"allowed" | "limited" | "unavailable"> {+ if (!limiter) return "unavailable";+ try {+ const result = await limiter.limit({ key: cliAuthCallerKey(req) });+ return result.success ? "allowed" : "limited";+ } catch {+ return "unavailable";+ }+}++async function fetchCLIAuthProviderJSON(+ input: string,+ init: RequestInit,+): Promise<{ response: Response; body: Record<string, unknown> | null }> {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), CLI_AUTH_PROVIDER_TIMEOUT_MS);+ try {+ const response = await fetch(input, { ...init, signal: controller.signal });+ const body = await parseProviderJSON(response);+ if (controller.signal.aborted) {+ throw new DOMException("WorkOS request timed out", "AbortError");+ }+ return { response, body };+ } finally {+ clearTimeout(timeout);+ }+}+async function readSmallJSONObject(req: Request,): Promise<Record<string, unknown> | null> {@@ -1602,18 +1654,29 @@ async function authCLIStart(req: Request, env: Env): Promise<Response> {if (!env.WORKOS_CLIENT_ID) {return finish(cliAuthError("cli_login_unavailable", 503), "configuration_error");}+ const rateLimit = await consumeCLIAuthRateLimit(req, env.CLI_AUTH_START_RATE_LIMIT);+ if (rateLimit === "limited") {+ return finish(cliAuthRateLimitError(), "rate_limited");+ }+ if (rateLimit === "unavailable") {+ return finish(cliAuthError("cli_login_unavailable", 503), "configuration_error");+ }if (await hasRequestBody(req)) {return finish(cliAuthError("invalid_request", 400), "invalid_request");}let providerResp: Response;+ let bodyJSON: Record<string, unknown> | null;try {- providerResp = await fetch("https://api.workos.com/user_management/authorize/device", {- method: "POST",- headers: { "content-type": "application/x-www-form-urlencoded" },- body: new URLSearchParams({ client_id: env.WORKOS_CLIENT_ID }).toString(),- redirect: "error",- });+ ({ response: providerResp, body: bodyJSON } = await fetchCLIAuthProviderJSON(+ "https://api.workos.com/user_management/authorize/device",+ {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ client_id: env.WORKOS_CLIENT_ID }).toString(),+ redirect: "error",+ },+ ));} catch {return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");}@@ -1621,7 +1684,6 @@ async function authCLIStart(req: Request, env: Env): Promise<Response> {return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");}- const bodyJSON = await parseProviderJSON(providerResp);if (!bodyJSON ||typeof bodyJSON.device_code !== "string" ||@@ -1672,6 +1734,13 @@ async function authCLIExchange(req: Request, env: Env): Promise<Response> {if (!env.WORKOS_CLIENT_ID) {return finish(cliAuthError("cli_login_unavailable", 503), "configuration_error");}+ const rateLimit = await consumeCLIAuthRateLimit(req, env.CLI_AUTH_EXCHANGE_RATE_LIMIT);+ if (rateLimit === "limited") {+ return finish(cliAuthRateLimitError(), "rate_limited");+ }+ if (rateLimit === "unavailable") {+ return finish(cliAuthError("cli_login_unavailable", 503), "configuration_error");+ }const body = await readSmallJSONObject(req);if (!body ||@@ -1690,22 +1759,25 @@ async function authCLIExchange(req: Request, env: Env): Promise<Response> {}let providerResp: Response;+ let providerBody: Record<string, unknown> | null;try {- providerResp = await fetch("https://api.workos.com/user_management/authenticate", {- method: "POST",- headers: { "content-type": "application/x-www-form-urlencoded" },- body: new URLSearchParams({- grant_type: "urn:ietf:params:oauth:grant-type:device_code",- device_code: body.device_code,- client_id: env.WORKOS_CLIENT_ID,- }).toString(),- redirect: "error",- });+ ({ response: providerResp, body: providerBody } = await fetchCLIAuthProviderJSON(+ "https://api.workos.com/user_management/authenticate",+ {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",+ device_code: body.device_code,+ client_id: env.WORKOS_CLIENT_ID,+ }).toString(),+ redirect: "error",+ },+ ));} catch {return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");}- const providerBody = await parseProviderJSON(providerResp);if (!providerResp.ok) {const code = providerErrorCode(providerBody);if (code === "authorization_pending") {@@ -2756,6 +2828,14 @@ export default {if (path === "/api/whoami" && req.method === "GET") {const caller = await authenticate(req, env);if (!caller) return json({ error: "missing or invalid API key" }, 401);+ if (caller.scope) {+ return json({+ org_id: caller.orgID,+ user_id: caller.userID,+ email: null,+ org_name: null,+ });+ }const identity = await env.OPENCOMPUTER_DB.prepare(`SELECT o.name AS org_name, u.email AS emailFROM orgs odiff --git a/cloudflare-workers/api-edge/wrangler.igor-dev.toml b/cloudflare-workers/api-edge/wrangler.igor-dev.tomlindex e972d0f6..52353dba 100644--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml@@ -45,6 +45,22 @@ database_name = "opencomputer-igor-dev"database_id = "d5bbb12a-0491-4a95-9d7d-32ed8c3ce15d"migrations_dir = "migrations"+[[ratelimits]]+name = "CLI_AUTH_START_RATE_LIMIT"+namespace_id = "2026072411"++ [ratelimits.simple]+ limit = 30+ period = 60++[[ratelimits]]+name = "CLI_AUTH_EXCHANGE_RATE_LIMIT"+namespace_id = "2026072412"++ [ratelimits.simple]+ limit = 180+ period = 60+# CreditAccount DO is self-hosted by this worker (script_name defaults to self).[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 91c19ad4..1471d0ed 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -37,6 +37,22 @@ migrations_dir = "migrations"binding = "SESSIONS_KV"id = "b496f905ce634f94b6ac1d4f619825e0"+[[ratelimits]]+name = "CLI_AUTH_START_RATE_LIMIT"+namespace_id = "2026072401"++ [ratelimits.simple]+ limit = 30+ period = 60++[[ratelimits]]+name = "CLI_AUTH_EXCHANGE_RATE_LIMIT"+namespace_id = "2026072402"++ [ratelimits.simple]+ limit = 180+ period = 60+[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"class_name = "CreditAccount"diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 7a70ea3b..ccb513d3 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -65,6 +65,22 @@ migrations_dir = "migrations"binding = "SESSIONS_KV"id = "694f22abd551461da4ad99839f161b2f"+[[ratelimits]]+name = "CLI_AUTH_START_RATE_LIMIT"+namespace_id = "2026072421"++ [ratelimits.simple]+ limit = 30+ period = 60++[[ratelimits]]+name = "CLI_AUTH_EXCHANGE_RATE_LIMIT"+namespace_id = "2026072422"++ [ratelimits.simple]+ limit = 180+ period = 60+[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"class_name = "CreditAccount"diff --git a/cmd/oc/internal/commands/auth.go b/cmd/oc/internal/commands/auth.goindex f3b75bb6..3d18be1d 100644--- a/cmd/oc/internal/commands/auth.go+++ b/cmd/oc/internal/commands/auth.go@@ -7,6 +7,7 @@ import ("errors""fmt""io"+ "net""net/http""net/url""os"@@ -271,6 +272,8 @@ func authAPIError(status int, code string) error {action = "Authorization completed, but the OpenComputer account could not be prepared; run `oc login` again."case "credential_creation_failed":action = "Authorization completed, but the CLI credential could not be created; run `oc login` again."+ case "rate_limited":+ action = "Too many login attempts were made from this network; wait a minute and retry."}if code == "" {code = "authentication_failed"@@ -362,6 +365,29 @@ func identityAsLoginResult(identity loginIdentity, metadata *config.LoginMetadatreturn result}+func loginAPIForSavedCredential(fileCfg config.Config, fallback string) string {+ if fileCfg.Login != nil && fileCfg.Login.APIURL != "" {+ return newCLIAuthHTTP(fileCfg.Login.APIURL).baseURL+ }+ if fileCfg.APIURL != "" {+ return newCLIAuthHTTP(fileCfg.APIURL).baseURL+ }+ return newCLIAuthHTTP(fallback).baseURL+}++func insecureRemoteAPIURL(rawURL string) bool {+ parsed, err := url.Parse(rawURL)+ if err != nil || parsed.Scheme != "http" {+ return false+ }+ host := parsed.Hostname()+ if strings.EqualFold(host, "localhost") {+ return false+ }+ ip := net.ParseIP(host)+ return ip == nil || !ip.IsLoopback()+}+func runLogin(cmd *cobra.Command, force, noBrowser bool) error {source := config.EffectiveCredentialSource(cmd)if source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag {@@ -374,6 +400,15 @@ func runLogin(cmd *cobra.Command, force, noBrowser bool) error {resolved.APIURL = config.DefaultAPIURL}authClient := newCLIAuthHTTP(resolved.APIURL)+ loginAPI := authClient.baseURL+ errOut := cmd.ErrOrStderr()+ if insecureRemoteAPIURL(loginAPI) {+ fmt.Fprintf(+ errOut,+ "Warning: %s is not HTTPS; login credentials will be sent over an unencrypted connection.\n",+ oneLine(loginAPI),+ )+ }var oldManagedKey stringvar oldManagedAPI string@@ -383,31 +418,48 @@ func runLogin(cmd *cobra.Command, force, noBrowser bool) error {return errors.New("a manually configured API key is already saved; use `oc login --force` to replace it locally")}} else {- oldAPI := fileCfg.Login.APIURL- if oldAPI == "" {- oldAPI = resolved.APIURL+ oldAPI := loginAPIForSavedCredential(fileCfg, loginAPI)+ if oldAPI != loginAPI && !force {+ return fmt.Errorf(+ "saved login belongs to %s, but the current API is %s; unset the API URL override or use `oc login --force` to replace it",+ oldAPI,+ loginAPI,+ )}- identity, err := newCLIAuthHTTP(oldAPI).whoami(cmd.Context(), fileCfg.APIKey)- if err == nil {- if !force {- return printLoginResult(cmd, identityAsLoginResult(identity, fileCfg.Login), true)- }+ if force {+ // Replacement is intentionally not gated on the old host. Keep+ // the exact old credential for best-effort revoke only after+ // the new login is durably saved and verified.oldManagedKey = fileCfg.APIKeyoldManagedAPI = oldAPI} else {- var apiErr *client.APIError- if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusUnauthorized {- return fmt.Errorf("checking existing login before replacement: %w", err)+ identity, err := newCLIAuthHTTP(oldAPI).whoami(cmd.Context(), fileCfg.APIKey)+ if err == nil {+ return printLoginResult(cmd, identityAsLoginResult(identity, fileCfg.Login), true)+ } else {+ var apiErr *client.APIError+ if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {+ // The old key is already terminal and needs no revoke.+ } else {+ return fmt.Errorf("checking existing login before replacement: %w", err)+ }}}}}+ if fileCfg.APIURL != "" && newCLIAuthHTTP(fileCfg.APIURL).baseURL != loginAPI {+ fmt.Fprintf(+ errOut,+ "Using API %s; successful login will replace the saved API URL %s.\n",+ oneLine(loginAPI),+ oneLine(newCLIAuthHTTP(fileCfg.APIURL).baseURL),+ )+ }receipt, err := authClient.start(cmd.Context())if err != nil {return fmt.Errorf("starting login: %w", err)}- errOut := cmd.ErrOrStderr()style := deployStyleFor(errOut)fmt.Fprintln(errOut, "Open this page to sign in:")fmt.Fprintf(errOut, " %s\n\n", terminalLink(receipt.VerificationURIComplete, style))@@ -454,13 +506,13 @@ func runLogin(cmd *cobra.Command, force, noBrowser bool) error {}nextCfg := fileCfg- nextCfg.APIURL = resolved.APIURL+ nextCfg.APIURL = loginAPInextCfg.APIKey = exchange.Credential.KeynextCfg.Login = &config.LoginMetadata{CredentialID: exchange.Credential.ID,KeyPrefix: exchange.Credential.KeyPrefix,Name: exchange.Credential.Name,- APIURL: resolved.APIURL,+ APIURL: loginAPI,}if err := config.Save(nextCfg); err != nil {return fmt.Errorf(@@ -480,9 +532,10 @@ func runLogin(cmd *cobra.Command, force, noBrowser bool) error {if oldManagedKey != "" {if err := newCLIAuthHTTP(oldManagedAPI).revoke(cmd.Context(), oldManagedKey); err != nil {- return fmt.Errorf(- "replacement login is active, but the previous CLI credential could not be revoked; remove it in the dashboard: %w",- err,+ fmt.Fprintf(+ errOut,+ "Warning: replacement login is active, but the previous CLI credential at %s could not be revoked. Remove it in the dashboard if needed.\n",+ oneLine(oldManagedAPI),)}}@@ -512,7 +565,8 @@ func runWhoami(cmd *cobra.Command) error {func runLogout(cmd *cobra.Command, localOnly bool) error {source := config.EffectiveCredentialSource(cmd)- if source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag {+ if !localOnly &&+ (source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag) {return fmt.Errorf("%s still controls authentication; unset it before logging out", source)}fileCfg := config.LoadFile()diff --git a/cmd/oc/internal/commands/auth_test.go b/cmd/oc/internal/commands/auth_test.goindex 63bbd742..5f426b70 100644--- a/cmd/oc/internal/commands/auth_test.go+++ b/cmd/oc/internal/commands/auth_test.go@@ -270,6 +270,27 @@ func TestLoginRefusesEnvironmentCredentialWithoutCallingAPI(t *testing.T) {}}+func TestLoginRefusesFlagCredentialWithoutCallingAPI(t *testing.T) {+ var calls int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ http.Error(w, "unexpected", 500)+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ cmd.Flags().String("api-key", "", "")+ if err := cmd.Flags().Set("api-key", "flag-key"); err != nil {+ t.Fatal(err)+ }+ err := runLogin(cmd, true, true)+ if err == nil || !strings.Contains(err.Error(), "--api-key") {+ t.Fatalf("error = %v", err)+ }+ if calls != 0 {+ t.Fatalf("API called %d times", calls)+ }+}+func TestLoginForceStoresAndVerifiesReplacementBeforeRevokingOld(t *testing.T) {var sequence []stringvar mu sync.Mutex@@ -329,12 +350,123 @@ func TestLoginForceStoresAndVerifiesReplacementBeforeRevokingOld(t *testing.T) {t.Fatalf("runLogin --force: %v", err)}got := strings.Join(sequence, ",")- want := "old-whoami,start,exchange,new-whoami,old-revoke"+ want := "start,exchange,new-whoami,old-revoke"if got != want {t.Fatalf("sequence = %q, want %q", got, want)}}+func TestLoginForceContinuesWhenPreviousAPIIsUnreachable(t *testing.T) {+ oldServer := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))+ oldURL := oldServer.URL+ oldServer.Close()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ writeJSONResponse(w, 200, authorizedExchange())+ case "/api/whoami":+ if r.Header.Get("X-API-Key") != testKey {+ t.Errorf("unexpected key at replacement API")+ }+ writeJSONResponse(w, 200, whoamiResponse())+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, stderr := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{+ APIURL: oldURL,+ APIKey: oldTestKey,+ Login: &config.LoginMetadata{+ CredentialID: "old-id",+ KeyPrefix: "osb_bbbb",+ Name: "oc CLI on old",+ APIURL: oldURL,+ },+ }); err != nil {+ t.Fatal(err)+ }++ if err := runLogin(cmd, true, true); err != nil {+ t.Fatalf("runLogin --force: %v", err)+ }+ if !strings.Contains(stderr.String(), "replacement login is active") ||+ !strings.Contains(stderr.String(), "could not be revoked") {+ t.Fatalf("stderr = %q", stderr.String())+ }+ got := config.LoadFile()+ if got.APIKey != testKey || got.Login == nil || got.Login.APIURL != server.URL {+ t.Fatalf("replacement config = %#v", got)+ }+}++func TestLoginRefusesSavedLoginAtDifferentEffectiveAPIWithoutForce(t *testing.T) {+ oldServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Errorf("old API should not be called")+ http.Error(w, "unexpected", 500)+ }))+ defer oldServer.Close()+ newServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Errorf("new API should not be called")+ http.Error(w, "unexpected", 500)+ }))+ defer newServer.Close()+ cmd, _, _ := authTestCommand(t, newServer.URL)+ if err := config.Save(config.Config{+ APIURL: oldServer.URL,+ APIKey: oldTestKey,+ Login: &config.LoginMetadata{+ CredentialID: "old-id",+ KeyPrefix: "osb_bbbb",+ Name: "oc CLI on old",+ APIURL: oldServer.URL,+ },+ }); err != nil {+ t.Fatal(err)+ }++ err := runLogin(cmd, false, true)+ if err == nil ||+ !strings.Contains(err.Error(), "saved login belongs to "+oldServer.URL) ||+ !strings.Contains(err.Error(), "current API is "+newServer.URL) {+ t.Fatalf("error = %v", err)+ }+}++func TestLoginMakesEffectiveAPIURLPersistenceExplicit(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ writeJSONResponse(w, 200, authorizedExchange())+ case "/api/whoami":+ writeJSONResponse(w, 200, whoamiResponse())+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, stderr := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{APIURL: "https://old.example.test"}); err != nil {+ t.Fatal(err)+ }++ if err := runLogin(cmd, false, true); err != nil {+ t.Fatalf("runLogin: %v", err)+ }+ if !strings.Contains(stderr.String(), "successful login will replace the saved API URL https://old.example.test") {+ t.Fatalf("stderr = %q", stderr.String())+ }+ if got := config.LoadFile(); got.APIURL != server.URL || got.Login == nil || got.Login.APIURL != server.URL {+ t.Fatalf("saved config = %#v", got)+ }+}+func TestLoginWithValidManagedCredentialExitsWithoutNewAuthorization(t *testing.T) {var starts intserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -495,6 +627,30 @@ func TestLogoutLocalDoesNotCallRemote(t *testing.T) {}}+func TestLogoutLocalIgnoresEffectiveCredentialOverride(t *testing.T) {+ cmd, _, _ := authTestCommand(t, "https://unused.example.test")+ if err := config.Save(config.Config{+ APIURL: "https://saved.example.test",+ APIKey: testKey,+ Login: &config.LoginMetadata{+ CredentialID: "credential-1",+ KeyPrefix: "osb_aaaa",+ Name: "oc CLI on test",+ APIURL: "https://saved.example.test",+ },+ }); err != nil {+ t.Fatal(err)+ }+ t.Setenv("OPENCOMPUTER_API_KEY", "environment-key")++ if err := runLogout(cmd, true); err != nil {+ t.Fatalf("runLogout --local: %v", err)+ }+ if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {+ t.Fatalf("local login remains: %#v", got)+ }+}+func TestLoginCancellationDoesNotSaveCredential(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/auth/cli/device" {@@ -514,6 +670,42 @@ func TestLoginCancellationDoesNotSaveCredential(t *testing.T) {}}+func TestLoginReportsDeniedAndExpiredWithoutSaving(t *testing.T) {+ for _, tc := range []struct {+ name string+ status int+ code string+ wantAction string+ }{+ {name: "denied", status: http.StatusForbidden, code: "authorization_denied", wantAction: "approve the displayed code"},+ {name: "expired", status: http.StatusGone, code: "authorization_expired", wantAction: "run `oc login` again"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ writeJSONResponse(w, tc.status, map[string]string{"error": tc.code})+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ err := runLogin(cmd, false, true)+ if err == nil ||+ !strings.Contains(err.Error(), tc.code) ||+ !strings.Contains(err.Error(), tc.wantAction) {+ t.Fatalf("error = %v", err)+ }+ if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {+ t.Fatalf("terminal authorization mutated config: %#v", got)+ }+ })+ }+}+func TestLoginRetriesTransientExchangeTwiceThenLeavesConfigUntouched(t *testing.T) {var exchanges intserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -623,6 +815,23 @@ func TestAuthClientNeverFollowsRedirectsWithCredentials(t *testing.T) {}}+func TestInsecureRemoteAPIURLWarningPolicy(t *testing.T) {+ for _, tc := range []struct {+ url string+ want bool+ }{+ {url: "https://api.example.test", want: false},+ {url: "http://localhost:8787", want: false},+ {url: "http://127.0.0.1:8787", want: false},+ {url: "http://[::1]:8787", want: false},+ {url: "http://api.example.test", want: true},+ } {+ if got := insecureRemoteAPIURL(tc.url); got != tc.want {+ t.Errorf("insecureRemoteAPIURL(%q) = %v, want %v", tc.url, got, tc.want)+ }+ }+}+func TestConfigSetAPIKeyClearsLoginManagementMetadata(t *testing.T) {cmd, _, _ := authTestCommand(t, "https://example.test")if err := config.Save(config.Config{diff --git a/docs/cli/overview.mdx b/docs/cli/overview.mdxindex 98ba37b1..3fa026e2 100644--- a/docs/cli/overview.mdx+++ b/docs/cli/overview.mdx@@ -62,7 +62,8 @@ should continue to receive an explicit org key through their secret manager and| 4 (lowest) | Defaults | `https://app.opencomputer.dev` |An active `--api-key` or `OPENCOMPUTER_API_KEY` override must be removed before-`oc login` or `oc logout`. Manually setting an API key remains supported:+`oc login` or remote `oc logout`; `oc logout --local` can still clear the saved+CLI login. Manually setting an API key remains supported:```bashoc config set api-key "$OPENCOMPUTER_API_KEY"diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdxindex a7657ed1..207dbb0d 100644--- a/docs/reference/cli.mdx+++ b/docs/reference/cli.mdx@@ -30,8 +30,9 @@ workspace. `oc logout` revokes a CLI-managed key before clearing it locally;`--local` skips remote revocation explicitly.An active `--api-key` or `OPENCOMPUTER_API_KEY` override takes precedence and-must be unset before login or logout. CI, servers, and SDK applications should-continue to use explicitly managed org keys.+must be unset before login or remote logout. `oc logout --local` can still+clear the saved CLI login. CI, servers, and SDK applications should continue+to use explicitly managed org keys.---diff --git a/docs/reference/cli/auth.mdx b/docs/reference/cli/auth.mdxindex 4a0229d8..d129db0d 100644--- a/docs/reference/cli/auth.mdx+++ b/docs/reference/cli/auth.mdx@@ -16,12 +16,18 @@ failure does not stop the flow.- `--no-browser` only prints the URL, which is useful over SSH or when a codingagent is running the command.- `--force` replaces an existing saved credential. A prior CLI-created key is- revoked only after the replacement is saved and verified. A manually- configured key is replaced locally but never remotely revoked.+ revoked only after the replacement is saved and verified. If its previous API+ is unreachable, replacement continues with a warning and that old key remains+ available for manual revocation. A manually configured key is replaced+ locally but never remotely revoked.The credential is stored in `~/.oc/config.json` with private permissions and isnever printed, including under `--json`. If `--api-key` or`OPENCOMPUTER_API_KEY` is active, unset that override before logging in.+When an API URL override differs from a saved login, the CLI requires an+explicit replacement rather than reporting the old host as logged in. Remote+login endpoints should use HTTPS; the CLI warns before sending credentials to+a non-loopback HTTP URL.`oc login` is for a person's local CLI. CI, servers, and SDK applicationsshould keep using an explicit org API key supplied through their secret@@ -50,5 +56,6 @@ credential is retained and the command fails so it cannot claim a still-livekey was revoked.`--local` explicitly clears local login state without remote revocation.-Manually configured and environment-provided keys are never remotely revoked-by this command.+It remains available when an environment or flag key currently overrides the+saved login. Manually configured and environment-provided keys are never+remotely revoked by this command.