UserRateLimiter had been created in initMiddlewares() + stored on
config.UserRateLimiter but never mounted — dead wiring. Per-user rate
limiting was silently not running anywhere.
Applying it as a separate `v1.Use(...)` would fire *before* the JWT
auth middleware sets `user_id`, so the limiter would always skip. The
alternative (add it after every `RequireAuth()` in ~15 route files)
bloats every routes_*.go and invites forgetting.
Solution: centralise it on AuthMiddleware. After a successful
`authenticate()` in `RequireAuth`, invoke the limiter's handler. When
the limiter is nil (tests, early boot), it's a no-op.
Changes:
- internal/middleware/auth.go
* new field AuthMiddleware.userRateLimiter *UserRateLimiter
* new method AuthMiddleware.SetUserRateLimiter(url)
* RequireAuth() flow: authenticate → presence → user rate limit
→ c.Next(). Abort surfaces as early-return without c.Next().
- internal/config/middlewares_init.go
* call c.AuthMiddleware.SetUserRateLimiter(c.UserRateLimiter)
right after AuthMiddleware construction.
Behavior:
- Authenticated requests: per-user limit enforced via Redis, with
X-RateLimit-Limit / Remaining / Reset headers, 429 + retry-after
on overflow. Defaults: 1000 req/min, burst 100 (env-tunable via
USER_RATE_LIMIT_PER_MINUTE / USER_RATE_LIMIT_BURST).
- Unauthenticated requests: RequireAuth already rejected them → the
limiter never runs, no behavior change there.
Tests: `go test ./internal/middleware/ -short` green (33s).
`go build ./...` + `go vet ./internal/middleware/` clean.
Refs: AUDIT_REPORT.md §4.3 "UserRateLimiter configuré non wiré"
+ §9 priority #11.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Surfaced by the v1.0.5 browser smoke test. ResponseCache captures the
entire body into a bytes.Buffer, JSON-serializes it (escaping non-UTF-8
bytes), and replays via c.Data for subsequent hits. For audio/video
streams this has two failure modes:
1. Range headers are never honored — the cache replays the *full body*
on every request, strips the Accept-Ranges header, and leaves the
<audio> element unable to seek. The smoke test caught this when a
`Range: bytes=100-299` request got back 200 OK with 48944 bytes
instead of 206 Partial Content with 200 bytes.
2. Non-UTF-8 bytes get escaped through the JSON round-trip (`\uFFFD`
substitution etc.), corrupting the MP3 payload so even full plays
can fail mid-stream.
Minimum-invasive fix: skip the cache entirely for any path containing
`/stream`, `/download`, or `/hls/`, and for any request that carries a
`Range` header (belt-and-suspenders for any future media endpoint). All
other anonymous GETs keep their 5-minute TTL.
Verified live: `GET /api/v1/tracks/:id/stream` returns
- full: 200 OK, Accept-Ranges: bytes, Content-Length matches disk,
body MD5 matches source file byte-for-byte
- range: 206 Partial Content, Content-Range: bytes 100-299/48944,
exactly 200 bytes
Browser <audio> plays end-to-end with currentTime progressing from 0 to
duration and seek to 1.5s succeeding (readyState=4, no error).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The maintenance toggle lived in a package-level `bool` inside
`middleware/maintenance.go`. Flipping it via `PUT /admin/maintenance`
only updated the pod handling that request — the other N-1 pods stayed
open for traffic. In practice this meant deploys-in-progress or
incident playbooks silently failed to put the fleet into maintenance.
New storage:
* Migration `976_platform_settings.sql` adds a typed key/value table
(`value_bool` / `value_text` to avoid string parsing in the hot
path) and seeds `maintenance_mode=false`. Idempotent on re-run.
* `middleware/maintenance.go` rewritten around a `maintenanceState`
with a 10s TTL cache. `InitMaintenanceMode(db, logger)` primes the
cache at boot; `MaintenanceModeEnabled()` refreshes lazily when the
next request lands after the TTL. Startup `MAINTENANCE_MODE` env is
still honoured for fresh pods.
* `router.go` calls `InitMaintenanceMode` before applying the
`MaintenanceGin()` middleware so the first request sees DB truth.
* `PUT /api/v1/admin/maintenance` in `routes_core.go` now does an
`INSERT ... ON CONFLICT DO UPDATE` on the table *before* the
in-memory setter, so the flip survives restarts and propagates to
every pod within ~10s (one TTL window).
Tests: `TestMaintenanceGin_DBBacked` flips the DB row, waits past a
shrunk-for-test TTL, and asserts the cache picked up the change. All
four pre-existing tests preserved (`Disabled`, `Enabled_Returns503`,
`HealthExempt`, `AdminExempt`).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
backend-ci.yml's `test -z "$(gofmt -l .)"` strict gate (added in
13c21ac11) failed on a backlog of unformatted files. None of the
85 files in this commit had been edited since the gate was added
because no push touched veza-backend-api/** in between, so the
gate never fired until today's CI fixes triggered it.
The diff is exclusively whitespace alignment in struct literals
and trailing-space comments. `go build ./...` and the full test
suite (with VEZA_SKIP_INTEGRATION=1 -short) pass identically.
- API key rate limiting middleware (1000 reads/h, 200 writes/h par clé)
— tracking séparé read/write, par API key ID (pas par IP)
— headers X-RateLimit-Limit/Remaining/Reset sur chaque réponse
- API key scope enforcement middleware (read → GET, write → POST/PUT/DELETE)
— admin scope permet tout, CSRF skip pour API key auth
- OpenAPI spec: ajout securityDefinition ApiKeyAuth (X-API-Key header)
- Swagger annotations: ajout ApiKeyAuth dans cmd/api/main.go
- Wiring dans router.go: middlewares appliqués sur tout le groupe /api/v1
- Tests: 10 tests (5 rate limiter + 5 scope enforcement), tous PASS
Backend existant déjà en place (pré-v0.12.8):
- Swagger UI (gin-swagger + frontend SwaggerUIDoc component)
- API key CRUD (create/list/delete + X-API-Key auth dans AuthMiddleware)
- Developer Dashboard frontend (API keys, webhooks, playground)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
MEDIUM-002: Remove manual X-Forwarded-For parsing in metrics_protection.go,
use c.ClientIP() only (respects SetTrustedProxies)
MEDIUM-003: Pin ClamAV Docker image to 1.4 across all compose files
MEDIUM-004: Add clampLimit(100) to 15+ handlers that parsed limit directly
MEDIUM-006: Remove unsafe-eval from CSP script-src on Swagger routes
MEDIUM-007: Pin all GitHub Actions to SHA in 11 workflow files
MEDIUM-008: Replace rabbitmq:3-management-alpine with rabbitmq:3-alpine in prod
MEDIUM-009: Add trial-already-used check in subscription service
MEDIUM-010: Add 60s periodic token re-validation to WebSocket connections
MEDIUM-011: Mask email in auth handler logs with maskEmail() helper
MEDIUM-012: Add k-anonymity threshold (k=5) to playback analytics stats
LOW-001: Align frontend password policy to 12 chars (matching backend)
LOW-003: Replace deprecated dotenv with dotenvy crate in Rust stream server
LOW-004: Enable xpack.security in Elasticsearch dev/local compose files
LOW-005: Accept context.Context in CleanupExpiredSessions instead of Background()
LOW-002: Noted — Hyperswitch version update deferred (requires payment integration tests)
29/30 findings remediated. 1 noted (LOW-002).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- ResponseCache: Redis-backed HTTP response caching for public GET endpoints
with configurable TTLs per endpoint prefix (tracks 15m, search 5m, etc.)
- CacheHeaders: CDN-optimized Cache-Control headers per asset type
(static 1yr immutable, audio 7d, HLS 60s, images 30d, API no-cache)
- Integrated both middlewares into the router middleware stack
- Unit tests for cache key generation, header rules, and config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- ORDER BY dynamiques : whitelist explicite, fallback created_at DESC
- Login/register soumis au rate limiter global
- VERSION sync + check CI
- Nettoyage références veza-chat-server
- Go 1.24 partout (Dockerfile, workflows)
- TODO/FIXME/HACK convertis en issues ou résolus
INT-03: Tests for health endpoint, auth flow, track upload auth,
webhook HTTPS-only, and rate limit headers. Build-tagged
'integration' to avoid running in regular test suite.
CLN-03: router.go, track/service.go, upload_validator.go, cors.go,
playlist_handler.go, and mfa.go now use zap.L() or local logger
for structured logging instead of fmt.Printf.
INF-01: RedisRateLimiter uses atomic Lua script (INCR+EXPIRE) for
distributed rate limiting. Falls back to in-memory SimpleRateLimiter
when Redis is unavailable. Same X-RateLimit-* headers and 429 format.
Replace NODE_ENV/APP_ENV bypass with DISABLE_RATE_LIMIT_FOR_TESTS=true.
Only test runners should set this. Prevents rate limiting bypass when
APP_ENV=development is mistakenly used in production.
Phase 1 audit - P1.6
- Explicitly check APP_ENV instead of relying on isProduction() helper
- Default to development mode (allow localhost origins) if APP_ENV is not set
- Ensures Swagger UI can be embedded from localhost:5173 in development
- Fixes issue where frame-ancestors was still 'self' even in development
- Update frame-ancestors CSP to include common localhost origins in development
- Allows embedding from localhost:5173 (Vite dev server) and localhost:3000
- Production remains restricted to same-origin only
- Fixes CSP violation when frontend (localhost:5173) embeds backend Swagger UI (localhost:8080)
Backend changes (Action 5.1.1.1):
- Set access_token cookie in Login, Register, and Refresh handlers
- Cookie uses same configuration as refresh_token (httpOnly, Secure, SameSite)
- Expiry matches AccessTokenTTL (5 minutes)
- Update logout handler to clear access_token cookie
Backend middleware (Action 5.1.1.1):
- Update auth middleware to read access token from cookie first
- Fallback to Authorization header for backward compatibility
- Update OptionalAuth with same cookie-first logic
Frontend changes (Actions 5.1.1.2 & 5.1.1.3):
- Remove localStorage token storage from TokenStorage service
- TokenStorage now returns null for getAccessToken/getRefreshToken (httpOnly cookies not accessible)
- Remove Authorization header logic from API client
- Remove token expiration checks (can't check httpOnly cookies from JS)
- Update AuthContext to remove localStorage usage
- Update tokenRefresh to work without reading tokens from JS
- Simplify refresh logic: periodic refresh every 4 minutes (no expiration checks)
Security improvements:
- Access tokens no longer exposed to XSS attacks (httpOnly cookies)
- Tokens automatically sent with requests via withCredentials: true
- Backend reads tokens from cookies, not Authorization headers
- All users will need to re-login after deployment (breaking change)
Breaking change: All users must re-login after deployment
- Conflit SQLx résolu (alignement sur version 0.7)
- build.rs configurés pour protoc dans chat/stream servers
- API Prometheus migrée vers HistogramOpts
- Traits Display/Debug corrigés (String au lieu de &dyn Display)
- API TOTP corrigée (totp-rs 5.4 avec Secret::Encoded)
- Layers tracing-subscriber corrigés (types conditionnels)
- VezaError/VezaResult exportés dans lib.rs
- TransactionProvider simplifié (retour void au lieu de Box<dyn>)
- VezaConfig contraint Serialize pour to_json()
Files: veza-common/Cargo.toml, veza-common/src/*.rs, veza-chat-server/Cargo.toml, veza-chat-server/build.rs, veza-stream-server/Cargo.toml, veza-stream-server/build.rs, VEZA_ROADMAP.json
Hours: 8 estimated, 3 actual