Observe rehearsal resources and support safe cleanup
This commit is contained in:
@@ -63,6 +63,13 @@ func runValidate(ctx context.Context, invocation cli.Invocation, output io.Write
|
||||
for _, operation := range invocation.Operations {
|
||||
request.Operations = append(request.Operations, releasekit.ReadinessOperation(operation))
|
||||
}
|
||||
for _, operation := range invocation.Operations {
|
||||
if operation == "rehearsal" && settings.Rehearsal != nil && settings.Rehearsal.Woodpecker != nil {
|
||||
wood := settings.Rehearsal.Woodpecker
|
||||
token, _, credentialErr := cli.ResolveWoodpeckerCredential(root, wood)
|
||||
request.Woodpecker = &releasekit.WoodpeckerObservation{BaseURL: wood.BaseURL, RepositoryID: wood.RepositoryID, Workflow: wood.Workflow, Step: wood.Step, Token: token, CredentialError: credentialErr}
|
||||
}
|
||||
}
|
||||
if settings.Readiness != nil {
|
||||
request.RequiredFiles = append([]string(nil), settings.Readiness.RequiredFiles...)
|
||||
}
|
||||
|
||||
@@ -244,3 +244,36 @@ func TestValidateRejectsInconsistentSourceSelection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRehearsalObservesWoodpeckerWithSeparateLocalCredential(t *testing.T) {
|
||||
repo, _ := newSimplePublishRepository(t, false)
|
||||
state := &deliveryServerState{}
|
||||
forgeServer := newDeliveryServer(t, state)
|
||||
defer forgeServer.Close()
|
||||
calls := 0
|
||||
ciServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/repos/42" || r.Header.Get("Authorization") != "Bearer woodpecker-private-value" {
|
||||
t.Errorf("unexpected Woodpecker request %s %s", r.Method, r.URL.Path)
|
||||
http.Error(w, "invalid", 400)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"id":42}`)
|
||||
}))
|
||||
defer ciServer.Close()
|
||||
writeRepositoryFile(t, repo, "forge-token", "fixture-token\n")
|
||||
writeRepositoryFile(t, repo, "ci-token", "woodpecker-private-value\n")
|
||||
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"local":{"token_file":"forge-token"}}},"rehearsal":{"woodpecker":{"base_url":%q,"repository_id":42,"workflow":"release","step":"deliver","token_file":"ci-token"}}}`, forgeServer.URL, ciServer.URL)
|
||||
writeRepositoryFile(t, repo, "releasekit.json", profile)
|
||||
var output bytes.Buffer
|
||||
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "rehearsal", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 0 || calls != 1 || !strings.Contains(output.String(), `"id":"woodpecker-access","operation":"rehearsal","status":"passed"`) || strings.Contains(output.String(), "woodpecker-private-value") || strings.Contains(output.String(), "fixture-token") {
|
||||
t.Fatalf("status=%d calls=%d report=%s", status, calls, output.String())
|
||||
}
|
||||
output.Reset()
|
||||
calls = 0
|
||||
status = run(context.Background(), []string{"validate", "--repo", repo, "--operation", "rehearsal", "--offline", "--json"}, &output, &bytes.Buffer{})
|
||||
if status != 0 || calls != 0 || !strings.Contains(output.String(), `"id":"woodpecker-access","operation":"rehearsal","status":"unchecked","reason":"offline"`) {
|
||||
t.Fatalf("offline status=%d calls=%d report=%s", status, calls, output.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||
// The workflow builds the tagged CLI, including changes under test that may
|
||||
// not yet be committed in the repository from which this fixture was cloned.
|
||||
files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "internal/readiness/readiness.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go"}
|
||||
files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "internal/readiness/readiness.go", "internal/woodpecker/client.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go"}
|
||||
for _, name := range files {
|
||||
contents, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name)))
|
||||
if err != nil {
|
||||
|
||||
@@ -23,6 +23,11 @@ checks. Local publication readiness also checks Git's configured tagger
|
||||
identity. Native Git and SSH authentication remain in use; no conventional
|
||||
private-key filename is required.
|
||||
|
||||
Rehearsal readiness also checks read access to the configured Woodpecker
|
||||
repository using the separate local Woodpecker token file. Offline validation
|
||||
checks the local settings but leaves that remote observation unchecked; it
|
||||
does not read or register CI job secrets.
|
||||
|
||||
To require a specific local input, list it in `readiness.required_files` in the
|
||||
profile. Paths are literal repository-root-relative or absolute filenames. This
|
||||
checks readability, not Git authentication. `--assets DIR` selects an existing
|
||||
|
||||
@@ -59,6 +59,7 @@ reports these implemented packages:
|
||||
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. |
|
||||
| `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. |
|
||||
| `internal/versioncontract` | Shared stable-version rules and linker-symbol identity. |
|
||||
| `internal/woodpecker` | Authenticated read-only CI repository, pipeline, workflow, step, and streamed log observation. |
|
||||
|
||||
The `buildinfo` facade depends only on its small runtime implementation. The
|
||||
root facade forwards to internal implementation packages. The CLI adapter is
|
||||
|
||||
@@ -510,6 +510,14 @@ and partial records after uncertain writes.
|
||||
|
||||
## Stage 10: Add Woodpecker observation and diagnostic forge effects
|
||||
|
||||
**Completed:** Read-only Woodpecker observation follows pipeline pages,
|
||||
correlates exact tag events and commits, retains workflow and step identities,
|
||||
and streams job logs. Rehearsal readiness checks repository access with the
|
||||
separate local credential. Diagnostic forge and Git operations preserve stable
|
||||
resource identities, conditional tag deletion, and uncertain-write evidence.
|
||||
Local HTTP and Git fixture tests, the offline `go test ./...` suite, and the
|
||||
compiled API/dependency check pass.
|
||||
|
||||
**Work:** implement an internal Woodpecker client and extend internal forge/Git
|
||||
boundaries with the effects needed for recorded diagnostics.
|
||||
|
||||
|
||||
17
internal/forge/diagnostic.go
Normal file
17
internal/forge/diagnostic.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package forge
|
||||
|
||||
import "context"
|
||||
|
||||
// DiagnosticBackend supports observation and deletion of recorded temporary
|
||||
// releases. Callers must establish ownership before asking for deletion.
|
||||
type DiagnosticBackend interface {
|
||||
FindDiagnosticRelease(context.Context, string) (DiagnosticRelease, error)
|
||||
ObserveDiagnosticRelease(context.Context, int64) (DiagnosticRelease, error)
|
||||
DeleteDiagnosticRelease(context.Context, int64, string) (WriteEvidence, error)
|
||||
}
|
||||
|
||||
// DiagnosticRelease carries a stable remote ID and the normal observed handle.
|
||||
type DiagnosticRelease struct {
|
||||
ID int64
|
||||
Release Release
|
||||
}
|
||||
80
internal/git/diagnostic.go
Normal file
80
internal/git/diagnostic.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func checkDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
|
||||
if !strings.HasPrefix(tag, "releasekit-test/") || !ValidObjectID(object) || !ValidObjectID(commit) {
|
||||
return errors.New("a diagnostic tag and exact tag object and commit are required")
|
||||
}
|
||||
return CheckTagRef(ctx, repo, tag)
|
||||
}
|
||||
|
||||
// PushDiagnosticTag publishes a verified local diagnostic object without
|
||||
// moving a conflicting remote ref. Callers reconcile an error by observation.
|
||||
func (endpoint Endpoint) PushDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
|
||||
if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil {
|
||||
return err
|
||||
}
|
||||
local, err := ReadAnnotatedTag(ctx, repo, tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !EqualObjectID(local.Object, object) || !EqualObjectID(local.Commit, commit) {
|
||||
return errors.New("local diagnostic tag differs from recorded object or commit")
|
||||
}
|
||||
remote, err := endpoint.QueryTag(ctx, repo, tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if remote.State == RefPresent && EqualObjectID(remote.Object, object) && EqualObjectID(remote.Peeled, commit) {
|
||||
return nil
|
||||
}
|
||||
if remote.State != RefAbsent {
|
||||
return fmt.Errorf("diagnostic tag already exists with different evidence: %w", ErrRemoteTagConflict)
|
||||
}
|
||||
return endpoint.PushTag(ctx, repo, tag, object)
|
||||
}
|
||||
|
||||
// DeleteDiagnosticTag deletes only the recorded remote annotated tag object.
|
||||
// A failed push remains uncertain; callers must query the endpoint again.
|
||||
func (endpoint Endpoint) DeleteDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
|
||||
if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil {
|
||||
return err
|
||||
}
|
||||
observed, err := endpoint.QueryTag(ctx, repo, tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if observed.State == RefAbsent {
|
||||
return nil
|
||||
}
|
||||
if observed.State != RefPresent || !EqualObjectID(observed.Object, object) || !EqualObjectID(observed.Peeled, commit) {
|
||||
return fmt.Errorf("diagnostic tag differs from recorded object or commit: %w", ErrRemoteTagConflict)
|
||||
}
|
||||
ref := "refs/tags/" + tag
|
||||
if _, err := run(ctx, repo, endpoint.scopedConfig(), "push", "--no-follow-tags", "--recurse-submodules=no", "--porcelain", "--force-with-lease="+ref+":"+object, endpoint.ScopedName, ":"+ref); err != nil {
|
||||
return fmt.Errorf("delete diagnostic tag %s at %s: %w", tag, DisplayURL(endpoint.PushURL), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteLocalDiagnosticTag uses Git's atomic expected-old-object check.
|
||||
func DeleteLocalDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
|
||||
if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil {
|
||||
return err
|
||||
}
|
||||
observed, err := ReadAnnotatedTag(ctx, repo, tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !EqualObjectID(observed.Object, object) || !EqualObjectID(observed.Commit, commit) {
|
||||
return errors.New("local diagnostic tag differs from recorded object or commit")
|
||||
}
|
||||
_, err = run(ctx, repo, nil, "update-ref", "-d", "refs/tags/"+tag, object)
|
||||
return err
|
||||
}
|
||||
43
internal/git/diagnostic_test.go
Normal file
43
internal/git/diagnostic_test.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiagnosticTagDeletionRequiresRecordedObjectAndCommit(t *testing.T) {
|
||||
fixture := newRemoteFixture(t)
|
||||
ctx := t.Context()
|
||||
endpoint, err := Resolve(ctx, fixture.work, "origin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tag := "releasekit-test/root/" + strings.Repeat("a", 32)
|
||||
object, err := CreateAnnotatedTag(ctx, fixture.work, tag, fixture.commit, []byte("diagnostic\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := endpoint.PushDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := endpoint.PushDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
|
||||
t.Fatalf("identical push: %v", err)
|
||||
}
|
||||
if err := endpoint.DeleteDiagnosticTag(ctx, fixture.work, tag, object, strings.Repeat("b", 40)); !errors.Is(err, ErrRemoteTagConflict) {
|
||||
t.Fatalf("incorrect commit error=%v", err)
|
||||
}
|
||||
if err := DeleteLocalDiagnosticTag(ctx, fixture.work, tag, strings.Repeat("b", 40), fixture.commit); err == nil {
|
||||
t.Fatal("deleted tag with incorrect object")
|
||||
}
|
||||
if err := endpoint.DeleteDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, err := endpoint.QueryTag(ctx, fixture.work, tag)
|
||||
if err != nil || ref.State != RefAbsent {
|
||||
t.Fatalf("remote=%+v error=%v", ref, err)
|
||||
}
|
||||
if err := DeleteLocalDiagnosticTag(ctx, fixture.work, tag, object, fixture.commit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
77
internal/gitea/diagnostic.go
Normal file
77
internal/gitea/diagnostic.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
)
|
||||
|
||||
func (b *Backend) FindDiagnosticRelease(ctx context.Context, tag string) (forge.DiagnosticRelease, error) {
|
||||
release, err := b.FindRelease(ctx, tag)
|
||||
if err != nil {
|
||||
return forge.DiagnosticRelease{}, err
|
||||
}
|
||||
handle, err := assetReleaseHandle(release.Handle)
|
||||
if err != nil {
|
||||
return forge.DiagnosticRelease{}, err
|
||||
}
|
||||
if release.Tag != tag {
|
||||
return forge.DiagnosticRelease{}, &forge.Failure{Kind: forge.FailureMalformed, Err: errors.New("release response does not match requested tag")}
|
||||
}
|
||||
return forge.DiagnosticRelease{ID: handle.id, Release: release}, nil
|
||||
}
|
||||
func (b *Backend) ObserveDiagnosticRelease(ctx context.Context, id int64) (forge.DiagnosticRelease, error) {
|
||||
if id <= 0 {
|
||||
return forge.DiagnosticRelease{}, &forge.Failure{Kind: forge.FailureInvalid, Err: errors.New("release ID must be positive")}
|
||||
}
|
||||
_, root, err := b.destinationAPI("observe diagnostic release")
|
||||
if err != nil {
|
||||
return forge.DiagnosticRelease{}, err
|
||||
}
|
||||
observed, _, err := b.client.getRelease(ctx, b.client.httpClient(), b.destination.Token, root+"/releases/"+strconv.FormatInt(id, 10))
|
||||
if err != nil {
|
||||
return forge.DiagnosticRelease{}, neutralFailure(err)
|
||||
}
|
||||
if observed.ID != id || observed.TagName == "" {
|
||||
return forge.DiagnosticRelease{}, &forge.Failure{Kind: forge.FailureMalformed, Err: errors.New("release response does not match requested ID")}
|
||||
}
|
||||
return forge.DiagnosticRelease{ID: id, Release: forge.Release{URL: observed.URL, Tag: observed.TagName, Title: observed.Title, Body: observed.Body, Draft: observed.Draft, Prerelease: observed.Prerelease, Handle: releaseHandle{id: id}}}, nil
|
||||
}
|
||||
func (b *Backend) DeleteDiagnosticRelease(ctx context.Context, id int64, tag string) (forge.WriteEvidence, error) {
|
||||
notAttempted := forge.WriteEvidence{Disposition: forge.WriteNotAttempted}
|
||||
if id <= 0 || !strings.HasPrefix(tag, "releasekit-test/") {
|
||||
return notAttempted, &forge.Failure{Kind: forge.FailureInvalid, Err: errors.New("diagnostic tag and positive release ID are required")}
|
||||
}
|
||||
observed, err := b.ObserveDiagnosticRelease(ctx, id)
|
||||
if err != nil {
|
||||
return notAttempted, err
|
||||
}
|
||||
if observed.Release.Tag != tag {
|
||||
return notAttempted, &forge.Failure{Kind: forge.FailureConflict, Err: errors.New("release ID belongs to a different tag")}
|
||||
}
|
||||
_, root, err := b.destinationAPI("delete diagnostic release")
|
||||
if err != nil {
|
||||
return notAttempted, err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, root+"/releases/"+strconv.FormatInt(id, 10), nil)
|
||||
if err != nil {
|
||||
return notAttempted, &forge.Failure{Kind: forge.FailureInvalid, Err: err}
|
||||
}
|
||||
request.Header.Set("Authorization", "token "+b.destination.Token)
|
||||
request.Header.Set("Accept", "application/json")
|
||||
response, err := b.client.httpClient().Do(request)
|
||||
if err != nil {
|
||||
failure := failure(FailureTransport, "delete diagnostic release", 0, err)
|
||||
return writeEvidence(0, failure), neutralFailure(failure)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
err := responseFailure("delete diagnostic release", response.StatusCode)
|
||||
return writeEvidence(response.StatusCode, err), neutralFailure(err)
|
||||
}
|
||||
return forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}, nil
|
||||
}
|
||||
75
internal/gitea/diagnostic_test.go
Normal file
75
internal/gitea/diagnostic_test.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
)
|
||||
|
||||
func TestDiagnosticReleaseObservationAndDeletion(t *testing.T) {
|
||||
tag := "releasekit-test/root/" + strings.Repeat("a", 32)
|
||||
deleted := false
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "token private" {
|
||||
t.Error("missing token")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/api/v1/repos/owner/repo/releases/23" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
fmt.Fprintf(w, `{"id":23,"tag_name":%q,"name":"test","body":"temporary"}`, tag)
|
||||
case "DELETE":
|
||||
deleted = true
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
t.Errorf("unexpected method %s", r.Method)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
backend := NewBackend(Destination{BaseURL: server.URL, Owner: "owner", Repository: "repo", Token: "private"}, nil)
|
||||
observed, err := backend.ObserveDiagnosticRelease(context.Background(), 23)
|
||||
if err != nil || observed.ID != 23 || observed.Release.Tag != tag {
|
||||
t.Fatalf("observed=%+v error=%v", observed, err)
|
||||
}
|
||||
evidence, err := backend.DeleteDiagnosticRelease(context.Background(), 23, "releasekit-test/root/foreign")
|
||||
var failure *forge.Failure
|
||||
if !errors.As(err, &failure) || failure.Kind != forge.FailureConflict || evidence.Attempted || deleted {
|
||||
t.Fatalf("conflict evidence=%+v error=%v", evidence, err)
|
||||
}
|
||||
evidence, err = backend.DeleteDiagnosticRelease(context.Background(), 23, tag)
|
||||
if err != nil || !deleted || evidence.Disposition != forge.WriteAccepted {
|
||||
t.Fatalf("delete evidence=%+v error=%v", evidence, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnosticReleaseDeletionReportsLostAcknowledgmentAsUncertain(t *testing.T) {
|
||||
tag := "releasekit-test/root/" + strings.Repeat("a", 32)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
fmt.Fprintf(w, `{"id":23,"tag_name":%q}`, tag)
|
||||
return
|
||||
}
|
||||
conn, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
conn.Close()
|
||||
}))
|
||||
defer server.Close()
|
||||
backend := NewBackend(Destination{BaseURL: server.URL, Owner: "owner", Repository: "repo", Token: "private"}, nil)
|
||||
evidence, err := backend.DeleteDiagnosticRelease(t.Context(), 23, tag)
|
||||
if err == nil || !evidence.Attempted || evidence.Disposition != forge.WriteUncertain || strings.Contains(err.Error(), "private") {
|
||||
t.Fatalf("evidence=%+v error=%v", evidence, err)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ type Request struct {
|
||||
DeliveryConfig func() error
|
||||
Credential func() error
|
||||
Delivery func(context.Context) error
|
||||
RehearsalConfig func() error
|
||||
Rehearsal func(context.Context) error
|
||||
Prebuilt func(context.Context, releaseidentity.ResolvedSource) error
|
||||
}
|
||||
|
||||
@@ -227,12 +229,18 @@ func Run(ctx context.Context, request Request) Report {
|
||||
}
|
||||
if selected["rehearsal"] {
|
||||
report.note("ci-secret-injection", "rehearsal", "unchecked", "not_executed", "CI job secret injection requires job evidence")
|
||||
if request.Offline {
|
||||
configOK := false
|
||||
if request.HasRehearsal && request.RehearsalConfig != nil {
|
||||
configOK = report.record("woodpecker-settings", "rehearsal", "configuration", request.RehearsalConfig())
|
||||
}
|
||||
if !configOK {
|
||||
report.note("woodpecker-access", "rehearsal", "skipped", "dependency", "rehearsal settings unavailable")
|
||||
} else if request.Offline {
|
||||
report.note("woodpecker-access", "rehearsal", "unchecked", "offline", "Woodpecker access not checked in offline mode")
|
||||
} else if request.HasRehearsal {
|
||||
} else if request.Rehearsal == nil {
|
||||
report.note("woodpecker-access", "rehearsal", "unchecked", "unavailable", "Woodpecker observation is unavailable")
|
||||
} else {
|
||||
report.note("woodpecker-access", "rehearsal", "skipped", "dependency", "rehearsal settings unavailable")
|
||||
report.record("woodpecker-access", "rehearsal", "remote", request.Rehearsal(ctx))
|
||||
}
|
||||
}
|
||||
return report
|
||||
|
||||
262
internal/woodpecker/client.go
Normal file
262
internal/woodpecker/client.go
Normal file
@@ -0,0 +1,262 @@
|
||||
// Package woodpecker observes Woodpecker repositories and diagnostic pipelines.
|
||||
package woodpecker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
)
|
||||
|
||||
// Client borrows its HTTP client and carries a separate observation credential.
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
RepositoryID int64
|
||||
Token string
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
type Pipeline struct {
|
||||
ID int64 `json:"id"`
|
||||
Number int64 `json:"number"`
|
||||
Event string `json:"event"`
|
||||
Ref string `json:"ref"`
|
||||
Commit string `json:"commit"`
|
||||
Status string `json:"status"`
|
||||
Workflows []Workflow `json:"workflows"`
|
||||
}
|
||||
type Workflow struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Steps []Step `json:"children"`
|
||||
}
|
||||
type Step struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// Error carries the status without exposing response bodies or credentials.
|
||||
type Error struct {
|
||||
Operation string
|
||||
Status int
|
||||
Cause error
|
||||
}
|
||||
|
||||
// ValidateConfiguration checks the selected endpoint and credential locally.
|
||||
func (c Client) ValidateConfiguration() error {
|
||||
_, err := c.endpoint("")
|
||||
return err
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Status != 0 {
|
||||
return fmt.Sprintf("woodpecker %s: HTTP %d", e.Operation, e.Status)
|
||||
}
|
||||
if e.Cause != nil {
|
||||
return fmt.Sprintf("woodpecker %s: %v", e.Operation, e.Cause)
|
||||
}
|
||||
return "woodpecker " + e.Operation
|
||||
}
|
||||
func (e *Error) Unwrap() error { return e.Cause }
|
||||
|
||||
func (c Client) endpoint(suffix string) (string, error) {
|
||||
u, err := url.Parse(c.BaseURL)
|
||||
if err != nil || u == nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", errors.New("Woodpecker base URL must be an absolute HTTP(S) URL without credentials, query, or fragment")
|
||||
}
|
||||
if c.RepositoryID <= 0 {
|
||||
return "", errors.New("Woodpecker repository ID must be positive")
|
||||
}
|
||||
if strings.TrimSpace(c.Token) == "" {
|
||||
return "", errors.New("Woodpecker token is required")
|
||||
}
|
||||
u.Path = strings.TrimRight(u.Path, "/") + "/api/repos/" + strconv.FormatInt(c.RepositoryID, 10) + suffix
|
||||
u.RawPath = ""
|
||||
return u.String(), nil
|
||||
}
|
||||
func (c Client) open(ctx context.Context, operation, suffix string, query url.Values) (io.ReadCloser, error) {
|
||||
endpoint, err := c.endpoint(suffix)
|
||||
if err != nil {
|
||||
return nil, &Error{Operation: operation, Cause: err}
|
||||
}
|
||||
if len(query) > 0 {
|
||||
endpoint += "?" + query.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, &Error{Operation: operation, Cause: err}
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
client := http.DefaultClient
|
||||
if c.HTTPClient != nil {
|
||||
client = c.HTTPClient
|
||||
}
|
||||
copyClient := *client
|
||||
copyClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
resp, err := copyClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, &Error{Operation: operation, Cause: err}
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
resp.Body.Close()
|
||||
return nil, &Error{Operation: operation, Status: resp.StatusCode}
|
||||
}
|
||||
return resp.Body, nil
|
||||
}
|
||||
func (c Client) read(ctx context.Context, operation, suffix string, query url.Values, value any) error {
|
||||
body, err := c.open(ctx, operation, suffix, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer body.Close()
|
||||
dec := json.NewDecoder(body)
|
||||
if err := dec.Decode(value); err != nil {
|
||||
return &Error{Operation: operation, Cause: fmt.Errorf("invalid response: %w", err)}
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return &Error{Operation: operation, Cause: errors.New("invalid trailing response data")}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckRepository verifies authenticated read access to the configured repository.
|
||||
func (c Client) CheckRepository(ctx context.Context) error {
|
||||
var repository struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
if err := c.read(ctx, "read repository", "", nil, &repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if repository.ID != c.RepositoryID {
|
||||
return &Error{Operation: "read repository", Cause: errors.New("repository response does not match configured ID")}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MatchingPipelines follows every page and matches exact tag event, ref and commit.
|
||||
func (c Client) MatchingPipelines(ctx context.Context, tag, commit string) ([]Pipeline, error) {
|
||||
if !git.ValidObjectID(commit) || tag == "" {
|
||||
return nil, errors.New("exact tag and full commit are required")
|
||||
}
|
||||
var matches []Pipeline
|
||||
seen := map[int64]bool{}
|
||||
for page := 1; ; page++ {
|
||||
query := url.Values{"page": {strconv.Itoa(page)}, "perPage": {"50"}, "event": {"tag"}, "ref": {"refs/tags/" + tag}}
|
||||
var items []Pipeline
|
||||
if err := c.read(ctx, "list pipelines", "/pipelines", query, &items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
return nil, &Error{Operation: "list pipelines", Cause: errors.New("pipeline response must be an array")}
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return matches, nil
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.ID <= 0 || item.Number <= 0 || item.Ref == "" || item.Commit == "" || item.Event == "" || item.Status == "" {
|
||||
return nil, &Error{Operation: "list pipelines", Cause: errors.New("pipeline response omits required identity")}
|
||||
}
|
||||
if seen[item.ID] {
|
||||
return nil, &Error{Operation: "list pipelines", Cause: errors.New("pagination repeated a pipeline")}
|
||||
}
|
||||
seen[item.ID] = true
|
||||
if item.Event == "tag" && item.Ref == "refs/tags/"+tag && git.EqualObjectID(item.Commit, commit) {
|
||||
matches = append(matches, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Job identifies one exact matching workflow and step, including reruns or
|
||||
// matrix jobs. Unknown states remain unknown rather than becoming success.
|
||||
type Job struct {
|
||||
PipelineID, PipelineNumber, WorkflowID, StepID int64
|
||||
PipelineStatus, WorkflowState, StepState string
|
||||
}
|
||||
|
||||
// Jobs finds every named step in the requested named workflow.
|
||||
func (p Pipeline) Jobs(workflow, step string) ([]Job, error) {
|
||||
if workflow == "" || step == "" || p.ID <= 0 || p.Number <= 0 {
|
||||
return nil, errors.New("pipeline, workflow, and step identity are required")
|
||||
}
|
||||
var jobs []Job
|
||||
for _, w := range p.Workflows {
|
||||
if w.Name != workflow {
|
||||
continue
|
||||
}
|
||||
if w.ID <= 0 || w.State == "" {
|
||||
return nil, errors.New("workflow response omits identity or state")
|
||||
}
|
||||
for _, s := range w.Steps {
|
||||
if s.Name != step {
|
||||
continue
|
||||
}
|
||||
if s.ID <= 0 || s.State == "" {
|
||||
return nil, errors.New("step response omits identity or state")
|
||||
}
|
||||
jobs = append(jobs, Job{PipelineID: p.ID, PipelineNumber: p.Number, WorkflowID: w.ID, StepID: s.ID, PipelineStatus: p.Status, WorkflowState: w.State, StepState: s.State})
|
||||
}
|
||||
}
|
||||
if len(jobs) == 0 {
|
||||
return nil, errors.New("configured workflow and step are absent from pipeline")
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// Pipeline retrieves one exact numbered pipeline, including workflow and step IDs.
|
||||
func (c Client) Pipeline(ctx context.Context, number int64) (Pipeline, error) {
|
||||
if number <= 0 {
|
||||
return Pipeline{}, errors.New("pipeline number must be positive")
|
||||
}
|
||||
var p Pipeline
|
||||
if err := c.read(ctx, "read pipeline", "/pipelines/"+strconv.FormatInt(number, 10), nil, &p); err != nil {
|
||||
return Pipeline{}, err
|
||||
}
|
||||
if p.ID <= 0 || p.Number != number || p.Event == "" || p.Ref == "" || p.Commit == "" || p.Status == "" {
|
||||
return Pipeline{}, &Error{Operation: "read pipeline", Cause: errors.New("pipeline response omits required identity")}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// DiagnosticPipeline binds a detail response to the exact event being tracked.
|
||||
func (c Client) DiagnosticPipeline(ctx context.Context, number int64, tag, commit string) (Pipeline, error) {
|
||||
p, err := c.Pipeline(ctx, number)
|
||||
if err != nil {
|
||||
return Pipeline{}, err
|
||||
}
|
||||
if tag == "" || p.Event != "tag" || p.Ref != "refs/tags/"+tag || !git.EqualObjectID(p.Commit, commit) {
|
||||
return Pipeline{}, &Error{Operation: "read pipeline", Cause: errors.New("pipeline does not match diagnostic tag and commit")}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// OpenLog returns a streaming log; the caller must close it.
|
||||
func (c Client) OpenLog(ctx context.Context, number, stepID int64) (io.ReadCloser, error) {
|
||||
if number <= 0 || stepID <= 0 {
|
||||
return nil, errors.New("pipeline number and step ID must be positive")
|
||||
}
|
||||
return c.open(ctx, "download step log", "/logs/"+strconv.FormatInt(number, 10)+"/"+strconv.FormatInt(stepID, 10)+"/download", nil)
|
||||
}
|
||||
|
||||
// StateClass distinguishes active, terminal and unrecognized server states.
|
||||
func StateClass(state string) string {
|
||||
switch state {
|
||||
case "pending", "running", "blocked", "created":
|
||||
return "active"
|
||||
case "success", "failure", "error", "killed", "skipped", "declined":
|
||||
return "terminal"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
114
internal/woodpecker/client_test.go
Normal file
114
internal/woodpecker/client_test.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package woodpecker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestObservationUsesExactIdentityAndFollowsPages(t *testing.T) {
|
||||
commit := strings.Repeat("a", 40)
|
||||
other := strings.Repeat("b", 40)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer separate-secret" {
|
||||
t.Error("missing observation credential")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/prefix/api/repos/7":
|
||||
fmt.Fprint(w, `{"id":7}`)
|
||||
case "/prefix/api/repos/7/pipelines":
|
||||
switch r.URL.Query().Get("page") {
|
||||
case "1":
|
||||
json.NewEncoder(w).Encode([]Pipeline{{ID: 1, Number: 3, Event: "tag", Ref: "refs/tags/target-extra", Commit: commit, Status: "success"}, {ID: 2, Number: 4, Event: "tag", Ref: "refs/tags/target", Commit: other, Status: "failure"}})
|
||||
case "2":
|
||||
json.NewEncoder(w).Encode([]Pipeline{{ID: 3, Number: 5, Event: "tag", Ref: "refs/tags/target", Commit: commit, Status: "running"}, {ID: 4, Number: 6, Event: "tag", Ref: "refs/tags/target", Commit: commit, Status: "success"}})
|
||||
default:
|
||||
fmt.Fprint(w, `[]`)
|
||||
}
|
||||
case "/prefix/api/repos/7/pipelines/6":
|
||||
fmt.Fprintf(w, `{"id":4,"number":6,"event":"tag","ref":"refs/tags/target","commit":%q,"status":"success","workflows":[{"id":12,"name":"release","state":"success","children":[{"id":99,"name":"deliver","state":"success"}]}]}`, commit)
|
||||
case "/prefix/api/repos/7/logs/6/99/download":
|
||||
fmt.Fprint(w, "result line\n")
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
c := Client{BaseURL: server.URL + "/prefix", RepositoryID: 7, Token: "separate-secret"}
|
||||
if err := c.CheckRepository(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pipelines, err := c.MatchingPipelines(t.Context(), "target", commit)
|
||||
if err != nil || len(pipelines) != 2 || pipelines[0].Number != 5 || pipelines[1].Number != 6 {
|
||||
t.Fatalf("pipelines=%+v err=%v", pipelines, err)
|
||||
}
|
||||
detail, err := c.DiagnosticPipeline(t.Context(), 6, "target", commit)
|
||||
if err != nil || len(detail.Workflows) != 1 || detail.Workflows[0].Steps[0].ID != 99 {
|
||||
t.Fatalf("pipeline=%+v err=%v", detail, err)
|
||||
}
|
||||
if _, err := c.DiagnosticPipeline(t.Context(), 6, "target", other); err == nil {
|
||||
t.Fatal("accepted a different pipeline commit")
|
||||
}
|
||||
stream, err := c.OpenLog(t.Context(), 6, 99)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stream.Close()
|
||||
text, err := io.ReadAll(stream)
|
||||
if err != nil || string(text) != "result line\n" {
|
||||
t.Fatalf("log=%q err=%v", text, err)
|
||||
}
|
||||
}
|
||||
func TestObservationHandlesFailuresAndDoesNotForwardCredential(t *testing.T) {
|
||||
var forwarded bool
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { forwarded = r.Header.Get("Authorization") != "" }))
|
||||
defer other.Close()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/repos/8":
|
||||
http.Redirect(w, r, other.URL, 302)
|
||||
case "/api/repos/8/pipelines":
|
||||
fmt.Fprint(w, `[{"id":1}]`)
|
||||
default:
|
||||
http.Error(w, "secret must not appear", 403)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
c := Client{BaseURL: server.URL, RepositoryID: 8, Token: "secret"}
|
||||
if err := c.CheckRepository(t.Context()); err == nil || forwarded || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("redirect error=%v forwarded=%v", err, forwarded)
|
||||
}
|
||||
if _, err := c.MatchingPipelines(t.Context(), "tag", strings.Repeat("a", 40)); err == nil {
|
||||
t.Fatal("accepted malformed response")
|
||||
}
|
||||
if _, err := c.Pipeline(t.Context(), 1); err == nil || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("rejected access error=%v", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if err := c.CheckRepository(ctx); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation error=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJobsPreserveMultipleMatchesAndUnknownStates(t *testing.T) {
|
||||
p := Pipeline{ID: 1, Number: 2, Status: "success", Workflows: []Workflow{{ID: 3, Name: "release", State: "success", Steps: []Step{{ID: 4, Name: "deliver", State: "success"}}}, {ID: 5, Name: "release", State: "running", Steps: []Step{{ID: 6, Name: "deliver", State: "new-server-state"}}}}}
|
||||
jobs, err := p.Jobs("release", "deliver")
|
||||
if err != nil || len(jobs) != 2 || jobs[1].WorkflowID != 5 || jobs[1].StepID != 6 {
|
||||
t.Fatalf("jobs=%+v error=%v", jobs, err)
|
||||
}
|
||||
if StateClass(jobs[0].StepState) != "terminal" || StateClass(jobs[1].StepState) != "unknown" || StateClass("running") != "active" {
|
||||
t.Fatal("unexpected state classification")
|
||||
}
|
||||
if _, err := p.Jobs("release", "missing"); err == nil {
|
||||
t.Fatal("accepted missing step")
|
||||
}
|
||||
}
|
||||
36
readiness.go
36
readiness.go
@@ -6,7 +6,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
"go.maximumdirect.net/releasekit/internal/readiness"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
||||
)
|
||||
|
||||
// ReadinessOperation selects an independent readiness capability.
|
||||
@@ -47,11 +47,12 @@ type ReadinessCredential struct {
|
||||
|
||||
// WoodpeckerObservation identifies the selected CI repository and credential.
|
||||
type WoodpeckerObservation struct {
|
||||
BaseURL string
|
||||
RepositoryID int64
|
||||
Workflow string
|
||||
Step string
|
||||
Token string
|
||||
BaseURL string
|
||||
RepositoryID int64
|
||||
Workflow string
|
||||
Step string
|
||||
Token string
|
||||
CredentialError error
|
||||
}
|
||||
|
||||
// ValidateRequest supplies working inputs and explicit credentials for a
|
||||
@@ -156,6 +157,20 @@ func Validate(ctx context.Context, request ValidateRequest) (ValidationReport, e
|
||||
return validateReadinessBuild(ctx, request, source)
|
||||
}
|
||||
}
|
||||
if request.Woodpecker != nil {
|
||||
observation := request.Woodpecker
|
||||
client := woodpecker.Client{BaseURL: observation.BaseURL, RepositoryID: observation.RepositoryID, Token: observation.Token}
|
||||
internalRequest.RehearsalConfig = func() error {
|
||||
if observation.CredentialError != nil {
|
||||
return observation.CredentialError
|
||||
}
|
||||
if strings.TrimSpace(observation.Workflow) == "" || strings.TrimSpace(observation.Step) == "" {
|
||||
return errors.New("rehearsal requires a Woodpecker workflow and step")
|
||||
}
|
||||
return client.ValidateConfiguration()
|
||||
}
|
||||
internalRequest.Rehearsal = client.CheckRepository
|
||||
}
|
||||
internal := readiness.Run(ctx, internalRequest)
|
||||
report := ValidationReport{InputSource: "working", RepositoryDir: internal.RepositoryDir, Operations: operations, Context: request.Context, Offline: request.Offline, GitDestination: internal.GitDestination, Credentials: append([]ReadinessCredential(nil), request.Credentials...)}
|
||||
if request.Destination != nil {
|
||||
@@ -191,15 +206,6 @@ func Validate(ctx context.Context, request ValidateRequest) (ValidationReport, e
|
||||
causes = append(causes, err)
|
||||
}
|
||||
}
|
||||
if seen[ReadinessRehearsal] && request.Woodpecker != nil {
|
||||
observation := request.Woodpecker
|
||||
base, err := url.Parse(observation.BaseURL)
|
||||
if err != nil || base == nil || (base.Scheme != "http" && base.Scheme != "https") || base.Host == "" || observation.RepositoryID <= 0 || strings.TrimSpace(observation.Workflow) == "" || strings.TrimSpace(observation.Step) == "" || strings.TrimSpace(observation.Token) == "" {
|
||||
err := errors.New("rehearsal requires a valid Woodpecker URL, repository ID, workflow, step, and token")
|
||||
report.Checks = append(report.Checks, ReadinessResult{ID: "woodpecker-settings", Operation: ReadinessRehearsal, Status: ReadinessFailed, Reason: "configuration", Message: err.Error(), Cause: err})
|
||||
causes = append(causes, err)
|
||||
}
|
||||
}
|
||||
if request.Output != nil {
|
||||
if _, err := fmt.Fprintf(request.Output, "readiness source=working context=%s offline=%t\n", request.Context, request.Offline); err != nil {
|
||||
causes = append(causes, err)
|
||||
|
||||
Reference in New Issue
Block a user