feat(16.3-01): account token API with OpenAPI and phrase keys

- Add list/create/revoke/scopes handlers, validation, and soft revoke
- Regenerate admin OpenAPI and TS types; inventory and conformance cases
- Add server-side api_tokens phrase keys (en/pl)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-11 01:51:11 +02:00
parent 183583e0e9
commit ffdb5d00ca
13 changed files with 1430 additions and 49 deletions

View File

@@ -11,6 +11,7 @@ import (
"sync"
"time"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/lagoon"
"gorm.io/gorm"
)
@@ -67,10 +68,119 @@ func wellFormedAPIToken(v string) bool {
return true
}
// issueAPIToken mints a token for ownerID with the given scopes and optional
// expiry, inserts the row, and returns the plaintext exactly once. Task 3
// grows this into the shared API/CLI validation path.
func issueAPIToken(db *gorm.DB, ownerID uint, name string, scopes []string, expiresAt *time.Time) (plain string, row *BackendAPIToken, err error) {
// cleanedTokenRequest is the validated create payload.
type cleanedTokenRequest struct {
Name string
ExpiresAt *time.Time
Scopes []string
}
// validateTokenRequest applies D-08/D-17 name, expiry and scope rules with no
// database access. details maps field names to message keys under
// backend::lang (for example api_tokens.name_required). cli enables YYYY-MM-DD
// expiry dates (00:00 UTC, must be after now).
func validateTokenRequest(reg *Registry, owner *bouncer.Principal, name, expires string, scopes []string, now time.Time, cli bool) (cleanedTokenRequest, map[string]any) {
details := map[string]any{}
name = strings.TrimSpace(name)
if name == "" {
details["name"] = []string{"api_tokens.name_required"}
} else if len([]rune(name)) > 100 {
details["name"] = []string{"api_tokens.name_too_long"}
}
expiresAt, expKey := parseTokenExpiry(expires, now, cli)
if expKey != "" {
details["expires"] = []string{expKey}
}
cleanedScopes, scopeDetails := validateTokenScopes(reg, owner, scopes)
for k, v := range scopeDetails {
details[k] = v
}
if len(details) > 0 {
return cleanedTokenRequest{}, details
}
return cleanedTokenRequest{Name: name, ExpiresAt: expiresAt, Scopes: cleanedScopes}, nil
}
func parseTokenExpiry(expires string, now time.Time, cli bool) (*time.Time, string) {
expires = strings.TrimSpace(expires)
if expires == "" {
expires = "90d"
}
switch expires {
case "30d":
t := now.UTC().Add(30 * 24 * time.Hour)
return &t, ""
case "90d":
t := now.UTC().Add(90 * 24 * time.Hour)
return &t, ""
case "365d":
t := now.UTC().Add(365 * 24 * time.Hour)
return &t, ""
case "never":
return nil, ""
}
if cli {
if t, err := time.Parse("2006-01-02", expires); err == nil {
t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
if !t.After(now.UTC()) {
return nil, "api_tokens.expires_invalid"
}
return &t, ""
}
}
return nil, "api_tokens.expires_invalid"
}
func validateTokenScopes(reg *Registry, owner *bouncer.Principal, scopes []string) ([]string, map[string]any) {
details := map[string]any{}
if len(scopes) == 0 {
details["scopes"] = []string{"api_tokens.scopes_required"}
return nil, details
}
for _, s := range scopes {
if s == scopeAll {
return []string{scopeAll}, nil
}
}
seen := map[string]bool{}
out := make([]string, 0, len(scopes))
for _, name := range scopes {
name = strings.TrimSpace(name)
if name == "" || seen[name] {
continue
}
seen[name] = true
if reg == nil || reg.tokenScopes == nil || reg.tokenScopes.byName[name] == nil || !scopeOverlaps(reg, owner, name) {
details["scopes"] = []string{"api_tokens.scope_unavailable|" + name}
return nil, details
}
out = append(out, name)
}
if len(out) == 0 {
details["scopes"] = []string{"api_tokens.scopes_required"}
return nil, details
}
return out, nil
}
// issueAPIToken validates and inserts a token for the owner. On validation
// failure details is non-nil and plain/row are zero. The plaintext is returned
// exactly once on success.
func issueAPIToken(db *gorm.DB, reg *Registry, owner *bouncer.Principal, name, expires string, scopes []string, now time.Time, cli bool) (plain string, row *BackendAPIToken, details map[string]any, err error) {
if owner == nil || owner.ID == 0 {
return "", nil, nil, fmt.Errorf("cabana: issue API token: missing owner")
}
cleaned, details := validateTokenRequest(reg, owner, name, expires, scopes, now, cli)
if details != nil {
return "", nil, details, nil
}
plain, row, err = insertAPIToken(db, owner.ID, cleaned.Name, cleaned.Scopes, cleaned.ExpiresAt)
return plain, row, nil, err
}
// insertAPIToken mints and persists a row without validation (tests and the
// validated issueAPIToken path).
func insertAPIToken(db *gorm.DB, ownerID uint, name string, scopes []string, expiresAt *time.Time) (plain string, row *BackendAPIToken, err error) {
if db == nil || ownerID == 0 {
return "", nil, fmt.Errorf("cabana: issue API token: missing database or owner")
}
@@ -98,6 +208,29 @@ func issueAPIToken(db *gorm.DB, ownerID uint, name string, scopes []string, expi
return plain, row, nil
}
// revokeAPIToken soft-revokes the owner's active token. notFound is true when
// no matching active row was updated.
func revokeAPIToken(db *gorm.DB, ownerID, id uint, revokedBy *uint) (row *BackendAPIToken, notFound bool, err error) {
if db == nil || ownerID == 0 || id == 0 {
return nil, true, nil
}
now := time.Now().UTC()
res := db.Model(&BackendAPIToken{}).
Where("id = ? AND backend_user_id = ? AND revoked_at IS NULL", id, ownerID).
Updates(map[string]any{"revoked_at": now, "revoked_by": revokedBy})
if res.Error != nil {
return nil, false, res.Error
}
if res.RowsAffected == 0 {
return nil, true, nil
}
var out BackendAPIToken
if err := db.First(&out, id).Error; err != nil {
return nil, false, err
}
return &out, false, nil
}
// tokenStore looks up usable personal API tokens by hash and stamps last_used_at.
type tokenStore interface {
FindUsableByHash(ctx context.Context, hash string, now time.Time) (*BackendAPIToken, error)