Fixes 9 auth middleware findings from the A-3 recon audit. F-A3-11 CRITICAL: Removed JWT secret from WebAuthMiddleware log output. Replaced emoji-prefixed fmt.Printf with ETHOS-compliant log.Printf. No secret values in any log output. F-A3-7 CRITICAL: Config download now requires WebAuthMiddleware. GET /downloads/config/:agent_id is admin-only (agents never call it). F-A3-6 HIGH: Update package download now requires AuthMiddleware. GET /downloads/updates/:package_id requires valid agent JWT. F-A3-10 HIGH: Scheduler stats changed from AuthMiddleware to WebAuthMiddleware. Agent JWTs can no longer view scheduler internals. F-A3-13 LOW: RequireAdmin() middleware implemented. 7 security settings routes re-enabled (GET/PUT/POST under /security/settings). security_settings.go.broken renamed to .go, API mismatches fixed. F-A3-12 MEDIUM: JWT issuer claims added for token type separation. Agent tokens: issuer=redflag-agent, Web tokens: issuer=redflag-web. AuthMiddleware rejects tokens with wrong issuer. Grace period: tokens with no issuer still accepted (backward compat). F-A3-2 MEDIUM: /auth/verify now has WebAuthMiddleware applied. Endpoint returns 200 with valid=true for valid admin tokens. F-A3-9 MEDIUM: Agent self-unregister (DELETE /:id) now rate-limited using the same agent_reports rate limiter as other agent routes. F-A3-14 LOW: CORS origin configurable via REDFLAG_CORS_ORIGIN env var. Defaults to http://localhost:3000 for development. Added PATCH method and agent-specific headers to CORS config. All 27 server tests pass. All 14 agent tests pass. No regressions. See docs/A3_Fix_Implementation.md and docs/Deviations_Report.md (DEV-020 through DEV-022). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
119 lines
4.4 KiB
Go
119 lines
4.4 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/handlers"
|
|
"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{
|
|
Issuer: middleware.JWTIssuerAgent,
|
|
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) {
|
|
// POST-FIX (F-A3-10): Route now uses WebAuthMiddleware (admin JWT required).
|
|
// Agent JWTs are rejected because WebAuthMiddleware expects UserClaims.
|
|
testSecret := "scheduler-test-secret"
|
|
middleware.JWTSecret = testSecret
|
|
|
|
authHandler := handlers.NewAuthHandler(testSecret, nil)
|
|
|
|
router := gin.New()
|
|
router.Use(authHandler.WebAuthMiddleware())
|
|
router.GET("/api/v1/scheduler/stats", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"scheduler": "stats"})
|
|
})
|
|
|
|
// Agent JWT should be rejected
|
|
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)
|
|
|
|
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)", rec.Code)
|
|
}
|
|
t.Logf("[INFO] [server] [scheduler] F-A3-10 FIXED: agent JWT rejected on scheduler stats (%d)", 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) {
|
|
// POST-FIX (F-A3-10): Agent JWT is now rejected on scheduler stats.
|
|
testSecret := "scheduler-test-secret-2"
|
|
middleware.JWTSecret = testSecret
|
|
|
|
authHandler := handlers.NewAuthHandler(testSecret, nil)
|
|
|
|
router := gin.New()
|
|
router.Use(authHandler.WebAuthMiddleware())
|
|
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)
|
|
|
|
// POST-FIX: agent JWT must be rejected
|
|
if rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden {
|
|
t.Errorf("[ERROR] [server] [scheduler] agent JWT still accepted (%d), expected 401/403", rec.Code)
|
|
}
|
|
t.Log("[INFO] [server] [scheduler] F-A3-10 FIXED: agent JWT rejected on scheduler stats")
|
|
}
|