v2.31.0-dev22 8d342c4

service.go RawHistoryFolder

1// Package auth implements the authentication use case for the registry.
2package auth
3
4import (
5	"context"
6	"errors"
7	"fmt"
8	"strings"
9	"time"
10
11	"github.com/bnema/zerowrap"
12	"github.com/golang-jwt/jwt/v5"
13	"github.com/google/uuid"
14
15	"github.com/bnema/gordon/internal/boundaries/out"
16	"github.com/bnema/gordon/internal/domain"
17)
18
19const (
20	// TokenIssuer is the issuer claim for generated tokens.
21	TokenIssuer = "gordon-registry"
22	// DefaultAccessTokenTTL is the default lifetime for ephemeral access tokens.
23	DefaultAccessTokenTTL = 15 * time.Minute
24	// MaxAccessTokenLifetime is the maximum lifetime for ephemeral access tokens.
25	// Tokens with this lifetime or less skip store validation.
26	MaxAccessTokenLifetime = 1 * time.Hour
27	// maxAccessTokenLifetimeSecs is MaxAccessTokenLifetime in seconds for JWT comparisons.
28	maxAccessTokenLifetimeSecs = int64(MaxAccessTokenLifetime / time.Second)
29	// tokenExtensionTTL is the amount of time added to a token's expiry when extended.
30	tokenExtensionTTL = 24 * time.Hour
31	// tokenExtensionDebounce is the minimum time between token extensions.
32	tokenExtensionDebounce = time.Hour
33	// serviceTokenSubject is the subject used for internal service tokens.
34	// Service tokens are not extended to avoid churn on the token store.
35	serviceTokenSubject = "gordon-service"
36)
37
38// Config holds the authentication configuration.
39type Config struct {
40	Enabled        bool
41	AuthType       domain.AuthType
42	Username       string
43	TokenSecret    []byte        // signing secret for token auth
44	TokenExpiry    time.Duration // default token expiry (0 = never)
45	AccessTokenTTL time.Duration // ephemeral token lifetime (default: 15m)
46}
47
48// Service implements the AuthService interface.
49type Service struct {
50	config     Config
51	tokenStore out.TokenStore
52	log        zerowrap.Logger
53}
54
55// NewService creates a new auth service.
56func NewService(config Config, tokenStore out.TokenStore, log zerowrap.Logger) *Service {
57	return &Service{
58		config:     config,
59		tokenStore: tokenStore,
60		log:        log,
61	}
62}
63
64// GetAuthType returns the configured authentication type.
65func (s *Service) GetAuthType() domain.AuthType {
66	return s.config.AuthType
67}
68
69// IsEnabled returns whether authentication is enabled.
70func (s *Service) IsEnabled() bool {
71	return s.config.Enabled
72}
73
74// GetAccessTokenTTL returns the configured ephemeral access token lifetime.
75func (s *Service) GetAccessTokenTTL() time.Duration {
76	if s.config.AccessTokenTTL > 0 {
77		return s.config.AccessTokenTTL
78	}
79	return DefaultAccessTokenTTL
80}
81
82// ValidateToken validates a JWT token and returns its claims.
83func (s *Service) ValidateToken(ctx context.Context, tokenString string) (*domain.TokenClaims, error) {
84	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
85		zerowrap.FieldLayer:   "usecase",
86		zerowrap.FieldUseCase: "ValidateToken",
87	})
88	log := zerowrap.FromCtx(ctx)
89
90	claims, err := s.parseTokenClaims(tokenString)
91	if err != nil {
92		log.Debug().Err(err).Msg("failed to parse token")
93		return nil, err
94	}
95
96	tokenClaims := buildTokenClaims(claims)
97
98	// Access tokens (short-lived, ≤1h, recently issued) skip store validation.
99	// CLI-generated tokens must exist in store to prevent use of externally-created tokens.
100	// Security: require token to be recently issued (within MaxAccessTokenLifetime) to prevent
101	// attackers with stolen secrets from creating arbitrary short-lived tokens.
102	isAccessToken := s.isEphemeralAccessToken(tokenClaims)
103	tokenClaims.IsEphemeral = isAccessToken
104
105	if !isAccessToken {
106		if err := s.ensureTokenExists(ctx, tokenClaims, log); err != nil {
107			return nil, err
108		}
109		if err := s.ensureTokenNotRevoked(ctx, tokenClaims, log); err != nil {
110			return nil, err
111		}
112	}
113
114	if err := ensureTokenNotExpired(tokenClaims, log); err != nil {
115		return nil, err
116	}
117
118	log.Debug().Str("subject", tokenClaims.Subject).Msg("token validation successful")
119	return tokenClaims, nil
120}
121
122// ensureTokenExists verifies the token exists in the store and the JTI matches.
123func (s *Service) ensureTokenExists(ctx context.Context, tokenClaims *domain.TokenClaims, log zerowrap.Logger) error {
124	_, storedToken, err := s.tokenStore.GetToken(ctx, tokenClaims.Subject)
125	if err != nil {
126		if errors.Is(err, domain.ErrTokenNotFound) {
127			log.Debug().Str("subject", tokenClaims.Subject).Msg("token not found in store")
128			return domain.ErrInvalidToken
129		}
130		// SECURITY: Fail closed on store errors
131		log.Error().Err(err).Msg("failed to verify token existence")
132		return fmt.Errorf("unable to verify token: %w", err)
133	}
134
135	// Verify the token ID matches the stored token
136	if storedToken.ID != tokenClaims.ID {
137		log.Debug().
138			Str("expected_id", storedToken.ID).
139			Str("actual_id", tokenClaims.ID).
140			Msg("token ID mismatch")
141		return domain.ErrInvalidToken
142	}
143
144	return nil
145}
146
147func (s *Service) parseTokenClaims(tokenString string) (jwt.MapClaims, error) {
148	// Parse token with issuer validation
149	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
150		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
151			return nil, domain.ErrInvalidToken
152		}
153		return s.config.TokenSecret, nil
154	},
155		jwt.WithIssuer(TokenIssuer), // SECURITY: Enforce issuer validation
156		jwt.WithIssuedAt(),          // SECURITY: Reject tokens with iat in the future
157	)
158	if err != nil {
159		return nil, domain.ErrInvalidToken
160	}
161
162	if !token.Valid {
163		return nil, domain.ErrInvalidToken
164	}
165
166	claims, ok := token.Claims.(jwt.MapClaims)
167	if !ok {
168		return nil, domain.ErrInvalidToken
169	}
170
171	// SECURITY: Double-check issuer claim matches expected value
172	if iss, ok := claims["iss"].(string); !ok || iss != TokenIssuer {
173		return nil, domain.ErrInvalidToken
174	}
175
176	return claims, nil
177}
178
179func buildTokenClaims(claims jwt.MapClaims) *domain.TokenClaims {
180	tokenClaims := &domain.TokenClaims{
181		Issuer: getStringClaim(claims, "iss"),
182	}
183
184	if jti, ok := claims["jti"].(string); ok {
185		tokenClaims.ID = jti
186	}
187	if sub, ok := claims["sub"].(string); ok {
188		tokenClaims.Subject = sub
189	}
190	if iat, ok := claims["iat"].(float64); ok {
191		tokenClaims.IssuedAt = int64(iat)
192	}
193	if exp, ok := claims["exp"].(float64); ok {
194		tokenClaims.ExpiresAt = int64(exp)
195	}
196	if scopes, ok := claims["scopes"].([]any); ok {
197		for _, scope := range scopes {
198			if s, ok := scope.(string); ok {
199				tokenClaims.Scopes = append(tokenClaims.Scopes, s)
200			}
201		}
202	}
203
204	return tokenClaims
205}
206
207func (s *Service) ensureTokenNotRevoked(ctx context.Context, tokenClaims *domain.TokenClaims, log zerowrap.Logger) error {
208	revoked, err := s.tokenStore.IsRevoked(ctx, tokenClaims.ID)
209	if err != nil {
210		// SECURITY: Fail closed - deny access on revocation check error
211		log.Error().Err(err).Str("token_id", tokenClaims.ID).Msg("failed to check token revocation, denying access")
212		return fmt.Errorf("unable to verify token status: %w", err)
213	}
214	if revoked {
215		log.Debug().Str("token_id", tokenClaims.ID).Msg("token has been revoked")
216		return domain.ErrRevokedToken
217	}
218
219	return nil
220}
221
222func ensureTokenNotExpired(tokenClaims *domain.TokenClaims, log zerowrap.Logger) error {
223	if tokenClaims.ExpiresAt <= 0 {
224		return nil
225	}
226
227	if time.Now().UTC().Unix() > tokenClaims.ExpiresAt {
228		log.Debug().Str("token_id", tokenClaims.ID).Msg("token has expired")
229		return domain.ErrExpiredToken
230	}
231
232	return nil
233}
234
235// isEphemeralAccessToken checks if a token is a short-lived access token that
236// doesn't require store validation. Access tokens must:
237// 1. Have a positive expiry (not never-expiring)
238// 2. Have lifetime ≤ MaxAccessTokenLifetime
239// 3. Be recently issued (within MaxAccessTokenLifetime) to prevent replay attacks
240func (s *Service) isEphemeralAccessToken(claims *domain.TokenClaims) bool {
241	if claims.ExpiresAt <= 0 {
242		return false // Never-expiring tokens require store validation
243	}
244
245	lifetime := claims.ExpiresAt - claims.IssuedAt
246	if lifetime > maxAccessTokenLifetimeSecs {
247		return false // Long-lived tokens require store validation
248	}
249
250	// Security: ensure token was recently issued to prevent attackers with
251	// stolen secrets from creating arbitrary short-lived tokens
252	now := time.Now().UTC().Unix()
253	tokenAge := now - claims.IssuedAt
254	if tokenAge < 0 {
255		// iat is in the future — do not classify as ephemeral (defense-in-depth: prevents bypass)
256		return false
257	}
258	if tokenAge > maxAccessTokenLifetimeSecs {
259		return false // Old tokens require store validation
260	}
261
262	return true
263}
264
265// GenerateToken creates a new JWT token for the given subject.
266func (s *Service) GenerateToken(ctx context.Context, subject string, scopes []string, expiry time.Duration) (string, error) {
267	if strings.Contains(subject, ":") {
268		return "", fmt.Errorf("subject %q must not contain ':' (used as Basic Auth username)", subject)
269	}
270
271	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
272		zerowrap.FieldLayer:   "usecase",
273		zerowrap.FieldUseCase: "GenerateToken",
274		"subject":             subject,
275	})
276	log := zerowrap.FromCtx(ctx)
277
278	tokenID := uuid.New().String()
279	now := time.Now().UTC()
280
281	// Build token
282	token := &domain.Token{
283		ID:       tokenID,
284		Subject:  subject,
285		Scopes:   scopes,
286		IssuedAt: now,
287		Revoked:  false,
288	}
289
290	// Build JWT claims
291	claims := jwt.MapClaims{
292		"jti":    tokenID,
293		"sub":    subject,
294		"iss":    TokenIssuer,
295		"iat":    now.Unix(),
296		"nbf":    now.Unix(), // SECURITY: Not-before claim for clock skew protection
297		"scopes": scopes,
298	}
299
300	// Set expiry if specified
301	if expiry > 0 {
302		expiresAt := now.Add(expiry)
303		token.ExpiresAt = expiresAt
304		claims["exp"] = expiresAt.Unix()
305	}
306	// If expiry is 0, token never expires (no exp claim)
307
308	// Sign token
309	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
310	tokenString, err := jwtToken.SignedString(s.config.TokenSecret)
311	if err != nil {
312		return "", log.WrapErr(err, "failed to sign token")
313	}
314
315	// Store token
316	if err := s.tokenStore.SaveToken(ctx, token, tokenString); err != nil {
317		return "", log.WrapErr(err, "failed to save token")
318	}
319
320	log.Info().
321		Str("token_id", tokenID).
322		Str("subject", subject).
323		Time("expires_at", token.ExpiresAt).
324		Msg("token generated")
325
326	return tokenString, nil
327}
328
329// GenerateAccessToken creates a short-lived JWT for registry access without storing it.
330// Used by /v2/token endpoint - these tokens don't need persistence.
331// Expiry must be > 0 and <= MaxAccessTokenLifetime to prevent misuse.
332func (s *Service) GenerateAccessToken(ctx context.Context, subject string, scopes []string, expiry time.Duration) (string, error) {
333	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
334		zerowrap.FieldLayer:   "usecase",
335		zerowrap.FieldUseCase: "GenerateAccessToken",
336		"subject":             subject,
337	})
338	log := zerowrap.FromCtx(ctx)
339
340	// Enforce expiry constraints to prevent misuse
341	if expiry <= 0 {
342		return "", fmt.Errorf("access token expiry must be positive")
343	}
344	if expiry > MaxAccessTokenLifetime {
345		return "", fmt.Errorf("access token expiry exceeds maximum of %v", MaxAccessTokenLifetime)
346	}
347
348	tokenID := uuid.New().String()
349	now := time.Now().UTC()
350
351	claims := jwt.MapClaims{
352		"jti":    tokenID,
353		"sub":    subject,
354		"iss":    TokenIssuer,
355		"iat":    now.Unix(),
356		"nbf":    now.Unix(), // SECURITY: Not-before claim for clock skew protection
357		"scopes": scopes,
358		"exp":    now.Add(expiry).Unix(),
359	}
360
361	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
362	tokenString, err := jwtToken.SignedString(s.config.TokenSecret)
363	if err != nil {
364		return "", log.WrapErr(err, "failed to sign access token")
365	}
366
367	log.Debug().
368		Str("token_id", tokenID).
369		Str("subject", subject).
370		Msg("access token generated")
371
372	return tokenString, nil
373}
374
375// RevokeToken revokes a token by its ID.
376func (s *Service) RevokeToken(ctx context.Context, tokenID string) error {
377	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
378		zerowrap.FieldLayer:   "usecase",
379		zerowrap.FieldUseCase: "RevokeToken",
380		"token_id":            tokenID,
381	})
382	log := zerowrap.FromCtx(ctx)
383
384	if err := s.tokenStore.Revoke(ctx, tokenID); err != nil {
385		return log.WrapErr(err, "failed to revoke token")
386	}
387
388	log.Info().Msg("token revoked")
389	return nil
390}
391
392// RevokeAllTokens revokes all stored tokens and returns the count of revoked tokens.
393func (s *Service) RevokeAllTokens(ctx context.Context) (int, error) {
394	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
395		zerowrap.FieldLayer:   "usecase",
396		zerowrap.FieldUseCase: "RevokeAllTokens",
397	})
398	log := zerowrap.FromCtx(ctx)
399
400	tokens, err := s.tokenStore.ListTokens(ctx)
401	if err != nil {
402		return 0, log.WrapErr(err, "failed to list tokens")
403	}
404
405	revoked := 0
406	for _, token := range tokens {
407		if token.Revoked {
408			continue // Already revoked
409		}
410		if err := s.tokenStore.Revoke(ctx, token.ID); err != nil {
411			log.Warn().Err(err).Str("token_id", token.ID).Msg("failed to revoke token")
412			continue
413		}
414		revoked++
415	}
416
417	log.Info().Int("count", revoked).Msg("all tokens revoked")
418	return revoked, nil
419}
420
421// ListTokens returns all stored tokens.
422func (s *Service) ListTokens(ctx context.Context) ([]domain.Token, error) {
423	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
424		zerowrap.FieldLayer:   "usecase",
425		zerowrap.FieldUseCase: "ListTokens",
426	})
427	log := zerowrap.FromCtx(ctx)
428
429	tokens, err := s.tokenStore.ListTokens(ctx)
430	if err != nil {
431		return nil, log.WrapErr(err, "failed to list tokens")
432	}
433
434	return tokens, nil
435}
436
437// ExtendToken re-issues the token with expiry slid forward by 24h.
438// Returns the same token string if it was already extended within the debounce window (1h).
439// Skips extension for ephemeral access tokens (≤1h) and service tokens.
440func (s *Service) ExtendToken(ctx context.Context, tokenString string) (string, error) {
441	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
442		zerowrap.FieldLayer:   "usecase",
443		zerowrap.FieldUseCase: "ExtendToken",
444	})
445	log := zerowrap.FromCtx(ctx)
446
447	// Parse claims without store validation first (to check skip conditions cheaply)
448	rawClaims, err := s.parseTokenClaims(tokenString)
449	if err != nil {
450		return "", domain.ErrInvalidToken
451	}
452
453	tokenClaims := buildTokenClaims(rawClaims)
454
455	// Skip ephemeral access tokens (≤1h lifetime)
456	if s.isEphemeralAccessToken(tokenClaims) {
457		log.Debug().Msg("skipping extension for ephemeral access token")
458		return tokenString, nil
459	}
460
461	// Skip service tokens
462	if tokenClaims.Subject == serviceTokenSubject {
463		log.Debug().Msg("skipping extension for service token")
464		return tokenString, nil
465	}
466
467	// Skip tokens with no expiry (permanent tokens must not be silently converted to 24h tokens)
468	if tokenClaims.ExpiresAt <= 0 {
469		log.Debug().Str("subject", tokenClaims.Subject).Msg("skipping extension for non-expiring token")
470		return tokenString, nil
471	}
472
473	// Full validation including store checks (not expired, not revoked, exists in store)
474	if _, err := s.ValidateToken(ctx, tokenString); err != nil {
475		return "", fmt.Errorf("token validation failed: %w", err)
476	}
477
478	// Fetch stored token to check debounce and get metadata
479	_, storedToken, err := s.tokenStore.GetToken(ctx, tokenClaims.Subject)
480	if err != nil {
481		return "", fmt.Errorf("failed to fetch stored token: %w", err)
482	}
483
484	// TOCTOU guard: confirm the store's current JTI matches the JWT we validated.
485	// A mismatch means the token was rotated between ValidateToken and GetToken;
486	// in that case return the original (still-valid) token without re-signing.
487	if storedToken.ID != tokenClaims.ID {
488		log.Debug().
489			Str("subject", tokenClaims.Subject).
490			Str("jwt_jti", tokenClaims.ID).
491			Str("store_id", storedToken.ID).
492			Msg("token ID mismatch after rotation, skipping extension")
493		return tokenString, nil
494	}
495
496	// Debounce: skip if already extended within the last hour
497	if !storedToken.LastExtendedAt.IsZero() && time.Since(storedToken.LastExtendedAt) < tokenExtensionDebounce {
498		log.Debug().
499			Str("subject", tokenClaims.Subject).
500			Time("last_extended_at", storedToken.LastExtendedAt).
501			Msg("token extension debounced")
502		return tokenString, nil
503	}
504
505	// Re-sign with same JTI but new expiry
506	now := time.Now().UTC()
507	newExpiresAt := now.Add(tokenExtensionTTL)
508
509	newClaims := jwt.MapClaims{
510		"jti":    tokenClaims.ID, // Reuse existing JTI to avoid invalidating concurrent requests
511		"sub":    tokenClaims.Subject,
512		"iss":    TokenIssuer,
513		"iat":    now.Unix(), // Update to current time (token is being re-issued)
514		"nbf":    now.Unix(), // SECURITY: not-before matches issuance time
515		"scopes": tokenClaims.Scopes,
516		"exp":    newExpiresAt.Unix(),
517	}
518
519	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, newClaims)
520	newTokenString, err := jwtToken.SignedString(s.config.TokenSecret)
521	if err != nil {
522		return "", log.WrapErr(err, "failed to re-sign token")
523	}
524
525	// Update stored token with new JWT, expiry, and LastExtendedAt
526	updatedToken := &domain.Token{
527		ID:             storedToken.ID,
528		Subject:        storedToken.Subject,
529		Scopes:         storedToken.Scopes,
530		IssuedAt:       storedToken.IssuedAt,
531		ExpiresAt:      newExpiresAt,
532		Revoked:        storedToken.Revoked,
533		LastExtendedAt: now,
534	}
535
536	if err := s.tokenStore.UpdateTokenExpiry(ctx, updatedToken, newTokenString); err != nil {
537		// Non-fatal: log and return original token rather than failing the request
538		log.Warn().Err(err).Str("subject", tokenClaims.Subject).Msg("failed to persist extended token, returning original")
539		return tokenString, nil
540	}
541
542	log.Debug().
543		Str("subject", tokenClaims.Subject).
544		Time("new_expires_at", newExpiresAt).
545		Msg("token expiry extended")
546
547	return newTokenString, nil
548}
549
550// getStringClaim safely extracts a string claim from JWT claims.
551func getStringClaim(claims jwt.MapClaims, key string) string {
552	if val, ok := claims[key].(string); ok {
553		return val
554	}
555	return ""
556}
557
558// GetAuthStatus returns authentication status from context.
559// Claims are already validated by AdminAuth middleware and stored in context.
560func (s *Service) GetAuthStatus(ctx context.Context) (*domain.AuthStatus, error) {
561	ctx = zerowrap.CtxWithFields(ctx, map[string]any{
562		zerowrap.FieldLayer:   "usecase",
563		zerowrap.FieldUseCase: "GetAuthStatus",
564	})
565
566	// If auth is disabled, return valid status with no claims
567	if !s.IsEnabled() {
568		return &domain.AuthStatus{Valid: true}, nil
569	}
570
571	// Extract claims from context (set by AdminAuth middleware)
572	claims := domain.GetTokenClaims(ctx)
573	if claims == nil {
574		return &domain.AuthStatus{Valid: false}, nil
575	}
576
577	return &domain.AuthStatus{
578		Valid:     true,
579		Subject:   claims.Subject,
580		Scopes:    claims.Scopes,
581		ExpiresAt: claims.ExpiresAt,
582		IssuedAt:  claims.IssuedAt,
583	}, nil
584}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 7

Tags 106

↑↓ moveenter openesc close