test(security): A-3 pre-fix tests for auth middleware coverage bugs

Pre-fix test suite documenting 8 auth middleware bugs found during
the A-3 recon audit. Tests are written to FAIL where they assert
correct post-fix behavior, and PASS where they document current
buggy behavior. No bugs are fixed in this commit.

Tests added:
- F-A3-11 CRITICAL: WebAuthMiddleware leaks JWT secret to stdout
  (3 tests: secret in output, emoji in output, ETHOS format)
- F-A3-7 CRITICAL: Config download requires no auth (2 tests)
- F-A3-6 HIGH: Update package download requires no auth (2 tests)
- F-A3-10 HIGH: Scheduler stats accepts agent JWT (2 tests)
- F-A3-12 MEDIUM: Cross-type JWT token confusion (2 tests)
- F-A3-2 MEDIUM: /auth/verify dead endpoint (2 tests)
- F-A3-13 LOW: RequireAdmin middleware missing (1 test + 1 build-tagged)
- F-A3-9 MEDIUM: Agent self-unregister no rate limit (2 tests)

Current state: 10 FAIL, 7 PASS, 1 SKIP (build-tagged), 1 unchanged
See docs/A3_PreFix_Tests.md for full inventory.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-28 21:54:48 -04:00
parent f97d4845af
commit ee246771dc
10 changed files with 1363 additions and 0 deletions

View File

@@ -0,0 +1,88 @@
package handlers_test
// agent_unregister_test.go — Pre-fix tests for missing rate limit on agent unregister.
//
// BUG F-A3-9 MEDIUM: DELETE /api/v1/agents/:id has AuthMiddleware and
// MachineBindingMiddleware but no rate limiter. A compromised agent token
// could unregister agents in a tight loop. Other agent routes in the same
// group have rate limiting (e.g., POST /:id/updates uses agent_reports limit).
//
// These tests inspect the route registration pattern to document the
// absence of rate limiting. They are documentation tests — no HTTP calls.
//
// Run: cd aggregator-server && go test ./internal/api/handlers/... -v -run TestAgentSelfUnregister
import (
"strings"
"testing"
)
// routeRegistration captures the middleware chain description for a route.
// This is a simplified representation — actual inspection would require
// reading main.go or using reflection on the Gin router.
// The route registration for DELETE /api/v1/agents/:id is:
// agents.DELETE("/:id", agentHandler.UnregisterAgent)
// in the agents group which has:
// agents.Use(middleware.AuthMiddleware())
// agents.Use(middleware.MachineBindingMiddleware(...))
// but NO rate limiter on the DELETE route itself.
// By contrast, other routes in the same group have explicit rate limiting:
// agents.POST("/:id/updates", rateLimiter.RateLimit("agent_reports", ...), ...)
// agents.POST("/:id/metrics", rateLimiter.RateLimit("agent_reports", ...), ...)
// ---------------------------------------------------------------------------
// Test 7.1 — Documents that agent self-unregister has no rate limit
//
// Category: PASS-NOW (documents the current state)
//
// BUG F-A3-9: DELETE /api/v1/agents/:id has no rate limit.
// A compromised agent token could unregister agents in a tight loop.
// After fix: add rate limiter matching other agent routes.
// ---------------------------------------------------------------------------
func TestAgentSelfUnregisterHasNoRateLimit(t *testing.T) {
// This is the exact route registration from main.go:479
// agents.DELETE("/:id", agentHandler.UnregisterAgent)
//
// Compare with rated-limited routes in the same group:
// agents.POST("/:id/updates", rateLimiter.RateLimit("agent_reports", ...), updateHandler.ReportUpdates)
// agents.POST("/:id/metrics", rateLimiter.RateLimit("agent_reports", ...), metricsHandler.ReportMetrics)
routeRegistration := `agents.DELETE("/:id", agentHandler.UnregisterAgent)`
// Document: no rateLimiter.RateLimit in the registration
if strings.Contains(routeRegistration, "rateLimiter.RateLimit") {
t.Error("[ERROR] [server] [agents] BUG F-A3-9 already fixed: " +
"rate limiter found on DELETE /:id route. Update this test.")
}
t.Log("[INFO] [server] [agents] BUG F-A3-9 confirmed: DELETE /:id has no rate limiter")
t.Log("[INFO] [server] [agents] middleware chain: AuthMiddleware + MachineBindingMiddleware (no rate limit)")
t.Log("[INFO] [server] [agents] after fix: add rateLimiter.RateLimit to DELETE /:id")
}
// ---------------------------------------------------------------------------
// Test 7.2 — Agent self-unregister SHOULD have rate limit
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// Documents the expected state: the DELETE route should include
// a rate limiter in its middleware chain.
// ---------------------------------------------------------------------------
func TestAgentSelfUnregisterShouldHaveRateLimit(t *testing.T) {
// This is the expected FIXED route registration:
// agents.DELETE("/:id", rateLimiter.RateLimit("agent_operations", ...), agentHandler.UnregisterAgent)
currentRegistration := `agents.DELETE("/:id", agentHandler.UnregisterAgent)`
if !strings.Contains(currentRegistration, "rateLimiter.RateLimit") {
t.Errorf("[ERROR] [server] [agents] DELETE /:id is missing rate limiter.\n"+
"BUG F-A3-9: agent self-unregister has no rate limit.\n"+
"Current: %s\n"+
"Expected: agents.DELETE(\"/:id\", rateLimiter.RateLimit(...), agentHandler.UnregisterAgent)\n"+
"After fix: add rateLimiter.RateLimit to the route.", currentRegistration)
}
}

View File

@@ -0,0 +1,211 @@
package handlers_test
// auth_middleware_leak_test.go — Pre-fix tests for JWT secret leak in WebAuthMiddleware.
//
// BUG F-A3-11 CRITICAL: WebAuthMiddleware (auth.go:128) prints the JWT signing
// secret to stdout on every validation failure:
// fmt.Printf("🔓 JWT validation failed: %v (secret: %s)\n", err, h.jwtSecret)
//
// Violations:
// 1. Secret in log output — any log collector captures the signing key
// 2. Emoji in log output — violates ETHOS #1 log format requirement
// 3. Log format wrong — must be [TAG] [system] [component] per ETHOS #1
//
// Tests 1.1-1.3 currently FAIL (bug present). They will PASS after the fix.
//
// Run: cd aggregator-server && go test ./internal/api/handlers/... -v -run TestWebAuthMiddleware
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/Fimeg/RedFlag/aggregator-server/internal/api/handlers"
"github.com/gin-gonic/gin"
)
func init() {
gin.SetMode(gin.TestMode)
}
// ---------------------------------------------------------------------------
// Test 1.1 — WebAuthMiddleware does NOT log the JWT secret
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-11: auth.go:128 prints h.jwtSecret directly to stdout.
// Any log collector (Docker logs, journald, CloudWatch) captures this secret.
// An attacker with log access can forge arbitrary admin tokens.
// ---------------------------------------------------------------------------
func TestWebAuthMiddlewareDoesNotLogSecret(t *testing.T) {
testSecret := "test-secret-12345"
authHandler := handlers.NewAuthHandler(testSecret, nil)
router := gin.New()
router.Use(authHandler.WebAuthMiddleware())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
// Capture stdout during middleware execution
oldStdout := os.Stdout
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("failed to create pipe: %v", err)
}
os.Stdout = w
// Send request with an invalid JWT (valid format, wrong signature)
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSJ9.invalidsig")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
captured := buf.String()
// The secret MUST NOT appear in stdout
if strings.Contains(captured, testSecret) {
t.Errorf("[ERROR] [server] [auth] WebAuthMiddleware leaked JWT secret to stdout.\n"+
"BUG F-A3-11: auth.go:128 prints h.jwtSecret on validation failure.\n"+
"Captured output contains: %q\n"+
"After fix: remove secret from log output entirely.", testSecret)
}
// Confirm the request was still rejected
if rec.Code != http.StatusUnauthorized {
t.Errorf("[ERROR] [server] [auth] expected 401 for invalid token, got %d", rec.Code)
}
}
// ---------------------------------------------------------------------------
// Test 1.2 — WebAuthMiddleware log output has no emoji characters
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-11: auth.go:128 uses "🔓" (U+1F513) in log output.
// ETHOS #1 requires [TAG] [system] [component] format, no emojis.
// ---------------------------------------------------------------------------
func TestWebAuthMiddlewareLogFormatHasNoEmoji(t *testing.T) {
authHandler := handlers.NewAuthHandler("emoji-test-secret", nil)
router := gin.New()
router.Use(authHandler.WebAuthMiddleware())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("Authorization", "Bearer invalid-token")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
captured := buf.String()
// Check for emoji characters (Unicode symbols above U+1F300)
hasEmoji := false
for _, ch := range captured {
if ch >= 0x1F300 || (ch >= 0x2600 && ch <= 0x27BF) {
hasEmoji = true
t.Errorf("[ERROR] [server] [auth] emoji character found in log output: U+%04X\n"+
"BUG F-A3-11: auth.go:128 uses emoji in log. ETHOS #1 violation.\n"+
"After fix: use [WARNING] [server] [auth] format.", ch)
break
}
}
// Also check for the specific emoji used
if strings.Contains(captured, "\U0001F513") {
if !hasEmoji {
t.Errorf("[ERROR] [server] [auth] lock emoji U+1F513 found in log output")
}
}
// Check that the word "secret" does not appear
if strings.Contains(strings.ToLower(captured), "secret") {
t.Errorf("[ERROR] [server] [auth] word 'secret' found in log output")
}
_ = rec // ensure request completed
}
// ---------------------------------------------------------------------------
// Test 1.3 — WebAuthMiddleware log format is ETHOS-compliant
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-11: Log format must be [TAG] [system] [component] message.
// Current output: "🔓 JWT validation failed: ... (secret: ...)"
// Expected: "[WARNING] [server] [auth] jwt_validation_failed error=..."
// ---------------------------------------------------------------------------
func TestWebAuthMiddlewareLogFormatCompliant(t *testing.T) {
authHandler := handlers.NewAuthHandler("format-test-secret", nil)
router := gin.New()
router.Use(authHandler.WebAuthMiddleware())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("Authorization", "Bearer invalid-jwt-token")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
captured := buf.String()
if captured == "" {
// No output is acceptable (middleware can log to logger instead of stdout)
t.Log("[INFO] [server] [auth] no stdout output produced (acceptable)")
return
}
// If output exists, it must follow ETHOS format
lines := strings.Split(strings.TrimSpace(captured), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Must start with [TAG] pattern
if !strings.HasPrefix(line, "[") {
t.Errorf("[ERROR] [server] [auth] log line does not follow [TAG] format: %q\n"+
"BUG F-A3-11: expected [WARNING] [server] [auth] or [ERROR] [server] [auth]", line)
}
// Must not contain the secret
if strings.Contains(line, "format-test-secret") {
t.Errorf("[ERROR] [server] [auth] log line contains JWT secret")
}
}
_ = rec
}

View File

@@ -0,0 +1,135 @@
package handlers_test
// auth_verify_test.go — Pre-fix tests for the dead /auth/verify endpoint.
//
// BUG F-A3-2 MEDIUM: GET /api/v1/auth/verify has no middleware applied.
// The handler calls c.Get("user_id") which is never set because no
// middleware runs to parse the JWT. The endpoint always returns 401
// {"valid": false} regardless of the token provided.
//
// Run: cd aggregator-server && go test ./internal/api/handlers/... -v -run TestAuthVerify
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Fimeg/RedFlag/aggregator-server/internal/api/handlers"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// ---------------------------------------------------------------------------
// Test 5.1 — /auth/verify always returns 401 without middleware
//
// Category: PASS-NOW (documents the broken state)
//
// BUG F-A3-2: The handler calls c.Get("user_id") but no middleware
// sets this context value. The endpoint always returns 401 {"valid": false}
// regardless of the token provided. This is a dead endpoint.
// ---------------------------------------------------------------------------
func TestAuthVerifyAlwaysReturns401WithoutMiddleware(t *testing.T) {
testSecret := "verify-test-secret"
authHandler := handlers.NewAuthHandler(testSecret, nil)
// Mirror current production state: NO middleware on this route
router := gin.New()
router.GET("/api/v1/auth/verify", authHandler.VerifyToken)
// Create a valid web JWT
claims := handlers.UserClaims{
UserID: "1",
Username: "admin",
Role: "admin",
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(testSecret))
if err != nil {
t.Fatalf("failed to sign JWT: %v", err)
}
// Send with valid JWT — should still fail because no middleware parses it
req := httptest.NewRequest("GET", "/api/v1/auth/verify", nil)
req.Header.Set("Authorization", "Bearer "+tokenString)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// Documents the bug: endpoint always returns 401
if rec.Code != http.StatusUnauthorized {
t.Errorf("[ERROR] [server] [auth] expected 401 from dead verify endpoint, got %d", rec.Code)
}
// Check the response body says valid: false
var body map[string]interface{}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err == nil {
if valid, ok := body["valid"].(bool); ok && valid {
t.Error("[ERROR] [server] [auth] verify endpoint returned valid=true without middleware (unexpected)")
}
}
t.Log("[INFO] [server] [auth] BUG F-A3-2 confirmed: /auth/verify always returns 401 without middleware")
}
// ---------------------------------------------------------------------------
// Test 5.2 — /auth/verify works correctly WITH middleware
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-2: With WebAuthMiddleware applied, the verify endpoint should
// return 200 for a valid token. Fix: add WebAuthMiddleware to the route
// in main.go.
// ---------------------------------------------------------------------------
func TestAuthVerifyWorksWithMiddleware(t *testing.T) {
testSecret := "verify-test-secret-2"
authHandler := handlers.NewAuthHandler(testSecret, nil)
// Correct configuration: WITH WebAuthMiddleware
router := gin.New()
router.Use(authHandler.WebAuthMiddleware())
router.GET("/api/v1/auth/verify", authHandler.VerifyToken)
// Create a valid web JWT
claims := handlers.UserClaims{
UserID: "1",
Username: "admin",
Role: "admin",
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(testSecret))
if err != nil {
t.Fatalf("failed to sign JWT: %v", err)
}
req := httptest.NewRequest("GET", "/api/v1/auth/verify", nil)
req.Header.Set("Authorization", "Bearer "+tokenString)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// With middleware: should return 200 with valid=true
if rec.Code != http.StatusOK {
t.Errorf("[ERROR] [server] [auth] verify with middleware returned %d, expected 200.\n"+
"BUG F-A3-2: /auth/verify is dead because main.go doesn't apply WebAuthMiddleware.\n"+
"This test shows the endpoint WORKS when middleware is correctly applied.\n"+
"After fix: add WebAuthMiddleware to the route in main.go.", rec.Code)
}
// Verify response contains valid: true
var body map[string]interface{}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err == nil {
if valid, ok := body["valid"].(bool); !ok || !valid {
t.Errorf("[ERROR] [server] [auth] verify response missing valid=true: %v", body)
}
}
}

View File

@@ -0,0 +1,137 @@
package handlers_test
// downloads_auth_test.go — Pre-fix tests for unauthenticated download endpoints.
//
// BUG F-A3-7 CRITICAL: GET /api/v1/downloads/config/:agent_id has no auth middleware.
// Agent config templates are downloadable by anyone who knows an agent UUID.
// ETHOS #2 violation: unauthenticated endpoint serves config data.
//
// BUG F-A3-6 HIGH: GET /api/v1/downloads/updates/:package_id has no auth middleware.
// Signed update binaries are downloadable by anyone with a package UUID.
//
// These tests use httptest to verify that unauthenticated requests reach the
// handler (documenting the bug) and that auth SHOULD be required (fail-now).
//
// Run: cd aggregator-server && go test ./internal/api/handlers/... -v -run TestConfigDownload
// Run: cd aggregator-server && go test ./internal/api/handlers/... -v -run TestUpdatePackageDownload
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
// ---------------------------------------------------------------------------
// Test 2.1 — Config download SHOULD require auth (currently doesn't)
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-7: Config download requires no auth. Agent UUIDs are not secret
// (they appear in URLs, logs, error messages). Any caller can download
// agent configuration by guessing or harvesting UUIDs.
// ETHOS #2 violation: unauthenticated endpoint serves sensitive data.
// ---------------------------------------------------------------------------
func TestConfigDownloadRequiresAuth(t *testing.T) {
// Build a minimal router that mirrors the CURRENT production state:
// no auth middleware on the config download route.
router := gin.New()
router.GET("/api/v1/downloads/config/:agent_id", func(c *gin.Context) {
// Stub handler — returns 200 if reached (simulates handler responding)
c.JSON(http.StatusOK, gin.H{"config": "template"})
})
// Make request with NO authorization header
req := httptest.NewRequest("GET", "/api/v1/downloads/config/550e8400-e29b-41d4-a716-446655440000", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// After fix: route must have auth middleware that returns 401
if rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden {
t.Errorf("[ERROR] [server] [downloads] config download without auth returned %d, expected 401 or 403.\n"+
"BUG F-A3-7: config download requires no authentication.\n"+
"After fix: add AuthMiddleware or WebAuthMiddleware to this route.", rec.Code)
}
}
// ---------------------------------------------------------------------------
// Test 2.2 — Documents that config download currently succeeds without auth
//
// Category: PASS-NOW / FAIL-AFTER-FIX
//
// BUG F-A3-7: This test PASSES because the route has no auth middleware.
// When the fix adds auth, the unauthenticated request will return 401
// and this assertion (not 401, not 403) will fail.
// ---------------------------------------------------------------------------
func TestConfigDownloadCurrentlyUnauthenticated(t *testing.T) {
router := gin.New()
router.GET("/api/v1/downloads/config/:agent_id", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"config": "template"})
})
req := httptest.NewRequest("GET", "/api/v1/downloads/config/550e8400-e29b-41d4-a716-446655440000", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// This assertion PASSES now (bug present) — will FAIL after fix
if rec.Code == http.StatusUnauthorized || rec.Code == http.StatusForbidden {
t.Errorf("[ERROR] [server] [downloads] BUG F-A3-7 already fixed: "+
"config download returned %d (auth required). Update this test.", rec.Code)
}
t.Logf("[INFO] [server] [downloads] BUG F-A3-7 confirmed: config download returned %d without auth", rec.Code)
t.Log("[INFO] [server] [downloads] after fix: this test will FAIL (update to assert 401)")
}
// ---------------------------------------------------------------------------
// Test 2.3 — Update package download SHOULD require auth (currently doesn't)
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-6: Update package download requires no auth.
// Signed update binaries should require at minimum a valid agent JWT.
// ---------------------------------------------------------------------------
func TestUpdatePackageDownloadRequiresAuth(t *testing.T) {
router := gin.New()
router.GET("/api/v1/downloads/updates/:package_id", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"package": "data"})
})
req := httptest.NewRequest("GET", "/api/v1/downloads/updates/550e8400-e29b-41d4-a716-446655440000", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden {
t.Errorf("[ERROR] [server] [downloads] update package download without auth returned %d, expected 401 or 403.\n"+
"BUG F-A3-6: update package download requires no authentication.\n"+
"After fix: add AuthMiddleware to this route.", rec.Code)
}
}
// ---------------------------------------------------------------------------
// Test 2.4 — Documents that update package download currently succeeds without auth
//
// Category: PASS-NOW / FAIL-AFTER-FIX
// ---------------------------------------------------------------------------
func TestUpdatePackageDownloadCurrentlyUnauthenticated(t *testing.T) {
router := gin.New()
router.GET("/api/v1/downloads/updates/:package_id", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"package": "data"})
})
req := httptest.NewRequest("GET", "/api/v1/downloads/updates/550e8400-e29b-41d4-a716-446655440000", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code == http.StatusUnauthorized || rec.Code == http.StatusForbidden {
t.Errorf("[ERROR] [server] [downloads] BUG F-A3-6 already fixed: "+
"update package download returned %d. Update this test.", rec.Code)
}
t.Logf("[INFO] [server] [downloads] BUG F-A3-6 confirmed: update package download returned %d without auth", rec.Code)
}