Files
archie/internal/webui/api_tasks.go
T
sam 8e4e353805 feat(identity): attribute a task action to the identity that acted
The transport could carry an actor and nothing filled it. It does now, so a
dashboard approval is recorded as the person whose credential verified, and an
agent's token is recorded as the agent's action -- for an agent, agent_approved;
for a person, human_approved; and for a caller whose identity archie could not
verify, task_approved, which claims nothing about who did it.

The actor travels the path the action takes: webui reads it from the request
context the middleware resolved, carries it in the gateway request, the daemon
passes it through the in-process adapter, and the NATS request body carries it to
the service that records it. Scope stays separate from actor at every hop, because
scope is which task a caller may touch and the actor is who touched it.

A chat channel's bound identity is an actor too: a bot acting on its own channel's
task is recorded as an agent's action rather than a person's, via ActorFromScope,
whose empty kind is what keeps it out of human_approved. The agent-facing
task_action tool passes that identity and never input["identity"].

The UI process's credential check is now filled by endpoint references rather than
by configuration: -oidc-issuer and -oidc-audience on archie-ui, two URLs the
process already understands the shape of, with the verifier built in Run because
cmd/ parses flags and nothing else. The UI package still never reads config, and a
configured provider that cannot be reached fails boot rather than falling back to
the gate that names nobody.

Evidence for this change, stated as measured: go build ./... and go vet ./... are
clean, and every package this touches passes -- webui, domain/taskactions,
infrastructure/taskactions, infrastructure/gatewayrpc, gateway, app/archieui,
app/archied, domain/messaging, channels/telegram, cmd/archie-ui. task check could
not be run to completion: it fails in cmd/archie-messaging on an untracked
internal/buildinfo package another lane has in flight, which is not this change and
was left untouched. The end-to-end flip is covered in
internal/webui/api_tasks_actor_test.go: a person's credential produces a record
naming that person with human_approved, an agent's produces agent_approved, an
unverified request produces task_approved with no actor, and a request carrying
forged actor fields cannot name one.
2026-09-22 14:52:10 +10:00

385 lines
13 KiB
Go

package webui
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
func (s *Server) handleSummary(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
statuses, err := s.Store.StatusCounts(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
workflows, err := s.Store.WorkflowStats(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stages, err := s.Store.StageStats(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
days, err := s.Store.TokensByDay(ctx, 14)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, map[string]any{
"statuses": statuses, "workflows": workflows,
"stages": stages, "tokens_by_day": days,
})
}
func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
tasks, err := s.Store.Tasks(r.Context(), 100)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
forge := s.resolveForge(r.Context())
views := make([]taskView, len(tasks))
for i := range tasks {
repoURL, issueURL, prURL := taskURLs(tasks[i], forge(tasks[i]))
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL}
}
writeJSON(w, views)
}
type taskView struct {
task.Task
Actions []taskstate.Action `json:"actions"`
RepoURL string `json:"repo_url,omitempty"`
IssueURL string `json:"issue_url,omitempty"`
PRURL string `json:"pr_url,omitempty"`
}
// forgeCoordinates locate a repository on its forge: the base URL, and the
// forge type that decides the pull-request path segment.
type forgeCoordinates struct {
host string
forgeType string
}
// resolveForge reads the forge layout once for a request and returns each
// task's coordinates from it.
//
// The projection publishes per-identity forges (ConfigView.Identities), so a
// multi-identity deployment links each task to the forge that owns it. The
// matching rules are the ones recovered from the pre-cutover resolver
// (forgeConfigForTask, 57d9be5): an exact identity name first, then repository
// ownership, and an ambiguous repository -- two identities claiming the same
// owner/name -- falling back to the default forge rather than pointing at
// either. Without this, every row in such a deployment renders unlinked.
func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} }
view, ok, err := s.configSource()(ctx)
if err != nil || !ok {
return unlinked
}
if len(view.Identities) == 0 {
// Nothing per-identity was published. A single-identity deployment's
// one forge is the whole answer. A document that reports identities
// but carries none is one an older daemon published, and there is
// nothing to attribute a task to -- so the links are withheld rather
// than pointed at the wrong forge.
if view.MultiIdentity {
return unlinked
}
published := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType}
return func(task.Task) forgeCoordinates { return published }
}
return forgeLocator(view)
}
// ownedRepo identifies a repository within an identity's repo list.
type ownedRepo struct{ owner, name string }
// forgeLocator indexes a published projection's per-identity forges once per
// request and resolves each task against them: exact identity name, then repo
// ownership, with an ambiguous repo falling back to the default forge.
func forgeLocator(view ConfigView) func(task.Task) forgeCoordinates {
fallback := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType}
byName := make(map[string]forgeCoordinates, len(view.Identities))
byRepo := make(map[ownedRepo]forgeCoordinates)
// ambiguous records a repo two identities both claim, which ownership
// cannot decide -- it is answered by the default forge instead.
ambiguous := make(map[ownedRepo]bool)
for _, identity := range view.Identities {
coords := forgeCoordinates{host: identity.ForgeHost, forgeType: identity.ForgeType}
// First definition of a name wins, as the recovered resolver's
// forward scan did (and as daemon.identityFor still does), so the two
// agree even if a config ever names one identity twice.
if _, seen := byName[identity.Name]; !seen {
byName[identity.Name] = coords
}
for _, repo := range identity.Repos {
key := ownedRepo{owner: repo.Owner, name: repo.Name}
if _, seen := byRepo[key]; seen {
ambiguous[key] = true
continue
}
byRepo[key] = coords
}
}
return func(t task.Task) forgeCoordinates {
if t.Identity != "" {
if coords, ok := byName[t.Identity]; ok {
return coords
}
}
key := ownedRepo{owner: t.Owner, name: t.Repo}
if ambiguous[key] {
return fallback
}
if coords, ok := byRepo[key]; ok {
return coords
}
return fallback
}
}
func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL string) {
if forge.host == "" || task.Owner == "" || task.Repo == "" {
return "", "", ""
}
repoURL = strings.TrimRight(forge.host, "/") + "/" + url.PathEscape(task.Owner) + "/" + url.PathEscape(task.Repo)
if task.IsForgeBacked() && task.IssueNumber > 0 {
issueURL = repoURL + "/issues/" + strconv.Itoa(task.IssueNumber)
}
if task.PRNumber > 0 {
segment := "pull"
if forge.forgeType == "gitea" {
segment = "pulls"
}
prURL = repoURL + "/" + segment + "/" + strconv.Itoa(task.PRNumber)
}
return repoURL, issueURL, prURL
}
func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
evs, err := s.Store.TaskEvents(r.Context(), id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, evs)
}
type taskActionRequest struct {
Action string `json:"action"`
}
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
action, ok := decodeTaskAction(w, r)
if !ok {
return
}
if err := s.applyOperatorTaskAction(r.Context(), id, action); err != nil {
switch {
case errors.Is(err, taskactions.ErrNotFound):
http.Error(w, "task not found", http.StatusNotFound)
case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storecontract.ErrStaleTransition):
http.Error(w, err.Error(), http.StatusConflict)
case errors.Is(err, taskactions.ErrUnavailable):
http.Error(w, err.Error(), http.StatusServiceUnavailable)
default:
s.logf("task action failed", "task", id, "err", err)
http.Error(w, "task action failed", http.StatusInternalServerError)
}
return
}
writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id})
}
func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, bool) {
r.Body = http.MaxBytesReader(w, r.Body, 4096)
var req taskActionRequest
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&req); err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
http.Error(w, "action body too large", http.StatusRequestEntityTooLarge)
return "", false
}
http.Error(w, "invalid action", http.StatusBadRequest)
return "", false
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
http.Error(w, "invalid action", http.StatusBadRequest)
return "", false
}
action := taskstate.Action(req.Action)
if !taskMutation(action) {
http.Error(w, "unknown action", http.StatusBadRequest)
return "", false
}
return action, true
}
func taskMutation(action taskstate.Action) bool {
switch action {
case taskstate.ActionCancel, taskstate.ActionStop, taskstate.ActionApprove,
taskstate.ActionReject, taskstate.ActionRetry, taskstate.ActionAbandon,
taskstate.ActionArchive:
return true
default:
return false
}
}
// authorizeTaskMutation applies the browser mutation contract at the handler
// boundary: JSON only, a non-simple custom header, and a matching Origin when
// the browser supplies one. The custom header forces cross-origin callers
// through a CORS preflight, which this server never permits.
//
// Origin comparison previously validated against the daemon's own direct network
// connection (r.TLS). It now validates against the effective external scheme
// and host, deriving them from X-Forwarded-Proto and X-Forwarded-Host only when
// explicit proxy header trust is enabled (Web.TrustForwardedHeaders). When trust
// is disabled (the default), forwarded headers are ignored to prevent untrusted
// clients from forging Origin scheme checks on exposed daemons.
func (s *Server) authorizeTaskMutation(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("X-Archie-CSRF") != "1" {
http.Error(w, "missing CSRF header", http.StatusForbidden)
return false
}
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
return false
}
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
u, err := url.Parse(origin)
if err != nil {
http.Error(w, "cross-origin mutation refused", http.StatusForbidden)
return false
}
wantScheme, wantHost := s.expectedOrigin(r)
if !validOrigin(u, wantScheme, wantHost) {
http.Error(w, "cross-origin mutation refused", http.StatusForbidden)
return false
}
return true
}
func (s *Server) expectedOrigin(r *http.Request) (scheme, host string) {
scheme = "http"
if r.TLS != nil {
scheme = "https"
}
host = r.Host
if s == nil || !s.trustForwardedHeaders() {
return scheme, host
}
if proto := firstForwardedValue(r.Header.Get("X-Forwarded-Proto")); proto != "" {
scheme = strings.ToLower(proto)
}
if fHost := firstForwardedValue(r.Header.Get("X-Forwarded-Host")); fHost != "" {
host = fHost
}
return scheme, host
}
func firstForwardedValue(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
if first, _, ok := strings.Cut(raw, ","); ok {
raw = first
}
return strings.TrimSpace(raw)
}
func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
if u == nil || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
return false
}
return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost)
}
// applyOperatorTaskAction sends the action to whoever owns task execution.
// The dashboard operator is authenticated and acts across identities, which
// the Gateway contract carries as its own method (archie-core-8cda.5.4).
//
// The UI process cannot run this itself: retry limits come from the daemon's
// configuration, closing the forge issue needs its forge client, the
// timeline needs its event bus, and stopping running work needs the
// goroutine or container that is executing it. Composing a local service
// over the task store alone would silently drop all four.
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action) error {
if s.Chat == nil || s.Chat.Contract == nil {
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
}
// The actor comes from the credential the middleware resolved and never from
// the request, so a caller cannot claim to be someone it did not authenticate
// as. An unauthenticated request (the shared-token gate) carries no identity,
// and the action is then recorded unattributed rather than as a human's.
actor := taskactions.Actor{}
if value, ok := ActingIdentity(ctx); ok {
actor = taskactions.ActorFor(value)
}
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action)
return err
}
// emit publishes an operator action so it reaches the task timeline and the
// live activity stream. A nil publisher is not an error: the action is still
// recorded in the store.
func (s *Server) emit(ctx context.Context, e events.Event) {
if e.Kind == "" {
return
}
if e.ID == 0 {
id, err := s.Store.InsertEvent(ctx, e)
if err != nil {
s.logf("operator activity persistence failed", "kind", e.Kind, "task", e.TaskID, "err", err)
} else {
e.ID = id
}
}
if s.Events != nil {
s.Events.Publish(e)
}
}
func (s *Server) logf(msg string, args ...any) {
if s.Log == nil {
return
}
s.Log.Warn(msg, args...)
}