fix(worktree): sign and attribute agent commits at push; forge git credentials (#1816, #1817)
deploy / plan (push) Failing after 7s
deploy / gate (push) Skipped
deploy / archied-image (push) Skipped
deploy / agent-image (push) Skipped
deploy / dist-zip (push) Skipped

This commit is contained in:
sam committed 2026-11-09 00:11:54 +11:00
1 parent 21a523bd35
commit fa76f4c994
9 files changed
+633 -114

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
package worktree
import (
"context"
"errors"
"fmt"
"io"
"slices"
"time"
"github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/go-git/go-git/v6/plumbing/storer"
)
// attest re-authors and signs the branch's unpublished commits as the bot
// before a push. Commits are made inside the task container, which holds
// neither the connection's identity nor its signing key, so the daemon applies
// both here. Only the first-parent chain back to the nearest published commit
// is rewritten; trees, messages and author times are kept.
func (m *Manager) attest(ctx context.Context, r *git.Repository, ref plumbing.ReferenceName) error {
tip, err := r.Reference(ref, true)
if err != nil {
return fmt.Errorf("read %s: %w", ref, err)
}
head, err := r.CommitObject(tip.Hash())
if err != nil {
return fmt.Errorf("read %s: %w", ref, err)
}
published, err := publishedBoundary(r, head)
if err != nil || len(published) == 0 {
return err
}
var chain []*object.Commit
for c := head; !published[c.Hash]; {
chain = append(chain, c)
if c.NumParents() == 0 {
return nil
}
if c, err = c.Parent(0); err != nil {
return fmt.Errorf("walk %s: %w", ref, err)
}
}
if len(chain) == 0 || !m.needsAttest(chain) {
return nil
}
var rewritten plumbing.Hash
for _, c := range slices.Backward(chain) {
if err := ctx.Err(); err != nil {
return err
}
parents := append([]plumbing.Hash(nil), c.ParentHashes...)
if !rewritten.IsZero() {
parents[0] = rewritten
}
if rewritten, err = m.recommit(ctx, r, c, parents); err != nil {
return err
}
}
if err := r.Storer.SetReference(plumbing.NewHashReference(ref, rewritten)); err != nil {
return fmt.Errorf("update %s: %w", ref, err)
}
return nil
}
// needsAttest reports whether any commit lacks the bot identity or, with a
// signer configured, a signature.
func (m *Manager) needsAttest(chain []*object.Commit) bool {
for _, c := range chain {
if c.Author.Name != m.BotUser || c.Author.Email != m.BotEmail || c.Committer.Name != m.BotUser || c.Committer.Email != m.BotEmail {
return true
}
if m.Signer != nil && c.Signature == "" {
return true
}
}
return false
}
func (m *Manager) recommit(ctx context.Context, r *git.Repository, c *object.Commit, parents []plumbing.Hash) (plumbing.Hash, error) {
next := &object.Commit{
Author: object.Signature{Name: m.BotUser, Email: m.BotEmail, When: c.Author.When},
Committer: object.Signature{Name: m.BotUser, Email: m.BotEmail, When: time.Now()},
Message: c.Message,
TreeHash: c.TreeHash,
ParentHashes: parents,
Encoding: c.Encoding,
}
if m.Signer != nil {
unsigned := &plumbing.MemoryObject{}
if err := next.EncodeWithoutSignature(unsigned); err != nil {
return plumbing.ZeroHash, fmt.Errorf("encode commit: %w", err)
}
body, err := unsigned.Reader()
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("encode commit: %w", err)
}
sig, err := m.Signer.Sign(ctx, body)
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("sign commit: %w", err)
}
next.Signature = string(sig)
}
obj := r.Storer.NewEncodedObject()
if err := next.Encode(obj); err != nil {
return plumbing.ZeroHash, fmt.Errorf("encode commit: %w", err)
}
h, err := r.Storer.SetEncodedObject(obj)
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("store commit: %w", err)
}
return h, nil
}
// publishedBoundary is the set of commits where head meets any remote-tracking
// ref: everything at or behind them is already on the forge.
func publishedBoundary(r *git.Repository, head *object.Commit) (map[plumbing.Hash]bool, error) {
refs, err := r.References()
if err != nil {
return nil, fmt.Errorf("list refs: %w", err)
}
out := map[plumbing.Hash]bool{}
err = refs.ForEach(func(ref *plumbing.Reference) error {
if !ref.Name().IsRemote() || ref.Type() != plumbing.HashReference {
return nil
}
remote, err := r.CommitObject(ref.Hash())
if errors.Is(err, plumbing.ErrObjectNotFound) {
return nil
}
if err != nil {
return err
}
bases, err := head.MergeBase(remote)
if err != nil {
return err
}
for _, b := range bases {
out[b.Hash] = true
}
return nil
})
if err != nil && !errors.Is(err, storer.ErrStop) && !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("find published commits: %w", err)
}
return out, nil
}
+97
View File
@@ -0,0 +1,97 @@
package worktree
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/pem"
"testing"
"time"
"github.com/go-git/go-billy/v6/memfs"
"github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/go-git/go-git/v6/storage/memory"
"github.com/hiddeco/sshsig"
"golang.org/x/crypto/ssh"
)
// Commits made in the task container carry no identity and no signature; the
// push must publish them as the connection's bot, signed, without touching
// what is already on the forge.
func TestAttestSignsOnlyUnpublishedCommits(t *testing.T) {
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
block, err := ssh.MarshalPrivateKey(priv, "")
if err != nil {
t.Fatal(err)
}
signer, err := NewSSHSigner(pem.EncodeToMemory(block))
if err != nil {
t.Fatal(err)
}
pub, err := ssh.NewPublicKey(priv.Public())
if err != nil {
t.Fatal(err)
}
r, err := git.Init(memory.NewStorage(), git.WithWorkTree(memfs.New()))
if err != nil {
t.Fatal(err)
}
wt, _ := r.Worktree()
commit := func(name string) plumbing.Hash {
f, _ := wt.Filesystem().Create(name)
_, _ = f.Write([]byte(name))
_ = f.Close()
_, _ = wt.Add(name)
// The explicit signer stands in for whatever the machine's git config asks for.
h, err := wt.Commit(name, &git.CommitOptions{Author: &object.Signature{Name: "someone", Email: "x@y", When: time.Now()}, Signer: signer})
if err != nil {
t.Fatal(err)
}
return h
}
base := commit("base")
if err := r.Storer.SetReference(plumbing.NewHashReference(plumbing.NewRemoteReferenceName("origin", "main"), base)); err != nil {
t.Fatal(err)
}
commit("one")
commit("two")
head, _ := r.Head()
ref := head.Name()
m := &Manager{BotUser: "archie", BotEmail: "archie@example.com", Signer: signer}
for range 2 { // a second attest must change nothing
if err := m.attest(context.Background(), r, ref); err != nil {
t.Fatal(err)
}
}
tip, _ := r.Reference(ref, true)
c, _ := r.CommitObject(tip.Hash())
for _, want := range []string{"two", "one"} {
if c.Message != want || c.Author.Name != "archie" || c.Committer.Email != "archie@example.com" {
t.Fatalf("commit %q: author %q committer %q", c.Message, c.Author.Name, c.Committer.Email)
}
unsigned := &plumbing.MemoryObject{}
_ = c.EncodeWithoutSignature(unsigned)
body, _ := unsigned.Reader()
sig, err := sshsig.Unarmor([]byte(c.Signature))
if err != nil {
t.Fatalf("commit %q signature: %v", want, err)
}
if err := sshsig.Verify(body, sig, pub, sshsig.HashSHA512, "git"); err != nil {
t.Fatalf("commit %q does not verify: %v", want, err)
}
if c, err = c.Parent(0); err != nil {
t.Fatal(err)
}
}
if c.Hash != base || c.Author.Name != "someone" {
t.Fatalf("published commit was rewritten: %s by %s", c.Hash, c.Author.Name)
}
}
+11
View File
@@ -656,6 +656,9 @@ func (m *Manager) push(ctx context.Context, dir, branch, remoteURL string) error
"check the repository connection's credential", branch)
}
ref := plumbing.NewBranchReferenceName(branch)
if err := m.attest(ctx, r, ref); err != nil {
return fmt.Errorf("attest %s: %w", branch, err)
}
spec := gitconfig.RefSpec(fmt.Sprintf("%s:%s", ref, ref))
if err := r.PushContext(ctx, &git.PushOptions{
RemoteName: git.DefaultRemoteName,
@@ -665,6 +668,14 @@ func (m *Manager) push(ctx context.Context, dir, branch, remoteURL string) error
}); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
return fmt.Errorf("push %s: %w", branch, err)
}
// The tracking ref marks what is published, so the next attest leaves
// these commits alone.
if pushed, err := r.Reference(ref, true); err == nil {
tracking := plumbing.NewRemoteReferenceName(git.DefaultRemoteName, branch)
if err := r.Storer.SetReference(plumbing.NewHashReference(tracking, pushed.Hash())); err != nil {
m.logger().WarnContext(ctx, "record pushed branch", "branch", branch, "err", err)
}
}
// Record the upstream so the branch tracks origin, matching what
// `git push -u` left behind previously. A post-publication metadata
// failure must not cause push to report an error.