Files
anchorage/internal/pkg/openapi/tokens.go
T
57_WolveandClaude Opus 4.7 90ac4b169c
Security / Vulnerability Check (push) Successful in 1m47s
Test / Build & Unit Tests (push) Successful in 5m4s
Test / Lint (push) Successful in 27s
Test / Integration Tests (push) Failing after 1m58s
ci: fix first CI run — tidy, gofmt, ordering test, govulncheck pin
- ids: TestIDsAreTimeOrdered asserted strict lexicographic ordering of
  back-to-back UUIDv7s, but the sub-ms tail is random and not required
  to be monotonic. Sleep between samples so each ID lands in a distinct
  millisecond — the property that actually gives Postgres index
  locality on (org_id, id desc).
- go.mod/go.sum: run go mod tidy. keyfunc/v3, prometheus/client_golang
  and testcontainers-go/modules/postgres are imported directly and
  should not be marked // indirect; also drops stale sum entries.
- gofmt -w across 12 files flagged by the lint job.
- security.yml: pin govulncheck to v1.2.0. @latest triggers a proxy
  lookup every run, which is the step that hung for 16m on the Gitea
  runner.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 09:18:49 -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"`
}