fix(security): A-3 auth middleware coverage fixes
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>
This commit is contained in:
@@ -10,3 +10,6 @@ JWT_SECRET=change-me-in-production-use-long-random-string
|
||||
# Agent Configuration
|
||||
CHECK_IN_INTERVAL=300 # seconds
|
||||
OFFLINE_THRESHOLD=600 # seconds before marking agent offline
|
||||
|
||||
# CORS Configuration (default: http://localhost:3000)
|
||||
# REDFLAG_CORS_ORIGIN=https://your-dashboard-domain.com
|
||||
|
||||
@@ -365,6 +365,13 @@ func main() {
|
||||
} else {
|
||||
log.Printf("[OK] Security settings service initialized")
|
||||
}
|
||||
|
||||
// Initialize security settings handler (F-A3-13: re-enable security settings routes)
|
||||
var securitySettingsHandler *handlers.SecuritySettingsHandler
|
||||
if securitySettingsService != nil {
|
||||
securitySettingsHandler = handlers.NewSecuritySettingsHandler(securitySettingsService)
|
||||
}
|
||||
|
||||
// Setup router
|
||||
router := gin.Default()
|
||||
|
||||
@@ -385,7 +392,7 @@ func main() {
|
||||
// Authentication routes (with rate limiting)
|
||||
api.POST("/auth/login", rateLimiter.RateLimit("public_access", middleware.KeyByIP), authHandler.Login)
|
||||
api.POST("/auth/logout", authHandler.Logout)
|
||||
api.GET("/auth/verify", authHandler.VerifyToken)
|
||||
api.GET("/auth/verify", authHandler.WebAuthMiddleware(), authHandler.VerifyToken)
|
||||
|
||||
// Public system routes (no authentication required)
|
||||
api.GET("/public-key", rateLimiter.RateLimit("public_access", middleware.KeyByIP), systemHandler.GetPublicKey)
|
||||
@@ -406,11 +413,13 @@ func main() {
|
||||
buildRoutes.POST("/detect", rateLimiter.RateLimit("agent_build", middleware.KeyByAgentID), handlers.DetectAgentInstallation)
|
||||
}
|
||||
|
||||
// Public download routes (no authentication - agents need these!)
|
||||
// Public download routes (agent binaries and install scripts remain public for bootstrapping)
|
||||
api.GET("/downloads/:platform", rateLimiter.RateLimit("public_access", middleware.KeyByIP), downloadHandler.DownloadAgent)
|
||||
api.GET("/downloads/updates/:package_id", rateLimiter.RateLimit("public_access", middleware.KeyByIP), downloadHandler.DownloadUpdatePackage)
|
||||
api.GET("/downloads/config/:agent_id", rateLimiter.RateLimit("public_access", middleware.KeyByIP), downloadHandler.HandleConfigDownload)
|
||||
api.GET("/install/:platform", rateLimiter.RateLimit("public_access", middleware.KeyByIP), downloadHandler.InstallScript)
|
||||
|
||||
// Protected download routes (F-A3-6, F-A3-7: require authentication)
|
||||
api.GET("/downloads/updates/:package_id", middleware.AuthMiddleware(), rateLimiter.RateLimit("public_access", middleware.KeyByIP), downloadHandler.DownloadUpdatePackage)
|
||||
api.GET("/downloads/config/:agent_id", authHandler.WebAuthMiddleware(), rateLimiter.RateLimit("public_access", middleware.KeyByIP), downloadHandler.HandleConfigDownload)
|
||||
}
|
||||
|
||||
// Start background goroutine to mark offline agents
|
||||
@@ -476,7 +485,7 @@ func main() {
|
||||
}
|
||||
verificationHandler.VerifySignature(c)
|
||||
})
|
||||
agents.DELETE("/:id", agentHandler.UnregisterAgent)
|
||||
agents.DELETE("/:id", rateLimiter.RateLimit("agent_reports", middleware.KeyByAgentID), agentHandler.UnregisterAgent)
|
||||
|
||||
// New dedicated endpoints for metrics and docker images (data classification fix)
|
||||
agents.POST("/:id/metrics", rateLimiter.RateLimit("agent_reports", middleware.KeyByAgentID), metricsHandler.ReportMetrics)
|
||||
@@ -597,17 +606,20 @@ func main() {
|
||||
dashboard.GET("/security/metrics", securityHandler.SecurityMetrics)
|
||||
|
||||
// Security Settings Management endpoints (admin-only)
|
||||
// securitySettings := dashboard.Group("/security/settings")
|
||||
// securitySettings.Use(middleware.RequireAdmin())
|
||||
// {
|
||||
// securitySettings.GET("", securitySettingsHandler.GetAllSecuritySettings)
|
||||
// securitySettings.GET("/audit", securitySettingsHandler.GetSecurityAuditTrail)
|
||||
// securitySettings.GET("/overview", securitySettingsHandler.GetSecurityOverview)
|
||||
// securitySettings.GET("/:category", securitySettingsHandler.GetSecuritySettingsByCategory)
|
||||
// securitySettings.PUT("/:category/:key", securitySettingsHandler.UpdateSecuritySetting)
|
||||
// securitySettings.POST("/validate", securitySettingsHandler.ValidateSecuritySettings)
|
||||
// securitySettings.POST("/apply", securitySettingsHandler.ApplySecuritySettings)
|
||||
// }
|
||||
// F-A3-13 fix: RequireAdmin() middleware implemented, routes re-enabled
|
||||
if securitySettingsHandler != nil {
|
||||
securitySettings := dashboard.Group("/security/settings")
|
||||
securitySettings.Use(middleware.RequireAdmin())
|
||||
{
|
||||
securitySettings.GET("", securitySettingsHandler.GetAllSecuritySettings)
|
||||
securitySettings.GET("/audit", securitySettingsHandler.GetSecurityAuditTrail)
|
||||
securitySettings.GET("/overview", securitySettingsHandler.GetSecurityOverview)
|
||||
securitySettings.GET("/:category", securitySettingsHandler.GetSecuritySettingsByCategory)
|
||||
securitySettings.PUT("/:category/:key", securitySettingsHandler.UpdateSecuritySetting)
|
||||
securitySettings.POST("/validate", securitySettingsHandler.ValidateSecuritySettings)
|
||||
securitySettings.POST("/apply", securitySettingsHandler.ApplySecuritySettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load subsystems into queue
|
||||
@@ -624,7 +636,8 @@ func main() {
|
||||
}
|
||||
|
||||
// Add scheduler stats endpoint (after scheduler is initialized)
|
||||
router.GET("/api/v1/scheduler/stats", middleware.AuthMiddleware(), func(c *gin.Context) {
|
||||
// F-A3-10 fix: use WebAuthMiddleware (admin only), not AuthMiddleware (agent JWT)
|
||||
router.GET("/api/v1/scheduler/stats", authHandler.WebAuthMiddleware(), func(c *gin.Context) {
|
||||
stats := subsystemScheduler.GetStats()
|
||||
queueStats := subsystemScheduler.GetQueueStats()
|
||||
c.JSON(200, gin.H{
|
||||
|
||||
@@ -43,24 +43,15 @@ import (
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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)
|
||||
// POST-FIX (F-A3-9): Route now includes rate limiter.
|
||||
// Updated route: agents.DELETE("/:id", rateLimiter.RateLimit("agent_reports", ...), agentHandler.UnregisterAgent)
|
||||
routeRegistration := `agents.DELETE("/:id", rateLimiter.RateLimit("agent_reports", middleware.KeyByAgentID), agentHandler.UnregisterAgent)`
|
||||
|
||||
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.")
|
||||
if !strings.Contains(routeRegistration, "rateLimiter.RateLimit") {
|
||||
t.Error("[ERROR] [server] [agents] F-A3-9 FIX BROKEN: rate limiter missing on DELETE /:id")
|
||||
}
|
||||
|
||||
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")
|
||||
t.Log("[INFO] [server] [agents] F-A3-9 FIXED: DELETE /:id has rate limiter")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -73,16 +64,11 @@ func TestAgentSelfUnregisterHasNoRateLimit(t *testing.T) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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)`
|
||||
// POST-FIX (F-A3-9): Route now includes rate limiter.
|
||||
currentRegistration := `agents.DELETE("/:id", rateLimiter.RateLimit("agent_reports", middleware.KeyByAgentID), 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)
|
||||
t.Errorf("[ERROR] [server] [agents] DELETE /:id is missing rate limiter")
|
||||
}
|
||||
t.Log("[INFO] [server] [agents] F-A3-9 FIXED: DELETE /:id has rate limiter")
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -65,6 +66,7 @@ func (h *AuthHandler) Login(c *gin.Context) {
|
||||
Username: admin.Username,
|
||||
Role: "admin", // Always admin for single-admin system
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: "redflag-web",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
@@ -124,15 +126,26 @@ func (h *AuthHandler) WebAuthMiddleware() gin.HandlerFunc {
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
// Debug: Log the JWT validation error (remove in production)
|
||||
fmt.Printf("🔓 JWT validation failed: %v (secret: %s)\n", err, h.jwtSecret)
|
||||
log.Printf("[WARNING] [server] [auth] jwt_validation_failed error=%q", err)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*UserClaims); ok {
|
||||
// F-A3-12: Validate issuer to prevent cross-type token confusion
|
||||
if claims.Issuer != "" && claims.Issuer != "redflag-web" {
|
||||
log.Printf("[WARNING] [server] [auth] wrong_token_issuer expected=redflag-web got=%s", claims.Issuer)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token type"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// TODO: remove issuer-absent grace period after 30 days
|
||||
if claims.Issuer == "" {
|
||||
log.Printf("[WARNING] [server] [auth] web_token_missing_issuer user_id=%s", claims.UserID)
|
||||
}
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("user_role", claims.Role)
|
||||
c.Next()
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
|
||||
@@ -19,8 +19,13 @@ 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"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -35,11 +40,14 @@ import (
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestConfigDownloadRequiresAuth(t *testing.T) {
|
||||
// Build a minimal router that mirrors the CURRENT production state:
|
||||
// no auth middleware on the config download route.
|
||||
// POST-FIX (F-A3-7): Config download now requires WebAuthMiddleware.
|
||||
// This test creates a router WITH auth middleware to confirm the fix works.
|
||||
testSecret := "config-download-test-secret"
|
||||
authHandler := handlers.NewAuthHandler(testSecret, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authHandler.WebAuthMiddleware())
|
||||
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"})
|
||||
})
|
||||
|
||||
@@ -48,12 +56,11 @@ func TestConfigDownloadRequiresAuth(t *testing.T) {
|
||||
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)
|
||||
// With auth middleware applied, unauthenticated requests return 401
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [downloads] config download without auth returned %d, expected 401", rec.Code)
|
||||
}
|
||||
t.Logf("[INFO] [server] [downloads] F-A3-7 FIXED: config download returned %d without auth", rec.Code)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -67,7 +74,13 @@ func TestConfigDownloadRequiresAuth(t *testing.T) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestConfigDownloadCurrentlyUnauthenticated(t *testing.T) {
|
||||
// POST-FIX (F-A3-7): This test now asserts that unauthenticated
|
||||
// requests to config download ARE rejected (previously they succeeded).
|
||||
testSecret := "config-download-test-secret-2"
|
||||
authHandler := handlers.NewAuthHandler(testSecret, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authHandler.WebAuthMiddleware())
|
||||
router.GET("/api/v1/downloads/config/:agent_id", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"config": "template"})
|
||||
})
|
||||
@@ -76,14 +89,11 @@ func TestConfigDownloadCurrentlyUnauthenticated(t *testing.T) {
|
||||
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)
|
||||
// POST-FIX: unauthenticated request must be rejected
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [downloads] config download without auth returned %d, expected 401", 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)")
|
||||
t.Log("[INFO] [server] [downloads] F-A3-7 FIXED: config download requires auth")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -96,20 +106,54 @@ func TestConfigDownloadCurrentlyUnauthenticated(t *testing.T) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestUpdatePackageDownloadRequiresAuth(t *testing.T) {
|
||||
// POST-FIX (F-A3-6): Update package download now requires AuthMiddleware (agent JWT).
|
||||
testSecret := "update-download-test-secret"
|
||||
middleware.JWTSecret = testSecret
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.AuthMiddleware())
|
||||
router.GET("/api/v1/downloads/updates/:package_id", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"package": "data"})
|
||||
})
|
||||
|
||||
// No auth header → should be rejected
|
||||
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)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [downloads] update package download without auth returned %d, expected 401", rec.Code)
|
||||
}
|
||||
|
||||
// With valid agent JWT → should succeed
|
||||
agentToken := makeTestAgentJWT(t, testSecret)
|
||||
req2 := httptest.NewRequest("GET", "/api/v1/downloads/updates/550e8400-e29b-41d4-a716-446655440000", nil)
|
||||
req2.Header.Set("Authorization", "Bearer "+agentToken)
|
||||
rec2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec2, req2)
|
||||
|
||||
if rec2.Code == http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [downloads] update package download with valid agent JWT returned 401")
|
||||
}
|
||||
t.Log("[INFO] [server] [downloads] F-A3-6 FIXED: update package download requires auth")
|
||||
}
|
||||
|
||||
// makeTestAgentJWT creates a valid agent JWT for testing
|
||||
func makeTestAgentJWT(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 test JWT: %v", err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -119,7 +163,12 @@ func TestUpdatePackageDownloadRequiresAuth(t *testing.T) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestUpdatePackageDownloadCurrentlyUnauthenticated(t *testing.T) {
|
||||
// POST-FIX (F-A3-6): Update package downloads are now rejected without auth.
|
||||
testSecret := "update-download-test-secret-2"
|
||||
middleware.JWTSecret = testSecret
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.AuthMiddleware())
|
||||
router.GET("/api/v1/downloads/updates/:package_id", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"package": "data"})
|
||||
})
|
||||
@@ -128,10 +177,8 @@ func TestUpdatePackageDownloadCurrentlyUnauthenticated(t *testing.T) {
|
||||
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)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [downloads] update download without auth returned %d, expected 401", rec.Code)
|
||||
}
|
||||
|
||||
t.Logf("[INFO] [server] [downloads] BUG F-A3-6 confirmed: update package download returned %d without auth", rec.Code)
|
||||
t.Log("[INFO] [server] [downloads] F-A3-6 FIXED: update package download requires auth")
|
||||
}
|
||||
|
||||
198
aggregator-server/internal/api/handlers/security_settings.go
Normal file
198
aggregator-server/internal/api/handlers/security_settings.go
Normal file
@@ -0,0 +1,198 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/Fimeg/RedFlag/aggregator-server/internal/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SecuritySettingsHandler handles security settings API endpoints
|
||||
type SecuritySettingsHandler struct {
|
||||
securitySettingsService *services.SecuritySettingsService
|
||||
}
|
||||
|
||||
// NewSecuritySettingsHandler creates a new security settings handler
|
||||
func NewSecuritySettingsHandler(securitySettingsService *services.SecuritySettingsService) *SecuritySettingsHandler {
|
||||
return &SecuritySettingsHandler{
|
||||
securitySettingsService: securitySettingsService,
|
||||
}
|
||||
}
|
||||
|
||||
// GetAllSecuritySettings returns all security settings
|
||||
func (h *SecuritySettingsHandler) GetAllSecuritySettings(c *gin.Context) {
|
||||
settings, err := h.securitySettingsService.GetAllSettings()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"settings": settings,
|
||||
"user_has_permission": true,
|
||||
})
|
||||
}
|
||||
|
||||
// GetSecuritySettingsByCategory returns settings for a specific category
|
||||
func (h *SecuritySettingsHandler) GetSecuritySettingsByCategory(c *gin.Context) {
|
||||
category := c.Param("category")
|
||||
|
||||
settings, err := h.securitySettingsService.GetSettingsByCategory(category)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// UpdateSecuritySetting updates a specific security setting
|
||||
func (h *SecuritySettingsHandler) UpdateSecuritySetting(c *gin.Context) {
|
||||
var req struct {
|
||||
Value interface{} `json:"value" binding:"required"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
category := c.Param("category")
|
||||
key := c.Param("key")
|
||||
userIDStr := c.GetString("user_id")
|
||||
|
||||
// Parse user_id to UUID (the service expects uuid.UUID)
|
||||
userID, err := uuid.Parse(userIDStr)
|
||||
if err != nil {
|
||||
// Fallback for numeric user IDs — use a deterministic UUID
|
||||
userID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("user:"+userIDStr))
|
||||
}
|
||||
|
||||
if err := h.securitySettingsService.ValidateSetting(category, key, req.Value); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.securitySettingsService.SetSetting(category, key, req.Value, userID, req.Reason); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
setting, err := h.securitySettingsService.GetSetting(category, key)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Setting updated",
|
||||
"setting": map[string]interface{}{
|
||||
"category": category,
|
||||
"key": key,
|
||||
"value": setting,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ValidateSecuritySettings validates settings without applying them
|
||||
func (h *SecuritySettingsHandler) ValidateSecuritySettings(c *gin.Context) {
|
||||
var req struct {
|
||||
Category string `json:"category" binding:"required"`
|
||||
Key string `json:"key" binding:"required"`
|
||||
Value interface{} `json:"value" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err := h.securitySettingsService.ValidateSetting(req.Category, req.Key, req.Value)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"valid": false, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"valid": true, "message": "Setting is valid"})
|
||||
}
|
||||
|
||||
// GetSecurityAuditTrail returns audit trail of security setting changes
|
||||
// Note: GetAuditTrail not yet implemented in service — returns placeholder
|
||||
func (h *SecuritySettingsHandler) GetSecurityAuditTrail(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"audit_entries": []interface{}{},
|
||||
"pagination": gin.H{
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"total": 0,
|
||||
"total_pages": 0,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// GetSecurityOverview returns current security status overview
|
||||
// Note: GetSecurityOverview not yet implemented in service — returns all settings
|
||||
func (h *SecuritySettingsHandler) GetSecurityOverview(c *gin.Context) {
|
||||
settings, err := h.securitySettingsService.GetAllSettings()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"overview": settings,
|
||||
})
|
||||
}
|
||||
|
||||
// ApplySecuritySettings applies batch of setting changes
|
||||
func (h *SecuritySettingsHandler) ApplySecuritySettings(c *gin.Context) {
|
||||
var req struct {
|
||||
Settings map[string]map[string]interface{} `json:"settings" binding:"required"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userIDStr := c.GetString("user_id")
|
||||
userID, err := uuid.Parse(userIDStr)
|
||||
if err != nil {
|
||||
userID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("user:"+userIDStr))
|
||||
}
|
||||
|
||||
// Validate all settings first
|
||||
for category, settings := range req.Settings {
|
||||
for key, value := range settings {
|
||||
if err := h.securitySettingsService.ValidateSetting(category, key, value); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("Validation failed for %s.%s: %v", category, key, err),
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply settings one by one (batch method not available in service)
|
||||
applied := 0
|
||||
for category, settings := range req.Settings {
|
||||
for key, value := range settings {
|
||||
if err := h.securitySettingsService.SetSetting(category, key, value, userID, req.Reason); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": fmt.Sprintf("Failed to apply %s.%s: %v", category, key, err),
|
||||
})
|
||||
return
|
||||
}
|
||||
applied++
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "All settings applied",
|
||||
"applied_count": applied,
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -19,11 +20,18 @@ type AgentClaims struct {
|
||||
// JWTSecret is set by the server at initialization
|
||||
var JWTSecret string
|
||||
|
||||
// JWT issuer constants for token type differentiation (F-A3-12 fix)
|
||||
const (
|
||||
JWTIssuerAgent = "redflag-agent"
|
||||
JWTIssuerWeb = "redflag-web"
|
||||
)
|
||||
|
||||
// GenerateAgentToken creates a new JWT token for an agent
|
||||
func GenerateAgentToken(agentID uuid.UUID) (string, error) {
|
||||
claims := AgentClaims{
|
||||
AgentID: agentID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: JWTIssuerAgent,
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
@@ -61,6 +69,17 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*AgentClaims); ok {
|
||||
// F-A3-12: Validate issuer to prevent cross-type token confusion
|
||||
if claims.Issuer != "" && claims.Issuer != JWTIssuerAgent {
|
||||
log.Printf("[WARNING] [server] [auth] wrong_token_issuer expected=%s got=%s", JWTIssuerAgent, claims.Issuer)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token type"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// TODO: remove issuer-absent grace period after 30 days (backward compat for deployed agents)
|
||||
if claims.Issuer == "" {
|
||||
log.Printf("[WARNING] [server] [auth] agent_token_missing_issuer agent_id=%s", claims.AgentID)
|
||||
}
|
||||
c.Set("agent_id", claims.AgentID)
|
||||
c.Next()
|
||||
} else {
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CORSMiddleware handles Cross-Origin Resource Sharing
|
||||
// Origin is configurable via REDFLAG_CORS_ORIGIN environment variable.
|
||||
// Defaults to http://localhost:3000 for development.
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
origin := os.Getenv("REDFLAG_CORS_ORIGIN")
|
||||
if origin == "" {
|
||||
origin = "http://localhost:3000"
|
||||
}
|
||||
log.Printf("[INFO] [server] [cors] cors_origin_set origin=%q", origin)
|
||||
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "http://localhost:3000")
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Machine-ID, X-Agent-Version, X-Update-Nonce")
|
||||
c.Header("Access-Control-Expose-Headers", "Content-Length")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
|
||||
|
||||
44
aggregator-server/internal/api/middleware/require_admin.go
Normal file
44
aggregator-server/internal/api/middleware/require_admin.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RequireAdmin is a middleware that checks if the authenticated user has admin role.
|
||||
// Must be used AFTER WebAuthMiddleware which sets user_id and role in context.
|
||||
// Returns 403 if the user is not an admin.
|
||||
func RequireAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// WebAuthMiddleware sets user_id from UserClaims
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
log.Printf("[WARNING] [server] [auth] require_admin called without user_id in context")
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Check role from context (set by WebAuthMiddleware from UserClaims)
|
||||
role, exists := c.Get("user_role")
|
||||
if !exists {
|
||||
// Fallback: if role is not in context, deny access
|
||||
log.Printf("[WARNING] [server] [auth] non_admin_access_attempt user_id=%v role=unknown", userID)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
roleStr, ok := role.(string)
|
||||
if !ok || roleStr != "admin" {
|
||||
log.Printf("[WARNING] [server] [auth] non_admin_access_attempt user_id=%v role=%v", userID, role)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,37 @@
|
||||
//go:build ignore
|
||||
// +build ignore
|
||||
|
||||
package middleware_test
|
||||
|
||||
// require_admin_behavior_test.go — Behavioral test for RequireAdmin middleware.
|
||||
//
|
||||
// This file is build-tagged //go:build ignore because RequireAdmin() does
|
||||
// not exist yet (BUG F-A3-13). Enable this test when the middleware is
|
||||
// implemented by removing the build tag.
|
||||
//
|
||||
// Test 6.2 — RequireAdmin blocks non-admin users
|
||||
//
|
||||
// Category: FAIL-NOW / PASS-AFTER-FIX
|
||||
// Cannot compile until F-A3-13 is fixed.
|
||||
// POST-FIX (F-A3-13): RequireAdmin() is now implemented.
|
||||
// Build tag removed — test compiles and runs.
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
func TestRequireAdminBlocksNonAdminUsers(t *testing.T) {
|
||||
testSecret := "admin-test-secret"
|
||||
middleware.JWTSecret = testSecret
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequireAdmin()) // Will not compile until implemented
|
||||
|
||||
// Simulate WebAuthMiddleware having set user_id and user_role
|
||||
router.Use(func(c *gin.Context) {
|
||||
role := c.GetHeader("X-Test-Role")
|
||||
c.Set("user_id", "test-user-1")
|
||||
c.Set("user_role", role)
|
||||
c.Next()
|
||||
})
|
||||
router.Use(middleware.RequireAdmin())
|
||||
router.GET("/admin-only", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"admin": true})
|
||||
})
|
||||
|
||||
// Test A: non-admin user should be blocked
|
||||
nonAdminClaims := jwt.MapClaims{
|
||||
"user_id": "2",
|
||||
"username": "viewer",
|
||||
"role": "viewer",
|
||||
"exp": jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
|
||||
"iat": jwt.NewNumericDate(time.Now()),
|
||||
}
|
||||
nonAdminToken := jwt.NewWithClaims(jwt.SigningMethodHS256, nonAdminClaims)
|
||||
nonAdminSigned, _ := nonAdminToken.SignedString([]byte(testSecret))
|
||||
|
||||
req := httptest.NewRequest("GET", "/admin-only", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+nonAdminSigned)
|
||||
req.Header.Set("X-Test-Role", "viewer")
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
@@ -56,22 +40,14 @@ func TestRequireAdminBlocksNonAdminUsers(t *testing.T) {
|
||||
}
|
||||
|
||||
// Test B: admin user should pass
|
||||
adminClaims := jwt.MapClaims{
|
||||
"user_id": "1",
|
||||
"username": "admin",
|
||||
"role": "admin",
|
||||
"exp": jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
|
||||
"iat": jwt.NewNumericDate(time.Now()),
|
||||
}
|
||||
adminToken := jwt.NewWithClaims(jwt.SigningMethodHS256, adminClaims)
|
||||
adminSigned, _ := adminToken.SignedString([]byte(testSecret))
|
||||
|
||||
req2 := httptest.NewRequest("GET", "/admin-only", nil)
|
||||
req2.Header.Set("Authorization", "Bearer "+adminSigned)
|
||||
req2.Header.Set("X-Test-Role", "admin")
|
||||
rec2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec2, req2)
|
||||
|
||||
if rec2.Code == http.StatusForbidden || rec2.Code == http.StatusUnauthorized {
|
||||
if rec2.Code != http.StatusOK {
|
||||
t.Errorf("[ERROR] [server] [middleware] admin user got %d, expected 200", rec2.Code)
|
||||
}
|
||||
|
||||
t.Log("[INFO] [server] [middleware] F-A3-13 FIXED: RequireAdmin correctly blocks non-admin users")
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"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"
|
||||
@@ -28,6 +29,7 @@ func makeAgentJWT(t *testing.T, secret string) string {
|
||||
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()),
|
||||
},
|
||||
@@ -52,32 +54,30 @@ func makeAgentJWT(t *testing.T, secret string) string {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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
|
||||
|
||||
// Current state: route uses AuthMiddleware (agent JWT accepted)
|
||||
// This mirrors the bug in main.go:627
|
||||
authHandler := handlers.NewAuthHandler(testSecret, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.AuthMiddleware())
|
||||
router.Use(authHandler.WebAuthMiddleware())
|
||||
router.GET("/api/v1/scheduler/stats", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"scheduler": "stats"})
|
||||
})
|
||||
|
||||
// Create a valid agent JWT
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -91,11 +91,14 @@ func TestSchedulerStatsRequiresAdminAuth(t *testing.T) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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(middleware.AuthMiddleware())
|
||||
router.Use(authHandler.WebAuthMiddleware())
|
||||
router.GET("/api/v1/scheduler/stats", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"scheduler": "stats"})
|
||||
})
|
||||
@@ -107,12 +110,9 @@ func TestSchedulerStatsCurrentlyAcceptsAgentJWT(t *testing.T) {
|
||||
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)
|
||||
// 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.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)")
|
||||
t.Log("[INFO] [server] [scheduler] F-A3-10 FIXED: agent JWT rejected on scheduler stats")
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// makeWebJWT creates a valid web/admin JWT for testing
|
||||
// makeWebJWT creates a valid web/admin JWT with correct issuer for testing
|
||||
func makeWebJWT(t *testing.T, secret string) string {
|
||||
t.Helper()
|
||||
claims := handlers.UserClaims{
|
||||
@@ -33,6 +33,7 @@ func makeWebJWT(t *testing.T, secret string) string {
|
||||
Username: "admin",
|
||||
Role: "admin",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: "redflag-web",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
@@ -57,6 +58,8 @@ func makeWebJWT(t *testing.T, secret string) string {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestWebTokenRejectedByAgentAuthMiddleware(t *testing.T) {
|
||||
// POST-FIX (F-A3-12): Web token with issuer=redflag-web is rejected by
|
||||
// agent AuthMiddleware which validates issuer=redflag-agent.
|
||||
sharedSecret := "shared-secret-confusion-test"
|
||||
middleware.JWTSecret = sharedSecret
|
||||
|
||||
@@ -71,7 +74,7 @@ func TestWebTokenRejectedByAgentAuthMiddleware(t *testing.T) {
|
||||
c.JSON(http.StatusOK, gin.H{"agent_id": agentID})
|
||||
})
|
||||
|
||||
// Create a web JWT (UserClaims with UserID, Username, Role)
|
||||
// Web JWT with issuer=redflag-web
|
||||
webToken := makeWebJWT(t, sharedSecret)
|
||||
|
||||
req := httptest.NewRequest("GET", "/agent-route", nil)
|
||||
@@ -79,16 +82,10 @@ func TestWebTokenRejectedByAgentAuthMiddleware(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
// A web token SHOULD be rejected by agent middleware.
|
||||
// If the claims parsing is strict enough, it will return 401.
|
||||
// If not, the token passes — documenting the confusion risk.
|
||||
if rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden {
|
||||
t.Errorf("[ERROR] [server] [auth] web JWT accepted by agent AuthMiddleware (got %d).\n"+
|
||||
"BUG F-A3-12: cross-type token confusion — web token passes agent auth.\n"+
|
||||
"After fix: add issuer/audience claims or use separate signing secrets.", rec.Code)
|
||||
} else {
|
||||
t.Logf("[INFO] [server] [auth] web JWT rejected by agent AuthMiddleware (%d) — claims parsing caught it", rec.Code)
|
||||
t.Errorf("[ERROR] [server] [auth] web JWT accepted by agent AuthMiddleware (got %d, expected 401)", rec.Code)
|
||||
}
|
||||
t.Logf("[INFO] [server] [auth] F-A3-12 FIXED: web JWT rejected by agent middleware (%d)", rec.Code)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -102,6 +99,8 @@ func TestWebTokenRejectedByAgentAuthMiddleware(t *testing.T) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestAgentTokenRejectedByWebAuthMiddleware(t *testing.T) {
|
||||
// POST-FIX (F-A3-12): Agent token with issuer=redflag-agent is rejected by
|
||||
// WebAuthMiddleware which validates issuer=redflag-web.
|
||||
sharedSecret := "shared-secret-confusion-test-2"
|
||||
middleware.JWTSecret = sharedSecret
|
||||
|
||||
@@ -118,10 +117,11 @@ func TestAgentTokenRejectedByWebAuthMiddleware(t *testing.T) {
|
||||
c.JSON(http.StatusOK, gin.H{"user_id": userID})
|
||||
})
|
||||
|
||||
// Create an agent JWT (AgentClaims with AgentID uuid.UUID)
|
||||
// Agent JWT with issuer=redflag-agent
|
||||
agentClaims := 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()),
|
||||
},
|
||||
@@ -137,12 +137,8 @@ func TestAgentTokenRejectedByWebAuthMiddleware(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
// An agent token SHOULD be rejected by web middleware.
|
||||
if rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden {
|
||||
t.Errorf("[ERROR] [server] [auth] agent JWT accepted by WebAuthMiddleware (got %d).\n"+
|
||||
"BUG F-A3-12: cross-type token confusion — agent token passes admin auth.\n"+
|
||||
"After fix: add issuer/audience claims or use separate signing secrets.", rec.Code)
|
||||
} else {
|
||||
t.Logf("[INFO] [server] [auth] agent JWT rejected by WebAuthMiddleware (%d) — claims parsing caught it", rec.Code)
|
||||
t.Errorf("[ERROR] [server] [auth] agent JWT accepted by WebAuthMiddleware (got %d, expected 401)", rec.Code)
|
||||
}
|
||||
t.Logf("[INFO] [server] [auth] F-A3-12 FIXED: agent JWT rejected by web middleware (%d)", rec.Code)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user