314 lines
12 KiB
Go
314 lines
12 KiB
Go
package releasekit
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"go.maximumdirect.net/releasekit/internal/artifact"
|
|
"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.
|
|
type ReadinessOperation string
|
|
|
|
const (
|
|
ReadinessPublication ReadinessOperation = "publication"
|
|
ReadinessGo ReadinessOperation = "go"
|
|
ReadinessBuild ReadinessOperation = "build"
|
|
ReadinessDelivery ReadinessOperation = "delivery"
|
|
ReadinessRehearsal ReadinessOperation = "rehearsal"
|
|
)
|
|
|
|
// ReadinessStatus describes the evidence obtained for a check.
|
|
type ReadinessStatus string
|
|
|
|
const (
|
|
ReadinessPassed ReadinessStatus = "passed"
|
|
ReadinessFailed ReadinessStatus = "failed"
|
|
ReadinessSkipped ReadinessStatus = "skipped"
|
|
ReadinessUnchecked ReadinessStatus = "unchecked"
|
|
)
|
|
|
|
// ReadinessCredential describes a credential source without exposing a token.
|
|
// Rehearsal readiness requires a declared CI source; job secret injection is
|
|
// established by the job rather than this declaration.
|
|
type ReadinessCredential struct {
|
|
Context string
|
|
Source string
|
|
Declared bool
|
|
}
|
|
|
|
// WoodpeckerObservation identifies the selected CI repository and credential.
|
|
type WoodpeckerObservation struct {
|
|
BaseURL string
|
|
RepositoryID int64
|
|
Workflow string
|
|
Step string
|
|
Token string
|
|
CredentialError error
|
|
}
|
|
|
|
// ValidateRequest supplies working inputs and explicit credentials for a
|
|
// read-only readiness inspection. It does not load ambient credentials.
|
|
type ValidateRequest struct {
|
|
RepositoryDir string
|
|
ModuleDir string
|
|
Source *SourceSpec
|
|
Product string
|
|
Remote string
|
|
ExpectedPushURL string
|
|
Operations []ReadinessOperation
|
|
Context string
|
|
Offline bool
|
|
// Validation supplies candidate configuration for publication/Go readiness.
|
|
Validation ValidationSpec
|
|
// RehearsalSelector defaults to root when rehearsal readiness is selected.
|
|
RehearsalSelector string
|
|
Build *BuildSpec
|
|
Destination *DeliveryDestination
|
|
Credentials []ReadinessCredential
|
|
CredentialError error
|
|
Woodpecker *WoodpeckerObservation
|
|
RequiredFiles []string
|
|
Prebuilt *BuildResult
|
|
Output io.Writer
|
|
}
|
|
|
|
// ReadinessError summarizes unsuccessful checks while preserving their causes.
|
|
type ReadinessError struct{ Causes []error }
|
|
|
|
func (err *ReadinessError) Error() string {
|
|
return "readiness validation did not complete successfully"
|
|
}
|
|
func (err *ReadinessError) Unwrap() []error { return err.Causes }
|
|
|
|
// Validate inspects working inputs and selected read-only access without
|
|
// building, publishing, checking out, or running product checks.
|
|
func Validate(ctx context.Context, request ValidateRequest) (ValidationReport, error) {
|
|
if request.Context == "" {
|
|
request.Context = "local"
|
|
}
|
|
operations := append([]ReadinessOperation(nil), request.Operations...)
|
|
if len(operations) == 0 {
|
|
operations = append(operations, ReadinessPublication)
|
|
selection, err := releaseidentity.NormalizeSource(request.ModuleDir, internalSourceSpec(request.Source))
|
|
if err == nil && selection.GoEnabled {
|
|
operations = append(operations, ReadinessGo)
|
|
}
|
|
if request.Build != nil && len(request.Build.Targets) != 0 {
|
|
operations = append(operations, ReadinessBuild)
|
|
}
|
|
if request.Destination != nil {
|
|
operations = append(operations, ReadinessDelivery)
|
|
}
|
|
}
|
|
var operationNames []string
|
|
seen := map[ReadinessOperation]bool{}
|
|
unique := operations[:0]
|
|
for _, operation := range operations {
|
|
if !seen[operation] {
|
|
seen[operation] = true
|
|
unique = append(unique, operation)
|
|
operationNames = append(operationNames, string(operation))
|
|
}
|
|
}
|
|
operations = unique
|
|
internalRequest := readiness.Request{
|
|
RepositoryDir: request.RepositoryDir, ModuleDir: request.ModuleDir, Source: internalSourceSpec(request.Source), Product: request.Product,
|
|
Remote: request.Remote, ExpectedPushURL: request.ExpectedPushURL, Context: request.Context, Operations: operationNames,
|
|
Validation: internalValidationSpec(request.Validation), Selector: request.RehearsalSelector,
|
|
Offline: request.Offline, HasDelivery: request.Destination != nil, HasRehearsal: request.Woodpecker != nil, RequiredFiles: request.RequiredFiles,
|
|
}
|
|
for _, credential := range request.Credentials {
|
|
if credential.Context == "ci" && credential.Declared && strings.TrimSpace(credential.Source) != "" {
|
|
internalRequest.CIConfigured = true
|
|
}
|
|
}
|
|
|
|
if request.Build != nil {
|
|
settings := *internalBuildSpec(request.Build)
|
|
internalRequest.Build = &settings
|
|
}
|
|
if request.Destination != nil {
|
|
internalRequest.DeliveryConfig = func() error {
|
|
destination := *request.Destination
|
|
destination.Token = "readiness-configuration"
|
|
backend, err := deliveryBackend(destination)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
validator, ok := backend.(interface{ ValidateConfiguration() error })
|
|
if !ok {
|
|
return errors.New("destination validation is unavailable")
|
|
}
|
|
return publicPreflightError(validator.ValidateConfiguration())
|
|
}
|
|
internalRequest.Credential = func() error {
|
|
if request.CredentialError != nil {
|
|
return request.CredentialError
|
|
}
|
|
if strings.TrimSpace(request.Destination.Token) == "" {
|
|
return errors.New("delivery token is required")
|
|
}
|
|
return nil
|
|
}
|
|
internalRequest.Delivery = func(ctx context.Context) error {
|
|
return PreflightDelivery(ctx, *request.Destination)
|
|
}
|
|
}
|
|
if request.Prebuilt != nil {
|
|
internalRequest.Prebuilt = func(ctx context.Context, source releaseidentity.ResolvedSource) error {
|
|
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 {
|
|
report.DeliveryDestination = git.DisplayURL(request.Destination.BaseURL) + "/" + request.Destination.Owner + "/" + request.Destination.Repository
|
|
}
|
|
var causes []error
|
|
for _, check := range internal.Checks {
|
|
if check.ID == "delivery-access" && check.Cause != nil {
|
|
var failure *DeliveryPreflightError
|
|
if errors.As(check.Cause, &failure) && failure.Kind != DeliveryPreflightUnavailable && !errors.Is(check.Cause, context.Canceled) && !errors.Is(check.Cause, context.DeadlineExceeded) {
|
|
check.Reason = "configuration"
|
|
}
|
|
}
|
|
report.Checks = append(report.Checks, ReadinessResult{ID: check.ID, Operation: ReadinessOperation(check.Operation), Status: ReadinessStatus(check.Status), Reason: check.Reason, Message: check.Message, Cause: check.Cause})
|
|
if check.Status == "failed" {
|
|
if check.Cause != nil {
|
|
causes = append(causes, check.Cause)
|
|
} else {
|
|
causes = append(causes, errors.New(check.Message))
|
|
}
|
|
}
|
|
if check.Status == "unchecked" && check.Reason == "unavailable" {
|
|
causes = append(causes, errors.New(check.Message))
|
|
}
|
|
}
|
|
for _, credential := range request.Credentials {
|
|
if !seen[ReadinessDelivery] && !seen[ReadinessRehearsal] {
|
|
break
|
|
}
|
|
if credential.Declared && strings.TrimSpace(credential.Source) == "" {
|
|
err := fmt.Errorf("%s credential source is blank", credential.Context)
|
|
report.Checks = append(report.Checks, ReadinessResult{ID: "credential-declaration", Operation: ReadinessDelivery, 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)
|
|
}
|
|
}
|
|
if len(causes) != 0 {
|
|
return report, &ReadinessError{Causes: causes}
|
|
}
|
|
return report, nil
|
|
}
|
|
|
|
func validateReadinessBuild(ctx context.Context, request ValidateRequest, source releaseidentity.ResolvedSource) error {
|
|
build := request.Prebuilt
|
|
if build.IdentityKind == "diagnostic" {
|
|
attempt := strings.TrimPrefix(build.Version, "releasekit-test-")
|
|
parts := strings.Split(build.Tag, "/")
|
|
if !strings.HasPrefix(build.Version, "releasekit-test-") || len(attempt) != 32 || strings.ToLower(attempt) != attempt || len(parts) != 3 || parts[0] != "releasekit-test" || parts[1] == "" || parts[2] != attempt {
|
|
return errors.New("invalid diagnostic build identity")
|
|
}
|
|
if _, err := hex.DecodeString(attempt); err != nil {
|
|
return errors.New("invalid diagnostic build identity")
|
|
}
|
|
if err := git.CheckTagRef(ctx, source.RepositoryDir, build.Tag); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
identity, err := releaseidentity.FromWorkingSource(ctx, source.RepositoryDir, request.ModuleDir, build.Version, internalSourceSpec(request.Source))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if build.IdentityKind != identity.Kind || build.Tag != identity.Tag {
|
|
return errors.New("prebuilt release identity does not match selected source")
|
|
}
|
|
}
|
|
commit, err := git.CaptureHead(ctx, source.RepositoryDir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if build.RepositoryDir != source.RepositoryDir || build.SourceDir != source.ModuleDir || build.SourceSubdir != source.ModuleSubdir || build.GoEnabled != source.GoEnabled || string(build.Publication) != source.Publication || string(build.VersionFormat) != source.VersionFormat || build.VersionPrefix != source.VersionPrefix || build.CandidateCommit != commit || build.ModulePath != source.ModulePath || build.ModuleDir != source.ModuleDir {
|
|
return errors.New("prebuilt identity does not match the selected source and commit")
|
|
}
|
|
if request.Build == nil {
|
|
return errors.New("prebuilt assets require declared build settings")
|
|
}
|
|
if len(request.Build.Targets) != 0 && !build.SourceVerified {
|
|
return errors.New("prebuilt build source was not verified")
|
|
}
|
|
want := internalBuildSpec(request.Build)
|
|
if build.MainPackage != want.MainPackage || build.BinaryName != want.BinaryName {
|
|
return errors.New("prebuilt build settings do not match")
|
|
}
|
|
declarations := make([]artifact.Declaration, 0, len(build.Artifacts))
|
|
assets := make([]artifact.ExpectedAsset, 0, len(build.Artifacts))
|
|
for _, item := range build.Artifacts {
|
|
declarations = append(declarations, artifact.Declaration{Target: artifact.Target{OS: item.Target.OS, Arch: item.Target.Arch}, Filename: item.Filename})
|
|
if !filepath.IsAbs(item.Path) || !filepath.IsAbs(build.OutputDir) || filepath.Clean(filepath.Dir(item.Path)) != filepath.Clean(build.OutputDir) {
|
|
return errors.New("prebuilt artifact path must be in the recorded output directory")
|
|
}
|
|
info, err := os.Stat(item.Path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
assets = append(assets, artifact.ExpectedAsset{Filename: item.Filename, Path: item.Path, SHA256: item.SHA256, Size: info.Size()})
|
|
}
|
|
if err := artifact.ValidateDeclarations(build.BinaryName, build.Version, artifact.NormalizeTargets(want.Targets), declarations); err != nil {
|
|
return err
|
|
}
|
|
return artifact.VerifyLocalAssets(assets)
|
|
}
|
|
|
|
// ReadinessResult records one check, its outcome, and an optional cause.
|
|
type ReadinessResult struct {
|
|
ID string
|
|
Operation ReadinessOperation
|
|
Status ReadinessStatus
|
|
Reason string
|
|
Message string
|
|
Cause error
|
|
}
|
|
|
|
// ValidationReport records the scope and ordered findings of a readiness run.
|
|
type ValidationReport struct {
|
|
InputSource string
|
|
RepositoryDir string
|
|
Operations []ReadinessOperation
|
|
Context string
|
|
Offline bool
|
|
GitDestination string
|
|
DeliveryDestination string
|
|
Credentials []ReadinessCredential
|
|
Checks []ReadinessResult
|
|
}
|