From dc9a0c5fc9b706c6394a3033db5dca13a07e9309 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 28 Jul 2026 13:33:03 -0700 Subject: [PATCH 01/37] Fail over to the local daemon when the configured server is unreachable A wedged Subrouter host takes every client with it. When cmux-mac-mini exhausted its kernel mbuf pool, it stopped accepting TCP entirely while still answering ICMP, so `sr codex` handed codex a base URL that silently hung instead of failing. Every machine on the team was blocked even though each had a healthy daemon on 127.0.0.1:31415 the whole time. Probe the configured server's /_subrouter/health before launching codex and substitute the local daemon when it does not answer. The probe is bounded at 1.5s because a buffer-exhausted host drops SYNs rather than refusing them, so an unbounded dial would hang rather than fail over. Resolution stays pure: defaultCodexBaseURLFor does no network I/O, and the probe runs only on the launch path in codexBaseURLWithFallback. An explicit SUBROUTER_CODEX_BASE_URL or SUBROUTER_CODEX_SERVER is a deliberate pin and is never overridden; SUBROUTER_DISABLE_FALLBACK opts out entirely. Also add sr up/down/restart/health, wrapping the launchd and systemd units that install-daemon and install-systemd already write, so restarting the server does not mean remembering launchctl bootout incantations. These are local-only commands and are never forwarded to a remote server. --- cmd/subrouter/codex.go | 19 ++- cmd/subrouter/lifecycle.go | 178 ++++++++++++++++++++++++++ cmd/subrouter/serverfallback.go | 133 ++++++++++++++++++++ cmd/subrouter/serverfallback_test.go | 182 +++++++++++++++++++++++++++ cmd/subrouter/sr.go | 12 ++ 5 files changed, 523 insertions(+), 1 deletion(-) create mode 100644 cmd/subrouter/lifecycle.go create mode 100644 cmd/subrouter/serverfallback.go create mode 100644 cmd/subrouter/serverfallback_test.go diff --git a/cmd/subrouter/codex.go b/cmd/subrouter/codex.go index 001c52ad1..a79714e50 100644 --- a/cmd/subrouter/codex.go +++ b/cmd/subrouter/codex.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "io" "os" "os/exec" "strconv" @@ -15,7 +16,7 @@ import ( const defaultCodexBaseURL = "http://127.0.0.1:31415/v1" func codex(args []string) error { - baseURL, err := codexBaseURL(defaultSRServerStore(accounts.DefaultCodexStore())) + baseURL, err := codexBaseURLWithFallback(defaultSRServerStore(accounts.DefaultCodexStore()), os.Stderr) if err != nil { return err } @@ -67,6 +68,22 @@ func defaultCodexBaseURLFor(store srServerStore) (string, error) { return codexBaseURLForServer(server), nil } +// codexBaseURLWithFallback resolves the base URL for launching codex, then +// substitutes the local daemon when the configured server is unreachable. An +// explicit SUBROUTER_CODEX_BASE_URL or SUBROUTER_CODEX_SERVER is treated as a +// deliberate pin and is never overridden. +func codexBaseURLWithFallback(store srServerStore, warn io.Writer) (string, error) { + baseURL, err := codexBaseURL(store) + if err != nil { + return "", err + } + if strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_BASE_URL")) != "" || + strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_SERVER")) != "" { + return baseURL, nil + } + return withLocalFallback(context.Background(), fallbackHTTPClient(), baseURL, warn), nil +} + func codexBaseURLForNamedServer(store srServerStore, name string) (string, error) { if name == "local" || name == "localhost" { return defaultCodexBaseURL, nil diff --git a/cmd/subrouter/lifecycle.go b/cmd/subrouter/lifecycle.go new file mode 100644 index 000000000..f5fd9c52e --- /dev/null +++ b/cmd/subrouter/lifecycle.go @@ -0,0 +1,178 @@ +package main + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/manaflow-ai/subrouter/internal/accounts" +) + +// serviceController starts, stops and inspects the installed local daemon. The +// two implementations wrap launchd and systemd rather than managing processes +// directly, so `sr up` and a reboot converge on the same supervised state. +type serviceController interface { + start() error + stop() error + restart() error + // installed reports whether a unit or agent exists to act on. + installed() bool + // describe names the managed unit for user-facing messages. + describe() string +} + +// launchdController manages the per-user LaunchAgent written by install-daemon. +type launchdController struct { + label string + home string + runner commandRunner +} + +func (c launchdController) plist() string { return launchAgentPath(c.home, c.label) } + +func (c launchdController) installed() bool { + _, err := os.Stat(c.plist()) + return err == nil +} + +func (c launchdController) describe() string { return c.label } + +func (c launchdController) domain() string { + return fmt.Sprintf("gui/%d", os.Getuid()) +} + +func (c launchdController) start() error { + if err := c.runner.Run("launchctl", "bootstrap", c.domain(), c.plist()); err != nil { + // Already bootstrapped is not a failure; kickstart still brings it up. + return c.runner.Run("launchctl", "kickstart", "-k", c.domain()+"/"+c.label) + } + return nil +} + +func (c launchdController) stop() error { + return c.runner.Run("launchctl", "bootout", c.domain(), c.plist()) +} + +func (c launchdController) restart() error { + return restartLaunchAgent(c.plist(), c.label, c.runner) +} + +// systemdController manages the system service written by install-systemd. +type systemdController struct { + service string + runner commandRunner +} + +func (c systemdController) installed() bool { + _, err := os.Stat(systemdUnitPath(systemdConfig{ServiceName: c.service})) + return err == nil +} + +func (c systemdController) describe() string { return c.service + ".service" } + +func (c systemdController) start() error { + return c.runner.Run("systemctl", "start", c.service) +} + +func (c systemdController) stop() error { + return c.runner.Run("systemctl", "stop", c.service) +} + +func (c systemdController) restart() error { + return c.runner.Run("systemctl", "restart", c.service) +} + +// newServiceController picks the supervisor for the running OS. +func newServiceController() (serviceController, error) { + switch runtime.GOOS { + case "darwin": + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + return launchdController{label: defaultDaemonLabel, home: home, runner: commandRunner{}}, nil + case "linux": + return systemdController{service: defaultSystemdServiceName, runner: commandRunner{}}, nil + default: + return nil, fmt.Errorf("managing the local daemon is not supported on %s", runtime.GOOS) + } +} + +// runServerLifecycle implements `sr up`, `sr down` and `sr restart`. +func runServerLifecycle(action string, out io.Writer) error { + controller, err := newServiceController() + if err != nil { + return err + } + if !controller.installed() { + return fmt.Errorf("no local Subrouter daemon installed; run '%s install-daemon' first", filepath.Base(os.Args[0])) + } + switch action { + case "up", "start": + if err := controller.start(); err != nil { + return fmt.Errorf("start %s: %w", controller.describe(), err) + } + fmt.Fprintf(out, "started %s\n", controller.describe()) + case "down", "stop": + if err := controller.stop(); err != nil { + return fmt.Errorf("stop %s: %w", controller.describe(), err) + } + fmt.Fprintf(out, "stopped %s\n", controller.describe()) + case "restart": + if err := controller.restart(); err != nil { + return fmt.Errorf("restart %s: %w", controller.describe(), err) + } + fmt.Fprintf(out, "restarted %s\n", controller.describe()) + default: + return fmt.Errorf("unknown server action %q", action) + } + return nil +} + +// runServerHealth implements `sr up --check` style reporting: it prints whether +// the configured server and the local daemon each answer their health probe, so +// an operator can tell a routing problem from a dead host without curl. +func runServerHealth(ctx context.Context, out io.Writer) error { + client := fallbackHTTPClient() + local := localBaseURL() + fmt.Fprintf(out, "%-40s %s\n", local, healthLabel(serverHealthy(ctx, client, local))) + + configured, err := defaultCodexBaseURLForHealth() + if err != nil { + return err + } + if configured != "" && !sameEndpoint(configured, local) { + fmt.Fprintf(out, "%-40s %s\n", configured, healthLabel(serverHealthy(ctx, client, configured))) + } + return nil +} + +func healthLabel(ok bool) string { + if ok { + return "healthy" + } + return "UNREACHABLE" +} + +// defaultCodexBaseURLForHealth resolves the configured server without applying +// fallback, so the health report shows what is configured rather than what a +// probe would substitute. +func defaultCodexBaseURLForHealth() (string, error) { + store := defaultSRServerStore(accounts.DefaultCodexStore()) + file, err := store.load() + if err != nil { + return "", err + } + if strings.TrimSpace(file.Default) == "" { + return "", nil + } + server, ok := file.find(file.Default) + if !ok { + return "", nil + } + return codexBaseURLForServer(server), nil +} diff --git a/cmd/subrouter/serverfallback.go b/cmd/subrouter/serverfallback.go new file mode 100644 index 000000000..5ecf11a04 --- /dev/null +++ b/cmd/subrouter/serverfallback.go @@ -0,0 +1,133 @@ +package main + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" +) + +// localFallbackBaseURL is where the per-machine daemon listens. It is the same +// address install-daemon and install-systemd bind. +const localFallbackBaseURL = "http://127.0.0.1:31415/v1" + +// fallbackProbeTimeout bounds each health probe. A host that has exhausted its +// kernel socket buffers drops SYNs instead of refusing them, so an unbounded +// dial hangs the agent launch indefinitely rather than failing over. +const fallbackProbeTimeout = 1500 * time.Millisecond + +// healthURLFor derives the health endpoint from a Subrouter base URL. Base URLs +// carry an optional /v1 suffix for OpenAI-compatible clients, while the health +// route is served at the origin. +func healthURLFor(baseURL string) (string, error) { + trimmed := strings.TrimSpace(baseURL) + if trimmed == "" { + return "", fmt.Errorf("empty base URL") + } + parsed, err := url.Parse(trimmed) + if err != nil { + return "", err + } + if parsed.Scheme == "" || parsed.Host == "" { + return "", fmt.Errorf("base URL %q is not absolute", baseURL) + } + parsed.Path = "/_subrouter/health" + parsed.RawQuery = "" + parsed.Fragment = "" + return parsed.String(), nil +} + +// sameEndpoint reports whether two base URLs address the same origin, so a +// server that is already local is never "failed over" onto itself. +func sameEndpoint(a, b string) bool { + parsedA, errA := url.Parse(strings.TrimSpace(a)) + parsedB, errB := url.Parse(strings.TrimSpace(b)) + if errA != nil || errB != nil { + return false + } + return strings.EqualFold(parsedA.Host, parsedB.Host) +} + +// serverHealthy reports whether a Subrouter server answers its health probe. +func serverHealthy(ctx context.Context, client *http.Client, baseURL string) bool { + healthURL, err := healthURLFor(baseURL) + if err != nil { + return false + } + probeCtx, cancel := context.WithTimeout(ctx, fallbackProbeTimeout) + defer cancel() + req, err := http.NewRequestWithContext(probeCtx, http.MethodGet, healthURL, nil) + if err != nil { + return false + } + resp, err := client.Do(req) + if err != nil { + return false + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<10)) + return resp.StatusCode == http.StatusOK +} + +// fallbackDisabled lets an operator pin the configured server even when it is +// down, for cases where routing through local accounts is worse than failing. +func fallbackDisabled() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv("SUBROUTER_DISABLE_FALLBACK"))) { + case "", "0", "false", "no": + return false + default: + return true + } +} + +// localBaseURL resolves where the per-machine daemon listens, allowing an +// override for non-default installs and for tests. +func localBaseURL() string { + if override := strings.TrimSpace(os.Getenv("SUBROUTER_LOCAL_BASE_URL")); override != "" { + return override + } + return localFallbackBaseURL +} + +// withLocalFallback returns baseURL when the configured server answers its +// health probe. When it does not and the local daemon does, it returns the local +// base URL so agents keep working through this machine's own accounts instead of +// hanging against a wedged host. +func withLocalFallback(ctx context.Context, client *http.Client, baseURL string, warn io.Writer) string { + return withLocalFallbackTo(ctx, client, baseURL, localBaseURL(), warn) +} + +// withLocalFallbackTo is withLocalFallback with an explicit local address. +func withLocalFallbackTo(ctx context.Context, client *http.Client, baseURL, local string, warn io.Writer) string { + if fallbackDisabled() { + return baseURL + } + if sameEndpoint(baseURL, local) { + return baseURL + } + if serverHealthy(ctx, client, baseURL) { + return baseURL + } + if !serverHealthy(ctx, client, local) { + return baseURL + } + if warn != nil { + fmt.Fprintf(warn, "subrouter: %s is unreachable; falling back to the local daemon at %s\n", baseURL, local) + } + return local +} + +// fallbackHTTPClient is the probe client. It deliberately does not follow +// redirects and keeps no idle connections, so a probe never wedges a later call. +func fallbackHTTPClient() *http.Client { + return &http.Client{ + Timeout: fallbackProbeTimeout, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } +} diff --git a/cmd/subrouter/serverfallback_test.go b/cmd/subrouter/serverfallback_test.go new file mode 100644 index 000000000..a7db0849a --- /dev/null +++ b/cmd/subrouter/serverfallback_test.go @@ -0,0 +1,182 @@ +package main + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" +) + +func healthServer(t *testing.T, status int) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/_subrouter/health" { + w.WriteHeader(http.StatusNotFound) + return + } + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestHealthURLForStripsVersionSuffix(t *testing.T) { + for _, tc := range []struct{ in, want string }{ + {"http://host:31415/v1", "http://host:31415/_subrouter/health"}, + {"http://host:31415", "http://host:31415/_subrouter/health"}, + {"https://subrouter.cmux.dev/v1/", "https://subrouter.cmux.dev/_subrouter/health"}, + } { + got, err := healthURLFor(tc.in) + if err != nil { + t.Fatalf("healthURLFor(%q): %v", tc.in, err) + } + if got != tc.want { + t.Fatalf("healthURLFor(%q) = %q, want %q", tc.in, got, tc.want) + } + } +} + +func TestHealthURLForRejectsRelative(t *testing.T) { + if _, err := healthURLFor("cmux-mac-mini:31415"); err == nil { + t.Fatal("expected error for non-absolute base URL") + } + if _, err := healthURLFor(" "); err == nil { + t.Fatal("expected error for empty base URL") + } +} + +func TestServerHealthy(t *testing.T) { + ok := healthServer(t, http.StatusOK) + if !serverHealthy(context.Background(), fallbackHTTPClient(), ok.URL+"/v1") { + t.Fatal("healthy server reported unhealthy") + } + + bad := healthServer(t, http.StatusInternalServerError) + if serverHealthy(context.Background(), fallbackHTTPClient(), bad.URL+"/v1") { + t.Fatal("500 reported healthy") + } + + // A closed listener stands in for an unreachable host. + dead := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + deadURL := dead.URL + dead.Close() + if serverHealthy(context.Background(), fallbackHTTPClient(), deadURL+"/v1") { + t.Fatal("closed server reported healthy") + } +} + +func TestWithLocalFallbackKeepsHealthyPrimary(t *testing.T) { + primary := healthServer(t, http.StatusOK) + local := healthServer(t, http.StatusOK) + + var warn bytes.Buffer + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), primary.URL+"/v1", local.URL+"/v1", &warn) + if got != primary.URL+"/v1" { + t.Fatalf("got %q, want primary %q", got, primary.URL+"/v1") + } + if warn.Len() != 0 { + t.Fatalf("unexpected warning: %q", warn.String()) + } +} + +func TestWithLocalFallbackUsesLocalWhenPrimaryDown(t *testing.T) { + dead := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + deadURL := dead.URL + "/v1" + dead.Close() + local := healthServer(t, http.StatusOK) + + var warn bytes.Buffer + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), deadURL, local.URL+"/v1", &warn) + if got != local.URL+"/v1" { + t.Fatalf("got %q, want local %q", got, local.URL+"/v1") + } + if warn.Len() == 0 { + t.Fatal("expected a warning when falling back") + } +} + +func TestWithLocalFallbackKeepsPrimaryWhenLocalAlsoDown(t *testing.T) { + deadPrimary := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + primaryURL := deadPrimary.URL + "/v1" + deadPrimary.Close() + deadLocal := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + localURL := deadLocal.URL + "/v1" + deadLocal.Close() + + var warn bytes.Buffer + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), primaryURL, localURL, &warn) + if got != primaryURL { + t.Fatalf("got %q, want primary %q preserved", got, primaryURL) + } + if warn.Len() != 0 { + t.Fatalf("unexpected warning: %q", warn.String()) + } +} + +func TestWithLocalFallbackRespectsDisableEnv(t *testing.T) { + t.Setenv("SUBROUTER_DISABLE_FALLBACK", "1") + dead := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + deadURL := dead.URL + "/v1" + dead.Close() + local := healthServer(t, http.StatusOK) + + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), deadURL, local.URL+"/v1", nil) + if got != deadURL { + t.Fatalf("got %q, want unchanged %q when fallback disabled", got, deadURL) + } +} + +func TestWithLocalFallbackDoesNotFailOverOntoItself(t *testing.T) { + local := healthServer(t, http.StatusOK) + // Same origin as the local daemon: nothing to fail over to. + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), local.URL+"/v1", local.URL+"/v1", nil) + if got != local.URL+"/v1" { + t.Fatalf("got %q, want %q", got, local.URL+"/v1") + } +} + +func TestCodexBaseURLWithFallbackSwapsUnreachableDefault(t *testing.T) { + dead := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + deadURL := dead.URL + dead.Close() + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + store := srServerStore{Path: filepath.Join(t.TempDir(), "servers.json")} + if err := store.save(srServerFile{ + Default: "team", + Servers: []srServerConfig{{Name: "team", URL: deadURL}}, + }); err != nil { + t.Fatal(err) + } + + var warn bytes.Buffer + got, err := codexBaseURLWithFallback(store, &warn) + if err != nil { + t.Fatal(err) + } + if got != local.URL+"/v1" { + t.Fatalf("base URL = %q, want local %q", got, local.URL+"/v1") + } +} + +func TestCodexBaseURLWithFallbackHonoursExplicitPin(t *testing.T) { + dead := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + deadURL := dead.URL + "/v1" + dead.Close() + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + t.Setenv("SUBROUTER_CODEX_BASE_URL", deadURL) + + store := srServerStore{Path: filepath.Join(t.TempDir(), "servers.json")} + got, err := codexBaseURLWithFallback(store, nil) + if err != nil { + t.Fatal(err) + } + if got != deadURL { + t.Fatalf("base URL = %q, want pinned %q", got, deadURL) + } +} diff --git a/cmd/subrouter/sr.go b/cmd/subrouter/sr.go index 2cf9506ae..d9ff12ee2 100644 --- a/cmd/subrouter/sr.go +++ b/cmd/subrouter/sr.go @@ -60,6 +60,11 @@ Usage: sr usage [days] Refresh and show API-key spend sr trace Show OAuth refresh breadcrumbs for an account + sr up Start the local Subrouter daemon + sr down Stop the local Subrouter daemon + sr restart Restart the local Subrouter daemon + sr health Probe the local daemon and the configured server + sr server Manage Subrouter servers sr server add --url [--default] sr server use [--no-codex-config] @@ -220,6 +225,10 @@ func (r srRunner) run(ctx context.Context, args []string) error { return r.attachProject(ctx, args[1], projectID) case "server", "servers": return r.server(ctx, args[1:]) + case "up", "start", "down", "stop", "restart": + return runServerLifecycle(args[0], r.out) + case "health": + return runServerHealth(ctx, r.out) case "help", "-h", "--help": fmt.Fprint(r.out, srHelp) return nil @@ -245,6 +254,9 @@ func shouldRouteSRCommand(command string) bool { switch command { case "server", "servers", "claude", "claude-aws", "claude-direct", "spend", "cost", "gemini", "help", "-h", "--help": return false + // Lifecycle and health act on this machine's daemon, never the remote server. + case "up", "start", "down", "stop", "restart", "health": + return false default: return true } From f271cf45dece214040de834bdc0765c48538ad4a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 28 Jul 2026 14:48:34 -0700 Subject: [PATCH 02/37] Add sr setup, doctor and cleanup, and move lifecycle under sr server The CLI had no answer to "is this thing working?" During today's outage the only way to tell a wedged server from a routing problem was curl against /_subrouter/health by hand. sr doctor reports the checks in the order a failure bites: daemon installed, daemon healthy, configured server healthy, accounts present. It distinguishes a server that is down but covered by local fallback (warn) from one that is down with no fallback (fail), and exits non-zero only on the latter so it can gate scripts. sr setup is idempotent onboarding: install the daemon, start it, wait for health, then print the one useful next step. sr cleanup prints its plan and does nothing without --yes; credentials survive unless --purge, because losing a refresh-token chain means re-running OAuth for every account. Lifecycle moves under sr server up/down/restart, matching the noun the verbs act on, and sr server status with no name now reports this machine rather than erroring. Both controllers gained remove(), and cleanup and doctor take an injected controller so tests do not depend on the host's launchd state. directSRCommands gains the three new verbs so they work when the binary is invoked as subrouter or cx, not only as sr, with main_test.go's guard list updated to match. --- cmd/subrouter/lifecycle.go | 22 ++- cmd/subrouter/main.go | 3 + cmd/subrouter/main_test.go | 3 + cmd/subrouter/sr.go | 27 ++-- cmd/subrouter/sr_server.go | 23 ++- cmd/subrouter/sr_setup.go | 253 +++++++++++++++++++++++++++++++++ cmd/subrouter/sr_setup_test.go | 141 ++++++++++++++++++ 7 files changed, 457 insertions(+), 15 deletions(-) create mode 100644 cmd/subrouter/sr_setup.go create mode 100644 cmd/subrouter/sr_setup_test.go diff --git a/cmd/subrouter/lifecycle.go b/cmd/subrouter/lifecycle.go index f5fd9c52e..460f6737d 100644 --- a/cmd/subrouter/lifecycle.go +++ b/cmd/subrouter/lifecycle.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "os" - "path/filepath" "runtime" "strings" @@ -21,6 +20,8 @@ type serviceController interface { restart() error // installed reports whether a unit or agent exists to act on. installed() bool + // remove deletes the unit or agent definition after stopping it. + remove() error // describe names the managed unit for user-facing messages. describe() string } @@ -61,6 +62,14 @@ func (c launchdController) restart() error { return restartLaunchAgent(c.plist(), c.label, c.runner) } +func (c launchdController) remove() error { + _ = c.runner.Run("launchctl", "bootout", c.domain(), c.plist()) + if err := os.Remove(c.plist()); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + // systemdController manages the system service written by install-systemd. type systemdController struct { service string @@ -86,6 +95,15 @@ func (c systemdController) restart() error { return c.runner.Run("systemctl", "restart", c.service) } +func (c systemdController) remove() error { + _ = c.runner.Run("systemctl", "disable", "--now", c.service) + unit := systemdUnitPath(systemdConfig{ServiceName: c.service}) + if err := os.Remove(unit); err != nil && !os.IsNotExist(err) { + return err + } + return c.runner.Run("systemctl", "daemon-reload") +} + // newServiceController picks the supervisor for the running OS. func newServiceController() (serviceController, error) { switch runtime.GOOS { @@ -109,7 +127,7 @@ func runServerLifecycle(action string, out io.Writer) error { return err } if !controller.installed() { - return fmt.Errorf("no local Subrouter daemon installed; run '%s install-daemon' first", filepath.Base(os.Args[0])) + return fmt.Errorf("no local Subrouter daemon installed; run '%s setup' first", programBase()) } switch action { case "up", "start": diff --git a/cmd/subrouter/main.go b/cmd/subrouter/main.go index 7318c831f..0818e7a48 100644 --- a/cmd/subrouter/main.go +++ b/cmd/subrouter/main.go @@ -134,7 +134,9 @@ var directSRCommands = map[string]struct{}{ "claude": {}, "claude-aws": {}, "claude-direct": {}, + "cleanup": {}, "cost": {}, + "doctor": {}, "g": {}, "gemini": {}, "gui": {}, @@ -152,6 +154,7 @@ var directSRCommands = map[string]struct{}{ "rm": {}, "server": {}, "servers": {}, + "setup": {}, "spend": {}, "status": {}, "switch": {}, diff --git a/cmd/subrouter/main_test.go b/cmd/subrouter/main_test.go index 2459bf31d..72f66676c 100644 --- a/cmd/subrouter/main_test.go +++ b/cmd/subrouter/main_test.go @@ -177,7 +177,9 @@ func TestDirectSRCommandNames(t *testing.T) { "claude", "claude-aws", "claude-direct", + "cleanup", "cost", + "doctor", "g", "gemini", "gui", @@ -195,6 +197,7 @@ func TestDirectSRCommandNames(t *testing.T) { "rm", "server", "servers", + "setup", "spend", "status", "switch", diff --git a/cmd/subrouter/sr.go b/cmd/subrouter/sr.go index d9ff12ee2..8708eb89d 100644 --- a/cmd/subrouter/sr.go +++ b/cmd/subrouter/sr.go @@ -60,10 +60,15 @@ Usage: sr usage [days] Refresh and show API-key spend sr trace Show OAuth refresh breadcrumbs for an account - sr up Start the local Subrouter daemon - sr down Stop the local Subrouter daemon - sr restart Restart the local Subrouter daemon - sr health Probe the local daemon and the configured server +Getting started: + sr setup Install and start the local daemon, then verify it + sr doctor Diagnose routing: daemon, server, accounts + sr cleanup Remove the local daemon (--yes to apply, --purge for credentials) + +Running agents: + sr codex [args] Run codex through Subrouter + sr claude [args] Run claude through Subrouter + sr gemini [args] Run gemini through Subrouter sr server Manage Subrouter servers sr server add --url [--default] @@ -225,10 +230,12 @@ func (r srRunner) run(ctx context.Context, args []string) error { return r.attachProject(ctx, args[1], projectID) case "server", "servers": return r.server(ctx, args[1:]) - case "up", "start", "down", "stop", "restart": - return runServerLifecycle(args[0], r.out) - case "health": - return runServerHealth(ctx, r.out) + case "setup": + return runSetup(ctx, r.store, args[1:], r.out) + case "cleanup": + return runCleanup(r.store, args[1:], r.out) + case "doctor": + return runDoctor(ctx, r.store, r.out) case "help", "-h", "--help": fmt.Fprint(r.out, srHelp) return nil @@ -254,8 +261,8 @@ func shouldRouteSRCommand(command string) bool { switch command { case "server", "servers", "claude", "claude-aws", "claude-direct", "spend", "cost", "gemini", "help", "-h", "--help": return false - // Lifecycle and health act on this machine's daemon, never the remote server. - case "up", "start", "down", "stop", "restart", "health": + // Setup, cleanup and doctor act on this machine, never the remote server. + case "setup", "cleanup", "doctor": return false default: return true diff --git a/cmd/subrouter/sr_server.go b/cmd/subrouter/sr_server.go index eca76197d..27a66ce33 100644 --- a/cmd/subrouter/sr_server.go +++ b/cmd/subrouter/sr_server.go @@ -36,7 +36,13 @@ func (r srRunner) serverCommand() string { func srServerHelp(command string) string { return fmt.Sprintf(`%[1]s - Manage Subrouter servers -Usage: +This machine's daemon: + %[1]s up + %[1]s down + %[1]s restart + %[1]s status Health of the local daemon and the configured server + +Named servers: %[1]s list %[1]s add --url [--default] [--admin-token ] [--gcp-instance --gcp-zone --gcp-project ] %[1]s use [--no-codex-config] @@ -44,7 +50,7 @@ Usage: %[1]s clear-default %[1]s rename %[1]s remove - %[1]s status + %[1]s status Usage for a named remote server %[1]s install [--version latest] %[1]s login [--device-auth] %[1]s sync [--device-auth] [--all] [--email ] [--dry-run] [--yes] @@ -100,9 +106,20 @@ func (r srRunner) server(ctx context.Context, args []string) error { return fmt.Errorf("usage: %s remove ", command) } return r.serverRemove(store, args[1]) + case "up", "start": + return runServerLifecycle("up", r.out) + case "down", "stop": + return runServerLifecycle("down", r.out) + case "restart": + return runServerLifecycle("restart", r.out) case "status": + // No name means "this machine": report the local daemon and whichever + // server codex would actually be pointed at. + if len(args) == 1 { + return runServerHealth(ctx, r.out) + } if len(args) != 2 { - return fmt.Errorf("usage: %s status ", command) + return fmt.Errorf("usage: %s status [name]", command) } return r.serverStatus(ctx, store, args[1]) case "install": diff --git a/cmd/subrouter/sr_setup.go b/cmd/subrouter/sr_setup.go new file mode 100644 index 000000000..dae10ef77 --- /dev/null +++ b/cmd/subrouter/sr_setup.go @@ -0,0 +1,253 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/manaflow-ai/subrouter/internal/accounts" +) + +// setupWaitTimeout bounds how long `sr setup` waits for the daemon to answer +// after starting it. Installation is fast; anything slower is a real failure. +const setupWaitTimeout = 15 * time.Second + +// runSetup brings this machine to a working state and is safe to re-run. It +// installs the supervised daemon if missing, starts it, waits for health, and +// then reports the single most useful next step. +func runSetup(ctx context.Context, store accounts.CodexStore, args []string, out io.Writer) error { + flags := flag.NewFlagSet("setup", flag.ContinueOnError) + flags.SetOutput(io.Discard) + var skipInstall bool + flags.BoolVar(&skipInstall, "no-install", false, "do not install or update the daemon; only start and verify it") + if err := flags.Parse(args); err != nil { + return err + } + + controller, err := newServiceController() + if err != nil { + return err + } + + if !skipInstall { + if runtime.GOOS != "darwin" && !controller.installed() { + return fmt.Errorf("no daemon installed; run '%s install-systemd' as root on this platform", programBase()) + } + if runtime.GOOS == "darwin" { + fmt.Fprintln(out, "installing the local daemon...") + if err := installDaemon(nil); err != nil { + return fmt.Errorf("install daemon: %w", err) + } + } + } + + if !controller.installed() { + return fmt.Errorf("no local daemon installed after setup; run '%s install-daemon' manually", programBase()) + } + + fmt.Fprintf(out, "starting %s...\n", controller.describe()) + if err := controller.start(); err != nil { + return fmt.Errorf("start %s: %w", controller.describe(), err) + } + + local := localBaseURL() + if !waitForHealth(ctx, local, setupWaitTimeout) { + return fmt.Errorf("daemon did not become healthy at %s within %s; check '%s server logs'", local, setupWaitTimeout, programBase()) + } + fmt.Fprintf(out, "daemon healthy at %s\n", local) + + list, err := store.List() + if err != nil { + return err + } + if len(list) == 0 { + fmt.Fprintf(out, "\nNo accounts yet. Add one with:\n %s add\n", programBase()) + return nil + } + fmt.Fprintf(out, "\n%d account(s) available. Try:\n %s codex\n %s claude\n", len(list), programBase(), programBase()) + return nil +} + +// waitForHealth polls a base URL until it answers or the deadline passes. +func waitForHealth(ctx context.Context, baseURL string, timeout time.Duration) bool { + client := fallbackHTTPClient() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + if serverHealthy(ctx, client, baseURL) { + return true + } + select { + case <-ctx.Done(): + return false + case <-time.After(250 * time.Millisecond): + } + } + return false +} + +// runCleanup removes this machine's daemon. Credentials are preserved unless +// --purge is passed, because losing a refresh-token chain means re-running OAuth +// for every account. +func runCleanup(store accounts.CodexStore, args []string, out io.Writer) error { + flags := flag.NewFlagSet("cleanup", flag.ContinueOnError) + flags.SetOutput(io.Discard) + var yes, purge bool + flags.BoolVar(&yes, "yes", false, "perform the removal instead of printing the plan") + flags.BoolVar(&purge, "purge", false, "also delete stored accounts and credentials") + if err := flags.Parse(args); err != nil { + return err + } + + controller, err := newServiceController() + if err != nil { + return err + } + return runCleanupWith(controller, store, yes, purge, out) +} + +// runCleanupWith is runCleanup with an injected controller so tests do not +// depend on what this machine happens to have installed. +func runCleanupWith(controller serviceController, store accounts.CodexStore, yes, purge bool, out io.Writer) error { + plan := []string{} + if controller.installed() { + plan = append(plan, fmt.Sprintf("stop and remove %s", controller.describe())) + } + if purge { + plan = append(plan, fmt.Sprintf("delete %s (all stored accounts and credentials)", store.StoreDir())) + } + if len(plan) == 0 { + fmt.Fprintln(out, "nothing to clean up") + return nil + } + + fmt.Fprintln(out, "cleanup will:") + for _, step := range plan { + fmt.Fprintf(out, " - %s\n", step) + } + if !yes { + fmt.Fprintf(out, "\nre-run with --yes to proceed\n") + return nil + } + + if controller.installed() { + if err := controller.stop(); err != nil { + // A daemon that is already stopped is not a failure worth aborting on. + fmt.Fprintf(out, "warning: stop %s: %v\n", controller.describe(), err) + } + if err := controller.remove(); err != nil { + return err + } + fmt.Fprintf(out, "removed %s\n", controller.describe()) + } + if purge { + if err := os.RemoveAll(store.StoreDir()); err != nil { + return err + } + fmt.Fprintf(out, "deleted %s\n", store.StoreDir()) + } + return nil +} + +// doctorCheck is one diagnosed condition. Status is "ok", "warn" or "fail". +type doctorCheck struct { + status string + title string + detail string +} + +// runDoctor reports whether traffic can actually flow, in the order a failure +// would bite: daemon installed, daemon healthy, configured server healthy, +// accounts present. It exits non-zero when something is broken so it can gate +// scripts. +func runDoctor(ctx context.Context, store accounts.CodexStore, out io.Writer) error { + controller, err := newServiceController() + return runDoctorWith(ctx, controller, err, store, out) +} + +// runDoctorWith is runDoctor with an injected controller, so tests exercise the +// reporting logic rather than this machine's launchd state. +func runDoctorWith(ctx context.Context, controller serviceController, controllerErr error, store accounts.CodexStore, out io.Writer) error { + checks := []doctorCheck{} + client := fallbackHTTPClient() + local := localBaseURL() + + err := controllerErr + switch { + case err != nil: + checks = append(checks, doctorCheck{"warn", "supervisor", err.Error()}) + case !controller.installed(): + checks = append(checks, doctorCheck{"warn", "daemon installed", fmt.Sprintf("no local daemon; run '%s setup'", programBase())}) + default: + checks = append(checks, doctorCheck{"ok", "daemon installed", controller.describe()}) + } + + localOK := serverHealthy(ctx, client, local) + if localOK { + checks = append(checks, doctorCheck{"ok", "local daemon", local}) + } else { + checks = append(checks, doctorCheck{"warn", "local daemon", fmt.Sprintf("%s is not answering; run '%s server up'", local, programBase())}) + } + + configured, err := defaultCodexBaseURLForHealth() + if err != nil { + checks = append(checks, doctorCheck{"warn", "configured server", err.Error()}) + } else if configured == "" || sameEndpoint(configured, local) { + checks = append(checks, doctorCheck{"ok", "configured server", "local"}) + } else if serverHealthy(ctx, client, configured) { + checks = append(checks, doctorCheck{"ok", "configured server", configured}) + } else if localOK && !fallbackDisabled() { + checks = append(checks, doctorCheck{"warn", "configured server", fmt.Sprintf("%s unreachable; codex will fall back to %s", configured, local)}) + } else { + checks = append(checks, doctorCheck{"fail", "configured server", fmt.Sprintf("%s unreachable and no local fallback available", configured)}) + } + + list, err := store.List() + switch { + case err != nil: + checks = append(checks, doctorCheck{"fail", "accounts", err.Error()}) + case len(list) == 0: + checks = append(checks, doctorCheck{"fail", "accounts", fmt.Sprintf("none stored; run '%s add'", programBase())}) + default: + checks = append(checks, doctorCheck{"ok", "accounts", fmt.Sprintf("%d stored", len(list))}) + } + + failed := false + for _, check := range checks { + fmt.Fprintf(out, "%s %-20s %s\n", doctorMark(check.status), check.title, check.detail) + if check.status == "fail" { + failed = true + } + } + if failed { + return errors.New("doctor found a blocking problem") + } + return nil +} + +func doctorMark(status string) string { + switch status { + case "ok": + return "ok " + case "warn": + return "warn" + default: + return "FAIL" + } +} + +// programBase is the invoked binary name, so help text matches how the user +// actually called it (sr, cx or subrouter). +func programBase() string { + base := filepath.Base(os.Args[0]) + if strings.TrimSpace(base) == "" || base == "." { + return "sr" + } + return base +} diff --git a/cmd/subrouter/sr_setup_test.go b/cmd/subrouter/sr_setup_test.go new file mode 100644 index 000000000..8e9531e74 --- /dev/null +++ b/cmd/subrouter/sr_setup_test.go @@ -0,0 +1,141 @@ +package main + +import ( + "bytes" + "context" + "errors" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/manaflow-ai/subrouter/internal/accounts" +) + +// fakeController records lifecycle calls without touching launchd or systemd. +type fakeController struct { + present bool + stopped bool + removed bool + stopErr error + removeEr error +} + +func (c *fakeController) start() error { return nil } +func (c *fakeController) stop() error { c.stopped = true; return c.stopErr } +func (c *fakeController) restart() error { return nil } +func (c *fakeController) installed() bool { return c.present } +func (c *fakeController) remove() error { c.removed = true; return c.removeEr } +func (c *fakeController) describe() string { + return "fake.daemon" +} + +func emptyStore(t *testing.T) accounts.CodexStore { + t.Helper() + return accounts.CodexStore{Dir: t.TempDir()} +} + +func TestCleanupWithoutYesOnlyPrintsPlan(t *testing.T) { + controller := &fakeController{present: true} + var out bytes.Buffer + if err := runCleanupWith(controller, emptyStore(t), false, false, &out); err != nil { + t.Fatal(err) + } + if controller.removed || controller.stopped { + t.Fatal("cleanup acted without --yes") + } + if !strings.Contains(out.String(), "--yes") { + t.Fatalf("plan should tell the user how to proceed, got %q", out.String()) + } +} + +func TestCleanupWithYesRemovesDaemon(t *testing.T) { + controller := &fakeController{present: true} + var out bytes.Buffer + if err := runCleanupWith(controller, emptyStore(t), true, false, &out); err != nil { + t.Fatal(err) + } + if !controller.stopped || !controller.removed { + t.Fatalf("expected stop+remove, got stopped=%v removed=%v", controller.stopped, controller.removed) + } +} + +func TestCleanupPreservesCredentialsUnlessPurge(t *testing.T) { + store := emptyStore(t) + marker := filepath.Join(store.StoreDir(), "accounts.json") + if err := os.MkdirAll(store.StoreDir(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(marker, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + + var out bytes.Buffer + if err := runCleanupWith(&fakeController{present: true}, store, true, false, &out); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(marker); err != nil { + t.Fatalf("credentials removed without --purge: %v", err) + } + + if err := runCleanupWith(&fakeController{present: true}, store, true, true, &out); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(marker); !os.IsNotExist(err) { + t.Fatalf("--purge should have deleted the store, stat err = %v", err) + } +} + +func TestCleanupWithNothingInstalled(t *testing.T) { + var out bytes.Buffer + if err := runCleanupWith(&fakeController{present: false}, emptyStore(t), true, false, &out); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "nothing to clean up") { + t.Fatalf("got %q", out.String()) + } +} + +func TestDoctorFailsWithoutAccounts(t *testing.T) { + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + var out bytes.Buffer + err := runDoctorWith(context.Background(), &fakeController{present: true}, nil, emptyStore(t), &out) + if err == nil { + t.Fatal("expected doctor to fail with no accounts stored") + } + if !strings.Contains(out.String(), "FAIL") { + t.Fatalf("expected a FAIL line, got %q", out.String()) + } +} + +func TestDoctorReportsUninstalledDaemonAsWarning(t *testing.T) { + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + var out bytes.Buffer + _ = runDoctorWith(context.Background(), &fakeController{present: false}, nil, emptyStore(t), &out) + if !strings.Contains(out.String(), "warn") { + t.Fatalf("expected a warn line for a missing daemon, got %q", out.String()) + } +} + +func TestDoctorSurfacesControllerError(t *testing.T) { + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + var out bytes.Buffer + _ = runDoctorWith(context.Background(), nil, errors.New("unsupported platform"), emptyStore(t), &out) + if !strings.Contains(out.String(), "unsupported platform") { + t.Fatalf("expected the controller error surfaced, got %q", out.String()) + } +} + +func TestWaitForHealthReturnsFalseWhenDead(t *testing.T) { + dead := healthServer(t, http.StatusInternalServerError) + if waitForHealth(context.Background(), dead.URL+"/v1", 300_000_000) { + t.Fatal("unhealthy server reported ready") + } +} From 9f7e2361e758aaa533cc5d5066ed151cf9e00452 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 28 Jul 2026 15:10:20 -0700 Subject: [PATCH 03/37] Auto-start the local daemon when launching an agent A cold machine had to run `sr server up` before `sr codex` would work, which is a step nobody remembers and the error it produced (a hung dial) did not explain. Launching an agent now starts the daemon when nothing is serving. Ordering matters and is deliberate: a healthy configured server always wins, so autostart only runs when nothing already answers. That keeps the common case free of extra probes and avoids starting a local daemon that would go unused. Autostart also runs when the configured target *is* this machine's daemon, including under SUBROUTER_DISABLE_FALLBACK, because starting it repairs the configured target rather than substituting a different one. Pinning via SUBROUTER_CODEX_BASE_URL still never redirects traffic elsewhere. For Claude, only the launching forms trigger it; `sr claude list` and the other management subcommands stay quiet. Also fixes help drift found while dogfooding: `sr help` renders usageText in main.go, not the srHelp const, so the new commands were missing from the help users actually see. Both surfaces now list them and a test asserts it. --- cmd/subrouter/codex.go | 6 ++ cmd/subrouter/main.go | 9 +++ cmd/subrouter/serverfallback.go | 92 ++++++++++++++++++++++-- cmd/subrouter/serverfallback_test.go | 102 +++++++++++++++++++++++++-- cmd/subrouter/sr_claude.go | 5 ++ cmd/subrouter/sr_setup_test.go | 28 ++++++++ 6 files changed, 231 insertions(+), 11 deletions(-) diff --git a/cmd/subrouter/codex.go b/cmd/subrouter/codex.go index a79714e50..b6d5db4c5 100644 --- a/cmd/subrouter/codex.go +++ b/cmd/subrouter/codex.go @@ -79,6 +79,12 @@ func codexBaseURLWithFallback(store srServerStore, warn io.Writer) (string, erro } if strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_BASE_URL")) != "" || strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_SERVER")) != "" { + // A pin is never substituted, but if it points at this machine's daemon + // we still start it rather than failing against a dead socket. + local := localBaseURL() + if sameEndpoint(baseURL, local) { + ensureLocalHealthy(context.Background(), fallbackHTTPClient(), local, defaultDaemonStarter(), warn) + } return baseURL, nil } return withLocalFallback(context.Background(), fallbackHTTPClient(), baseURL, warn), nil diff --git a/cmd/subrouter/main.go b/cmd/subrouter/main.go index 0818e7a48..aae0bf16c 100644 --- a/cmd/subrouter/main.go +++ b/cmd/subrouter/main.go @@ -886,6 +886,11 @@ func usageText(program string) string { } return fmt.Sprintf(`%[1]s routes AI coding-agent traffic across subscription accounts. +Getting started: + %[1]s setup Install and start the local daemon, then verify it + %[1]s doctor Diagnose routing: daemon, server, accounts + %[1]s cleanup Remove the local daemon (--yes to apply, --purge for credentials) + Usage: %[1]s Show Codex and Claude usage, grouped by provider %[1]s add Add a new Codex account (opens OAuth login) @@ -904,6 +909,10 @@ Usage: %[1]s trace Show OAuth refresh breadcrumbs for an account %[1]s server Manage Subrouter servers + %[1]s server up Start this machine's daemon + %[1]s server down Stop this machine's daemon + %[1]s server restart Restart this machine's daemon + %[1]s server status Health of the local daemon and the configured server %[1]s server add --url [--default] %[1]s server use [--no-codex-config] %[1]s server rename diff --git a/cmd/subrouter/serverfallback.go b/cmd/subrouter/serverfallback.go index 5ecf11a04..25c1c7d7a 100644 --- a/cmd/subrouter/serverfallback.go +++ b/cmd/subrouter/serverfallback.go @@ -98,21 +98,78 @@ func localBaseURL() string { // base URL so agents keep working through this machine's own accounts instead of // hanging against a wedged host. func withLocalFallback(ctx context.Context, client *http.Client, baseURL string, warn io.Writer) string { - return withLocalFallbackTo(ctx, client, baseURL, localBaseURL(), warn) + return withLocalFallbackTo(ctx, client, baseURL, localBaseURL(), defaultDaemonStarter(), warn) } -// withLocalFallbackTo is withLocalFallback with an explicit local address. -func withLocalFallbackTo(ctx context.Context, client *http.Client, baseURL, local string, warn io.Writer) string { - if fallbackDisabled() { +// daemonStarter brings the local daemon up. It is injected so tests can drive +// autostart without touching launchd. +type daemonStarter func() error + +// autostartTimeout bounds how long an agent launch waits for a daemon it just +// started. Longer than a healthy start needs, shorter than a user will tolerate. +const autostartTimeout = 10 * time.Second + +// defaultDaemonStarter starts the installed daemon, or reports why it cannot. +func defaultDaemonStarter() daemonStarter { + return func() error { + controller, err := newServiceController() + if err != nil { + return err + } + if !controller.installed() { + return fmt.Errorf("no local daemon installed; run '%s setup'", programBase()) + } + return controller.start() + } +} + +// ensureLocalHealthy probes the local daemon and starts it if nothing answers, +// so `sr codex` works on a cold machine without a separate `sr server up`. +func ensureLocalHealthy(ctx context.Context, client *http.Client, local string, start daemonStarter, warn io.Writer) bool { + if serverHealthy(ctx, client, local) { + return true + } + if start == nil { + return false + } + if warn != nil { + fmt.Fprintln(warn, "subrouter: local daemon is not running, starting it...") + } + if err := start(); err != nil { + if warn != nil { + fmt.Fprintf(warn, "subrouter: could not start the local daemon: %v\n", err) + } + return false + } + if !waitForHealth(ctx, local, autostartTimeout) { + if warn != nil { + fmt.Fprintf(warn, "subrouter: local daemon did not become healthy within %s\n", autostartTimeout) + } + return false + } + return true +} + +// withLocalFallbackTo is withLocalFallback with an explicit local address and an +// injected starter. +// +// Order matters: a healthy configured server always wins, so autostart only runs +// when nothing is already serving the request. +func withLocalFallbackTo(ctx context.Context, client *http.Client, baseURL, local string, start daemonStarter, warn io.Writer) string { + if serverHealthy(ctx, client, baseURL) { return baseURL } + // The configured target is down. If it *is* the local daemon, starting it + // fixes the configured target itself rather than substituting anything, so + // this path runs even when cross-host fallback is disabled. if sameEndpoint(baseURL, local) { + ensureLocalHealthy(ctx, client, local, start, warn) return baseURL } - if serverHealthy(ctx, client, baseURL) { + if fallbackDisabled() { return baseURL } - if !serverHealthy(ctx, client, local) { + if !ensureLocalHealthy(ctx, client, local, start, warn) { return baseURL } if warn != nil { @@ -131,3 +188,26 @@ func fallbackHTTPClient() *http.Client { }, } } + +// claudeManagementSubcommands never launch the agent, so they must not trigger +// a daemon autostart. +var claudeManagementSubcommands = map[string]struct{}{ + "add": {}, "login": {}, + "list": {}, "ls": {}, "status": {}, + "switch": {}, "use": {}, + "remove": {}, "rm": {}, + "env": {}, + "pick": {}, + "push": {}, "upload": {}, + "help": {}, "-h": {}, "--help": {}, +} + +// claudeLaunchesAgent reports whether `sr claude ` will start Claude Code. +// No arguments means the interactive launcher, which does. +func claudeLaunchesAgent(args []string) bool { + if len(args) == 0 { + return true + } + _, management := claudeManagementSubcommands[args[0]] + return !management +} diff --git a/cmd/subrouter/serverfallback_test.go b/cmd/subrouter/serverfallback_test.go index a7db0849a..c307fde4a 100644 --- a/cmd/subrouter/serverfallback_test.go +++ b/cmd/subrouter/serverfallback_test.go @@ -3,9 +3,11 @@ package main import ( "bytes" "context" + "errors" "net/http" "net/http/httptest" "path/filepath" + "strings" "testing" ) @@ -73,7 +75,7 @@ func TestWithLocalFallbackKeepsHealthyPrimary(t *testing.T) { local := healthServer(t, http.StatusOK) var warn bytes.Buffer - got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), primary.URL+"/v1", local.URL+"/v1", &warn) + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), primary.URL+"/v1", local.URL+"/v1", nil, &warn) if got != primary.URL+"/v1" { t.Fatalf("got %q, want primary %q", got, primary.URL+"/v1") } @@ -89,7 +91,7 @@ func TestWithLocalFallbackUsesLocalWhenPrimaryDown(t *testing.T) { local := healthServer(t, http.StatusOK) var warn bytes.Buffer - got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), deadURL, local.URL+"/v1", &warn) + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), deadURL, local.URL+"/v1", nil, &warn) if got != local.URL+"/v1" { t.Fatalf("got %q, want local %q", got, local.URL+"/v1") } @@ -107,7 +109,7 @@ func TestWithLocalFallbackKeepsPrimaryWhenLocalAlsoDown(t *testing.T) { deadLocal.Close() var warn bytes.Buffer - got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), primaryURL, localURL, &warn) + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), primaryURL, localURL, nil, &warn) if got != primaryURL { t.Fatalf("got %q, want primary %q preserved", got, primaryURL) } @@ -123,7 +125,7 @@ func TestWithLocalFallbackRespectsDisableEnv(t *testing.T) { dead.Close() local := healthServer(t, http.StatusOK) - got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), deadURL, local.URL+"/v1", nil) + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), deadURL, local.URL+"/v1", nil, nil) if got != deadURL { t.Fatalf("got %q, want unchanged %q when fallback disabled", got, deadURL) } @@ -132,7 +134,7 @@ func TestWithLocalFallbackRespectsDisableEnv(t *testing.T) { func TestWithLocalFallbackDoesNotFailOverOntoItself(t *testing.T) { local := healthServer(t, http.StatusOK) // Same origin as the local daemon: nothing to fail over to. - got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), local.URL+"/v1", local.URL+"/v1", nil) + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), local.URL+"/v1", local.URL+"/v1", nil, nil) if got != local.URL+"/v1" { t.Fatalf("got %q, want %q", got, local.URL+"/v1") } @@ -180,3 +182,93 @@ func TestCodexBaseURLWithFallbackHonoursExplicitPin(t *testing.T) { t.Fatalf("base URL = %q, want pinned %q", got, deadURL) } } + +func TestEnsureLocalHealthyStartsDeadDaemon(t *testing.T) { + // The daemon is "started" by flipping the handler to healthy. + healthy := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !healthy { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + started := 0 + start := func() error { started++; healthy = true; return nil } + + var warn bytes.Buffer + if !ensureLocalHealthy(context.Background(), fallbackHTTPClient(), srv.URL+"/v1", start, &warn) { + t.Fatal("expected daemon to become healthy after autostart") + } + if started != 1 { + t.Fatalf("start called %d times, want 1", started) + } + if !strings.Contains(warn.String(), "starting it") { + t.Fatalf("expected an autostart notice, got %q", warn.String()) + } +} + +func TestEnsureLocalHealthySkipsStartWhenAlreadyUp(t *testing.T) { + local := healthServer(t, http.StatusOK) + started := 0 + start := func() error { started++; return nil } + + if !ensureLocalHealthy(context.Background(), fallbackHTTPClient(), local.URL+"/v1", start, nil) { + t.Fatal("healthy daemon reported unhealthy") + } + if started != 0 { + t.Fatalf("start called %d times on a healthy daemon, want 0", started) + } +} + +func TestEnsureLocalHealthyReportsStartFailure(t *testing.T) { + dead := healthServer(t, http.StatusServiceUnavailable) + start := func() error { return errors.New("launchctl exploded") } + + var warn bytes.Buffer + if ensureLocalHealthy(context.Background(), fallbackHTTPClient(), dead.URL+"/v1", start, &warn) { + t.Fatal("expected failure when the starter errors") + } + if !strings.Contains(warn.String(), "launchctl exploded") { + t.Fatalf("expected the start error surfaced, got %q", warn.String()) + } +} + +func TestAutostartRunsForLocalPinEvenWhenFallbackDisabled(t *testing.T) { + t.Setenv("SUBROUTER_DISABLE_FALLBACK", "1") + healthy := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !healthy { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + started := 0 + start := func() error { started++; healthy = true; return nil } + + got := withLocalFallbackTo(context.Background(), fallbackHTTPClient(), srv.URL+"/v1", srv.URL+"/v1", start, nil) + if got != srv.URL+"/v1" { + t.Fatalf("pinned local URL changed to %q", got) + } + if started != 1 { + t.Fatalf("start called %d times, want 1", started) + } +} + +func TestClaudeLaunchesAgent(t *testing.T) { + for _, args := range [][]string{nil, {}, {"run"}, {"--model", "opus"}, {"-p", "hi"}} { + if !claudeLaunchesAgent(args) { + t.Errorf("claudeLaunchesAgent(%v) = false, want true", args) + } + } + for _, args := range [][]string{{"list"}, {"ls"}, {"status"}, {"add"}, {"push"}, {"help"}, {"--help"}} { + if claudeLaunchesAgent(args) { + t.Errorf("claudeLaunchesAgent(%v) = true, want false", args) + } + } +} diff --git a/cmd/subrouter/sr_claude.go b/cmd/subrouter/sr_claude.go index f8773975b..370bcbe77 100644 --- a/cmd/subrouter/sr_claude.go +++ b/cmd/subrouter/sr_claude.go @@ -52,6 +52,11 @@ type claudeRunner struct { } func (r srRunner) claude(ctx context.Context, args []string) error { + // Launching Claude needs a live daemon; account management does not. Start + // the daemon only for the launching forms so `sr claude list` stays quiet. + if claudeLaunchesAgent(args) { + ensureLocalHealthy(ctx, fallbackHTTPClient(), localBaseURL(), defaultDaemonStarter(), r.errOut) + } cr := claudeRunner{ store: claude.DefaultStore(), in: r.in, diff --git a/cmd/subrouter/sr_setup_test.go b/cmd/subrouter/sr_setup_test.go index 8e9531e74..5b289389e 100644 --- a/cmd/subrouter/sr_setup_test.go +++ b/cmd/subrouter/sr_setup_test.go @@ -139,3 +139,31 @@ func TestWaitForHealthReturnsFalseWhenDead(t *testing.T) { t.Fatal("unhealthy server reported ready") } } + +// TestUsageTextListsLifecycleCommands guards against help drift: the CLI has two +// help surfaces (usageText and srHelp) and the new verbs were briefly missing +// from the one users actually see. +func TestUsageTextListsLifecycleCommands(t *testing.T) { + text := usageText("sr") + for _, want := range []string{ + "sr setup", + "sr doctor", + "sr cleanup", + "sr server up", + "sr server down", + "sr server restart", + "sr server status", + } { + if !strings.Contains(text, want) { + t.Errorf("usage text missing %q", want) + } + } +} + +func TestSRHelpListsLifecycleCommands(t *testing.T) { + for _, want := range []string{"sr setup", "sr doctor", "sr cleanup"} { + if !strings.Contains(srHelp, want) { + t.Errorf("srHelp missing %q", want) + } + } +} From f99083fe0f260106f8123f1ac572944291bdef0c Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 28 Jul 2026 17:05:24 -0700 Subject: [PATCH 04/37] Add team-vault credential leases with local egress --- cloudflare/packages/worker/README.md | 19 + cloudflare/packages/worker/src/contract.ts | 32 +- cloudflare/packages/worker/src/index.ts | 615 +++++++++++++- cloudflare/packages/worker/src/telemetry.ts | 7 + .../packages/worker/test/contract.test.ts | 73 ++ .../worker/test/credential-lease.test.ts | 460 +++++++++++ cmd/subrouter/cloud_mode_test.go | 209 +++++ cmd/subrouter/codex.go | 79 +- cmd/subrouter/install_systemd_user.go | 111 +++ cmd/subrouter/lifecycle.go | 60 +- cmd/subrouter/main.go | 87 +- cmd/subrouter/main_test.go | 8 + cmd/subrouter/sr.go | 31 +- cmd/subrouter/sr_claude.go | 59 ++ cmd/subrouter/sr_cloud.go | 753 ++++++++++++++++++ cmd/subrouter/sr_daemon.go | 85 ++ cmd/subrouter/sr_setup.go | 131 ++- docs/local-egress.md | 36 + internal/broker/client.go | 469 +++++++++++ internal/broker/client_test.go | 256 ++++++ internal/broker/config.go | 164 ++++ internal/proxy/credential_broker_test.go | 335 ++++++++ internal/proxy/proxy.go | 164 +++- 23 files changed, 4141 insertions(+), 102 deletions(-) create mode 100644 cloudflare/packages/worker/test/credential-lease.test.ts create mode 100644 cmd/subrouter/cloud_mode_test.go create mode 100644 cmd/subrouter/install_systemd_user.go create mode 100644 cmd/subrouter/sr_cloud.go create mode 100644 cmd/subrouter/sr_daemon.go create mode 100644 docs/local-egress.md create mode 100644 internal/broker/client.go create mode 100644 internal/broker/client_test.go create mode 100644 internal/broker/config.go create mode 100644 internal/proxy/credential_broker_test.go diff --git a/cloudflare/packages/worker/README.md b/cloudflare/packages/worker/README.md index 4639dbfe4..7e5f2a653 100644 --- a/cloudflare/packages/worker/README.md +++ b/cloudflare/packages/worker/README.md @@ -135,6 +135,25 @@ curl -sS -X DELETE https://subrouter.cmux.dev/tenant/accounts/$ACCOUNT_ID \ OAuth uploads schedule the existing Durable Object alarm refresh path. Rotated refresh tokens are persisted in the tenant DO. +## Local Egress Credential Leases + +`POST /tenant/leases` selects a team account, refreshes it centrally when +needed, and returns an access-only five-minute lease. The response never +contains a provider refresh token or ID token. The caller sends the provider +request from its own machine, then reports the result to +`POST /tenant/leases/:id/events`. + +`POST /tenant/accounts?adopt=1` and the matching repair route force one central +OAuth refresh before acknowledging the credential. This rotates refresh +custody away from the source laptop without making a model or usage request +from Cloudflare. + +Refreshes are single-flight per account. A response that proves the refresh +chain invalid, or leaves rotation ambiguous after a transport or parse failure, +freezes the account until `POST /tenant/accounts/:id/repair` replaces it. +Blocked accounts are removed from routing, so another healthy team credential +can serve the lease. + ## Admin Tenant Data Tenant-scoped admin reads require an explicit `?tenant=`: diff --git a/cloudflare/packages/worker/src/contract.ts b/cloudflare/packages/worker/src/contract.ts index c541c86a7..207e99c91 100644 --- a/cloudflare/packages/worker/src/contract.ts +++ b/cloudflare/packages/worker/src/contract.ts @@ -14,6 +14,7 @@ export interface AccountCredentials { readonly tokenEndpoint?: string readonly clientId?: string readonly lastRefreshAt?: number + readonly credentialGeneration?: number readonly refreshFailure?: OAuthRefreshFailure readonly usageUrl?: string readonly [key: string]: unknown @@ -581,7 +582,7 @@ export const refreshOAuthCredentials = async ( if (!force && !credentialNeedsRefresh(credentials, now)) { return { credentials, refreshed: false } } - if (credentials.refreshFailure && terminalRefreshFailure(credentials.refreshFailure)) { + if (credentials.refreshFailure && blockingRefreshFailure(credentials.refreshFailure)) { throw new Error(credentials.refreshFailure.message) } if (providerForAccount(kind) === "claude") { @@ -625,6 +626,7 @@ const refreshCodexCredentials = async ( idToken: payload.id_token, ...(expiresAt !== undefined ? { expiresAt } : {}), lastRefreshAt: now, + credentialGeneration: (credentials.credentialGeneration ?? 0) + 1, }, refreshed: true, } @@ -669,6 +671,7 @@ const refreshClaudeCredentials = async ( : {}), ...(expiresAt !== undefined ? { expiresAt } : {}), lastRefreshAt: now, + credentialGeneration: (credentials.credentialGeneration ?? 0) + 1, }, refreshed: true, } @@ -685,7 +688,7 @@ const parseRefreshJSON = (body: string): Record & { } const refreshError = (status: number, body: string): Error => { - let message = body.trim() + let message = "provider rejected the refresh" let providerCode: string | undefined let providerType: string | undefined try { @@ -694,13 +697,15 @@ const refreshError = (status: number, body: string): Error => { } if (typeof payload.error === "string") { message = payload.error + providerCode = payload.error } else if (payload.error) { - message = payload.error.message ?? message providerCode = payload.error.code providerType = payload.error.type + message = providerCode ?? providerType ?? message } } catch { - // Keep the raw provider body in the error message. + // Provider response bodies can contain echoed credentials. Status is enough + // to diagnose this failure without persisting an untrusted body. } const error = new Error(`OAuth refresh failed (${status}): ${message}`) Object.assign(error, { status, providerCode, providerType }) @@ -724,8 +729,23 @@ export const refreshFailureFromError = ( export const terminalRefreshFailure = (failure: OAuthRefreshFailure): boolean => { if (failure.status !== 400 && failure.status !== 401) return false const combined = `${failure.providerCode ?? ""} ${failure.message}`.toLowerCase() - return combined.includes("refresh_token") || combined.includes("refresh token") -} + return ( + combined.includes("invalid_grant") || + combined.includes("invalid grant") || + combined.includes("refresh_token") || + combined.includes("refresh token") + ) +} + +// A transport failure or malformed success response is ambiguous: the provider +// may have rotated the refresh token before the response was lost. Retrying that +// old token can invalidate the only recoverable credential chain, so central +// refresh stops and asks for repair instead of guessing. +export const uncertainRefreshFailure = (failure: OAuthRefreshFailure): boolean => + failure.status === 0 + +export const blockingRefreshFailure = (failure: OAuthRefreshFailure): boolean => + terminalRefreshFailure(failure) || uncertainRefreshFailure(failure) export const jwtExpiryMillis = (token: string | undefined): number | null => { if (!token) return null diff --git a/cloudflare/packages/worker/src/index.ts b/cloudflare/packages/worker/src/index.ts index 8aaaf8183..7b28425f5 100644 --- a/cloudflare/packages/worker/src/index.ts +++ b/cloudflare/packages/worker/src/index.ts @@ -7,6 +7,8 @@ import { } from "@subrouter/core" import { authModeForAccount, + blockingRefreshFailure, + credentialExpiresAt, credentialNeedsRefresh, fetchProviderUsage, isOAuthKind, @@ -21,7 +23,6 @@ import { setUpstreamAuthHeaders, stripSubrouterHeaders, stickySessionId, - terminalRefreshFailure, upstreamURLForRequest, usageStatus, type AccountCredentials, @@ -74,6 +75,55 @@ interface UsageInput { readonly accountId: string } +interface CredentialLeaseInput extends RouteInput { + readonly upstreamProvider: UpstreamProvider +} + +interface CredentialLeaseOutput { + readonly leaseId: string + readonly accountId: string + readonly provider: UpstreamProvider + readonly authMode: "oauth" | "apikey" + readonly token: string + readonly providerAccountId?: string + readonly label: string + readonly email?: string + readonly credentialGeneration: number + readonly issuedAt: string + readonly expiresAt: string + readonly credentialExpiresAt?: string +} + +type CredentialLeaseOutcome = + | "success" + | "unauthorized" + | "rate_limited" + | "provider_error" + +interface CredentialLeaseEventInput { + readonly orgId?: string + readonly leaseId: string + readonly outcome: CredentialLeaseOutcome + readonly statusCode?: number +} + +interface CredentialLeaseRow { + readonly [key: string]: SqlStorageValue + readonly id: string + readonly org_id: string + readonly account_id: string + readonly agent_type: string + readonly session_id: string + readonly quota_key: string + readonly provider: string + readonly credential_generation: number + readonly issued_at: number + readonly expires_at: number + readonly last_outcome: string | null + readonly last_status_code: number | null + readonly reported_at: number | null +} + interface TotpConfig { readonly seed: string readonly digits?: number @@ -95,6 +145,7 @@ interface UpsertAccountInput { interface TenantAccountUploadInput { readonly validate: boolean + readonly adopt: boolean readonly account: UpsertAccountInput } @@ -112,6 +163,9 @@ interface TenantAccountOutput { type UpstreamProvider = "claude" | "codex" type WaitUntil = (promise: Promise) => void +const credentialLeaseTTLms = 5 * 60 * 1000 +const credentialLeaseRetentionMs = 24 * 60 * 60 * 1000 + interface AccountHealthOutput { readonly ok: boolean readonly lastQuotaErrorAt?: string @@ -146,6 +200,7 @@ interface StoredAccount extends Account { readonly lastQuotaErrorAt?: number readonly lastQuotaErrorCode?: string readonly consecutiveQuotaErrors?: number + readonly credentialBlocked?: boolean } interface RouteOutput { @@ -411,6 +466,72 @@ const parseUsageInput = async (request: Request): Promise return input } +const parseCredentialLeaseInput = async ( + request: Request, + orgId: string +): Promise => { + const record = await parseJsonRecord(request) + if (record instanceof Response) return record + + const upstreamProvider = nonEmptyString(record["provider"]) + if (upstreamProvider !== "codex" && upstreamProvider !== "claude") { + return json({ error: "provider must be codex or claude" }, { status: 400 }) + } + const sessionId = nonEmptyString(record["sessionId"]) + if (!sessionId || sessionId.length > 512) { + return json({ error: "sessionId is required" }, { status: 400 }) + } + const agentType = + normalizeAgentType(nonEmptyString(record["agentType"])) || + upstreamProvider + const userEmail = nonEmptyString(record["userEmail"]) + const preferAccountId = nonEmptyString(record["preferAccountId"]) + const model = nonEmptyString(record["model"]) + + return { + orgId, + upstreamProvider, + agentType, + sessionId, + ...(userEmail ? { userEmail } : {}), + ...(preferAccountId ? { preferAccountId } : {}), + ...(model ? { model } : {}), + } +} + +const parseCredentialLeaseEventInput = async ( + request: Request, + orgId: string, + leaseId: string +): Promise => { + const record = await parseJsonRecord(request) + if (record instanceof Response) return record + const outcome = nonEmptyString(record["outcome"]) + if ( + outcome !== "success" && + outcome !== "unauthorized" && + outcome !== "rate_limited" && + outcome !== "provider_error" + ) { + return json({ error: "invalid lease outcome" }, { status: 400 }) + } + const rawStatus = record["statusCode"] + if ( + rawStatus !== undefined && + (!Number.isInteger(rawStatus) || + (rawStatus as number) < 100 || + (rawStatus as number) > 599) + ) { + return json({ error: "invalid statusCode" }, { status: 400 }) + } + return { + orgId, + leaseId, + outcome, + ...(typeof rawStatus === "number" ? { statusCode: rawStatus } : {}), + } +} + const parseUpsertAccountInput = async ( request: Request ): Promise => { @@ -471,7 +592,8 @@ const parseTenantAccountUploadInput = async ( try { const input = accountInputForTenantUpload(provider, label, tenantId, record) const validate = new URL(request.url).searchParams.get("validate") === "1" - return { validate, account: input } + const adopt = new URL(request.url).searchParams.get("adopt") === "1" + return { validate, adopt, account: input } } catch (error) { return json({ error: String((error as Error).message ?? error) }, { status: 400 }) } @@ -616,6 +738,12 @@ const safeTenantAccount = ( } const accountHealth = (account: StoredAccount): AccountHealthOutput => { + if (account.credentialBlocked) { + return { + ok: false, + message: "Credential requires repair before it can be leased.", + } + } if (!account.lastQuotaErrorAt) return { ok: true } return { ok: false, @@ -845,8 +973,27 @@ const rowToAccount = (row: AccountRow): StoredAccount => ({ ...(row.consecutive_quota_errors !== null ? { consecutiveQuotaErrors: row.consecutive_quota_errors } : {}), + ...(!row.enabled || accountRowRefreshBlocked(row) + ? { credentialBlocked: true } + : {}), }) +const accountRowRefreshBlocked = (row: AccountRow): boolean => { + if (!isOAuthKind(row.kind as AccountKind)) return false + if (!row.credentials_json) return false + try { + const credentials = JSON.parse( + row.credentials_json + ) as AccountCredentials + return Boolean( + credentials.refreshFailure && + blockingRefreshFailure(credentials.refreshFailure) + ) + } catch { + return true + } +} + const quotaRowsToRecord = ( rows: ReadonlyArray ): AccountModelQuotas => { @@ -1473,6 +1620,23 @@ export class SubrouterDurableObject extends DurableObject { ON transcript_events(org_id, agent_type, session_id, event_id); CREATE INDEX IF NOT EXISTS transcript_events_org_time_idx ON transcript_events(org_id, timestamp); + CREATE TABLE IF NOT EXISTS credential_leases( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + account_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + session_id TEXT NOT NULL, + quota_key TEXT NOT NULL, + provider TEXT NOT NULL, + credential_generation INTEGER NOT NULL, + issued_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_outcome TEXT, + last_status_code INTEGER, + reported_at INTEGER + ); + CREATE INDEX IF NOT EXISTS credential_leases_org_expiry_idx + ON credential_leases(org_id, expires_at); CREATE TABLE IF NOT EXISTS lifecycle( id INTEGER PRIMARY KEY CHECK (id = 1), draining INTEGER NOT NULL DEFAULT 0, @@ -1676,6 +1840,248 @@ export class SubrouterDurableObject extends DurableObject { } } + async issueCredentialLease( + input: CredentialLeaseInput + ): Promise { + const routed = await this.route(input) + const now = Date.now() + let row = this.getAccountRow( + this.ctx.storage.sql, + routed.account.orgId, + routed.account.id, + true + ) + if (!row) throw new Error("selected account disappeared") + + let credentials = row.credentials_json + ? (JSON.parse(row.credentials_json) as AccountCredentials) + : undefined + const kind = row.kind as AccountKind + const currentCredentialExpiry = credentialExpiresAt(credentials) + if ( + isOAuthKind(kind) && + (!currentCredentialExpiry || + currentCredentialExpiry < now + credentialLeaseTTLms) + ) { + try { + row = await this.refreshAccountIfExpired( + routed.account.orgId, + routed.account.id, + true + ) + } catch (error) { + const failed = this.getAccountRow( + this.ctx.storage.sql, + routed.account.orgId, + routed.account.id, + true + ) + if (failed && accountRowRefreshBlocked(failed)) { + // A terminal or ambiguous refresh failure removes this account from + // eligibility. Route the same request again so another healthy team + // credential can carry it without exposing the broken chain. + const { + preferAccountId: _failedPreferredAccount, + ...retryInput + } = input + return this.issueCredentialLease(retryInput) + } + throw error + } + if (!row) throw new Error("selected account disappeared") + credentials = row.credentials_json + ? (JSON.parse(row.credentials_json) as AccountCredentials) + : undefined + } + + const token = isOAuthKind(kind) + ? credentials?.accessToken + : credentials?.apiKey + if (!token) { + throw new Error("selected account has no usable credential") + } + + const credentialExpiry = credentialExpiresAt(credentials) + if ( + isOAuthKind(kind) && + credentialExpiry !== null && + credentialExpiry < now + credentialLeaseTTLms + ) { + throw new Error("selected account credential expires before the lease") + } + + const leaseId = crypto.randomUUID() + const expiresAt = now + credentialLeaseTTLms + const generation = credentials?.credentialGeneration ?? 0 + this.ctx.storage.sql.exec( + `DELETE FROM credential_leases WHERE expires_at < ?`, + now - credentialLeaseRetentionMs + ) + this.ctx.storage.sql.exec( + `INSERT INTO credential_leases( + id, + org_id, + account_id, + agent_type, + session_id, + quota_key, + provider, + credential_generation, + issued_at, + expires_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + leaseId, + routed.account.orgId, + routed.account.id, + this.resolveAgentType(input.agentType), + stickySessionId( + this.resolveAgentType(input.agentType), + this.requireNonEmpty(input.sessionId, "sessionId") + ), + routed.quotaKey, + input.upstreamProvider, + generation, + now, + expiresAt + ) + + const safe = safeGoAccount({ + ...this.accountFromRow(row), + ...(credentials ? { credentials } : {}), + }) + return { + leaseId, + accountId: row.id, + provider: input.upstreamProvider, + authMode: authModeForAccount(kind), + token, + ...(credentials?.accountId + ? { providerAccountId: credentials.accountId } + : {}), + label: row.label, + ...(safe.email ? { email: safe.email } : {}), + credentialGeneration: generation, + issuedAt: new Date(now).toISOString(), + expiresAt: new Date(expiresAt).toISOString(), + ...(credentialExpiry !== null + ? { credentialExpiresAt: new Date(credentialExpiry).toISOString() } + : {}), + } + } + + async recordCredentialLeaseEvent( + input: CredentialLeaseEventInput + ): Promise<{ ok: true; refreshState?: "refreshed" }> { + const orgId = this.resolveOrgId(input.orgId) + const leaseId = this.requireNonEmpty(input.leaseId, "leaseId") + const lease = this.ctx.storage.sql + .exec( + `SELECT * FROM credential_leases WHERE id = ? AND org_id = ?`, + leaseId, + orgId + ) + .toArray()[0] + if (!lease) throw new Error("credential lease not found") + + const now = Date.now() + this.ctx.storage.sql.exec( + `UPDATE credential_leases + SET last_outcome = ?, last_status_code = ?, reported_at = ? + WHERE id = ? AND org_id = ?`, + input.outcome, + input.statusCode ?? null, + now, + leaseId, + orgId + ) + + if (input.outcome === "success") { + await this.clearAccountQuotaError({ + orgId, + accountId: lease.account_id, + }) + return { ok: true } + } + if (input.outcome === "rate_limited") { + await this.recordAccountQuotaError({ + orgId, + accountId: lease.account_id, + code: String(input.statusCode ?? 429), + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND agent_type = ? AND quota_key = ? + AND session_id = ? AND account_id = ?`, + orgId, + lease.agent_type, + lease.quota_key, + lease.session_id, + lease.account_id + ) + return { ok: true } + } + if (input.outcome === "unauthorized") { + const current = this.getAccountRow( + this.ctx.storage.sql, + orgId, + lease.account_id, + true + ) + const currentCredentials = current?.credentials_json + ? (JSON.parse(current.credentials_json) as AccountCredentials) + : undefined + if ( + (currentCredentials?.credentialGeneration ?? 0) !== + lease.credential_generation + ) { + return { ok: true } + } + if (current && !isOAuthKind(current.kind as AccountKind)) { + // API keys cannot be refreshed. Remove a rejected key from routing + // until a team manager repairs it in place. + this.ctx.storage.sql.exec( + `UPDATE accounts SET enabled = 0, updated_at = ? + WHERE id = ? AND org_id = ?`, + now, + lease.account_id, + orgId + ) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND account_id = ?`, + orgId, + lease.account_id + ) + return { ok: true } + } + if (current && !currentCredentials?.refreshToken) { + // Legacy access-only OAuth rows can serve until their access token is + // rejected. At that point central refresh is impossible, so freeze the + // row instead of leasing the same known-bad token forever. + this.updateAccountCredentials(lease.account_id, { + ...currentCredentials, + refreshFailure: { + at: now, + status: 401, + message: + "provider rejected the access token and the central refresh token is missing", + providerCode: "missing_refresh_token", + }, + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND account_id = ?`, + orgId, + lease.account_id + ) + return { ok: true } + } + await this.refreshAccountIfExpired(orgId, lease.account_id, true) + return { ok: true, refreshState: "refreshed" } + } + return { ok: true } + } + async recordUsage(input: UsageInput): Promise<{ ok: true }> { const orgId = this.resolveOrgId(input.orgId) const sessionId = this.requireNonEmpty(input.sessionId, "sessionId") @@ -1801,6 +2207,38 @@ export class SubrouterDurableObject extends DurableObject { return { account } } + async adoptAccountCredentials(input: { + readonly orgId?: string + readonly accountId: string + }): Promise<{ account: StoredAccount }> { + const orgId = this.resolveOrgId(input.orgId) + const accountId = this.requireNonEmpty(input.accountId, "accountId") + const row = this.getAccountRow( + this.ctx.storage.sql, + orgId, + accountId, + true + ) + if (!row) throw new Error("account not found") + if (isOAuthKind(row.kind as AccountKind)) { + const refreshed = await this.refreshAccountIfExpired( + orgId, + accountId, + true + ) + if (!refreshed) throw new Error("account disappeared during adoption") + } + const account = this.getAccount( + this.ctx.storage.sql, + orgId, + accountId, + false + ) + if (!account) throw new Error("account disappeared during adoption") + await this.scheduleNextRefreshAlarm() + return { account } + } + async listAccounts(orgId: string): Promise<{ accounts: ReadonlyArray }> { return { accounts: this.ctx.storage.sql @@ -1843,6 +2281,62 @@ export class SubrouterDurableObject extends DurableObject { return { ok: true } } + async repairAccount(input: { + readonly orgId?: string + readonly accountId: string + readonly replacement: UpsertAccountInput + }): Promise<{ account: StoredAccount }> { + const orgId = this.resolveOrgId(input.orgId) + const accountId = this.requireNonEmpty(input.accountId, "accountId") + const existing = this.getAccountRow( + this.ctx.storage.sql, + orgId, + accountId, + false + ) + if (!existing) throw new Error("account not found") + if (existing.kind !== input.replacement.kind) { + throw new Error("replacement provider does not match account") + } + const existingCredentials = existing.credentials_json + ? (JSON.parse(existing.credentials_json) as AccountCredentials) + : undefined + const replacementCredentials = input.replacement.credentials + ? { + ...input.replacement.credentials, + credentialGeneration: + (existingCredentials?.credentialGeneration ?? 0) + 1, + refreshFailure: undefined, + } + : undefined + const repaired = await this.upsertAccount({ + ...input.replacement, + id: accountId, + orgId, + label: input.replacement.label || existing.label, + enabled: true, + rateLimitRemaining: undefined, + ...(replacementCredentials + ? { credentials: replacementCredentials } + : {}), + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND account_id = ?`, + orgId, + accountId + ) + // Reports from an access token issued before repair must not refresh or + // penalize the replacement credential chain. + this.ctx.storage.sql.exec( + `DELETE FROM credential_leases + WHERE org_id = ? AND account_id = ?`, + orgId, + accountId + ) + return repaired + } + async accountStatuses(orgId: string, forceRefresh: boolean): Promise> { const rows = this.ctx.storage.sql .exec( @@ -2188,10 +2682,12 @@ export class SubrouterDurableObject extends DurableObject { orgId ) .toArray() + .filter((row) => !accountRowRefreshBlocked(row)) .map((row) => this.accountFromRow(row)) - .filter((account) => - accountMatchesUpstreamProvider(account, upstreamProvider) && - accountHasQuotaForModel(account, quotaKey) + .filter( + (account) => + accountMatchesUpstreamProvider(account, upstreamProvider) && + accountHasQuotaForModel(account, quotaKey) ) } @@ -2203,7 +2699,9 @@ export class SubrouterDurableObject extends DurableObject { enabledOnly: boolean, upstreamProvider: UpstreamProvider | undefined ): StoredAccount | null { - const account = this.getAccount(sql, orgId, accountId, enabledOnly) + const row = this.getAccountRow(sql, orgId, accountId, enabledOnly) + if (!row || accountRowRefreshBlocked(row)) return null + const account = this.accountFromRow(row) if (!account) return null return accountMatchesUpstreamProvider(account, upstreamProvider) && accountHasQuotaForModel(account, quotaKey) @@ -2277,7 +2775,7 @@ export class SubrouterDurableObject extends DurableObject { ...credentials, refreshFailure: failure, } - if (terminalRefreshFailure(failure)) { + if (blockingRefreshFailure(failure)) { this.updateAccountCredentials(row.id, nextCredentials) } throw error @@ -2357,7 +2855,10 @@ export class SubrouterDurableObject extends DurableObject { const now = Date.now() for (const row of rows) { const credentials = JSON.parse(row.credentials_json ?? "{}") as AccountCredentials - if (credentials.refreshFailure && terminalRefreshFailure(credentials.refreshFailure)) { + if ( + credentials.refreshFailure && + blockingRefreshFailure(credentials.refreshFailure) + ) { continue } const candidate = nextRefreshAt(credentials, now) @@ -3693,6 +4194,48 @@ const handleFetch = async ( } } + if (url.pathname === "/tenant/leases" && request.method === "POST") { + const tenant = await authorizeTenant(request, env, telemetry) + if (tenant instanceof Response) return tenant + if (tenant.legacy) { + return json({ error: "Tenant key required" }, { status: 401 }) + } + const input = await parseCredentialLeaseInput(request, tenant.tenantId) + if (input instanceof Response) return input + try { + return json(await tenantActor(env, tenant).issueCredentialLease(input)) + } catch (error) { + if (telemetry) telemetry.errorType = errorTypeFor(error) + return errorJson(error, 409) + } + } + + const tenantLeaseEventMatch = url.pathname.match( + /^\/tenant\/leases\/([^/]+)\/events$/ + ) + if (tenantLeaseEventMatch && request.method === "POST") { + const tenant = await authorizeTenant(request, env, telemetry) + if (tenant instanceof Response) return tenant + if (tenant.legacy) { + return json({ error: "Tenant key required" }, { status: 401 }) + } + const leaseId = decodeURIComponent(tenantLeaseEventMatch[1]!) + const input = await parseCredentialLeaseEventInput( + request, + tenant.tenantId, + leaseId + ) + if (input instanceof Response) return input + try { + return json( + await tenantActor(env, tenant).recordCredentialLeaseEvent(input) + ) + } catch (error) { + if (telemetry) telemetry.errorType = errorTypeFor(error) + return errorJson(error, 404) + } + } + if (url.pathname === "/tenant/accounts" && request.method === "POST") { const tenant = await authorizeTenant(request, env, telemetry) if (tenant instanceof Response) return tenant @@ -3711,7 +4254,14 @@ const handleFetch = async ( } const actor = tenantActor(env, tenant) try { - const { account } = await actor.upsertAccount(input.account) + let { account } = await actor.upsertAccount(input.account) + if (input.adopt) { + const adopted = await actor.adoptAccountCredentials({ + orgId: tenant.tenantId, + accountId: account.id, + }) + account = adopted.account + } return json(safeTenantAccount(account, validation)) } catch (error) { if (telemetry) telemetry.errorType = errorTypeFor(error) @@ -3729,6 +4279,53 @@ const handleFetch = async ( return json({ accounts: accounts.map((account) => safeTenantAccount(account)) }) } + const tenantAccountRepairMatch = url.pathname.match( + /^\/tenant\/accounts\/([^/]+)\/repair$/ + ) + if (tenantAccountRepairMatch && request.method === "POST") { + const tenant = await authorizeTenant(request, env, telemetry) + if (tenant instanceof Response) return tenant + if (tenant.legacy) { + return json({ error: "Tenant key required" }, { status: 401 }) + } + const accountId = decodeURIComponent(tenantAccountRepairMatch[1]!) + const input = await parseTenantAccountUploadInput( + request, + tenant.tenantId + ) + if (input instanceof Response) return input + const validation = input.validate + ? await validateTenantAccountUpload(input.account, { + timeoutMs: validationTimeoutMs(env), + }) + : undefined + if (validation === "failed") { + return json( + { error: "Account validation failed", validation }, + { status: 400 } + ) + } + try { + const actor = tenantActor(env, tenant) + let { account } = await actor.repairAccount({ + orgId: tenant.tenantId, + accountId, + replacement: input.account, + }) + if (input.adopt) { + const adopted = await actor.adoptAccountCredentials({ + orgId: tenant.tenantId, + accountId, + }) + account = adopted.account + } + return json(safeTenantAccount(account, validation)) + } catch (error) { + if (telemetry) telemetry.errorType = errorTypeFor(error) + return errorJson(error, 400) + } + } + const tenantAccountDeleteMatch = url.pathname.match(/^\/tenant\/accounts\/([^/]+)$/) if (tenantAccountDeleteMatch && request.method === "DELETE") { const tenant = await authorizeTenant(request, env, telemetry) diff --git a/cloudflare/packages/worker/src/telemetry.ts b/cloudflare/packages/worker/src/telemetry.ts index a8154dc91..92d61115f 100644 --- a/cloudflare/packages/worker/src/telemetry.ts +++ b/cloudflare/packages/worker/src/telemetry.ts @@ -107,7 +107,14 @@ export const routePatternForRequest = ( if (path === "/usage") return "/usage" if (path === "/status") return "/status" if (path === "/tenant/accounts") return "/tenant/accounts" + if (/^\/tenant\/accounts\/[^/]+\/repair$/.test(path)) { + return "/tenant/accounts/:id/repair" + } if (/^\/tenant\/accounts\/[^/]+$/.test(path)) return "/tenant/accounts/:id" + if (path === "/tenant/leases") return "/tenant/leases" + if (/^\/tenant\/leases\/[^/]+\/events$/.test(path)) { + return "/tenant/leases/:id/events" + } if (path === "/admin/tenants") return "/admin/tenants" if (/^\/admin\/tenants\/[^/]+\/revoke$/.test(path)) return "/admin/tenants/:id/revoke" if (/^\/admin\/tenants\/[^/]+\/rotate$/.test(path)) return "/admin/tenants/:id/rotate" diff --git a/cloudflare/packages/worker/test/contract.test.ts b/cloudflare/packages/worker/test/contract.test.ts index 5fe55a70e..11ddf3440 100644 --- a/cloudflare/packages/worker/test/contract.test.ts +++ b/cloudflare/packages/worker/test/contract.test.ts @@ -1,9 +1,11 @@ import { describe, expect, test } from "bun:test" import { accountStatus, + blockingRefreshFailure, credentialNeedsRefresh, fetchProviderUsage, refreshOAuthCredentials, + refreshFailureFromError, parseProxyRouteInput, redactedUpstreamURL, safeGoAccount, @@ -219,6 +221,77 @@ describe("subrouter Durable Object contract", () => { expect(refreshed.credentials.expiresAt).toBe(now + 3_600_000) }) + test("invalid_grant is terminal and raw refresh bodies are never persisted", async () => { + const secret = "sk-refresh-response-secret" + let caught: unknown + try { + await refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "old-refresh", + expiresAt: 1, + }, + true, + (async () => + new Response( + JSON.stringify({ + error: "invalid_grant", + detail: secret, + }), + { status: 400 }, + )) as unknown as typeof fetch, + ) + } catch (error) { + caught = error + } + const failure = refreshFailureFromError(caught) + expect(blockingRefreshFailure(failure)).toBe(true) + expect(JSON.stringify(failure)).not.toContain(secret) + }) + + test("an ambiguous refresh freezes the old rotation token", async () => { + let attempts = 0 + let caught: unknown + try { + await refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "rotation-token", + expiresAt: 1, + }, + true, + (async () => { + attempts++ + throw new TypeError("connection reset after write") + }) as unknown as typeof fetch, + ) + } catch (error) { + caught = error + } + const failure = refreshFailureFromError(caught) + expect(blockingRefreshFailure(failure)).toBe(true) + + await expect( + refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "rotation-token", + expiresAt: 1, + refreshFailure: failure, + }, + true, + (async () => { + attempts++ + return Response.json({ access_token: "must-not-happen" }) + }) as unknown as typeof fetch, + ), + ).rejects.toThrow() + expect(attempts).toBe(1) + }) + test("codex usage fetch parses base and model-family windows", async () => { const calls: Request[] = [] const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => { diff --git a/cloudflare/packages/worker/test/credential-lease.test.ts b/cloudflare/packages/worker/test/credential-lease.test.ts new file mode 100644 index 000000000..bf9e0b4f5 --- /dev/null +++ b/cloudflare/packages/worker/test/credential-lease.test.ts @@ -0,0 +1,460 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { + cleanupWorkers, + createTenant, + startWorker, +} from "./helpers/worker.ts" + +const servers: Array<{ stop: () => void }> = [] + +afterEach(async () => { + await cleanupWorkers() + for (const server of servers.splice(0)) server.stop() +}) + +describe("tenant credential leases", () => { + test("refreshes centrally once, returns access-only leases, and persists rotation", async () => { + const refreshTokens: string[] = [] + let refreshCount = 0 + const tokenServer = Bun.serve({ + port: 0, + async fetch(request) { + const form = new URLSearchParams(await request.text()) + refreshTokens.push(form.get("refresh_token") ?? "") + refreshCount++ + return Response.json({ + access_token: `claude-access-${refreshCount}`, + refresh_token: `claude-refresh-${refreshCount}`, + expires_in: 3600, + }) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Lease Tenant") + const uploaded = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "shared@example.com", + claudeAiOauth: { + accessToken: "claude-access-expired", + refreshToken: "claude-refresh-original", + expiresAt: Date.now() - 60_000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }) + expect(uploaded.status).toBe(200) + + const [first, second] = await Promise.all([ + requestLease(worker.baseURL, tenant.key, "session-a"), + requestLease(worker.baseURL, tenant.key, "session-b"), + ]) + expect(first.response.status).toBe(200) + expect(second.response.status).toBe(200) + expect(refreshCount).toBe(1) + expect(first.body.token).toBe("claude-access-1") + expect(second.body.token).toBe("claude-access-1") + expect(first.body.authMode).toBe("oauth") + expect(first.body.provider).toBe("claude") + expect(first.body.credentialGeneration).toBe(1) + expect(Date.parse(first.body.expiresAt) - Date.parse(first.body.issuedAt)).toBe(5 * 60 * 1000) + + const serialized = JSON.stringify([first.body, second.body]) + expect(serialized).not.toContain("claude-refresh") + expect(serialized).not.toContain("idToken") + expect(serialized).not.toContain("refreshToken") + + const unauthorized = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(first.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(unauthorized.status).toBe(200) + const unauthorizedBody = await unauthorized.json() as { + ok: boolean + refreshState: string + } + expect(unauthorizedBody).toEqual({ ok: true, refreshState: "refreshed" }) + expect(refreshTokens).toEqual([ + "claude-refresh-original", + "claude-refresh-1", + ]) + + const staleUnauthorized = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(second.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(staleUnauthorized.status).toBe(200) + const staleUnauthorizedBody = await staleUnauthorized.json() as { + ok: boolean + } + expect(staleUnauthorizedBody).toEqual({ ok: true }) + expect(refreshCount).toBe(2) + }, 60_000) + + test("adopts an OAuth refresh chain before acknowledging upload", async () => { + let refreshCount = 0 + const tokenServer = Bun.serve({ + port: 0, + fetch() { + refreshCount++ + return Response.json({ + access_token: "central-access", + refresh_token: "central-refresh", + expires_in: 3600, + }) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Adoption") + const uploaded = await fetch( + `${worker.baseURL}/tenant/accounts?adopt=1`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "adopt@example.com", + claudeAiOauth: { + accessToken: "laptop-access", + refreshToken: "laptop-refresh", + expiresAt: Date.now() + 60 * 60 * 1000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }, + ) + expect(uploaded.status).toBe(200) + expect(refreshCount).toBe(1) + const uploadedText = await uploaded.text() + expect(uploadedText).not.toContain("central-access") + expect(uploadedText).not.toContain("central-refresh") + + const lease = await requestLease(worker.baseURL, tenant.key, "adopted") + expect(lease.response.status).toBe(200) + expect(lease.body.token).toBe("central-access") + expect(lease.body.credentialGeneration).toBe(1) + expect(refreshCount).toBe(1) + }, 60_000) + + test("rejects lease events from another tenant", async () => { + const worker = await startWorker() + const owner = await createTenant(worker.baseURL, "Owner") + const attacker = await createTenant(worker.baseURL, "Attacker") + const uploaded = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(owner.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "shared key", + apiKey: "sk-ant-lease-test", + }), + }) + expect(uploaded.status).toBe(200) + + const lease = await requestLease(worker.baseURL, owner.key, "session-owner") + expect(lease.response.status).toBe(200) + const crossTenant = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(lease.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(attacker.key), + body: JSON.stringify({ outcome: "success", statusCode: 200 }), + }, + ) + expect(crossTenant.status).toBe(404) + expect(await crossTenant.text()).not.toContain("sk-ant-lease-test") + }, 60_000) + + test("removes a rejected API key from routing until it is repaired", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Rejected API key") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "rejected", + apiKey: "sk-ant-rejected", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "healthy", + apiKey: "sk-ant-healthy", + }), + }) + expect(second.status).toBe(200) + + const rejectedLease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "rejected-key", + preferAccountId: firstBody.id, + }), + }) + const rejectedLeaseBody = await rejectedLease.json() as { + leaseId: string + token: string + } + expect(rejectedLease.status).toBe(200) + expect(rejectedLeaseBody.token).toBe("sk-ant-rejected") + + const unauthorized = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(rejectedLeaseBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(unauthorized.status).toBe(200) + + const accounts = await fetch(`${worker.baseURL}/tenant/accounts`, { + headers: tenantHeaders(tenant.key), + }) + const accountsBody = await accounts.json() as { + accounts: Array<{ id: string; health: { ok: boolean; message?: string } }> + } + expect( + accountsBody.accounts.find((account) => account.id === firstBody.id)?.health, + ).toEqual({ + ok: false, + message: "Credential requires repair before it can be leased.", + }) + + const replacement = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "healthy-key", + preferAccountId: firstBody.id, + }), + }) + const replacementBody = await replacement.json() as { token: string } + expect(replacement.status).toBe(200) + expect(replacementBody.token).toBe("sk-ant-healthy") + }, 60_000) + + test("routes around an account whose central refresh needs repair", async () => { + let refreshCount = 0 + const tokenServer = Bun.serve({ + port: 0, + fetch() { + refreshCount++ + return Response.json( + { error: "invalid_grant", error_description: "repair required" }, + { status: 400 }, + ) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Refresh fallback") + const broken = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "broken oauth", + claudeAiOauth: { + accessToken: "expired-access", + refreshToken: "broken-refresh", + expiresAt: Date.now() - 60_000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }) + const brokenBody = await broken.json() as { id: string } + expect(broken.status).toBe(200) + const healthy = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "healthy fallback", + apiKey: "sk-ant-healthy-fallback", + }), + }) + expect(healthy.status).toBe(200) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "refresh-fallback", + preferAccountId: brokenBody.id, + }), + }) + const leaseBody = await lease.json() as { + authMode: string + token: string + } + expect(lease.status).toBe(200) + expect(leaseBody.authMode).toBe("apikey") + expect(leaseBody.token).toBe("sk-ant-healthy-fallback") + expect(refreshCount).toBe(1) + + const second = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "refresh-fallback-2", + preferAccountId: brokenBody.id, + }), + }) + expect(second.status).toBe(200) + expect(refreshCount).toBe(1) + }, 60_000) + + test("repairs an OAuth account in place and leases only the replacement access token", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Repair") + const future = Date.now() + 60 * 60 * 1000 + const created = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "Repair me", + claudeAiOauth: { + accessToken: "old-access", + refreshToken: "old-refresh", + expiresAt: future, + }, + }), + }) + const createdBody = await created.json() as { id: string } + expect(created.status).toBe(200) + const oldLease = await requestLease( + worker.baseURL, + tenant.key, + "pre-repair-session", + ) + expect(oldLease.response.status).toBe(200) + expect(oldLease.body.credentialGeneration).toBe(0) + + const repaired = await fetch( + `${worker.baseURL}/tenant/accounts/${encodeURIComponent(createdBody.id)}/repair`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "Repair me", + claudeAiOauth: { + accessToken: "replacement-access", + refreshToken: "replacement-refresh", + expiresAt: future, + }, + }), + }, + ) + expect(repaired.status).toBe(200) + const repairedText = await repaired.text() + expect(repairedText).not.toContain("replacement-access") + expect(repairedText).not.toContain("replacement-refresh") + + const staleEvent = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(oldLease.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(staleEvent.status).toBe(404) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "repair-session", + preferAccountId: createdBody.id, + }), + }) + const leaseBody = await lease.json() as { + accountId: string + token: string + credentialGeneration: number + } + expect(lease.status).toBe(200) + expect(leaseBody.accountId).toBe(createdBody.id) + expect(leaseBody.token).toBe("replacement-access") + expect(leaseBody.credentialGeneration).toBe(1) + }, 60_000) +}) + +const requestLease = async ( + baseURL: string, + tenantKey: string, + sessionId: string, +): Promise<{ + response: Response + body: { + leaseId: string + token: string + provider: string + authMode: string + credentialGeneration: number + issuedAt: string + expiresAt: string + } +}> => { + const response = await fetch(`${baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenantKey), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId, + }), + }) + return { + response, + body: await response.json() as { + leaseId: string + token: string + provider: string + authMode: string + credentialGeneration: number + issuedAt: string + expiresAt: string + }, + } +} + +const tenantHeaders = (tenantKey: string): HeadersInit => ({ + Authorization: `Bearer ${tenantKey}`, + "Content-Type": "application/json", +}) diff --git a/cmd/subrouter/cloud_mode_test.go b/cmd/subrouter/cloud_mode_test.go new file mode 100644 index 000000000..e6882fc18 --- /dev/null +++ b/cmd/subrouter/cloud_mode_test.go @@ -0,0 +1,209 @@ +package main + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/manaflow-ai/subrouter/internal/accounts" + "github.com/manaflow-ai/subrouter/internal/broker" +) + +func saveReadyCloudConfig(t *testing.T) { + t.Helper() + path := filepath.Join(t.TempDir(), "cloud.json") + t.Setenv("SUBROUTER_CLOUD_CONFIG", path) + if err := broker.SaveConfig(path, broker.Config{ + BaseURL: "https://cmux.test", + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + TeamName: "Team A", + }); err != nil { + t.Fatal(err) + } +} + +func TestCloudCodexAlwaysUsesLocalProxy(t *testing.T) { + saveReadyCloudConfig(t) + local := healthServer(t, 200) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + store := srServerStore{Path: filepath.Join(t.TempDir(), "servers.json")} + if err := store.save(srServerFile{ + Default: "remote", + Servers: []srServerConfig{{ + Name: "remote", + URL: "http://remote.example:31415", + }}, + }); err != nil { + t.Fatal(err) + } + var warnings bytes.Buffer + got, err := codexBaseURLWithFallback(store, &warnings) + if err != nil { + t.Fatal(err) + } + if got != local.URL+"/v1" { + t.Fatalf("base URL = %q, want local proxy", got) + } + if strings.Contains(warnings.String(), "remote.example") { + t.Fatalf("cloud mode should not probe or fall back through the legacy remote: %q", warnings.String()) + } +} + +func TestCloudClaudeEnvironmentRoutesLocallyWithoutProviderSecrets(t *testing.T) { + env := cloudClaudeEnvironment([]string{ + "PATH=/usr/bin", + "ANTHROPIC_BASE_URL=https://remote.example", + "ANTHROPIC_AUTH_TOKEN=old-token", + "ANTHROPIC_API_KEY=sk-ant-secret", + "CLAUDE_CODE_USE_BEDROCK=1", + }, "http://127.0.0.1:31415/v1", "stack-local-token") + joined := strings.Join(env, "\n") + for _, banned := range []string{ + "https://remote.example", + "old-token", + "sk-ant-secret", + "CLAUDE_CODE_USE_BEDROCK", + } { + if strings.Contains(joined, banned) { + t.Fatalf("cloud Claude env retained %q:\n%s", banned, joined) + } + } + for _, want := range []string{ + "ANTHROPIC_BASE_URL=http://127.0.0.1:31415", + "ANTHROPIC_AUTH_TOKEN=stack-local-token", + } { + if !strings.Contains(joined, want) { + t.Fatalf("cloud Claude env missing %q:\n%s", want, joined) + } + } +} + +func TestCloudCodexUsesAuthenticatedLocalProvider(t *testing.T) { + args := codexArgsWithLocalProxyToken( + []string{"exec", "hello"}, + "http://127.0.0.1:31415/v1", + "", + "", + "stack-local-token", + ) + joined := strings.Join(args, "\n") + for _, want := range []string{ + `model_provider="subrouter"`, + `model_providers.subrouter.env_key="SUBROUTER_CODEX_DUMMY_API_KEY"`, + } { + if !strings.Contains(joined, want) { + t.Fatalf("cloud Codex args missing %q:\n%s", want, joined) + } + } +} + +func TestUserSystemdUnitIsLoopbackAndCloudConfigured(t *testing.T) { + unit, err := renderUserSystemdUnit( + "/home/alice", + "/home/alice/.local/bin/subrouter", + ) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "--addr 127.0.0.1:31415", + "--cloud-config /home/alice/.config/subrouter/cloud.json", + "ProtectHome=read-only", + "UMask=0077", + } { + if !strings.Contains(unit, want) { + t.Fatalf("unit missing %q:\n%s", want, unit) + } + } + if strings.Contains(unit, "0.0.0.0") { + t.Fatalf("user daemon must not bind publicly:\n%s", unit) + } +} + +func TestCloudModeConfigMissingIsLegacyMode(t *testing.T) { + t.Setenv("SUBROUTER_CLOUD_CONFIG", filepath.Join(t.TempDir(), "missing.json")) + config, err := cloudModeConfig() + if err != nil { + t.Fatal(err) + } + if config.Ready() { + t.Fatalf("missing config unexpectedly enabled cloud mode: %+v", config) + } +} + +func TestSelectLocalAccountUploadRequiresOneExactCanary(t *testing.T) { + uploads := []localAccountUpload{ + {kind: "codex", label: "alice@example.com"}, + {kind: "claude", label: "alice@example.com"}, + {kind: "codex", label: "bob@example.com"}, + } + + selected, err := selectLocalAccountUpload(uploads, "codex:alice@example.com") + if err != nil { + t.Fatal(err) + } + if len(selected) != 1 || + selected[0].kind != "codex" || + selected[0].label != "alice@example.com" { + t.Fatalf("selected = %+v", selected) + } + + if _, err := selectLocalAccountUpload(uploads, "alice@example.com"); err == nil { + t.Fatal("same-label accounts across providers must be ambiguous") + } + if _, err := selectLocalAccountUpload(uploads, "missing"); err == nil { + t.Fatal("missing selector unexpectedly matched an account") + } +} + +func TestBulkAccountImportRequiresExplicitConfirmation(t *testing.T) { + var uploads atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/subrouter/accounts": + _, _ = w.Write([]byte(`{"accounts":[]}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/subrouter/accounts": + uploads.Add(1) + _, _ = w.Write([]byte( + `{"account":{"id":"acct-1","kind":"openai-apikey","label":"paid"}}`, + )) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + store := accounts.CodexStore{Dir: t.TempDir()} + if _, _, err := store.AddAPIKey("paid", "sk-test-paid"); err != nil { + t.Fatal(err) + } + client := broker.NewClient(broker.Config{ + BaseURL: server.URL, + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + }) + var out bytes.Buffer + runner := srRunner{store: store, out: &out, errOut: &out} + + err := runner.cloudAccountImport( + context.Background(), + client, + []string{"--all"}, + ) + if err == nil || !strings.Contains(err.Error(), "--yes") { + t.Fatalf("bulk import error = %v, want --yes requirement", err) + } + if uploads.Load() != 0 { + t.Fatalf("bulk import uploaded %d accounts without confirmation", uploads.Load()) + } +} diff --git a/cmd/subrouter/codex.go b/cmd/subrouter/codex.go index b6d5db4c5..bed11328a 100644 --- a/cmd/subrouter/codex.go +++ b/cmd/subrouter/codex.go @@ -20,6 +20,11 @@ func codex(args []string) error { if err != nil { return err } + cloudConfig, err := cloudModeConfig() + if err != nil { + return err + } + localProxyToken := cloudLocalProxyToken(cloudConfig) bin := envOrDefault("SUBROUTER_CODEX_BIN", "codex") userEmailRaw := os.Getenv("SUBROUTER_CODEX_USER_EMAIL") accountID := session.NormalizeAccountID(os.Getenv("SUBROUTER_CODEX_ACCOUNT_ID")) @@ -31,12 +36,28 @@ func codex(args []string) error { } } - cmd := exec.CommandContext(context.Background(), bin, codexArgs(args, baseURL, userEmail, accountID)...) + cmd := exec.CommandContext( + context.Background(), + bin, + codexArgsWithLocalProxyToken( + args, + baseURL, + userEmail, + accountID, + localProxyToken, + )..., + ) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr env := os.Environ() - if userEmail != "" || accountID != "" || codexModelArg(args) != "" { + if localProxyToken != "" { + env = upsertEnv( + env, + "SUBROUTER_CODEX_DUMMY_API_KEY", + localProxyToken, + ) + } else if userEmail != "" || accountID != "" || codexModelArg(args) != "" { env = upsertEnv(env, "SUBROUTER_CODEX_DUMMY_API_KEY", "subrouter") } cmd.Env = env @@ -87,6 +108,23 @@ func codexBaseURLWithFallback(store srServerStore, warn io.Writer) (string, erro } return baseURL, nil } + config, err := cloudModeConfig() + if err != nil { + return "", fmt.Errorf("load cmux.com login: %w", err) + } + if config.Ready() { + local := localBaseURL() + if !ensureLocalHealthy( + context.Background(), + fallbackHTTPClient(), + local, + defaultDaemonStarter(), + warn, + ) { + return "", fmt.Errorf("local proxy is unavailable; run '%s doctor'", programBase()) + } + return local, nil + } return withLocalFallback(context.Background(), fallbackHTTPClient(), baseURL, warn), nil } @@ -113,8 +151,30 @@ func codexBaseURLForServer(server srServerConfig) string { } func codexArgs(args []string, baseURL, userEmail, accountID string) []string { + return codexArgsWithLocalProxyToken( + args, + baseURL, + userEmail, + accountID, + "", + ) +} + +func codexArgsWithLocalProxyToken( + args []string, + baseURL string, + userEmail string, + accountID string, + localProxyToken string, +) []string { model := codexModelArg(args) - configArgs := codexConfigArgs(baseURL, userEmail, accountID, model) + configArgs := codexConfigArgs( + baseURL, + userEmail, + accountID, + model, + localProxyToken != "", + ) if len(args) == 0 || strings.HasPrefix(args[0], "-") || !isKnownCodexCommand(args[0]) { return append(configArgs, args...) } @@ -127,8 +187,17 @@ func codexArgs(args []string, baseURL, userEmail, accountID string) []string { return out } -func codexConfigArgs(baseURL, userEmail, accountID, model string) []string { - if userEmail == "" && accountID == "" && model == "" { +func codexConfigArgs( + baseURL string, + userEmail string, + accountID string, + model string, + forceAuthenticatedProvider bool, +) []string { + if !forceAuthenticatedProvider && + userEmail == "" && + accountID == "" && + model == "" { return []string{"-c", "openai_base_url=" + strconv.Quote(baseURL)} } return []string{ diff --git a/cmd/subrouter/install_systemd_user.go b/cmd/subrouter/install_systemd_user.go new file mode 100644 index 000000000..3767ed8ee --- /dev/null +++ b/cmd/subrouter/install_systemd_user.go @@ -0,0 +1,111 @@ +package main + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "text/template" +) + +func userSystemdUnitPath(home, service string) string { + return filepath.Join(home, ".config", "systemd", "user", service+".service") +} + +func installUserSystemd(home string, runner commandRunner) error { + binDir := filepath.Join(home, ".local", "bin") + installPath := filepath.Join(binDir, "subrouter") + configDir := filepath.Join(home, ".config", "subrouter") + stateDir := filepath.Join(home, ".subrouter") + unitPath := userSystemdUnitPath(home, defaultSystemdServiceName) + for _, dir := range []string{ + binDir, + configDir, + stateDir, + filepath.Dir(unitPath), + } { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + } + if err := installCurrentExecutable(installPath); err != nil { + return err + } + for _, alias := range []string{"sr", "cx"} { + if err := installBinaryAlias( + installPath, + filepath.Join(binDir, alias), + ); err != nil { + return err + } + } + + unit, err := renderUserSystemdUnit(home, installPath) + if err != nil { + return err + } + if err := os.WriteFile(unitPath, []byte(unit), 0o600); err != nil { + return err + } + if err := runner.Run("systemctl", "--user", "daemon-reload"); err != nil { + return err + } + if err := runner.Run( + "systemctl", + "--user", + "enable", + "--now", + defaultSystemdServiceName, + ); err != nil { + return err + } + fmt.Printf("Installed %s\n", installPath) + fmt.Printf("Installed %s\n", unitPath) + fmt.Printf("Started %s.service (user)\n", defaultSystemdServiceName) + return nil +} + +func renderUserSystemdUnit(home, installPath string) (string, error) { + data := struct { + Home string + InstallPath string + ConfigPath string + StateDir string + }{ + Home: home, + InstallPath: installPath, + ConfigPath: filepath.Join(home, ".config", "subrouter", "cloud.json"), + StateDir: filepath.Join(home, ".subrouter"), + } + var out bytes.Buffer + if err := userSystemdTemplate.Execute(&out, data); err != nil { + return "", err + } + return out.String(), nil +} + +var userSystemdTemplate = template.Must(template.New("systemd-user").Parse(`[Unit] +Description=Subrouter local credential proxy +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +Environment=HOME={{.Home}} +ExecStart={{.InstallPath}} serve --addr 127.0.0.1:31415 --cloud-config {{.ConfigPath}} --sr-switch-interval 0 +Restart=on-failure +RestartSec=3 +TimeoutStopSec=10min +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths={{.StateDir}} {{.Home}}/.config/subrouter +RestrictSUIDSGID=true + +[Install] +WantedBy=default.target +`)) diff --git a/cmd/subrouter/lifecycle.go b/cmd/subrouter/lifecycle.go index 460f6737d..1d6b2356e 100644 --- a/cmd/subrouter/lifecycle.go +++ b/cmd/subrouter/lifecycle.go @@ -73,35 +73,71 @@ func (c launchdController) remove() error { // systemdController manages the system service written by install-systemd. type systemdController struct { service string + home string runner commandRunner } -func (c systemdController) installed() bool { +func (c systemdController) userUnit() string { + return userSystemdUnitPath(c.home, c.service) +} + +func (c systemdController) userInstalled() bool { + _, err := os.Stat(c.userUnit()) + return err == nil +} + +func (c systemdController) systemInstalled() bool { _, err := os.Stat(systemdUnitPath(systemdConfig{ServiceName: c.service})) return err == nil } -func (c systemdController) describe() string { return c.service + ".service" } +func (c systemdController) installed() bool { + return c.userInstalled() || c.systemInstalled() +} + +func (c systemdController) describe() string { + if c.userInstalled() { + return c.service + ".service (user)" + } + return c.service + ".service" +} + +func (c systemdController) run(args ...string) error { + if c.userInstalled() { + args = append([]string{"--user"}, args...) + } + return c.runner.Run("systemctl", args...) +} func (c systemdController) start() error { - return c.runner.Run("systemctl", "start", c.service) + return c.run("start", c.service) } func (c systemdController) stop() error { - return c.runner.Run("systemctl", "stop", c.service) + return c.run("stop", c.service) } func (c systemdController) restart() error { - return c.runner.Run("systemctl", "restart", c.service) + return c.run("restart", c.service) } func (c systemdController) remove() error { - _ = c.runner.Run("systemctl", "disable", "--now", c.service) + userUnit := c.userInstalled() + run := func(args ...string) error { + if userUnit { + args = append([]string{"--user"}, args...) + } + return c.runner.Run("systemctl", args...) + } + _ = run("disable", "--now", c.service) unit := systemdUnitPath(systemdConfig{ServiceName: c.service}) + if userUnit { + unit = c.userUnit() + } if err := os.Remove(unit); err != nil && !os.IsNotExist(err) { return err } - return c.runner.Run("systemctl", "daemon-reload") + return run("daemon-reload") } // newServiceController picks the supervisor for the running OS. @@ -114,7 +150,15 @@ func newServiceController() (serviceController, error) { } return launchdController{label: defaultDaemonLabel, home: home, runner: commandRunner{}}, nil case "linux": - return systemdController{service: defaultSystemdServiceName, runner: commandRunner{}}, nil + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + return systemdController{ + service: defaultSystemdServiceName, + home: home, + runner: commandRunner{}, + }, nil default: return nil, fmt.Errorf("managing the local daemon is not supported on %s", runtime.GOOS) } diff --git a/cmd/subrouter/main.go b/cmd/subrouter/main.go index aae0bf16c..345120f39 100644 --- a/cmd/subrouter/main.go +++ b/cmd/subrouter/main.go @@ -25,11 +25,12 @@ import ( awsconfig "github.com/aws/aws-sdk-go-v2/config" "github.com/manaflow-ai/subrouter/internal/accounts" agentclaude "github.com/manaflow-ai/subrouter/internal/agents/claude" + "github.com/manaflow-ai/subrouter/internal/broker" "github.com/manaflow-ai/subrouter/internal/proxy" - "github.com/manaflow-ai/subrouter/selectacct" - "github.com/manaflow-ai/subrouter/session" "github.com/manaflow-ai/subrouter/internal/storepath" "github.com/manaflow-ai/subrouter/internal/transcript" + "github.com/manaflow-ai/subrouter/selectacct" + "github.com/manaflow-ai/subrouter/session" ) func main() { @@ -129,6 +130,8 @@ var directSRCommands = map[string]struct{}{ "add-api-key": {}, "add-key": {}, "admin-keys": {}, + "account": {}, + "accounts": {}, "attach-project": {}, "breadcrumbs": {}, "claude": {}, @@ -136,6 +139,7 @@ var directSRCommands = map[string]struct{}{ "claude-direct": {}, "cleanup": {}, "cost": {}, + "daemon": {}, "doctor": {}, "g": {}, "gemini": {}, @@ -147,6 +151,7 @@ var directSRCommands = map[string]struct{}{ "list-admin-keys": {}, "login": {}, "ls": {}, + "logout": {}, "pick": {}, "remove": {}, "remove-admin-key": {}, @@ -158,6 +163,7 @@ var directSRCommands = map[string]struct{}{ "spend": {}, "status": {}, "switch": {}, + "team": {}, "trace": {}, "usage": {}, "use": {}, @@ -199,6 +205,7 @@ func serve(args []string) error { bedrockProfiles := flags.String("bedrock-profiles", "", "comma-separated AWS profiles for the Bedrock gateway; defaults to SUBROUTER_BEDROCK_PROFILES or discovered awN profiles") bedrockAutoBump := flags.Bool("bedrock-autobump", false, "request a Service Quotas increase (2x, deduped) when Bedrock throttles Fable/Opus") fableBedrockPrimary := flags.Bool("fable-bedrock-primary", false, "route Claude Fable to Bedrock first (before the subscription pool); defaults to SUBROUTER_FABLE_BEDROCK_PRIMARY") + cloudConfigPath := flags.String("cloud-config", "", "cmux.com team credential config; defaults to ~/.config/subrouter/cloud.json") if err := flags.Parse(args); err != nil { return err } @@ -242,6 +249,18 @@ func serve(args []string) error { return err } + cloudConfig, err := broker.LoadConfig(*cloudConfigPath) + if err != nil { + return fmt.Errorf("load cmux.com config: %w", err) + } + if cloudConfig.LoggedIn() && cloudConfig.TeamID == "" { + return errors.New("cmux.com login has no selected team; run 'sr team use '") + } + var credentialBroker *broker.Client + if cloudConfig.Ready() { + credentialBroker = broker.NewClient(cloudConfig) + } + store, err := session.NewStore(*sessionPath) if err != nil { return err @@ -264,7 +283,7 @@ func serve(args []string) error { // swapped in once ready. Per-request 401/429 failover covers the brief // window before fresh scores land. schedulerRef := selectacct.NewSchedulerRef(selectacct.NewScheduler(fallbackScores(codexAccounts))) - if *fetchUsage { + if *fetchUsage && credentialBroker == nil { go func() { fetchedScores, successful := fetchCodexScoresWithStore(context.Background(), codexStore, codexAccounts) if successful > 0 { @@ -309,10 +328,13 @@ func serve(args []string) error { initialAccounts := append([]accounts.Account(nil), codexAccounts...) initialAccounts = append(initialAccounts, claudeAccounts...) - accountRef := proxy.NewAccountRef(codexStore, initialAccounts, &http.Client{ - Timeout: 15 * time.Second, - Transport: outboundTransport, - }) + var accountRef *proxy.AccountRef + if credentialBroker == nil { + accountRef = proxy.NewAccountRef(codexStore, initialAccounts, &http.Client{ + Timeout: 15 * time.Second, + Transport: outboundTransport, + }) + } server := proxy.Server{ StreamDrops: &proxy.StreamDropStats{}, @@ -324,6 +346,7 @@ func serve(args []string) error { ZAIUpstream: zaiUpstream, Accounts: nil, AccountRef: accountRef, + CredentialBroker: credentialBroker, Sessions: store, SchedulerRef: schedulerRef, UsageScoreTTL: usageScoreTTLForServe(*fetchUsage, *usageScoreTTL), @@ -331,6 +354,7 @@ func serve(args []string) error { Logger: slog.Default(), Lifecycle: proxy.NewLifecycle(), AdminToken: *adminToken, + LocalProxyToken: cloudLocalProxyToken(cloudConfig), MaxBodyBytes: *maxBodyBytes, Bedrock: bedrockConfig, ClaudeFableAPIKey: strings.TrimSpace(os.Getenv("SUBROUTER_CLAUDE_FABLE_API_KEY")), @@ -349,7 +373,7 @@ func serve(args []string) error { if transcriptGCSSyncer.Enabled() { go transcriptGCSSyncer.Run(context.Background()) } - if srSwitchInterval > 0 && *fetchUsage { + if srSwitchInterval > 0 && *fetchUsage && credentialBroker == nil { go runSRAutoSwitch(context.Background(), srAutoSwitchConfig{ Interval: srSwitchInterval, AccountsFunc: accountRef.All, @@ -358,7 +382,7 @@ func serve(args []string) error { Logger: slog.Default(), Lease: newSRAutoSwitchLease(storepath.StateDir()), }) - } else if srSwitchInterval > 0 { + } else if srSwitchInterval > 0 && credentialBroker == nil { slog.Info("sr auto-switch disabled because usage fetching is disabled", "interval", srSwitchInterval.String()) } @@ -380,9 +404,9 @@ func serve(args []string) error { } if upstream != nil { - slog.Info("subrouter listening", "addr", *addr, "upstream", upstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) + slog.Info("subrouter listening", "addr", *addr, "upstream", upstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "cloud_team", cloudConfig.TeamID, "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) } else { - slog.Info("subrouter listening", "addr", *addr, "codex_upstream", codexUpstream.String(), "api_upstream", apiUpstream.String(), "claude_upstream", claudeUpstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) + slog.Info("subrouter listening", "addr", *addr, "codex_upstream", codexUpstream.String(), "api_upstream", apiUpstream.String(), "claude_upstream", claudeUpstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "cloud_team", cloudConfig.TeamID, "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) } return listenAndServeWithSignals(httpServer, server.Lifecycle, *shutdownTimeout, slog.Default()) } @@ -887,9 +911,28 @@ func usageText(program string) string { return fmt.Sprintf(`%[1]s routes AI coding-agent traffic across subscription accounts. Getting started: - %[1]s setup Install and start the local daemon, then verify it - %[1]s doctor Diagnose routing: daemon, server, accounts - %[1]s cleanup Remove the local daemon (--yes to apply, --purge for credentials) + %[1]s login Sign in to cmux.com with Stack Auth and choose a team + %[1]s setup Install and start the local proxy daemon, then verify it + %[1]s doctor Diagnose login, team vault, daemon, and local egress + %[1]s cleanup Remove the local daemon (--yes to apply, --purge for local credentials) + +Team vault: + %[1]s team list List Stack Auth teams + %[1]s team current Show the selected team + %[1]s team use Select the team whose credentials this machine leases + %[1]s account list List credentials shared with the selected team + %[1]s account add + Add one credential to the selected team vault + %[1]s account import --only