Files
archie/internal/webui/api_source.go
T
sam 3960a00f5d Feat/org epic (#1634)
* fix(postgres): scope OpenPRs to the caller's org

A principal-carrying caller read every org's pr_open tasks. The query now
honours the request scope; the daemon's unscoped review scan still sees all
orgs.

Issue: archie-core-kgxw.23

* fix(statestore): serve task logs only to the task's org

ReadTaskLog and StreamTaskLogContent took a task ID and read the file with
no org check. The State Store's task-log reader now confirms the task is
visible under the caller's scope first; unscoped services read as before.

Issue: archie-core-kgxw.24

* fix(postgres): scope ListPolicies to the caller's org

Every org's policy text reached any principal-carrying caller. A scoped read
now sees its own org's policies, plus instance policies when scoped to the
system org. The engines and the lockout guard decide for every org, so they
read the full chain unscoped: the dashboard engine loads without the
request's principal and the guard lifts the caller's scope.

Issue: archie-core-kgxw.25

* fix(postgres): scope identity reads to the caller's org

ListIdentities and GetIdentity (and its alias fallback) returned every
identity to any caller. A caller scoped to an org now sees only that org's
members and assigned agents; the system org and unscoped services still see
the whole instance.

Issue: archie-core-kgxw.26

* fix(postgres): hide instance status from other orgs

ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot
answered any org principal with instance-wide state. They now return nothing
unless the request is unscoped or scoped to the system org. The dashboard
reads the published config as itself, since its handlers project it for
callers of every org.

Issue: archie-core-kgxw.27

* feat(postgres): assign new agents an org and role at creation

A bot or service account created through the API served no org until the
next State Store boot granted it one. Create now assigns it to the org the
request acts in with the developer role in the same transaction, so it is
authorized immediately.

Issue: archie-core-kgxw.14

* feat(edastore): create event records in a chosen workspace

Sources are created in a workspace of the caller's org, the default one when
none is named; event types and bindings take their source's workspace and
mappings their event type's, the same rule the org backfill applied. The
binding, mapping and event type contracts carry the workspace, the four list
endpoints accept ?workspace=, and the Events page has a workspace selector
that filters every step and picks where a new source goes.

Issue: archie-core-kgxw.11

* feat(webui): authorize a record in its workspace

The API built every access request with no workspace, so workspace
policies and per-workspace roles never applied. A request naming a source,
binding, mapping, event type or task now reads the record's workspace under
the caller's scope and authorizes in it; tasks carry their workspace on the
State Store contract for this.

Issue: archie-core-kgxw.9

* feat(access): expose workspace environment to policies

Policies can test resource.workspace.environment. The workspace attribute
is the workspace entity, which carries its environment; the principal
brings its org's workspaces from the State Store, so the dashboard and the
daemon's run checks describe a resource's workspace without another lookup,
and the daemon now authorizes runs in the task's or binding's workspace.

Issue: archie-core-kgxw.10

* fix(webui): ask read_secret when a source secret is read

Rotating a source's secret returns its value, but the route asked update,
which every developer holds, so no policy could narrow who reads a secret.
It now asks read_secret on the secret, which the shipped roles give admins
and an object policy can narrow further.

Issue: archie-core-kgxw.17

* refactor(org): delete the unused upgrade-incomplete sentinel

Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org
upgrade before it serves.

Issue: archie-core-kgxw.18
2026-10-12 03:24:04 +11:00

292 lines
8.5 KiB
Go

package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// Capture sources and their signing setting. A secret is returned only by the
// two writes that generate it, so the operator can copy it into the sender;
// every other read withholds it. Turning signing off is a request plus an
// approval, both behind the same mutation gate that arms a binding.
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
list, err := s.Sources.ListSources(r.Context())
if err != nil {
s.Log.Error("list sources", "err", err)
http.Error(w, "list sources failed", http.StatusInternalServerError)
return
}
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
for i := range list {
list[i].Secret = ""
}
writeJSON(w, map[string]any{"sources": list, "refusals": s.recentRefusals(r)})
}
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
var req struct {
Path string `json:"path"`
// Workspace is the caller's org workspace to create it in; empty is
// the default one.
Workspace org.WorkspaceID `json:"workspace"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
src, err := source.New(req.Path)
if errors.Is(err, source.ErrInvalidPath) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err == nil {
src.WorkspaceID = req.Workspace
err = s.Sources.InsertSource(r.Context(), src)
}
if err != nil {
s.sourceError(w, "create source", err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, src)
}
// handleSourceSigning turns signing on at once, or requests turning it off.
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
var req struct {
Signed bool `json:"signed"`
}
if !s.authorizeTaskMutation(w, r) {
return
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
transition := (*source.Source).RequestUnsigned
if req.Signed {
transition = (*source.Source).RequireSigning
}
s.transitionSource(w, r, transition)
}
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
}
// transitionSource applies one domain signing transition and writes it with
// the state it was decided from, so a concurrent change is refused.
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
src, ok := s.loadSource(w, r)
if !ok {
return
}
from := src.Signing
if err := transition(src); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
s.sourceError(w, "set source signing", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceSecret generates a new secret and returns it once.
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
secret, err := source.NewSecret()
if err == nil {
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
}
if err != nil {
s.sourceError(w, "set source secret", err)
return
}
src.Secret = secret
writeJSON(w, src)
}
// handleSourceName relabels a source; its path does not change.
func (s *Server) handleSourceName(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
var request struct {
Name string `json:"name"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid source name", http.StatusBadRequest)
return
}
src.Name = strings.TrimSpace(request.Name)
if err := s.Sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
s.sourceError(w, "set source name", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDeliveryHeader sets the header that names a source's
// deliveries, so a sender's retry dispatches no second run.
func (s *Server) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
var request struct {
Header string `json:"header"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid delivery header", http.StatusBadRequest)
return
}
header, err := source.DeliveryHeader(request.Header)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
src.DeliveryHeader = header
if err := s.Sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
s.sourceError(w, "set source delivery header", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDelete deletes a source no armed binding fires on.
func (s *Server) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
if err := s.Sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
s.sourceError(w, "delete source", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return nil, false
}
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
if err != nil {
s.sourceError(w, "get source", err)
return nil, false
}
if src == nil {
http.Error(w, "source not found", http.StatusNotFound)
return nil, false
}
return src, true
}
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, storecontract.ErrSourcePathTaken):
http.Error(w, "source path already taken", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceSigningStale):
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceNotFound):
http.Error(w, "source not found", http.StatusNotFound)
case errors.Is(err, org.ErrInvalidWorkspace):
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
case errors.Is(err, storecontract.ErrSourceInUse):
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
default:
s.Log.Error(what, "err", err)
http.Error(w, what+" failed", http.StatusInternalServerError)
}
}
// unsignedSources is the set of source paths approved to take unsigned
// events. With no source store nothing is unsigned.
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
out := map[string]bool{}
if s.Sources == nil {
return out, nil
}
list, err := s.Sources.ListSources(ctx)
if err != nil {
return nil, err
}
for _, src := range list {
if src.Unsigned() {
out[src.Path] = true
}
}
return out, nil
}
// recentRefusals maps each source to what the network rules refused on it in
// the last day. Unavailable refusals leave the map empty.
func (s *Server) recentRefusals(r *http.Request) map[string]storecontract.CaptureRefusals {
out := map[string]storecontract.CaptureRefusals{}
if s.Refusals == nil {
return out
}
list, err := s.Refusals.CaptureRefusals(r.Context(), s.clock().Add(-24*time.Hour))
if err != nil {
s.Log.Warn("capture refusals unavailable", "err", err)
return out
}
for _, c := range list {
out[c.Source] = c
}
return out
}
// listedIn reports whether a record in ws belongs in a list the request
// narrowed with ?workspace=; with none, every record does.
func listedIn(r *http.Request, ws org.WorkspaceID) bool {
want := r.URL.Query().Get("workspace")
return want == "" || org.WorkspaceID(want) == ws
}