Files
geo/server/internal/shared/auth/jwt.go
T
root 618399f86d feat(server): hot-reload config store and reloadable infra clients
- Replace single Load() with a watching Store that re-reads config files
  (and config.local.yaml) and fans out a ReloadEvent with a per-field diff
  so consumers can decide whether the change is hot-applicable or requires
  a process restart.
- Wrap llm, retrieval, vector store, and object storage clients in
  Reloadable* shells so the bootstrap can swap their underlying impls when
  config changes without re-instantiating handlers.
- Make jwt.Manager and ops TokenIssuer mutable under a lock so secrets and
  TTLs can be rotated live; thread default plan code through a setter on
  the ops AdminUserService.
- Wire ConfigStore through bootstrap and every cmd/main.go, scheduler /
  worker / tenant-api / ops-api start the watcher; services and handlers
  take a config.Provider so they always read current values for things
  like generation.stream_enabled, scheduler dispatch, retrieval, etc.
- Switch shared/config decoding off viper to a Kratos-derived runtime
  package so env placeholders (\${VAR:default}) resolve consistently and
  the same source machinery powers both the loader and the watcher.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 16:01:23 +08:00

136 lines
3.3 KiB
Go

package auth
import (
"crypto/sha256"
"fmt"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
type Manager struct {
mu sync.RWMutex
secret []byte
accessTTL time.Duration
refreshTTL time.Duration
}
func NewManager(secret string, accessTTL, refreshTTL time.Duration) *Manager {
m := &Manager{}
m.Update(secret, accessTTL, refreshTTL)
return m
}
func (m *Manager) Update(secret string, accessTTL, refreshTTL time.Duration) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
m.secret = []byte(secret)
m.accessTTL = accessTTL
m.refreshTTL = refreshTTL
}
type TokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
AccessJTI string `json:"-"`
RefreshJTI string `json:"-"`
ExpiresAt int64 `json:"expires_at"`
}
func (m *Manager) Issue(userID, tenantID, primaryWorkspaceID int64, role string) (*TokenPair, error) {
secret, accessTTL, refreshTTL := m.snapshot()
now := time.Now()
accessJTI := uuid.New().String()
refreshJTI := uuid.New().String()
accessClaims := Claims{
UserID: userID,
TenantID: tenantID,
PrimaryWorkspaceID: primaryWorkspaceID,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
ID: accessJTI,
Subject: "access",
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(accessTTL)),
},
}
accessToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString(secret)
if err != nil {
return nil, fmt.Errorf("sign access token: %w", err)
}
refreshClaims := Claims{
UserID: userID,
TenantID: tenantID,
PrimaryWorkspaceID: primaryWorkspaceID,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
ID: refreshJTI,
Subject: "refresh",
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(refreshTTL)),
},
}
refreshToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString(secret)
if err != nil {
return nil, fmt.Errorf("sign refresh token: %w", err)
}
return &TokenPair{
AccessToken: accessToken,
RefreshToken: refreshToken,
AccessJTI: accessJTI,
RefreshJTI: refreshJTI,
ExpiresAt: now.Add(accessTTL).Unix(),
}, nil
}
func (m *Manager) Parse(tokenStr string) (*Claims, error) {
secret, _, _ := m.snapshot()
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return secret, nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, fmt.Errorf("invalid token claims")
}
return claims, nil
}
func (m *Manager) AccessTTL() time.Duration {
_, ttl, _ := m.snapshot()
return ttl
}
func (m *Manager) RefreshTTL() time.Duration {
_, _, ttl := m.snapshot()
return ttl
}
func (m *Manager) snapshot() ([]byte, time.Duration, time.Duration) {
if m == nil {
return nil, 0, 0
}
m.mu.RLock()
defer m.mu.RUnlock()
secret := append([]byte(nil), m.secret...)
return secret, m.accessTTL, m.refreshTTL
}
func HashToken(raw string) string {
h := sha256.Sum256([]byte(raw))
return fmt.Sprintf("%x", h)
}