feat: isolate task workspaces and capture exact Git candidates
9 files changed,
+1,653
−13
internal/equipo/task_prepare.go+4 −7internal/runner/paseo/client.go+21 −1internal/runner/paseo/client_test.go+23 −1internal/runner/paseo/types.go+13 −0internal/runner/workspace/workspace.go+869 −0internal/runner/workspace/workspace_test.go+688 −0internal/runnerproto/types.go+6 −0runner/paseo/bridge.mjs+14 −2runner/paseo/bridge.test.mjs+15 −2
CI failed — run details
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go| index a8a53175..5a15047a 100644 |
| --- a/internal/equipo/task_prepare.go |
| +++ b/internal/equipo/task_prepare.go |
| @@ -8,14 +8,11 @@ import ( |
| "reflect" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| ) |
| -type PreparedBug struct { |
| - Repository, DefaultBranch, BaseCommit string |
| - CheckDefinition []byte |
| - CheckDefinitionHash, BaselineTestSetHash string |
| -} |
| +type PreparedBug = runnerproto.PreparedBug |
| type BugPreparer interface { |
| Prepare(context.Context, TargetBinding) (PreparedBug, error) |
| } |
| @@ -24,7 +21,7 @@ func hexDigest(s string, n int) bool { |
| b, err := hex.DecodeString(s) |
| return err == nil && len(b) == n/2 && hex.EncodeToString(b) == s |
| } |
| -func (p PreparedBug) valid(project Project) bool { |
| +func validPreparedBug(p PreparedBug, project Project) bool { |
| hash := sha256.Sum256(p.CheckDefinition) |
| return p.Repository == project.Repository && p.DefaultBranch == project.DefaultBranch && (hexDigest(p.BaseCommit, 40) || hexDigest(p.BaseCommit, 64)) && len(p.CheckDefinition) > 0 && len(p.CheckDefinition) <= team.MaxArtifactBytes && p.CheckDefinitionHash == hex.EncodeToString(hash[:]) && hexDigest(p.BaselineTestSetHash, 64) |
| } |
| @@ -107,7 +104,7 @@ func (s *Store) PrepareBug(ctx context.Context, principal RunnerPrincipal, taskI |
| if err != nil { |
| return err |
| } |
| - if !prepared.valid(project) { |
| + if !validPreparedBug(prepared, project) { |
| return ErrInvalid |
| } |
| raw, _ := json.Marshal(prepared) |
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go| index 952240fc..20bb1f55 100644 |
| --- a/internal/runner/paseo/client.go |
| +++ b/internal/runner/paseo/client.go |
| @@ -402,7 +402,7 @@ func (c *Client) intent(ctx context.Context, kind, key string, request any) erro |
| } |
| func (c *Client) CreateWorkspace(ctx context.Context, r WorkspaceRequest) (Workspace, error) { |
| var w Workspace |
| - if !pathAllowed(r.Path, r.ReadPolicy) || r.ProjectID == "" || r.BaseCommit == "" || r.Branch == "" { |
| + if r.Isolation != "worktree" || !pathAllowed(r.Path, r.ReadPolicy) || r.ProjectID == "" || r.BaseCommit == "" || r.Branch == "" { |
| return w, ErrPolicy |
| } |
| if _, err := c.Preflight(ctx, r.Selection, r.ReadPolicy); err != nil { |
| @@ -609,3 +609,23 @@ func (c *Client) ArchiveWorkspace(ctx context.Context, w Workspace) error { |
| Workspace Workspace `json:"workspace"` |
| }{w}, nil) |
| } |
| + |
| +func (c *Client) RegisterProject(ctx context.Context, r ProjectRequest) (Project, error) { |
| + var p Project |
| + if !pathAllowed(r.Path, r.ReadPolicy) { |
| + return p, ErrPolicy |
| + } |
| + if _, err := c.Preflight(ctx, r.Selection, r.ReadPolicy); err != nil { |
| + return p, err |
| + } |
| + if err := c.intent(ctx, "project", r.IdempotencyKey, r); err != nil { |
| + return p, err |
| + } |
| + if err := c.call(ctx, "register_project", r, &p); err != nil { |
| + return p, err |
| + } |
| + if p.ServerID != c.cfg.ServerID || p.ProjectID == "" || p.Path != r.Path { |
| + return p, ErrUncertain |
| + } |
| + return p, nil |
| +} |
diff --git a/internal/runner/paseo/client_test.go b/internal/runner/paseo/client_test.go| index 9aba94db..046f69a6 100644 |
| --- a/internal/runner/paseo/client_test.go |
| +++ b/internal/runner/paseo/client_test.go |
| @@ -72,7 +72,7 @@ func TestPaseoAdapterContract(t *testing.T) { |
| if err != nil || !caps.ReadIsolation { |
| t.Fatalf("preflight: %+v %v", caps, err) |
| } |
| - w, err := c.CreateWorkspace(ctx, WorkspaceRequest{ProjectID: "project", Path: "/repo", BaseCommit: strings.Repeat("a", 40), Branch: "review/fixture", IdempotencyKey: "workspace-intent", Selection: fixtureSelection(), ReadPolicy: fixturePolicy()}) |
| + w, err := c.CreateWorkspace(ctx, WorkspaceRequest{Isolation: "worktree", ProjectID: "project", Path: "/repo", BaseCommit: strings.Repeat("a", 40), Branch: "review/fixture", IdempotencyKey: "workspace-intent", Selection: fixtureSelection(), ReadPolicy: fixturePolicy()}) |
| if err != nil || w != fixtureWorkspace() { |
| t.Fatalf("workspace: %+v %v", w, err) |
| } |
| @@ -257,6 +257,8 @@ func TestPaseoHelper(t *testing.T) { |
| caps.PaseoVersion = "0.15.0" |
| } |
| result = caps |
| + case "register_project": |
| + result = Project{ServerID: "server", ProjectID: "project", Path: "/repo"} |
| case "create_workspace": |
| result = fixtureWorkspace() |
| case "create_agent": |
| @@ -375,3 +377,23 @@ func TestPaseoPolicyAndRecovery(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestPaseoWorkspaceIsolationMode(t *testing.T) { |
| + c := testClient(t, "normal", nil) |
| + r := WorkspaceRequest{Isolation: "none", ProjectID: "project", Path: "/repo", BaseCommit: strings.Repeat("a", 40), Branch: "review/fixture", IdempotencyKey: "workspace-intent", Selection: fixtureSelection(), ReadPolicy: fixturePolicy()} |
| + if _, err := c.CreateWorkspace(context.Background(), r); !errors.Is(err, ErrPolicy) { |
| + t.Fatalf("wrong isolation accepted: %v", err) |
| + } |
| +} |
| +func TestPaseoRegisterProject(t *testing.T) { |
| + c := testClient(t, "normal", nil) |
| + r := ProjectRequest{Path: "/repo", IdempotencyKey: "project-intent", Selection: fixtureSelection(), ReadPolicy: fixturePolicy()} |
| + p, err := c.RegisterProject(context.Background(), r) |
| + if err != nil || p.ProjectID != "project" || p.Path != "/repo" { |
| + t.Fatalf("project registration: %+v %v", p, err) |
| + } |
| + r.Path = "/protected/repo" |
| + if _, err := c.RegisterProject(context.Background(), r); !errors.Is(err, ErrPolicy) { |
| + t.Fatal("protected project registered") |
| + } |
| +} |
diff --git a/internal/runner/paseo/types.go b/internal/runner/paseo/types.go| index b0bb9c2b..b5177643 100644 |
| --- a/internal/runner/paseo/types.go |
| +++ b/internal/runner/paseo/types.go |
| @@ -77,6 +77,7 @@ type Agent struct { |
| Family string `json:"family"` |
| } |
| type WorkspaceRequest struct { |
| + Isolation string `json:"isolation"` |
| ProjectID string `json:"project_id"` |
| Path string `json:"path"` |
| BaseCommit string `json:"base_commit"` |
| @@ -138,3 +139,15 @@ type Config struct { |
| InspectProcesses func(context.Context, Selection) (bool, error) |
| AuthorizeUnconfined func(context.Context, Selection, Capabilities) error |
| } |
| + |
| +type ProjectRequest struct { |
| + Path string `json:"path"` |
| + IdempotencyKey string `json:"idempotency_key"` |
| + Selection Selection `json:"selection"` |
| + ReadPolicy ReadPolicy `json:"read_policy"` |
| +} |
| +type Project struct { |
| + ServerID string `json:"server_id"` |
| + ProjectID string `json:"project_id"` |
| + Path string `json:"path"` |
| +} |
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go| new file mode 100644 |
| index 00000000..adebb030 |
| --- /dev/null |
| +++ b/internal/runner/workspace/workspace.go |
| @@ -0,0 +1,869 @@ |
| +package workspace |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha1" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type PreparedBug = runnerproto.PreparedBug |
| +type GitCandidate = team.GitCandidate |
| +type Remote struct{ URL, Bearer string } |
| +type ForgeRead interface { |
| + Resolve(context.Context, string) (Remote, error) |
| +} |
| +type SecurityPaths struct { |
| + RunnerState, RunnerConfig, Journal, Bearer, Cleanup, ForgeCredential, PaseoHome, SSH string |
| + ProviderHomes []string |
| +} |
| + |
| +func (p SecurityPaths) all() []string { |
| + return append([]string{p.RunnerState, p.RunnerConfig, p.Journal, p.Bearer, p.Cleanup, p.ForgeCredential, p.PaseoHome, p.SSH}, p.ProviderHomes...) |
| +} |
| + |
| +type Config struct { |
| + Protected SecurityPaths |
| + PrivateRoot, WorkspaceRoot, GitPath string |
| + Forge ForgeRead |
| + Policy func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) |
| + Definitions func(context.Context, team.TargetBinding, string) (PreparedBug, error) |
| +} |
| +type workspaceClient interface { |
| + RegisterProject(context.Context, paseo.ProjectRequest) (paseo.Project, error) |
| + Preflight(context.Context, paseo.Selection, paseo.ReadPolicy) (paseo.Capabilities, error) |
| + CreateWorkspace(context.Context, paseo.WorkspaceRequest) (paseo.Workspace, error) |
| +} |
| +type Manager struct { |
| + cfg Config |
| + client workspaceClient |
| + mu sync.Mutex |
| +} |
| +type Workspace struct { |
| + Paseo paseo.Workspace |
| + ArtifactHashes []string |
| + Isolation team.IsolationSnapshot |
| + key string |
| +} |
| +type attempt struct { |
| + AssignmentHash string |
| + Hash string |
| + Request paseo.WorkspaceRequest |
| + Workspace paseo.Workspace |
| + Target team.TargetBinding |
| + ArtifactHashes []string |
| + Isolation team.IsolationSnapshot |
| +} |
| + |
| +var objectID = regexp.MustCompile(`^(?:[a-f0-9]{40}|[a-f0-9]{64})$`) |
| +var packFile = regexp.MustCompile(`^pack-[a-f0-9]{40}(?:[a-f0-9]{24})?\.(pack|idx|rev)$`) |
| + |
| +func New(cfg Config, client *paseo.Client) (*Manager, error) { |
| + if client == nil { |
| + return nil, paseo.ErrContract |
| + } |
| + return newManager(cfg, client) |
| +} |
| +func newManager(cfg Config, client workspaceClient) (*Manager, error) { |
| + if client == nil || cfg.Forge == nil || cfg.Policy == nil || cfg.Definitions == nil || !filepath.IsAbs(cfg.GitPath) { |
| + return nil, paseo.ErrContract |
| + } |
| + for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} { |
| + if !filepath.IsAbs(p) || filepath.Clean(p) != p { |
| + return nil, paseo.ErrPolicy |
| + } |
| + } |
| + if contains(cfg.PrivateRoot, cfg.WorkspaceRoot) || contains(cfg.WorkspaceRoot, cfg.PrivateRoot) { |
| + return nil, paseo.ErrPolicy |
| + } |
| + if len(cfg.Protected.ProviderHomes) == 0 { |
| + return nil, paseo.ErrPolicy |
| + } |
| + cfg.Protected.ProviderHomes = append([]string(nil), cfg.Protected.ProviderHomes...) |
| + for _, p := range cfg.Protected.all() { |
| + if _, e := canonical(p); e != nil { |
| + return nil, paseo.ErrPolicy |
| + } |
| + } |
| + for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} { |
| + if resolved, e := canonical(p); e != nil || resolved != p { |
| + return nil, paseo.ErrPolicy |
| + } |
| + if err := os.MkdirAll(p, 0700); err != nil { |
| + return nil, paseo.ErrPolicy |
| + } |
| + info, err := os.Stat(p) |
| + if err != nil || info.Mode().Perm()&0077 != 0 { |
| + return nil, paseo.ErrPolicy |
| + } |
| + resolved, err := filepath.EvalSymlinks(p) |
| + if err != nil || resolved != p { |
| + return nil, paseo.ErrPolicy |
| + } |
| + } |
| + return &Manager{cfg: cfg, client: client}, nil |
| +} |
| +func digest(v any) string { |
| + b, _ := json.Marshal(v) |
| + s := sha256.Sum256(b) |
| + return hex.EncodeToString(s[:]) |
| +} |
| +func contains(root, p string) bool { |
| + rel, e := filepath.Rel(root, p) |
| + return e == nil && (rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))) |
| +} |
| +func canonical(p string) (string, error) { |
| + if !filepath.IsAbs(p) || filepath.Clean(p) != p { |
| + return "", paseo.ErrPolicy |
| + } |
| + tail := "" |
| + for ancestor := p; ; ancestor = filepath.Dir(ancestor) { |
| + r, e := filepath.EvalSymlinks(ancestor) |
| + if e == nil { |
| + return filepath.Join(r, tail), nil |
| + } |
| + if !os.IsNotExist(e) || ancestor == filepath.Dir(ancestor) { |
| + return "", paseo.ErrPolicy |
| + } |
| + tail = filepath.Join(filepath.Base(ancestor), tail) |
| + } |
| +} |
| +func allowed(p string, policy paseo.ReadPolicy) bool { |
| + r, e := canonical(p) |
| + if e != nil || policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 { |
| + return false |
| + } |
| + for _, deny := range policy.DeniedPaths { |
| + d, e := canonical(deny) |
| + if e != nil || contains(d, r) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| +func safeEnv() map[string]string { |
| + return map[string]string{"PATH": "/usr/bin:/bin", "LANG": "C", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_TERMINAL_PROMPT": "0", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_ATTR_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "7", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": "/dev/null", "GIT_CONFIG_KEY_1": "credential.helper", "GIT_CONFIG_VALUE_1": "", "GIT_CONFIG_KEY_2": "core.fsmonitor", "GIT_CONFIG_VALUE_2": "false", "GIT_CONFIG_KEY_3": "protocol.allow", "GIT_CONFIG_VALUE_3": "never", "GIT_CONFIG_KEY_4": "core.attributesFile", "GIT_CONFIG_VALUE_4": "/dev/null", "GIT_CONFIG_KEY_5": "core.sshCommand", "GIT_CONFIG_VALUE_5": "/bin/false", "GIT_CONFIG_KEY_6": "commit.gpgSign", "GIT_CONFIG_VALUE_6": "false"} |
| +} |
| +func GitEnvironment() map[string]string { return safeEnv() } |
| +func (w Workspace) Environment() map[string]string { return GitEnvironment() } |
| +func (m *Manager) git(ctx context.Context, dir string, input []byte, extra map[string]string, args ...string) ([]byte, error) { |
| + cmd := exec.CommandContext(ctx, m.cfg.GitPath, args...) |
| + cmd.Dir = dir |
| + env := safeEnv() |
| + env["HOME"] = "/nonexistent" |
| + for k, v := range extra { |
| + env[k] = v |
| + } |
| + for k, v := range env { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Stdin = bytes.NewReader(input) |
| + cmd.Stderr = io.Discard |
| + b, err := cmd.Output() |
| + if err != nil { |
| + return nil, paseo.ErrContract |
| + } |
| + return b, nil |
| +} |
| +func (m *Manager) run(ctx context.Context, dir string, args ...string) (string, error) { |
| + b, e := m.git(ctx, dir, nil, nil, args...) |
| + return strings.TrimSpace(string(b)), e |
| +} |
| +func (m *Manager) validTarget(ctx context.Context, t team.TargetBinding, base bool) bool { |
| + if t.Kind != team.TargetRepository || t.Repository == "" || strings.ContainsAny(t.Repository, "\r\n\x00") || t.Ref == t.DefaultRef || t.Subject != "" || base && !objectID.MatchString(t.BaseRevision) { |
| + return false |
| + } |
| + for _, r := range []string{t.Ref, t.DefaultRef} { |
| + if r == "" || r == "HEAD" || r == "@" || strings.HasPrefix(r, "refs/") || strings.HasPrefix(r, "-") { |
| + return false |
| + } |
| + if _, e := m.run(ctx, m.cfg.PrivateRoot, "check-ref-format", "refs/heads/"+r); e != nil { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| +func (m *Manager) init(ctx context.Context, dir, format string, bare bool) error { |
| + args := []string{"init", "--template=", "--object-format=" + format} |
| + if bare { |
| + args = append(args, "--bare") |
| + } |
| + args = append(args, dir) |
| + if _, e := m.run(ctx, m.cfg.PrivateRoot, args...); e != nil { |
| + return e |
| + } |
| + for _, kv := range [][2]string{{"core.hooksPath", "/dev/null"}, {"credential.helper", ""}, {"core.fsmonitor", "false"}, {"core.attributesFile", "/dev/null"}, {"protocol.allow", "never"}, {"commit.gpgSign", "false"}} { |
| + if _, e := m.run(ctx, dir, "config", "--local", kv[0], kv[1]); e != nil { |
| + return e |
| + } |
| + } |
| + return nil |
| +} |
| +func objectFormat(id string) string { |
| + if len(id) == 64 { |
| + return "sha256" |
| + } |
| + return "sha1" |
| +} |
| +func (m *Manager) fetch(ctx context.Context, t team.TargetBinding) (string, string, error) { |
| + remote, err := m.cfg.Forge.Resolve(ctx, t.Repository) |
| + if err != nil { |
| + return "", "", paseo.ErrContract |
| + } |
| + protocol := "" |
| + if filepath.IsAbs(remote.URL) { |
| + r, e := canonical(remote.URL) |
| + if e != nil || r != remote.URL || remote.Bearer != "" { |
| + return "", "", paseo.ErrPolicy |
| + } |
| + protocol = "file" |
| + } else { |
| + u, e := url.Parse(remote.URL) |
| + if e != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(remote.URL+remote.Bearer, "\r\n\x00") { |
| + return "", "", paseo.ErrPolicy |
| + } |
| + protocol = "https" |
| + } |
| + repo := filepath.Join(m.cfg.PrivateRoot, "project-"+digest(t.Repository)) |
| + if _, err := os.Stat(repo); os.IsNotExist(err) { |
| + if err = m.init(ctx, repo, objectFormat(t.BaseRevision), true); err != nil { |
| + return "", "", err |
| + } |
| + } else if err != nil { |
| + return "", "", paseo.ErrContract |
| + } |
| + ref := t.BaseRevision |
| + if ref == "" { |
| + ref = "refs/heads/" + t.DefaultRef |
| + } |
| + env := map[string]string{} |
| + if remote.Bearer != "" { |
| + env["GIT_CONFIG_COUNT"] = "8" |
| + env["GIT_CONFIG_KEY_7"] = "http.extraHeader" |
| + env["GIT_CONFIG_VALUE_7"] = "Authorization: Bearer " + remote.Bearer |
| + } |
| + if _, err := m.git(ctx, repo, nil, env, "-c", "protocol."+protocol+".allow=always", "-c", "http.followRedirects=false", "fetch", "--no-auto-maintenance", "--no-tags", "--no-recurse-submodules", "--", remote.URL, ref); err != nil { |
| + return "", "", err |
| + } |
| + base, err := m.run(ctx, repo, "rev-parse", "--verify", "FETCH_HEAD^{commit}") |
| + if err != nil || !objectID.MatchString(base) || t.BaseRevision != "" && base != t.BaseRevision { |
| + return "", "", paseo.ErrIdentity |
| + } |
| + return repo, base, nil |
| +} |
| +func (m *Manager) Prepare(ctx context.Context, target team.TargetBinding) (PreparedBug, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if !m.validTarget(ctx, target, target.BaseRevision != "") { |
| + return PreparedBug{}, paseo.ErrContract |
| + } |
| + repo, base, err := m.fetch(ctx, target) |
| + if err != nil { |
| + return PreparedBug{}, err |
| + } |
| + target.BaseRevision = base |
| + p, err := m.cfg.Definitions(ctx, target, repo) |
| + if err != nil { |
| + return PreparedBug{}, paseo.ErrContract |
| + } |
| + s := sha256.Sum256(p.CheckDefinition) |
| + if len(p.CheckDefinition) == 0 || len(p.CheckDefinition) > team.MaxArtifactBytes || hex.EncodeToString(s[:]) != p.CheckDefinitionHash || len(p.BaselineTestSetHash) != 64 || !objectID.MatchString(p.BaselineTestSetHash) { |
| + return PreparedBug{}, paseo.ErrContract |
| + } |
| + p.Repository = target.Repository |
| + p.DefaultBranch = target.DefaultRef |
| + p.BaseCommit = base |
| + p.CheckDefinition = bytes.Clone(p.CheckDefinition) |
| + return p, nil |
| +} |
| +func selection(a runnerproto.Assignment) paseo.Selection { |
| + s := a.Selection |
| + return paseo.Selection{ConnectionID: s.ConnectionID, Provider: s.Provider, Family: s.Family, Model: s.Model, AccountID: s.AccountID} |
| +} |
| +func (m *Manager) preflight(ctx context.Context, a runnerproto.Assignment) (paseo.ReadPolicy, error) { |
| + s := selection(a) |
| + p, e := m.cfg.Policy(ctx, s) |
| + if e != nil { |
| + return p, paseo.ErrPolicy |
| + } |
| + p.DeniedPaths = append([]string(nil), p.DeniedPaths...) |
| + for _, protected := range append(m.cfg.Protected.all(), m.cfg.PrivateRoot) { |
| + resolved, e := canonical(protected) |
| + if e != nil { |
| + return p, paseo.ErrPolicy |
| + } |
| + for _, path := range []string{protected, resolved} { |
| + covered := false |
| + for _, d := range p.DeniedPaths { |
| + if !filepath.IsAbs(d) || filepath.Clean(d) != d { |
| + return p, paseo.ErrPolicy |
| + } |
| + if contains(d, path) { |
| + covered = true |
| + } |
| + } |
| + if !covered { |
| + return p, paseo.ErrPolicy |
| + } |
| + } |
| + } |
| + if !allowed(m.cfg.WorkspaceRoot, p) { |
| + return p, paseo.ErrPolicy |
| + } |
| + c, e := m.client.Preflight(ctx, s, p) |
| + if e != nil { |
| + return p, e |
| + } |
| + if c.IsolationConfigHash != p.ConfigHash { |
| + return p, paseo.ErrPolicy |
| + } |
| + snap := a.Selection.Isolation |
| + if !c.ReadIsolation { |
| + tuple := team.IsolationTuple{Provider: s.Provider, ProviderVersion: c.ProviderVersion, PaseoVersion: c.PaseoVersion, IsolationConfigHash: c.IsolationConfigHash} |
| + found := false |
| + for _, v := range snap.ObservedTuples { |
| + if v == tuple { |
| + found = true |
| + } |
| + } |
| + if s.Provider != "codex" || c.ProviderVersion != "0.165.0" || c.PaseoVersion != "0.14.0" || snap.Status != "unconfined" || !snap.RunnerTainted || len(snap.AcknowledgementIDs) == 0 || !found { |
| + return p, paseo.ErrIsolation |
| + } |
| + } else if snap.Status != "confined" { |
| + return p, paseo.ErrIsolation |
| + } |
| + return p, nil |
| +} |
| +func save(path string, v any) error { |
| + b, e := json.Marshal(v) |
| + if e != nil { |
| + return paseo.ErrContract |
| + } |
| + f, e := os.CreateTemp(filepath.Dir(path), ".receipt-") |
| + if e != nil { |
| + return paseo.ErrContract |
| + } |
| + name := f.Name() |
| + defer os.Remove(name) |
| + if _, e = f.Write(b); e == nil { |
| + e = f.Sync() |
| + } |
| + closeErr := f.Close() |
| + if e != nil || closeErr != nil { |
| + return paseo.ErrContract |
| + } |
| + if os.Rename(name, path) != nil { |
| + return paseo.ErrContract |
| + } |
| + d, e := os.Open(filepath.Dir(path)) |
| + if e != nil { |
| + return paseo.ErrContract |
| + } |
| + defer d.Close() |
| + if d.Sync() != nil { |
| + return paseo.ErrContract |
| + } |
| + return nil |
| +} |
| +func load(path string, v any) error { |
| + b, e := os.ReadFile(path) |
| + if e != nil { |
| + return e |
| + } |
| + if json.Unmarshal(b, v) != nil { |
| + return paseo.ErrContract |
| + } |
| + return nil |
| +} |
| +func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief runnerproto.RunnerBrief) (Workspace, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + var zero Workspace |
| + if a.ID == "" || a.TaskID == "" || a.WorkspaceKey == "" || a.StepKey == "" || !reflect.DeepEqual(a.Selection, brief.Selection) || !m.validTarget(ctx, brief.Target, true) { |
| + return zero, paseo.ErrContract |
| + } |
| + if a.StepKey == "implement" && len(brief.ArtifactHashes) == 0 { |
| + return zero, paseo.ErrContract |
| + } |
| + for _, h := range brief.ArtifactHashes { |
| + if len(h) != 64 || !objectID.MatchString(h) { |
| + return zero, paseo.ErrContract |
| + } |
| + } |
| + policy, err := m.preflight(ctx, a) |
| + if err != nil { |
| + return zero, err |
| + } |
| + hash := digest(struct { |
| + Assignment runnerproto.Assignment |
| + Brief runnerproto.RunnerBrief |
| + Policy paseo.ReadPolicy |
| + }{a, brief, policy}) |
| + dir := filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(a.WorkspaceKey)) |
| + record := filepath.Join(dir, "attempt.json") |
| + var at attempt |
| + err = load(record, &at) |
| + if os.IsNotExist(err) { |
| + if err = os.Mkdir(dir, 0700); err != nil { |
| + return zero, paseo.ErrUncertain |
| + } |
| + repo, _, e := m.fetch(ctx, brief.Target) |
| + if e != nil { |
| + return zero, e |
| + } |
| + source := filepath.Join(m.cfg.WorkspaceRoot, "source-"+digest(a.WorkspaceKey)) |
| + if !allowed(source, policy) { |
| + return zero, paseo.ErrPolicy |
| + } |
| + if _, e := os.Lstat(source); !os.IsNotExist(e) { |
| + return zero, paseo.ErrUncertain |
| + } |
| + if e = m.init(ctx, source, objectFormat(brief.Target.BaseRevision), false); e != nil { |
| + return zero, e |
| + } |
| + if e = copyObjects(filepath.Join(repo, "objects"), filepath.Join(source, ".git", "objects")); e != nil { |
| + return zero, e |
| + } |
| + if _, e = m.run(ctx, source, "checkout", "--detach", brief.Target.BaseRevision); e != nil { |
| + return zero, e |
| + } |
| + project, e := m.client.RegisterProject(ctx, paseo.ProjectRequest{Path: source, IdempotencyKey: "project-" + a.WorkspaceKey, Selection: selection(a), ReadPolicy: policy}) |
| + if e != nil { |
| + return zero, e |
| + } |
| + if project.ProjectID == "" || project.Path != source || project.ServerID == "" { |
| + return zero, paseo.ErrUncertain |
| + } |
| + at = attempt{AssignmentHash: digest(a), Hash: hash, Request: paseo.WorkspaceRequest{Isolation: "worktree", ProjectID: project.ProjectID, Path: source, BaseCommit: brief.Target.BaseRevision, Branch: brief.Target.Ref, IdempotencyKey: a.WorkspaceKey, Selection: selection(a), ReadPolicy: policy}, Target: brief.Target, ArtifactHashes: append([]string(nil), brief.ArtifactHashes...), Isolation: a.Selection.Isolation} |
| + if e = save(record, at); e != nil { |
| + return zero, e |
| + } |
| + } else if err != nil { |
| + return zero, paseo.ErrUncertain |
| + } |
| + if at.Hash != hash { |
| + return zero, paseo.ErrIdentity |
| + } |
| + if at.Workspace.WorkspaceID == "" { |
| + w, e := m.client.CreateWorkspace(ctx, at.Request) |
| + if e != nil { |
| + return zero, e |
| + } |
| + if w.WorkspaceID == "" || w.ServerID == "" || w.ProjectID != at.Request.ProjectID || !allowed(w.Path, policy) || !contains(m.cfg.WorkspaceRoot, w.Path) { |
| + return zero, paseo.ErrUncertain |
| + } |
| + at.Workspace = w |
| + if e = m.validateWorkspace(at); e != nil { |
| + return zero, e |
| + } |
| + head, e := m.head(at) |
| + if e != nil || head != at.Target.BaseRevision { |
| + return zero, paseo.ErrUncertain |
| + } |
| + if e = save(record, at); e != nil { |
| + return zero, e |
| + } |
| + } else if err = m.validateWorkspace(at); err != nil { |
| + return zero, err |
| + } |
| + return Workspace{Paseo: at.Workspace, ArtifactHashes: append([]string(nil), at.ArtifactHashes...), Isolation: at.Isolation, key: a.WorkspaceKey}, nil |
| +} |
| +func regular(path string) ([]byte, error) { |
| + s, e := os.Lstat(path) |
| + if e != nil || !s.Mode().IsRegular() { |
| + return nil, paseo.ErrIdentity |
| + } |
| + b, e := os.ReadFile(path) |
| + if e != nil { |
| + return nil, paseo.ErrIdentity |
| + } |
| + return b, nil |
| +} |
| +func (m *Manager) gitdir(at attempt) (string, error) { |
| + b, e := regular(filepath.Join(at.Workspace.Path, ".git")) |
| + if e != nil || !strings.HasPrefix(string(b), "gitdir: ") { |
| + return "", paseo.ErrIdentity |
| + } |
| + p := strings.TrimSpace(strings.TrimPrefix(string(b), "gitdir: ")) |
| + r, e := canonical(p) |
| + if e != nil || r != p || !contains(filepath.Join(at.Request.Path, ".git", "worktrees"), p) { |
| + return "", paseo.ErrIdentity |
| + } |
| + common, e := regular(filepath.Join(p, "commondir")) |
| + if e != nil { |
| + return "", e |
| + } |
| + r, e = canonical(filepath.Clean(filepath.Join(p, strings.TrimSpace(string(common))))) |
| + if e != nil || r != filepath.Join(at.Request.Path, ".git") { |
| + return "", paseo.ErrIdentity |
| + } |
| + return p, nil |
| +} |
| +func (m *Manager) validateWorkspace(at attempt) error { |
| + for _, p := range []string{at.Workspace.Path, at.Request.Path, filepath.Join(at.Request.Path, ".git")} { |
| + r, e := canonical(p) |
| + if e != nil || r != p || !allowed(p, at.Request.ReadPolicy) { |
| + return paseo.ErrPolicy |
| + } |
| + } |
| + _, e := m.gitdir(at) |
| + return e |
| +} |
| +func (m *Manager) head(at attempt) (string, error) { |
| + dir, e := m.gitdir(at) |
| + if e != nil { |
| + return "", e |
| + } |
| + b, e := regular(filepath.Join(dir, "HEAD")) |
| + ref := "refs/heads/" + at.Target.Ref |
| + if e != nil || strings.TrimSpace(string(b)) != "ref: "+ref { |
| + return "", paseo.ErrIdentity |
| + } |
| + common := filepath.Join(at.Request.Path, ".git") |
| + p := filepath.Join(common, ref) |
| + resolved, e := canonical(p) |
| + if e != nil || resolved != p { |
| + return "", paseo.ErrIdentity |
| + } |
| + b, e = regular(p) |
| + if e == nil { |
| + id := strings.TrimSpace(string(b)) |
| + if objectID.MatchString(id) { |
| + return id, nil |
| + } |
| + return "", paseo.ErrIdentity |
| + } |
| + b, e = regular(filepath.Join(common, "packed-refs")) |
| + if e != nil { |
| + return "", e |
| + } |
| + for _, line := range strings.Split(string(b), "\n") { |
| + parts := strings.Split(line, " ") |
| + if len(parts) == 2 && parts[1] == ref && objectID.MatchString(parts[0]) { |
| + return parts[0], nil |
| + } |
| + } |
| + return "", paseo.ErrIdentity |
| +} |
| +func copyObjects(from, to string) error { |
| + return filepath.WalkDir(from, func(p string, d os.DirEntry, err error) error { |
| + if err != nil { |
| + return paseo.ErrIdentity |
| + } |
| + rel, e := filepath.Rel(from, p) |
| + if e != nil || d.Type()&os.ModeSymlink != 0 { |
| + return paseo.ErrIdentity |
| + } |
| + if d.IsDir() { |
| + if rel != "." && rel != "info" && rel != "pack" && !(len(rel) == 2 && strings.Trim(rel, "0123456789abcdef") == "") { |
| + return paseo.ErrIdentity |
| + } |
| + if os.MkdirAll(filepath.Join(to, rel), 0700) != nil { |
| + return paseo.ErrContract |
| + } |
| + return nil |
| + } |
| + if !d.Type().IsRegular() { |
| + return paseo.ErrIdentity |
| + } |
| + parts := strings.Split(rel, string(filepath.Separator)) |
| + valid := len(parts) == 2 && ((len(parts[0]) == 2 && objectID.MatchString(parts[0]+parts[1])) || (parts[0] == "pack" && packFile.MatchString(parts[1]))) |
| + if !valid { |
| + return paseo.ErrIdentity |
| + } |
| + in, e := os.Open(p) |
| + if e != nil { |
| + return paseo.ErrIdentity |
| + } |
| + defer in.Close() |
| + out, e := os.OpenFile(filepath.Join(to, rel), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| + if e != nil { |
| + return paseo.ErrContract |
| + } |
| + _, e = io.Copy(out, in) |
| + closeErr := out.Close() |
| + if e != nil || closeErr != nil { |
| + return paseo.ErrContract |
| + } |
| + return nil |
| + }) |
| +} |
| +func (m *Manager) clean(ctx context.Context, repo, path, commit string) error { |
| + b, e := m.git(ctx, repo, nil, nil, "ls-tree", "-rz", "--full-tree", commit) |
| + if e != nil { |
| + return e |
| + } |
| + type entry struct{ mode, id string } |
| + tracked := map[string]entry{} |
| + dirs := map[string]bool{} |
| + for _, item := range bytes.Split(b, []byte{0}) { |
| + if len(item) == 0 { |
| + continue |
| + } |
| + parts := bytes.SplitN(item, []byte{'\t'}, 2) |
| + if len(parts) != 2 { |
| + return paseo.ErrIdentity |
| + } |
| + fields := strings.Fields(string(parts[0])) |
| + name := string(parts[1]) |
| + if len(fields) != 3 || fields[1] != "blob" || filepath.Clean(name) != name || filepath.IsAbs(name) || name == ".git" || strings.HasPrefix(name, "../") { |
| + return paseo.ErrIdentity |
| + } |
| + tracked[name] = entry{fields[0], fields[2]} |
| + for d := filepath.Dir(name); d != "."; d = filepath.Dir(d) { |
| + dirs[d] = true |
| + } |
| + } |
| + seen := 0 |
| + e = filepath.WalkDir(path, func(p string, d os.DirEntry, err error) error { |
| + if err != nil { |
| + return paseo.ErrIdentity |
| + } |
| + rel, e := filepath.Rel(path, p) |
| + if e != nil { |
| + return paseo.ErrIdentity |
| + } |
| + if rel == "." { |
| + return nil |
| + } |
| + if rel == ".git" { |
| + if d.IsDir() { |
| + return filepath.SkipDir |
| + } |
| + return nil |
| + } |
| + if d.IsDir() { |
| + if !dirs[rel] { |
| + return paseo.ErrIdentity |
| + } |
| + return nil |
| + } |
| + ent, ok := tracked[rel] |
| + if !ok { |
| + return paseo.ErrIdentity |
| + } |
| + var data []byte |
| + switch ent.mode { |
| + case "120000": |
| + if d.Type()&os.ModeSymlink == 0 { |
| + return paseo.ErrIdentity |
| + } |
| + link, e := os.Readlink(p) |
| + if e != nil || filepath.IsAbs(link) { |
| + return paseo.ErrIdentity |
| + } |
| + resolved, e := canonical(filepath.Clean(filepath.Join(filepath.Dir(p), link))) |
| + if e != nil || !contains(path, resolved) { |
| + return paseo.ErrIdentity |
| + } |
| + data = []byte(link) |
| + case "100644", "100755": |
| + if !d.Type().IsRegular() { |
| + return paseo.ErrIdentity |
| + } |
| + s, e := d.Info() |
| + if e != nil || ((s.Mode()&0111) != 0) != (ent.mode == "100755") { |
| + return paseo.ErrIdentity |
| + } |
| + data, e = os.ReadFile(p) |
| + if e != nil { |
| + return paseo.ErrIdentity |
| + } |
| + default: |
| + return paseo.ErrIdentity |
| + } |
| + framed := append([]byte(fmt.Sprintf("blob %d\x00", len(data))), data...) |
| + id := "" |
| + if len(ent.id) == 40 { |
| + s := sha1.Sum(framed) |
| + id = hex.EncodeToString(s[:]) |
| + } else { |
| + s := sha256.Sum256(framed) |
| + id = hex.EncodeToString(s[:]) |
| + } |
| + if id != ent.id { |
| + return paseo.ErrIdentity |
| + } |
| + seen++ |
| + return nil |
| + }) |
| + if e != nil || seen != len(tracked) { |
| + return paseo.ErrIdentity |
| + } |
| + return nil |
| +} |
| +func (m *Manager) CaptureCandidate(ctx context.Context, w Workspace, target team.TargetBinding) (GitCandidate, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + var zero GitCandidate |
| + var at attempt |
| + if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || at.Target != target { |
| + return zero, paseo.ErrIdentity |
| + } |
| + if e := m.validateWorkspace(at); e != nil { |
| + return zero, e |
| + } |
| + commit, e := m.head(at) |
| + if e != nil { |
| + return zero, e |
| + } |
| + staging, e := os.MkdirTemp(m.cfg.PrivateRoot, "capture-") |
| + if e != nil { |
| + return zero, paseo.ErrContract |
| + } |
| + defer os.RemoveAll(staging) |
| + if e = m.init(ctx, staging, objectFormat(target.BaseRevision), true); e != nil { |
| + return zero, e |
| + } |
| + if e = copyObjects(filepath.Join(at.Request.Path, ".git", "objects"), filepath.Join(staging, "objects")); e != nil { |
| + return zero, e |
| + } |
| + if _, e = m.run(ctx, staging, "merge-base", "--is-ancestor", target.BaseRevision, commit); e != nil { |
| + return zero, paseo.ErrIdentity |
| + } |
| + tree, e := m.run(ctx, staging, "rev-parse", "--verify", commit+"^{tree}") |
| + if e != nil || !objectID.MatchString(tree) { |
| + return zero, paseo.ErrIdentity |
| + } |
| + gitdir, e := m.gitdir(at) |
| + if e != nil { |
| + return zero, e |
| + } |
| + index, e := regular(filepath.Join(gitdir, "index")) |
| + if e != nil { |
| + return zero, e |
| + } |
| + if os.WriteFile(filepath.Join(staging, "index"), index, 0600) != nil { |
| + return zero, paseo.ErrContract |
| + } |
| + if _, e = m.run(ctx, staging, "diff-index", "--cached", "--quiet", "--no-ext-diff", "--no-textconv", commit, "--"); e != nil { |
| + return zero, paseo.ErrIdentity |
| + } |
| + if e = m.clean(ctx, staging, w.Paseo.Path, commit); e != nil { |
| + return zero, e |
| + } |
| + again, e := m.head(at) |
| + if e != nil || again != commit { |
| + return zero, paseo.ErrIdentity |
| + } |
| + c := GitCandidate{Repository: target.Repository, BaseCommit: target.BaseRevision, Commit: commit, Tree: tree} |
| + if _, e = m.run(ctx, staging, "update-ref", "refs/heads/candidate", commit); e != nil { |
| + return zero, e |
| + } |
| + if _, e = m.run(ctx, staging, "fsck", "--strict", "--no-reflogs"); e != nil { |
| + return zero, paseo.ErrIdentity |
| + } |
| + if _, e = m.run(ctx, staging, "-c", "core.fsync=all", "-c", "repack.writeBitmaps=false", "repack", "-adn"); e != nil { |
| + return zero, e |
| + } |
| + entries, e := os.ReadDir(filepath.Join(staging, "objects")) |
| + if e != nil { |
| + return zero, paseo.ErrContract |
| + } |
| + for _, entry := range entries { |
| + if len(entry.Name()) == 2 && strings.Trim(entry.Name(), "0123456789abcdef") == "" { |
| + if os.RemoveAll(filepath.Join(staging, "objects", entry.Name())) != nil { |
| + return zero, paseo.ErrContract |
| + } |
| + } |
| + } |
| + destination := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) |
| + if _, e = os.Stat(destination); e == nil { |
| + var saved GitCandidate |
| + if load(filepath.Join(destination, "candidate.json"), &saved) != nil || saved != c { |
| + return zero, paseo.ErrIdentity |
| + } |
| + return c, nil |
| + } |
| + if e = save(filepath.Join(staging, "candidate.json"), c); e != nil { |
| + return zero, e |
| + } |
| + if os.Rename(staging, destination) != nil { |
| + return zero, paseo.ErrContract |
| + } |
| + parent, e := os.Open(m.cfg.PrivateRoot) |
| + if e != nil { |
| + return zero, paseo.ErrUncertain |
| + } |
| + defer parent.Close() |
| + if parent.Sync() != nil { |
| + return zero, paseo.ErrUncertain |
| + } |
| + return c, nil |
| +} |
| +func (m *Manager) ExportCandidate(ctx context.Context, c GitCandidate, destination string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + source := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c)) |
| + var saved GitCandidate |
| + if load(filepath.Join(source, "candidate.json"), &saved) != nil || saved != c { |
| + return paseo.ErrIdentity |
| + } |
| + r, e := canonical(destination) |
| + if e != nil || r != destination || !allowed(destination, paseo.ReadPolicy{ConfigHash: "export", DeniedPaths: append(m.cfg.Protected.all(), m.cfg.PrivateRoot)}) { |
| + return paseo.ErrPolicy |
| + } |
| + if _, e = os.Lstat(destination); !os.IsNotExist(e) { |
| + return paseo.ErrIdentity |
| + } |
| + if e = os.Mkdir(destination, 0700); e != nil { |
| + return paseo.ErrContract |
| + } |
| + ok := false |
| + defer func() { |
| + if !ok { |
| + _ = os.RemoveAll(destination) |
| + } |
| + }() |
| + if e = m.init(ctx, destination, objectFormat(c.Commit), false); e != nil { |
| + return e |
| + } |
| + if e = copyObjects(filepath.Join(source, "objects"), filepath.Join(destination, ".git", "objects")); e != nil { |
| + return e |
| + } |
| + tree, e := m.run(ctx, destination, "rev-parse", c.Commit+"^{tree}") |
| + if e != nil || tree != c.Tree { |
| + return paseo.ErrIdentity |
| + } |
| + if _, e = m.run(ctx, destination, "checkout", "--detach", c.Commit); e != nil { |
| + return e |
| + } |
| + if e = m.clean(ctx, destination, destination, c.Commit); e != nil { |
| + return e |
| + } |
| + ok = true |
| + return nil |
| +} |
| + |
| +func (m *Manager) ValidateTurn(ctx context.Context, a runnerproto.Assignment, w Workspace) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + var at attempt |
| + if w.key == "" || w.key != a.WorkspaceKey || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || at.AssignmentHash != digest(a) { |
| + return paseo.ErrIdentity |
| + } |
| + policy, err := m.preflight(ctx, a) |
| + if err != nil { |
| + return err |
| + } |
| + if !reflect.DeepEqual(policy, at.Request.ReadPolicy) { |
| + return paseo.ErrPolicy |
| + } |
| + return m.validateWorkspace(at) |
| +} |
diff --git a/internal/runner/workspace/workspace_test.go b/internal/runner/workspace/workspace_test.go| new file mode 100644 |
| index 00000000..9ab5a49f |
| --- /dev/null |
| +++ b/internal/runner/workspace/workspace_test.go |
| @@ -0,0 +1,688 @@ |
| +package workspace |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +var ctx = context.Background() |
| + |
| +func git(t *testing.T, dir string, args ...string) string { |
| + t.Helper() |
| + c := exec.Command("/usr/bin/git", append([]string{"-c", "core.hooksPath=/dev/null"}, args...)...) |
| + c.Dir = dir |
| + c.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=fixture", "GIT_AUTHOR_EMAIL=fixture@example.test", "GIT_COMMITTER_NAME=fixture", "GIT_COMMITTER_EMAIL=fixture@example.test"} |
| + out, err := c.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("git %v: %v %s", args, err, out) |
| + } |
| + return strings.TrimSpace(string(out)) |
| +} |
| +func put(t *testing.T, p, s string) { |
| + t.Helper() |
| + if err := os.WriteFile(p, []byte(s), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +type forgeFake struct { |
| + remote Remote |
| + repositories []string |
| +} |
| + |
| +func (f *forgeFake) Resolve(_ context.Context, repository string) (Remote, error) { |
| + f.repositories = append(f.repositories, repository) |
| + return f.remote, nil |
| +} |
| + |
| +type clientFake struct { |
| + calls []paseo.WorkspaceRequest |
| + receipts map[string]paseo.Workspace |
| + fail bool |
| + preflightErr error |
| + caps paseo.Capabilities |
| + t *testing.T |
| +} |
| + |
| +func (f *clientFake) Preflight(_ context.Context, s paseo.Selection, p paseo.ReadPolicy) (paseo.Capabilities, error) { |
| + if f.preflightErr != nil { |
| + return f.caps, f.preflightErr |
| + } |
| + return f.caps, nil |
| +} |
| +func (f *clientFake) CreateWorkspace(_ context.Context, r paseo.WorkspaceRequest) (paseo.Workspace, error) { |
| + f.calls = append(f.calls, r) |
| + if w, ok := f.receipts[r.IdempotencyKey]; ok { |
| + return w, nil |
| + } |
| + path := r.Path + "-work" |
| + git(f.t, r.Path, "worktree", "add", "-b", r.Branch, path, r.BaseCommit) |
| + w := paseo.Workspace{ServerID: "server", ProjectID: r.ProjectID, WorkspaceID: r.IdempotencyKey, Path: path} |
| + f.receipts[r.IdempotencyKey] = w |
| + if f.fail { |
| + return paseo.Workspace{}, paseo.ErrUncertain |
| + } |
| + return w, nil |
| +} |
| + |
| +type fixture struct { |
| + m *Manager |
| + cfg Config |
| + f *clientFake |
| + forge *forgeFake |
| + target team.TargetBinding |
| + a runnerproto.Assignment |
| + brief runnerproto.RunnerBrief |
| + root, seed, remote string |
| +} |
| + |
| +func setup(t *testing.T) *fixture { |
| + return setupWithFormat(t, "sha1") |
| +} |
| +func setupWithFormat(t *testing.T, format string) *fixture { |
| + t.Helper() |
| + root := t.TempDir() |
| + seed := filepath.Join(root, "seed") |
| + remote := filepath.Join(root, "remote.git") |
| + if err := os.Mkdir(seed, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + git(t, seed, "init", "--object-format="+format, "-b", "main") |
| + put(t, filepath.Join(seed, "file"), "base\n") |
| + git(t, seed, "add", ".") |
| + git(t, seed, "commit", "-m", "base") |
| + base := git(t, seed, "rev-parse", "HEAD") |
| + git(t, root, "clone", "--bare", seed, remote) |
| + f := &clientFake{t: t, receipts: map[string]paseo.Workspace{}, caps: paseo.Capabilities{ServerID: "server", ReadIsolation: true, IsolationStatus: "confined", IsolationConfigHash: "policy"}} |
| + forge := &forgeFake{remote: Remote{URL: remote}} |
| + private := filepath.Join(root, "private") |
| + public := filepath.Join(root, "public") |
| + protected := filepath.Join(root, "protected") |
| + if err := os.Mkdir(protected, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := Config{PrivateRoot: private, WorkspaceRoot: public, GitPath: "/usr/bin/git", Forge: forge, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { |
| + return paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{private, protected}}, nil |
| + }, Definitions: func(_ context.Context, _ team.TargetBinding, _ string) (PreparedBug, error) { |
| + b := []byte(`{"command":"test"}`) |
| + sum := sha256.Sum256(b) |
| + return PreparedBug{CheckDefinition: b, CheckDefinitionHash: hex.EncodeToString(sum[:]), BaselineTestSetHash: strings.Repeat("a", 64)}, nil |
| + }} |
| + cfg.Protected = SecurityPaths{RunnerState: protected + "/state", RunnerConfig: protected + "/config", Journal: protected + "/journal", Bearer: protected + "/bearer", Cleanup: protected + "/cleanup", ForgeCredential: protected + "/forge", PaseoHome: protected + "/paseo", SSH: protected + "/ssh", ProviderHomes: []string{protected + "/provider"}} |
| + m, err := newManager(cfg, f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + target := team.TargetBinding{Kind: team.TargetRepository, Repository: "amadan.test/team/repo", DefaultRef: "main", Ref: "equipo/task", BaseRevision: base} |
| + sel := runnerproto.Selection{ConnectionID: "connection", Provider: "claude", Family: "anthropic", Model: "model", AccountID: "account", Revision: 1, Isolation: team.IsolationSnapshot{Status: "confined"}} |
| + a := runnerproto.Assignment{ID: "assignment", TaskID: "task", StepKey: "reproduce", WorkspaceKey: "attempt-1", Selection: sel} |
| + return &fixture{m, cfg, f, forge, target, a, runnerproto.RunnerBrief{Target: target, Selection: sel}, root, seed, remote} |
| +} |
| +func (f *fixture) create(t *testing.T) Workspace { |
| + t.Helper() |
| + w, err := f.m.Create(ctx, f.a, f.brief) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return w |
| +} |
| +func TestWorkspacePinsBase(t *testing.T) { |
| + f := setup(t) |
| + put(t, filepath.Join(f.seed, "file"), "moving default\n") |
| + git(t, f.seed, "commit", "-am", "move") |
| + git(t, f.seed, "push", f.remote, "main") |
| + p, err := f.m.Prepare(ctx, f.target) |
| + if err != nil || p.BaseCommit != f.target.BaseRevision || p.Repository != f.target.Repository { |
| + t.Fatalf("prepare: %+v %v", p, err) |
| + } |
| + w := f.create(t) |
| + if got := git(t, w.Paseo.Path, "rev-parse", "HEAD"); got != f.target.BaseRevision { |
| + t.Fatalf("base moved: %s", got) |
| + } |
| + r := f.f.calls[0] |
| + if r.Isolation != "worktree" || r.BaseCommit != f.target.BaseRevision || r.Branch != f.target.Ref || r.IdempotencyKey != f.a.WorkspaceKey { |
| + t.Fatalf("request lost exact fields: %+v", r) |
| + } |
| + f.a.WorkspaceKey = "attempt-2" |
| + f.a.StepKey = "implement" |
| + f.brief.ArtifactHashes = []string{strings.Repeat("b", 64)} |
| + next := f.create(t) |
| + if next.Paseo.Path == w.Paseo.Path || !reflect.DeepEqual(next.ArtifactHashes, f.brief.ArtifactHashes) || git(t, next.Paseo.Path, "rev-parse", "HEAD") != f.target.BaseRevision { |
| + t.Fatal("implementation did not get fresh base and frozen reproduction") |
| + } |
| + f.brief.ArtifactHashes = nil |
| + f.a.WorkspaceKey = "attempt-3" |
| + if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| + t.Fatal("implementation without frozen reproduction accepted") |
| + } |
| +} |
| +func TestWorkspaceHasNoCredentials(t *testing.T) { |
| + f := setup(t) |
| + sentinel := "credential-sentinel-do-not-leak" |
| + marker := filepath.Join(f.root, "executed") |
| + poison := filepath.Join(f.root, "poison") |
| + put(t, poison, "[include]\n path = /missing\n[core]\n hooksPath = "+f.root+"\n fsmonitor = touch "+marker+"\n[credential]\n helper = !touch "+marker+"\n[url \"ext::touch "+marker+"\"]\n insteadOf = "+f.remote+"\n") |
| + t.Setenv("GIT_CONFIG_GLOBAL", poison) |
| + t.Setenv("GIT_CONFIG_SYSTEM", poison) |
| + t.Setenv("GIT_CONFIG_COUNT", "1") |
| + t.Setenv("GIT_CONFIG_KEY_0", "core.fsmonitor") |
| + t.Setenv("GIT_CONFIG_VALUE_0", "touch "+marker) |
| + t.Setenv("EQUIPO_BEARER", sentinel) |
| + put(t, filepath.Join(f.remote, "hooks", "post-checkout"), "#!/bin/sh\ntouch "+marker+"\n") |
| + if err := os.Chmod(filepath.Join(f.remote, "hooks", "post-checkout"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := f.create(t) |
| + env := w.Environment() |
| + for k, v := range env { |
| + if strings.Contains(k+v, sentinel) || strings.Contains(k, "BEARER") { |
| + t.Fatal("credential leaked to agent") |
| + } |
| + } |
| + if env["GIT_CONFIG_NOSYSTEM"] != "1" || env["GIT_CONFIG_GLOBAL"] != "/dev/null" || env["GIT_CONFIG_COUNT"] == "" { |
| + t.Fatal("agent git environment not isolated") |
| + } |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "candidate\n") |
| + put(t, filepath.Join(w.Paseo.Path, ".gitattributes"), "file filter=poison\n") |
| + git(t, w.Paseo.Path, "add", ".") |
| + git(t, w.Paseo.Path, "commit", "-m", "candidate") |
| + // Includes, hooks, helpers, filters and fsmonitor in builder config must never be loaded by capture. |
| + source := f.f.calls[0].Path |
| + file, err := os.OpenFile(filepath.Join(source, ".git", "config"), os.O_APPEND|os.O_WRONLY, 0600) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = file.WriteString("\n[include]\n path = " + poison + "\n[filter \"poison\"]\n clean = touch " + marker + "\n required = true\n") |
| + file.Close() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err := f.m.CaptureCandidate(ctx, w, f.target) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dest := filepath.Join(f.root, "export") |
| + if err := f.m.ExportCandidate(ctx, c, dest); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, dir := range []string{f.cfg.WorkspaceRoot, dest} { |
| + err := filepath.WalkDir(dir, func(p string, d os.DirEntry, e error) error { |
| + if e != nil { |
| + return e |
| + } |
| + if !d.IsDir() && d.Type().IsRegular() { |
| + b, e := os.ReadFile(p) |
| + if e != nil { |
| + return e |
| + } |
| + if strings.Contains(string(b), sentinel) { |
| + t.Fatalf("credential leaked to %s", p) |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := os.Stat(marker); !os.IsNotExist(err) { |
| + t.Fatal("poison git configuration executed") |
| + } |
| + f.forge.remote = Remote{URL: "https://user:secret@invalid.test/repo", Bearer: sentinel} |
| + f.target.Repository = "invalid" |
| + if _, err := f.m.Prepare(ctx, f.target); err == nil || strings.Contains(err.Error(), sentinel) { |
| + t.Fatal("credential URL accepted or diagnostic leaked") |
| + } |
| +} |
| +func TestCandidateCaptureCleanAndImmutable(t *testing.T) { |
| + for _, kind := range []string{"tracked", "staged", "untracked", "ignored", "symlink", "relative symlink", "wrong repository", "wrong ref", "not descendant", "wrong gitdir", "objects symlink", "alternates", "skip worktree"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f := setup(t) |
| + w := f.create(t) |
| + target := f.target |
| + switch kind { |
| + case "tracked": |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "dirty") |
| + case "staged": |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "staged") |
| + git(t, w.Paseo.Path, "add", ".") |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "base\n") |
| + case "untracked": |
| + put(t, filepath.Join(w.Paseo.Path, "extra"), "dirty") |
| + case "ignored": |
| + put(t, filepath.Join(w.Paseo.Path, ".gitignore"), "ignored\n") |
| + git(t, w.Paseo.Path, "add", ".") |
| + git(t, w.Paseo.Path, "commit", "-m", "ignore") |
| + put(t, filepath.Join(w.Paseo.Path, "ignored"), "dirty") |
| + case "symlink": |
| + if err := os.Symlink(f.root, filepath.Join(w.Paseo.Path, "escape")); err != nil { |
| + t.Fatal(err) |
| + } |
| + git(t, w.Paseo.Path, "add", ".") |
| + git(t, w.Paseo.Path, "commit", "-m", "escape") |
| + case "relative symlink": |
| + rel, err := filepath.Rel(w.Paseo.Path, f.root) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(rel, filepath.Join(w.Paseo.Path, "escape")); err != nil { |
| + t.Fatal(err) |
| + } |
| + git(t, w.Paseo.Path, "add", ".") |
| + git(t, w.Paseo.Path, "commit", "-m", "escape") |
| + case "wrong repository": |
| + target.Repository = "other/repo" |
| + case "wrong ref": |
| + git(t, w.Paseo.Path, "checkout", "-b", "wrong") |
| + case "not descendant": |
| + git(t, w.Paseo.Path, "checkout", "--orphan", "other") |
| + git(t, w.Paseo.Path, "add", ".") |
| + git(t, w.Paseo.Path, "commit", "-m", "orphan") |
| + git(t, w.Paseo.Path, "branch", "-f", f.target.Ref, "HEAD") |
| + git(t, w.Paseo.Path, "checkout", f.target.Ref) |
| + case "wrong gitdir": |
| + foreign := filepath.Join(f.root, "foreign-work") |
| + git(t, f.seed, "worktree", "add", "-b", f.target.Ref, foreign, f.target.BaseRevision) |
| + b, err := os.ReadFile(filepath.Join(foreign, ".git")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + put(t, filepath.Join(w.Paseo.Path, ".git"), string(b)) |
| + case "objects symlink": |
| + oid := git(t, f.seed, "rev-parse", "HEAD:file") |
| + object := filepath.Join(f.f.calls[0].Path, ".git", "objects", oid[:2], oid[2:]) |
| + if err := os.Remove(object); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(filepath.Join(f.seed, ".git", "objects", oid[:2], oid[2:]), object); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "alternates": |
| + put(t, filepath.Join(f.f.calls[0].Path, ".git", "objects", "info", "alternates"), filepath.Join(f.seed, ".git", "objects")) |
| + case "skip worktree": |
| + git(t, w.Paseo.Path, "update-index", "--skip-worktree", "file") |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "hidden dirty") |
| + } |
| + if _, err := f.m.CaptureCandidate(ctx, w, target); err == nil { |
| + t.Fatalf("unsafe candidate accepted: %s", kind) |
| + } |
| + }) |
| + } |
| + f := setup(t) |
| + w := f.create(t) |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "fixed\n") |
| + git(t, w.Paseo.Path, "commit", "-am", "fix") |
| + unusedPath := filepath.Join(f.root, "unused") |
| + put(t, unusedPath, "unused-private-fixture") |
| + unused := git(t, w.Paseo.Path, "hash-object", "-w", unusedPath) |
| + c, err := f.m.CaptureCandidate(ctx, w, f.target) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.Commit != git(t, w.Paseo.Path, "rev-parse", "HEAD") || c.Tree != git(t, w.Paseo.Path, "rev-parse", "HEAD^{tree}") { |
| + t.Fatal("candidate identity mismatch") |
| + } |
| + if err := os.RemoveAll(f.cfg.WorkspaceRoot); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, name := range []string{"review", "checks"} { |
| + dest := filepath.Join(f.root, name) |
| + if err := f.m.ExportCandidate(ctx, c, dest); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command("/usr/bin/git", "-C", dest, "cat-file", "-e", unused) |
| + if cmd.Run() == nil { |
| + t.Fatal("unreachable builder object exported") |
| + } |
| + if got := git(t, dest, "rev-parse", "HEAD^{tree}"); got != c.Tree { |
| + t.Fatal("staged tree changed") |
| + } |
| + } |
| + bad := c |
| + bad.Tree = strings.Repeat("a", 40) |
| + if err := f.m.ExportCandidate(ctx, bad, filepath.Join(f.root, "bad")); err == nil { |
| + t.Fatal("forged candidate exported") |
| + } |
| +} |
| +func TestWorkspaceRetryIdentity(t *testing.T) { |
| + f := setup(t) |
| + f.f.fail = true |
| + if _, err := f.m.Create(ctx, f.a, f.brief); !errors.Is(err, paseo.ErrUncertain) { |
| + t.Fatalf("lost reply: %v", err) |
| + } |
| + // A restarted manager uses exactly the persisted source and request key. |
| + m, err := newManager(f.cfg, f.f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.m = m |
| + f.f.fail = false |
| + w := f.create(t) |
| + if len(f.f.receipts) != 1 || len(f.f.calls) != 2 || !reflect.DeepEqual(f.f.calls[0], f.f.calls[1]) { |
| + t.Fatal("retry duplicated workspace identity") |
| + } |
| + again := f.create(t) |
| + if again.Paseo != w.Paseo { |
| + t.Fatal("receipt changed on retry") |
| + } |
| + f.brief.Instructions = "changed" |
| + if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| + t.Fatal("same key changed payload accepted") |
| + } |
| +} |
| +func TestReadIsolationRequired(t *testing.T) { |
| + for _, kind := range []string{"denied subtree", "denied alias", "changed policy", "preflight denied", "unconfined Claude", "unconfined Codex without acknowledgement", "changed tuple"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f := setup(t) |
| + switch kind { |
| + case "denied subtree": |
| + f.cfg.WorkspaceRoot = filepath.Join(f.cfg.PrivateRoot, "agent") |
| + case "denied alias": |
| + alias := filepath.Join(f.root, "alias") |
| + if err := os.Symlink(f.cfg.PrivateRoot, alias); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.cfg.WorkspaceRoot = filepath.Join(alias, "agent") |
| + case "changed policy": |
| + f.create(t) |
| + f.cfg.Policy = func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { |
| + return paseo.ReadPolicy{ConfigHash: "changed", DeniedPaths: []string{f.cfg.PrivateRoot}}, nil |
| + } |
| + case "preflight denied": |
| + f.f.preflightErr = paseo.ErrIsolation |
| + case "unconfined Claude": |
| + f.f.caps.ReadIsolation = false |
| + f.f.caps.IsolationStatus = "unconfined" |
| + case "unconfined Codex without acknowledgement": |
| + f.a.Selection.Provider = "codex" |
| + f.brief.Selection = f.a.Selection |
| + f.f.caps.ReadIsolation = false |
| + f.f.caps.IsolationStatus = "unconfined" |
| + case "changed tuple": |
| + f.f.caps.IsolationConfigHash = "changed" |
| + } |
| + m, err := newManager(f.cfg, f.f) |
| + if err == nil { |
| + _, err = m.Create(ctx, f.a, f.brief) |
| + } |
| + if err == nil { |
| + t.Fatalf("read policy bypass: %s", kind) |
| + } |
| + }) |
| + } |
| + f := setup(t) |
| + f.a.Selection.Provider = "codex" |
| + f.a.Selection.Isolation = team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"ack"}, ObservedTuples: []team.IsolationTuple{{Provider: "codex", ProviderVersion: "0.165.0", PaseoVersion: "0.14.0", IsolationConfigHash: "policy"}}} |
| + f.brief.Selection = f.a.Selection |
| + f.f.caps.ReadIsolation = false |
| + f.f.caps.IsolationStatus = "unconfined" |
| + f.f.caps.ProviderVersion = "0.165.0" |
| + f.f.caps.PaseoVersion = "0.14.0" |
| + w := f.create(t) |
| + if w.Isolation.Status != "unconfined" || !w.Isolation.RunnerTainted { |
| + t.Fatal("unconfined label lost") |
| + } |
| + f.f.preflightErr = paseo.ErrIsolation |
| + if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| + t.Fatal("revoked acknowledgement accepted on retry") |
| + } |
| +} |
| + |
| +func (f *clientFake) RegisterProject(_ context.Context, r paseo.ProjectRequest) (paseo.Project, error) { |
| + return paseo.Project{ServerID: "server", ProjectID: digest(r.Path), Path: r.Path}, nil |
| +} |
| + |
| +func TestWorkspaceHasNoCredentialsScopedFetch(t *testing.T) { |
| + f := setup(t) |
| + t.Setenv("EQUIPO_BEARER", "runner-only-sentinel") |
| + spy := filepath.Join(f.root, "git-spy") |
| + log := filepath.Join(f.root, "fetch-observations") |
| + script := fmt.Sprintf(`#!/usr/bin/python3 |
| +import os, sys, json |
| +args = sys.argv[1:] |
| +with open(%q, 'a') as out: |
| + out.write(json.dumps({'args':args, 'env':dict(os.environ)}) + '\n') |
| +if 'https://forge.invalid/repo' in args: |
| + args[args.index('https://forge.invalid/repo')] = %q |
| + args = ['-c', 'protocol.file.allow=always'] + args |
| +os.execve('/usr/bin/git', ['/usr/bin/git'] + args, dict(os.environ)) |
| +`, log, f.remote) |
| + put(t, spy, script) |
| + if err := os.Chmod(spy, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.cfg.GitPath = spy |
| + f.forge.remote = Remote{URL: "https://forge.invalid/repo", Bearer: "fetch-only-sentinel"} |
| + var err error |
| + f.m, err = newManager(f.cfg, f.f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := f.create(t) |
| + observations, err := os.ReadFile(log) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fetches := 0 |
| + for _, line := range strings.Split(strings.TrimSpace(string(observations)), "\n") { |
| + var row struct { |
| + Args []string |
| + Env map[string]string |
| + } |
| + if json.Unmarshal([]byte(line), &row) != nil { |
| + t.Fatal("bad spy record") |
| + } |
| + args := strings.Join(row.Args, " ") |
| + if strings.Contains(args, "fetch-only-sentinel") { |
| + t.Fatal("fetch credential in argv") |
| + } |
| + if row.Env["EQUIPO_BEARER"] != "" { |
| + t.Fatal("runner bearer inherited by git subprocess") |
| + } |
| + env, _ := json.Marshal(row.Env) |
| + if strings.Contains(args, " fetch ") { |
| + fetches++ |
| + if row.Env["GIT_CONFIG_VALUE_7"] != "Authorization: Bearer fetch-only-sentinel" { |
| + t.Fatal("fetch missing scoped credential") |
| + } |
| + } else if strings.Contains(string(env), "fetch-only-sentinel") { |
| + t.Fatal("credential inherited by non-fetch subprocess") |
| + } |
| + } |
| + if fetches != 1 { |
| + t.Fatalf("fetch count %d", fetches) |
| + } |
| + err = filepath.WalkDir(f.cfg.WorkspaceRoot, func(p string, d os.DirEntry, e error) error { |
| + if e != nil { |
| + return e |
| + } |
| + if d.Type().IsRegular() { |
| + b, e := os.ReadFile(p) |
| + if e != nil { |
| + return e |
| + } |
| + if strings.Contains(string(b), "fetch-only-sentinel") { |
| + t.Fatal("fetch credential in source or worktree") |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(fmt.Sprint(w.Environment()), "fetch-only-sentinel") { |
| + t.Fatal("fetch credential in agent environment") |
| + } |
| +} |
| + |
| +func TestReadIsolationRequiredEveryTurn(t *testing.T) { |
| + f := setup(t) |
| + w := f.create(t) |
| + if err := f.m.ValidateTurn(ctx, f.a, w); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.f.preflightErr = paseo.ErrIsolation |
| + if err := f.m.ValidateTurn(ctx, f.a, w); err == nil { |
| + t.Fatal("turn ignored current acknowledgement authority") |
| + } |
| + f.f.preflightErr = nil |
| + originalPolicy := f.cfg.Policy |
| + f.cfg.Policy = func(c context.Context, s paseo.Selection) (paseo.ReadPolicy, error) { |
| + p, e := originalPolicy(c, s) |
| + p.DeniedPaths = append(p.DeniedPaths, filepath.Join(f.root, "extra-denied")) |
| + return p, e |
| + } |
| + changed, err := newManager(f.cfg, f.f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := changed.ValidateTurn(ctx, f.a, w); err == nil { |
| + t.Fatal("turn accepted changed paths with unchanged hash") |
| + } |
| + f.cfg.Policy = func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { |
| + return paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{f.cfg.PrivateRoot}}, nil |
| + } |
| + m, err := newManager(f.cfg, f.f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := m.ValidateTurn(ctx, f.a, w); err == nil { |
| + t.Fatal("turn accepted removed protected paths") |
| + } |
| +} |
| +func TestReadIsolationRequiredProtectedPaths(t *testing.T) { |
| + f := setup(t) |
| + f.cfg.Protected = SecurityPaths{} |
| + if _, err := newManager(f.cfg, f.f); err == nil { |
| + t.Fatal("missing protected paths accepted") |
| + } |
| +} |
| + |
| +func TestReadIsolationRequiredExactAcknowledgement(t *testing.T) { |
| + for _, kind := range []string{"missing ack", "wrong tuple", "wrong provider", "provider version", "daemon version", "taint", "status"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f := setup(t) |
| + f.a.Selection.Provider = "codex" |
| + f.a.Selection.Isolation = team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"ack"}, ObservedTuples: []team.IsolationTuple{{Provider: "codex", ProviderVersion: "0.165.0", PaseoVersion: "0.14.0", IsolationConfigHash: "policy"}}} |
| + f.f.caps.ReadIsolation = false |
| + f.f.caps.IsolationStatus = "unconfined" |
| + f.f.caps.ProviderVersion = "0.165.0" |
| + f.f.caps.PaseoVersion = "0.14.0" |
| + switch kind { |
| + case "missing ack": |
| + f.a.Selection.Isolation.AcknowledgementIDs = nil |
| + case "wrong tuple": |
| + f.a.Selection.Isolation.ObservedTuples[0].IsolationConfigHash = "other" |
| + case "wrong provider": |
| + f.a.Selection.Provider = "claude" |
| + f.a.Selection.Isolation.ObservedTuples[0].Provider = "claude" |
| + case "provider version": |
| + f.f.caps.ProviderVersion = "new" |
| + f.a.Selection.Isolation.ObservedTuples[0].ProviderVersion = "new" |
| + case "daemon version": |
| + f.f.caps.PaseoVersion = "new" |
| + f.a.Selection.Isolation.ObservedTuples[0].PaseoVersion = "new" |
| + case "taint": |
| + f.a.Selection.Isolation.RunnerTainted = false |
| + case "status": |
| + f.a.Selection.Isolation.Status = "confined" |
| + } |
| + f.brief.Selection = f.a.Selection |
| + if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| + t.Fatalf("invalid acknowledgement accepted: %s", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestWorkspacePinsBaseRejectsInvalidTarget(t *testing.T) { |
| + for _, kind := range []string{"default", "bad hash", "ref option", "missing base", "wrong selection"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f := setup(t) |
| + switch kind { |
| + case "default": |
| + f.brief.Target.Ref = f.target.DefaultRef |
| + case "bad hash": |
| + f.brief.Target.BaseRevision = "HEAD" |
| + case "ref option": |
| + f.brief.Target.Ref = "--upload-pack=bad" |
| + case "missing base": |
| + f.brief.Target.BaseRevision = strings.Repeat("f", 40) |
| + case "wrong selection": |
| + f.brief.Selection.ConnectionID = "other" |
| + } |
| + if _, err := f.m.Create(ctx, f.a, f.brief); err == nil { |
| + t.Fatalf("invalid target accepted: %s", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestWorkspacePinsBasePrepareDefault(t *testing.T) { |
| + f := setup(t) |
| + f.target.BaseRevision = "" |
| + p, err := f.m.Prepare(ctx, f.target) |
| + if err != nil || p.BaseCommit != f.brief.Target.BaseRevision { |
| + t.Fatalf("default prepare: %+v %v", p, err) |
| + } |
| +} |
| + |
| +func TestReadIsolationRequiredMissingDeniedPaths(t *testing.T) { |
| + f := setup(t) |
| + f.cfg.Policy = func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { |
| + return paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{f.cfg.PrivateRoot}}, nil |
| + } |
| + m, err := newManager(f.cfg, f.f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := m.Create(ctx, f.a, f.brief); err == nil { |
| + t.Fatal("omitted protected paths accepted") |
| + } |
| +} |
| + |
| +func TestWorkspaceRetryIdentityPartialPreparation(t *testing.T) { |
| + f := setup(t) |
| + dir := filepath.Join(f.cfg.PrivateRoot, "attempt-"+digest(f.a.WorkspaceKey)) |
| + if err := os.Mkdir(dir, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.m.Create(ctx, f.a, f.brief); !errors.Is(err, paseo.ErrUncertain) { |
| + t.Fatalf("partial preparation did not stay uncertain: %v", err) |
| + } |
| + if len(f.f.calls) != 0 { |
| + t.Fatal("partial preparation created a second workspace") |
| + } |
| +} |
| + |
| +var _ equipo.BugPreparer = (*Manager)(nil) |
| + |
| +func TestCandidateCaptureSHA256(t *testing.T) { |
| + f := setupWithFormat(t, "sha256") |
| + w := f.create(t) |
| + put(t, filepath.Join(w.Paseo.Path, "file"), "fixed sha256\n") |
| + git(t, w.Paseo.Path, "commit", "-am", "fix") |
| + c, err := f.m.CaptureCandidate(ctx, w, f.target) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(c.Commit) != 64 || len(c.Tree) != 64 || len(c.BaseCommit) != 64 { |
| + t.Fatal("sha256 object identity lost") |
| + } |
| + if err := f.m.ExportCandidate(ctx, c, filepath.Join(f.root, "sha256-review")); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go| index 56bd3388..16cf5a4e 100644 |
| --- a/internal/runnerproto/types.go |
| +++ b/internal/runnerproto/types.go |
| @@ -168,3 +168,9 @@ type CredentialRotation struct { |
| } |
| type Scope = team.Scope |
| + |
| +type PreparedBug struct { |
| + Repository, DefaultBranch, BaseCommit string |
| + CheckDefinition []byte |
| + CheckDefinitionHash, BaselineTestSetHash string |
| +} |
diff --git a/runner/paseo/bridge.mjs b/runner/paseo/bridge.mjs| index 9c5dd12c..20e6bc53 100644 |
| --- a/runner/paseo/bridge.mjs |
| +++ b/runner/paseo/bridge.mjs |
| @@ -140,8 +140,20 @@ export class Bridge { |
| const features = this.client.getLastServerInfoMessage()?.features; |
| if (!features?.creationLifecycle || !features.agentRequestReceipts || !features.workspaceRequestReceipts) fail('creation_receipts_required'); |
| } |
| + async registerProject(r) { |
| + keys(r, ['path', 'idempotency_key', 'selection', 'read_policy']); |
| + allowedPath(r.path, r.read_policy); |
| + const status = await this.status(); |
| + if (status.version !== VERSION) fail('unsupported_daemon_version'); |
| + if (!text(r.idempotency_key)) fail('invalid_request'); |
| + const result = await this.client.addProject(r.path, r.idempotency_key); |
| + if (result.error || !result.project) fail('uncertain'); |
| + if (!text(result.project.projectId) || result.project.projectRootPath !== r.path) fail('identity_mismatch'); |
| + return { server_id: status.serverId, project_id: result.project.projectId, path: result.project.projectRootPath }; |
| + } |
| async createWorkspace(r) { |
| - keys(r, ['project_id', 'path', 'base_commit', 'branch', 'idempotency_key', 'selection', 'read_policy']); |
| + keys(r, ['project_id', 'path', 'base_commit', 'branch', 'idempotency_key', 'selection', 'read_policy', 'isolation']); |
| + if (r.isolation !== 'worktree') fail('invalid_request'); |
| allowedPath(r.path, r.read_policy); |
| const status = await this.status(); |
| if (status.version !== VERSION) fail('unsupported_daemon_version'); |
| @@ -311,7 +323,7 @@ export async function run(input, output, diagnostic) { |
| bridge = new Bridge(await connectLocal(q.params, await loadSDK()), write); result = {}; |
| } else { |
| if (!bridge) fail('invalid_request'); |
| - const methods = { preflight: 'preflight', create_workspace: 'createWorkspace', create_agent: 'createAgent', subscribe: 'subscribe', unsubscribe: 'unsubscribe', send: 'send', respond: 'respond', stop: 'stop', archive: 'archive', archive_workspace: 'archiveWorkspace' }; |
| + const methods = { preflight: 'preflight', register_project: 'registerProject', create_workspace: 'createWorkspace', create_agent: 'createAgent', subscribe: 'subscribe', unsubscribe: 'unsubscribe', send: 'send', respond: 'respond', stop: 'stop', archive: 'archive', archive_workspace: 'archiveWorkspace' }; |
| if (!Object.hasOwn(methods, q.op)) fail('invalid_request'); |
| result = await bridge[methods[q.op]](q.params); |
| } |
diff --git a/runner/paseo/bridge.test.mjs b/runner/paseo/bridge.test.mjs| index 9dcd235e..63967c18 100644 |
| --- a/runner/paseo/bridge.test.mjs |
| +++ b/runner/paseo/bridge.test.mjs |
| @@ -82,7 +82,7 @@ test('MCP at creation', async () => { |
| test('workspace identity', async () => { |
| const f = fake(); |
| - const result = await f.bridge.createWorkspace({ project_id: workspace.project_id, path: '/repo', base_commit: 'a'.repeat(40), branch: 'review/fixture', idempotency_key: 'workspace-intent', read_policy: policy }); |
| + const result = await f.bridge.createWorkspace({ isolation: 'worktree', project_id: workspace.project_id, path: '/repo', base_commit: 'a'.repeat(40), branch: 'review/fixture', idempotency_key: 'workspace-intent', read_policy: policy }); |
| assert.deepEqual(result, workspace); |
| assert.equal(f.calls[0][1].source.refName, 'a'.repeat(40)); |
| assert.equal(f.calls[0][1].idempotencyKey, 'workspace-intent'); |
| @@ -202,7 +202,7 @@ test('creation requires durable daemon receipts', async () => { |
| const f = fake(); |
| f.daemon.getLastServerInfoMessage = () => ({ features: {} }); |
| await assert.rejects(f.bridge.createAgent(request()), /creation_receipts_required/); |
| - await assert.rejects(f.bridge.createWorkspace({ project_id: workspace.project_id, path: '/repo', base_commit: 'a'.repeat(40), branch: 'review/fixture', idempotency_key: 'intent', read_policy: policy }), /creation_receipts_required/); |
| + await assert.rejects(f.bridge.createWorkspace({ isolation: 'worktree', project_id: workspace.project_id, path: '/repo', base_commit: 'a'.repeat(40), branch: 'review/fixture', idempotency_key: 'intent', read_policy: policy }), /creation_receipts_required/); |
| assert.equal(f.calls.length, 0); |
| }); |
| @@ -296,3 +296,16 @@ test('locked dependency versions', async () => { |
| assert.ok(item.resolved.startsWith('https://registry.npmjs.org/')); |
| } |
| }); |
| + |
| +test('workspace isolation mode', async () => { |
| + const f = fake(); |
| + await assert.rejects(f.bridge.createWorkspace({ isolation: 'none', project_id: workspace.project_id, path: '/repo', base_commit: 'a'.repeat(40), branch: 'review/fixture', idempotency_key: 'intent', read_policy: policy }), /invalid_request/); |
| +}); |
| +test('project registration', async () => { |
| + const f = fake(); |
| + f.daemon.addProject = async (cwd, key) => { assert.equal(cwd, '/repo'); assert.equal(key, 'project-intent'); return { project: { projectId: 'project-fixture', projectRootPath: cwd }, error: null }; }; |
| + const r = { path: '/repo', idempotency_key: 'project-intent', read_policy: policy, selection }; |
| + assert.deepEqual(await f.bridge.registerProject(r), { server_id: 'server-fixture', project_id: 'project-fixture', path: '/repo' }); |
| + f.daemon.addProject = async () => ({ project: { projectId: 'other', projectRootPath: '/wrong' }, error: null }); |
| + await assert.rejects(f.bridge.registerProject(r), /identity_mismatch/); |
| +}); |