feat(archie): add declarative multi-stage promotion bundles (#2157)
This commit is contained in:
4 files changed
+2607
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,585 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
// BundleExportReply is the JSON response returned by GET /api/bundles/export.
|
||||
type BundleExportReply struct {
|
||||
SchemaVersion string `json:"schema_version"`
|
||||
ExportedAt time.Time `json:"exported_at"`
|
||||
Digest string `json:"digest"`
|
||||
BundleYAML string `json:"bundle_yaml"`
|
||||
}
|
||||
|
||||
// BundleDiffReply is the JSON response returned by POST /api/bundles/diff.
|
||||
type BundleDiffReply struct {
|
||||
Digest string `json:"digest"`
|
||||
Empty bool `json:"empty"`
|
||||
Formatted string `json:"formatted"`
|
||||
Diff BundleDiff `json:"diff"`
|
||||
}
|
||||
|
||||
// BundleApplyReply is the JSON response returned by POST /api/bundles/apply.
|
||||
type BundleApplyReply struct {
|
||||
Digest string `json:"digest"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
Applied bool `json:"applied"`
|
||||
Empty bool `json:"empty"`
|
||||
Formatted string `json:"formatted"`
|
||||
Diff BundleDiff `json:"diff"`
|
||||
}
|
||||
|
||||
type bundleStore interface {
|
||||
ReadBundle(ctx context.Context) (Bundle, error)
|
||||
ApplyBundle(ctx context.Context, desired Bundle, stage string, dryRun bool) (BundleDiff, error)
|
||||
}
|
||||
|
||||
type pgBundleStore struct {
|
||||
db *sqlx.DB
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func (s pgBundleStore) ReadBundle(ctx context.Context) (Bundle, error) {
|
||||
return readBundle(ctx, s.db)
|
||||
}
|
||||
|
||||
func (s pgBundleStore) ApplyBundle(ctx context.Context, desired Bundle, stage string, dryRun bool) (BundleDiff, error) {
|
||||
return applyBundleDB(ctx, s.db, s.log, desired, stage, dryRun)
|
||||
}
|
||||
|
||||
type bundleAPI struct {
|
||||
store bundleStore
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// RegisterBundleAPI registers Cedar-gated promotion bundle endpoints on api.
|
||||
// When db is nil (as during OpenAPI generation), routes are registered without
|
||||
// a backing store.
|
||||
func RegisterBundleAPI(api huma.API, db *sqlx.DB, log *slog.Logger) {
|
||||
var st bundleStore
|
||||
if db != nil {
|
||||
st = pgBundleStore{db: db, log: log}
|
||||
}
|
||||
registerBundleRoutes(api, st, log)
|
||||
}
|
||||
|
||||
func registerBundleRoutes(api huma.API, store bundleStore, log *slog.Logger) {
|
||||
a := &bundleAPI{store: store, log: log}
|
||||
tags := []string{"Bundles"}
|
||||
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindSettings), huma.Operation{
|
||||
OperationID: "export-bundle", Method: http.MethodGet, Path: "/api/bundles/export",
|
||||
Summary: "Export a deterministic promotion bundle", Tags: tags,
|
||||
}, a.export)
|
||||
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindSettings), huma.Operation{
|
||||
OperationID: "diff-bundle", Method: http.MethodPost, Path: "/api/bundles/diff",
|
||||
Summary: "Diff a promotion bundle against the active stage", Tags: tags,
|
||||
}, a.diff)
|
||||
httpapi.Register(api, httpapi.Authorized(governance.ActionManagePolicies, governance.KindSettings), huma.Operation{
|
||||
OperationID: "apply-bundle", Method: http.MethodPost, Path: "/api/bundles/apply",
|
||||
Summary: "Apply a promotion bundle atomically", Tags: tags,
|
||||
}, a.apply)
|
||||
}
|
||||
|
||||
type bundleDiffInput struct {
|
||||
Body struct {
|
||||
BundleYAML string `json:"bundle_yaml" doc:"Portable promotion bundle YAML"`
|
||||
}
|
||||
}
|
||||
|
||||
type bundleApplyInput struct {
|
||||
Body struct {
|
||||
BundleYAML string `json:"bundle_yaml" doc:"Portable promotion bundle YAML"`
|
||||
BindingsYAML string `json:"bindings_yaml,omitempty" doc:"Optional stage-local bindings YAML"`
|
||||
DryRun bool `json:"dry_run,omitempty" doc:"Validate and compute diff without mutating state"`
|
||||
ExpectDigest string `json:"expect_digest,omitempty" doc:"Expected canonical bundle SHA-256 digest"`
|
||||
}
|
||||
}
|
||||
|
||||
func (a *bundleAPI) export(ctx context.Context, _ *struct{}) (*httpapi.Reply[BundleExportReply], error) {
|
||||
if a.store == nil {
|
||||
return nil, huma.Error503ServiceUnavailable("bundle store unavailable")
|
||||
}
|
||||
b, err := a.store.ReadBundle(ctx)
|
||||
if err != nil {
|
||||
a.log.ErrorContext(ctx, "export bundle", "error", err)
|
||||
return nil, huma.Error500InternalServerError("couldn't export bundle")
|
||||
}
|
||||
b.ExportedAt = time.Now().UTC()
|
||||
canon := b.Canonical()
|
||||
digest, err := canon.Digest()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't digest bundle")
|
||||
}
|
||||
raw, err := yaml.Marshal(canon)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't encode bundle")
|
||||
}
|
||||
return httpapi.OK(BundleExportReply{
|
||||
SchemaVersion: canon.SchemaVersion,
|
||||
ExportedAt: canon.ExportedAt,
|
||||
Digest: digest,
|
||||
BundleYAML: string(raw),
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (a *bundleAPI) diff(ctx context.Context, in *bundleDiffInput) (*httpapi.Reply[BundleDiffReply], error) {
|
||||
if a.store == nil {
|
||||
return nil, huma.Error503ServiceUnavailable("bundle store unavailable")
|
||||
}
|
||||
desired, err := ParseBundle([]byte(in.Body.BundleYAML))
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest(err.Error())
|
||||
}
|
||||
digest, err := desired.Digest()
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest(err.Error())
|
||||
}
|
||||
current, err := a.store.ReadBundle(ctx)
|
||||
if err != nil {
|
||||
a.log.ErrorContext(ctx, "diff bundle read", "error", err)
|
||||
return nil, huma.Error500InternalServerError("couldn't read current bundle state")
|
||||
}
|
||||
d := DiffBundle(current, desired)
|
||||
return httpapi.OK(BundleDiffReply{
|
||||
Digest: digest,
|
||||
Empty: d.Empty(),
|
||||
Formatted: d.Format(),
|
||||
Diff: d,
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (a *bundleAPI) apply(ctx context.Context, in *bundleApplyInput) (*httpapi.Reply[BundleApplyReply], error) {
|
||||
if a.store == nil {
|
||||
return nil, huma.Error503ServiceUnavailable("bundle store unavailable")
|
||||
}
|
||||
desired, stage, err := validateApplyInput(in.Body.BundleYAML, in.Body.BindingsYAML)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest(err.Error())
|
||||
}
|
||||
if err := verifyBundleDigest(desired, in.Body.ExpectDigest); err != nil {
|
||||
return nil, huma.Error409Conflict(err.Error())
|
||||
}
|
||||
digest, err := desired.Digest()
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest(err.Error())
|
||||
}
|
||||
d, err := a.store.ApplyBundle(ctx, desired, stage, in.Body.DryRun)
|
||||
if err != nil {
|
||||
if errors.Is(err, governance.ErrPolicyLockout) {
|
||||
return nil, huma.Error409Conflict(err.Error())
|
||||
}
|
||||
a.log.ErrorContext(ctx, "apply bundle", "error", err)
|
||||
return nil, huma.Error500InternalServerError("couldn't apply bundle")
|
||||
}
|
||||
return httpapi.OK(BundleApplyReply{
|
||||
Digest: digest,
|
||||
DryRun: in.Body.DryRun,
|
||||
Applied: !in.Body.DryRun && !d.Empty(),
|
||||
Empty: d.Empty(),
|
||||
Formatted: d.Format(),
|
||||
Diff: d,
|
||||
}), nil
|
||||
}
|
||||
|
||||
func validateApplyInput(bundleYAML, bindingsYAML string) (Bundle, string, error) {
|
||||
desired, err := ParseBundle([]byte(bundleYAML))
|
||||
if err != nil {
|
||||
return Bundle{}, "", err
|
||||
}
|
||||
if strings.TrimSpace(bindingsYAML) == "" {
|
||||
return desired, "", nil
|
||||
}
|
||||
bindings, err := ParseBindings([]byte(bindingsYAML))
|
||||
if err != nil {
|
||||
return Bundle{}, "", err
|
||||
}
|
||||
if err := ValidateBundleBindings(desired, bindings); err != nil {
|
||||
return Bundle{}, "", err
|
||||
}
|
||||
return desired, bindings.Stage, nil
|
||||
}
|
||||
|
||||
// BundleClient calls Archie's HTTPS control-plane bundle endpoints using a
|
||||
// bearer token, for CI runners without direct Postgres access.
|
||||
type BundleClient struct {
|
||||
BaseURL string
|
||||
Token string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
// LoadBundleClient resolves API transport credentials from ARCHIE_URL and
|
||||
// ARCHIE_TOKEN / ARCHIE_TOKEN_FILE. ok is false when baseURL is unset.
|
||||
func LoadBundleClient(baseURLOverride string) (BundleClient, bool, error) {
|
||||
baseURL := strings.TrimSpace(baseURLOverride)
|
||||
if baseURL == "" {
|
||||
baseURL = strings.TrimSpace(os.Getenv("ARCHIE_URL"))
|
||||
}
|
||||
if baseURL == "" {
|
||||
return BundleClient{}, false, nil
|
||||
}
|
||||
u, err := url.Parse(baseURL)
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return BundleClient{}, false, fmt.Errorf("invalid ARCHIE_URL %q", baseURL)
|
||||
}
|
||||
token, hasToken, err := envOrFile("ARCHIE_TOKEN", "ARCHIE_TOKEN_FILE")
|
||||
if err != nil {
|
||||
return BundleClient{}, false, err
|
||||
}
|
||||
if !hasToken {
|
||||
return BundleClient{}, false, errors.New("ARCHIE_TOKEN or ARCHIE_TOKEN_FILE is required when ARCHIE_URL is set")
|
||||
}
|
||||
return BundleClient{
|
||||
BaseURL: strings.TrimRight(baseURL, "/"),
|
||||
Token: token,
|
||||
HTTP: &http.Client{Timeout: 30 * time.Second},
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
// Export fetches the stage's bundle YAML from GET /api/bundles/export.
|
||||
func (c BundleClient) Export(ctx context.Context) (BundleExportReply, error) {
|
||||
var out BundleExportReply
|
||||
if err := c.doJSON(ctx, http.MethodGet, "/api/bundles/export", nil, &out); err != nil {
|
||||
return BundleExportReply{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Diff posts bundleYAML to POST /api/bundles/diff.
|
||||
func (c BundleClient) Diff(ctx context.Context, bundleYAML string) (BundleDiffReply, error) {
|
||||
reqBody := map[string]any{"bundle_yaml": bundleYAML}
|
||||
var out BundleDiffReply
|
||||
if err := c.doJSON(ctx, http.MethodPost, "/api/bundles/diff", reqBody, &out); err != nil {
|
||||
return BundleDiffReply{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Apply posts a bundle apply request to POST /api/bundles/apply.
|
||||
func (c BundleClient) Apply(ctx context.Context, bundleYAML, bindingsYAML, expectDigest string, dryRun bool) (BundleApplyReply, error) {
|
||||
reqBody := map[string]any{
|
||||
"bundle_yaml": bundleYAML,
|
||||
"bindings_yaml": bindingsYAML,
|
||||
"dry_run": dryRun,
|
||||
"expect_digest": expectDigest,
|
||||
}
|
||||
var out BundleApplyReply
|
||||
if err := c.doJSON(ctx, http.MethodPost, "/api/bundles/apply", reqBody, &out); err != nil {
|
||||
return BundleApplyReply{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c BundleClient) doJSON(ctx context.Context, method, path string, in, out any) error {
|
||||
var bodyReader io.Reader
|
||||
if in != nil {
|
||||
raw, err := json.Marshal(in)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode request: %w", err)
|
||||
}
|
||||
bodyReader = bytes.NewReader(raw)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, bodyReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if in != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
client := c.HTTP
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
resp, err := client.Do(req) //nolint:gosec // operator-configured ARCHIE_URL endpoint
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s: %w", method, path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
respBytes, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s %s response: %w", method, path, err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("%s %s: HTTP %d: %s", method, path, resp.StatusCode, strings.TrimSpace(string(respBytes)))
|
||||
}
|
||||
if err := json.Unmarshal(respBytes, out); err != nil {
|
||||
return fmt.Errorf("decode %s %s response: %w", method, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunBundleCLI executes `archie bundle <subcommand>` (`export`, `validate`,
|
||||
// `diff`, `apply`) supporting both direct DB mode and ARCHIE_URL API mode.
|
||||
// It returns an exit code (0 = success/no-changes, 2 = drift/changes with
|
||||
// --detailed-exitcode, 1 = error) alongside any error.
|
||||
func RunBundleCLI(ctx context.Context, configPath string, args []string, stdout io.Writer) (int, error) {
|
||||
if stdout == nil {
|
||||
stdout = os.Stdout
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return 1, errors.New("usage: archie bundle <export|validate|diff|apply> [flags]")
|
||||
}
|
||||
switch args[0] {
|
||||
case "export":
|
||||
return runBundleExportCLI(ctx, configPath, args[1:], stdout)
|
||||
case "validate":
|
||||
return runBundleValidateCLI(args[1:], stdout)
|
||||
case "diff":
|
||||
return runBundleDiffCLI(ctx, configPath, args[1:], stdout)
|
||||
case "apply":
|
||||
return runBundleApplyCLI(ctx, configPath, args[1:], stdout)
|
||||
default:
|
||||
return 1, fmt.Errorf("unknown bundle subcommand %q", args[0])
|
||||
}
|
||||
}
|
||||
|
||||
func runBundleExportCLI(ctx context.Context, configPath string, args []string, stdout io.Writer) (int, error) {
|
||||
fs := flag.NewFlagSet("bundle export", flag.ContinueOnError)
|
||||
outPath := fs.String("out", "", "output file path (stdout when omitted or -)")
|
||||
apiURL := fs.String("url", "", "control-plane base URL (overrides ARCHIE_URL)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
client, useAPI, err := LoadBundleClient(*apiURL)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if !useAPI {
|
||||
if err := ExportBundle(ctx, configPath, *outPath); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
reply, err := client.Export(ctx)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if *outPath == "" || *outPath == "-" {
|
||||
_, err := io.WriteString(stdout, reply.BundleYAML)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
if err := writeConfig(*outPath, []byte(reply.BundleYAML)); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func runBundleValidateCLI(args []string, stdout io.Writer) (int, error) {
|
||||
fs := flag.NewFlagSet("bundle validate", flag.ContinueOnError)
|
||||
bundlePath := fs.String("bundle", "", "path to bundle YAML")
|
||||
bindingsPath := fs.String("bindings", "", "optional path to stage bindings YAML")
|
||||
format := fs.String("format", "text", "output format: text or json")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if strings.TrimSpace(*bundlePath) == "" {
|
||||
return 1, errors.New("-bundle is required")
|
||||
}
|
||||
b, err := ValidateBundleFile(*bundlePath, *bindingsPath)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
digest, err := b.Digest()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if err := writeValidateOutput(stdout, *format, digest); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func writeValidateOutput(w io.Writer, format, digest string) error {
|
||||
switch format {
|
||||
case "text":
|
||||
_, err := fmt.Fprintf(w, "valid (%s)\n", digest)
|
||||
return err
|
||||
case "json":
|
||||
return writeJSONLine(w, map[string]any{"valid": true, "digest": digest})
|
||||
default:
|
||||
return fmt.Errorf("unsupported -format %q (want text or json)", format)
|
||||
}
|
||||
}
|
||||
|
||||
func runBundleDiffCLI(ctx context.Context, configPath string, args []string, stdout io.Writer) (int, error) {
|
||||
fs := flag.NewFlagSet("bundle diff", flag.ContinueOnError)
|
||||
bundlePath := fs.String("bundle", "", "path to bundle YAML")
|
||||
format := fs.String("format", "text", "output format: text or json")
|
||||
detailedExit := fs.Bool("detailed-exitcode", false, "return exit code 2 when drift is detected")
|
||||
apiURL := fs.String("url", "", "control-plane base URL (overrides ARCHIE_URL)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if strings.TrimSpace(*bundlePath) == "" {
|
||||
return 1, errors.New("-bundle is required")
|
||||
}
|
||||
diff, digest, err := runDiffTransport(ctx, configPath, *bundlePath, *apiURL)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if err := writeDiffOutput(stdout, *format, digest, diff, false); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if *detailedExit && !diff.Empty() {
|
||||
return 2, nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func runDiffTransport(ctx context.Context, configPath, bundlePath, apiURL string) (BundleDiff, string, error) {
|
||||
client, useAPI, err := LoadBundleClient(apiURL)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
if useAPI {
|
||||
raw, err := os.ReadFile(bundlePath) //nolint:gosec // operator-supplied bundle path
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", fmt.Errorf("read bundle %s: %w", bundlePath, err)
|
||||
}
|
||||
reply, err := client.Diff(ctx, string(raw))
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
return reply.Diff, reply.Digest, nil
|
||||
}
|
||||
b, err := loadBundleFile(bundlePath)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
digest, err := b.Digest()
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
diff, err := DiffBundleFile(ctx, configPath, bundlePath)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
return diff, digest, nil
|
||||
}
|
||||
|
||||
func runBundleApplyCLI(ctx context.Context, configPath string, args []string, stdout io.Writer) (int, error) {
|
||||
fs := flag.NewFlagSet("bundle apply", flag.ContinueOnError)
|
||||
bundlePath := fs.String("bundle", "", "path to bundle YAML")
|
||||
bindingsPath := fs.String("bindings", "", "optional path to stage bindings YAML")
|
||||
dryRun := fs.Bool("dry-run", false, "validate and diff without writing")
|
||||
expectDigest := fs.String("expect-digest", "", "fail closed unless bundle digest matches")
|
||||
format := fs.String("format", "text", "output format: text or json")
|
||||
detailedExit := fs.Bool("detailed-exitcode", false, "return exit code 2 when changes exist")
|
||||
apiURL := fs.String("url", "", "control-plane base URL (overrides ARCHIE_URL)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if strings.TrimSpace(*bundlePath) == "" {
|
||||
return 1, errors.New("-bundle is required")
|
||||
}
|
||||
diff, digest, err := runApplyTransport(ctx, configPath, *bundlePath, *bindingsPath, *expectDigest, *apiURL, *dryRun)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if err := writeDiffOutput(stdout, *format, digest, diff, *dryRun); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if *detailedExit && !diff.Empty() {
|
||||
return 2, nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func runApplyTransport(ctx context.Context, configPath, bundlePath, bindingsPath, expectDigest, apiURL string, dryRun bool) (BundleDiff, string, error) {
|
||||
client, useAPI, err := LoadBundleClient(apiURL)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
if !useAPI {
|
||||
b, err := ValidateBundleFile(bundlePath, bindingsPath)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
digest, err := b.Digest()
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
diff, err := ApplyBundlePinned(ctx, configPath, bundlePath, bindingsPath, expectDigest, dryRun)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
return diff, digest, nil
|
||||
}
|
||||
rawBundle, err := os.ReadFile(bundlePath) //nolint:gosec // operator-supplied bundle path
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", fmt.Errorf("read bundle %s: %w", bundlePath, err)
|
||||
}
|
||||
rawBindings, err := readOptionalFile(bindingsPath)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
reply, err := client.Apply(ctx, string(rawBundle), rawBindings, expectDigest, dryRun)
|
||||
if err != nil {
|
||||
return BundleDiff{}, "", err
|
||||
}
|
||||
return reply.Diff, reply.Digest, nil
|
||||
}
|
||||
|
||||
func readOptionalFile(path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", nil
|
||||
}
|
||||
b, err := os.ReadFile(path) //nolint:gosec // operator-supplied bindings path
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read bindings %s: %w", path, err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func writeDiffOutput(w io.Writer, format, digest string, diff BundleDiff, dryRun bool) error {
|
||||
switch format {
|
||||
case "text":
|
||||
_, err := io.WriteString(w, diff.Format())
|
||||
return err
|
||||
case "json":
|
||||
return writeJSONLine(w, map[string]any{
|
||||
"service": "archie",
|
||||
"version": buildinfo.Version,
|
||||
"digest": digest,
|
||||
"dry_run": dryRun,
|
||||
"empty": diff.Empty(),
|
||||
"diff": diff,
|
||||
})
|
||||
default:
|
||||
return fmt.Errorf("unsupported -format %q (want text or json)", format)
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSONLine(w io.Writer, v any) error {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintf(w, "%s\n", raw)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
type fakeBundleStore struct {
|
||||
current Bundle
|
||||
lastApply struct {
|
||||
desired Bundle
|
||||
stage string
|
||||
dryRun bool
|
||||
called bool
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeBundleStore) ReadBundle(context.Context) (Bundle, error) {
|
||||
return f.current, nil
|
||||
}
|
||||
|
||||
func (f *fakeBundleStore) ApplyBundle(_ context.Context, desired Bundle, stage string, dryRun bool) (BundleDiff, error) {
|
||||
f.lastApply.desired = desired
|
||||
f.lastApply.stage = stage
|
||||
f.lastApply.dryRun = dryRun
|
||||
f.lastApply.called = true
|
||||
diff := DiffBundle(f.current, desired)
|
||||
if !dryRun && !diff.Empty() {
|
||||
f.current = desired.Canonical()
|
||||
}
|
||||
return diff, nil
|
||||
}
|
||||
|
||||
func newTestBundleServer(t *testing.T, st bundleStore, allowErr error) (*httptest.Server, *fakeBundleStore) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
auth := operator{}
|
||||
authz := &refuses{err: allowErr}
|
||||
api := httpapi.New(mux, "test", auth, authz)
|
||||
registerBundleRoutes(api, st, slog.New(slog.DiscardHandler))
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
if fs, ok := st.(*fakeBundleStore); ok {
|
||||
return srv, fs
|
||||
}
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// TestBundleAPIRoutesAuthzAndRoundTrip guards Cedar route enforcement,
|
||||
// export/diff/apply HTTP round-trips, digest pinning, and idempotent no-ops.
|
||||
func TestBundleAPIRoutesAuthzAndRoundTrip(t *testing.T) {
|
||||
initial := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "triage.alert", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
}
|
||||
|
||||
// Denied by authorizer -> 403 Forbidden before handler runs.
|
||||
deniedSrv, _ := newTestBundleServer(t, &fakeBundleStore{current: initial}, httpapi.ErrDenied)
|
||||
deniedClient := BundleClient{BaseURL: deniedSrv.URL, Token: "test-token", HTTP: deniedSrv.Client()}
|
||||
if _, err := deniedClient.Export(t.Context()); err == nil || !strings.Contains(err.Error(), "HTTP 403") {
|
||||
t.Fatalf("expected 403 when denied, got %v", err)
|
||||
}
|
||||
|
||||
// Allowed -> export, diff, apply with digest pinning, and idempotent second apply.
|
||||
st := &fakeBundleStore{current: initial}
|
||||
srv, _ := newTestBundleServer(t, st, nil)
|
||||
client := BundleClient{BaseURL: srv.URL, Token: "test-token", HTTP: srv.Client()}
|
||||
|
||||
exported, err := client.Export(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Export: %v", err)
|
||||
}
|
||||
parsed, err := ParseBundle([]byte(exported.BundleYAML))
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle(exported): %v", err)
|
||||
}
|
||||
wantDigest, err := parsed.Digest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if exported.Digest != wantDigest {
|
||||
t.Fatalf("exported digest = %q, want %q", exported.Digest, wantDigest)
|
||||
}
|
||||
|
||||
// Update bundle with a new workflow and custom org access policy.
|
||||
desired := parsed
|
||||
desired.Workflows = append(desired.Workflows, BundleWorkflow{
|
||||
Name: "notify.only", Body: "repository: none\nsteps:\n - type: run.notify\n", Enabled: true,
|
||||
})
|
||||
desired.AccessPolicies = []governance.Policy{{
|
||||
ID: "dev-approve", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy,
|
||||
}}
|
||||
desiredRaw, err := yaml.Marshal(desired)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
desiredDigest, err := desired.Digest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
diffReply, err := client.Diff(t.Context(), string(desiredRaw))
|
||||
if err != nil {
|
||||
t.Fatalf("Diff: %v", err)
|
||||
}
|
||||
if diffReply.Empty || diffReply.Digest != desiredDigest {
|
||||
t.Fatalf("unexpected diff reply: %+v", diffReply)
|
||||
}
|
||||
|
||||
// Wrong expect_digest must fail closed with 409 Conflict and never call ApplyBundle.
|
||||
if _, err := client.Apply(t.Context(), string(desiredRaw), "", "sha256:"+strings.Repeat("0", 64), false); err == nil || !strings.Contains(err.Error(), "HTTP 409") {
|
||||
t.Fatalf("expected HTTP 409 on digest mismatch, got %v", err)
|
||||
}
|
||||
if st.lastApply.called {
|
||||
t.Fatal("ApplyBundle should not run when expect_digest fails")
|
||||
}
|
||||
|
||||
// Disallowed connector in bindings must fail with 400 Bad Request.
|
||||
badBindings, _ := yaml.Marshal(Bindings{Stage: "prod", AllowedConnectors: []string{"github"}})
|
||||
if _, err := client.Apply(t.Context(), string(desiredRaw), string(badBindings), desiredDigest, false); err == nil || !strings.Contains(err.Error(), "HTTP 400") {
|
||||
t.Fatalf("expected HTTP 400 on disallowed connector, got %v", err)
|
||||
}
|
||||
|
||||
// Valid apply with matching digest and bindings succeeds.
|
||||
goodBindings, _ := yaml.Marshal(Bindings{Stage: "prod", AllowedConnectors: []string{"github", "slack"}})
|
||||
applyReply, err := client.Apply(t.Context(), string(desiredRaw), string(goodBindings), desiredDigest, false)
|
||||
if err != nil {
|
||||
t.Fatalf("Apply: %v", err)
|
||||
}
|
||||
if !applyReply.Applied || applyReply.Empty || st.lastApply.stage != "prod" {
|
||||
t.Fatalf("unexpected apply reply: %+v (stage=%q)", applyReply, st.lastApply.stage)
|
||||
}
|
||||
|
||||
// Second apply of identical bundle is an idempotent no-op.
|
||||
secondReply, err := client.Apply(t.Context(), string(desiredRaw), string(goodBindings), desiredDigest, false)
|
||||
if err != nil {
|
||||
t.Fatalf("second Apply: %v", err)
|
||||
}
|
||||
if secondReply.Applied || !secondReply.Empty {
|
||||
t.Fatalf("expected idempotent no-op on second apply, got %+v", secondReply)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunBundleCLIValidateDiffApplyAndExitCodes guards offline CI validation,
|
||||
// API-mode diff/apply flags, --format json, and --detailed-exitcode semantics.
|
||||
func TestRunBundleCLIValidateDiffApplyAndExitCodes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
bundlePath := filepath.Join(dir, "bundle.yaml")
|
||||
bindingsPath := filepath.Join(dir, "bindings.yaml")
|
||||
tokenPath := filepath.Join(dir, "token")
|
||||
|
||||
b := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "triage.alert", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
}
|
||||
rawBundle, err := yaml.Marshal(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rawBindings, err := yaml.Marshal(Bindings{Stage: "staging", AllowedConnectors: []string{"github", "slack"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(bundlePath, rawBundle, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(bindingsPath, rawBindings, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(tokenPath, []byte("ci-bearer-token\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Offline `validate` runs with zero DB/network access.
|
||||
var out bytes.Buffer
|
||||
code, err := RunBundleCLI(t.Context(), "", []string{"validate", "-bundle", bundlePath, "-bindings", bindingsPath, "-format", "json"}, &out)
|
||||
if err != nil || code != 0 {
|
||||
t.Fatalf("validate failed: code=%d err=%v out=%s", code, err, out.String())
|
||||
}
|
||||
var valOut map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &valOut); err != nil || valOut["valid"] != true {
|
||||
t.Fatalf("unexpected validate json output: %q (%v)", out.String(), err)
|
||||
}
|
||||
|
||||
// API mode via ARCHIE_URL + ARCHIE_TOKEN_FILE.
|
||||
st := &fakeBundleStore{current: Bundle{SchemaVersion: BundleSchemaVersion}}
|
||||
srv, _ := newTestBundleServer(t, st, nil)
|
||||
t.Setenv("ARCHIE_URL", srv.URL)
|
||||
t.Setenv("ARCHIE_TOKEN_FILE", tokenPath)
|
||||
|
||||
// diff with --detailed-exitcode returns 2 when changes exist.
|
||||
out.Reset()
|
||||
code, err = RunBundleCLI(t.Context(), "", []string{"diff", "-bundle", bundlePath, "-detailed-exitcode", "-format", "json"}, &out)
|
||||
if err != nil || code != 2 {
|
||||
t.Fatalf("diff expected exit code 2 on drift, got code=%d err=%v", code, err)
|
||||
}
|
||||
|
||||
// apply --dry-run leaves store unchanged and returns exit code 2 with --detailed-exitcode.
|
||||
out.Reset()
|
||||
code, err = RunBundleCLI(t.Context(), "", []string{"apply", "-bundle", bundlePath, "-bindings", bindingsPath, "-dry-run", "-detailed-exitcode"}, &out)
|
||||
if err != nil || code != 2 {
|
||||
t.Fatalf("dry-run apply expected exit code 2, got code=%d err=%v", code, err)
|
||||
}
|
||||
if len(st.current.Workflows) != 0 {
|
||||
t.Fatal("dry-run mutated store state")
|
||||
}
|
||||
|
||||
// Real apply updates store; subsequent diff with --detailed-exitcode returns 0.
|
||||
digest, _ := b.Digest()
|
||||
out.Reset()
|
||||
code, err = RunBundleCLI(t.Context(), "", []string{"apply", "-bundle", bundlePath, "-bindings", bindingsPath, "-expect-digest", digest}, &out)
|
||||
if err != nil || code != 0 {
|
||||
t.Fatalf("apply failed: code=%d err=%v", code, err)
|
||||
}
|
||||
out.Reset()
|
||||
code, err = RunBundleCLI(t.Context(), "", []string{"diff", "-bundle", bundlePath, "-detailed-exitcode"}, &out)
|
||||
if err != nil || code != 0 {
|
||||
t.Fatalf("post-apply diff expected exit code 0, got code=%d err=%v", code, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterBundleAPINilStoreAndAuthorizedActions guards OpenAPI emptyAPI
|
||||
// registration (db == nil) and verifies all routes declare valid Cedar actions.
|
||||
func TestRegisterBundleAPINilStoreAndAuthorizedActions(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
probe := &refuses{err: httpapi.ErrDenied}
|
||||
api := httpapi.New(mux, "test", operator{}, probe)
|
||||
RegisterBundleAPI(api, nil, slog.New(slog.DiscardHandler))
|
||||
|
||||
routes := httpapi.Routes(api)
|
||||
if len(routes) != 3 {
|
||||
t.Fatalf("got %d bundle routes, want 3", len(routes))
|
||||
}
|
||||
for _, r := range routes {
|
||||
action, kind, ok := r.Access.Declared()
|
||||
if !ok {
|
||||
t.Fatalf("%s declares no access", r.ID)
|
||||
}
|
||||
if err := governance.Action(action).Validate(); err != nil || kind == "" {
|
||||
t.Fatalf("%s invalid access (%q, %q): %v", r.ID, action, kind, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With nil store and allowing authorizer, export returns 503 instead of panicking.
|
||||
probe.err = nil
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/bundles/export", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("GET /api/bundles/export with nil store = %d, want 503", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
)
|
||||
|
||||
const validWorkflowYAML = `inputs:
|
||||
target:
|
||||
type: string
|
||||
required: true
|
||||
repository: none
|
||||
steps:
|
||||
- id: check
|
||||
type: connector.action
|
||||
settings:
|
||||
connector: github
|
||||
name: get-issue
|
||||
input:
|
||||
number: "{{ inputs.target }}"
|
||||
- id: wait
|
||||
type: approval.wait
|
||||
- id: tell
|
||||
type: message.send
|
||||
settings:
|
||||
channel: slack
|
||||
chat_id: C123
|
||||
text: "Checked {{ steps.check.summary }}"
|
||||
`
|
||||
|
||||
const validHardRulesCedar = `@id("no-prod-delete")
|
||||
@reason("production deletions are blocked")
|
||||
forbid(principal, action == Action::"ssh::rm", resource) when {
|
||||
resource.environment == "production"
|
||||
};`
|
||||
|
||||
const validChangeRequestCedar = `@id("prod-change-ticket")
|
||||
permit(principal, action, resource) when {
|
||||
resource.environment == "production" && context.guard_failed == true
|
||||
};`
|
||||
|
||||
const validCustomOrgPolicy = `permit(principal, action, resource) when {
|
||||
resource.org == principal.org &&
|
||||
principal.role == "developer" &&
|
||||
action == Archie::Action::"approve"
|
||||
};`
|
||||
|
||||
// TestBundleYAMLRoundTripAndAutonomyExclusion guards YAML serialization of
|
||||
// Bundle and proves earned-autonomy fields are absent from the schema and
|
||||
// rejected on unmarshal.
|
||||
func TestBundleYAMLRoundTripAndAutonomyExclusion(t *testing.T) {
|
||||
exportedAt := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC)
|
||||
want := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
ExportedAt: exportedAt,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "triage.alert", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
AccessPolicies: []governance.Policy{
|
||||
{
|
||||
ID: "dev-approve-custom",
|
||||
Level: governance.LevelOrg,
|
||||
OrgID: governance.DefaultOrgID,
|
||||
Text: validCustomOrgPolicy,
|
||||
},
|
||||
},
|
||||
JudgementRules: BundleJudgement{
|
||||
HardRules: validHardRulesCedar,
|
||||
ChangeRequest: validChangeRequestCedar,
|
||||
},
|
||||
ActionTypes: []BundleActionType{
|
||||
{
|
||||
Connector: "github",
|
||||
Action: "get-issue",
|
||||
TargetKind: "issue",
|
||||
Environment: "staging",
|
||||
Notes: "read-only issue lookup",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
raw, err := yaml.Marshal(want)
|
||||
if err != nil {
|
||||
t.Fatalf("yaml.Marshal: %v", err)
|
||||
}
|
||||
text := string(raw)
|
||||
for _, forbidden := range []string{"approval_count", "autonomy_level"} {
|
||||
if strings.Contains(text, forbidden) {
|
||||
t.Fatalf("marshaled bundle YAML unexpectedly contains %q:\n%s", forbidden, text)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify structurally that BundleActionType carries no autonomy/approval fields.
|
||||
typ := reflect.TypeFor[BundleActionType]()
|
||||
for _, field := range []string{"ApprovalCount", "AutonomyLevel", "Level", "Count"} {
|
||||
if _, ok := typ.FieldByName(field); ok {
|
||||
t.Fatalf("BundleActionType must not define field %q", field)
|
||||
}
|
||||
}
|
||||
|
||||
got, err := ParseBundle(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("round-trip mismatch:\n got: %+v\nwant: %+v", got, want)
|
||||
}
|
||||
|
||||
// Strictly reject YAML bundles attempting to smuggle earned autonomy fields.
|
||||
for _, field := range []string{"approval_count: 10", "autonomy_level: act_quietly"} {
|
||||
smuggled := strings.Replace(text, "notes: read-only issue lookup", "notes: ok\n "+field, 1)
|
||||
if _, err := ParseBundle([]byte(smuggled)); err == nil {
|
||||
t.Fatalf("expected ParseBundle to reject %q", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseBundleRejectsInvalidInputs guards schema, workflow, Cedar policy,
|
||||
// shipped-policy, and action-type validation before touching the database.
|
||||
func TestParseBundleRejectsInvalidInputs(t *testing.T) {
|
||||
base := func() Bundle {
|
||||
return Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
ExportedAt: time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC),
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "triage.alert", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
JudgementRules: BundleJudgement{
|
||||
HardRules: validHardRulesCedar,
|
||||
ChangeRequest: validChangeRequestCedar,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Bundle)
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "wrong schema version",
|
||||
mutate: func(b *Bundle) { b.SchemaVersion = "archie.bundle/v99" },
|
||||
wantErr: "schema_version",
|
||||
},
|
||||
{
|
||||
name: "invalid workflow name",
|
||||
mutate: func(b *Bundle) { b.Workflows[0].Name = "Bad Name!" },
|
||||
wantErr: "invalid name",
|
||||
},
|
||||
{
|
||||
name: "duplicate workflow name",
|
||||
mutate: func(b *Bundle) {
|
||||
b.Workflows = append(b.Workflows, BundleWorkflow{Name: "triage.alert", Body: validWorkflowYAML})
|
||||
},
|
||||
wantErr: "duplicate workflow",
|
||||
},
|
||||
{
|
||||
name: "invalid workflow body rejected by runs.ParseDocument",
|
||||
mutate: func(b *Bundle) { b.Workflows[0].Body = "steps:\n - type: does.not.exist\n" },
|
||||
wantErr: "unknown type",
|
||||
},
|
||||
{
|
||||
name: "shipped org access policy rejected",
|
||||
mutate: func(b *Bundle) {
|
||||
b.AccessPolicies = []governance.Policy{{
|
||||
ID: governance.PolicyOrgRead,
|
||||
Level: governance.LevelOrg,
|
||||
OrgID: governance.DefaultOrgID,
|
||||
Text: validCustomOrgPolicy,
|
||||
}}
|
||||
},
|
||||
wantErr: "shipped policy",
|
||||
},
|
||||
{
|
||||
name: "non-org access policy rejected",
|
||||
mutate: func(b *Bundle) {
|
||||
b.AccessPolicies = []governance.Policy{{
|
||||
ID: "instance-custom",
|
||||
Level: governance.LevelInstance,
|
||||
Text: validCustomOrgPolicy,
|
||||
}}
|
||||
},
|
||||
wantErr: "org level only",
|
||||
},
|
||||
{
|
||||
name: "invalid access policy Cedar rejected",
|
||||
mutate: func(b *Bundle) {
|
||||
b.AccessPolicies = []governance.Policy{{
|
||||
ID: "bad-cedar",
|
||||
Level: governance.LevelOrg,
|
||||
OrgID: governance.DefaultOrgID,
|
||||
Text: "not valid cedar",
|
||||
}}
|
||||
},
|
||||
wantErr: "does not parse",
|
||||
},
|
||||
{
|
||||
name: "hard rules must be forbid",
|
||||
mutate: func(b *Bundle) {
|
||||
b.JudgementRules.HardRules = `@id("bad-permit") permit(principal, action, resource);`
|
||||
},
|
||||
wantErr: "must be a forbid",
|
||||
},
|
||||
{
|
||||
name: "change request must be permit",
|
||||
mutate: func(b *Bundle) {
|
||||
b.JudgementRules.ChangeRequest = `@id("bad-forbid") forbid(principal, action, resource);`
|
||||
},
|
||||
wantErr: "must be a permit",
|
||||
},
|
||||
{
|
||||
name: "action type requires connector and action",
|
||||
mutate: func(b *Bundle) {
|
||||
b.ActionTypes = []BundleActionType{{Connector: "", Action: "rm", TargetKind: "host", Environment: "prod"}}
|
||||
},
|
||||
wantErr: "connector and action are required",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
b := base()
|
||||
tt.mutate(&b)
|
||||
raw, err := yaml.Marshal(b)
|
||||
if err != nil {
|
||||
t.Fatalf("yaml.Marshal: %v", err)
|
||||
}
|
||||
_, err = ParseBundle(raw)
|
||||
if err == nil {
|
||||
t.Fatalf("expected error containing %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("error = %q, want substring %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiffBundleDeterministic guards deterministic sorting, Empty(), Format(),
|
||||
// and line-ending normalization in DiffBundle.
|
||||
func TestDiffBundleDeterministic(t *testing.T) {
|
||||
current := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "z.wf", Body: "repository: none\r\nsteps:\r\n - type: run.notify\r\n", Enabled: true},
|
||||
{Name: "a.wf", Body: validWorkflowYAML, Enabled: true},
|
||||
{Name: "old.wf", Body: validWorkflowYAML, Enabled: false},
|
||||
},
|
||||
AccessPolicies: []governance.Policy{
|
||||
{ID: "p-keep", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy},
|
||||
{ID: "p-drop", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy},
|
||||
},
|
||||
JudgementRules: BundleJudgement{
|
||||
HardRules: validHardRulesCedar,
|
||||
},
|
||||
ActionTypes: []BundleActionType{
|
||||
{Connector: "ssh", Action: "exec", TargetKind: "host", Environment: "staging"},
|
||||
},
|
||||
}
|
||||
|
||||
// Identical aside from slice order and CRLF -> Empty().
|
||||
sameReordered := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "old.wf", Body: validWorkflowYAML, Enabled: false},
|
||||
{Name: "a.wf", Body: validWorkflowYAML, Enabled: true},
|
||||
{Name: "z.wf", Body: "repository: none\nsteps:\n - type: run.notify\n", Enabled: true},
|
||||
},
|
||||
AccessPolicies: []governance.Policy{
|
||||
{ID: "p-drop", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy},
|
||||
{ID: "p-keep", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy},
|
||||
},
|
||||
JudgementRules: BundleJudgement{
|
||||
HardRules: validHardRulesCedar,
|
||||
},
|
||||
ActionTypes: []BundleActionType{
|
||||
{Connector: "ssh", Action: "exec", TargetKind: "host", Environment: "staging"},
|
||||
},
|
||||
}
|
||||
if d := DiffBundle(current, sameReordered); !d.Empty() || d.Format() != "no changes\n" {
|
||||
t.Fatalf("expected empty diff, got empty=%v format=%q", d.Empty(), d.Format())
|
||||
}
|
||||
|
||||
desired := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "z.wf", Body: "repository: none\nsteps:\n - type: run.notify\n", Enabled: false},
|
||||
{Name: "b.wf", Body: validWorkflowYAML, Enabled: true},
|
||||
{Name: "a.wf", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
AccessPolicies: []governance.Policy{
|
||||
{ID: "p-add", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy},
|
||||
{ID: "p-keep", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: validCustomOrgPolicy + "\n// changed"},
|
||||
},
|
||||
JudgementRules: BundleJudgement{
|
||||
HardRules: validHardRulesCedar + "\n// rule v2",
|
||||
ChangeRequest: validChangeRequestCedar,
|
||||
},
|
||||
ActionTypes: []BundleActionType{
|
||||
{Connector: "github", Action: "get-issue", TargetKind: "issue", Environment: "staging"},
|
||||
{Connector: "ssh", Action: "exec", TargetKind: "host", Environment: "staging", Notes: "host command"},
|
||||
},
|
||||
}
|
||||
|
||||
diff := DiffBundle(current, desired)
|
||||
if diff.Empty() {
|
||||
t.Fatal("expected non-empty diff")
|
||||
}
|
||||
|
||||
const wantFormatted = `+ workflow b.wf
|
||||
- workflow old.wf
|
||||
~ workflow z.wf (enabled)
|
||||
+ access_policy p-add
|
||||
- access_policy p-drop
|
||||
~ access_policy p-keep
|
||||
~ judgement_rule hard_rules
|
||||
+ judgement_rule change_request
|
||||
+ action_type github/get-issue (issue, staging)
|
||||
~ action_type ssh/exec (host, staging) (notes)
|
||||
`
|
||||
if got := diff.Format(); got != wantFormatted {
|
||||
t.Fatalf("diff.Format() =\n%s\nwant:\n%s", got, wantFormatted)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateBundleBindingsConnectorAllowList guards stage-local connector
|
||||
// allow-list enforcement and pre-DB rejection in ApplyBundle.
|
||||
func TestValidateBundleBindingsConnectorAllowList(t *testing.T) {
|
||||
bundle := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "triage.alert", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
}
|
||||
|
||||
// Both github (connector.action) and slack (message.send) are allowed -> pass.
|
||||
if err := ValidateBundleBindings(bundle, Bindings{
|
||||
Stage: "staging",
|
||||
AllowedConnectors: []string{"github", "slack"},
|
||||
AutonomyCeilings: map[string]string{"default": judgement.ProposeAndWait.String()},
|
||||
}); err != nil {
|
||||
t.Fatalf("expected allowed connectors to pass, got %v", err)
|
||||
}
|
||||
|
||||
// Missing slack (referenced by message.send) -> refuse.
|
||||
err := ValidateBundleBindings(bundle, Bindings{
|
||||
Stage: "prod",
|
||||
AllowedConnectors: []string{"github"},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), `"slack"`) {
|
||||
t.Fatalf("expected disallowed slack connector error, got %v", err)
|
||||
}
|
||||
|
||||
// Explicit empty allow-list -> refuse.
|
||||
err = ValidateBundleBindings(bundle, Bindings{
|
||||
Stage: "prod",
|
||||
AllowedConnectors: []string{},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "allowed_connectors") {
|
||||
t.Fatalf("expected empty allowed_connectors error, got %v", err)
|
||||
}
|
||||
|
||||
// Invalid autonomy ceiling level -> refuse.
|
||||
err = ValidateBundleBindings(bundle, Bindings{
|
||||
Stage: "prod",
|
||||
AutonomyCeilings: map[string]string{"ssh": "unrestricted"},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "autonomy_ceilings") {
|
||||
t.Fatalf("expected invalid autonomy_ceilings error, got %v", err)
|
||||
}
|
||||
|
||||
// Verify ApplyBundle rejects disallowed connectors before opening DB.
|
||||
dir := t.TempDir()
|
||||
bundlePath := filepath.Join(dir, "bundle.yaml")
|
||||
bindingsPath := filepath.Join(dir, "bindings.yaml")
|
||||
bundleBytes, err := yaml.Marshal(bundle)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bindingsBytes, err := yaml.Marshal(Bindings{
|
||||
Stage: "prod",
|
||||
AllowedConnectors: []string{"github"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(bundlePath, bundleBytes, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(bindingsPath, bindingsBytes, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = ApplyBundle(t.Context(), filepath.Join(dir, "missing-config.toml"), bundlePath, bindingsPath, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "allowed_connectors") {
|
||||
t.Fatalf("expected ApplyBundle to reject disallowed connector before reading config/DB, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBundleDigestCanonicalAndDeterministic guards Bundle.Digest() stability
|
||||
// across slice orderings and ExportedAt timestamps, and sensitivity to content.
|
||||
func TestBundleDigestCanonicalAndDeterministic(t *testing.T) {
|
||||
b1 := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
ExportedAt: time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC),
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "b.wf", Body: validWorkflowYAML, Enabled: true},
|
||||
{Name: "a.wf", Body: "repository: none\nsteps:\n - type: run.notify\n", Enabled: false},
|
||||
},
|
||||
ActionTypes: []BundleActionType{
|
||||
{Connector: "ssh", Action: "exec", TargetKind: "host", Environment: "prod"},
|
||||
{Connector: "github", Action: "get-issue", TargetKind: "issue", Environment: "prod"},
|
||||
},
|
||||
}
|
||||
b2 := Bundle{
|
||||
SchemaVersion: BundleSchemaVersion,
|
||||
ExportedAt: time.Date(2026, 12, 1, 15, 30, 0, 0, time.UTC),
|
||||
Workflows: []BundleWorkflow{
|
||||
{Name: "a.wf", Body: "repository: none\r\nsteps:\r\n - type: run.notify\r\n", Enabled: false},
|
||||
{Name: "b.wf", Body: validWorkflowYAML, Enabled: true},
|
||||
},
|
||||
ActionTypes: []BundleActionType{
|
||||
{Connector: "github", Action: "get-issue", TargetKind: "issue", Environment: "prod"},
|
||||
{Connector: "ssh", Action: "exec", TargetKind: "host", Environment: "prod"},
|
||||
},
|
||||
}
|
||||
|
||||
d1, err := b1.Digest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d2, err := b2.Digest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(d1, "sha256:") || d1 != d2 {
|
||||
t.Fatalf("expected matching sha256 digests ignoring ExportedAt/order, got %q vs %q", d1, d2)
|
||||
}
|
||||
|
||||
b2.Workflows[0].Enabled = true
|
||||
d3, err := b2.Digest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d3 == d1 {
|
||||
t.Fatal("expected digest to change when workflow content changes")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user