diff --git a/internal/app/archied/kit_launcher.go b/internal/app/archied/kit_launcher.go index 8449da392..0ace13d46 100644 --- a/internal/app/archied/kit_launcher.go +++ b/internal/app/archied/kit_launcher.go @@ -81,7 +81,7 @@ func (b *boot) setupKitLauncher(ctx context.Context) { b.kitLauncher = &kitrun.Launcher{ Pool: pool, Fetch: fetcher, Proxy: proxy, Networks: networks, AgentBinary: agentBinary, CAFile: egress.CACertPath(caDir), - Config: b.cfgHolder, Secrets: b.secrets, Grants: grants, + Config: b.cfgHolder, Secrets: b.secrets, Grants: grants, OAuth: oauthStore, } log.Info("kit harness runs enabled", "proxy", ln.Addr().String()) } diff --git a/internal/infrastructure/kit/credential_file.go b/internal/infrastructure/kit/credential_file.go new file mode 100644 index 000000000..754d45ef1 --- /dev/null +++ b/internal/infrastructure/kit/credential_file.go @@ -0,0 +1,156 @@ +package kit + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/BurntSushi/toml" + "github.com/docker/sandbox-kit-spec/v3/spec" +) + +// Credential-file placeholders, the vocabulary the Kit spec's +// credentialFile.structure declares. A leaf may reference the token +// sentinels as a whole value or inside a larger string; ExpiresAt is a +// number and so may only be the whole value. +const ( + accessPlaceholder = "{{.AccessToken}}" + refreshPlaceholder = "{{.RefreshToken}}" + expiresPlaceholder = "{{.ExpiresAt}}" + + // credentialFileMode is owner-only: the file holds sentinels, but the + // path is still a credential the agent alone should read. + credentialFileMode = "0600" +) + +// renderCredentialFile renders c's oauth.credentialFile: the declared +// structure with the Kit's sentinels substituted for the token placeholders +// and the stored token set's expiry for {{.ExpiresAt}}, encoded in the +// declared format. expires is the only fact about the stored token set the +// renderer receives, so a real token cannot reach the file +// (docs/prds/external-agent-harness.md, "Verification: the credential file +// holds only sentinels"). +func renderCredentialFile(c spec.CredentialCapability, expires time.Time) (string, error) { + cf := c.OAuth.CredentialFile + var sentinels spec.Sentinels + if c.OAuth.Sentinels != nil { + sentinels = *c.OAuth.Sentinels + } + expiresAt := int64(0) + if !expires.IsZero() { + // Both in-spec OAuth credential files (Claude Code's credentials.json + // and OpenCode's auth.json) carry the epoch in milliseconds. + expiresAt = expires.UnixMilli() + } + structure, err := substitutePlaceholders(cf.Structure, sentinels, expiresAt) + if err != nil { + return "", fmt.Errorf("credential %q credential file: %w", c.Service, err) + } + encoded, err := encodeCredentialFile(cf.Format, structure) + if err != nil { + return "", fmt.Errorf("credential %q credential file: %w", c.Service, err) + } + return encoded, nil +} + +// substitutePlaceholders replaces every leaf that references a placeholder +// with the typed value the target encoding expects, and refuses a placeholder +// archie does not render rather than leaving it standing in the file. +func substitutePlaceholders(v any, sentinels spec.Sentinels, expiresAt int64) (any, error) { + switch t := v.(type) { + case map[string]any: + out := make(map[string]any, len(t)) + for k, e := range t { + sub, err := substitutePlaceholders(e, sentinels, expiresAt) + if err != nil { + return nil, fmt.Errorf("%s: %w", k, err) + } + out[k] = sub + } + return out, nil + case []any: + out := make([]any, len(t)) + for i, e := range t { + sub, err := substitutePlaceholders(e, sentinels, expiresAt) + if err != nil { + return nil, fmt.Errorf("[%d]: %w", i, err) + } + out[i] = sub + } + return out, nil + case string: + return substituteString(t, sentinels, expiresAt) + default: + return v, nil + } +} + +func substituteString(s string, sentinels spec.Sentinels, expiresAt int64) (any, error) { + switch s { + case accessPlaceholder: + if sentinels.AccessToken == "" { + return nil, fmt.Errorf("no access-token sentinel is declared for this credential") + } + return sentinels.AccessToken, nil + case refreshPlaceholder: + if sentinels.RefreshToken == "" { + return nil, fmt.Errorf("no refresh-token sentinel is declared for this credential") + } + return sentinels.RefreshToken, nil + case expiresPlaceholder: + return expiresAt, nil + } + // A token sentinel may ride inside a larger string, e.g. "Bearer ...". + out := s + if strings.Contains(out, accessPlaceholder) { + if sentinels.AccessToken == "" { + return nil, fmt.Errorf("no access-token sentinel is declared for this credential") + } + out = strings.ReplaceAll(out, accessPlaceholder, sentinels.AccessToken) + } + if strings.Contains(out, refreshPlaceholder) { + if sentinels.RefreshToken == "" { + return nil, fmt.Errorf("no refresh-token sentinel is declared for this credential") + } + out = strings.ReplaceAll(out, refreshPlaceholder, sentinels.RefreshToken) + } + if at := firstPlaceholder(out); at != "" { + return nil, fmt.Errorf("placeholder %s is not rendered by archie", at) + } + return out, nil +} + +// firstPlaceholder reports the first {{...}} occurrence in s, or "". +func firstPlaceholder(s string) string { + start := strings.Index(s, "{{") + if start < 0 { + return "" + } + end := strings.Index(s[start:], "}}") + if end < 0 { + return s[start:] + } + return s[start : start+end+2] +} + +// encodeCredentialFile writes the substituted structure in the Kit's declared +// format: json unless it names toml. +func encodeCredentialFile(format string, structure any) (string, error) { + switch format { + case "", "json": + b, err := json.Marshal(structure) + if err != nil { + return "", err + } + return string(b), nil + case "toml": + var buf strings.Builder + if err := toml.NewEncoder(&buf).Encode(structure); err != nil { + return "", err + } + return buf.String(), nil + default: + return "", fmt.Errorf("unknown format %q", format) + } +} diff --git a/internal/infrastructure/kit/credential_file_test.go b/internal/infrastructure/kit/credential_file_test.go new file mode 100644 index 000000000..7e943c187 --- /dev/null +++ b/internal/infrastructure/kit/credential_file_test.go @@ -0,0 +1,217 @@ +package kit + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/BurntSushi/toml" + "github.com/docker/sandbox-kit-spec/v3/spec" +) + +// oauthCredentialFileKit is a Kit declaring a proxy-managed OAuth credential +// whose harness reads its tokens from a credential file, as the published +// Claude Code Kit does (the spec's own example). +const oauthCredentialFileKit = sessions + ` + - type: com.docker.sandbox/credential@1 + config: + service: claude-code + phase: runtime + oauth: + tokenEndpoint: {host: platform.claude.com, path: /v1/oauth/token} + sentinels: + accessToken: sk-ant-oat01-proxy-managed + refreshToken: sk-ant-ort01-proxy-managed + credentialFile: + path: /home/agent/.claude/.credentials.json + structure: + claudeAiOauth: + accessToken: "{{.AccessToken}}" + refreshToken: "{{.RefreshToken}}" + expiresAt: "{{.ExpiresAt}}"` + +func credentialFilePlan(t *testing.T) *Plan { + t.Helper() + p, err := Admit(descriptor(t, spec.KindWorkload, oauthCredentialFileKit)) + if err != nil { + t.Fatalf("admit: %v", err) + } + return p +} + +func findFile(files []spec.File, path string) (spec.File, bool) { + for _, f := range files { + if f.Path == path { + return f, true + } + } + return spec.File{}, false +} + +// TestAssembleRendersTheOAuthCredentialFile is the sentinel rule: a bound +// OAuth credential whose Kit declares a credentialFile gets that file written +// at the declared path, holding the Kit's sentinels and never a real token. +func TestAssembleRendersTheOAuthCredentialFile(t *testing.T) { + l, err := Assemble(credentialFilePlan(t), image, LaunchParams{ + Execution: "exec-42", ProxyToken: "tok", CAPath: "/etc/archie/ca.pem", + Bound: []string{"claude-code"}, + }) + if err != nil { + t.Fatal(err) + } + f, ok := findFile(l.Files, "/home/agent/.claude/.credentials.json") + if !ok { + t.Fatalf("no credential file at the declared path; files = %v", l.Files) + } + if f.Mode != "0600" { + t.Errorf("credential file mode = %q, want 0600", f.Mode) + } + if strings.Contains(f.Content, "{{") { + t.Errorf("credential file still holds a placeholder: %s", f.Content) + } + var doc struct { + ClaudeAiOauth struct { + AccessToken string `json:"accessToken"` + RefreshToken string `json:"refreshToken"` + ExpiresAt float64 `json:"expiresAt"` + } `json:"claudeAiOauth"` + } + if err := json.Unmarshal([]byte(f.Content), &doc); err != nil { + t.Fatalf("credential file is not JSON: %v\n%s", err, f.Content) + } + if doc.ClaudeAiOauth.AccessToken != "sk-ant-oat01-proxy-managed" { + t.Errorf("accessToken = %q, want the Kit's access-token sentinel", doc.ClaudeAiOauth.AccessToken) + } + if doc.ClaudeAiOauth.RefreshToken != "sk-ant-ort01-proxy-managed" { + t.Errorf("refreshToken = %q, want the Kit's refresh-token sentinel", doc.ClaudeAiOauth.RefreshToken) + } + if doc.ClaudeAiOauth.ExpiresAt != 0 { + t.Errorf("expiresAt = %v, want 0 with no stored token set", doc.ClaudeAiOauth.ExpiresAt) + } +} + +// TestAssembleRendersTheStoredExpiry proves the credential file carries the +// stored token set's expiry -- the value the CLI checks before it decides to +// refresh -- and that it is a number, not a quoted placeholder. +func TestAssembleRendersTheStoredExpiry(t *testing.T) { + expires := time.UnixMilli(1700000000123) + l, err := Assemble(credentialFilePlan(t), image, LaunchParams{ + Execution: "exec-42", ProxyToken: "tok", CAPath: "/etc/archie/ca.pem", + Bound: []string{"claude-code"}, OAuthExpiries: map[string]time.Time{"claude-code": expires}, + }) + if err != nil { + t.Fatal(err) + } + f, ok := findFile(l.Files, "/home/agent/.claude/.credentials.json") + if !ok { + t.Fatalf("no credential file at the declared path; files = %v", l.Files) + } + var doc struct { + ClaudeAiOauth struct { + ExpiresAt int64 `json:"expiresAt"` + } `json:"claudeAiOauth"` + } + if err := json.Unmarshal([]byte(f.Content), &doc); err != nil { + t.Fatalf("credential file is not JSON: %v\n%s", err, f.Content) + } + if doc.ClaudeAiOauth.ExpiresAt != expires.UnixMilli() { + t.Errorf("expiresAt = %d, want the stored expiry %d", doc.ClaudeAiOauth.ExpiresAt, expires.UnixMilli()) + } +} + +// TestAssembleRendersATOMLCredentialFile covers the non-default encoding the +// spec provides for agents that read TOML credentials files. +func TestAssembleRendersATOMLCredentialFile(t *testing.T) { + const tomlKit = sessions + ` + - type: com.docker.sandbox/credential@1 + config: + service: example + phase: runtime + oauth: + tokenEndpoint: {host: auth.example.com} + sentinels: {accessToken: sentinel-access, refreshToken: sentinel-refresh} + credentialFile: + path: /home/agent/credentials.toml + format: toml + structure: + api_url: "https://api.example.com" + tokens: + access_token: "{{.AccessToken}}" + refresh_token: "{{.RefreshToken}}"` + p, err := Admit(descriptor(t, spec.KindWorkload, tomlKit)) + if err != nil { + t.Fatalf("admit: %v", err) + } + l, err := Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: []string{"example"}}) + if err != nil { + t.Fatal(err) + } + f, ok := findFile(l.Files, "/home/agent/credentials.toml") + if !ok { + t.Fatalf("no credential file at the declared path; files = %v", l.Files) + } + var doc struct { + APIURL string `toml:"api_url"` + Tokens struct { + AccessToken string `toml:"access_token"` + RefreshToken string `toml:"refresh_token"` + } `toml:"tokens"` + } + if _, err := toml.Decode(f.Content, &doc); err != nil { + t.Fatalf("credential file is not TOML: %v\n%s", err, f.Content) + } + if doc.Tokens.AccessToken != "sentinel-access" || doc.Tokens.RefreshToken != "sentinel-refresh" { + t.Errorf("tokens = %+v, want the sentinels", doc.Tokens) + } +} + +// TestAssembleRefusesAPlaceholderItCannotRender: a placeholder archie does +// not supply must refuse the launch rather than leave the literal standing in +// the file, which the CLI would read as a credential. +func TestAssembleRefusesAPlaceholderItCannotRender(t *testing.T) { + const scopesKit = sessions + ` + - type: com.docker.sandbox/credential@1 + config: + service: example + phase: runtime + oauth: + tokenEndpoint: {host: auth.example.com} + sentinels: {accessToken: sentinel-access} + credentialFile: + path: /home/agent/credentials.json + structure: + scopes: "{{.Scopes}}"` + p, err := Admit(descriptor(t, spec.KindWorkload, scopesKit)) + if err != nil { + t.Fatalf("admit: %v", err) + } + _, err = Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: []string{"example"}}) + if err == nil || !strings.Contains(err.Error(), "{{.Scopes}}") { + t.Fatalf("Assemble = %v, want a refusal naming {{.Scopes}}", err) + } +} + +// TestAssembleRefusesAMissingSentinel: a token placeholder with no declared +// sentinel cannot be hidden, so the file must not be written at all. +func TestAssembleRefusesAMissingSentinel(t *testing.T) { + const noSentinelKit = sessions + ` + - type: com.docker.sandbox/credential@1 + config: + service: example + phase: runtime + oauth: + tokenEndpoint: {host: auth.example.com} + credentialFile: + path: /home/agent/credentials.json + structure: + access_token: "{{.AccessToken}}"` + p, err := Admit(descriptor(t, spec.KindWorkload, noSentinelKit)) + if err != nil { + t.Fatalf("admit: %v", err) + } + _, err = Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: []string{"example"}}) + if err == nil || !strings.Contains(err.Error(), "access-token sentinel") { + t.Fatalf("Assemble = %v, want a refusal naming the missing access-token sentinel", err) + } +} diff --git a/internal/infrastructure/kit/launch.go b/internal/infrastructure/kit/launch.go index 168d88069..4aef607d9 100644 --- a/internal/infrastructure/kit/launch.go +++ b/internal/infrastructure/kit/launch.go @@ -8,6 +8,7 @@ import ( "regexp" "slices" "strings" + "time" "github.com/docker/sandbox-kit-spec/v3/spec" @@ -51,6 +52,11 @@ type LaunchParams struct { CAPath string // Bound lists the credential services the run credential carries. Bound []string + // OAuthExpiries is the stored token set's expiry for each bound OAuth + // credential whose Kit renders a credentialFile, keyed by service. It is + // the only fact about a token set the renderer receives: the tokens + // themselves never cross into kit, so a real token cannot be written. + OAuthExpiries map[string]time.Time } // Hook is one lifecycle hook, ready to exec in the container. @@ -128,6 +134,11 @@ func Assemble(p *Plan, img ImageConfig, params LaunchParams) (Launch, error) { } l.Files = lifecycle.Files } + credential, err := credentialFiles(creds, params.Bound, params.OAuthExpiries) + if err != nil { + return Launch{}, err + } + l.Files = append(l.Files, credential...) for _, v := range volumes { l.Volumes = append(l.Volumes, Volume{Name: volumeName(params.Execution, v.Path), Path: v.Path}) } @@ -137,6 +148,25 @@ func Assemble(p *Plan, img ImageConfig, params LaunchParams) (Launch, error) { return l, nil } +// credentialFiles renders the credential file of every bound OAuth credential +// whose Kit declares one: the path and structure the Kit names, with the +// stored token set's expiry. A service the run credential does not carry +// produces no file. +func credentialFiles(creds []spec.CredentialCapability, bound []string, expiries map[string]time.Time) ([]spec.File, error) { + var files []spec.File + for _, c := range creds { + if c.OAuth == nil || c.OAuth.CredentialFile == nil || !slices.Contains(bound, c.Service) { + continue + } + content, err := renderCredentialFile(c, expiries[c.Service]) + if err != nil { + return nil, err + } + files = append(files, spec.File{Path: c.OAuth.CredentialFile.Path, Content: content, Mode: credentialFileMode}) + } + return files, nil +} + // contextFiles materializes agent-context@1: the workload's profile file // beside the workspace, never in it, carrying an index of each Kit's body. // A staged body is pointed at where the image holds it; an inline one is diff --git a/internal/infrastructure/kitrun/credential_file_test.go b/internal/infrastructure/kitrun/credential_file_test.go new file mode 100644 index 000000000..07cae045d --- /dev/null +++ b/internal/infrastructure/kitrun/credential_file_test.go @@ -0,0 +1,134 @@ +package kitrun + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/docker/sandbox-kit-spec/v3/spec" + + "github.com/samcharles93/archie-core/internal/domain/harnesssecret" + "github.com/samcharles93/archie-core/internal/infrastructure/kit" +) + +type fakeOAuthSecrets struct { + secret harnesssecret.Secret + err error +} + +func (f fakeOAuthSecrets) GetHarnessSecret(context.Context, string, string) (harnesssecret.Secret, error) { + if f.err != nil { + return harnesssecret.Secret{}, f.err + } + return f.secret, nil +} + +const credentialFileKit = ` +schemaVersion: "3" +kind: workload +capabilities: + - type: com.docker.sandbox/agent-sessions@1 + config: {prompt: [-p, "{{.Prompt}}"]} + - type: com.docker.sandbox/credential@1 + config: + service: claude-code + phase: runtime + oauth: + tokenEndpoint: {host: platform.claude.com, path: /v1/oauth/token} + sentinels: + accessToken: sk-ant-oat01-proxy-managed + refreshToken: sk-ant-ort01-proxy-managed + credentialFile: + path: /home/agent/.claude/.credentials.json + structure: + claudeAiOauth: + accessToken: "{{.AccessToken}}" + refreshToken: "{{.RefreshToken}}" + expiresAt: "{{.ExpiresAt}}" +` + +func credentialFilePlan(t *testing.T) *kit.Plan { + t.Helper() + d, err := spec.Decode([]byte(credentialFileKit)) + if err != nil { + t.Fatalf("fixture does not decode: %v", err) + } + p, err := kit.Admit(d) + if err != nil { + t.Fatalf("admit: %v", err) + } + return p +} + +func planCredentials(t *testing.T, p *kit.Plan) []spec.CredentialCapability { + t.Helper() + creds, err := spec.CredentialsOf(p.Capabilities) + if err != nil { + t.Fatalf("credentials of plan: %v", err) + } + return creds +} + +// TestCredentialFileNeverCarriesARealToken is the sentinel rule end to end: +// the store holds real tokens, kitrun reads the set only for its expiry, and +// the assembled credential file holds the Kit's sentinels instead. The store's +// real values must not appear anywhere in the rendered file. +func TestCredentialFileNeverCarriesARealToken(t *testing.T) { + expires := time.UnixMilli(1700000000123) + l := &Launcher{OAuth: fakeOAuthSecrets{secret: harnesssecret.Secret{ + Org: "acme", Service: "claude-code", + AccessToken: "real-access-token", RefreshToken: "real-refresh-token", + ExpiresAt: expires, + }}} + p := credentialFilePlan(t) + bound := []string{"claude-code"} + + expiries, err := l.oauthExpiries(context.Background(), "acme", planCredentials(t, p), bound) + if err != nil { + t.Fatal(err) + } + if got := expiries["claude-code"]; got != expires { + t.Fatalf("oauthExpiries[claude-code] = %v, want the stored expiry %v", got, expires) + } + + launch, err := kit.Assemble(p, kit.ImageConfig{User: "agent"}, kit.LaunchParams{ + Execution: "exec-1", Bound: bound, OAuthExpiries: expiries, + }) + if err != nil { + t.Fatal(err) + } + var content string + for _, f := range launch.Files { + if f.Path == "/home/agent/.claude/.credentials.json" { + content = f.Content + } + } + if content == "" { + t.Fatalf("no credential file rendered; files = %v", launch.Files) + } + if strings.Contains(content, "real-access-token") || strings.Contains(content, "real-refresh-token") { + t.Fatalf("credential file carries a real token: %s", content) + } + if !strings.Contains(content, "sk-ant-oat01-proxy-managed") || !strings.Contains(content, "sk-ant-ort01-proxy-managed") { + t.Fatalf("credential file does not hold the sentinels: %s", content) + } +} + +// TestOAuthExpiriesFailsClosed: a Kit that renders a credential file cannot be +// launched without the stored token set its expiry comes from. +func TestOAuthExpiriesFailsClosed(t *testing.T) { + p := credentialFilePlan(t) + creds := planCredentials(t, p) + bound := []string{"claude-code"} + ctx := context.Background() + + if _, err := (&Launcher{}).oauthExpiries(ctx, "acme", creds, bound); err == nil { + t.Fatal("oauthExpiries with no store = nil error, want a refusal") + } + l := &Launcher{OAuth: fakeOAuthSecrets{err: errors.New("no captured token")}} + if _, err := l.oauthExpiries(ctx, "acme", creds, bound); err == nil { + t.Fatal("oauthExpiries with no stored token = nil error, want a refusal") + } +} diff --git a/internal/infrastructure/kitrun/launcher.go b/internal/infrastructure/kitrun/launcher.go index 8a5e85df5..84bc2f227 100644 --- a/internal/infrastructure/kitrun/launcher.go +++ b/internal/infrastructure/kitrun/launcher.go @@ -10,6 +10,7 @@ import ( "maps" "slices" "sync" + "time" "github.com/docker/sandbox-kit-spec/v3/fetch" "github.com/docker/sandbox-kit-spec/v3/spec" @@ -17,6 +18,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" + "github.com/samcharles93/archie-core/internal/domain/harnesssecret" "github.com/samcharles93/archie-core/internal/infrastructure/egress" "github.com/samcharles93/archie-core/internal/infrastructure/kit" "github.com/samcharles93/archie-core/internal/skill" @@ -37,6 +39,15 @@ type Grants interface { RevokeGrant(run string) } +// OAuthSecrets reads an org's stored OAuth token set for a bound service, so a +// Kit's credential file can render that set's expiry. It is the store's read +// half only: kitrun never writes a token set, and nothing but the expiry +// leaves oauthExpiries, so a real token cannot reach the credential file +// (docs/prds/external-agent-harness.md, "Verification"). +type OAuthSecrets interface { + GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error) +} + const ( agentPath = "/opt/archie/archie-agent" caPath = "/opt/archie/ca.pem" @@ -64,6 +75,11 @@ type Launcher struct { Config *config.Holder Secrets SecretResolver Grants Grants + // OAuth reads the stored token set whose expiry a Kit's credential file + // renders. A nil OAuth refuses the launch of a Kit that renders one, the + // same way a nil OAuthStore makes the proxy refuse a required OAuth + // credential. + OAuth OAuthSecrets mu sync.Mutex started bool @@ -125,6 +141,10 @@ func (l *Launcher) Launch(ctx context.Context, req Request) (*Run, error) { return nil, err } granted, bound := l.resolveCredentials(req, k.creds) + expiries, err := l.oauthExpiries(ctx, req.Org, k.creds, bound) + if err != nil { + return nil, err + } if l.Grants != nil { l.Grants.Grant(req.Execution, granted) } @@ -136,7 +156,7 @@ func (l *Launcher) Launch(ctx context.Context, req Request) (*Run, error) { return nil, err } run := &Run{network: "archie-kit-" + req.Execution, token: session.Token(), execution: req.Execution} - launch, err := kit.Assemble(k.plan, k.img, kit.LaunchParams{Execution: req.Execution, ProxyToken: session.Token(), CAPath: caPath, Bound: bound}) + launch, err := kit.Assemble(k.plan, k.img, kit.LaunchParams{Execution: req.Execution, ProxyToken: session.Token(), CAPath: caPath, Bound: bound, OAuthExpiries: expiries}) if err != nil { l.release(run) return nil, err @@ -214,6 +234,28 @@ func (l *Launcher) resolveCredentials(req Request, creds []spec.CredentialCapabi return granted, bound } +// oauthExpiries reads the stored token set's expiry for each bound OAuth +// credential whose Kit renders a credential file. The store is read only for a +// service the run credential carries, and only the expiry leaves here: the +// tokens stay behind, so the renderer has no way to write one. +func (l *Launcher) oauthExpiries(ctx context.Context, org string, creds []spec.CredentialCapability, bound []string) (map[string]time.Time, error) { + expiries := map[string]time.Time{} + for _, c := range creds { + if c.OAuth == nil || c.OAuth.CredentialFile == nil || !egress.IsOAuthManaged(c) || !slices.Contains(bound, c.Service) { + continue + } + if l.OAuth == nil { + return nil, fmt.Errorf("credential %q renders a credential file, but no harness secret store is configured", c.Service) + } + secret, err := l.OAuth.GetHarnessSecret(ctx, org, c.Service) + if err != nil { + return nil, fmt.Errorf("credential %q renders a credential file and has no captured OAuth token (run the setup terminal first): %w", c.Service, err) + } + expiries[c.Service] = secret.ExpiresAt + } + return expiries, nil +} + // release undoes what Launch already did for run: the egress grant, then the // session. Call sites past this point pass the network/container errors // through their own cleanup; release only ever needs to run once per Launch