Files
archie/internal/app/archie/bundle_test.go
T

457 lines
14 KiB
Go

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 serialisation 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 normalisation 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")
}
}