Repository navigation
Add team-vault credential leases with local egress #99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit
Hold shift + click to select a range
dc9a0c5
Fail over to the local daemon when the configured server is unreachable
lawrencecchen f271cf4
Add sr setup, doctor and cleanup, and move lifecycle under sr server
lawrencecchen 9f7e236
Auto-start the local daemon when launching an agent
lawrencecchen f99083f
Add team-vault credential leases with local egress
lawrencecchen 73498c1
Merge remote-tracking branch 'origin/main' into feat/client-failover
lawrencecchen 61a0481
Test credential storage mode overrides legacy servers
lawrencecchen 10fa100
Make credential storage mode authoritative
lawrencecchen b66d411
Test lifecycle waits for daemon readiness
lawrencecchen 2a09316
Wait for daemon health after lifecycle starts
lawrencecchen 8895763
Isolate doctor tests from live team config
lawrencecchen fc1bbf6
Test credential custody review regressions
lawrencecchen 5d5c726
Harden central credential custody and local egress
lawrencecchen 99b1e63
Test daemon custody and lease lifecycle regressions
lawrencecchen 1dbb4c6
Harden local credential proxy custody
lawrencecchen 6f7f586
Test credential failover review regressions
lawrencecchen 0392925
Harden credential failover and provider custody
lawrencecchen 7ac1cee
Allow explicit proxy health recovery probes
lawrencecchen d90bde9
Test device authorization client binding
lawrencecchen 3bfec39
Bind Subrouter login to its device authorization
lawrencecchen 298a336
Test systemd path escaping
lawrencecchen dfa19a2
Escape systemd user service paths
lawrencecchen 1c714fc
Add regression coverage for cloud credential boundaries
lawrencecchen 8ab2695
Harden local proxy and cloud credential recovery
lawrencecchen 953c310
Test stale credential lease outcomes
lawrencecchen 7da74c6
Ignore stale credential lease outcomes
lawrencecchen 0be9500
Keep Go module metadata tidy
lawrencecchen 8f3b799
Test central adoption and monotonic cooldowns
lawrencecchen 7ecab5c
Adopt uploaded refresh chains and preserve cooldowns
lawrencecchen 7916574
Test team-vault failure isolation and cleanup
lawrencecchen 7c9892e
Harden team leases and scoped failover
lawrencecchen b888dae
Test quota-scoped forbidden lease rotation
lawrencecchen 1bb42c5
Rotate model-scoped forbidden leases
lawrencecchen cd8c320
Test provider-specific forbidden lease handling
lawrencecchen e21eec6
Classify forbidden leases by provider context
lawrencecchen 446c833
Test Claude API-key forbidden scope
lawrencecchen ba3da7f
Scope Claude forbidden leases by auth mode
lawrencecchen 03b24b0
Test provider-specific lease retry deadlines
lawrencecchen 2856789
Use provider-specific lease retry deadlines
lawrencecchen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| // 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) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| 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 | ||
| }, | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.