Files
Redflag/aggregator-server/internal/api/middleware/scheduler_auth_test.go
jpetree331 ee246771dc 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>
2026-03-28 21:54:48 -04:00

119 lines
4.3 KiB
Go

package middleware_test
// scheduler_auth_test.go — Pre-fix tests for scheduler stats wrong middleware.
//
// BUG F-A3-10 HIGH: GET /api/v1/scheduler/stats uses AuthMiddleware (agent JWT)
// instead of WebAuthMiddleware (admin JWT). Any registered agent can view
// scheduler internals (queue stats, subsystem counts, timing data).
//
// ETHOS #2: All admin dashboard routes must use WebAuthMiddleware.
//
// Run: cd aggregator-server && go test ./internal/api/middleware/... -v -run TestScheduler
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Fimeg/RedFlag/aggregator-server/internal/api/middleware"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
// makeAgentJWT creates a valid agent JWT for testing
func makeAgentJWT(t *testing.T, secret string) string {
t.Helper()
claims := middleware.AgentClaims{
AgentID: uuid.New(),
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatalf("failed to sign agent JWT: %v", err)
}
return signed
}
// ---------------------------------------------------------------------------
// Test 3.1 — Scheduler stats should reject agent JWTs (require admin)
//
// Category: FAIL-NOW / PASS-AFTER-FIX
//
// BUG F-A3-10: /scheduler/stats uses AuthMiddleware (agent JWT).
// An agent JWT is currently accepted. After fix, agent JWT must be
// rejected (route should use WebAuthMiddleware instead).
// ETHOS #2: All admin dashboard routes must use WebAuthMiddleware.
// ---------------------------------------------------------------------------
func TestSchedulerStatsRequiresAdminAuth(t *testing.T) {
testSecret := "scheduler-test-secret"
middleware.JWTSecret = testSecret
// Current state: route uses AuthMiddleware (agent JWT accepted)
// This mirrors the bug in main.go:627
router := gin.New()
router.Use(middleware.AuthMiddleware())
router.GET("/api/v1/scheduler/stats", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"scheduler": "stats"})
})
// Create a valid agent JWT
agentToken := makeAgentJWT(t, testSecret)
req := httptest.NewRequest("GET", "/api/v1/scheduler/stats", nil)
req.Header.Set("Authorization", "Bearer "+agentToken)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// After fix: agent JWT should be rejected (route uses WebAuthMiddleware)
// Currently: agent JWT is accepted (200) — this assertion FAILS
if rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden {
t.Errorf("[ERROR] [server] [scheduler] agent JWT accepted on scheduler stats (got %d, expected 401/403).\n"+
"BUG F-A3-10: scheduler stats accessible to any registered agent.\n"+
"After fix: change AuthMiddleware to WebAuthMiddleware on this route.", rec.Code)
}
}
// ---------------------------------------------------------------------------
// Test 3.2 — Documents that agent JWT currently grants scheduler access
//
// Category: PASS-NOW / FAIL-AFTER-FIX
//
// This test PASSES because the bug exists (agent JWT accepted).
// When the fix changes the middleware to WebAuthMiddleware, agent JWTs
// will be rejected and this test will FAIL.
// ---------------------------------------------------------------------------
func TestSchedulerStatsCurrentlyAcceptsAgentJWT(t *testing.T) {
testSecret := "scheduler-test-secret-2"
middleware.JWTSecret = testSecret
router := gin.New()
router.Use(middleware.AuthMiddleware())
router.GET("/api/v1/scheduler/stats", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"scheduler": "stats"})
})
agentToken := makeAgentJWT(t, testSecret)
req := httptest.NewRequest("GET", "/api/v1/scheduler/stats", nil)
req.Header.Set("Authorization", "Bearer "+agentToken)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// This PASSES now (bug present) — agent JWT is accepted
if rec.Code == http.StatusUnauthorized || rec.Code == http.StatusForbidden {
t.Errorf("[ERROR] [server] [scheduler] BUG F-A3-10 already fixed: "+
"agent JWT rejected (%d). Update this test.", rec.Code)
}
t.Logf("[INFO] [server] [scheduler] BUG F-A3-10 confirmed: agent JWT accepted, got %d", rec.Code)
t.Log("[INFO] [server] [scheduler] after fix: this test will FAIL (update to assert 401)")
}