Capture diagnostic identities and rehearsal records

This commit is contained in:
2026-12-05 22:45:28 +00:00
parent 6f01e9ef0a
commit 181e5a030c
19 changed files with 1284 additions and 60 deletions

View File

@@ -47,6 +47,22 @@ func RepositoryRoot(ctx context.Context, directory string) (string, error) {
return normalizeRepositoryRoot(root)
}
// ResolveCommit resolves a revision to its full commit ID without changing the checkout.
func ResolveCommit(ctx context.Context, repositoryDir, revision string) (string, error) {
if revision == "" {
revision = "HEAD"
}
output, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", "--end-of-options", revision+"^{commit}")
if err != nil {
return "", fmt.Errorf("resolve selected revision: %w", err)
}
commit := strings.TrimSpace(output)
if !validObjectID(commit) {
return "", fmt.Errorf("selected revision did not resolve to a full commit ID")
}
return commit, nil
}
// CheckTaggerIdentity checks Git's native committer identity without creating a tag.
func CheckTaggerIdentity(ctx context.Context, directory string) error {
if _, err := run(ctx, directory, nil, "var", "GIT_COMMITTER_IDENT"); err != nil {

View File

@@ -9,6 +9,79 @@ import (
"strings"
)
// AnnotatedTag is the immutable tag object and its direct commit target.
type AnnotatedTag struct {
Object string
Commit string
Message []byte
}
// ReadAnnotatedTag reads an exact local tag and requires a direct commit target.
func ReadAnnotatedTag(ctx context.Context, repositoryDir, tag string) (AnnotatedTag, error) {
if err := CheckTagRef(ctx, repositoryDir, tag); err != nil {
return AnnotatedTag{}, err
}
ref := "refs/tags/" + tag
object, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("resolve annotated tag: %w", err)
}
object = strings.TrimSpace(object)
if !validObjectID(object) {
return AnnotatedTag{}, errors.New("invalid annotated tag object")
}
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", object)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag: %w", err)
}
if strings.TrimSpace(tagType) != "tag" {
return AnnotatedTag{}, errors.New("diagnostic reference is not an annotated tag")
}
contents, err := run(ctx, repositoryDir, nil, "cat-file", "tag", object)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("read annotated tag: %w", err)
}
header, message, ok := strings.Cut(contents, "\n\n")
if !ok {
return AnnotatedTag{}, errors.New("annotated tag has no message")
}
var target, targetType, tagName string
for _, line := range strings.Split(header, "\n") {
key, value, ok := strings.Cut(line, " ")
if !ok {
continue
}
switch key {
case "object":
if target != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its target")
}
target = value
case "type":
if targetType != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its type")
}
targetType = value
case "tag":
if tagName != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its name")
}
tagName = value
}
}
if !validObjectID(target) || targetType != "commit" || tagName != tag {
return AnnotatedTag{}, errors.New("annotated tag target or name does not match")
}
actualType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", target)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag target: %w", err)
}
if strings.TrimSpace(actualType) != "commit" {
return AnnotatedTag{}, errors.New("annotated tag target is not a commit")
}
return AnnotatedTag{Object: object, Commit: target, Message: []byte(message)}, nil
}
// CreateAnnotatedTag records the captured note as an unsigned annotated tag
// on the captured commit. Once its type and ID are established, the ID is
// returned even if a later verification fails.

View File

@@ -10,11 +10,10 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/recordstore"
)
const recordFormatVersion = 1
@@ -184,21 +183,7 @@ func saveEvidenceNamed(ctx context.Context, repositoryDir, root, override, recor
}
func resolveRecordDir(ctx context.Context, repositoryDir, override string) (string, string, error) {
root, err := git.RepositoryRoot(ctx, repositoryDir)
if err != nil {
return "", "", err
}
if override != "" {
if filepath.IsAbs(override) {
return filepath.Clean(override), root, nil
}
return filepath.Join(root, override), root, nil
}
common, err := git.CommonDirectory(ctx, repositoryDir)
if err != nil {
return "", "", err
}
return filepath.Join(common, "releasekit", "publication-attempts"), root, nil
return recordstore.ResolveDir(ctx, repositoryDir, override, "publication-attempts")
}
func proposedRecordPath(directory string) (string, error) {
@@ -210,31 +195,5 @@ func proposedRecordPath(directory string) (string, error) {
}
func rejectUnignoredWorktreePath(ctx context.Context, repositoryDir, root, proposed string) error {
parent, err := filepath.EvalSymlinks(filepath.Dir(proposed))
if err != nil {
return fmt.Errorf("resolve record directory %q: %w", filepath.Dir(proposed), err)
}
actual := filepath.Join(parent, filepath.Base(proposed))
rel, err := filepath.Rel(root, actual)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
metadata, err := git.MetadataDirectories(ctx, repositoryDir)
if err != nil {
return err
}
for _, directory := range metadata {
rel, err := filepath.Rel(directory, actual)
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
}
ignored, err := git.IsIgnored(ctx, repositoryDir, actual)
if err != nil {
return fmt.Errorf("check Git ignore rules for record path %q: %w", actual, err)
}
if !ignored {
return fmt.Errorf("record path %q is inside the worktree and is not ignored", actual)
}
return nil
return recordstore.CheckPath(ctx, repositoryDir, root, proposed)
}

View File

@@ -0,0 +1,63 @@
// Package recordstore owns private record location and worktree checks.
package recordstore
import (
"context"
"fmt"
"path/filepath"
"strings"
"go.maximumdirect.net/releasekit/internal/git"
)
// ResolveDir resolves an override relative to the repository or a directory in
// its shared Git metadata, returning both the record directory and checkout.
func ResolveDir(ctx context.Context, repositoryDir, override, category string) (string, string, error) {
root, err := git.RepositoryRoot(ctx, repositoryDir)
if err != nil {
return "", "", err
}
if override != "" {
if filepath.IsAbs(override) {
return filepath.Clean(override), root, nil
}
return filepath.Join(root, override), root, nil
}
common, err := git.CommonDirectory(ctx, repositoryDir)
if err != nil {
return "", "", err
}
return filepath.Join(common, "releasekit", category), root, nil
}
// CheckPath requires worktree record locations to be ignored, except for Git
// metadata directories. The record directory must already exist.
func CheckPath(ctx context.Context, repositoryDir, root, proposed string) error {
parent, err := filepath.EvalSymlinks(filepath.Dir(proposed))
if err != nil {
return fmt.Errorf("resolve record directory %q: %w", filepath.Dir(proposed), err)
}
actual := filepath.Join(parent, filepath.Base(proposed))
rel, err := filepath.Rel(root, actual)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
metadata, err := git.MetadataDirectories(ctx, repositoryDir)
if err != nil {
return err
}
for _, directory := range metadata {
rel, err := filepath.Rel(directory, actual)
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
}
ignored, err := git.IsIgnored(ctx, repositoryDir, actual)
if err != nil {
return fmt.Errorf("check Git ignore rules for record path %q: %w", actual, err)
}
if !ignored {
return fmt.Errorf("record path %q is inside the worktree and is not ignored", actual)
}
return nil
}

View File

@@ -0,0 +1,280 @@
// Package rehearsal owns diagnostic attempt identity and durable evidence.
package rehearsal
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"path"
"strings"
"unicode/utf8"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
const manifestHeader = "ReleaseKit rehearsal v1\n"
// Manifest binds a diagnostic tag to one committed profile and source selection.
type Manifest struct {
SchemaVersion int `json:"schema_version"`
AttemptID string `json:"attempt_id,omitempty"`
Selector string `json:"selector,omitempty"`
Commit string `json:"commit,omitempty"`
ProfilePath string `json:"profile_path,omitempty"`
ProfileSHA256 string `json:"profile_sha256,omitempty"`
SourceDir string `json:"source_dir,omitempty"`
GoEnabled bool `json:"go_enabled"`
ModulePath string `json:"module_path,omitempty"`
PublicationMode string `json:"publication_mode,omitempty"`
VersionFormat string `json:"version_format,omitempty"`
VersionPrefix string `json:"version_prefix"`
DiagnosticVersion string `json:"diagnostic_version,omitempty"`
Tag string `json:"tag,omitempty"`
IdentityBytes map[string][]byte `json:"identity_bytes,omitempty"`
}
type stringField struct {
name string
value *string
}
func manifestFields(m *Manifest) []stringField {
return []stringField{{"attempt_id", &m.AttemptID}, {"selector", &m.Selector}, {"commit", &m.Commit}, {"profile_path", &m.ProfilePath}, {"profile_sha256", &m.ProfileSHA256}, {"source_dir", &m.SourceDir}, {"module_path", &m.ModulePath}, {"publication_mode", &m.PublicationMode}, {"version_format", &m.VersionFormat}, {"version_prefix", &m.VersionPrefix}, {"diagnostic_version", &m.DiagnosticVersion}, {"tag", &m.Tag}}
}
// EncodeManifest returns the exact annotated-tag message, preserving non-UTF-8
// identity bytes through base64 overrides.
func EncodeManifest(manifest Manifest) ([]byte, error) {
manifest.IdentityBytes = nil
for _, field := range manifestFields(&manifest) {
if !utf8.ValidString(*field.value) {
if manifest.IdentityBytes == nil {
manifest.IdentityBytes = make(map[string][]byte)
}
manifest.IdentityBytes[field.name] = []byte(*field.value)
*field.value = ""
}
}
raw, err := json.Marshal(manifest)
if err != nil {
return nil, err
}
if len(manifest.IdentityBytes) != 0 {
var object map[string]json.RawMessage
if err := json.Unmarshal(raw, &object); err != nil {
return nil, err
}
for name := range manifest.IdentityBytes {
delete(object, name)
}
raw, err = json.Marshal(object)
if err != nil {
return nil, err
}
}
return append(append([]byte(manifestHeader), raw...), '\n'), nil
}
// DecodeManifest reads one supported diagnostic annotation.
func DecodeManifest(message []byte) (Manifest, error) {
var manifest Manifest
if !strings.HasPrefix(string(message), manifestHeader) {
return manifest, errors.New("diagnostic annotation has an invalid marker")
}
var object map[string]json.RawMessage
if err := json.Unmarshal(message[len(manifestHeader):], &object); err != nil {
return Manifest{}, fmt.Errorf("decode diagnostic manifest: %w", err)
}
overrides := object["identity_bytes"]
delete(object, "identity_bytes")
data, err := json.Marshal(object)
if err != nil {
return Manifest{}, err
}
if err := json.Unmarshal(data, &manifest); err != nil {
return Manifest{}, fmt.Errorf("decode diagnostic manifest: %w", err)
}
if manifest.SchemaVersion != 1 {
return Manifest{}, fmt.Errorf("unsupported diagnostic manifest version %d", manifest.SchemaVersion)
}
if err := decodeStringOverrides(overrides, manifestFields(&manifest)); err != nil {
return Manifest{}, fmt.Errorf("decode diagnostic identity bytes: %w", err)
}
return manifest, nil
}
func decodeStringOverrides(raw json.RawMessage, fields []stringField) error {
if len(raw) == 0 {
return nil
}
var values map[string]json.RawMessage
if err := json.Unmarshal(raw, &values); err != nil {
return err
}
for _, field := range fields {
value, ok := values[field.name]
if !ok {
continue
}
var encoded *string
if err := json.Unmarshal(value, &encoded); err != nil {
return fmt.Errorf("%s: %w", field.name, err)
}
if encoded == nil {
return fmt.Errorf("%s must be a base64 string", field.name)
}
decoded, err := base64.StdEncoding.DecodeString(*encoded)
if err != nil {
return fmt.Errorf("%s: %w", field.name, err)
}
*field.value = string(decoded)
}
return nil
}
func validAttemptID(value string) bool {
if len(value) != 32 || strings.ToLower(value) != value {
return false
}
_, err := hex.DecodeString(value)
return err == nil
}
func validateManifestStructure(manifest Manifest) error {
if manifest.SchemaVersion != 1 || !validAttemptID(manifest.AttemptID) {
return errors.New("invalid diagnostic attempt identity")
}
if manifest.Selector == "" || strings.Contains(manifest.Selector, "/") || manifest.Tag != "releasekit-test/"+manifest.Selector+"/"+manifest.AttemptID || manifest.DiagnosticVersion != "releasekit-test-"+manifest.AttemptID {
return errors.New("diagnostic tag and identity do not match")
}
if !git.ValidObjectID(manifest.Commit) {
return errors.New("invalid diagnostic commit")
}
if manifest.ProfilePath == "" || path.IsAbs(manifest.ProfilePath) || path.Clean(manifest.ProfilePath) != manifest.ProfilePath || manifest.ProfilePath == ".." || strings.HasPrefix(manifest.ProfilePath, "../") || strings.Contains(manifest.ProfilePath, "\\") {
return errors.New("invalid diagnostic profile path")
}
if len(manifest.ProfileSHA256) != 64 || strings.ToLower(manifest.ProfileSHA256) != manifest.ProfileSHA256 {
return errors.New("invalid diagnostic profile digest")
}
if _, err := hex.DecodeString(manifest.ProfileSHA256); err != nil {
return errors.New("invalid diagnostic profile digest")
}
if manifest.SourceDir == "" || path.IsAbs(manifest.SourceDir) || path.Clean(manifest.SourceDir) != manifest.SourceDir || manifest.SourceDir == ".." || strings.HasPrefix(manifest.SourceDir, "../") {
return errors.New("invalid diagnostic source directory")
}
if manifest.GoEnabled != (manifest.ModulePath != "") {
return errors.New("diagnostic Go selection and module path do not match")
}
if manifest.PublicationMode != "source" && manifest.PublicationMode != "go-module" {
return errors.New("invalid diagnostic publication mode")
}
if manifest.VersionFormat != "semver" && manifest.VersionFormat != "date" && manifest.VersionFormat != "year-month" {
return errors.New("invalid diagnostic version format")
}
if manifest.VersionPrefix != "" && manifest.VersionPrefix != "v" {
return errors.New("invalid diagnostic version prefix")
}
if manifest.PublicationMode == "go-module" && (!manifest.GoEnabled || manifest.VersionFormat != "semver" || manifest.VersionPrefix != "v") {
return errors.New("invalid diagnostic Go module selection")
}
return nil
}
// NewManifest binds a resolved diagnostic identity to the exact profile bytes.
func NewManifest(identity releaseidentity.Identity, attempt, selector, profilePath string, profile []byte) Manifest {
digest := sha256.Sum256(profile)
return Manifest{SchemaVersion: 1, AttemptID: attempt, Selector: selector, Commit: identity.Commit, ProfilePath: profilePath, ProfileSHA256: hex.EncodeToString(digest[:]), SourceDir: identity.SourceSubdir, GoEnabled: identity.GoEnabled, ModulePath: identity.ModulePath, PublicationMode: identity.Publication, VersionFormat: identity.VersionFormat, VersionPrefix: identity.VersionPrefix, DiagnosticVersion: identity.Version, Tag: identity.Tag}
}
// CreateDiagnosticTag creates an unsigned annotated local tag without moving
// an existing reference. Remote dispatch is a separate operation.
func CreateDiagnosticTag(ctx context.Context, repository string, manifest Manifest) (string, error) {
if err := validateManifestStructure(manifest); err != nil {
return "", err
}
message, err := EncodeManifest(manifest)
if err != nil {
return "", err
}
return git.CreateAnnotatedTag(ctx, repository, manifest.Tag, manifest.Commit, message)
}
// VerifyManifest checks the exact tag, target commit, committed profile and
// normalized source selection supplied by the caller.
func VerifyManifest(ctx context.Context, repository, tag, target, expectedProfile string, profile []byte, source releaseidentity.ResolvedSource, manifest Manifest) error {
if err := validateManifestStructure(manifest); err != nil {
return err
}
if manifest.Tag != tag {
return errors.New("diagnostic tag and identity do not match")
}
if err := git.CheckTagRef(ctx, repository, tag); err != nil {
return err
}
if !git.EqualObjectID(manifest.Commit, target) {
return errors.New("diagnostic target commit does not match")
}
if manifest.ProfilePath != expectedProfile {
return errors.New("diagnostic profile path does not match")
}
digest := sha256.Sum256(profile)
if manifest.ProfileSHA256 != hex.EncodeToString(digest[:]) {
return errors.New("diagnostic profile digest does not match")
}
if manifest.SourceDir != source.ModuleSubdir || manifest.GoEnabled != source.GoEnabled || manifest.ModulePath != source.ModulePath || manifest.PublicationMode != source.Publication || manifest.VersionFormat != source.VersionFormat || manifest.VersionPrefix != source.VersionPrefix {
return errors.New("diagnostic source selection does not match")
}
return nil
}
// VerifiedTag contains the captured identity and exact committed profile.
type VerifiedTag struct {
Manifest Manifest
TagObject string
Profile []byte
Source releaseidentity.ResolvedSource
}
// VerifyTag reads the annotated tag and profile from Git, resolves the profile's
// source through the supplied decoder, and binds them to the event identity.
func VerifyTag(ctx context.Context, repository, tag, eventCommit, expectedSelector, expectedProfile string, resolve func(context.Context, string, []byte) (releaseidentity.ResolvedSource, error)) (VerifiedTag, error) {
var result VerifiedTag
tagged, err := git.ReadAnnotatedTag(ctx, repository, tag)
if err != nil {
return result, err
}
result.TagObject = tagged.Object
if !git.EqualObjectID(tagged.Commit, eventCommit) {
return result, errors.New("diagnostic tag target does not match the event commit")
}
result.Manifest, err = DecodeManifest(tagged.Message)
if err != nil {
return result, err
}
if err := validateManifestStructure(result.Manifest); err != nil {
return result, err
}
if result.Manifest.Selector != expectedSelector || result.Manifest.ProfilePath != expectedProfile {
return result, errors.New("diagnostic selector or profile does not match dispatch")
}
result.Profile, err = git.ReadCommitFile(ctx, repository, tagged.Commit, result.Manifest.ProfilePath)
if err != nil {
return result, fmt.Errorf("read captured diagnostic profile: %w", err)
}
if resolve == nil {
return result, errors.New("diagnostic source resolver is required")
}
result.Source, err = resolve(ctx, tagged.Commit, result.Profile)
if err != nil {
return result, fmt.Errorf("resolve captured diagnostic source: %w", err)
}
if err := VerifyManifest(ctx, repository, tag, tagged.Commit, expectedProfile, result.Profile, result.Source, result.Manifest); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,144 @@
package rehearsal
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func rehearsalFixture(t *testing.T) (string, []byte, releaseidentity.ResolvedSource, releaseidentity.Identity, string) {
t.Helper()
repo := t.TempDir()
run := func(args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v: %s", args, err, output)
}
return strings.TrimSpace(string(output))
}
run("init", "--initial-branch=main")
run("config", "user.name", "ReleaseKit Test")
run("config", "user.email", "releasekit@example.test")
run("config", "tag.gpgsign", "false")
profile := []byte("{\"product\":\"Example\",\"source\":{}}\n")
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), profile, 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "capture profile")
commit := run("rev-parse", "HEAD")
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", commit, &releaseidentity.SourceSpec{})
if err != nil {
t.Fatal(err)
}
identity, attempt, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", commit)
if err != nil {
t.Fatal(err)
}
return repo, profile, source, identity, attempt
}
func TestDiagnosticManifestBindsAnnotatedCommitAndProfile(t *testing.T) {
repo, profile, source, identity, attempt := rehearsalFixture(t)
manifest := NewManifest(identity, attempt, "root", "releasekit.json", profile)
message, err := EncodeManifest(manifest)
if err != nil {
t.Fatal(err)
}
object, err := CreateDiagnosticTag(t.Context(), repo, manifest)
if err != nil {
t.Fatal(err)
}
tag, err := git.ReadAnnotatedTag(t.Context(), repo, identity.Tag)
if err != nil {
t.Fatal(err)
}
if tag.Object != object || tag.Commit != identity.Commit || !bytes.Equal(tag.Message, message) {
t.Fatalf("tag=%+v", tag)
}
if _, err := CreateDiagnosticTag(t.Context(), repo, manifest); err == nil {
t.Fatal("moved an existing diagnostic tag")
}
unchanged, err := git.ReadAnnotatedTag(t.Context(), repo, identity.Tag)
if err != nil || unchanged.Object != object {
t.Fatalf("existing tag changed: %+v, error=%v", unchanged, err)
}
decoded, err := DecodeManifest(tag.Message)
if err != nil {
t.Fatal(err)
}
if err := VerifyManifest(t.Context(), repo, identity.Tag, tag.Commit, "releasekit.json", profile, source, decoded); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("changed working profile"), 0600); err != nil {
t.Fatal(err)
}
resolve := func(ctx context.Context, commit string, captured []byte) (releaseidentity.ResolvedSource, error) {
if !bytes.Equal(captured, profile) {
t.Error("used working profile instead of committed bytes")
}
return releaseidentity.LoadCommittedSource(ctx, repo, "", commit, &releaseidentity.SourceSpec{})
}
verified, err := VerifyTag(t.Context(), repo, identity.Tag, tag.Commit, "root", "releasekit.json", resolve)
if err != nil || verified.TagObject != object || !bytes.Equal(verified.Profile, profile) {
t.Fatalf("verified=%+v err=%v", verified, err)
}
if _, err := VerifyTag(t.Context(), repo, identity.Tag, tag.Commit, "other", "releasekit.json", resolve); err == nil {
t.Fatal("accepted a different dispatch selector")
}
for _, changed := range []struct {
name string
tag, commit, profilePath string
profile []byte
}{
{"tag", "releasekit-test/other/" + attempt, tag.Commit, "releasekit.json", profile},
{"commit", identity.Tag, strings.Repeat("a", 40), "releasekit.json", profile},
{"profile path", identity.Tag, tag.Commit, "other.json", profile},
{"profile bytes", identity.Tag, tag.Commit, "releasekit.json", []byte("changed")},
} {
t.Run(changed.name, func(t *testing.T) {
if err := VerifyManifest(context.Background(), repo, changed.tag, changed.commit, changed.profilePath, changed.profile, source, decoded); err == nil {
t.Fatal("accepted inconsistent diagnostic evidence")
}
})
}
source.VersionFormat = "date"
if err := VerifyManifest(t.Context(), repo, identity.Tag, tag.Commit, "releasekit.json", profile, source, decoded); err == nil {
t.Fatal("accepted changed source selection")
}
}
func TestManifestPreservesExactIdentityBytesAndRejectsMalformedOverrides(t *testing.T) {
raw := string([]byte{'p', 0xff, 'q'})
original := Manifest{SchemaVersion: 1, ProfilePath: raw, VersionPrefix: raw}
data, err := EncodeManifest(original)
if err != nil {
t.Fatal(err)
}
if bytes.Contains(data, []byte("\\ufffd")) || !bytes.Contains(data, []byte("identity_bytes")) {
t.Fatalf("encoded manifest = %q", data)
}
decoded, err := DecodeManifest(data)
if err != nil || decoded.ProfilePath != raw || decoded.VersionPrefix != raw {
t.Fatalf("decoded=%+v err=%v", decoded, err)
}
for _, data := range []string{
"not a manifest", manifestHeader + `{"schema_version":2}`,
manifestHeader + `{"schema_version":1,"identity_bytes":{"profile_path":null}}`,
manifestHeader + `{"schema_version":1,"identity_bytes":{"profile_path":"%%%"}}`,
} {
if _, err := DecodeManifest([]byte(data)); err == nil {
t.Fatalf("accepted malformed manifest %q", data)
}
}
}

View File

@@ -0,0 +1,252 @@
package rehearsal
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"sync"
"time"
"unicode/utf8"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/recordstore"
)
// Attempt retains the immutable identity and observations needed for recovery.
// It deliberately contains no resolved forge or Woodpecker token.
type Attempt struct {
FormatVersion int `json:"format_version"`
Manifest Manifest `json:"manifest"`
RepositoryDir string `json:"repository_dir,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Remote string `json:"remote,omitempty"`
ForgeBaseURL string `json:"forge_base_url,omitempty"`
ForgeOwner string `json:"forge_owner,omitempty"`
ForgeRepository string `json:"forge_repository,omitempty"`
WoodpeckerBaseURL string `json:"woodpecker_base_url,omitempty"`
WoodpeckerRepositoryID int64 `json:"woodpecker_repository_id,omitempty"`
Workflow string `json:"workflow,omitempty"`
Step string `json:"step,omitempty"`
ExpectedPageTitle string `json:"expected_page_title,omitempty"`
ExpectedBodySHA256 string `json:"expected_body_sha256,omitempty"`
TagObject string `json:"tag_object,omitempty"`
PageID int64 `json:"page_id,omitempty"`
PipelineIDs []int64 `json:"pipeline_ids,omitempty"`
Outcomes map[string]string `json:"outcomes,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
IdentityBytes map[string][]byte `json:"identity_bytes,omitempty"`
}
func attemptFields(a *Attempt) []stringField {
return []stringField{{"repository_dir", &a.RepositoryDir}, {"endpoint", &a.Endpoint}, {"remote", &a.Remote}, {"forge_base_url", &a.ForgeBaseURL}, {"forge_owner", &a.ForgeOwner}, {"forge_repository", &a.ForgeRepository}, {"woodpecker_base_url", &a.WoodpeckerBaseURL}, {"workflow", &a.Workflow}, {"step", &a.Step}, {"expected_page_title", &a.ExpectedPageTitle}, {"expected_body_sha256", &a.ExpectedBodySHA256}, {"tag_object", &a.TagObject}, {"created_at", &a.CreatedAt}, {"updated_at", &a.UpdatedAt}}
}
func encodeAttempt(attempt Attempt) ([]byte, error) {
attempt.FormatVersion = 1
attempt.IdentityBytes = nil
for _, field := range attemptFields(&attempt) {
if !utf8.ValidString(*field.value) {
if attempt.IdentityBytes == nil {
attempt.IdentityBytes = map[string][]byte{}
}
attempt.IdentityBytes[field.name] = []byte(*field.value)
*field.value = ""
}
}
encodedManifest, err := EncodeManifest(attempt.Manifest)
if err != nil {
return nil, err
}
raw, err := json.Marshal(attempt)
if err != nil {
return nil, err
}
var object map[string]json.RawMessage
if err := json.Unmarshal(raw, &object); err != nil {
return nil, err
}
object["manifest"] = json.RawMessage(encodedManifest[len(manifestHeader) : len(encodedManifest)-1])
for name := range attempt.IdentityBytes {
delete(object, name)
}
return json.Marshal(object)
}
// LoadAttempt reads exactly one explicitly selected private record.
func LoadAttempt(path string) (Attempt, error) {
var attempt Attempt
data, err := os.ReadFile(path)
if err != nil {
return attempt, fmt.Errorf("read rehearsal record: %w", err)
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil {
return attempt, fmt.Errorf("decode rehearsal record: %w", err)
}
manifestBytes, ok := object["manifest"]
if !ok {
return attempt, errors.New("rehearsal record has no manifest")
}
delete(object, "manifest")
overrides := object["identity_bytes"]
delete(object, "identity_bytes")
remainder, err := json.Marshal(object)
if err != nil {
return attempt, err
}
if err := json.Unmarshal(remainder, &attempt); err != nil {
return Attempt{}, fmt.Errorf("decode rehearsal record: %w", err)
}
if attempt.FormatVersion != 1 {
return Attempt{}, fmt.Errorf("unsupported rehearsal record version %d", attempt.FormatVersion)
}
attempt.Manifest, err = DecodeManifest(append([]byte(manifestHeader), manifestBytes...))
if err != nil {
return Attempt{}, err
}
if err := validateManifestStructure(attempt.Manifest); err != nil {
return Attempt{}, fmt.Errorf("invalid rehearsal identity: %w", err)
}
if err := decodeStringOverrides(overrides, attemptFields(&attempt)); err != nil {
return Attempt{}, fmt.Errorf("decode rehearsal identity bytes: %w", err)
}
return attempt, nil
}
// Store serializes updates made through one handle for one attempt.
type Store struct {
Path string
mu sync.Mutex
manifest Manifest
createdAt string
identity attemptIdentity
tagObject string
}
type attemptIdentity struct {
RepositoryDir, Endpoint, Remote, ForgeBaseURL, ForgeOwner, ForgeRepository string
WoodpeckerBaseURL, Workflow, Step, ExpectedPageTitle, ExpectedBodySHA256 string
WoodpeckerRepositoryID int64
}
func identityOf(attempt Attempt) attemptIdentity {
return attemptIdentity{RepositoryDir: attempt.RepositoryDir, Endpoint: attempt.Endpoint, Remote: attempt.Remote, ForgeBaseURL: attempt.ForgeBaseURL, ForgeOwner: attempt.ForgeOwner, ForgeRepository: attempt.ForgeRepository, WoodpeckerBaseURL: attempt.WoodpeckerBaseURL, WoodpeckerRepositoryID: attempt.WoodpeckerRepositoryID, Workflow: attempt.Workflow, Step: attempt.Step, ExpectedPageTitle: attempt.ExpectedPageTitle, ExpectedBodySHA256: attempt.ExpectedBodySHA256}
}
// CreateAttempt writes an exclusive initial record before any remote effect.
func CreateAttempt(ctx context.Context, repositoryDir, override string, attempt Attempt) (*Store, error) {
if err := validateManifestStructure(attempt.Manifest); err != nil {
return nil, err
}
if attempt.TagObject != "" && !git.ValidObjectID(attempt.TagObject) {
return nil, errors.New("invalid rehearsal tag object")
}
if err := git.CheckTagRef(ctx, repositoryDir, attempt.Manifest.Tag); err != nil {
return nil, err
}
dir, root, err := recordstore.ResolveDir(ctx, repositoryDir, override, "rehearsals")
if err != nil {
return nil, err
}
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, fmt.Errorf("create rehearsal record directory: %w", err)
}
filename := filepath.Join(dir, attempt.Manifest.AttemptID+".json")
if override != "" {
if err := recordstore.CheckPath(ctx, repositoryDir, root, filename); err != nil {
return nil, err
}
}
if attempt.CreatedAt == "" {
attempt.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
}
attempt.UpdatedAt = attempt.CreatedAt
data, err := encodeAttempt(attempt)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return nil, fmt.Errorf("create rehearsal record: %w", err)
}
if _, err = file.Write(data); err != nil {
_ = file.Close()
_ = os.Remove(filename)
return nil, fmt.Errorf("write rehearsal record: %w", err)
}
if err = file.Close(); err != nil {
_ = os.Remove(filename)
return nil, fmt.Errorf("close rehearsal record: %w", err)
}
return &Store{Path: filename, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject}, nil
}
// OpenStore selects a previously recorded attempt explicitly.
func OpenStore(path string) (*Store, Attempt, error) {
absolute, err := filepath.Abs(path)
if err != nil {
return nil, Attempt{}, err
}
attempt, err := LoadAttempt(absolute)
if err != nil {
return nil, Attempt{}, err
}
return &Store{Path: absolute, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject}, attempt, nil
}
// Save atomically replaces one attempt record after an observation or intent.
func (store *Store) Save(attempt Attempt) (resultErr error) {
store.mu.Lock()
defer store.mu.Unlock()
if !reflect.DeepEqual(attempt.Manifest, store.manifest) {
return errors.New("rehearsal record identity cannot change")
}
if identityOf(attempt) != store.identity {
return errors.New("rehearsal destinations cannot change")
}
if store.tagObject != "" && attempt.TagObject != store.tagObject {
return errors.New("rehearsal tag object cannot change")
}
if attempt.TagObject != "" && !git.ValidObjectID(attempt.TagObject) {
return errors.New("invalid rehearsal tag object")
}
if attempt.CreatedAt != "" && attempt.CreatedAt != store.createdAt {
return errors.New("rehearsal creation time cannot change")
}
attempt.CreatedAt = store.createdAt
attempt.UpdatedAt = time.Now().UTC().Format(time.RFC3339Nano)
data, err := encodeAttempt(attempt)
if err != nil {
return err
}
file, err := os.CreateTemp(filepath.Dir(store.Path), ".rehearsal-*")
if err != nil {
return fmt.Errorf("create temporary rehearsal record: %w", err)
}
temp := file.Name()
defer func() {
if err := os.Remove(temp); err != nil && !errors.Is(err, os.ErrNotExist) {
resultErr = errors.Join(resultErr, err)
}
}()
if _, err = file.Write(data); err != nil {
_ = file.Close()
return fmt.Errorf("write rehearsal record: %w", err)
}
if err = file.Close(); err != nil {
return fmt.Errorf("close rehearsal record: %w", err)
}
if err := os.Rename(temp, store.Path); err != nil {
return fmt.Errorf("replace rehearsal record: %w", err)
}
store.tagObject = attempt.TagObject
return nil
}

View File

@@ -0,0 +1,120 @@
package rehearsal
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func TestAttemptStoreSerializesConcurrentUpdates(t *testing.T) {
repo, profile, _, identity, attemptID := rehearsalFixture(t)
attempt := Attempt{Manifest: NewManifest(identity, attemptID, "root", "releasekit.json", profile), RepositoryDir: repo}
store, err := CreateAttempt(t.Context(), repo, "", attempt)
if err != nil {
t.Fatal(err)
}
var wait sync.WaitGroup
for _, outcome := range []string{"first", "second", "third"} {
wait.Add(1)
go func() {
defer wait.Done()
copy := attempt
copy.Outcomes = map[string]string{"observation": outcome}
if err := store.Save(copy); err != nil {
t.Errorf("save %s: %v", outcome, err)
}
}()
}
wait.Wait()
loaded, err := LoadAttempt(store.Path)
if err != nil || loaded.Outcomes["observation"] == "" {
t.Fatalf("loaded=%+v error=%v", loaded, err)
}
}
func TestIndependentAttemptsUseSeparateRecords(t *testing.T) {
repo, profile, source, identity, firstID := rehearsalFixture(t)
secondIdentity, secondID, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", identity.Commit)
if err != nil {
t.Fatal(err)
}
first, err := CreateAttempt(t.Context(), repo, "", Attempt{Manifest: NewManifest(identity, firstID, "root", "releasekit.json", profile)})
if err != nil {
t.Fatal(err)
}
second, err := CreateAttempt(t.Context(), repo, "", Attempt{Manifest: NewManifest(secondIdentity, secondID, "root", "releasekit.json", profile)})
if err != nil {
t.Fatal(err)
}
if first.Path == second.Path {
t.Fatalf("attempts share record %q", first.Path)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = CreateAttempt(ctx, repo, "", Attempt{Manifest: NewManifest(identity, firstID, "root", "releasekit.json", profile)})
if !errors.Is(err, context.Canceled) {
t.Fatalf("canceled create error = %v", err)
}
}
func TestAttemptRecordPreservesIdentityAndUpdates(t *testing.T) {
repo, profile, _, identity, attemptID := rehearsalFixture(t)
raw := string([]byte{'x', 0xff, 'y'})
attempt := Attempt{Manifest: NewManifest(identity, attemptID, "root", "releasekit.json", profile), RepositoryDir: repo, Endpoint: raw, Remote: "origin", ExpectedPageTitle: "diagnostic", Outcomes: map[string]string{"tag": "planned"}}
store, err := CreateAttempt(t.Context(), repo, "", attempt)
if err != nil {
t.Fatal(err)
}
if filepath.Base(store.Path) != attemptID+".json" {
t.Fatalf("record path = %q", store.Path)
}
info, err := os.Stat(store.Path)
if err != nil || info.Mode().Perm()&0077 != 0 {
t.Fatalf("record permissions = %v, error=%v", info, err)
}
if _, err := CreateAttempt(t.Context(), repo, "", attempt); !errors.Is(err, os.ErrExist) {
t.Fatalf("collision error = %v", err)
}
attempt.Outcomes["tag"] = "created"
attempt.TagObject = strings.Repeat("a", 40)
if err := store.Save(attempt); err != nil {
t.Fatal(err)
}
_, loaded, err := OpenStore(store.Path)
if err != nil || loaded.Endpoint != raw || loaded.Outcomes["tag"] != "created" || loaded.TagObject != attempt.TagObject || loaded.CreatedAt == "" || loaded.UpdatedAt == "" {
t.Fatalf("loaded=%+v error=%v", loaded, err)
}
changed := loaded
changed.Endpoint = "other"
if err := store.Save(changed); err == nil {
t.Fatal("accepted changed destination")
}
changed = loaded
changed.Manifest.Tag = "other"
if err := store.Save(changed); err == nil {
t.Fatal("accepted changed manifest")
}
changed = loaded
changed.TagObject = strings.Repeat("b", 40)
if err := store.Save(changed); err == nil {
t.Fatal("accepted changed tag object")
}
reloaded, err := LoadAttempt(store.Path)
if err != nil || reloaded.Endpoint != raw || reloaded.TagObject != attempt.TagObject {
t.Fatalf("record changed after rejected update: %+v %v", reloaded, err)
}
}
func TestAttemptRecordRejectsUnignoredWorktreeLocation(t *testing.T) {
repo, profile, _, identity, attempt := rehearsalFixture(t)
_, err := CreateAttempt(t.Context(), repo, "records", Attempt{Manifest: NewManifest(identity, attempt, "root", "releasekit.json", profile)})
if err == nil || !strings.Contains(err.Error(), "not ignored") {
t.Fatalf("record error = %v", err)
}
}