Files
Redflag/aggregator-server/internal/api/middleware/auth.go
jpetree331 4c62de8d8b 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>
2026-03-28 22:17:40 -04:00

91 lines
2.5 KiB
Go

package middleware
import (
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
// AgentClaims represents JWT claims for agent authentication
type AgentClaims struct {
AgentID uuid.UUID `json:"agent_id"`
jwt.RegisteredClaims
}
// 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()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(JWTSecret))
}
// AuthMiddleware validates JWT tokens from agents
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
c.Abort()
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization format"})
c.Abort()
return
}
token, err := jwt.ParseWithClaims(tokenString, &AgentClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(JWTSecret), nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
c.Abort()
return
}
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 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
c.Abort()
}
}
}