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. // identitiesAPI owns the identity routes and the signed-in person's API // tokens. Either store may be nil; its routes then answer Unavailable. type identitiesAPI struct { identities identity.Repository tokens identity.PersonalTokens } func newIdentitiesAPI(s *Server) *identitiesAPI { return &identitiesAPI{identities: s.Identities, tokens: s.PersonalTokens} } func (a *identitiesAPI) register(mux *http.ServeMux) { mux.HandleFunc("GET /api/identities", instanceOnly(a.handleIdentitiesList)) mux.HandleFunc("POST /api/identities", instanceOnly(a.handleIdentityCreate)) mux.HandleFunc("POST /api/identities/{id}/{command}", instanceOnly(a.handleIdentityCommand)) mux.HandleFunc("POST /api/identities/{id}/tokens", instanceOnly(a.handleIdentityTokenCreate)) mux.HandleFunc("GET /api/tokens", a.handlePersonalTokensList) mux.HandleFunc("POST /api/tokens", a.handlePersonalTokenCreate) mux.HandleFunc("DELETE /api/tokens/{id}", a.handlePersonalTokenRevoke) } 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 (a *identitiesAPI) handleIdentitiesList(w http.ResponseWriter, r *http.Request) { if a.identities == nil { http.Error(w, "identity store unavailable", http.StatusServiceUnavailable) return } values, err := a.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 (a *identitiesAPI) 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 = a.identities.Create(r.Context(), value, audit) } if err != nil { writeIdentityError(w, err) return } w.WriteHeader(http.StatusCreated) writeJSON(w, value) } func (a *identitiesAPI) 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 := a.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 (a *identitiesAPI) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) { id := identity.IdentityID(r.PathValue("id")) if a.identities == nil { http.Error(w, "identity store unavailable", http.StatusServiceUnavailable) return } value, err := a.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 := a.tokens.(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) }