Files
archie/internal/webui/api_identities.go
T
sam c180a2debb
Quality / check (push) Successful in 3m49s
deploy / gate (push) Successful in 4m48s
deploy / archied-image (push) Successful in 2m55s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
feat(access): scoped canary grant replaces instance-admin CANARY_TOKEN (#1727)
The canary now authenticates as a dedicated service-account identity in the
system org whose only grant is access.CalaryGrantPolicy: read the signal
endpoints (chat update, alerts, logs, tasks), read and write the
update-settings resource, and trigger an update install. CANARY_TOKEN no
longer carries instance admin; DEPLOY_TOKEN stays CI-only.

- authorize: POST /api/chat/update/install and /defer map to
  update on Object::"update" (dashboard) instead of run on any workflow,
  so the grant can cover installs without granting workflow runs
- accounts: active service-account identities may authenticate with bearer
  tokens (CanAct), not just users
- new POST /api/identities/{id}/tokens (behind manage_identities) mints a
  token for a named non-user identity; new AccountService RPC
  BindIdentityPersonalToken backs it remotely, refusing user-kind targets,
  with the caller recorded as audit actor
- engine tests pin the grant's exact allow/deny surface

RELEASING.md documents the one-time setup. task check passes on this tree.
2026-11-02 06:03:41 +11:00

189 lines
6.1 KiB
Go

package webui
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"net/http"
"strings"
"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/infrastructure/staterpc"
)
// identityTokenBinder is the one store-side operation the per-identity token
// route needs: binding a token to a NAMED identity. The remote client's
// caller-scoped PersonalTokens view cannot express that, so the store fronts
// it as its own RPC and the Client carries it under this name.
type identityTokenBinder interface {
BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error
}
// The production store client satisfies the route's narrow contract.
var _ identityTokenBinder = (*staterpc.Client)(nil)
type identityRequest struct {
DisplayName string `json:"display_name"`
Kind identity.Kind `json:"kind"`
ExpectedVersion int64 `json:"expected_version"`
}
func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
if s.Identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
values, err := s.Identities.List(r.Context())
if err != nil {
writeIdentityError(w, err)
return
}
if values == nil {
values = []identity.Identity{}
}
writeJSON(w, map[string]any{"identities": values})
}
func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[identityRequest](w, r)
if !ok {
return
}
id, err := randomIdentityID()
if err != nil {
http.Error(w, "cannot create identity ID", http.StatusInternalServerError)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
value, err := identity.New(id, request.Kind, request.DisplayName)
if err == nil {
value, err = s.Identities.Create(r.Context(), value, audit)
}
if err != nil {
writeIdentityError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, value)
}
func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[identityRequest](w, r)
if !ok {
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
command := identity.Command{Type: identity.CommandType(r.PathValue("command")), DisplayName: request.DisplayName}
value, err := s.Identities.Apply(r.Context(), identity.IdentityID(r.PathValue("id")), request.ExpectedVersion, command, audit)
if err != nil {
writeIdentityError(w, err)
return
}
writeJSON(w, value)
}
// handleIdentityTokenCreate issues an API token for one named identity, which
// is how a non-user identity gets its bearer credential: a person's token
// comes from /api/tokens, a service account's from here. The raw token is
// returned exactly once; the store keeps only its hash.
func (s *Server) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
id := identity.IdentityID(r.PathValue("id"))
if s.Identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
value, err := s.Identities.Get(r.Context(), id)
if errors.Is(err, identity.ErrNotFound) {
http.Error(w, "No such identity.", http.StatusBadRequest)
return
}
if err != nil {
writeIdentityError(w, err)
return
}
if !value.CanAct() {
http.Error(w, "That identity may not act.", http.StatusConflict)
return
}
name, expiresAt, ok := decodeTokenRequest(w, r)
if !ok {
return
}
// The store side of the PersonalTokens contract binds a token to a named
// identity; the remote caller's view only ever names its own principal.
binder, ok := s.PersonalTokens.(identityTokenBinder)
if !ok {
http.Error(w, "identity token binding unavailable", http.StatusServiceUnavailable)
return
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
if err := binder.BindPersonalToken(r.Context(), id, subject, name, expiresAt, audit); err != nil {
writeIdentityError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
}
// webAudit attributes a dashboard write to the request's own principal: the
// person the dashboard acts as. Only a request with no principal at all falls
// back to the System identity, which is a real identity the repository
// resolves, never a name the request could claim for itself.
func webAudit(ctx context.Context) (identity.Audit, error) {
id, err := newControlPlaneRequestID()
if err != nil {
return identity.Audit{}, err
}
actor := identity.SystemID
if p, ok := access.PrincipalFromContext(ctx); ok && p.IdentityID != "" {
actor = p.IdentityID
}
return identity.Audit{ActorID: actor, Source: "archie-ui", RequestID: id}, nil
}
func randomIdentityID() (identity.IdentityID, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
value[6] = value[6]&0x0f | 0x40
value[8] = value[8]&0x3f | 0x80
encoded := hex.EncodeToString(value[:])
return identity.IdentityID(encoded[:8] + "-" + encoded[8:12] + "-" + encoded[12:16] + "-" + encoded[16:20] + "-" + encoded[20:]), nil
}
func writeIdentityError(w http.ResponseWriter, err error) {
code := http.StatusInternalServerError
switch {
case errors.Is(err, identity.ErrNotFound):
code = http.StatusNotFound
case errors.Is(err, identity.ErrConflict), errors.Is(err, org.ErrLastOwner):
code = http.StatusConflict
case errors.Is(err, identity.ErrInvalid), errors.Is(err, identity.ErrIllegalTransition), errors.Is(err, identity.ErrSystemImmutable):
code = http.StatusBadRequest
}
http.Error(w, strings.TrimSpace(err.Error()), code)
}