fix(worktree): bind publication to dispatch grants
Worktree RPC used to accept repository coordinates from the sandbox. It now accepts only an opaque per-dispatch grant, and the daemon derives the repository path and branch from grant-owned state. Repository worktree paths also move from an ambiguous flattened key to encoded owner/repo components. Origin-matched legacy clones migrate safely; mismatched legacy paths are preserved.
This commit is contained in:
1 parent
7df2ae3626
commit
dbb6550ab3
19 files changed
+494
-175
No files matched your search
@@ -1,10 +1,8 @@
|
||||
// Package worktreerpc lets archie-agent request the two worktree
|
||||
// operations that touch the network -- clone/fetch (Prepare) and push
|
||||
// (Push) -- over core NATS request/reply, instead of holding the forge
|
||||
// credential itself. archied remains the sole holder of
|
||||
// worktree.Manager.Token and performs both against the host worktree
|
||||
// directory (the same files the agent container has bind-mounted at
|
||||
// /data/worktree).
|
||||
// Package worktreerpc lets archie-agent request publication of the task branch
|
||||
// over core NATS request/reply without holding the forge credential itself.
|
||||
// archied has already prepared the bind-mounted worktree before the container
|
||||
// starts. Publication is authorized by an opaque per-dispatch grant; sandbox
|
||||
// input never selects a host path, repository, or branch.
|
||||
//
|
||||
// CommitAll/Diff/ChangedFiles/ChangedLines are purely local git
|
||||
// operations against the already-mounted worktree and don't need the
|
||||
@@ -13,20 +11,24 @@ package worktreerpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
const (
|
||||
SubjectPush = "archie.worktree.push"
|
||||
SubjectPrepare = "archie.worktree.prepare"
|
||||
SubjectPush = "archie.worktree.push"
|
||||
)
|
||||
|
||||
// SubjectFor returns the subject for base, scoped to identity when set.
|
||||
@@ -42,48 +44,75 @@ func SubjectFor(identity, base string) string {
|
||||
return "archie.worktree." + identity + "." + strings.TrimPrefix(base, "archie.worktree.")
|
||||
}
|
||||
|
||||
// PushRequest identifies the task's worktree by owner/repo/issue rather
|
||||
// than trusting a path from the (sandboxed) agent -- the server resolves
|
||||
// the directory itself via worktree.Manager.Dir.
|
||||
type PushRequest struct {
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Issue int `json:"issue"`
|
||||
Branch string `json:"branch"`
|
||||
Grant string `json:"grant"`
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
// PrepareRequest mirrors worktree.Manager.Prepare's arguments.
|
||||
type PrepareRequest struct {
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Base string `json:"base"`
|
||||
Issue int `json:"issue"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Labels string `json:"labels"`
|
||||
type grant struct {
|
||||
identity string
|
||||
owner, repo string
|
||||
issue int
|
||||
branch string
|
||||
}
|
||||
|
||||
type PrepareResponse struct {
|
||||
Dir string `json:"dir"`
|
||||
Branch string `json:"branch"`
|
||||
natsrpc.Envelope
|
||||
// Grants owns short-lived publication capabilities issued for one dispatched
|
||||
// task. A grant is useful only on the identity-scoped server that issued it.
|
||||
type Grants struct {
|
||||
mu sync.RWMutex
|
||||
grants map[string]grant
|
||||
}
|
||||
|
||||
// defaultHandlerTimeout bounds a single prepare or push when the Server
|
||||
// has no explicit Timeout. A clone of a large repository over a slow link
|
||||
// is the long pole, so this is generous rather than tight.
|
||||
func NewGrants() *Grants { return &Grants{grants: make(map[string]grant)} }
|
||||
|
||||
// Issue creates a per-dispatch grant and a revocation function.
|
||||
func (g *Grants) Issue(task *store.Task) (string, func(), error) {
|
||||
if task == nil || task.ID <= 0 || task.Branch == "" ||
|
||||
!worktree.ValidCoordinates(task.Owner, task.Repo, task.IssueNumber) {
|
||||
return "", nil, errors.New("task is not ready for worktree publication")
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", nil, fmt.Errorf("generate worktree grant: %w", err)
|
||||
}
|
||||
token := fmt.Sprintf("%x", raw)
|
||||
g.mu.Lock()
|
||||
g.grants[token] = grant{identity: task.Identity, owner: task.Owner, repo: task.Repo, issue: task.IssueNumber, branch: task.Branch}
|
||||
g.mu.Unlock()
|
||||
return token, func() {
|
||||
g.mu.Lock()
|
||||
delete(g.grants, token)
|
||||
g.mu.Unlock()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *Grants) resolve(token, identity string) (grant, error) {
|
||||
if g == nil || token == "" {
|
||||
return grant{}, errors.New("worktree publication grant is required")
|
||||
}
|
||||
g.mu.RLock()
|
||||
item, ok := g.grants[token]
|
||||
g.mu.RUnlock()
|
||||
if !ok || item.identity != identity {
|
||||
return grant{}, errors.New("worktree publication grant is invalid")
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// defaultHandlerTimeout bounds one publication request when the Server has no
|
||||
// explicit Timeout. A large repository push can be slow, so this is generous.
|
||||
const defaultHandlerTimeout = 15 * time.Minute
|
||||
|
||||
// Server proxies push requests to a real worktree.Manager holding the
|
||||
// forge push token.
|
||||
type Server struct {
|
||||
Trees *worktree.Manager
|
||||
Log *slog.Logger
|
||||
// Timeout bounds a single prepare or push. Zero uses
|
||||
Trees *worktree.Manager
|
||||
Grants *Grants
|
||||
Log *slog.Logger
|
||||
// Timeout bounds a single publication. Zero uses
|
||||
// defaultHandlerTimeout.
|
||||
Timeout time.Duration
|
||||
}
|
||||
@@ -102,23 +131,20 @@ func (s *Server) handlerContext() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), timeout)
|
||||
}
|
||||
|
||||
// Register subscribes the push and prepare handlers on nc under the root
|
||||
// (identity-less) subjects. RegisterFor(nc, identity) registers them under
|
||||
// that identity's scoped subjects; the daemon calls it once per identity.
|
||||
// Register subscribes the publication handler under the root identity.
|
||||
// RegisterFor subscribes it under one identity-scoped subject.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
return s.RegisterFor(nc, "")
|
||||
}
|
||||
|
||||
// RegisterFor registers the push and prepare handlers under the subjects
|
||||
// scoped to identity.
|
||||
// RegisterFor registers publication under the subject scoped to identity.
|
||||
func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) {
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectFor(identity, SubjectPush), Handler: s.handlePush},
|
||||
{Subject: SubjectFor(identity, SubjectPrepare), Handler: s.handlePrepare},
|
||||
{Subject: SubjectFor(identity, SubjectPush), Handler: func(msg *nats.Msg) { s.handlePush(identity, msg) }},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePush(msg *nats.Msg) {
|
||||
func (s *Server) handlePush(identity string, msg *nats.Msg) {
|
||||
var req PushRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, err)
|
||||
@@ -126,25 +152,13 @@ func (s *Server) handlePush(msg *nats.Msg) {
|
||||
}
|
||||
ctx, cancel := s.handlerContext()
|
||||
defer cancel()
|
||||
dir := s.Trees.Dir(req.Owner, req.Repo, req.Issue)
|
||||
s.respond(msg, s.Trees.Push(ctx, dir, req.Branch))
|
||||
}
|
||||
|
||||
func (s *Server) handlePrepare(msg *nats.Msg) {
|
||||
var req PrepareRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respondPrepare(msg, "", "", err)
|
||||
item, err := s.Grants.resolve(req.Grant, identity)
|
||||
if err != nil {
|
||||
s.respond(msg, err)
|
||||
return
|
||||
}
|
||||
ctx, cancel := s.handlerContext()
|
||||
defer cancel()
|
||||
dir, branch, err := s.Trees.Prepare(ctx, req.Owner, req.Repo, req.Base, req.Issue, req.Title, req.Body, req.Labels)
|
||||
s.respondPrepare(msg, dir, branch, err)
|
||||
}
|
||||
|
||||
func (s *Server) respondPrepare(msg *nats.Msg, dir, branch string, err error) {
|
||||
resp := PrepareResponse{Dir: dir, Branch: branch, Envelope: natsrpc.NewEnvelope(err)}
|
||||
natsrpc.Respond(msg, s.Log, "worktreerpc", resp)
|
||||
dir := s.Trees.Dir(item.owner, item.repo, item.issue)
|
||||
s.respond(msg, s.Trees.Push(ctx, dir, item.branch))
|
||||
}
|
||||
|
||||
func (s *Server) respond(msg *nats.Msg, err error) {
|
||||
@@ -159,34 +173,20 @@ type Client struct {
|
||||
// Identity scopes this client's calls to one identity's RPC server.
|
||||
// Empty uses the root subjects (single-identity deployments).
|
||||
Identity string
|
||||
Grant string
|
||||
}
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
func (c *Client) subject(base string) string { return SubjectFor(c.Identity, base) }
|
||||
|
||||
// Push requests that archied push branch for owner/repo/issue's worktree
|
||||
// using its held forge credential.
|
||||
func (c *Client) Push(ctx context.Context, owner, repo string, issue int, branch string) error {
|
||||
req := PushRequest{Owner: owner, Repo: repo, Issue: issue, Branch: branch}
|
||||
// Push asks archied to publish the branch bound to this client's dispatch
|
||||
// grant using the daemon-held forge credential.
|
||||
func (c *Client) Push(ctx context.Context) error {
|
||||
req := PushRequest{Grant: c.Grant}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectPush), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// Prepare requests that archied clone/fetch the worktree for
|
||||
// owner/repo/issue using its held forge credential, matching
|
||||
// worktree.Manager.Prepare's signature.
|
||||
func (c *Client) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) {
|
||||
req := PrepareRequest{Owner: owner, Repo: repo, Base: base, Issue: issue, Title: title, Body: body, Labels: labels}
|
||||
resp, err := natsrpc.Call[PrepareResponse](ctx, c.rpc(), c.subject(SubjectPrepare), req)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if err := resp.Err(); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return resp.Dir, resp.Branch, nil
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
@@ -109,10 +110,29 @@ func remoteHasBranch(t *testing.T, host, owner, repo, branch string) bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func TestClientPreparePublishesViaServer(t *testing.T) {
|
||||
func TestManagerPrepareCannotDeleteOutsideWorkDir(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
root := t.TempDir()
|
||||
workDir := filepath.Join(root, "worktrees")
|
||||
outside := filepath.Join(root, "escape-widget", "issue-7")
|
||||
if err := os.MkdirAll(outside, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marker := filepath.Join(outside, "keep")
|
||||
if err := os.WriteFile(marker, []byte("operator data"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
m := &worktree.Manager{WorkDir: workDir, BaseURL: t.TempDir()}
|
||||
_, _, _ = m.Prepare(ctx, "../escape", "widget", "main", 7, "feat: test", "", "")
|
||||
if _, err := os.Stat(marker); err != nil {
|
||||
t.Fatalf("Prepare removed a path outside WorkDir: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientPushRejectsTaskMismatchedCoordinates(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
host := newLocalRemote(t, "other", "widget")
|
||||
m := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused-for-file-remotes",
|
||||
@@ -120,27 +140,32 @@ func TestClientPreparePublishesViaServer(t *testing.T) {
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: host,
|
||||
}
|
||||
dir, branch, err := m.Prepare(ctx, "other", "widget", "main", 9, "feat: other", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "unexpected.txt"), []byte("unexpected\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if changed, err := m.CommitAll(ctx, dir, "unexpected"); err != nil || !changed {
|
||||
t.Fatalf("CommitAll = (%v, %v)", changed, err)
|
||||
}
|
||||
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
rpcServer := &Server{Trees: m, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(connect(t, url))
|
||||
grants := NewGrants()
|
||||
rpcServer := &Server{Trees: m, Grants: grants, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(connect(t, srv.ClientURL()))
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(unsub)
|
||||
|
||||
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second}
|
||||
dir, branch, err := client.Prepare(ctx, "acme", "widget", "main", 1, "feat: test", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Prepare: %v", err)
|
||||
client := &Client{Conn: connect(t, srv.ClientURL()), Timeout: 5 * time.Second}
|
||||
if err := client.Push(ctx); err == nil {
|
||||
t.Fatal("Push accepted coordinates that were not correlated to an authoritative task")
|
||||
}
|
||||
if dir == "" || branch != "feat/1-test" {
|
||||
t.Fatalf("Prepare = (%q, %q)", dir, branch)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".git")); err != nil {
|
||||
t.Fatalf("expected worktree cloned at %q: %v", dir, err)
|
||||
if remoteHasBranch(t, host, "other", "widget", branch) {
|
||||
t.Fatalf("task-mismatched branch %q was published", branch)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,15 +195,21 @@ func TestClientPushPublishesViaServer(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
rpcServer := &Server{Trees: m, Log: slog.New(slog.DiscardHandler)}
|
||||
grants := NewGrants()
|
||||
token, revoke, err := grants.Issue(&store.Task{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 1, Branch: branch})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(revoke)
|
||||
rpcServer := &Server{Trees: m, Grants: grants, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(connect(t, url))
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
t.Cleanup(unsub)
|
||||
|
||||
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second}
|
||||
if err := client.Push(ctx, "acme", "widget", 1, branch); err != nil {
|
||||
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second, Grant: token}
|
||||
if err := client.Push(ctx); err != nil {
|
||||
t.Fatalf("Push: %v", err)
|
||||
}
|
||||
|
||||
@@ -192,7 +223,7 @@ func TestClientPropagatesServerError(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
rpcServer := &Server{Trees: m, Log: slog.New(slog.DiscardHandler)}
|
||||
rpcServer := &Server{Trees: m, Grants: NewGrants(), Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(connect(t, url))
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
@@ -201,7 +232,7 @@ func TestClientPropagatesServerError(t *testing.T) {
|
||||
|
||||
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second}
|
||||
// No worktree ever prepared at this dir -- push must fail.
|
||||
err = client.Push(context.Background(), "acme", "nonexistent", 999, "some-branch")
|
||||
err = client.Push(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected Push to propagate the server-side git error")
|
||||
}
|
||||
@@ -211,7 +242,7 @@ func TestClientPushTimesOutWithNoResponder(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
client := &Client{Conn: connect(t, srv.ClientURL()), Timeout: 100 * time.Millisecond}
|
||||
|
||||
err := client.Push(context.Background(), "acme", "widget", 1, "branch")
|
||||
err := client.Push(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected Push to time out with no server registered")
|
||||
}
|
||||
@@ -226,8 +257,39 @@ func TestSubjectFor(t *testing.T) {
|
||||
if got := SubjectFor("winter", SubjectPush); got != "archie.worktree.winter.push" {
|
||||
t.Fatalf("SubjectFor(\"winter\", %q) = %q", SubjectPush, got)
|
||||
}
|
||||
if got := SubjectFor("winter", SubjectPrepare); got != "archie.worktree.winter.prepare" {
|
||||
t.Fatalf("SubjectFor(\"winter\", %q) = %q", SubjectPrepare, got)
|
||||
}
|
||||
|
||||
func TestGrantIsScopedAndRevocable(t *testing.T) {
|
||||
grants := NewGrants()
|
||||
token, revoke, err := grants.Issue(&store.Task{
|
||||
ID: 1, Identity: "winter", Owner: "acme", Repo: "widget",
|
||||
IssueNumber: 7, Branch: "feat/7-widget",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := grants.resolve(token, ""); err == nil {
|
||||
t.Fatal("root identity accepted another identity's grant")
|
||||
}
|
||||
if _, err := grants.resolve(token, "winter"); err != nil {
|
||||
t.Fatalf("owning identity rejected grant: %v", err)
|
||||
}
|
||||
revoke()
|
||||
if _, err := grants.resolve(token, "winter"); err == nil {
|
||||
t.Fatal("revoked grant remained usable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrantRejectsIncompleteTask(t *testing.T) {
|
||||
grants := NewGrants()
|
||||
for _, task := range []*store.Task{
|
||||
nil,
|
||||
{ID: 1, Owner: "../escape", Repo: "widget", IssueNumber: 7, Branch: "feat/7-widget"},
|
||||
{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 7},
|
||||
} {
|
||||
if _, _, err := grants.Issue(task); err == nil {
|
||||
t.Fatalf("Issue(%+v) error = nil", task)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user