anchorage v1.0 initial tree

Greenfield Go multi-tenant IPFS Pinning Service wire-compatible with the
IPFS Pinning Services API spec. Paired 1:1 with Kubo over localhost RPC,
clustered via embedded NATS JetStream, Postgres source-of-truth with
RLS-enforced tenancy, Fiber + huma v2 for the HTTP surface, Authentik
OIDC for session login with kid-rotated HS256 JWT API tokens.

Feature-complete against the 22-milestone build plan, including the
ship-it v1.0 gap items:

  * admin CLIs: drain/uncordon, maintenance, mint-token, rotate-key,
    prune-denylist, rebalance --dry-run, cache-stats, cluster-presences
  * TTL leader election via NATS KV, fence tokens, JetStream dedup
  * rebalancer (plan/apply split), reconciler, requeue sweeper
  * ristretto caches with NATS-backed cross-node invalidation
    (placements live-nodes + token denylist)
  * maintenance watchdog for stuck cluster-pause flag
  * Prometheus /metrics with CIDR ACL, HTTP/pin/scheduler/cache gauges
  * rate limiting: session (10/min) + anonymous global (120/min)
  * integration tests: rebalance, refcount multi-org, RLS belt
  * goreleaser (tar + deb/rpm/apk + Alpine Docker) targeting Gitea

Stack: Cobra/Viper, Fiber v2 + huma v2, embedded NATS JetStream,
pgx/sqlc/golang-migrate, ristretto, TypeID, prometheus/client_golang,
testcontainers-go.
This commit is contained in:
57_Wolve committed 2026-04-16 18:13:36 -05:00
commit 12bf35caf8
112 files changed
+16884

No files matched your search

+500
View File
@@ -0,0 +1,500 @@
package openapi
import (
"context"
"errors"
"time"
"github.com/danielgtaylor/huma/v2"
"anchorage/internal/pkg/auth"
"anchorage/internal/pkg/cache"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/maintenance"
"anchorage/internal/pkg/node"
"anchorage/internal/pkg/scheduler"
"anchorage/internal/pkg/store"
)
type auditBody struct {
ID int64 `json:"id"`
Action string `json:"action"`
Target string `json:"target"`
Result string `json:"result"`
Detail map[string]any `json:"detail,omitempty"`
ActorUserID string `json:"actor_user_id,omitempty"`
OrgID string `json:"org_id,omitempty"`
Created time.Time `json:"created"`
}
func ifUserID(p *ids.UserID) string {
if p == nil {
return ""
}
return p.String()
}
func ifOrgID(p *ids.OrgID) string {
if p == nil {
return ""
}
return p.String()
}
// AdminDeps holds the collaborators the admin endpoints need.
type AdminDeps struct {
Store store.Store
Maint *maintenance.Manager
Rebalancer *scheduler.Rebalancer
// Presences is the source of real-time NATS heartbeat data
// (distinct from the DB view via Store.Nodes().ListAll()). Used by
// /v1/admin/cluster/presences to let operators compare what each
// node is broadcasting right now against the DB registry.
Presences PresenceSource
}
// PresenceSource is implemented by *node.Runner. Narrow interface so
// tests can stub; the real implementation returns a snapshot of the
// in-memory heartbeat map keyed by NodeID.
type PresenceSource interface {
LivePresences() []node.Presence
}
// NodePresence is the admin-API projection of node.Presence. Kept in
// openapi so the HTTP response shape stays stable even if the internal
// node.Presence struct evolves.
type NodePresence struct {
NodeID string `json:"node_id"`
Multiaddrs []string `json:"multiaddrs"`
Status string `json:"status"`
SentAt time.Time `json:"sent_at"`
// AgeSeconds is derived server-side so clients don't have to
// reason about clock skew — operators eyeballing the response can
// see "last heard 12s ago" directly.
AgeSeconds float64 `json:"age_seconds"`
}
// RegisterAdmin wires drain/uncordon/maintenance endpoints at
// /v1/admin/*. Access is restricted to sysadmins; orgadmins cannot
// drain nodes (that would be a cluster-level action).
func RegisterAdmin(api huma.API, deps AdminDeps) {
huma.Register(api, huma.Operation{
OperationID: "adminDrain",
Method: "POST",
Path: "/admin/nodes/{node_id}/drain",
Summary: "Drain a cluster node",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
NodeID string `path:"node_id"`
}) (*struct {
Body struct {
OK bool `json:"ok"`
}
}, error) {
if err := requireSysadmin(ctx); err != nil {
return nil, err
}
nid, err := ids.ParseNode(in.NodeID)
if err != nil {
return nil, huma.Error400BadRequest("bad node id")
}
if err := deps.Store.Nodes().Drain(ctx, nid); err != nil {
return nil, huma.Error500InternalServerError("drain", err)
}
out := &struct {
Body struct {
OK bool `json:"ok"`
}
}{}
out.Body.OK = true
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "adminUncordon",
Method: "POST",
Path: "/admin/nodes/{node_id}/uncordon",
Summary: "Return a drained node to service",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
NodeID string `path:"node_id"`
}) (*struct {
Body struct {
OK bool `json:"ok"`
}
}, error) {
if err := requireSysadmin(ctx); err != nil {
return nil, err
}
nid, err := ids.ParseNode(in.NodeID)
if err != nil {
return nil, huma.Error400BadRequest("bad node id")
}
if err := deps.Store.Nodes().Uncordon(ctx, nid); err != nil {
return nil, huma.Error500InternalServerError("uncordon", err)
}
out := &struct {
Body struct {
OK bool `json:"ok"`
}
}{}
out.Body.OK = true
return out, nil
})
type maintenanceStatusBody struct {
On bool `json:"on"`
Reason string `json:"reason,omitempty"`
SetBy string `json:"set_by,omitempty"`
SetAt time.Time `json:"set_at,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
}
huma.Register(api, huma.Operation{
OperationID: "adminMaintenanceOn",
Method: "POST",
Path: "/admin/maintenance/on",
Summary: "Enable cluster-wide maintenance",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
Body struct {
Reason string `json:"reason,omitempty"`
TTL time.Duration `json:"ttl,omitempty"`
}
}) (*struct {
Body maintenanceStatusBody
}, error) {
cc, err := requireSysadminCC(ctx)
if err != nil {
return nil, err
}
f := maintenance.Flag{
Reason: in.Body.Reason,
SetBy: cc.User.String(),
SetAt: time.Now().UTC(),
}
if in.Body.TTL > 0 {
f.ExpiresAt = f.SetAt.Add(in.Body.TTL)
}
if err := deps.Maint.Set(ctx, f); err != nil {
return nil, huma.Error500InternalServerError("maintenance on", err)
}
out := &struct{ Body maintenanceStatusBody }{}
out.Body = maintenanceStatusBody{
On: true, Reason: f.Reason, SetBy: f.SetBy, SetAt: f.SetAt, ExpiresAt: f.ExpiresAt,
}
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "adminMaintenanceOff",
Method: "POST",
Path: "/admin/maintenance/off",
Summary: "Disable cluster-wide maintenance",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body maintenanceStatusBody
}, error) {
if err := requireSysadmin(ctx); err != nil {
return nil, err
}
if err := deps.Maint.Clear(ctx); err != nil {
return nil, huma.Error500InternalServerError("maintenance off", err)
}
out := &struct{ Body maintenanceStatusBody }{}
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "adminGrantSysadmin",
Method: "POST",
Path: "/admin/users/{email}/grant-sysadmin",
Summary: "Promote an existing user to sysadmin",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
Email string `path:"email"`
}) (*struct {
Body struct {
OK bool `json:"ok"`
}
}, error) {
cc, err := requireSysadminCC(ctx)
if err != nil {
return nil, err
}
user, err := deps.Store.Users().GetByEmail(ctx, in.Email)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("user (must have logged in at least once via Authentik)")
}
return nil, huma.Error500InternalServerError("lookup", err)
}
if err := deps.Store.Users().PromoteSysadmin(ctx, user.ID); err != nil {
return nil, huma.Error500InternalServerError("promote", err)
}
_ = deps.Store.Audit().Insert(ctx, &store.AuditEntry{
ActorUserID: &cc.User,
Action: "admin.grant-sysadmin",
Target: user.ID.String(),
Result: "ok",
Detail: map[string]any{"email": in.Email},
})
out := &struct {
Body struct {
OK bool `json:"ok"`
}
}{}
out.Body.OK = true
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "adminListAudit",
Method: "GET",
Path: "/admin/audit",
Summary: "Paged audit-log listing",
Description: "sysadmin with no org_id sees every org; org members can only read their own org's audit",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
OrgID string `query:"org_id"`
Limit int `query:"limit" default:"50" minimum:"1" maximum:"1000"`
Offset int `query:"offset" default:"0" minimum:"0"`
}) (*struct {
Body struct {
Results []auditBody `json:"results"`
}
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
var scopeOrg ids.OrgID
if in.OrgID != "" {
scopeOrg, err = ids.ParseOrg(in.OrgID)
if err != nil {
return nil, huma.Error400BadRequest("bad org id")
}
if cc.Role != "sysadmin" && scopeOrg != cc.Org {
return nil, huma.Error403Forbidden("cannot view other org's audit")
}
} else if cc.Role != "sysadmin" {
scopeOrg = cc.Org
}
rows, err := deps.Store.Audit().List(ctx, scopeOrg, in.Limit, in.Offset)
if err != nil {
return nil, huma.Error500InternalServerError("list", err)
}
out := &struct {
Body struct {
Results []auditBody `json:"results"`
}
}{}
for _, e := range rows {
out.Body.Results = append(out.Body.Results, auditBody{
ID: e.ID,
Action: e.Action,
Target: e.Target,
Result: e.Result,
Detail: e.Detail,
ActorUserID: ifUserID(e.ActorUserID),
OrgID: ifOrgID(e.OrgID),
Created: e.Created,
})
}
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "adminMaintenanceStatus",
Method: "GET",
Path: "/admin/maintenance",
Summary: "Report current cluster-maintenance state",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body maintenanceStatusBody
}, error) {
if err := requireSysadmin(ctx); err != nil {
return nil, err
}
f, on, err := deps.Maint.IsOn(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("maintenance status", err)
}
out := &struct{ Body maintenanceStatusBody }{}
if on && f != nil {
out.Body = maintenanceStatusBody{
On: true, Reason: f.Reason, SetBy: f.SetBy,
SetAt: f.SetAt, ExpiresAt: f.ExpiresAt,
}
}
return out, nil
})
// ---- prune-denylist ----------------------------------------------------
huma.Register(api, huma.Operation{
OperationID: "adminPruneTokenDenylist",
Method: "POST",
Path: "/admin/tokens/prune-denylist",
Summary: "Delete denylist rows whose expires_at has passed",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body struct {
OK bool `json:"ok"`
}
}, error) {
cc, err := requireSysadminCC(ctx)
if err != nil {
return nil, err
}
if err := deps.Store.Tokens().PruneDenylist(ctx); err != nil {
return nil, huma.Error500InternalServerError("prune", err)
}
_ = deps.Store.Audit().Insert(ctx, &store.AuditEntry{
ActorUserID: &cc.User,
Action: "admin.prune-denylist",
Target: "token_denylist",
Result: "ok",
})
out := &struct {
Body struct {
OK bool `json:"ok"`
}
}{}
out.Body.OK = true
return out, nil
})
// ---- rebalance ---------------------------------------------------------
type rebalanceReq struct {
Apply bool `json:"apply,omitempty" doc:"when true, execute the moves; otherwise return a dry-run preview"`
}
type rebalanceResp struct {
Body struct {
Applied bool `json:"applied"`
Moves []scheduler.PlannedMove `json:"moves"`
}
}
huma.Register(api, huma.Operation{
OperationID: "adminRebalance",
Method: "POST",
Path: "/admin/rebalance",
Summary: "One-shot rebalance preview or apply (leader-loop keeps running regardless)",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
Body rebalanceReq
}) (*rebalanceResp, error) {
cc, err := requireSysadminCC(ctx)
if err != nil {
return nil, err
}
if deps.Rebalancer == nil {
return nil, huma.Error503ServiceUnavailable("rebalancer not available")
}
var moves []scheduler.PlannedMove
if in.Body.Apply {
moves, err = deps.Rebalancer.RunOnce(ctx)
} else {
moves, err = deps.Rebalancer.DryRun(ctx)
}
if err != nil {
return nil, huma.Error500InternalServerError("rebalance", err)
}
if in.Body.Apply {
_ = deps.Store.Audit().Insert(ctx, &store.AuditEntry{
ActorUserID: &cc.User,
Action: "admin.rebalance",
Target: "cluster",
Result: "ok",
Detail: map[string]any{"moves": len(moves)},
})
}
out := &rebalanceResp{}
out.Body.Applied = in.Body.Apply
out.Body.Moves = moves
return out, nil
})
// ---- cache-stats -------------------------------------------------------
huma.Register(api, huma.Operation{
OperationID: "adminCacheStats",
Method: "GET",
Path: "/admin/cache-stats",
Summary: "In-memory cache hit/miss/eviction counters per named cache",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body struct {
Caches []cache.Stats `json:"caches"`
}
}, error) {
if err := requireSysadmin(ctx); err != nil {
return nil, err
}
out := &struct {
Body struct {
Caches []cache.Stats `json:"caches"`
}
}{}
out.Body.Caches = cache.AllStats()
return out, nil
})
// ---- cluster presences -------------------------------------------------
//
// Real-time heartbeat view, distinct from the DB registry. The DB
// updates status via the stale-sweeper (leader-gated, fires every
// downAfter interval); this endpoint shows what each peer is
// broadcasting RIGHT NOW over NATS. Operators comparing the two
// diagnose "the DB says X is up but nobody's heard from it" gaps.
huma.Register(api, huma.Operation{
OperationID: "adminClusterPresences",
Method: "GET",
Path: "/admin/cluster/presences",
Summary: "Real-time NATS heartbeat view of every peer this node has heard from",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body struct {
Presences []NodePresence `json:"presences"`
}
}, error) {
if err := requireSysadmin(ctx); err != nil {
return nil, err
}
if deps.Presences == nil {
return nil, huma.Error503ServiceUnavailable("presence source not wired")
}
now := time.Now()
raw := deps.Presences.LivePresences()
out := &struct {
Body struct {
Presences []NodePresence `json:"presences"`
}
}{}
out.Body.Presences = make([]NodePresence, 0, len(raw))
for _, p := range raw {
out.Body.Presences = append(out.Body.Presences, NodePresence{
NodeID: p.NodeID,
Multiaddrs: p.Multiaddrs,
Status: p.Status,
SentAt: p.SentAt,
AgeSeconds: now.Sub(p.SentAt).Seconds(),
})
}
return out, nil
})
}
// requireSysadmin rejects any request without a sysadmin client context.
func requireSysadmin(ctx context.Context) error {
_, err := requireSysadminCC(ctx)
return err
}
func requireSysadminCC(ctx context.Context) (*auth.ClientContext, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
if cc.Role != "sysadmin" {
return nil, huma.Error403Forbidden("sysadmin required")
}
return cc, nil
}
+104
View File
@@ -0,0 +1,104 @@
// Package openapi registers anchorage's HTTP surface on a huma API instance.
//
// Handlers are grouped by domain (pins, tokens, orgs, audit) and registered
// via huma's code-first operations. The generated OpenAPI 3.1 spec lives at
// GET /openapi.json; Scalar UI is served at GET /docs.
package openapi
import (
"context"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humafiber"
"github.com/gofiber/fiber/v2"
)
// New creates a huma.API configured to match the anchorage spec.
//
// The returned huma.API is not yet populated with routes — callers
// (see internal/app/anchorage) wire in domain handlers via Register*
// functions exported by their respective packages.
func New(app *fiber.App) huma.API {
cfg := huma.DefaultConfig("anchorage", "0.1.0")
cfg.OpenAPI.Info.Description = "Highly-available IPFS Pinning Service API. Wire-compatible with the IPFS Pinning Services API spec, plus org/admin extensions."
cfg.Servers = []*huma.Server{
{URL: "/v1", Description: "Default v1 endpoint"},
}
cfg.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
"accessToken": {
Type: "http",
Scheme: "bearer",
BearerFormat: "JWT",
},
}
return humafiber.New(app, cfg)
}
// HealthResponse is the body of /health (liveness probe).
type HealthResponse struct {
Body struct {
Status string `json:"status" example:"ok"`
}
}
// ReadyResponse is the body of /ready (readiness probe). Includes the
// Reconciler drift count so operators can alert on out-of-sync nodes
// without scraping /metrics.
type ReadyResponse struct {
Body struct {
Status string `json:"status" example:"ok"`
// Drift is the current reconciler drift count (pins the store
// believes this node holds vs. pins actually in Kubo's pinset).
// 0 on a healthy node. Non-zero is not inherently "not ready" —
// a drifted node still serves requests fine — but operators
// alert on sustained non-zero values.
Drift int64 `json:"drift"`
}
}
// ReadyState is the signal the readyz callback returns to
// RegisterHealth. Ready controls the HTTP status (true → 200, false →
// 503). Drift is surfaced in the body regardless.
type ReadyState struct {
Ready bool
Reason string
Drift int64
}
// RegisterHealth registers /health and /ready.
//
// /health is a liveness probe: the process is alive and the API is
// reachable. /ready is a readiness probe: returns 503 while the node
// is drained or while mandatory dependencies (Postgres, NATS) are
// unavailable. The readyz callback receives the per-request context so
// dependency probes are scoped to the request (not the app's root
// ctx, which would stall health-checks mid-shutdown).
func RegisterHealth(api huma.API, readyz func(ctx context.Context) ReadyState) {
huma.Register(api, huma.Operation{
OperationID: "getHealth",
Method: "GET",
Path: "/health",
Summary: "Liveness probe",
}, func(_ context.Context, _ *struct{}) (*HealthResponse, error) {
out := &HealthResponse{}
out.Body.Status = "ok"
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "getReady",
Method: "GET",
Path: "/ready",
Summary: "Readiness probe (also reports reconciler drift)",
}, func(ctx context.Context, _ *struct{}) (*ReadyResponse, error) {
state := readyz(ctx)
out := &ReadyResponse{}
out.Body.Drift = state.Drift
if state.Ready {
out.Body.Status = "ok"
return out, nil
}
out.Body.Status = "not-ready: " + state.Reason
return out, huma.Error503ServiceUnavailable("not ready: " + state.Reason)
})
}
+286
View File
@@ -0,0 +1,286 @@
package openapi
import (
"context"
"errors"
"strings"
"time"
"github.com/danielgtaylor/huma/v2"
"anchorage/internal/pkg/auth"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/store"
)
// RegisterOrgs wires org + membership endpoints on api.
//
// Authz model:
// - `POST /v1/orgs` — any authenticated user. The creator is auto-added
// as the first orgadmin.
// - `GET /v1/orgs` — lists the caller's memberships (not every org
// that exists — that would be a cross-tenant leak).
// - `GET /v1/orgs/{id}` / `PATCH /v1/orgs/{id}` — orgadmin of that
// org, or sysadmin.
// - `POST/DELETE /v1/orgs/{id}/members` — orgadmin of that org, or
// sysadmin.
func RegisterOrgs(api huma.API, s store.Store) {
huma.Register(api, huma.Operation{
OperationID: "createOrg",
Method: "POST",
Path: "/orgs",
Summary: "Create a new organisation",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
Body struct {
Slug string `json:"slug" minLength:"2" maxLength:"64" pattern:"^[a-z0-9][a-z0-9-]*$"`
Name string `json:"name" minLength:"1" maxLength:"256"`
}
}) (*struct{ Body orgBody }, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
orgID, err := ids.NewOrg()
if err != nil {
return nil, huma.Error500InternalServerError("id", err)
}
org, err := s.Orgs().Create(ctx, orgID, strings.ToLower(in.Body.Slug), in.Body.Name)
if err != nil {
if errors.Is(err, store.ErrConflict) {
return nil, huma.Error409Conflict("slug already in use")
}
return nil, huma.Error500InternalServerError("create org", err)
}
if err := s.Memberships().Add(ctx, org.ID, cc.User, store.RoleOrgAdmin); err != nil {
return nil, huma.Error500InternalServerError("add membership", err)
}
_ = s.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &org.ID, ActorUserID: &cc.User,
Action: "org.create", Target: org.ID.String(), Result: "ok",
Detail: map[string]any{"slug": org.Slug, "name": org.Name},
})
return &struct{ Body orgBody }{Body: toOrgBody(org)}, nil
})
huma.Register(api, huma.Operation{
OperationID: "listMyOrgs",
Method: "GET",
Path: "/orgs",
Summary: "List organisations the caller is a member of",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body struct {
Results []orgBody `json:"results"`
}
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
memberships, err := s.Memberships().ListForUser(ctx, cc.User)
if err != nil {
return nil, huma.Error500InternalServerError("list", err)
}
out := &struct {
Body struct {
Results []orgBody `json:"results"`
}
}{}
for _, m := range memberships {
out.Body.Results = append(out.Body.Results, orgBody{
ID: m.OrgID.String(), Slug: m.OrgSlug, Name: m.OrgName, Role: m.Role,
})
}
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "getOrg",
Method: "GET",
Path: "/orgs/{org_id}",
Summary: "Fetch an organisation by ID",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
OrgID string `path:"org_id"`
}) (*struct{ Body orgBody }, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
orgID, err := ids.ParseOrg(in.OrgID)
if err != nil {
return nil, huma.Error400BadRequest("bad org id")
}
if err := requireOrgMember(ctx, s, cc, orgID); err != nil {
return nil, err
}
org, err := s.Orgs().GetByID(ctx, orgID)
if err != nil {
return nil, huma.Error404NotFound("org")
}
return &struct{ Body orgBody }{Body: toOrgBody(org)}, nil
})
huma.Register(api, huma.Operation{
OperationID: "patchOrg",
Method: "PATCH",
Path: "/orgs/{org_id}",
Summary: "Rename an organisation",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
OrgID string `path:"org_id"`
Body struct {
Name string `json:"name" minLength:"1" maxLength:"256"`
}
}) (*struct{ Body orgBody }, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
orgID, err := ids.ParseOrg(in.OrgID)
if err != nil {
return nil, huma.Error400BadRequest("bad org id")
}
if err := requireOrgAdmin(ctx, s, cc, orgID); err != nil {
return nil, err
}
org, err := s.Orgs().UpdateName(ctx, orgID, in.Body.Name)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("org")
}
return nil, huma.Error500InternalServerError("update", err)
}
_ = s.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &orgID, ActorUserID: &cc.User,
Action: "org.rename", Target: orgID.String(), Result: "ok",
Detail: map[string]any{"name": in.Body.Name},
})
return &struct{ Body orgBody }{Body: toOrgBody(org)}, nil
})
huma.Register(api, huma.Operation{
OperationID: "addMember",
Method: "POST",
Path: "/orgs/{org_id}/members",
Summary: "Add a user to an organisation",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
OrgID string `path:"org_id"`
Body struct {
UserID string `json:"user_id"`
Role string `json:"role" enum:"orgadmin,member" default:"member"`
}
}) (*struct{}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
orgID, err := ids.ParseOrg(in.OrgID)
if err != nil {
return nil, huma.Error400BadRequest("bad org id")
}
if err := requireOrgAdmin(ctx, s, cc, orgID); err != nil {
return nil, err
}
userID, err := ids.ParseUser(in.Body.UserID)
if err != nil {
return nil, huma.Error400BadRequest("bad user id")
}
if err := s.Memberships().Add(ctx, orgID, userID, in.Body.Role); err != nil {
return nil, huma.Error500InternalServerError("add", err)
}
_ = s.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &orgID, ActorUserID: &cc.User,
Action: "org.member.add", Target: userID.String(), Result: "ok",
Detail: map[string]any{"role": in.Body.Role},
})
return &struct{}{}, nil
})
huma.Register(api, huma.Operation{
OperationID: "removeMember",
Method: "DELETE",
Path: "/orgs/{org_id}/members/{user_id}",
Summary: "Remove a user from an organisation",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
OrgID string `path:"org_id"`
UserID string `path:"user_id"`
}) (*struct{}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
orgID, err := ids.ParseOrg(in.OrgID)
if err != nil {
return nil, huma.Error400BadRequest("bad org id")
}
if err := requireOrgAdmin(ctx, s, cc, orgID); err != nil {
return nil, err
}
userID, err := ids.ParseUser(in.UserID)
if err != nil {
return nil, huma.Error400BadRequest("bad user id")
}
if err := s.Memberships().Remove(ctx, orgID, userID); err != nil {
return nil, huma.Error500InternalServerError("remove", err)
}
_ = s.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &orgID, ActorUserID: &cc.User,
Action: "org.member.remove", Target: userID.String(), Result: "ok",
})
return &struct{}{}, nil
})
}
type orgBody struct {
ID string `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
Role string `json:"role,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
}
func toOrgBody(o *store.Org) orgBody {
return orgBody{
ID: o.ID.String(), Slug: o.Slug, Name: o.Name, CreatedAt: o.CreatedAt,
}
}
// requireOrgMember fails with 403 unless cc is a member of orgID (or
// cc is a sysadmin — cross-org read is one of the sysadmin privileges).
func requireOrgMember(ctx context.Context, s store.Store, cc *auth.ClientContext, orgID ids.OrgID) error {
if cc.Role == "sysadmin" {
return nil
}
memberships, err := s.Memberships().ListForUser(ctx, cc.User)
if err != nil {
return huma.Error500InternalServerError("lookup membership", err)
}
for _, m := range memberships {
if m.OrgID == orgID {
return nil
}
}
return huma.Error403Forbidden("not a member of this org")
}
// requireOrgAdmin tightens requireOrgMember: must be role=orgadmin in
// that specific org (sysadmins are always allowed).
func requireOrgAdmin(ctx context.Context, s store.Store, cc *auth.ClientContext, orgID ids.OrgID) error {
if cc.Role == "sysadmin" {
return nil
}
memberships, err := s.Memberships().ListForUser(ctx, cc.User)
if err != nil {
return huma.Error500InternalServerError("lookup membership", err)
}
for _, m := range memberships {
if m.OrgID == orgID && m.Role == store.RoleOrgAdmin {
return nil
}
}
return huma.Error403Forbidden("orgadmin required")
}
+291
View File
@@ -0,0 +1,291 @@
package openapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/danielgtaylor/huma/v2"
"anchorage/internal/pkg/auth"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/pin"
"anchorage/internal/pkg/store"
)
// pinService is the subset of pin.Service the handlers need, defined as
// an interface so tests can stub it.
type pinService interface {
Create(ctx context.Context, in pin.CreateInput) (*store.Pin, []*store.Placement, error)
Delete(ctx context.Context, orgID ids.OrgID, rid ids.PinID) error
Replace(ctx context.Context, orgID ids.OrgID, rid ids.PinID, in pin.CreateInput) (*store.Pin, []*store.Placement, error)
}
// parsePinFilter maps the spec's HTTP query params into a store.PinFilter.
// Returns a *time.Time (not string) for Before/After after RFC3339 parse;
// returns a map[string]any parsed from the meta JSON string.
func parsePinFilter(in *struct {
CID []string `query:"cid" maxItems:"10"`
Name string `query:"name"`
Match string `query:"match" enum:"exact,iexact,partial,ipartial" default:"exact"`
Status []string `query:"status"`
Before string `query:"before" doc:"RFC3339; return only pins created before this timestamp"`
After string `query:"after" doc:"RFC3339; return only pins created at or after this timestamp"`
Meta string `query:"meta" doc:"JSON object; pin.meta must contain every key/value"`
Limit int `query:"limit" default:"10" minimum:"1" maximum:"1000"`
Offset int `query:"offset" default:"0" minimum:"0"`
}) (store.PinFilter, error) {
f := store.PinFilter{
CIDs: in.CID,
Name: in.Name,
Match: in.Match,
Status: in.Status,
Limit: in.Limit,
Offset: in.Offset,
}
if in.Before != "" {
t, err := time.Parse(time.RFC3339, in.Before)
if err != nil {
return f, fmt.Errorf("before: %w", err)
}
f.Before = &t
}
if in.After != "" {
t, err := time.Parse(time.RFC3339, in.After)
if err != nil {
return f, fmt.Errorf("after: %w", err)
}
f.After = &t
}
if in.Meta != "" {
if err := json.Unmarshal([]byte(in.Meta), &f.Meta); err != nil {
return f, fmt.Errorf("meta: %w", err)
}
}
return f, nil
}
// pinStatusBody is the spec-compliant PinStatus response.
type pinStatusBody struct {
RequestID string `json:"requestid"`
Status string `json:"status" enum:"queued,pinning,pinned,failed"`
Created time.Time `json:"created"`
Pin pinBody `json:"pin"`
Delegates []string `json:"delegates"`
Info map[string]any `json:"info,omitempty"`
}
type pinBody struct {
CID string `json:"cid"`
Name string `json:"name,omitempty"`
Origins []string `json:"origins,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
}
// RegisterPins wires the 5 spec-compliant pin endpoints onto api.
func RegisterPins(api huma.API, pins pinService, s store.Store) {
huma.Register(api, huma.Operation{
OperationID: "createPin",
Method: "POST",
Path: "/pins",
Summary: "Create a pin request",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
Body pinBody
}) (*struct {
Body pinStatusBody
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
created, placements, err := pins.Create(ctx, pin.CreateInput{
OrgID: cc.Org,
CID: in.Body.CID,
Name: optString(in.Body.Name),
Meta: in.Body.Meta,
Origins: in.Body.Origins,
})
if err != nil {
if !errors.Is(err, store.ErrConflict) {
return nil, huma.Error500InternalServerError("create pin", err)
}
// Idempotent re-add: load the existing pin's real placements
// so the caller gets accurate delegates, not the /unknown
// sentinel from an empty list.
if created != nil {
if existing, err := s.Pins().ListPlacements(ctx, created.RequestID); err == nil {
placements = existing
}
}
}
return &struct{ Body pinStatusBody }{Body: toBody(created, placements)}, nil
})
huma.Register(api, huma.Operation{
OperationID: "getPin",
Method: "GET",
Path: "/pins/{requestid}",
Summary: "Get a pin by request id",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
RequestID string `path:"requestid"`
}) (*struct{ Body pinStatusBody }, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
rid, err := ids.ParsePin(in.RequestID)
if err != nil {
return nil, huma.Error400BadRequest("bad request id")
}
p, err := s.Pins().Get(ctx, cc.Org, rid)
if err != nil {
return nil, huma.Error404NotFound("pin")
}
pls, _ := s.Pins().ListPlacements(ctx, rid)
return &struct{ Body pinStatusBody }{Body: toBody(p, pls)}, nil
})
huma.Register(api, huma.Operation{
OperationID: "listPins",
Method: "GET",
Path: "/pins",
Summary: "List pins with the full spec-compliant filter set",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
CID []string `query:"cid" maxItems:"10"`
Name string `query:"name"`
Match string `query:"match" enum:"exact,iexact,partial,ipartial" default:"exact"`
Status []string `query:"status"`
Before string `query:"before" doc:"RFC3339; return only pins created before this timestamp"`
After string `query:"after" doc:"RFC3339; return only pins created at or after this timestamp"`
Meta string `query:"meta" doc:"JSON object; pin.meta must contain every key/value"`
Limit int `query:"limit" default:"10" minimum:"1" maximum:"1000"`
Offset int `query:"offset" default:"0" minimum:"0"`
}) (*struct {
Body struct {
Results []pinStatusBody `json:"results"`
}
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
filter, err := parsePinFilter(in)
if err != nil {
return nil, huma.Error400BadRequest("bad filter", err)
}
pins, err := s.Pins().Filter(ctx, cc.Org, filter)
if err != nil {
return nil, huma.Error500InternalServerError("list pins", err)
}
out := &struct {
Body struct {
Results []pinStatusBody `json:"results"`
}
}{}
for _, p := range pins {
pls, _ := s.Pins().ListPlacements(ctx, p.RequestID)
out.Body.Results = append(out.Body.Results, toBody(p, pls))
}
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "replacePin",
Method: "POST",
Path: "/pins/{requestid}",
Summary: "Replace a pin's CID (spec-compliant pin update)",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
RequestID string `path:"requestid"`
Body pinBody
}) (*struct{ Body pinStatusBody }, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
rid, err := ids.ParsePin(in.RequestID)
if err != nil {
return nil, huma.Error400BadRequest("bad request id")
}
replaced, placements, err := pins.Replace(ctx, cc.Org, rid, pin.CreateInput{
OrgID: cc.Org,
CID: in.Body.CID,
Name: optString(in.Body.Name),
Meta: in.Body.Meta,
Origins: in.Body.Origins,
})
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("pin")
}
return nil, huma.Error500InternalServerError("replace pin", err)
}
return &struct{ Body pinStatusBody }{Body: toBody(replaced, placements)}, nil
})
huma.Register(api, huma.Operation{
OperationID: "deletePin",
Method: "DELETE",
Path: "/pins/{requestid}",
Summary: "Remove a pin",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
RequestID string `path:"requestid"`
}) (*struct{}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
rid, err := ids.ParsePin(in.RequestID)
if err != nil {
return nil, huma.Error400BadRequest("bad request id")
}
if err := pins.Delete(ctx, cc.Org, rid); err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("pin")
}
return nil, huma.Error500InternalServerError("delete pin", err)
}
return &struct{}{}, nil
})
}
func toBody(p *store.Pin, placements []*store.Placement) pinStatusBody {
if p == nil {
return pinStatusBody{}
}
delegates := make([]string, 0, len(placements))
for _, pl := range placements {
delegates = append(delegates, pl.Multiaddrs...)
}
if len(delegates) == 0 {
delegates = []string{"/unknown"}
}
b := pinStatusBody{
RequestID: p.RequestID.String(),
Status: p.Status,
Created: p.Created,
Pin: pinBody{
CID: p.CID,
Origins: p.Origins,
Meta: p.Meta,
},
Delegates: delegates,
}
if p.Name != nil {
b.Pin.Name = *p.Name
}
return b
}
func optString(s string) *string {
if s == "" {
return nil
}
return &s
}
+306
View File
@@ -0,0 +1,306 @@
package openapi
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/danielgtaylor/huma/v2"
"anchorage/internal/pkg/auth"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/store"
"anchorage/internal/pkg/token"
)
// SessionDeps wires the session endpoints to the store, the token
// signer, and the Authentik verifier.
type SessionDeps struct {
Store store.Store
Signer *token.Signer
// OIDC may be nil in environments without Authentik (dev, tests).
// The session POST will 503 in that case with a clear message.
OIDC *auth.OIDCVerifier
// Sysadmins is the list of emails that get promoted to sysadmin on
// their first login — mirrors config.BootstrapConfig.Sysadmins.
Sysadmins []string
// SessionTTL controls how long the issued session JWT lives.
SessionTTL time.Duration
// CookieSecure controls whether the Set-Cookie uses `Secure`. True
// in production; false is only appropriate for plain-HTTP local dev.
CookieSecure bool
}
// RegisterSession wires POST /auth/session, DELETE /auth/session, and
// GET /me onto api.
func RegisterSession(api huma.API, deps SessionDeps) {
// --- POST /auth/session ------------------------------------------------
huma.Register(api, huma.Operation{
OperationID: "createSession",
Method: "POST",
Path: "/auth/session",
Summary: "Exchange an Authentik ID token for an anchorage session",
Description: `The web UI completes Authorization Code + PKCE against Authentik,
then POSTs the resulting ID token here. anchorage validates the
signature + issuer + audience against the JWKS, upserts the user,
promotes bootstrap sysadmins on first login, and returns a session
JWT as an HttpOnly cookie.`,
}, func(ctx context.Context, in *struct {
Body createSessionRequest
}) (*createSessionResponse, error) {
if deps.OIDC == nil {
return nil, huma.Error503ServiceUnavailable(
"auth: OIDC is not configured — set auth.authentik.issuer/clientID/audience in anchorage.yaml")
}
claims, err := deps.OIDC.Verify(ctx, in.Body.IDToken)
if err != nil {
return nil, huma.Error401Unauthorized("auth: " + err.Error())
}
user, err := upsertUser(ctx, deps, claims)
if err != nil {
return nil, huma.Error500InternalServerError("auth: upsert user", err)
}
sessionJWT, sessionClaims, err := mintSession(ctx, deps, user)
if err != nil {
return nil, huma.Error500InternalServerError("auth: mint session", err)
}
out := &createSessionResponse{}
out.SetCookie = sessionCookieHeader(sessionJWT, deps)
out.Body.User = userBody(user)
out.Body.ExpiresAt = sessionClaims.ExpiresAt.Time
return out, nil
})
// --- DELETE /auth/session ----------------------------------------------
huma.Register(api, huma.Operation{
OperationID: "deleteSession",
Method: "DELETE",
Path: "/auth/session",
Summary: "Log out — revoke the session cookie",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*deleteSessionResponse, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
// Add the jti to the denylist so the cookie-bearer can't keep
// using the raw JWT elsewhere until natural expiry.
if cc.TokenJTI != nil {
expiry := time.Now().Add(deps.SessionTTL)
if err := deps.Store.Tokens().AddDenylist(ctx, *cc.TokenJTI, expiry, "logout"); err != nil {
// Non-fatal: clearing the cookie still improves the user's
// situation even if denylist write fails.
_ = err
}
}
out := &deleteSessionResponse{}
// Empty Value + MaxAge=-1 tells the browser to drop the cookie.
out.SetCookie = clearCookieHeader(deps)
return out, nil
})
// --- GET /me ----------------------------------------------------------
huma.Register(api, huma.Operation{
OperationID: "getMe",
Method: "GET",
Path: "/me",
Summary: "Current authenticated user",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body meBody
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
user, err := deps.Store.Users().GetByID(ctx, cc.User)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("user")
}
return nil, huma.Error500InternalServerError("get user", err)
}
memberships, err := deps.Store.Memberships().ListForUser(ctx, cc.User)
if err != nil {
return nil, huma.Error500InternalServerError("list memberships", err)
}
out := &struct{ Body meBody }{}
out.Body.User = userBody(user)
out.Body.Role = cc.Role
for _, m := range memberships {
out.Body.Memberships = append(out.Body.Memberships, membershipBody{
OrgID: m.OrgID.String(),
OrgSlug: m.OrgSlug,
OrgName: m.OrgName,
Role: m.Role,
})
}
return out, nil
})
}
// ---------------------------------------------------------------------------
// Request / response bodies
// ---------------------------------------------------------------------------
type createSessionRequest struct {
// IDToken is the raw JWT returned by Authentik at the end of the
// Authorization Code + PKCE dance.
IDToken string `json:"id_token" minLength:"32"`
}
type createSessionResponse struct {
// SetCookie is emitted as a Set-Cookie header so the browser picks
// up the session JWT. huma knows `header:"Set-Cookie"` means a
// response header, one entry per cookie.
SetCookie string `header:"Set-Cookie"`
Body struct {
User userBodyT `json:"user"`
ExpiresAt time.Time `json:"expires_at"`
}
}
type deleteSessionResponse struct {
SetCookie string `header:"Set-Cookie"`
}
type meBody struct {
User userBodyT `json:"user"`
Role string `json:"role"`
Memberships []membershipBody `json:"memberships"`
}
type userBodyT struct {
ID string `json:"id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
IsSysadmin bool `json:"is_sysadmin"`
}
type membershipBody struct {
OrgID string `json:"org_id"`
OrgSlug string `json:"org_slug"`
OrgName string `json:"org_name"`
Role string `json:"role"`
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
func upsertUser(ctx context.Context, deps SessionDeps, claims *auth.OIDCClaims) (*store.User, error) {
// Check if this Authentik subject already maps to a user. If yes,
// we don't need a fresh TypeID — upsert keeps the existing one.
existing, err := deps.Store.Users().GetByEmail(ctx, claims.Email)
var userID ids.UserID
switch {
case err == nil:
userID = existing.ID
case errors.Is(err, store.ErrNotFound):
userID, err = ids.NewUser()
if err != nil {
return nil, err
}
default:
return nil, err
}
isSysadmin := bootstrapSysadmin(claims.Email, deps.Sysadmins)
// Preserve existing sysadmin status (don't demote an admin just
// because their email was removed from config).
if existing != nil && existing.IsSysadmin {
isSysadmin = true
}
return deps.Store.Users().UpsertByAuthentikSub(ctx, userID, claims.Sub, claims.Email, claims.DisplayName(), isSysadmin)
}
// bootstrapSysadmin matches the email case-insensitively against the
// config list. Authentik is case-preserving on the `email` claim which
// is a common footgun when operators type the email with different
// capitalisation in config vs. Authentik.
func bootstrapSysadmin(email string, sysadmins []string) bool {
target := strings.ToLower(strings.TrimSpace(email))
for _, s := range sysadmins {
if strings.ToLower(strings.TrimSpace(s)) == target {
return true
}
}
return false
}
// mintSession mints an anchorage-signed JWT representing the session.
// The role comes from the user's sysadmin flag; non-sysadmins default
// to "member" and attach the first membership's org if any exists (so
// the handlers can resolve cc.Org without a separate lookup).
func mintSession(ctx context.Context, deps SessionDeps, user *store.User) (string, *token.Claims, error) {
role := store.RoleMember
if user.IsSysadmin {
role = "sysadmin"
}
var orgID ids.OrgID
memberships, _ := deps.Store.Memberships().ListForUser(ctx, user.ID)
if len(memberships) > 0 {
orgID = memberships[0].OrgID
} else {
// No org yet — synthetic TypeID so the JWT is well-formed. The
// user has to be granted org membership (or promoted sysadmin)
// before this token is useful for tenant-scoped endpoints.
fresh, err := ids.NewOrg()
if err != nil {
return "", nil, err
}
orgID = fresh
}
ttl := deps.SessionTTL
if ttl <= 0 {
ttl = 24 * time.Hour
}
return deps.Signer.Mint(ctx, orgID, user.ID, role, nil, ttl)
}
func sessionCookieHeader(jwtValue string, deps SessionDeps) string {
parts := []string{
fmt.Sprintf("%s=%s", auth.SessionCookieName, jwtValue),
"Path=/",
"HttpOnly",
"SameSite=Lax",
fmt.Sprintf("Max-Age=%d", int(deps.SessionTTL.Seconds())),
}
if deps.CookieSecure {
parts = append(parts, "Secure")
}
return strings.Join(parts, "; ")
}
func clearCookieHeader(deps SessionDeps) string {
parts := []string{
fmt.Sprintf("%s=", auth.SessionCookieName),
"Path=/",
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
}
if deps.CookieSecure {
parts = append(parts, "Secure")
}
return strings.Join(parts, "; ")
}
func userBody(u *store.User) userBodyT {
return userBodyT{
ID: u.ID.String(),
Email: u.Email,
DisplayName: u.DisplayName,
IsSysadmin: u.IsSysadmin,
}
}
+185
View File
@@ -0,0 +1,185 @@
package openapi
import (
"context"
"errors"
"time"
"github.com/danielgtaylor/huma/v2"
"anchorage/internal/pkg/auth"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/store"
"anchorage/internal/pkg/token"
)
// TokenDeps wires token endpoints to the store + signer.
type TokenDeps struct {
Store store.Store
Signer *token.Signer
DefaultTTL time.Duration
MaxTTL time.Duration
}
// RegisterTokens wires POST / GET / DELETE /tokens onto api.
//
// POST /tokens is scoped to an org — the session JWT already carries
// cc.Org, so the minted API token inherits that org. Sysadmins with no
// memberships cannot use this endpoint; they either mint offline via
// `anchorage admin mint-token` or create an org first.
func RegisterTokens(api huma.API, deps TokenDeps) {
huma.Register(api, huma.Operation{
OperationID: "createToken",
Method: "POST",
Path: "/tokens",
Summary: "Mint an API token tied to the caller's current org + role",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
Body struct {
Label string `json:"label" minLength:"1" maxLength:"128"`
Scopes []string `json:"scopes,omitempty"`
TTLHours int `json:"ttl_hours,omitempty" minimum:"1"`
}
}) (*struct {
Body struct {
Token string `json:"token"`
JTI string `json:"jti"`
ExpiresAt time.Time `json:"expires_at"`
}
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
ttl := time.Duration(in.Body.TTLHours) * time.Hour
if ttl <= 0 {
ttl = deps.DefaultTTL
}
if deps.MaxTTL > 0 && ttl > deps.MaxTTL {
return nil, huma.Error400BadRequest("ttl exceeds auth.apiToken.maxTTL")
}
signed, claims, err := deps.Signer.Mint(ctx, cc.Org, cc.User, cc.Role, in.Body.Scopes, ttl)
if err != nil {
return nil, huma.Error500InternalServerError("mint", err)
}
jti, err := ids.ParseToken(claims.ID)
if err != nil {
return nil, huma.Error500InternalServerError("parse jti", err)
}
// Persist metadata so the user can list + revoke later. The
// raw token itself is NOT stored.
if err := deps.Store.Tokens().Create(ctx, &store.APIToken{
JTI: jti, OrgID: cc.Org, UserID: cc.User,
Label: in.Body.Label, Scopes: in.Body.Scopes,
ExpiresAt: claims.ExpiresAt.Time,
}); err != nil {
return nil, huma.Error500InternalServerError("persist", err)
}
_ = deps.Store.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &cc.Org, ActorUserID: &cc.User,
Action: "token.create", Target: jti.String(), Result: "ok",
Detail: map[string]any{"label": in.Body.Label, "ttl": ttl.String()},
})
out := &struct {
Body struct {
Token string `json:"token"`
JTI string `json:"jti"`
ExpiresAt time.Time `json:"expires_at"`
}
}{}
out.Body.Token = signed
out.Body.JTI = jti.String()
out.Body.ExpiresAt = claims.ExpiresAt.Time
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "listMyTokens",
Method: "GET",
Path: "/tokens",
Summary: "List API tokens minted by the caller",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, _ *struct{}) (*struct {
Body struct {
Results []tokenBody `json:"results"`
}
}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
rows, err := deps.Store.Tokens().ListForUser(ctx, cc.Org, cc.User)
if err != nil {
return nil, huma.Error500InternalServerError("list", err)
}
out := &struct {
Body struct {
Results []tokenBody `json:"results"`
}
}{}
for _, t := range rows {
out.Body.Results = append(out.Body.Results, tokenBody{
JTI: t.JTI.String(),
Label: t.Label,
Scopes: t.Scopes,
ExpiresAt: t.ExpiresAt,
CreatedAt: t.CreatedAt,
LastUsedAt: t.LastUsedAt,
RevokedAt: t.RevokedAt,
})
}
return out, nil
})
huma.Register(api, huma.Operation{
OperationID: "revokeToken",
Method: "DELETE",
Path: "/tokens/{jti}",
Summary: "Revoke an API token (adds the jti to the denylist)",
Security: []map[string][]string{{"accessToken": {}}},
}, func(ctx context.Context, in *struct {
JTI string `path:"jti"`
}) (*struct{}, error) {
cc, err := auth.Require(ctx)
if err != nil {
return nil, huma.Error401Unauthorized("auth")
}
jti, err := ids.ParseToken(in.JTI)
if err != nil {
return nil, huma.Error400BadRequest("bad jti")
}
existing, err := deps.Store.Tokens().GetByJTI(ctx, jti)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("token")
}
return nil, huma.Error500InternalServerError("lookup", err)
}
// Users can only revoke their own tokens; sysadmins can revoke any.
if cc.Role != "sysadmin" && existing.UserID != cc.User {
return nil, huma.Error403Forbidden("not your token")
}
if err := deps.Signer.Revoke(ctx, jti, existing.ExpiresAt, "user-initiated"); err != nil {
return nil, huma.Error500InternalServerError("revoke", err)
}
_ = deps.Store.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &existing.OrgID, ActorUserID: &cc.User,
Action: "token.revoke", Target: jti.String(), Result: "ok",
})
return &struct{}{}, nil
})
}
type tokenBody struct {
JTI string `json:"jti"`
Label string `json:"label"`
Scopes []string `json:"scopes,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
}