gittuf/pkg/gitinterface/commit.go
Paulo Gomes 9e269f46fb
Introduce gitstore.Storer and make gittuf's core dependency-light
Restructure storage so gittuf verification can run over backends other
than the git binary (e.g. go-git):

- pkg/githash: concrete Git object hash, stdlib-only.
  gitinterface.Hash aliases it.
- pkg/gitstore: the single Storer interface (24 methods) that all
  storage consumers program against, plus the shared
  ErrReferenceNotFound sentinel. *gitinterface.Repository satisfies it
  structurally (compile-time asserted). Also defines ConfigKey, the
  canonical type for the Git config settings gittuf reads.
- pkg/rsl (from internal/rsl): entry model, codec, and readers over
  gitstore.Storer; zero gitinterface/sigstore dependencies. rsl.Hash
  aliases githash.Hash; nil is the unset-Hash sentinel and IsZero
  matches nil and empty as well as both format zeros (no
  object-format-unaware ZeroHash). Entry commits (empty tree on the
  RSL ref) are owned by the package; no storer adapter.
- internal/signerverifier/gitobject: verifies commit/tag signatures
  over (payload, signature) bytes, Rekor URL as an option. The storage
  half is Repository.GetObjectSignature. Removes sigstore, cosign, and
  gitsign from gitinterface's dependency tree.
- internal/propagation: propagation workflow, moved off pkg/rsl's
  public API (its tuf directive types are internal).
- internal/{attestations,cache,policy}: storage via gitstore.Storer;
  tree writing via WriteTree(blobs, subtrees).

Breaking changes to pkg/gitinterface: Repository.VerifySignature and
the verification sentinels are removed (use gitobject.Verify);
ErrReferenceNotFound now aliases gitstore's. Repository.GetGitConfig
(which returned the whole config map) is replaced by
LookupConfig(gitstore.ConfigKey), returning a single setting's value.
Policy resolves the Rekor override from git config once per
verification and extracts signed payloads once per object instead of
per key attempt.

Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Paulo Gomes <paulo@entire.io>
2026-08-03 21:27:49 +01:00

297 lines
8.3 KiB
Go

// Copyright The gittuf Authors
// SPDX-License-Identifier: Apache-2.0
package gitinterface
import (
"errors"
"fmt"
"io"
"strings"
"testing"
"time"
"github.com/gittuf/gittuf/pkg/gitstore"
"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"
)
// Commit creates a new commit in the repo and sets targetRef's to the commit.
// This function is meant only for gittuf references, and therefore it does not
// mutate repository worktrees.
func (r *Repository) Commit(treeID Hash, targetRef, message string, sign bool) (Hash, error) {
currentGitID, err := r.GetReference(targetRef)
if err != nil {
if !errors.Is(err, ErrReferenceNotFound) {
return ZeroHash, err
}
}
args := []string{"commit-tree", "-m", message}
if !currentGitID.IsZero() {
args = append(args, "-p", currentGitID.String())
}
if sign {
args = append(args, "-S")
}
args = append(args, treeID.String())
now := r.clock.Now().Format(time.RFC3339)
env := []string{fmt.Sprintf("%s=%s", committerTimeKey, now), fmt.Sprintf("%s=%s", authorTimeKey, now)}
stdOut, err := r.executor(args...).withEnv(env...).executeString()
if err != nil {
return ZeroHash, fmt.Errorf("unable to create commit: %w", err)
}
commitID, err := NewHash(stdOut)
if err != nil {
return ZeroHash, fmt.Errorf("received invalid commit ID: %w", err)
}
return commitID, r.CheckAndSetReference(targetRef, commitID, currentGitID)
}
// CommitUsingSpecificKey creates a new commit in the repository for the
// specified parameters. The commit is signed using the PEM encoded SSH or GPG
// private key. This function is expected for use in tests and gittuf's
// developer mode. In standard workflows, Commit() must be used instead which
// infers the signing key from the user's Git config.
func (r *Repository) CommitUsingSpecificKey(treeID Hash, targetRef, message string, signingKeyPEMBytes []byte) (Hash, error) {
name, _, err := r.LookupConfig(gitstore.ConfigUserName)
if err != nil {
return ZeroHash, err
}
email, _, err := r.LookupConfig(gitstore.ConfigUserEmail)
if err != nil {
return ZeroHash, err
}
commitMetadata := object.Signature{
Name: name,
Email: email,
When: r.clock.Now(),
}
commit := &object.Commit{
Author: commitMetadata,
Committer: commitMetadata,
TreeHash: plumbing.NewHash(treeID.String()),
Message: message,
}
refTip, err := r.GetReference(targetRef)
if err != nil {
if !errors.Is(err, ErrReferenceNotFound) {
return ZeroHash, err
}
}
if !refTip.IsZero() {
commit.ParentHashes = []plumbing.Hash{plumbing.NewHash(refTip.String())}
}
commitContents, err := getCommitBytesWithoutSignature(commit)
if err != nil {
return ZeroHash, err
}
signature, err := signGitObjectUsingKey(commitContents, signingKeyPEMBytes)
if err != nil {
return ZeroHash, err
}
// SHA-256 repositories store the signature under the `gpgsig-sha256`
// header (go-git's SignatureSHA256), matching Git's own behavior, so it
// can be read back during verification.
if r.GetObjectFormat() == ObjectFormatSHA256 {
commit.SignatureSHA256 = signature
} else {
commit.Signature = signature
}
goGitRepo, err := r.GetGoGitRepository()
if err != nil {
return ZeroHash, err
}
obj := goGitRepo.Storer.NewEncodedObject()
if err := commit.Encode(obj); err != nil {
return ZeroHash, err
}
commitID, err := goGitRepo.Storer.SetEncodedObject(obj)
if err != nil {
return ZeroHash, err
}
commitIDHash, err := NewHash(commitID.String())
if err != nil {
return ZeroHash, err
}
return commitIDHash, r.CheckAndSetReference(targetRef, commitIDHash, refTip)
}
// commitWithParents creates a new commit in the repo but does not update any
// references. It is only meant to be used for tests, and therefore accepts
// specific parent commit IDs.
func (r *Repository) commitWithParents(t *testing.T, treeID Hash, parentIDs []Hash, message string, sign bool) Hash { //nolint:unparam
args := []string{"commit-tree", "-m", message}
for _, commitID := range parentIDs {
args = append(args, "-p", commitID.String())
}
if sign {
args = append(args, "-S")
}
args = append(args, treeID.String())
now := r.clock.Now().Format(time.RFC3339)
env := []string{fmt.Sprintf("%s=%s", committerTimeKey, now), fmt.Sprintf("%s=%s", authorTimeKey, now)}
stdOut, err := r.executor(args...).withEnv(env...).executeString()
if err != nil {
t.Fatal(fmt.Errorf("unable to create commit: %w", err))
}
commitID, err := NewHash(stdOut)
if err != nil {
t.Fatal(fmt.Errorf("received invalid commit ID: %w", err))
}
return commitID
}
// GetCommitMessage returns the commit's message.
func (r *Repository) GetCommitMessage(commitID Hash) (string, error) {
if err := r.ensureIsCommit(commitID); err != nil {
return "", err
}
commitMessage, err := r.executor("show", "-s", "--format=%B", commitID.String()).executeString()
if err != nil {
return "", fmt.Errorf("unable to identify message for commit '%s': %w", commitID.String(), err)
}
return commitMessage, nil
}
// GetCommitTreeID returns the commit's Git tree ID.
func (r *Repository) GetCommitTreeID(commitID Hash) (Hash, error) {
if err := r.ensureIsCommit(commitID); err != nil {
return ZeroHash, err
}
stdOut, err := r.executor("rev-parse", fmt.Sprintf("%s^{tree}", commitID.String())).executeString()
if err != nil {
return ZeroHash, fmt.Errorf("unable to identify tree for commit '%s': %w", commitID.String(), err)
}
hash, err := NewHash(stdOut)
if err != nil {
return ZeroHash, fmt.Errorf("invalid tree for commit ID '%s': %w", commitID, err)
}
return hash, nil
}
// GetCommitParentIDs returns the commit's parent commit IDs.
func (r *Repository) GetCommitParentIDs(commitID Hash) ([]Hash, error) {
if err := r.ensureIsCommit(commitID); err != nil {
return nil, err
}
stdOut, err := r.executor("rev-parse", fmt.Sprintf("%s^@", commitID.String())).executeString()
if err != nil {
return nil, fmt.Errorf("unable to identify parents for commit '%s': %w", commitID.String(), err)
}
commitIDSplit := strings.Split(stdOut, "\n")
if len(commitIDSplit) == 0 {
return nil, nil
}
commitIDs := []Hash{}
for _, commitID := range commitIDSplit {
if commitID == "" {
continue
}
hash, err := NewHash(commitID)
if err != nil {
return nil, fmt.Errorf("invalid parent commit ID '%s': %w", commitID, err)
}
commitIDs = append(commitIDs, hash)
}
if len(commitIDs) == 0 {
return nil, nil
}
return commitIDs, nil
}
// KnowsCommit returns true if the `testCommit` is a descendent of the
// `ancestorCommit`. That is, the testCommit _knows_ the ancestorCommit as it
// has a path in the commit graph to the ancestorCommit.
func (r *Repository) KnowsCommit(testCommitID, ancestorCommitID Hash) (bool, error) {
if err := r.ensureIsCommit(testCommitID); err != nil {
return false, err
}
if err := r.ensureIsCommit(ancestorCommitID); err != nil {
return false, err
}
_, err := r.executor("merge-base", "--is-ancestor", ancestorCommitID.String(), testCommitID.String()).executeString()
return err == nil, nil
}
// GetCommonAncestor finds the common ancestor commit for the two supplied
// commits.
func (r *Repository) GetCommonAncestor(commitAID, commitBID Hash) (Hash, error) {
if err := r.ensureIsCommit(commitAID); err != nil {
return nil, err
}
if err := r.ensureIsCommit(commitBID); err != nil {
return nil, err
}
mergeBase, err := r.executor("merge-base", commitAID.String(), commitBID.String()).executeString()
if err != nil {
return nil, err
}
mergeBaseID, err := NewHash(mergeBase)
if err != nil {
return nil, fmt.Errorf("received invalid commit ID: %w", err)
}
return mergeBaseID, nil
}
// ensureIsCommit is a helper to check that the ID represents a Git commit
// object.
func (r *Repository) ensureIsCommit(commitID Hash) error {
objType, err := r.executor("cat-file", "-t", commitID.String()).executeString()
if err != nil {
return fmt.Errorf("unable to inspect if object is commit: %w", err)
} else if objType != "commit" {
return fmt.Errorf("requested Git ID '%s' is not a commit object", commitID.String())
}
return nil
}
func getCommitBytesWithoutSignature(commit *object.Commit) ([]byte, error) {
commitEncoded := memory.NewStorage().NewEncodedObject()
if err := commit.EncodeWithoutSignature(commitEncoded); err != nil {
return nil, err
}
r, err := commitEncoded.Reader()
if err != nil {
return nil, err
}
return io.ReadAll(r)
}