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:
sam committed 2026-08-22 22:06:54 +10:00
1 parent 7df2ae3626
commit dbb6550ab3
19 files changed
+494 -175

No files matched your search

+79 -79
View File
@@ -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
}