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

270 lines
9.4 KiB
Go

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)
}
}