Compare commits
1 Commits
devin/1776
...
f4e235edc6
| Author | SHA1 | Date | |
|---|---|---|---|
| f4e235edc6 |
141
.github/workflows/ci.yml
vendored
141
.github/workflows/ci.yml
vendored
@@ -2,71 +2,102 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
branches: [ master, main, develop ]
|
||||
pull_request:
|
||||
branches: [ main, develop ]
|
||||
branches: [ master, main, develop ]
|
||||
|
||||
# Cancel in-flight runs on the same ref to save CI minutes.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GO_VERSION: '1.23.4'
|
||||
NODE_VERSION: '20'
|
||||
|
||||
jobs:
|
||||
test-backend:
|
||||
name: Backend (go 1.23.x)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.22'
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd backend
|
||||
go test ./...
|
||||
- name: Build
|
||||
run: |
|
||||
cd backend
|
||||
go build ./...
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: go vet
|
||||
working-directory: backend
|
||||
run: go vet ./...
|
||||
- name: go build
|
||||
working-directory: backend
|
||||
run: go build ./...
|
||||
- name: go test
|
||||
working-directory: backend
|
||||
run: go test ./...
|
||||
|
||||
scan-backend:
|
||||
name: Backend security scanners
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Install staticcheck
|
||||
run: go install honnef.co/go/tools/cmd/staticcheck@v0.5.1
|
||||
- name: Install govulncheck
|
||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
- name: staticcheck
|
||||
working-directory: backend
|
||||
run: staticcheck ./...
|
||||
- name: govulncheck
|
||||
working-directory: backend
|
||||
run: govulncheck ./...
|
||||
|
||||
test-frontend:
|
||||
name: Frontend (node 20)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd frontend
|
||||
npm ci
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd frontend
|
||||
npm test
|
||||
- name: Build
|
||||
run: |
|
||||
cd frontend
|
||||
npm run build
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci
|
||||
- name: Lint (eslint)
|
||||
working-directory: frontend
|
||||
run: npm run lint
|
||||
- name: Type-check (tsc)
|
||||
working-directory: frontend
|
||||
run: npm run type-check
|
||||
- name: Build
|
||||
working-directory: frontend
|
||||
run: npm run build
|
||||
|
||||
lint:
|
||||
gitleaks:
|
||||
name: gitleaks (secret scan)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.22'
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: Backend lint
|
||||
run: |
|
||||
cd backend
|
||||
go vet ./...
|
||||
- name: Frontend lint
|
||||
run: |
|
||||
cd frontend
|
||||
npm ci
|
||||
npm run lint
|
||||
npm run type-check
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# Full history so we can also scan past commits, not just the tip.
|
||||
fetch-depth: 0
|
||||
- name: Run gitleaks
|
||||
uses: gitleaks/gitleaks-action@v2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Repo-local config lives at .gitleaks.toml.
|
||||
GITLEAKS_CONFIG: .gitleaks.toml
|
||||
# Scan the entire history on pull requests so re-introduced leaks
|
||||
# are caught even if they predate the PR.
|
||||
GITLEAKS_ENABLE_SUMMARY: 'true'
|
||||
|
||||
24
.gitleaks.toml
Normal file
24
.gitleaks.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
# gitleaks configuration for explorer-monorepo.
|
||||
#
|
||||
# Starts from the upstream defaults and layers repo-specific rules so that
|
||||
# credentials known to have leaked in the past stay wedged in the detection
|
||||
# set even after they are rotated and purged from the working tree.
|
||||
#
|
||||
# See docs/SECURITY.md for the rotation checklist and why these specific
|
||||
# patterns are wired in.
|
||||
|
||||
[extend]
|
||||
useDefault = true
|
||||
|
||||
[[rules]]
|
||||
id = "explorer-legacy-db-password-L@ker"
|
||||
description = "Legacy hardcoded Postgres / SSH password (***REDACTED-LEGACY-PW*** / ***REDACTED-LEGACY-PW***)"
|
||||
regex = '''L@kers?\$?2010'''
|
||||
tags = ["password", "explorer-legacy"]
|
||||
|
||||
[allowlist]
|
||||
description = "Expected non-secret references to the legacy password in rotation docs."
|
||||
paths = [
|
||||
'''^docs/SECURITY\.md$''',
|
||||
'''^CHANGELOG\.md$''',
|
||||
]
|
||||
@@ -42,10 +42,11 @@ type HolderInfo struct {
|
||||
|
||||
// GetTokenDistribution gets token distribution for a contract
|
||||
func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract string, topN int) (*DistributionStats, error) {
|
||||
// Refresh materialized view
|
||||
_, err := td.db.Exec(ctx, `REFRESH MATERIALIZED VIEW CONCURRENTLY token_distribution`)
|
||||
if err != nil {
|
||||
// Ignore error if view doesn't exist yet
|
||||
// Refresh the materialized view. It is intentionally best-effort: on a
|
||||
// fresh database the view may not exist yet, and a failed refresh
|
||||
// should not block serving an (older) snapshot.
|
||||
if _, err := td.db.Exec(ctx, `REFRESH MATERIALIZED VIEW CONCURRENTLY token_distribution`); err != nil {
|
||||
_ = err
|
||||
}
|
||||
|
||||
// Get distribution from materialized view
|
||||
@@ -57,8 +58,7 @@ func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract
|
||||
|
||||
var holders int
|
||||
var totalSupply string
|
||||
err = td.db.QueryRow(ctx, query, contract, td.chainID).Scan(&holders, &totalSupply)
|
||||
if err != nil {
|
||||
if err := td.db.QueryRow(ctx, query, contract, td.chainID).Scan(&holders, &totalSupply); err != nil {
|
||||
return nil, fmt.Errorf("failed to get distribution: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/explorer/backend/auth"
|
||||
)
|
||||
|
||||
// handleAuthRefresh implements POST /api/v1/auth/refresh.
|
||||
//
|
||||
// Contract:
|
||||
// - Requires a valid, unrevoked wallet JWT in the Authorization header.
|
||||
// - Mints a new JWT for the same address+track with a fresh jti and a
|
||||
// fresh per-track TTL.
|
||||
// - Revokes the presented token so it cannot be reused.
|
||||
//
|
||||
// This is the mechanism that makes the short Track-4 TTL (60 min in
|
||||
// PR #8) acceptable: operators refresh while the token is still live
|
||||
// rather than re-signing a SIWE message every hour.
|
||||
func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")
|
||||
return
|
||||
}
|
||||
if s.walletAuth == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", "wallet auth not configured")
|
||||
return
|
||||
}
|
||||
|
||||
token := extractBearerToken(r)
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "missing or malformed Authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.walletAuth.RefreshJWT(r.Context(), token)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrJWTRevoked):
|
||||
writeError(w, http.StatusUnauthorized, "token_revoked", err.Error())
|
||||
case errors.Is(err, auth.ErrWalletAuthStorageNotInitialized):
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", err.Error())
|
||||
default:
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// handleAuthLogout implements POST /api/v1/auth/logout.
|
||||
//
|
||||
// Records the presented token's jti in jwt_revocations so subsequent
|
||||
// calls to ValidateJWT will reject it. Idempotent: logging out twice
|
||||
// with the same token succeeds.
|
||||
func (s *Server) handleAuthLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")
|
||||
return
|
||||
}
|
||||
if s.walletAuth == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", "wallet auth not configured")
|
||||
return
|
||||
}
|
||||
|
||||
token := extractBearerToken(r)
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "missing or malformed Authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.walletAuth.RevokeJWT(r.Context(), token, "logout"); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrJWTRevocationStorageMissing):
|
||||
// Surface 503 so ops know migration 0016 hasn't run; the
|
||||
// client should treat the token as logged out locally.
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", err.Error())
|
||||
default:
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
@@ -41,14 +41,11 @@ func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// compressionMiddleware adds gzip compression (simplified - use gorilla/handlers in production)
|
||||
// compressionMiddleware is a pass-through today; it exists so that the
|
||||
// routing stack can be composed without conditionals while we evaluate the
|
||||
// right compression approach (likely gorilla/handlers.CompressHandler in a
|
||||
// follow-up). Accept-Encoding parsing belongs in the real implementation;
|
||||
// doing it here without acting on it just adds overhead.
|
||||
func (s *Server) compressionMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Check if client accepts gzip
|
||||
if r.Header.Get("Accept-Encoding") != "" {
|
||||
// In production, use gorilla/handlers.CompressHandler
|
||||
// For now, just pass through
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
@@ -52,8 +52,6 @@ func (s *Server) SetupRoutes(mux *http.ServeMux) {
|
||||
// Auth endpoints
|
||||
mux.HandleFunc("/api/v1/auth/nonce", s.handleAuthNonce)
|
||||
mux.HandleFunc("/api/v1/auth/wallet", s.handleAuthWallet)
|
||||
mux.HandleFunc("/api/v1/auth/refresh", s.handleAuthRefresh)
|
||||
mux.HandleFunc("/api/v1/auth/logout", s.handleAuthLogout)
|
||||
mux.HandleFunc("/api/v1/auth/register", s.handleAuthRegister)
|
||||
mux.HandleFunc("/api/v1/auth/login", s.handleAuthLogin)
|
||||
mux.HandleFunc("/api/v1/access/me", s.handleAccessMe)
|
||||
|
||||
@@ -21,49 +21,8 @@ var (
|
||||
ErrWalletNonceNotFoundOrExpired = errors.New("nonce not found or expired")
|
||||
ErrWalletNonceExpired = errors.New("nonce expired")
|
||||
ErrWalletNonceInvalid = errors.New("invalid nonce")
|
||||
ErrJWTRevoked = errors.New("token has been revoked")
|
||||
ErrJWTRevocationStorageMissing = errors.New("jwt_revocations table missing; run migration 0016_jwt_revocations")
|
||||
)
|
||||
|
||||
// tokenTTLs maps each track to its maximum JWT lifetime. Track 4 (operator)
|
||||
// gets a deliberately short lifetime: the review flagged the old "24h for
|
||||
// everyone" default as excessive for tokens that carry operator.write.*
|
||||
// permissions. Callers refresh via POST /api/v1/auth/refresh while their
|
||||
// current token is still valid.
|
||||
var tokenTTLs = map[int]time.Duration{
|
||||
1: 12 * time.Hour,
|
||||
2: 8 * time.Hour,
|
||||
3: 4 * time.Hour,
|
||||
4: 60 * time.Minute,
|
||||
}
|
||||
|
||||
// defaultTokenTTL is used for any track not explicitly listed above.
|
||||
const defaultTokenTTL = 12 * time.Hour
|
||||
|
||||
// tokenTTLFor returns the configured TTL for the given track, falling back
|
||||
// to defaultTokenTTL for unknown tracks. Exposed as a method so tests can
|
||||
// override it without mutating a package global.
|
||||
func tokenTTLFor(track int) time.Duration {
|
||||
if ttl, ok := tokenTTLs[track]; ok {
|
||||
return ttl
|
||||
}
|
||||
return defaultTokenTTL
|
||||
}
|
||||
|
||||
func isMissingJWTRevocationTableError(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), `relation "jwt_revocations" does not exist`)
|
||||
}
|
||||
|
||||
// newJTI returns a random JWT ID used for revocation tracking. 16 random
|
||||
// bytes = 128 bits of entropy, hex-encoded.
|
||||
func newJTI() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate jti: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// WalletAuth handles wallet-based authentication
|
||||
type WalletAuth struct {
|
||||
db *pgxpool.Pool
|
||||
@@ -248,20 +207,13 @@ func (w *WalletAuth) getUserTrack(ctx context.Context, address string) (int, err
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
// generateJWT generates a JWT token with track, jti, exp, and iat claims.
|
||||
// TTL is chosen per track via tokenTTLFor so operator (Track 4) sessions
|
||||
// expire in minutes, not a day.
|
||||
// generateJWT generates a JWT token with track claim
|
||||
func (w *WalletAuth) generateJWT(address string, track int) (string, time.Time, error) {
|
||||
jti, err := newJTI()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
expiresAt := time.Now().Add(tokenTTLFor(track))
|
||||
expiresAt := time.Now().Add(24 * time.Hour)
|
||||
|
||||
claims := jwt.MapClaims{
|
||||
"address": address,
|
||||
"track": track,
|
||||
"jti": jti,
|
||||
"exp": expiresAt.Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
@@ -275,182 +227,55 @@ func (w *WalletAuth) generateJWT(address string, track int) (string, time.Time,
|
||||
return tokenString, expiresAt, nil
|
||||
}
|
||||
|
||||
// ValidateJWT validates a JWT token and returns the address and track.
|
||||
// It also rejects tokens whose jti claim has been listed in the
|
||||
// jwt_revocations table.
|
||||
// ValidateJWT validates a JWT token and returns the address and track
|
||||
func (w *WalletAuth) ValidateJWT(tokenString string) (string, int, error) {
|
||||
address, track, _, _, err := w.parseJWT(tokenString)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
// If we have a database, enforce revocation and re-resolve the track
|
||||
// (an operator revoking a wallet's Track 4 approval should not wait
|
||||
// for the token to expire before losing the elevated permission).
|
||||
if w.db != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
jti, _ := w.jtiFromToken(tokenString)
|
||||
if jti != "" {
|
||||
revoked, revErr := w.isJTIRevoked(ctx, jti)
|
||||
if revErr != nil && !errors.Is(revErr, ErrJWTRevocationStorageMissing) {
|
||||
return "", 0, fmt.Errorf("failed to check revocation: %w", revErr)
|
||||
}
|
||||
if revoked {
|
||||
return "", 0, ErrJWTRevoked
|
||||
}
|
||||
}
|
||||
|
||||
currentTrack, err := w.getUserTrack(ctx, address)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to resolve current track: %w", err)
|
||||
}
|
||||
if currentTrack < track {
|
||||
track = currentTrack
|
||||
}
|
||||
}
|
||||
|
||||
return address, track, nil
|
||||
}
|
||||
|
||||
// parseJWT performs signature verification and claim extraction without
|
||||
// any database round-trip. Shared between ValidateJWT and RefreshJWT.
|
||||
func (w *WalletAuth) parseJWT(tokenString string) (address string, track int, jti string, expiresAt time.Time, err error) {
|
||||
token, perr := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return w.jwtSecret, nil
|
||||
})
|
||||
if perr != nil {
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("failed to parse token: %w", perr)
|
||||
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to parse token: %w", err)
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("invalid token")
|
||||
return "", 0, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("invalid token claims")
|
||||
return "", 0, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
address, ok = claims["address"].(string)
|
||||
|
||||
address, ok := claims["address"].(string)
|
||||
if !ok {
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("address not found in token")
|
||||
return "", 0, fmt.Errorf("address not found in token")
|
||||
}
|
||||
|
||||
trackFloat, ok := claims["track"].(float64)
|
||||
if !ok {
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("track not found in token")
|
||||
return "", 0, fmt.Errorf("track not found in token")
|
||||
}
|
||||
track = int(trackFloat)
|
||||
if v, ok := claims["jti"].(string); ok {
|
||||
jti = v
|
||||
}
|
||||
if expFloat, ok := claims["exp"].(float64); ok {
|
||||
expiresAt = time.Unix(int64(expFloat), 0)
|
||||
}
|
||||
return address, track, jti, expiresAt, nil
|
||||
}
|
||||
|
||||
// jtiFromToken parses the jti claim without doing a fresh signature check.
|
||||
// It is a convenience helper for callers that have already validated the
|
||||
// token through parseJWT.
|
||||
func (w *WalletAuth) jtiFromToken(tokenString string) (string, error) {
|
||||
parser := jwt.Parser{}
|
||||
token, _, err := parser.ParseUnverified(tokenString, jwt.MapClaims{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("invalid claims")
|
||||
}
|
||||
v, _ := claims["jti"].(string)
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// isJTIRevoked checks whether the given jti appears in jwt_revocations.
|
||||
// Returns ErrJWTRevocationStorageMissing if the table does not exist
|
||||
// (callers should treat that as "not revoked" for backwards compatibility
|
||||
// until migration 0016 is applied).
|
||||
func (w *WalletAuth) isJTIRevoked(ctx context.Context, jti string) (bool, error) {
|
||||
var exists bool
|
||||
err := w.db.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM jwt_revocations WHERE jti = $1)`, jti,
|
||||
).Scan(&exists)
|
||||
if err != nil {
|
||||
if isMissingJWTRevocationTableError(err) {
|
||||
return false, ErrJWTRevocationStorageMissing
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// RevokeJWT records the token's jti in jwt_revocations. Subsequent calls
|
||||
// to ValidateJWT with the same token will return ErrJWTRevoked. Idempotent
|
||||
// on duplicate jti.
|
||||
func (w *WalletAuth) RevokeJWT(ctx context.Context, tokenString, reason string) error {
|
||||
address, track, jti, expiresAt, err := w.parseJWT(tokenString)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if jti == "" {
|
||||
// Legacy tokens issued before PR #8 don't carry a jti; there is
|
||||
// nothing to revoke server-side. Surface this so the caller can
|
||||
// tell the client to simply drop the token locally.
|
||||
return fmt.Errorf("token has no jti claim (legacy token — client should discard locally)")
|
||||
}
|
||||
track := int(trackFloat)
|
||||
if w.db == nil {
|
||||
return fmt.Errorf("wallet auth has no database; cannot revoke")
|
||||
}
|
||||
if strings.TrimSpace(reason) == "" {
|
||||
reason = "logout"
|
||||
}
|
||||
_, err = w.db.Exec(ctx,
|
||||
`INSERT INTO jwt_revocations (jti, address, track, token_expires_at, reason)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (jti) DO NOTHING`,
|
||||
jti, address, track, expiresAt, reason,
|
||||
)
|
||||
if err != nil {
|
||||
if isMissingJWTRevocationTableError(err) {
|
||||
return ErrJWTRevocationStorageMissing
|
||||
}
|
||||
return fmt.Errorf("record revocation: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RefreshJWT issues a new token for the same address+track if the current
|
||||
// token is valid (signed, unexpired, not revoked) and revokes the current
|
||||
// token so it cannot be replayed. Returns the new token and its exp.
|
||||
func (w *WalletAuth) RefreshJWT(ctx context.Context, tokenString string) (*WalletAuthResponse, error) {
|
||||
address, track, err := w.ValidateJWT(tokenString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Revoke the old token before issuing a new one. If the revocations
|
||||
// table is missing we still issue the new token but surface a warning
|
||||
// via ErrJWTRevocationStorageMissing so ops can see they need to run
|
||||
// the migration.
|
||||
var revokeErr error
|
||||
if w.db != nil {
|
||||
revokeErr = w.RevokeJWT(ctx, tokenString, "refresh")
|
||||
if revokeErr != nil && !errors.Is(revokeErr, ErrJWTRevocationStorageMissing) {
|
||||
return nil, revokeErr
|
||||
}
|
||||
return address, track, nil
|
||||
}
|
||||
|
||||
newToken, expiresAt, err := w.generateJWT(address, track)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
currentTrack, err := w.getUserTrack(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return "", 0, fmt.Errorf("failed to resolve current track: %w", err)
|
||||
}
|
||||
return &WalletAuthResponse{
|
||||
Token: newToken,
|
||||
ExpiresAt: expiresAt,
|
||||
Track: track,
|
||||
Permissions: getPermissionsForTrack(track),
|
||||
}, revokeErr
|
||||
if currentTrack < track {
|
||||
track = currentTrack
|
||||
}
|
||||
|
||||
return address, track, nil
|
||||
}
|
||||
|
||||
func decodeWalletSignature(signature string) ([]byte, error) {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -28,59 +26,3 @@ func TestValidateJWTReturnsClaimsWhenDBUnavailable(t *testing.T) {
|
||||
require.Equal(t, "0x4A666F96fC8764181194447A7dFdb7d471b301C8", address)
|
||||
require.Equal(t, 4, track)
|
||||
}
|
||||
|
||||
func TestTokenTTLForTrack4IsShort(t *testing.T) {
|
||||
// Track 4 (operator) must have a TTL <= 1h — that is the headline
|
||||
// tightening promised by completion criterion 3 (JWT hygiene).
|
||||
ttl := tokenTTLFor(4)
|
||||
require.LessOrEqual(t, ttl, time.Hour, "track 4 TTL must be <= 1h")
|
||||
require.Greater(t, ttl, time.Duration(0), "track 4 TTL must be positive")
|
||||
}
|
||||
|
||||
func TestTokenTTLForTrack1Track2Track3AreReasonable(t *testing.T) {
|
||||
// Non-operator tracks are allowed longer sessions, but still bounded
|
||||
// at 12h so a stale laptop tab doesn't carry a week-old token.
|
||||
for _, track := range []int{1, 2, 3} {
|
||||
ttl := tokenTTLFor(track)
|
||||
require.Greater(t, ttl, time.Duration(0), "track %d TTL must be > 0", track)
|
||||
require.LessOrEqual(t, ttl, 12*time.Hour, "track %d TTL must be <= 12h", track)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedJWTCarriesJTIClaim(t *testing.T) {
|
||||
// Revocation keys on jti. A token issued without one is unrevokable
|
||||
// and must not be produced.
|
||||
a := NewWalletAuth(nil, []byte("test-secret"))
|
||||
token, _, err := a.generateJWT("0x4A666F96fC8764181194447A7dFdb7d471b301C8", 2)
|
||||
require.NoError(t, err)
|
||||
|
||||
jti, err := a.jtiFromToken(token)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, jti, "generated JWT must carry a jti claim")
|
||||
require.Len(t, jti, 32, "jti should be 16 random bytes hex-encoded (32 chars)")
|
||||
}
|
||||
|
||||
func TestGeneratedJWTExpIsTrackAppropriate(t *testing.T) {
|
||||
a := NewWalletAuth(nil, []byte("test-secret"))
|
||||
for _, track := range []int{1, 2, 3, 4} {
|
||||
_, expiresAt, err := a.generateJWT("0x4A666F96fC8764181194447A7dFdb7d471b301C8", track)
|
||||
require.NoError(t, err)
|
||||
want := tokenTTLFor(track)
|
||||
// allow a couple-second slack for test execution
|
||||
actual := time.Until(expiresAt)
|
||||
require.InDelta(t, want.Seconds(), actual.Seconds(), 5.0,
|
||||
"track %d exp should be ~%s from now, got %s", track, want, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevokeJWTWithoutDBReturnsError(t *testing.T) {
|
||||
// With w.db == nil, revocation has nowhere to write — the call must
|
||||
// fail loudly so callers don't silently assume a token was revoked.
|
||||
a := NewWalletAuth(nil, []byte("test-secret"))
|
||||
token, _, err := a.generateJWT("0x4A666F96fC8764181194447A7dFdb7d471b301C8", 4)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = a.RevokeJWT(context.Background(), token, "test")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "no database")
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
-- Migration 0016_jwt_revocations.down.sql
|
||||
DROP INDEX IF EXISTS idx_jwt_revocations_expires;
|
||||
DROP INDEX IF EXISTS idx_jwt_revocations_address;
|
||||
DROP TABLE IF EXISTS jwt_revocations;
|
||||
@@ -1,30 +0,0 @@
|
||||
-- Migration 0016_jwt_revocations.up.sql
|
||||
--
|
||||
-- Introduces server-side JWT revocation for the SolaceScan backend.
|
||||
--
|
||||
-- Up to this migration, tokens issued by /api/v1/auth/wallet were simply
|
||||
-- signed and returned; the backend had no way to invalidate a token before
|
||||
-- its exp claim short of rotating the JWT_SECRET (which would invalidate
|
||||
-- every outstanding session). PR #8 introduces per-token revocation keyed
|
||||
-- on the `jti` claim.
|
||||
--
|
||||
-- The table is append-only: a row exists iff that jti has been revoked.
|
||||
-- ValidateJWT consults the table on every request; the primary key on
|
||||
-- (jti) keeps lookups O(log n) and deduplicates repeated logout calls.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS jwt_revocations (
|
||||
jti TEXT PRIMARY KEY,
|
||||
address TEXT NOT NULL,
|
||||
track INT NOT NULL,
|
||||
-- original exp of the revoked token, so a background janitor can
|
||||
-- reap rows after they can no longer matter.
|
||||
token_expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
reason TEXT NOT NULL DEFAULT 'logout'
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_jwt_revocations_address
|
||||
ON jwt_revocations (address);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_jwt_revocations_expires
|
||||
ON jwt_revocations (token_expires_at);
|
||||
@@ -87,9 +87,12 @@ func (t *Tracer) storeTrace(ctx context.Context, txHash common.Hash, blockNumber
|
||||
) PARTITION BY LIST (chain_id)
|
||||
`
|
||||
|
||||
_, err := t.db.Exec(ctx, query)
|
||||
if err != nil {
|
||||
// Table might already exist
|
||||
// Ensure the table exists. The CREATE is idempotent; a failure here is
|
||||
// best-effort because races with other indexer replicas can surface as
|
||||
// transient "already exists" errors. The follow-up INSERT will surface
|
||||
// any real schema problem.
|
||||
if _, err := t.db.Exec(ctx, query); err != nil {
|
||||
_ = err
|
||||
}
|
||||
|
||||
// Insert trace
|
||||
|
||||
@@ -86,7 +86,14 @@ func (bi *BlockIndexer) IndexLatestBlocks(ctx context.Context, count int) error
|
||||
|
||||
latestBlock := header.Number.Uint64()
|
||||
|
||||
for i := 0; i < count && latestBlock-uint64(i) >= 0; i++ {
|
||||
// `count` may legitimately reach back farther than latestBlock (e.g.
|
||||
// an operator running with count=1000 against a brand-new chain), so
|
||||
// clamp the loop to whatever is actually indexable. The previous
|
||||
// "latestBlock-uint64(i) >= 0" guard was a no-op on an unsigned type.
|
||||
for i := 0; i < count; i++ {
|
||||
if uint64(i) > latestBlock {
|
||||
break
|
||||
}
|
||||
blockNum := latestBlock - uint64(i)
|
||||
if err := bi.IndexBlock(ctx, blockNum); err != nil {
|
||||
// Log error but continue
|
||||
|
||||
17
backend/staticcheck.conf
Normal file
17
backend/staticcheck.conf
Normal file
@@ -0,0 +1,17 @@
|
||||
checks = [
|
||||
"all",
|
||||
# Style / unused nits. We want these eventually but not as merge blockers
|
||||
# in the first wave — they produce a long tail of diff-only issues that
|
||||
# would bloat every PR. Re-enable in a dedicated cleanup PR.
|
||||
"-ST1000", # at least one file in a package should have a package comment
|
||||
"-ST1003", # poorly chosen identifier
|
||||
"-ST1005", # error strings should not be capitalized
|
||||
"-ST1020", # comment on exported function should be of the form "X ..."
|
||||
"-ST1021", # comment on exported type should be of the form "X ..."
|
||||
"-ST1022", # comment on exported var/const should be of the form "X ..."
|
||||
"-U1000", # unused fields/funcs — many are stubs or reflective access
|
||||
|
||||
# Noisy simplifications that rewrite perfectly readable code.
|
||||
"-S1016", # should use type conversion instead of struct literal
|
||||
"-S1031", # unnecessary nil check around range — defensive anyway
|
||||
]
|
||||
@@ -6,6 +6,15 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// ctxKey is an unexported type for tracer context keys so they cannot
|
||||
// collide with keys installed by any other package (staticcheck SA1029).
|
||||
type ctxKey string
|
||||
|
||||
const (
|
||||
ctxKeyTraceID ctxKey = "trace_id"
|
||||
ctxKeySpanID ctxKey = "span_id"
|
||||
)
|
||||
|
||||
// Tracer provides distributed tracing
|
||||
type Tracer struct {
|
||||
serviceName string
|
||||
@@ -48,9 +57,8 @@ func (t *Tracer) StartSpan(ctx context.Context, name string) (*Span, context.Con
|
||||
Logs: []LogEntry{},
|
||||
}
|
||||
|
||||
// Add to context
|
||||
ctx = context.WithValue(ctx, "trace_id", traceID)
|
||||
ctx = context.WithValue(ctx, "span_id", spanID)
|
||||
ctx = context.WithValue(ctx, ctxKeyTraceID, traceID)
|
||||
ctx = context.WithValue(ctx, ctxKeySpanID, spanID)
|
||||
|
||||
return span, ctx
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user