package webui import ( "context" "encoding/json" "io" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/scheduling" infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" ) // fakeSchedules is an in-memory ScheduleStore: the schedules the State Store // would hold, keyed by id, with Put recording what it was asked to store. type fakeSchedules struct { byID map[string]scheduling.Schedule runs map[string][]scheduling.Run put []scheduling.Schedule asked []string deleted []string } func newFakeSchedules(list ...scheduling.Schedule) *fakeSchedules { f := &fakeSchedules{byID: map[string]scheduling.Schedule{}, runs: map[string][]scheduling.Run{}} for _, s := range list { f.byID[s.ID] = s } return f } func (f *fakeSchedules) ListSchedules(context.Context) ([]scheduling.Schedule, error) { out := make([]scheduling.Schedule, 0, len(f.byID)) for _, s := range f.byID { out = append(out, s) } return out, nil } func (f *fakeSchedules) GetSchedule(_ context.Context, id string) (scheduling.Schedule, error) { s, ok := f.byID[id] if !ok { return scheduling.Schedule{}, scheduling.ErrNotFound } return s, nil } func (f *fakeSchedules) PutSchedule(_ context.Context, s scheduling.Schedule) (scheduling.Schedule, error) { if err := s.Validate(); err != nil { return scheduling.Schedule{}, err } f.byID[s.ID] = s f.put = append(f.put, s) return s, nil } func (f *fakeSchedules) DeleteSchedule(_ context.Context, id string) error { if _, ok := f.byID[id]; !ok { return scheduling.ErrNotFound } delete(f.byID, id) f.deleted = append(f.deleted, id) return nil } func (f *fakeSchedules) RequestScheduleRun(_ context.Context, id string) (scheduling.Run, error) { if _, ok := f.byID[id]; !ok { return scheduling.Run{}, scheduling.ErrNotFound } f.asked = append(f.asked, id) return scheduling.Run{ScheduleID: id, ScheduledFor: time.Now(), Result: scheduling.RunPending}, nil } func (f *fakeSchedules) ListScheduleRuns(_ context.Context, scheduleID string, _ int) ([]scheduling.Run, error) { return f.runs[scheduleID], nil } func instanceSchedule(id string) scheduling.Schedule { return scheduling.Schedule{ ID: id, Name: id, Owner: scheduling.Owner{Kind: scheduling.OwnerInstance}, Enabled: true, Timing: scheduling.Timing{Kind: scheduling.TimingInterval, Interval: scheduling.Duration(time.Hour)}, } } func orgSchedule(id, orgID string) scheduling.Schedule { return scheduling.Schedule{ ID: id, Name: id, Owner: scheduling.Owner{Kind: scheduling.OwnerOrg, ID: orgID}, Enabled: true, Timing: scheduling.Timing{Kind: scheduling.TimingInterval, Interval: scheduling.Duration(time.Hour)}, } } // scheduleRoutes is the schedule mux behind the same credential and authorise // wrappers the real server mounts. func scheduleRoutes(s *Server) http.Handler { mux := http.NewServeMux() newSchedulesAPI(s).register(mux) return s.requireToken(s.authorize(mux)) } // acmePrincipals gives the token-named identity a membership of the acme // org with the given role, as the State Store would report it. type acmePrincipals struct{ role org.Role } func (p acmePrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) { return access.Principal{ IdentityID: id, Org: "acme", Memberships: []org.Membership{{IdentityID: id, OrgID: "acme", Role: p.role}}, }, nil } // acmeServer is a dashboard wired as a member of the non-system org acme // would see it, with the shipped role policies of both orgs loaded. func acmeServer(schedules *fakeSchedules, role org.Role) *Server { engine := infraaccess.New(append( access.ShippedOrgPolicies(org.DefaultOrgID), access.ShippedOrgPolicies("acme")..., )) return &Server{ Access: engine, Principals: acmePrincipals{role: role}, Schedules: schedules, Authenticate: func(_ context.Context, token string) (identity.Identity, error) { return identity.Identity{ID: identity.IdentityID(token), Kind: identity.KindUser}, nil }, } } func scheduleRequest(t *testing.T, s *Server, method, path, body string) *httptest.ResponseRecorder { t.Helper() var reader io.Reader if body != "" { reader = strings.NewReader(body) } req := httptest.NewRequestWithContext(t.Context(), method, path, reader) req.Header.Set("Authorization", "Bearer dev") if body != "" { req.Header.Set("Content-Type", "application/json") } if method != http.MethodGet { req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Archie-CSRF", "1") } rec := httptest.NewRecorder() scheduleRoutes(s).ServeHTTP(rec, req) return rec } func scheduleIDs(t *testing.T, rec *httptest.ResponseRecorder) []string { t.Helper() var body struct { Schedules []scheduleView `json:"schedules"` } if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("decode %s: %v", rec.Body.String(), err) } ids := make([]string, 0, len(body.Schedules)) for _, s := range body.Schedules { ids = append(ids, s.ID) } return ids } // TestScheduleRoutesScopeByOrg drives the schedule API as a developer of the // non-system org acme: it lists only its own org's schedules, creates new ones // owned by that org, and reads another org's or the instance's schedule as // not found. func TestScheduleRoutesScopeByOrg(t *testing.T) { store := newFakeSchedules( instanceSchedule("nightly"), func() scheduling.Schedule { s := instanceSchedule("builtin-hourly"); s.BuiltIn = true; return s }(), orgSchedule("acme-daily", "acme"), orgSchedule("other-weekly", "other"), ) s := acmeServer(store, org.RoleDeveloper) t.Run("lists only the acting org's schedules", func(t *testing.T) { rec := scheduleRequest(t, s, http.MethodGet, "/api/schedules", "") if rec.Code != http.StatusOK { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } got := scheduleIDs(t, rec) if len(got) != 1 || got[0] != "acme-daily" { t.Fatalf("schedules = %v, want [acme-daily]", got) } }) t.Run("creates a schedule owned by the acting org", func(t *testing.T) { rec := scheduleRequest(t, s, http.MethodPut, "/api/schedules/acme-hourly", `{"name":"Hourly","enabled":true,"timing":{"kind":"interval","interval":"1h0m0s"}}`) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } var view scheduleView if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil { t.Fatalf("decode: %v", err) } if view.Owner.Kind != scheduling.OwnerOrg || view.Owner.ID != "acme" { t.Fatalf("owner = %+v, want org acme", view.Owner) } stored := store.byID["acme-hourly"] if stored.Owner.Kind != scheduling.OwnerOrg || stored.Owner.ID != "acme" { t.Fatalf("stored owner = %+v, want org acme", stored.Owner) } }) t.Run("updates its own schedule", func(t *testing.T) { rec := scheduleRequest(t, s, http.MethodPut, "/api/schedules/acme-daily", `{"name":"Daily","enabled":false,"timing":{"kind":"interval","interval":"24h0m0s"}}`) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } if store.byID["acme-daily"].Owner.ID != "acme" || store.byID["acme-daily"].Enabled { t.Fatalf("stored = %+v, want acme-owned and disabled", store.byID["acme-daily"]) } }) t.Run("another org's schedule reads as not found", func(t *testing.T) { rec := scheduleRequest(t, s, http.MethodPut, "/api/schedules/other-weekly", `{"name":"x","enabled":true,"timing":{"kind":"interval","interval":"1h0m0s"}}`) if rec.Code != http.StatusNotFound { t.Fatalf("PUT status = %d, want 404", rec.Code) } // A delete is an admin's grant, so a developer is refused before the // ownership check; an owner reaches it and gets the 404. rec = scheduleRequest(t, s, http.MethodDelete, "/api/schedules/other-weekly", "") if rec.Code != http.StatusForbidden { t.Fatalf("developer DELETE status = %d, want 403", rec.Code) } rec = scheduleRequest(t, acmeServer(store, org.RoleOwner), http.MethodDelete, "/api/schedules/other-weekly", "") if rec.Code != http.StatusNotFound { t.Fatalf("owner DELETE status = %d, want 404", rec.Code) } rec = scheduleRequest(t, s, http.MethodGet, "/api/schedules/other-weekly/runs", "") if rec.Code != http.StatusNotFound { t.Fatalf("runs status = %d, want 404", rec.Code) } rec = scheduleRequest(t, s, http.MethodPost, "/api/schedules/other-weekly/runs", "{}") if rec.Code != http.StatusNotFound { t.Fatalf("run-now status = %d, want 404", rec.Code) } }) t.Run("the instance's schedules read as not found", func(t *testing.T) { for _, id := range []string{"nightly", "builtin-hourly"} { rec := scheduleRequest(t, s, http.MethodPut, "/api/schedules/"+id, `{"name":"x","enabled":true,"timing":{"kind":"interval","interval":"1h0m0s"}}`) if rec.Code != http.StatusNotFound { t.Fatalf("PUT %s status = %d, want 404", id, rec.Code) } rec = scheduleRequest(t, acmeServer(store, org.RoleOwner), http.MethodDelete, "/api/schedules/"+id, "") if rec.Code != http.StatusNotFound { t.Fatalf("DELETE %s status = %d, want 404", id, rec.Code) } } }) t.Run("deletes and runs its own schedule", func(t *testing.T) { rec := scheduleRequest(t, s, http.MethodPost, "/api/schedules/acme-daily/runs", "{}") if rec.Code != http.StatusOK { t.Fatalf("run-now status = %d, body %s", rec.Code, rec.Body.String()) } rec = scheduleRequest(t, s, http.MethodGet, "/api/schedules/acme-daily/runs", "") if rec.Code != http.StatusOK { t.Fatalf("runs status = %d, body %s", rec.Code, rec.Body.String()) } rec = scheduleRequest(t, acmeServer(store, org.RoleOwner), http.MethodDelete, "/api/schedules/acme-daily", "") if rec.Code != http.StatusNoContent { t.Fatalf("delete status = %d, body %s", rec.Code, rec.Body.String()) } if _, ok := store.byID["acme-daily"]; ok { t.Fatal("schedule still stored after delete") } }) } type fixedPrincipals struct{ principal access.Principal } func (f fixedPrincipals) PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error) { return f.principal, nil } // TestScheduleRoutesSystemOrgUnchanged pins the system org's view: every // schedule is listed, a new one belongs to the instance, and a developer's // write stays instance administration, which the shipped policies refuse. func TestScheduleRoutesSystemOrgUnchanged(t *testing.T) { store := newFakeSchedules(instanceSchedule("nightly"), orgSchedule("acme-daily", "acme")) engine := infraaccess.New(access.ShippedOrgPolicies(org.DefaultOrgID)) newServer := func(role org.Role) *Server { return &Server{ Access: engine, Schedules: store, Principals: fixedPrincipals{principal: access.Principal{ IdentityID: "dev", Org: org.DefaultOrgID, Memberships: []org.Membership{{IdentityID: "dev", OrgID: org.DefaultOrgID, Role: role}}, }}, Authenticate: func(_ context.Context, token string) (identity.Identity, error) { return identity.Identity{ID: identity.IdentityID(token), Kind: identity.KindUser}, nil }, } } t.Run("lists every schedule", func(t *testing.T) { rec := scheduleRequest(t, newServer(org.RoleOwner), http.MethodGet, "/api/schedules", "") if rec.Code != http.StatusOK { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } if got := scheduleIDs(t, rec); len(got) != 2 { t.Fatalf("schedules = %v, want both", got) } }) t.Run("creates an instance-owned schedule", func(t *testing.T) { rec := scheduleRequest(t, newServer(org.RoleOwner), http.MethodPut, "/api/schedules/weekly", `{"name":"Weekly","enabled":true,"timing":{"kind":"interval","interval":"168h0m0s"}}`) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } if got := store.byID["weekly"].Owner; got.Kind != scheduling.OwnerInstance { t.Fatalf("owner = %+v, want instance", got) } }) t.Run("a developer's write is instance administration and refused", func(t *testing.T) { rec := scheduleRequest(t, newServer(org.RoleDeveloper), http.MethodPut, "/api/schedules/acme-daily", `{"name":"x","enabled":true,"timing":{"kind":"interval","interval":"1h0m0s"}}`) if rec.Code != http.StatusForbidden { t.Fatalf("status = %d, want 403", rec.Code) } }) } // TestScheduleRouteMapping pins the action the authorise chain derives for // the schedule routes: instance administration in the system org, an // ordinary org-resource write for any other org. func TestScheduleRouteMapping(t *testing.T) { acme := access.Principal{Org: "acme", Memberships: []org.Membership{{OrgID: "acme", Role: org.RoleDeveloper}}} tests := []struct { name string principal *access.Principal method string path string wantAction access.Action wantKind access.ResourceKind }{ {"no principal is the instance", nil, http.MethodPut, "/api/schedules/nightly", access.ActionManageIdentities, access.KindPolicy}, {"the system org is the instance", &access.Principal{Org: org.DefaultOrgID}, http.MethodPut, "/api/schedules/nightly", access.ActionManageIdentities, access.KindPolicy}, {"the system org reads", &access.Principal{Org: org.DefaultOrgID}, http.MethodGet, "/api/schedules", access.ActionRead, access.KindPolicy}, {"another org updates its own", &acme, http.MethodPut, "/api/schedules/acme-daily", access.ActionUpdate, access.KindSchedule}, {"another org reads", &acme, http.MethodGet, "/api/schedules", access.ActionRead, access.KindSchedule}, {"another org runs one", &acme, http.MethodPost, "/api/schedules/acme-daily/runs", access.ActionCreate, access.KindSchedule}, {"another org deletes", &acme, http.MethodDelete, "/api/schedules/acme-daily", access.ActionDelete, access.KindSchedule}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := t.Context() if tt.principal != nil { ctx = access.WithPrincipal(ctx, *tt.principal) } action, kind, id := accessRequest(httptest.NewRequestWithContext(ctx, tt.method, tt.path, nil)) if action != tt.wantAction || kind != tt.wantKind { t.Fatalf("accessRequest = %q on %q, want %q on %q", action, kind, tt.wantAction, tt.wantKind) } if strings.Contains(tt.path, "{id}") && id == "" { t.Fatal("record key is empty") } }) } }