package runner import ( "context" "crypto/x509" "io" "net/http" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runnerproto" ) func configFixture(t *testing.T) Config { t.Helper() root := t.TempDir() amadan := filepath.Join(root, "amadan") mustJournal(t, os.WriteFile(amadan, []byte("#!/bin/sh\nexit 0\n"), 0700)) return Config{BwrapPath: "/usr/bin/bwrap", ClaudePath: "/usr/bin/claude", CodexCodeModeHostPath: "/usr/bin/codex-code-mode-host", Origin: "https://equipo.example", StateDir: filepath.Join(root, "state"), AmadanCredentialPath: filepath.Join(root, "forge.json"), AccountBindingsPath: filepath.Join(root, "bindings.json"), CodexPath: "/usr/bin/codex", GoRoot: "/opt/go", GoBinary: "/opt/go/bin/go", WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: amadan, Executable: "/usr/bin/equipo-runner", InstanceID: "instance"} } func TestRunnerConfig(t *testing.T) { c := configFixture(t) mustJournal(t, c.validate()) policy, err := bindingPolicy(c, nil, AccountBinding{}) if err != nil || c.securityPaths(nil).ForgeCredential != c.AmadanCredentialPath || !slices.Contains(policy.DeniedPaths, c.AmadanCredentialPath) { t.Fatal("forge credentials absent from protected paths", err) } for _, origin := range []string{"http://example.com", "https://user:pass@example.com", "https://example.com/path", "https://example.com?x=y", "https://example.com/#x"} { bad := c bad.Origin = origin if bad.validate() == nil { t.Fatalf("accepted unsafe origin %s", origin) } } bad := c bad.StateDir = "relative" if bad.validate() == nil { t.Fatal("accepted relative state") } if _, err := LoadConfig(func(string) string { return "" }); err == nil { t.Fatal("accepted missing config") } } func TestRunnerServiceLifecycle(t *testing.T) { c := configFixture(t) lock, err := lockState(c.StateDir) if err != nil { t.Fatal(err) } if second, err := lockState(c.StateDir); err == nil { second.Close() t.Fatal("second process acquired lock") } st, err := os.Stat(c.StateDir) if err != nil || st.Mode().Perm() != 0700 { t.Fatal("state is not private", err) } lock.Close() lock, err = lockState(c.StateDir) if err != nil { t.Fatal("lock not released", err) } lock.Close() path := filepath.Join(c.StateDir, "credentials.json") credential := runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Version: 1, Token: "secret", ExpiresAt: time.Now().Add(time.Hour)}} if err := runnerproto.JournalCredentials(path, credential); err != nil { t.Fatal(err) } got, err := readCredentials(path) if err != nil || got.Bearer.Token != "secret" { t.Fatal("credentials not restored", err) } st, _ = os.Stat(path) if st.Mode().Perm() != 0600 { t.Fatal("credential mode") } if err := os.Chmod(path, 0644); err != nil { t.Fatal(err) } if _, err = readCredentials(path); err == nil { t.Fatal("accepted exposed credentials") } } type transportFunc func(*http.Request) (*http.Response, error) func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func TestRunnerHTTPClient(t *testing.T) { j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "j.db")) if err != nil { t.Fatal(err) } defer j.Close() c, err := NewHTTPInstance("https://equipo.example/api/runner/v2", j, runnerproto.RunnerCredential{Token: "secret", ExpiresAt: time.Now().Add(time.Hour)}) if err != nil { t.Fatal(err) } calls := 0 c.client.Transport = transportFunc(func(r *http.Request) (*http.Response, error) { calls++ if r.URL.Host != "equipo.example" || r.Header.Get("Authorization") != "Bearer secret" { t.Fatal("bearer escaped origin") } return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{"https://evil.example/"}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil }) if _, err = c.Poll(context.Background()); err == nil || calls != 1 { t.Fatal("followed redirect", err, calls) } c.bearer.ExpiresAt = time.Now().Add(-time.Second) if _, err = c.Poll(context.Background()); err == nil || calls != 1 { t.Fatal("expired credential reused") } } func TestRunnerHTTPClientTLSFailure(t *testing.T) { j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private/j.db")) if err != nil { t.Fatal(err) } defer j.Close() c, err := NewHTTPInstance("https://equipo.example/api/runner/v2", j, runnerproto.RunnerCredential{Token: "secret", ExpiresAt: time.Now().Add(time.Hour)}) if err != nil { t.Fatal(err) } calls := 0 c.client.Transport = transportFunc(func(*http.Request) (*http.Response, error) { calls++; return nil, x509.UnknownAuthorityError{} }) if _, err = c.Poll(context.Background()); err == nil || calls != 1 { t.Fatal("TLS failure bypassed", err, calls) } } func TestAccountHomeConfiguredRuntime(t *testing.T) { c := configFixture(t) b := AccountBinding{ProviderHome: filepath.Join(t.TempDir(), "dedicated")} if _, e := c.DirectBinding(b); e != nil { t.Fatal(e) } for _, path := range []string{"/", "relative", b.ProviderHome, filepath.Join(b.ProviderHome, "nested")} { bad := c bad.ScratchRoot = path if _, e := bad.DirectBinding(b); e == nil { t.Fatalf("unsafe runtime root accepted: %s", path) } } } func TestRunnerConfigAmadanPath(t *testing.T) { c := configFixture(t) command := filepath.Join(t.TempDir(), "amadan") t.Chdir(filepath.Dir(command)) if err := os.WriteFile(command, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { t.Fatal(err) } env := map[string]string{ "EQUIPO_ORIGIN": c.Origin, "EQUIPO_INSTANCE_ID": c.InstanceID, "EQUIPO_RUNNER_STATE_DIR": c.StateDir, "EQUIPO_AMADAN_CREDENTIAL_PATH": c.AmadanCredentialPath, "EQUIPO_ACCOUNT_BINDINGS_PATH": c.AccountBindingsPath, "EQUIPO_CODEX_PATH": c.CodexPath, "EQUIPO_GO_ROOT": c.GoRoot, "EQUIPO_GO_BINARY": c.GoBinary, "EQUIPO_WORKSPACE_ROOT": c.WorkspaceRoot, "EQUIPO_SCRATCH_ROOT": c.ScratchRoot, "EQUIPO_GIT_PATH": c.GitPath, "EQUIPO_RUNNER_EXECUTABLE": c.Executable, "EQUIPO_AMADAN_PATH": command, "EQUIPO_BWRAP_PATH": c.BwrapPath, "EQUIPO_CLAUDE_PATH": c.ClaudePath, "EQUIPO_CODEX_CODE_MODE_HOST_PATH": c.CodexCodeModeHostPath, } if _, err := LoadConfig(func(k string) string { return env[k] }); err != nil { t.Fatal(err) } for _, mode := range []string{"unset", "relative", "unclean", "missing", "directory", "not_executable"} { t.Run(mode, func(t *testing.T) { path := command switch mode { case "unset": path = "" case "relative": path = "amadan" case "unclean": path = filepath.Dir(command) + "/./amadan" case "missing": path += "-missing" case "directory": path = filepath.Dir(command) case "not_executable": path += "-not-executable" if err := os.WriteFile(path, []byte("exit 0"), 0600); err != nil { t.Fatal(err) } } env["EQUIPO_AMADAN_PATH"] = path _, err := LoadConfig(func(k string) string { return env[k] }) _, variable := Diagnostic(err) if err == nil || variable != "EQUIPO_AMADAN_PATH" { t.Fatalf("invalid Amadan path accepted or misdiagnosed: %v (%s)", err, variable) } }) } } // A Mac worker needs its roots, git and itself, nothing of the Linux // runner's harnesses; the same configuration on Linux is refused. func TestMacWorkerConfig(t *testing.T) { root := t.TempDir() c := Config{Origin: "https://equipo.example", InstanceID: "instance", StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", Executable: "/Users/equipo-paul/.local/lib/equipo-runner/equipo-runner"} mustJournal(t, c.validateFor("darwin")) if c.validateFor("linux") == nil { t.Fatal("a Linux runner without bubblewrap or harnesses accepted") } for name, bad := range map[string]func(*Config){ "origin": func(c *Config) { c.Origin = "http://example.com" }, "instance": func(c *Config) { c.InstanceID = "" }, "git": func(c *Config) { c.GitPath = "git" }, "scratch inside": func(c *Config) { c.ScratchRoot = filepath.Join(c.StateDir, "scratch") }, "state inside": func(c *Config) { c.StateDir = filepath.Join(c.WorkspaceRoot, "state") }, } { b := c bad(&b) if b.validateFor("darwin") == nil { t.Fatalf("%s accepted", name) } } } func TestPreviewHostDefaultsToPrivateDevbox(t *testing.T) { for _, kind := range []string{"", "devbox", "carloku_temp", "off"} { c, _ := LoadConfig(func(k string) string { if k == "EQUIPO_PREVIEW_HOST" { return kind } return "" }) want := kind if want == "" { want = "devbox" } if c.PreviewHost != want { t.Fatalf("host %q: got %q want %q", kind, c.PreviewHost, want) } } }