feat(api): let owners audit all api tokens and cap their lifetime
Holders of tokens.manage list every token of the org with owner, permissions, creation, expiry and last use, and can revoke any of them. A maximum lifetime rejects tokens that would outlive it and shortens existing ones when it is set. Closes #48 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
da128c5081
commit
b52698ffbc
9 files changed
+674
-296
No files matched your search
+15
-2
@@ -429,6 +429,9 @@ func (s *Server) roleResult(c *gin.Context, err error, code string, ok func()) {
|
||||
type policyRequest struct {
|
||||
RequireTOTP bool `json:"require_totp"`
|
||||
RequireSSO bool `json:"require_sso"`
|
||||
// APITokenMaxDays limits how long API tokens stay valid; 0 or null
|
||||
// means no limit.
|
||||
APITokenMaxDays *int `json:"api_token_max_days" binding:"omitempty,min=0,max=3650"`
|
||||
}
|
||||
|
||||
func (s *Server) updatePolicy(c *gin.Context) {
|
||||
@@ -457,8 +460,18 @@ func (s *Server) updatePolicy(c *gin.Context) {
|
||||
return errNoSSOProvider
|
||||
}
|
||||
}
|
||||
var maxDays *int32
|
||||
if req.APITokenMaxDays != nil && *req.APITokenMaxDays > 0 {
|
||||
maxDays = ptr(int32(*req.APITokenMaxDays))
|
||||
}
|
||||
var err error
|
||||
org, err = q.UpdateOrgPolicy(ctx, store.UpdateOrgPolicyParams{ID: p.Org.ID, RequireTotp: req.RequireTOTP, RequireSso: req.RequireSSO})
|
||||
org, err = q.UpdateOrgPolicy(ctx, store.UpdateOrgPolicyParams{
|
||||
ID: p.Org.ID, RequireTotp: req.RequireTOTP, RequireSso: req.RequireSSO, ApiTokenMaxDays: maxDays,
|
||||
})
|
||||
if err != nil || maxDays == nil {
|
||||
return err
|
||||
}
|
||||
_, err = q.ClampAPITokenExpiry(ctx, store.ClampAPITokenExpiryParams{OrgID: p.Org.ID, MaxDays: *maxDays})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, errNoSSOProvider) {
|
||||
@@ -469,7 +482,7 @@ func (s *Server) updatePolicy(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"require_totp": org.RequireTotp, "require_sso": org.RequireSso})
|
||||
c.JSON(http.StatusOK, gin.H{"require_totp": org.RequireTotp, "require_sso": org.RequireSso, "api_token_max_days": org.ApiTokenMaxDays})
|
||||
}
|
||||
|
||||
var errNoSSOProvider = errors.New("api: no enabled sso provider")
|
||||
+36
-4
@@ -2,6 +2,7 @@ package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -268,7 +269,11 @@ func (s *Server) ssoSettingsView(c *gin.Context, p *principal, page web.Page, me
|
||||
}
|
||||
|
||||
func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
return web.OrgSettingsPage(page, me, web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso}), nil
|
||||
v := web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso}
|
||||
if p.Org.ApiTokenMaxDays != nil {
|
||||
v.TokenMaxDays = int(*p.Org.ApiTokenMaxDays)
|
||||
}
|
||||
return web.OrgSettingsPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
@@ -337,7 +342,7 @@ func (s *Server) rolesView(c *gin.Context, p *principal, page web.Page, me web.M
|
||||
|
||||
func (s *Server) tokensView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
showAll := p.Grants.Can(authz.MembersManage)
|
||||
showAll := p.Grants.Can(authz.TokensManage)
|
||||
var filter *uuid.UUID
|
||||
if !showAll {
|
||||
filter = &p.UserID
|
||||
@@ -351,10 +356,17 @@ func (s *Server) tokensView(c *gin.Context, p *principal, page web.Page, me web.
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.TokensView{Grantable: grantable(p), ShowOwner: showAll}
|
||||
v := web.TokensView{Grantable: grantable(p), ShowOwner: showAll, ExpiryDays: expiryChoices(p.Org.ApiTokenMaxDays)}
|
||||
if p.Org.ApiTokenMaxDays != nil {
|
||||
v.MaxDays = int(*p.Org.ApiTokenMaxDays)
|
||||
}
|
||||
never := i18n.T(ctx, "tokens.never")
|
||||
for _, r := range rows {
|
||||
t := web.Token{ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, UserEmail: r.UserEmail, Permissions: r.Permissions, ExpiresAt: never, LastUsedAt: "–"}
|
||||
t := web.Token{
|
||||
ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, UserEmail: r.UserEmail,
|
||||
Permissions: authz.NewSet(r.Permissions...).Strings(), CreatedAt: r.CreatedAt.Format(time.DateOnly),
|
||||
ExpiresAt: never, LastUsedAt: "–",
|
||||
}
|
||||
if r.ExpiresAt != nil {
|
||||
t.ExpiresAt = r.ExpiresAt.Format(time.DateOnly)
|
||||
}
|
||||
@@ -366,6 +378,26 @@ func (s *Server) tokensView(c *gin.Context, p *principal, page web.Page, me web.
|
||||
return web.TokensPage(page, me, v), nil
|
||||
}
|
||||
|
||||
// expiryChoices returns the token lifetimes to offer, in days, honoring the
|
||||
// org's limit. 0 stands for no expiry and is only offered without a limit.
|
||||
func expiryChoices(limit *int32) []int {
|
||||
defaults := []int{90, 30, 365, 0}
|
||||
if limit == nil {
|
||||
return defaults
|
||||
}
|
||||
max := int(*limit)
|
||||
var out []int
|
||||
for _, d := range defaults {
|
||||
if d > 0 && d <= max {
|
||||
out = append(out, d)
|
||||
}
|
||||
}
|
||||
if !slices.Contains(out, max) {
|
||||
out = append(out, max)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func toWebMe(m meView) web.Me {
|
||||
out := web.Me{
|
||||
Email: m.Email,
|
||||
|
||||
@@ -209,3 +209,68 @@ func TestPermissions(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestTokenOversightAndLifetimePolicy(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
domain := uniq("t") + ".test"
|
||||
owner := e.browser(t)
|
||||
owner.signup("owner@"+domain, uniq("tok-"))
|
||||
editor := e.joinVia(t, owner.invite("editor@"+domain, owner.roleID("editor")))
|
||||
|
||||
st, body := editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "forever", "permissions": []string{"monitors.read"}})
|
||||
expect(t, "editor creates non-expiring token", st, body, http.StatusCreated, "")
|
||||
editorTokenID := body["id"].(string)
|
||||
api := &browser{t: t, base: editor.base, hc: e.srv.Client(), bearer: body["token"].(string)}
|
||||
owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "own", "permissions": []string{"monitors.read"}})
|
||||
|
||||
tokenNames := func(b *browser) []string {
|
||||
_, body := b.do("GET", "/api/v1/org/tokens", nil)
|
||||
var names []string
|
||||
for _, tk := range body["tokens"].([]any) {
|
||||
names = append(names, tk.(map[string]any)["name"].(string))
|
||||
}
|
||||
return names
|
||||
}
|
||||
if got := tokenNames(owner); len(got) != 2 {
|
||||
t.Errorf("owner sees tokens %v, want both", got)
|
||||
}
|
||||
if got := tokenNames(editor); len(got) != 1 || got[0] != "forever" {
|
||||
t.Errorf("editor sees tokens %v, want only own", got)
|
||||
}
|
||||
|
||||
st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"api_token_max_days": 30})
|
||||
expect(t, "set lifetime policy", st, body, http.StatusOK, "")
|
||||
_, list := owner.do("GET", "/api/v1/org/tokens", nil)
|
||||
for _, tk := range list["tokens"].([]any) {
|
||||
tk := tk.(map[string]any)
|
||||
exp, _ := time.Parse(time.RFC3339Nano, fmtString(tk["expires_at"]))
|
||||
if exp.IsZero() || exp.After(time.Now().Add(31*24*time.Hour)) {
|
||||
t.Errorf("token %v expires_at = %v, want within 30 days", tk["name"], tk["expires_at"])
|
||||
}
|
||||
}
|
||||
|
||||
for _, days := range []int{0, 31} {
|
||||
st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "x", "permissions": []string{"monitors.read"}, "expires_in_days": days})
|
||||
expect(t, "token beyond policy", st, body, http.StatusUnprocessableEntity, "token_lifetime_exceeds_policy")
|
||||
}
|
||||
st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ok", "permissions": []string{"monitors.read"}, "expires_in_days": 30})
|
||||
expect(t, "token within policy", st, body, http.StatusCreated, "")
|
||||
|
||||
st, body = owner.do("DELETE", "/api/v1/org/tokens/"+editorTokenID, nil)
|
||||
expect(t, "owner revokes editor token", st, body, http.StatusNoContent, "")
|
||||
st, body = api.do("GET", "/api/v1/org/tokens", nil)
|
||||
expect(t, "revoked token", st, body, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"api_token_max_days": 0})
|
||||
if st != http.StatusOK || body["api_token_max_days"] != nil {
|
||||
t.Errorf("clear lifetime policy = %d %v, want 200 with null", st, body)
|
||||
}
|
||||
if got := owner.visit("/settings/tokens"); got.Path != "/settings/tokens" {
|
||||
t.Errorf("tokens page ended at %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func fmtString(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
+10
-5
@@ -98,10 +98,10 @@ type tokenView struct {
|
||||
func (s *Server) listTokens(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
// Members see their own tokens; members.manage reveals everyone's so
|
||||
// tokens of departing staff can be revoked.
|
||||
// Members see their own tokens; tokens.manage reveals everyone's so the
|
||||
// owner can audit and revoke them.
|
||||
var filter *uuid.UUID
|
||||
if !p.Grants.Can(authz.MembersManage) {
|
||||
if !p.Grants.Can(authz.TokensManage) {
|
||||
filter = &p.UserID
|
||||
}
|
||||
var rows []store.ListAPITokensRow
|
||||
@@ -127,7 +127,8 @@ func (s *Server) listTokens(c *gin.Context) {
|
||||
type createTokenRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"`
|
||||
// ExpiresInDays of 0 creates a token that does not expire.
|
||||
// ExpiresInDays of 0 creates a token that does not expire, unless the
|
||||
// org limits token lifetime.
|
||||
ExpiresInDays int `json:"expires_in_days" binding:"min=0,max=3650"`
|
||||
}
|
||||
|
||||
@@ -146,6 +147,10 @@ func (s *Server) createToken(c *gin.Context) {
|
||||
fail(c, http.StatusForbidden, "permission_escalation")
|
||||
return
|
||||
}
|
||||
if limit := p.Org.ApiTokenMaxDays; limit != nil && (req.ExpiresInDays == 0 || req.ExpiresInDays > int(*limit)) {
|
||||
fail(c, http.StatusUnprocessableEntity, "token_lifetime_exceeds_policy", "Count", int(*limit))
|
||||
return
|
||||
}
|
||||
var expires *time.Time
|
||||
if req.ExpiresInDays > 0 {
|
||||
t := time.Now().AddDate(0, 0, req.ExpiresInDays)
|
||||
@@ -187,7 +192,7 @@ func (s *Server) deleteToken(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if row.UserID != p.UserID && !p.Grants.Can(authz.MembersManage) {
|
||||
if row.UserID != p.UserID && !p.Grants.Can(authz.TokensManage) {
|
||||
return nil
|
||||
}
|
||||
found = true
|
||||
|
||||
Reference in new issue
Block a user