refactor: testing from the beginning. a journey in 150k lines of tests to none

This commit is contained in:
sam committed 2026-10-03 21:16:25 +10:00
1 parent ba37e37e53
commit ff424b70ac
651 files changed
-146443

No files matched your search

@@ -1,219 +0,0 @@
package kit
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/BurntSushi/toml"
"github.com/docker/sandbox-kit-spec/v3/spec"
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
)
// 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: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth},
})
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: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth}, OAuth: map[string]OAuthFacts{"claude-code": {ExpiresAt: 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: map[string]egress.CredentialKind{"example": egress.CredentialOAuth}})
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 unknownKit = 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:
mystery: "{{.NotAPlaceholder}}"`
p, err := Admit(descriptor(t, spec.KindWorkload, unknownKit))
if err != nil {
t.Fatalf("admit: %v", err)
}
_, err = Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: map[string]egress.CredentialKind{"example": egress.CredentialOAuth}})
if err == nil || !strings.Contains(err.Error(), "{{.NotAPlaceholder}}") {
t.Fatalf("Assemble = %v, want a refusal naming {{.NotAPlaceholder}}", 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: map[string]egress.CredentialKind{"example": egress.CredentialOAuth}})
if err == nil || !strings.Contains(err.Error(), "access-token sentinel") {
t.Fatalf("Assemble = %v, want a refusal naming the missing access-token sentinel", err)
}
}
@@ -1,133 +0,0 @@
package kit
import (
"encoding/json"
"strings"
"testing"
"github.com/docker/sandbox-kit-spec/v3/spec"
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
)
// claudeCodeCredentialFileKit mirrors the published Claude Code Kit's
// credentialFile: the OAuth fields nested, the granted scopes among them, and
// a top-level primaryApiKey.
const claudeCodeCredentialFileKit = 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}}"
scopes: "{{.Scopes}}"
primaryApiKey: "{{.PrimaryApiKey}}"`
// renderClaudeCredentialFile assembles the Claude-shaped Kit with facts and
// returns the credential file's decoded top level.
func renderClaudeCredentialFile(t *testing.T, facts OAuthFacts) map[string]any {
t.Helper()
p, err := Admit(descriptor(t, spec.KindWorkload, claudeCodeCredentialFileKit))
if err != nil {
t.Fatalf("admit: %v", err)
}
l, err := Assemble(p, image, LaunchParams{
Execution: "exec-42", Bound: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth},
OAuth: map[string]OAuthFacts{"claude-code": facts},
})
if err != nil {
t.Fatalf("Assemble: %v", 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 map[string]any
if err := json.Unmarshal([]byte(f.Content), &doc); err != nil {
t.Fatalf("credential file is not JSON: %v\n%s", err, f.Content)
}
return doc
}
// TestAssembleRendersTheGrantedScopes: {{.Scopes}} is an array in the target
// encoding, so a one-element set must still be a one-element ARRAY and never
// collapse to a bare string -- the single and multi cases differ exactly
// there, and nowhere else.
func TestAssembleRendersTheGrantedScopes(t *testing.T) {
tests := []struct {
name string
scopes []string
}{
{name: "a single granted scope is a one-element array", scopes: []string{"user:inference"}},
{name: "several granted scopes are a multi-element array", scopes: []string{"user:inference", "user:profile"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
doc := renderClaudeCredentialFile(t, OAuthFacts{Scopes: tt.scopes})
oauth, _ := doc["claudeAiOauth"].(map[string]any)
if oauth == nil {
t.Fatalf("claudeAiOauth = %v, want an object", doc["claudeAiOauth"])
}
raw, ok := oauth["scopes"].([]any)
if !ok {
t.Fatalf("scopes = %#v (%T), want a JSON array", oauth["scopes"], oauth["scopes"])
}
if len(raw) != len(tt.scopes) {
t.Fatalf("scopes = %v, want %v", raw, tt.scopes)
}
for i, want := range tt.scopes {
if raw[i] != want {
t.Fatalf("scopes[%d] = %v, want %q", i, raw[i], want)
}
}
})
}
}
// TestAssembleRefusesWhenNoScopesWereCaptured: the spec declares no omission
// case for {{.Scopes}}, so a token set with no scopes refuses the launch with
// something the operator can act on rather than writing an empty array, which
// would silently change the CLI's capability decisions.
func TestAssembleRefusesWhenNoScopesWereCaptured(t *testing.T) {
p, err := Admit(descriptor(t, spec.KindWorkload, claudeCodeCredentialFileKit))
if err != nil {
t.Fatalf("admit: %v", err)
}
_, err = Assemble(p, image, LaunchParams{
Execution: "exec-42", Bound: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth},
OAuth: map[string]OAuthFacts{"claude-code": {}},
})
if err == nil {
t.Fatal("Assemble with no captured scopes = nil error, want a refusal")
}
for _, want := range []string{"{{.Scopes}}", "setup terminal"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("Assemble error = %q, want it to name %q", err, want)
}
}
}
// TestAssembleOmitsAnUncapturedPrimaryApiKey: the spec's case for
// {{.PrimaryApiKey}} is that its enclosing key is omitted when no key is
// captured. archie never hands the container a key -- it resolves one only to
// fill the egress grant -- so the key must be ABSENT; absent and empty are
// different bugs.
func TestAssembleOmitsAnUncapturedPrimaryApiKey(t *testing.T) {
doc := renderClaudeCredentialFile(t, OAuthFacts{Scopes: []string{"user:inference"}})
if v, present := doc["primaryApiKey"]; present {
t.Fatalf("primaryApiKey = %#v, want the key omitted entirely", v)
}
if _, ok := doc["claudeAiOauth"]; !ok {
t.Fatalf("claudeAiOauth missing alongside primaryApiKey: %v", doc)
}
}
-278
View File
@@ -1,278 +0,0 @@
package kit
import (
"errors"
"slices"
"strings"
"testing"
"github.com/docker/sandbox-kit-spec/v3/spec"
)
const sessions = `
- type: com.docker.sandbox/agent-sessions@1
config:
prompt: [-p, "{{.Prompt}}"]
resume: [--resume, "{{.SessionID}}"]`
func descriptor(t *testing.T, kind, capabilities string) *spec.Descriptor {
t.Helper()
d, err := spec.Decode([]byte("schemaVersion: \"3\"\nkind: " + kind + "\ncapabilities:" + capabilities + "\n"))
if err != nil {
t.Fatalf("fixture does not decode: %v", err)
}
return d
}
func refusedTypes(t *testing.T, err error) []string {
t.Helper()
var refused *RefusedError
if !errors.As(err, &refused) {
t.Fatalf("want *RefusedError, got %v", err)
}
var types []string
for _, r := range refused.Refusals {
types = append(types, r.Type)
}
return types
}
func TestAdmit(t *testing.T) {
tests := []struct {
name string
capabilities string
wantRefused []string
wantSkipped []string
wantAdmitted int
}{
{
name: "every supported type is admitted",
capabilities: sessions + `
- type: com.docker.sandbox/network-policy@1
config: {runtime: {allow: [api.example.com:443]}}
- type: com.docker.sandbox/credential@1
config:
service: example
phase: runtime
apiKey: {name: EXAMPLE_KEY, proxyManaged: true, inject: [{domain: api.example.com, header: Authorization, format: "Bearer %s"}]}
- type: com.docker.sandbox/volume@1
config: {path: /home/agent/.state, size: 1g}
- type: com.docker.sandbox/lifecycle@1
config: {startup: [{command: [true]}]}
- type: com.docker.sandbox/agent-skills@1
config: {path: /home/agent/.skills}
- type: com.docker.sandbox/agent-context@1
config: {content: be terse}
- type: com.docker.sandbox/resources@1
config: {memory: 2g}`,
wantAdmitted: 8,
},
{
name: "a required unsupported type refuses the launch",
capabilities: sessions + "\n - type: com.docker.sandbox/privileged@1",
wantRefused: []string{"com.docker.sandbox/privileged@1"},
},
{
name: "an optional unsupported type is skipped and recorded",
capabilities: sessions + `
- type: com.docker.sandbox/port@1
optional: true
config: {port: 8080}`,
wantSkipped: []string{"com.docker.sandbox/port@1"},
wantAdmitted: 1,
},
{
name: "network-policy@2 is refused",
capabilities: sessions + `
- type: com.docker.sandbox/network-policy@2
config: {runtime: {allow: [api.example.com]}}`,
wantRefused: []string{"com.docker.sandbox/network-policy@2"},
},
{
name: "a host-specific type archie does not know is refused",
capabilities: sessions + `
- type: example.com/gpu-broker@1
config: {pool: a}`,
wantRefused: []string{"example.com/gpu-broker@1"},
},
{
name: "a credential with passthrough is refused",
capabilities: sessions + `
- type: com.docker.sandbox/network-policy@1
config: {runtime: {allow: [api.example.com]}}
- type: com.docker.sandbox/credential@1
config:
service: example
phase: runtime
oauth: {tokenEndpoint: {host: api.example.com}, passthrough: true}`,
wantRefused: []string{"com.docker.sandbox/credential@1"},
},
{
name: "an optional forge credential is skipped, never bound",
capabilities: sessions + `
- type: com.docker.sandbox/network-policy@1
config: {runtime: {allow: [api.github.com]}}
- type: com.docker.sandbox/credential@1
optional: true
config:
service: github
phase: runtime
apiKey: {name: GH_TOKEN, proxyManaged: true, inject: [{domain: api.github.com, header: Authorization, format: "Bearer %s"}]}`,
wantSkipped: []string{"com.docker.sandbox/credential@1"},
wantAdmitted: 2,
},
{
name: "every refusal is reported, not only the first",
capabilities: sessions + `
- type: com.docker.sandbox/privileged@1
- type: com.docker.sandbox/long-running@1`,
wantRefused: []string{"com.docker.sandbox/privileged@1", "com.docker.sandbox/long-running@1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
plan, err := Admit(descriptor(t, spec.KindWorkload, tt.capabilities))
if tt.wantRefused != nil {
if got := refusedTypes(t, err); !slices.Equal(got, tt.wantRefused) {
t.Fatalf("refused %v, want %v", got, tt.wantRefused)
}
return
}
if err != nil {
t.Fatalf("Admit: %v", err)
}
var skipped []string
for _, s := range plan.Skipped {
skipped = append(skipped, s.Type)
}
if !slices.Equal(skipped, tt.wantSkipped) {
t.Fatalf("skipped %v, want %v", skipped, tt.wantSkipped)
}
if len(plan.Capabilities) != tt.wantAdmitted {
t.Fatalf("admitted %d capabilities, want %d", len(plan.Capabilities), tt.wantAdmitted)
}
})
}
}
func TestRefusalNamesTheCapability(t *testing.T) {
_, err := Admit(descriptor(t, spec.KindWorkload, sessions+"\n - type: com.docker.sandbox/usb-device@1\n config: {class: hid}"))
if err == nil || !strings.Contains(err.Error(), "com.docker.sandbox/usb-device@1") {
t.Fatalf("error %v does not name the refused capability", err)
}
}
// admit reads one Kit the way the launcher does: merged alone, then admitted.
func admit(t *testing.T, c spec.Contribution) (*Plan, error) {
t.Helper()
merged, err := spec.Merge([]spec.Contribution{c}, MergeOptions)
if err != nil {
t.Fatalf("Merge: %v", err)
}
return FromMerge(merged)
}
func TestFromMerge(t *testing.T) {
workload := spec.Contribution{Reference: "workload", Descriptor: descriptor(t, spec.KindWorkload, sessions)}
mixin := spec.Contribution{Reference: "mixin", Descriptor: descriptor(t, spec.KindMixin, `
- type: com.docker.sandbox/network-policy@1
config: {runtime: {allow: [api.example.com]}}`)}
bareWorkload := spec.Contribution{Reference: "bare", Descriptor: descriptor(t, spec.KindWorkload, `
- type: com.docker.sandbox/resources@1
config: {memory: 1g}`)}
plan, err := admit(t, workload)
if err != nil || plan.Sessions == nil || len(plan.Sessions.Prompt) == 0 {
t.Fatalf("admit(workload) = %+v, %v; want a plan with a headless prompt verb", plan, err)
}
tests := []struct {
name string
kit spec.Contribution
want string
}{
{"a bare mixin", mixin, "publish a Kit set"},
{"no headless prompt verb", bareWorkload, "agent-sessions"},
}
for _, tt := range tests {
t.Run(tt.name+" is refused", func(t *testing.T) {
_, err := admit(t, tt.kit)
if err == nil || !strings.Contains(err.Error(), tt.want) {
t.Fatalf("error %v, want one mentioning %q", err, tt.want)
}
})
}
}
// TestValidateNeeds pins the harness PRD's "a gate retry without a resume
// verb" refusal (Contract): archie resumes the harness's own session with the
// gate's output rather than starting a fresh one, so a gated stage's retry
// budget is unmeetable by a Kit whose agent-sessions capability names no
// resume verb.
func TestValidateNeeds(t *testing.T) {
promptOnly := descriptor(t, spec.KindWorkload, `
- type: com.docker.sandbox/agent-sessions@1
config:
prompt: [-p, "{{.Prompt}}"]`)
withResume := descriptor(t, spec.KindWorkload, sessions)
tests := []struct {
name string
descriptor *spec.Descriptor
gateRetries int
wantErr bool
}{
{"no gated stage, no resume verb", promptOnly, 0, false},
{"gated stage, no resume verb", promptOnly, 2, true},
{"gated stage, a resume verb", withResume, 2, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
plan, err := Admit(tt.descriptor)
if err != nil {
t.Fatalf("Admit: %v", err)
}
sessions, err := spec.AgentSessionsOf(plan.Capabilities)
if err != nil {
t.Fatalf("AgentSessionsOf: %v", err)
}
plan.Sessions = sessions
err = ValidateNeeds(plan, tt.gateRetries)
if tt.wantErr && err == nil {
t.Fatal("ValidateNeeds accepted a gate retry budget the kit cannot resume")
}
if !tt.wantErr && err != nil {
t.Fatalf("ValidateNeeds: %v", err)
}
})
}
}
func TestDecodePublished(t *testing.T) {
published := "schemaVersion: \"3\"\nkind: workload\ncapabilities:" + sessions + "\n"
tests := []struct {
name string
annotations map[string]string
wantErr string
}{
{"a published descriptor decodes", map[string]string{spec.AnnotationDescriptor: published}, ""},
{"an image without the annotation is not a kit", map[string]string{"org.opencontainers.image.title": "x"}, "not a kit"},
{"an unknown field is an error", map[string]string{spec.AnnotationDescriptor: published + "surprise: true\n"}, "surprise"},
{"an unexpanded build arg is not a published form", map[string]string{spec.AnnotationDescriptor: "schemaVersion: \"3\"\nkind: workload\nversion: \"${{ kit.args.version }}\"\n"}, "version"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d, err := DecodePublished(tt.annotations)
if tt.wantErr == "" {
if err != nil || d == nil {
t.Fatalf("DecodePublished: %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("error %v, want one mentioning %q", err, tt.wantErr)
}
})
}
}
-222
View File
@@ -1,222 +0,0 @@
package kit
import (
"slices"
"strings"
"testing"
"github.com/docker/sandbox-kit-spec/v3/spec"
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
)
const launchKit = `
- type: com.docker.sandbox/agent-sessions@1
config:
prompt: [-p, "{{.Prompt}}"]
resume: [--resume, "{{.SessionID}}"]
- type: com.docker.sandbox/network-policy@1
config: {install: {allow: [registry.example.com]}, runtime: {allow: [api.example.com]}}
- type: com.docker.sandbox/credential@1
config:
service: example
phase: runtime
apiKey: {name: EXAMPLE_KEY, proxyManaged: true, inject: [{domain: api.example.com, header: x-api-key, format: "%s"}]}
- type: com.docker.sandbox/volume@1
config: {path: /home/agent/.cli/sessions, size: 1g}
- type: com.docker.sandbox/volume@1
config: {path: /home/agent/.cli/history}
- type: com.docker.sandbox/lifecycle@1
config:
install:
- command: echo "$WORKSPACE_DIR" > /etc/seeded
env: [WORKSPACE_DIR]
startup:
- command: [cli, warm-up]
env: [SBX_CRED_EXAMPLE_MODE, NOT_A_RUNTIME_VARIABLE]
- command: [cli, daemon]
user: "0"
background: true`
func plan(t *testing.T) *Plan {
t.Helper()
p, err := admit(t, spec.Contribution{Reference: "kit", Descriptor: descriptor(t, spec.KindWorkload, launchKit)})
if err != nil {
t.Fatalf("admit: %v", err)
}
return p
}
var image = ImageConfig{
Entrypoint: []string{"/usr/local/bin/cli"},
Cmd: []string{"--no-color"},
Env: []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/home/agent", "IMAGE_ONLY=kept"},
User: "agent",
}
var params = LaunchParams{Execution: "exec-42", ProxyToken: "tok", CAPath: "/etc/archie/ca.pem", Bound: map[string]egress.CredentialKind{"example": egress.CredentialAPIKey}}
func TestAssembleHarness(t *testing.T) {
l, err := Assemble(plan(t), image, params)
if err != nil {
t.Fatal(err)
}
h := l.Harness
if !slices.Equal(h.Launch, []string{"/usr/local/bin/cli", "--no-color"}) {
t.Errorf("launch %v, want the image entrypoint then cmd", h.Launch)
}
if !slices.Equal(h.Prompt, []string{"-p", "{{.Prompt}}"}) || !slices.Equal(h.Resume, []string{"--resume", "{{.SessionID}}"}) {
t.Errorf("verbs prompt=%v resume=%v, want the Kit's agent-sessions verbs", h.Prompt, h.Resume)
}
if h.User != "agent" {
t.Errorf("user %q, want the image's user", h.User)
}
for _, want := range []string{
"PATH=/usr/local/bin:/usr/bin:/bin", "IMAGE_ONLY=kept",
"WORKSPACE_DIR=" + WorkspaceDir,
"HTTPS_PROXY=http://archie:tok@archie-egress:3128",
"SSL_CERT_FILE=/etc/archie/ca.pem",
"EXAMPLE_KEY=archie-proxy-managed",
} {
if !slices.Contains(h.Env, want) {
t.Errorf("harness env lacks %q:\n%s", want, strings.Join(h.Env, "\n"))
}
}
}
func TestAssembleNeverRunsTheHarnessAsRoot(t *testing.T) {
for _, user := range []string{"", "root", "0", "0:0"} {
img := image
img.User = user
l, err := Assemble(plan(t), img, params)
if err != nil {
t.Fatal(err)
}
if l.Harness.User != DefaultHarnessUser {
t.Errorf("image user %q gave harness user %q, want %q", user, l.Harness.User, DefaultHarnessUser)
}
}
}
func TestAssembleHooks(t *testing.T) {
l, err := Assemble(plan(t), image, params)
if err != nil {
t.Fatal(err)
}
if len(l.Install) != 1 || len(l.Startup) != 2 {
t.Fatalf("install %d startup %d, want 1 and 2", len(l.Install), len(l.Startup))
}
install := l.Install[0]
if !slices.Equal(install.Argv, []string{"sh", "-c", `echo "$WORKSPACE_DIR" > /etc/seeded`}) {
t.Errorf("a string command runs through the shell, as the Kit spec decodes it; got %v", install.Argv)
}
if install.User != "0" {
t.Errorf("install hook user %q, want root by default", install.User)
}
if !slices.Contains(install.Env, "WORKSPACE_DIR="+WorkspaceDir) || !slices.Contains(install.Env, "HTTPS_PROXY=http://archie:tok@archie-egress:3128") {
t.Errorf("install env %v, want its declared variable and the egress baseline", install.Env)
}
warm := l.Startup[0]
if warm.User != DefaultHarnessUser {
t.Errorf("startup hook user %q, want the agent user by default", warm.User)
}
if !slices.Contains(warm.Env, "SBX_CRED_EXAMPLE_MODE=apikey") {
t.Errorf("startup env %v, want the bound credential's mode", warm.Env)
}
for _, e := range warm.Env {
if strings.HasPrefix(e, "NOT_A_RUNTIME_VARIABLE=") || strings.HasPrefix(e, "IMAGE_ONLY=") || strings.HasPrefix(e, "EXAMPLE_KEY=") {
t.Errorf("startup env carries %q, which it neither declared nor is baseline", e)
}
}
if daemon := l.Startup[1]; daemon.User != "0" || !daemon.Background {
t.Errorf("startup hook %+v, want its declared root user and background flag", daemon)
}
}
func TestAssembleVolumesArePerExecution(t *testing.T) {
a, err := Assemble(plan(t), image, params)
if err != nil {
t.Fatal(err)
}
again, _ := Assemble(plan(t), image, params)
other := params
other.Execution = "exec-43"
b, _ := Assemble(plan(t), image, other)
if len(a.Volumes) != 2 {
t.Fatalf("volumes %v, want 2", a.Volumes)
}
if !slices.Equal(a.Volumes, again.Volumes) {
t.Error("volume names are not stable for one execution; a retry would lose its sessions")
}
if a.Volumes[0].Name == a.Volumes[1].Name {
t.Error("two paths share a volume")
}
for i := range a.Volumes {
if a.Volumes[i].Name == b.Volumes[i].Name {
t.Errorf("executions share volume %q", a.Volumes[i].Name)
}
}
}
func TestAssembleAgentContextProfile(t *testing.T) {
assemble := func(t *testing.T, contextYAML string) Launch {
t.Helper()
p, err := admit(t, spec.Contribution{Reference: "registry/team-set@sha256:ab", Descriptor: descriptor(t, spec.KindWorkload, sessions+contextYAML)})
if err != nil {
t.Fatalf("admit: %v", err)
}
l, err := Assemble(p, image, LaunchParams{Execution: "exec-1"})
if err != nil {
t.Fatalf("Assemble: %v", err)
}
return l
}
byPath := func(files []spec.File) map[string]string {
out := map[string]string{}
for _, f := range files {
out[f.Path] = f.Content
}
return out
}
t.Run("a staged body is indexed where the image holds it", func(t *testing.T) {
files := byPath(assemble(t, `
- type: com.docker.sandbox/agent-context@1
config: {filename: CLAUDE.md, contentFile: /usr/share/sandbox/kit/team/context.md}`).Context)
profile, ok := files["/archie/CLAUDE.md"]
if !ok || len(files) != 1 {
t.Fatalf("context files = %v, want only the profile beside the workspace", files)
}
if !strings.Contains(profile, "registry/team-set@sha256:ab") || !strings.Contains(profile, "/usr/share/sandbox/kit/team/context.md") {
t.Fatalf("profile does not index the Kit's staged body:\n%s", profile)
}
})
t.Run("an inline body gets its own file the profile points at", func(t *testing.T) {
files := byPath(assemble(t, `
- type: com.docker.sandbox/agent-context@1
config: {filename: AGENTS.md, content: "Use motd."}`).Context)
profile := files["/archie/AGENTS.md"]
var body string
for path, content := range files {
if path != "/archie/AGENTS.md" {
body = path
if content != "Use motd." {
t.Fatalf("%s = %q, want the inline body", path, content)
}
}
}
if body == "" || strings.HasPrefix(body, WorkspaceDir+"/") || !strings.Contains(profile, body) {
t.Fatalf("files %v: want the inline body outside the workspace and indexed by the profile", files)
}
if strings.Contains(profile, "Use motd.") {
t.Fatal("the profile inlines a Kit's body; it must only point at it")
}
})
t.Run("no profile filename materializes nothing", func(t *testing.T) {
if files := assemble(t, "").Context; len(files) != 0 {
t.Fatalf("context files = %v, want none", files)
}
})
}