Files
anchorage/internal/pkg/openapi/tokens.go
T
57_Wolve 12bf35caf8 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.
2026-04-16 18:13:36 -05:00

186 lines
5.6 KiB
Go

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"`
}