diff --git a/internal/app/archie/bundle.go b/internal/app/archie/bundle.go new file mode 100644 index 000000000..74ac8be28 --- /dev/null +++ b/internal/app/archie/bundle.go @@ -0,0 +1,1297 @@ +package archie + +import ( + "bytes" + "context" + "crypto/sha256" + "crypto/subtle" + "database/sql" + "encoding/hex" + json "encoding/json/v2" + "errors" + "fmt" + "io" + "log/slog" + "maps" + "os" + "slices" + "strings" + "time" + + cedar "github.com/cedar-policy/cedar-go" + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/internal/buildinfo" + "github.com/samcharles93/archie-core/internal/platform/pg" + "github.com/samcharles93/archie-core/internal/platform/stableid" + "github.com/samcharles93/archie-core/modules/governance" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/runs" +) + +// BundleSchemaVersion is the schema version written to and accepted by +// promotion bundles. +const BundleSchemaVersion = "archie.bundle/v1" + +const ( + bundleAdvisoryLockKey = "archie.bundle.owner" + maxBundlePolicyBytes = 64 << 10 +) + +// Bundle is a portable declarative snapshot of an organisation's workflows, +// non-shipped org access policies, judgement rules, and action-type metadata. +type Bundle struct { + SchemaVersion string `yaml:"schema_version"` + ExportedAt time.Time `yaml:"exported_at"` + Workflows []BundleWorkflow `yaml:"workflows"` + AccessPolicies []governance.Policy `yaml:"access_policies"` + JudgementRules BundleJudgement `yaml:"judgement_rules"` + ActionTypes []BundleActionType `yaml:"action_types"` +} + +// BundleWorkflow is a portable workflow definition without stage-local IDs. +type BundleWorkflow struct { + Name string `yaml:"name"` + Body string `yaml:"body"` + Enabled bool `yaml:"enabled"` +} + +// BundleJudgement holds an organisation's Cedar hard rules and change-request rules. +type BundleJudgement struct { + HardRules string `yaml:"hard_rules"` + ChangeRequest string `yaml:"change_request"` +} + +// BundleActionType declares action-type metadata without runtime autonomy +// state (no approval counts or autonomy levels), so promotion never resets or +// widens earned autonomy in Staging or Production. +type BundleActionType struct { + Connector string `yaml:"connector"` + Action string `yaml:"action"` + TargetKind string `yaml:"target_kind"` + Environment string `yaml:"environment"` + Notes string `yaml:"notes,omitempty"` +} + +// Bindings holds stage-local constraints verified during bundle application. +type Bindings struct { + Stage string `yaml:"stage"` + AutonomyCeilings map[string]string `yaml:"autonomy_ceilings,omitempty"` + AllowedConnectors []string `yaml:"allowed_connectors,omitempty"` +} + +// DiffOp classifies a change between current and desired bundle states. +type DiffOp string + +const ( + DiffAdd DiffOp = "add" + DiffUpdate DiffOp = "update" + DiffRemove DiffOp = "remove" +) + +// WorkflowChange describes a workflow difference between two bundles. +type WorkflowChange struct { + Op DiffOp `json:"op"` + Name string `json:"name"` + Details []string `json:"details,omitzero"` +} + +// AccessPolicyChange describes a non-shipped org access policy difference. +type AccessPolicyChange struct { + Op DiffOp `json:"op"` + ID string `json:"id"` +} + +// RuleChange describes a judgement rule set difference. +type RuleChange struct { + Op DiffOp `json:"op"` + Kind string `json:"kind"` +} + +// ActionTypeChange describes an action-type metadata difference. +type ActionTypeChange struct { + Op DiffOp `json:"op"` + Connector string `json:"connector"` + Action string `json:"action"` + TargetKind string `json:"target_kind"` + Environment string `json:"environment"` + Details []string `json:"details,omitzero"` +} + +// BundleDiff describes the changes required to reach a desired Bundle from the +// current Bundle. +type BundleDiff struct { + Workflows []WorkflowChange `json:"workflows,omitzero"` + AccessPolicies []AccessPolicyChange `json:"access_policies,omitzero"` + JudgementRules []RuleChange `json:"judgement_rules,omitzero"` + ActionTypes []ActionTypeChange `json:"action_types,omitzero"` +} + +// Empty reports whether d contains no changes. +func (d BundleDiff) Empty() bool { + return len(d.Workflows) == 0 && + len(d.AccessPolicies) == 0 && + len(d.JudgementRules) == 0 && + len(d.ActionTypes) == 0 +} + +// Format renders d as a deterministic human-readable summary. +func (d BundleDiff) Format() string { + if d.Empty() { + return "no changes\n" + } + var b strings.Builder + for _, c := range d.Workflows { + fmt.Fprintf(&b, "%s workflow %s", opSymbol(c.Op), c.Name) + if len(c.Details) > 0 { + fmt.Fprintf(&b, " (%s)", strings.Join(c.Details, ", ")) + } + b.WriteByte('\n') + } + for _, c := range d.AccessPolicies { + fmt.Fprintf(&b, "%s access_policy %s\n", opSymbol(c.Op), c.ID) + } + for _, c := range d.JudgementRules { + fmt.Fprintf(&b, "%s judgement_rule %s\n", opSymbol(c.Op), c.Kind) + } + for _, c := range d.ActionTypes { + fmt.Fprintf(&b, "%s action_type %s/%s (%s, %s)", opSymbol(c.Op), c.Connector, c.Action, c.TargetKind, c.Environment) + if len(c.Details) > 0 { + fmt.Fprintf(&b, " (%s)", strings.Join(c.Details, ", ")) + } + b.WriteByte('\n') + } + return b.String() +} + +func opSymbol(op DiffOp) string { + switch op { + case DiffAdd: + return "+" + case DiffUpdate: + return "~" + case DiffRemove: + return "-" + default: + return "?" + } +} + +// Canonical returns a sorted copy of b so exports and digests are +// deterministic regardless of input slice order. +func (b Bundle) Canonical() Bundle { + out := Bundle{ + SchemaVersion: b.SchemaVersion, + ExportedAt: b.ExportedAt, + Workflows: slices.Clone(b.Workflows), + AccessPolicies: slices.Clone(b.AccessPolicies), + JudgementRules: b.JudgementRules, + ActionTypes: slices.Clone(b.ActionTypes), + } + slices.SortFunc(out.Workflows, func(a, c BundleWorkflow) int { + return strings.Compare(a.Name, c.Name) + }) + for i := range out.AccessPolicies { + if out.AccessPolicies[i].OrgID == "" && out.AccessPolicies[i].Level == governance.LevelOrg { + out.AccessPolicies[i].OrgID = governance.DefaultOrgID + } + } + slices.SortFunc(out.AccessPolicies, func(a, c governance.Policy) int { + return strings.Compare(a.ID, c.ID) + }) + slices.SortFunc(out.ActionTypes, func(a, c BundleActionType) int { + return compareActionTypeKey(keyForActionType(a), keyForActionType(c)) + }) + return out +} + +// Digest returns the canonical SHA-256 digest ("sha256:") over b's sorted +// portable content, excluding ExportedAt. +func (b Bundle) Digest() (string, error) { + canon := b.Canonical() + canon.ExportedAt = time.Time{} + for i := range canon.Workflows { + canon.Workflows[i].Body = normaliseBundleText(canon.Workflows[i].Body) + } + for i := range canon.AccessPolicies { + canon.AccessPolicies[i].Text = normaliseBundleText(canon.AccessPolicies[i].Text) + } + canon.JudgementRules.HardRules = normaliseBundleText(canon.JudgementRules.HardRules) + canon.JudgementRules.ChangeRequest = normaliseBundleText(canon.JudgementRules.ChangeRequest) + + raw, err := json.Marshal(canon, json.Deterministic(true)) + if err != nil { + return "", fmt.Errorf("canonicalise bundle for digest: %w", err) + } + sum := sha256.Sum256(raw) + return "sha256:" + hex.EncodeToString(sum[:]), nil +} + +func verifyBundleDigest(b Bundle, expect string) error { + want := normaliseDigest(expect) + if want == "" { + return nil + } + got, err := b.Digest() + if err != nil { + return err + } + gotHex := normaliseDigest(got) + if len(want) != len(gotHex) || subtle.ConstantTimeCompare([]byte(want), []byte(gotHex)) != 1 { + return fmt.Errorf("bundle digest %s does not match expected %s", got, expect) + } + return nil +} + +func normaliseDigest(raw string) string { + s := strings.ToLower(strings.TrimSpace(raw)) + return strings.TrimPrefix(s, "sha256:") +} + +// ParseBundle decodes YAML strictly into a Bundle and validates its schema, +// workflows, access policies, judgement rules, and action types. +func ParseBundle(raw []byte) (Bundle, error) { + var b Bundle + if err := decodeStrictYAML(raw, &b); err != nil { + return Bundle{}, fmt.Errorf("decode bundle: %w", err) + } + if err := ValidateBundle(b); err != nil { + return Bundle{}, err + } + return b, nil +} + +// ParseBindings decodes YAML strictly into stage Bindings and validates them. +func ParseBindings(raw []byte) (Bindings, error) { + var b Bindings + if err := decodeStrictYAML(raw, &b); err != nil { + return Bindings{}, fmt.Errorf("decode bindings: %w", err) + } + if err := ValidateBindings(b); err != nil { + return Bindings{}, err + } + return b, nil +} + +func decodeStrictYAML(raw []byte, target any) error { + dec := yaml.NewDecoder(bytes.NewReader(raw)) + dec.KnownFields(true) + if err := dec.Decode(target); err != nil { + return err + } + if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + return errors.New("expected a single YAML document") + } + return nil +} + +// ValidateBundle validates b without touching the database. +func ValidateBundle(b Bundle) error { + if b.SchemaVersion != BundleSchemaVersion { + return fmt.Errorf("unsupported bundle schema_version %q (want %q)", b.SchemaVersion, BundleSchemaVersion) + } + if err := validateBundleWorkflows(b.Workflows); err != nil { + return err + } + if err := validateBundlePolicies(b.AccessPolicies); err != nil { + return err + } + if err := validateBundleJudgement(b.JudgementRules); err != nil { + return err + } + return validateBundleActionTypes(b.ActionTypes) +} + +// ValidateBundleFile reads and validates bundlePath (and optional bindingsPath) +// completely offline with zero database or network access. +func ValidateBundleFile(bundlePath, bindingsPath string) (Bundle, error) { + b, err := loadBundleFile(bundlePath) + if err != nil { + return Bundle{}, err + } + if bindingsPath != "" { + bindings, err := loadBindingsFile(bindingsPath) + if err != nil { + return Bundle{}, err + } + if err := ValidateBundleBindings(b, bindings); err != nil { + return Bundle{}, err + } + } + return b, nil +} + +func validateBundleWorkflows(workflows []BundleWorkflow) error { + seen := make(map[string]bool, len(workflows)) + for _, w := range workflows { + if !stableid.Valid(w.Name) { + return fmt.Errorf("workflow %q: invalid name (must match %s)", w.Name, stableid.Pattern) + } + if seen[w.Name] { + return fmt.Errorf("workflow %q: duplicate workflow in bundle", w.Name) + } + seen[w.Name] = true + if _, err := runs.ParseDocument(w.Body); err != nil { + return fmt.Errorf("workflow %q: %w", w.Name, err) + } + } + return nil +} + +func validateBundlePolicies(policies []governance.Policy) error { + engine := governance.NewEngine(nil) + seen := make(map[string]bool, len(policies)) + for _, p := range policies { + if p.Level != governance.LevelOrg { + return fmt.Errorf("access policy %q: level %q is not allowed in bundles (org level only)", p.ID, p.Level) + } + if governance.IsShippedPolicy(p) { + return fmt.Errorf("access policy %q: shipped policy cannot be included in a bundle", p.ID) + } + if p.OrgID != "" && p.OrgID != governance.DefaultOrgID { + return fmt.Errorf("access policy %q: org_id %q does not match %q", p.ID, p.OrgID, governance.DefaultOrgID) + } + p.OrgID = governance.DefaultOrgID + if seen[p.ID] { + return fmt.Errorf("access policy %q: duplicate policy in bundle", p.ID) + } + seen[p.ID] = true + if err := engine.Validate(p); err != nil { + return fmt.Errorf("access policy %q: %w", p.ID, err) + } + } + return nil +} + +func validateBundleJudgement(rules BundleJudgement) error { + if err := validateJudgementPolicySet(judgement.KindHardRules, rules.HardRules); err != nil { + return err + } + return validateJudgementPolicySet(judgement.KindChangeRequest, rules.ChangeRequest) +} + +func validateJudgementPolicySet(kind, body string) error { + if len(body) > maxBundlePolicyBytes { + return fmt.Errorf("judgement %s: exceeds maximum size of %d bytes", kind, maxBundlePolicyBytes) + } + if strings.TrimSpace(body) == "" { + return nil + } + list, err := cedar.NewPolicyListFromBytes(kind, []byte(body)) + if err != nil { + return fmt.Errorf("judgement %s: %w", kind, err) + } + want := cedar.Forbid + wantName := "forbid" + if kind == judgement.KindChangeRequest { + want = cedar.Permit + wantName = "permit" + } + seen := make(map[string]bool, len(list)) + for i, pol := range list { + id := string(pol.Annotations()["id"]) + switch { + case id == "": + return fmt.Errorf("judgement %s: policy %d needs an @id annotation", kind, i+1) + case pol.Effect() != want: + return fmt.Errorf("judgement %s: policy %q must be a %s", kind, id, wantName) + case seen[id]: + return fmt.Errorf("judgement %s: duplicate policy id %q", kind, id) + } + seen[id] = true + } + return nil +} + +func validateBundleActionTypes(types []BundleActionType) error { + seen := make(map[actionTypeKey]bool, len(types)) + for _, t := range types { + if strings.TrimSpace(t.Connector) == "" || strings.TrimSpace(t.Action) == "" { + return fmt.Errorf("action type %q/%q: connector and action are required", t.Connector, t.Action) + } + k := keyForActionType(t) + if seen[k] { + return fmt.Errorf("action type %s/%s (%s, %s): duplicate entry in bundle", t.Connector, t.Action, t.TargetKind, t.Environment) + } + seen[k] = true + } + return nil +} + +// ValidateBindings checks stage-local bindings configuration. +func ValidateBindings(b Bindings) error { + for k, rawLevel := range b.AutonomyCeilings { + var lvl judgement.Level + if err := lvl.UnmarshalText([]byte(rawLevel)); err != nil { + return fmt.Errorf("autonomy_ceilings[%q]: %w", k, err) + } + } + return nil +} + +// ValidateBundleBindings verifies that b satisfies stage-local bindings +// constraints, refusing any workflow referencing a disallowed connector. +func ValidateBundleBindings(b Bundle, bindings Bindings) error { + if err := ValidateBindings(bindings); err != nil { + return err + } + if bindings.AllowedConnectors == nil { + return nil + } + allowed := make(map[string]bool, len(bindings.AllowedConnectors)) + for _, c := range bindings.AllowedConnectors { + allowed[c] = true + } + for _, w := range b.Workflows { + doc, err := runs.ParseDocument(w.Body) + if err != nil { + return fmt.Errorf("workflow %q: %w", w.Name, err) + } + connectors, err := workflowConnectors(doc.Steps) + if err != nil { + return fmt.Errorf("workflow %q: %w", w.Name, err) + } + for _, c := range connectors { + if !allowed[c] { + return fmt.Errorf("workflow %q references connector %q, which is not in stage %q allowed_connectors", w.Name, c, bindings.Stage) + } + } + } + return nil +} + +func workflowConnectors(steps []runs.Step) ([]string, error) { + var out []string + err := walkWorkflowSteps(steps, func(step runs.Step) error { + c, err := stepConnectorName(step) + if err != nil { + return err + } + if c != "" && !slices.Contains(out, c) { + out = append(out, c) + } + return nil + }) + if err != nil { + return nil, err + } + slices.Sort(out) + return out, nil +} + +func walkWorkflowSteps(steps []runs.Step, visit func(runs.Step) error) error { + for _, step := range steps { + if err := visit(step); err != nil { + return err + } + for _, branch := range step.Parallel { + if err := walkWorkflowSteps(branch, visit); err != nil { + return err + } + } + if step.Switch == nil { + continue + } + for _, branch := range step.Switch.Cases { + if err := walkWorkflowSteps(branch, visit); err != nil { + return err + } + } + } + return nil +} + +func stepConnectorName(step runs.Step) (string, error) { + switch step.Type { + case "connector.action": + var s struct { + Connector string `yaml:"connector"` + } + if err := step.Settings.Decode(&s); err != nil { + return "", fmt.Errorf("decode connector.action settings: %w", err) + } + return strings.TrimSpace(s.Connector), nil + case "message.send": + var s struct { + Channel string `yaml:"channel"` + } + if err := step.Settings.Decode(&s); err != nil { + return "", fmt.Errorf("decode message.send settings: %w", err) + } + return strings.TrimSpace(s.Channel), nil + default: + return "", nil + } +} + +type actionTypeKey struct { + connector string + action string + targetKind string + environment string +} + +func keyForActionType(t BundleActionType) actionTypeKey { + return actionTypeKey{ + connector: t.Connector, + action: t.Action, + targetKind: t.TargetKind, + environment: t.Environment, + } +} + +func compareActionTypeKey(a, b actionTypeKey) int { + for _, pair := range [][2]string{ + {a.connector, b.connector}, + {a.action, b.action}, + {a.targetKind, b.targetKind}, + {a.environment, b.environment}, + } { + if c := strings.Compare(pair[0], pair[1]); c != 0 { + return c + } + } + return 0 +} + +// DiffBundle compares current and desired deterministically across workflows, +// access policies, judgement rules, and action types. +func DiffBundle(current, desired Bundle) BundleDiff { + return BundleDiff{ + Workflows: diffWorkflows(current.Workflows, desired.Workflows), + AccessPolicies: diffAccessPolicies(current.AccessPolicies, desired.AccessPolicies), + JudgementRules: diffJudgementRules(current.JudgementRules, desired.JudgementRules), + ActionTypes: diffActionTypes(current.ActionTypes, desired.ActionTypes), + } +} + +func diffWorkflows(current, desired []BundleWorkflow) []WorkflowChange { + curMap := make(map[string]BundleWorkflow, len(current)) + for _, w := range current { + curMap[w.Name] = w + } + desMap := make(map[string]BundleWorkflow, len(desired)) + for _, w := range desired { + desMap[w.Name] = w + } + names := unionKeys(curMap, desMap) + var out []WorkflowChange + for _, name := range names { + c, inCur := curMap[name] + d, inDes := desMap[name] + switch { + case !inCur && inDes: + out = append(out, WorkflowChange{Op: DiffAdd, Name: name}) + case inCur && !inDes: + out = append(out, WorkflowChange{Op: DiffRemove, Name: name}) + default: + var details []string + if normaliseBundleText(c.Body) != normaliseBundleText(d.Body) { + details = append(details, "body") + } + if c.Enabled != d.Enabled { + details = append(details, "enabled") + } + if len(details) > 0 { + out = append(out, WorkflowChange{Op: DiffUpdate, Name: name, Details: details}) + } + } + } + return out +} + +func diffAccessPolicies(current, desired []governance.Policy) []AccessPolicyChange { + curMap := make(map[string]governance.Policy, len(current)) + for _, p := range current { + curMap[p.ID] = p + } + desMap := make(map[string]governance.Policy, len(desired)) + for _, p := range desired { + desMap[p.ID] = p + } + ids := unionKeys(curMap, desMap) + var out []AccessPolicyChange + for _, id := range ids { + c, inCur := curMap[id] + d, inDes := desMap[id] + switch { + case !inCur && inDes: + out = append(out, AccessPolicyChange{Op: DiffAdd, ID: id}) + case inCur && !inDes: + out = append(out, AccessPolicyChange{Op: DiffRemove, ID: id}) + case normaliseBundleText(c.Text) != normaliseBundleText(d.Text): + out = append(out, AccessPolicyChange{Op: DiffUpdate, ID: id}) + } + } + return out +} + +func diffJudgementRules(current, desired BundleJudgement) []RuleChange { + pairs := []struct { + kind string + cur string + des string + }{ + {kind: judgement.KindHardRules, cur: normaliseBundleText(current.HardRules), des: normaliseBundleText(desired.HardRules)}, + {kind: judgement.KindChangeRequest, cur: normaliseBundleText(current.ChangeRequest), des: normaliseBundleText(desired.ChangeRequest)}, + } + var out []RuleChange + for _, pair := range pairs { + if pair.cur == pair.des { + continue + } + op := DiffUpdate + switch { + case pair.cur == "" && pair.des != "": + op = DiffAdd + case pair.cur != "" && pair.des == "": + op = DiffRemove + } + out = append(out, RuleChange{Op: op, Kind: pair.kind}) + } + return out +} + +func diffActionTypes(current, desired []BundleActionType) []ActionTypeChange { + curMap := make(map[actionTypeKey]BundleActionType, len(current)) + for _, t := range current { + curMap[keyForActionType(t)] = t + } + desMap := make(map[actionTypeKey]BundleActionType, len(desired)) + for _, t := range desired { + desMap[keyForActionType(t)] = t + } + keys := make([]actionTypeKey, 0, len(curMap)+len(desMap)) + seen := make(map[actionTypeKey]bool, len(curMap)+len(desMap)) + for k := range curMap { + seen[k] = true + keys = append(keys, k) + } + for k := range desMap { + if !seen[k] { + keys = append(keys, k) + } + } + slices.SortFunc(keys, compareActionTypeKey) + var out []ActionTypeChange + for _, k := range keys { + c, inCur := curMap[k] + d, inDes := desMap[k] + switch { + case !inCur && inDes: + out = append(out, ActionTypeChange{ + Op: DiffAdd, Connector: k.connector, Action: k.action, + TargetKind: k.targetKind, Environment: k.environment, + }) + case inCur && !inDes: + out = append(out, ActionTypeChange{ + Op: DiffRemove, Connector: k.connector, Action: k.action, + TargetKind: k.targetKind, Environment: k.environment, + }) + case strings.TrimSpace(c.Notes) != strings.TrimSpace(d.Notes): + out = append(out, ActionTypeChange{ + Op: DiffUpdate, Connector: k.connector, Action: k.action, + TargetKind: k.targetKind, Environment: k.environment, + Details: []string{"notes"}, + }) + } + } + return out +} + +func unionKeys[V any](a, b map[string]V) []string { + keys := make([]string, 0, len(a)+len(b)) + seen := make(map[string]bool, len(a)+len(b)) + for k := range a { + seen[k] = true + keys = append(keys, k) + } + for k := range b { + if !seen[k] { + keys = append(keys, k) + } + } + slices.Sort(keys) + return keys +} + +func normaliseBundleText(s string) string { + return strings.TrimSpace(strings.ReplaceAll(s, "\r\n", "\n")) +} + +// ExportBundle reads the current declarative state from the database and +// writes it as deterministic YAML to outPath (or stdout when outPath is empty or "-"). +func ExportBundle(ctx context.Context, configPath, outPath string) error { + db, err := openVerifiedRuntimeDB(ctx, configPath) + if err != nil { + return err + } + defer func() { _ = db.Close() }() + + bundle, err := readBundle(ctx, db) + if err != nil { + return err + } + bundle.ExportedAt = time.Now().UTC() + raw, err := yaml.Marshal(bundle.Canonical()) + if err != nil { + return fmt.Errorf("marshal bundle: %w", err) + } + if outPath == "" || outPath == "-" { + _, err := os.Stdout.Write(raw) + return err + } + return writeConfig(outPath, raw) +} + +// DiffBundleFile validates the bundle at bundlePath and compares it against the +// current database state. +func DiffBundleFile(ctx context.Context, configPath, bundlePath string) (BundleDiff, error) { + desired, err := loadBundleFile(bundlePath) + if err != nil { + return BundleDiff{}, err + } + db, err := openVerifiedRuntimeDB(ctx, configPath) + if err != nil { + return BundleDiff{}, err + } + defer func() { _ = db.Close() }() + + current, err := readBundle(ctx, db) + if err != nil { + return BundleDiff{}, err + } + return DiffBundle(current, desired), nil +} + +// ApplyBundle validates bundlePath (and optional bindingsPath) before opening a +// transaction, applies declarative changes atomically while preserving existing +// earned-autonomy counters and credentials, and writes a JSON audit log. +func ApplyBundle(ctx context.Context, configPath, bundlePath, bindingsPath string, dryRun bool) (BundleDiff, error) { + return ApplyBundlePinned(ctx, configPath, bundlePath, bindingsPath, "", dryRun) +} + +// ApplyBundlePinned validates bundlePath, optional bindingsPath, and optional +// expected SHA-256 digest before opening a transaction, then applies changes +// atomically. +func ApplyBundlePinned(ctx context.Context, configPath, bundlePath, bindingsPath, expectDigest string, dryRun bool) (BundleDiff, error) { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version) + + desired, err := ValidateBundleFile(bundlePath, bindingsPath) + if err != nil { + return BundleDiff{}, err + } + if err := verifyBundleDigest(desired, expectDigest); err != nil { + return BundleDiff{}, err + } + var stage string + if bindingsPath != "" { + bindings, err := loadBindingsFile(bindingsPath) + if err != nil { + return BundleDiff{}, err + } + stage = bindings.Stage + } + + db, err := openVerifiedRuntimeDB(ctx, configPath) + if err != nil { + return BundleDiff{}, err + } + defer func() { _ = db.Close() }() + + return applyBundleDB(ctx, db, log, desired, stage, dryRun) +} + +func applyBundleDB(ctx context.Context, db *sqlx.DB, log *slog.Logger, desired Bundle, stage string, dryRun bool) (BundleDiff, error) { + tx, err := db.BeginTxx(ctx, nil) + if err != nil { + return BundleDiff{}, fmt.Errorf("begin bundle transaction: %w", err) + } + defer func() { _ = tx.Rollback() }() + + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, bundleAdvisoryLockKey); err != nil { + return BundleDiff{}, fmt.Errorf("acquire bundle lock: %w", err) + } + + current, err := readBundle(ctx, tx) + if err != nil { + return BundleDiff{}, err + } + diff := DiffBundle(current, desired) + if !dryRun && !diff.Empty() { + if err := applyBundleTx(ctx, tx, desired); err != nil { + return BundleDiff{}, err + } + if err := tx.Commit(); err != nil { + return BundleDiff{}, fmt.Errorf("commit bundle: %w", err) + } + } + + logBundleApply(ctx, log, stage, dryRun, diff) + return diff, nil +} + +func openVerifiedRuntimeDB(ctx context.Context, configPath string) (*sqlx.DB, error) { + dbURL, err := LoadRuntimeDBConfig(configPath) + if err != nil { + return nil, err + } + db, err := pg.Open(ctx, dbURL) + if err != nil { + return nil, err + } + if err := pg.VerifySchema(ctx, db); err != nil { + _ = db.Close() + return nil, err + } + return db, nil +} + +func loadBundleFile(path string) (Bundle, error) { + raw, err := os.ReadFile(path) //nolint:gosec // operator-supplied bundle path + if err != nil { + return Bundle{}, fmt.Errorf("read bundle %s: %w", path, err) + } + return ParseBundle(raw) +} + +func loadBindingsFile(path string) (Bindings, error) { + raw, err := os.ReadFile(path) //nolint:gosec // operator-supplied bindings path + if err != nil { + return Bindings{}, fmt.Errorf("read bindings %s: %w", path, err) + } + return ParseBindings(raw) +} + +func readBundle(ctx context.Context, q sqlx.QueryerContext) (Bundle, error) { + workflows, err := readWorkflows(ctx, q, orgID) + if err != nil { + return Bundle{}, err + } + policies, err := readOrgPolicies(ctx, q, string(governance.DefaultOrgID)) + if err != nil { + return Bundle{}, err + } + hardRules, err := readPolicySetBody(ctx, q, orgID, judgement.KindHardRules) + if err != nil { + return Bundle{}, err + } + changeRules, err := readPolicySetBody(ctx, q, orgID, judgement.KindChangeRequest) + if err != nil { + return Bundle{}, err + } + actionTypes, err := readActionTypes(ctx, q, orgID) + if err != nil { + return Bundle{}, err + } + return Bundle{ + SchemaVersion: BundleSchemaVersion, + Workflows: workflows, + AccessPolicies: policies, + JudgementRules: BundleJudgement{HardRules: hardRules, ChangeRequest: changeRules}, + ActionTypes: actionTypes, + }.Canonical(), nil +} + +type dbWorkflowRow struct { + ID uuid.UUID `db:"id"` + Name string `db:"name"` + Enabled bool `db:"enabled"` + Version int `db:"version"` + Body string `db:"body"` + Calls []byte `db:"calls"` +} + +func readWorkflows(ctx context.Context, q sqlx.QueryerContext, org string) ([]BundleWorkflow, error) { + var rows []dbWorkflowRow + if err := sqlx.SelectContext(ctx, q, &rows, ` + SELECT DISTINCT ON (w.name) w.id, w.name, w.enabled, v.version, v.body, v.calls + FROM runs.workflows w + JOIN runs.workflow_versions v ON v.workflow_id = w.id + WHERE w.org_id = $1 AND w.deleted_at IS NULL + ORDER BY w.name, v.version DESC`, org); err != nil { + return nil, fmt.Errorf("read workflows: %w", err) + } + out := make([]BundleWorkflow, 0, len(rows)) + for _, r := range rows { + out = append(out, BundleWorkflow{Name: r.Name, Body: r.Body, Enabled: r.Enabled}) + } + return out, nil +} + +type dbPolicyRow struct { + Level string `db:"level"` + OrgID string `db:"org_id"` + WorkspaceID string `db:"workspace_id"` + ObjectKind string `db:"object_kind"` + ObjectID string `db:"object_id"` + PolicyID string `db:"policy_id"` + Text string `db:"text"` +} + +func (r dbPolicyRow) toPolicy() governance.Policy { + return governance.Policy{ + ID: r.PolicyID, + Level: governance.Level(r.Level), + OrgID: governance.OrgID(r.OrgID), + WorkspaceID: governance.WorkspaceID(r.WorkspaceID), + ObjectKind: governance.ResourceKind(r.ObjectKind), + ObjectID: r.ObjectID, + Text: r.Text, + } +} + +func readOrgPolicies(ctx context.Context, q sqlx.QueryerContext, govOrg string) ([]governance.Policy, error) { + var rows []dbPolicyRow + if err := sqlx.SelectContext(ctx, q, &rows, ` + SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text + FROM governance.access_policies + WHERE level = 'org' AND org_id = $1 + ORDER BY policy_id`, govOrg); err != nil { + return nil, fmt.Errorf("read access policies: %w", err) + } + out := make([]governance.Policy, 0, len(rows)) + for _, r := range rows { + p := r.toPolicy() + if governance.IsShippedPolicy(p) { + continue + } + out = append(out, p) + } + return out, nil +} + +func readPolicySetBody(ctx context.Context, q sqlx.QueryerContext, org, kind string) (string, error) { + var body string + err := sqlx.GetContext(ctx, q, &body, ` + SELECT body FROM judgement.policy_sets + WHERE org_id = $1 AND kind = $2 + ORDER BY version DESC LIMIT 1`, org, kind) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("read judgement %s: %w", kind, err) + } + return body, nil +} + +type dbActionTypeRow struct { + Connector string `db:"connector"` + Action string `db:"action"` + TargetKind string `db:"target_kind"` + Environment string `db:"environment"` +} + +func readActionTypes(ctx context.Context, q sqlx.QueryerContext, org string) ([]BundleActionType, error) { + var rows []dbActionTypeRow + if err := sqlx.SelectContext(ctx, q, &rows, ` + SELECT connector, action, target_kind, environment + FROM judgement.action_types + WHERE org_id = $1 + ORDER BY connector, action, target_kind, environment`, org); err != nil { + return nil, fmt.Errorf("read action types: %w", err) + } + out := make([]BundleActionType, 0, len(rows)) + for _, r := range rows { + out = append(out, BundleActionType{ + Connector: r.Connector, + Action: r.Action, + TargetKind: r.TargetKind, + Environment: r.Environment, + }) + } + return out, nil +} + +func applyBundleTx(ctx context.Context, tx *sqlx.Tx, desired Bundle) error { + if err := applyWorkflowsTx(ctx, tx, orgID, desired.Workflows); err != nil { + return err + } + if err := applyAccessPoliciesTx(ctx, tx, governance.DefaultOrgID, desired.AccessPolicies); err != nil { + return err + } + if err := applyJudgementRulesTx(ctx, tx, orgID, desired.JudgementRules); err != nil { + return err + } + return applyActionTypesTx(ctx, tx, orgID, desired.ActionTypes) +} + +type liveWorkflowMeta struct { + ID uuid.UUID `db:"id"` + Name string `db:"name"` + Enabled bool `db:"enabled"` +} + +func applyWorkflowsTx(ctx context.Context, tx *sqlx.Tx, org string, workflows []BundleWorkflow) error { + var live []liveWorkflowMeta + if err := tx.SelectContext(ctx, &live, ` + SELECT id, name, enabled FROM runs.workflows + WHERE org_id = $1 AND deleted_at IS NULL`, org); err != nil { + return fmt.Errorf("list workflows: %w", err) + } + byName := make(map[string]liveWorkflowMeta, len(live)+len(workflows)) + for _, w := range live { + byName[w.Name] = w + } + for _, w := range workflows { + if _, ok := byName[w.Name]; ok { + continue + } + id := uuid.New() + if _, err := tx.ExecContext(ctx, ` + INSERT INTO runs.workflows (id, org_id, name, enabled) VALUES ($1, $2, $3, $4)`, + id, org, w.Name, w.Enabled); err != nil { + return fmt.Errorf("create workflow %q: %w", w.Name, err) + } + byName[w.Name] = liveWorkflowMeta{ID: id, Name: w.Name, Enabled: w.Enabled} + } + + var latest []dbWorkflowRow + if err := tx.SelectContext(ctx, &latest, ` + SELECT DISTINCT ON (w.name) w.id, w.name, w.enabled, v.version, v.body, v.calls + FROM runs.workflows w + JOIN runs.workflow_versions v ON v.workflow_id = w.id + WHERE w.org_id = $1 AND w.deleted_at IS NULL + ORDER BY w.name, v.version DESC`, org); err != nil { + return fmt.Errorf("read workflow versions: %w", err) + } + latestByName := make(map[string]dbWorkflowRow, len(latest)) + for _, r := range latest { + latestByName[r.Name] = r + } + for _, w := range workflows { + if err := applyOneWorkflowTx(ctx, tx, org, w, byName, latestByName[w.Name]); err != nil { + return err + } + } + return nil +} + +func applyOneWorkflowTx(ctx context.Context, tx *sqlx.Tx, org string, w BundleWorkflow, byName map[string]liveWorkflowMeta, latest dbWorkflowRow) error { + meta := byName[w.Name] + doc, err := runs.ParseDocument(w.Body) + if err != nil { + return fmt.Errorf("workflow %q: %w", w.Name, err) + } + calls, err := resolveWorkflowCalls(doc.Steps, byName) + if err != nil { + return fmt.Errorf("workflow %q: %w", w.Name, err) + } + var prevCalls map[string]uuid.UUID + if len(latest.Calls) > 0 { + if err := json.Unmarshal(latest.Calls, &prevCalls); err != nil { + return fmt.Errorf("workflow %q calls: %w", w.Name, err) + } + } + if latest.Version == 0 || normaliseBundleText(latest.Body) != normaliseBundleText(w.Body) || !maps.Equal(prevCalls, calls) { + callsRaw, err := json.Marshal(calls) + if err != nil { + return fmt.Errorf("workflow %q encode calls: %w", w.Name, err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO runs.workflow_versions (workflow_id, version, body, calls, created_by) + VALUES ($1, $2, $3, $4, $5)`, + meta.ID, latest.Version+1, w.Body, callsRaw, string(governance.SystemID)); err != nil { + return fmt.Errorf("publish workflow %q: %w", w.Name, err) + } + if _, err := tx.ExecContext(ctx, `DELETE FROM runs.workflow_drafts WHERE workflow_id = $1`, meta.ID); err != nil { + return fmt.Errorf("discard draft for %q: %w", w.Name, err) + } + } + if meta.Enabled != w.Enabled { + if _, err := tx.ExecContext(ctx, ` + UPDATE runs.workflows SET enabled = $3 WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, + org, meta.ID, w.Enabled); err != nil { + return fmt.Errorf("update workflow %q enabled: %w", w.Name, err) + } + } + return nil +} + +func resolveWorkflowCalls(steps []runs.Step, byName map[string]liveWorkflowMeta) (map[string]uuid.UUID, error) { + calls := make(map[string]uuid.UUID) + err := walkWorkflowSteps(steps, func(s runs.Step) error { + for _, target := range stepWorkflowTargets(s) { + meta, ok := byName[target] + if !ok { + return fmt.Errorf("references unknown workflow %q", target) + } + calls[target] = meta.ID + } + return nil + }) + if err != nil { + return nil, err + } + return calls, nil +} + +func stepWorkflowTargets(s runs.Step) []string { + if s.Type != "workflow.call" && s.Type != "workflow.handoff" && s.Type != "workflow.approve" { + return nil + } + var named struct { + Workflow string `yaml:"workflow"` + Then string `yaml:"then"` + } + if err := s.Settings.Decode(&named); err != nil { + return nil + } + var targets []string + for _, target := range []string{named.Workflow, named.Then} { + if t := strings.TrimSpace(target); t != "" { + targets = append(targets, t) + } + } + return targets +} + +func applyAccessPoliciesTx(ctx context.Context, tx *sqlx.Tx, govOrg governance.OrgID, desired []governance.Policy) error { + var allRows []dbPolicyRow + if err := tx.SelectContext(ctx, &allRows, ` + SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text + FROM governance.access_policies`); err != nil { + return fmt.Errorf("read access policies: %w", err) + } + candidate, changed := buildPolicyCandidate(govOrg, allRows, desired) + if !changed { + return nil + } + if err := checkPolicyCandidate(ctx, govOrg, candidate); err != nil { + return err + } + return persistOrgPoliciesTx(ctx, tx, govOrg, desired) +} + +func buildPolicyCandidate(govOrg governance.OrgID, allRows []dbPolicyRow, desired []governance.Policy) ([]governance.Policy, bool) { + curNonShipped := make(map[string]string) + candidate := make([]governance.Policy, 0, len(allRows)+len(desired)) + for _, r := range allRows { + p := r.toPolicy() + if p.Level == governance.LevelOrg && p.OrgID == govOrg && !governance.IsShippedPolicy(p) { + curNonShipped[p.ID] = normaliseBundleText(p.Text) + continue + } + candidate = append(candidate, p) + } + desMap := make(map[string]string, len(desired)) + for _, p := range desired { + p.OrgID = govOrg + desMap[p.ID] = normaliseBundleText(p.Text) + candidate = append(candidate, p) + } + return candidate, !maps.Equal(curNonShipped, desMap) +} + +func checkPolicyCandidate(ctx context.Context, govOrg governance.OrgID, candidate []governance.Policy) error { + engine := governance.NewEngine(candidate) + if problems := engine.Problems(); len(problems) > 0 { + return fmt.Errorf("access policy %q: %w", problems[0].Policy.ID, problems[0].Err) + } + if dec := engine.Authorize(ctx, governance.SharedTokenOwner(), governance.ActionManagePolicies, + governance.Resource{Kind: governance.KindPolicy, Org: govOrg}, governance.AccessContext{}); !dec.Allowed { + return governance.ErrPolicyLockout + } + return nil +} + +func persistOrgPoliciesTx(ctx context.Context, tx *sqlx.Tx, govOrg governance.OrgID, desired []governance.Policy) error { + keepIDs := shippedOrgPolicyIDList(govOrg) + for _, p := range desired { + keepIDs = append(keepIDs, p.ID) + } + if _, err := tx.ExecContext(ctx, ` + DELETE FROM governance.access_policies + WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]))`, + string(govOrg), keepIDs); err != nil { + return fmt.Errorf("prune removed access policies: %w", err) + } + for _, p := range desired { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text) + VALUES ('org', $1, '', '', '', $2, $3) + ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id) + DO UPDATE SET text = EXCLUDED.text, updated_at = now()`, + string(govOrg), p.ID, p.Text); err != nil { + return fmt.Errorf("upsert access policy %q: %w", p.ID, err) + } + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.access_policy_versions (level, org_id, workspace_id, version) + VALUES ('org', $1, '', 2) + ON CONFLICT (level, org_id, workspace_id) + DO UPDATE SET version = governance.access_policy_versions.version + 1, updated_at = now()`, string(govOrg)); err != nil { + return fmt.Errorf("bump access policy version: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.access_policy_revision (only_row, version) VALUES (true, 1) + ON CONFLICT (only_row) + DO UPDATE SET version = governance.access_policy_revision.version + 1, updated_at = now()`); err != nil { + return fmt.Errorf("bump access policy revision: %w", err) + } + return nil +} + +func shippedOrgPolicyIDList(govOrg governance.OrgID) []string { + shipped := governance.ShippedOrgPolicies(govOrg) + ids := make([]string, 0, len(shipped)) + for _, p := range shipped { + ids = append(ids, p.ID) + } + return ids +} + +func applyJudgementRulesTx(ctx context.Context, tx *sqlx.Tx, org string, desired BundleJudgement) error { + for _, pair := range []struct { + kind string + body string + }{ + {kind: judgement.KindHardRules, body: desired.HardRules}, + {kind: judgement.KindChangeRequest, body: desired.ChangeRequest}, + } { + current, err := readPolicySetBody(ctx, tx, org, pair.kind) + if err != nil { + return err + } + if normaliseBundleText(current) == normaliseBundleText(pair.body) { + continue + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO judgement.policy_sets (id, org_id, kind, version, body, created_by) + SELECT $1, $2, $3, COALESCE(max(version), 0) + 1, $4, $5 + FROM judgement.policy_sets WHERE org_id = $2 AND kind = $3`, + uuid.New(), org, pair.kind, pair.body, string(governance.SystemID)); err != nil { + return fmt.Errorf("store judgement %s: %w", pair.kind, err) + } + } + return nil +} + +func applyActionTypesTx(ctx context.Context, tx *sqlx.Tx, org string, types []BundleActionType) error { + for _, t := range types { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO judgement.action_types (id, org_id, connector, action, target_kind, environment, read_only, level) + VALUES ($1, $2, $3, $4, $5, $6, false, 'propose_and_wait') + ON CONFLICT (org_id, connector, action, target_kind, environment) DO NOTHING`, + uuid.New(), org, t.Connector, t.Action, t.TargetKind, t.Environment); err != nil { + return fmt.Errorf("ensure action type %s/%s: %w", t.Connector, t.Action, err) + } + } + return nil +} + +func logBundleApply(ctx context.Context, log *slog.Logger, stage string, dryRun bool, diff BundleDiff) { + log.InfoContext(ctx, "bundle apply", + "audit", true, + "stage", stage, + "dry_run", dryRun, + "empty", diff.Empty(), + "workflows_changed", len(diff.Workflows), + "access_policies_changed", len(diff.AccessPolicies), + "judgement_rules_changed", len(diff.JudgementRules), + "action_types_changed", len(diff.ActionTypes), + ) +} diff --git a/internal/app/archie/bundle_api.go b/internal/app/archie/bundle_api.go new file mode 100644 index 000000000..b6ce10de8 --- /dev/null +++ b/internal/app/archie/bundle_api.go @@ -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 ` (`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 [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 +} diff --git a/internal/app/archie/bundle_api_test.go b/internal/app/archie/bundle_api_test.go new file mode 100644 index 000000000..2951b57e6 --- /dev/null +++ b/internal/app/archie/bundle_api_test.go @@ -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) + } +} diff --git a/internal/app/archie/bundle_test.go b/internal/app/archie/bundle_test.go new file mode 100644 index 000000000..39d31f759 --- /dev/null +++ b/internal/app/archie/bundle_test.go @@ -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") + } +}