feat(webui): org-scoped schedules for non-system orgs (#1639 #1051 #49)

This commit is contained in:
sam committed 2026-10-31 14:25:24 +11:00
1 parent da01f2cbe1
commit 3212437b8d
13 files changed
+633 -110

No files matched your search

+1
View File
@@ -101,6 +101,7 @@ const (
KindIdentity ResourceKind = "identity"
KindPolicy ResourceKind = "policy"
KindMember ResourceKind = "member"
KindSchedule ResourceKind = "schedule"
KindDashboard ResourceKind = "dashboard"
KindEventIngest ResourceKind = "event"
KindAudit ResourceKind = "audit"
+5
View File
@@ -249,6 +249,11 @@ func (s *Store) AssignAgent(ctx context.Context, value org.AgentAssignment) erro
}); err != nil {
return err
}
// EnsureAgentOrgMembership only runs at boot, so an agent assigned
// later still needs its developer membership in the assigned org.
if err := q.EnsureAgentOrgMembershipFor(ctx, string(value.IdentityID)); err != nil {
return err
}
// A move is two facts: the identity joins the target org and leaves the
// old one, each filed under the org it belongs to.
if err := insertAuditValues(ctx, q, "org_agents", string(value.OrgID)+"/"+string(value.IdentityID), "org_id",
@@ -38,6 +38,20 @@ func (q *Queries) EnsureAgentOrgMembership(ctx context.Context) error {
return err
}
const ensureAgentOrgMembershipFor = `-- name: EnsureAgentOrgMembershipFor :exec
INSERT INTO memberships (identity_id, org_id, role)
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
WHERE a.identity_id = $1
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING
`
// Same grant as EnsureAgentOrgMembership for one identity: an agent assigned
// to an org after boot (AssignAgent) still gets the developer membership there.
func (q *Queries) EnsureAgentOrgMembershipFor(ctx context.Context, identityID string) error {
_, err := q.db.Exec(ctx, ensureAgentOrgMembershipFor, identityID)
return err
}
const ensureMembership = `-- name: EnsureMembership :exec
INSERT INTO memberships (identity_id, org_id, workspace_id, role)
VALUES ($1, $2, $3, $4)
@@ -79,6 +79,14 @@ INSERT INTO memberships (identity_id, org_id, role)
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING;
-- name: EnsureAgentOrgMembershipFor :exec
-- Same grant as EnsureAgentOrgMembership for one identity: an agent assigned
-- to an org after boot (AssignAgent) still gets the developer membership there.
INSERT INTO memberships (identity_id, org_id, role)
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
WHERE a.identity_id = $1
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING;
-- name: ListOrgOwners :many
SELECT identity_id FROM memberships
WHERE org_id = $1 AND workspace_id IS NULL AND role = 'owner'
+63 -2
View File
@@ -131,6 +131,44 @@ func (s *Server) schedulesReady(w http.ResponseWriter) bool {
return true
}
// scheduleScope is the org a schedule request acts in and whether that org is
// the system org, which operates the instance. A request without a principal
// is an install without the access chain, whose operator is the system org.
func scheduleScope(r *http.Request) (org.OrgID, bool) {
id := org.OrgFromContext(r.Context())
return id, id == org.DefaultOrgID
}
// scheduleOwned reports whether the acting org may see and change sched. The
// system org operates the instance and may act on every schedule; any other
// org only on the schedules it owns, and another org's or the instance's
// schedule reads as absent to it.
func scheduleOwned(instance bool, orgID org.OrgID, sched scheduling.Schedule) bool {
if instance {
return true
}
return sched.Owner.Kind == scheduling.OwnerOrg && sched.Owner.ID == string(orgID)
}
// ownedSchedule reads the named schedule and reports whether the acting org
// owns it, answering not found when it does not exist or belongs elsewhere.
func (s *Server) ownedSchedule(w http.ResponseWriter, r *http.Request, id string) (scheduling.Schedule, bool) {
orgID, instance := scheduleScope(r)
sched, err := s.Schedules.GetSchedule(r.Context(), id)
switch {
case errors.Is(err, scheduling.ErrNotFound):
http.Error(w, "schedule not found", http.StatusNotFound)
return scheduling.Schedule{}, false
case err != nil:
s.scheduleError(r.Context(), w, "get schedule", err)
return scheduling.Schedule{}, false
case !scheduleOwned(instance, orgID, sched):
http.Error(w, "schedule not found", http.StatusNotFound)
return scheduling.Schedule{}, false
}
return sched, true
}
func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
if !s.schedulesReady(w) {
return
@@ -140,16 +178,22 @@ func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
s.scheduleError(r.Context(), w, "list schedules", err)
return
}
orgID, instance := scheduleScope(r)
names := map[org.OrgID]string{}
views := make([]scheduleView, 0, len(list))
for _, sched := range list {
if !scheduleOwned(instance, orgID, sched) {
continue
}
views = append(views, s.scheduleView(r.Context(), sched, names))
}
writeJSON(w, map[string]any{"schedules": views})
}
// handleSchedulePut creates the schedule or replaces what the dashboard may
// change on it. New schedules belong to the instance.
// change on it. A new schedule belongs to the instance when the system org
// writes it and to the acting org otherwise; an existing schedule must be the
// acting org's own.
func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
return
@@ -160,13 +204,21 @@ func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
return
}
id := r.PathValue("id")
orgID, instance := scheduleScope(r)
sched, err := s.Schedules.GetSchedule(r.Context(), id)
switch {
case errors.Is(err, scheduling.ErrNotFound):
sched = scheduling.Schedule{ID: id, Owner: scheduling.Owner{Kind: scheduling.OwnerInstance}}
owner := scheduling.Owner{Kind: scheduling.OwnerInstance}
if !instance {
owner = scheduling.Owner{Kind: scheduling.OwnerOrg, ID: string(orgID)}
}
sched = scheduling.Schedule{ID: id, Owner: owner}
case err != nil:
s.scheduleError(r.Context(), w, "get schedule", err)
return
case !scheduleOwned(instance, orgID, sched):
http.Error(w, "schedule not found", http.StatusNotFound)
return
}
sched.Name, sched.Enabled, sched.Timing = input.Name, input.Enabled, input.Timing
saved, err := s.Schedules.PutSchedule(r.Context(), sched)
@@ -181,6 +233,9 @@ func (s *Server) handleScheduleDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
return
}
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
return
}
if err := s.Schedules.DeleteSchedule(r.Context(), r.PathValue("id")); err != nil {
s.scheduleError(r.Context(), w, "delete schedule", err)
return
@@ -192,6 +247,9 @@ func (s *Server) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
return
}
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
return
}
run, err := s.Schedules.RequestScheduleRun(r.Context(), r.PathValue("id"))
if err != nil {
s.scheduleError(r.Context(), w, "run schedule", err)
@@ -206,6 +264,9 @@ func (s *Server) handleScheduleRuns(w http.ResponseWriter, r *http.Request) {
if !s.schedulesReady(w) {
return
}
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
return
}
runs, err := s.Schedules.ListScheduleRuns(r.Context(), r.PathValue("id"), scheduleRunsShown)
if err != nil {
s.scheduleError(r.Context(), w, "list schedule runs", err)
+369
View File
@@ -0,0 +1,369 @@
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 authorize
// wrappers the real server mounts.
func scheduleRoutes(s *Server) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/schedules", s.handleSchedules)
mux.HandleFunc("PUT /api/schedules/{id}", s.handleSchedulePut)
mux.HandleFunc("DELETE /api/schedules/{id}", s.handleScheduleDelete)
mux.HandleFunc("GET /api/schedules/{id}/runs", s.handleScheduleRuns)
mux.HandleFunc("POST /api/schedules/{id}/runs", s.handleScheduleRunNow)
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 authorize 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")
}
})
}
}
+31 -14
View File
@@ -41,8 +41,8 @@ func (s *Server) authorize(h http.Handler) http.Handler {
http.Error(w, "principal unavailable", http.StatusServiceUnavailable)
return
}
action, kind, id := accessRequest(r)
ctx := org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)
action, kind, id := accessRequest(r.WithContext(ctx))
// The record's org is not loaded here: org-filtered lookups keep a
// record of another org from ever being fetched, and this request's
// record (when it has an ID) belongs to the caller's org. The
@@ -273,7 +273,7 @@ func accessRequest(r *http.Request) (access.Action, access.ResourceKind, string)
// export route below the same prefix carries the same grant.
return access.ActionReadAudit, access.KindAudit, ""
}
if a, kind, id, ok := routeOverride(action, path); ok {
if a, kind, id, ok := routeOverride(r, action, path); ok {
return a, kind, id
}
return action, kindOf(path), segmentValue(path, 2)
@@ -295,7 +295,7 @@ func actionOf(method string) access.Action {
// routeOverride returns the action, kind and record key a specific route
// shape carries, or ok=false when the method-and-kind fallback applies.
func routeOverride(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
func routeOverride(r *http.Request, action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if a, kind, ok := accountRoute(path); ok {
return a, kind, "", true
}
@@ -311,10 +311,10 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res
return actionManage(action), access.KindIdentity, segmentValue(path, 2), true
case matchPrefix(path, "/api/orgs"):
return orgRouteAction(action, path), access.KindOrg, segmentValue(path, 2), true
case matchPrefix(path, "/api/extensions"), matchPrefix(path, "/api/schedules"):
// Installing and enabling an extension runs a process on the host, and
// a schedule runs unattended as the instance, so both are the same
// administration as editing a control-plane resource.
case matchPrefix(path, "/api/schedules"):
return scheduleRoute(r, action, path)
case matchPrefix(path, "/api/extensions"):
// Installing and enabling an extension runs a process on the host.
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
case matchPrefix(path, "/api/control-plane/resources"):
return controlPlaneResourceRoute(action, path)
@@ -328,17 +328,34 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res
return access.ActionUpdate, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/bindings"):
return access.ActionRead, access.KindSecret, "", true
case matchPrefix(path, "/api/channels"):
return actionManage(action), access.KindDashboard, segmentValue(path, 2), true
case matchPrefix(path, "/api/config"), matchPrefix(path, "/api/logs"),
// A person's own tokens act only as that person, so managing them
// needs no more than reading the dashboard.
matchPrefix(path, "/api/tokens"):
return access.ActionRead, access.KindDashboard, "", true
case matchPrefix(path, "/api/channels"), matchPrefix(path, "/api/config"),
matchPrefix(path, "/api/logs"), matchPrefix(path, "/api/tokens"):
return dashboardRoute(action, path)
}
return action, "", "", false
}
// dashboardRoute maps the dashboard's own routes: channel settings are
// instance administration, while config, logs and a person's own tokens act
// only as that person, needing no more than a dashboard read.
func dashboardRoute(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if matchPrefix(path, "/api/channels") {
return actionManage(action), access.KindDashboard, segmentValue(path, 2), true
}
return access.ActionRead, access.KindDashboard, "", true
}
// scheduleRoute maps a schedule request. A schedule the system org owns runs
// unattended as the instance, so there it is the same administration as a
// control-plane resource. A schedule another org owns fires in that org, so
// there it is an ordinary org resource its members may create and update.
func scheduleRoute(r *http.Request, action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if p, ok := access.PrincipalFromContext(r.Context()); ok && p.Org != org.DefaultOrgID {
return action, access.KindSchedule, segmentValue(path, 2), true
}
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
}
// controlPlaneResourceRoute maps a control-plane resource request. History
// returns the raw stored revisions, including secret references and policy
// text, because restore re-applies the real value: that is stronger than the
+11 -7
View File
@@ -213,8 +213,9 @@ type Server struct {
// routes 503 and lists bindings without their last outcome.
Dispatches storecontract.DispatchLedger
// Schedules reads and edits the instance's schedules and their runs. Nil
// answers the /api/schedules routes 503.
// Schedules reads and edits schedules and their runs: every schedule to
// the system org, only the acting org's own to any other. Nil answers the
// /api/schedules routes 503.
Schedules ScheduleStore
// Sources persists capture sources and their signing setting.
@@ -292,11 +293,14 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/skills", instanceOnly(s.handleSkills))
mux.HandleFunc("GET /api/curators", instanceOnly(s.handleCurators))
mux.HandleFunc("GET /api/captures", s.handleCaptures)
mux.HandleFunc("GET /api/schedules", instanceOnly(s.handleSchedules))
mux.HandleFunc("PUT /api/schedules/{id}", instanceOnly(s.handleSchedulePut))
mux.HandleFunc("DELETE /api/schedules/{id}", instanceOnly(s.handleScheduleDelete))
mux.HandleFunc("GET /api/schedules/{id}/runs", instanceOnly(s.handleScheduleRuns))
mux.HandleFunc("POST /api/schedules/{id}/runs", instanceOnly(s.handleScheduleRunNow))
// Schedule routes are org-scoped, not instance-only: the system org sees
// every schedule, any other org only its own, and the handlers enforce
// that ownership.
mux.HandleFunc("GET /api/schedules", s.handleSchedules)
mux.HandleFunc("PUT /api/schedules/{id}", s.handleSchedulePut)
mux.HandleFunc("DELETE /api/schedules/{id}", s.handleScheduleDelete)
mux.HandleFunc("GET /api/schedules/{id}/runs", s.handleScheduleRuns)
mux.HandleFunc("POST /api/schedules/{id}/runs", s.handleScheduleRunNow)
mux.HandleFunc("GET /api/channels", instanceOnly(s.handleChannels))
mux.HandleFunc("POST /api/channels/{id}/reload", instanceOnly(s.handleChannelReload))
mux.HandleFunc("GET /api/version", s.handleVersion)