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:
@@ -0,0 +1,130 @@
|
||||
package middleware_test
|
||||
|
||||
// auth_secret_leak_test.go — Pre-fix tests for JWT secret leak in WebAuthMiddleware.
|
||||
//
|
||||
// BUG F-A3-11: WebAuthMiddleware prints the JWT secret to stdout on validation
|
||||
// failure (auth.go:128). Two violations:
|
||||
// 1. Secret value in log output — any log collector captures the signing key
|
||||
// 2. Emoji in log output — violates ETHOS #1
|
||||
//
|
||||
// These tests verify that the middleware does NOT leak secrets or use emojis.
|
||||
// They currently FAIL because the bug exists.
|
||||
//
|
||||
// Run: cd aggregator-server && go test ./internal/api/middleware/... -v -run TestWebAuth
|
||||
|
||||
// NOTE: WebAuthMiddleware is defined in handlers/auth.go (on AuthHandler),
|
||||
// not in the middleware package. These tests exercise the middleware indirectly
|
||||
// via the handler's exported method. Since we need to test the actual handler
|
||||
// behavior without importing the handlers package from a middleware_test package,
|
||||
// we test the agent AuthMiddleware here (which is in this package) and create
|
||||
// a parallel test file in handlers_test for WebAuthMiddleware.
|
||||
//
|
||||
// See: aggregator-server/internal/api/handlers/auth_middleware_leak_test.go
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode"
|
||||
|
||||
"github.com/Fimeg/RedFlag/aggregator-server/internal/api/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
gin.SetMode(gin.TestMode)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 1.1 — Agent AuthMiddleware does not leak middleware.JWTSecret
|
||||
//
|
||||
// Category: PASS-NOW (agent middleware does not have the leak bug)
|
||||
//
|
||||
// This test confirms that the agent-side AuthMiddleware does NOT print
|
||||
// secrets on failure. It serves as a contrast to the WebAuthMiddleware
|
||||
// which DOES print secrets (see handlers/auth_middleware_leak_test.go).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestAgentAuthMiddlewareDoesNotLogSecret(t *testing.T) {
|
||||
testSecret := "agent-test-secret-67890"
|
||||
middleware.JWTSecret = testSecret
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.AuthMiddleware())
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
})
|
||||
|
||||
// Capture stdout
|
||||
oldStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
req := httptest.NewRequest("GET", "/test", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid-token-abc123")
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
captured := buf.String()
|
||||
|
||||
// Agent middleware should NOT print the secret
|
||||
if strings.Contains(captured, testSecret) {
|
||||
t.Errorf("[ERROR] [server] [auth] agent AuthMiddleware leaked JWT secret to stdout")
|
||||
}
|
||||
|
||||
// Confirm the request was rejected
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [auth] expected 401, got %d", rec.Code)
|
||||
}
|
||||
|
||||
t.Log("[INFO] [server] [auth] agent AuthMiddleware does not leak secrets (correct)")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 1.2 — Agent AuthMiddleware stdout has no emoji characters
|
||||
//
|
||||
// Category: PASS-NOW (agent middleware does not use emojis)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestAgentAuthMiddlewareLogHasNoEmoji(t *testing.T) {
|
||||
middleware.JWTSecret = "test-secret-no-emoji"
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.AuthMiddleware())
|
||||
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 bad-token")
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
captured := buf.String()
|
||||
|
||||
for _, r := range captured {
|
||||
if r > 0x1F300 || (r >= 0x1F600 && r <= 0x1F64F) || unicode.Is(unicode.So, r) {
|
||||
t.Errorf("[ERROR] [server] [auth] emoji character found in agent middleware output: U+%04X", r)
|
||||
}
|
||||
}
|
||||
|
||||
t.Log("[INFO] [server] [auth] agent AuthMiddleware output has no emoji (correct)")
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//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.
|
||||
|
||||
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
|
||||
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)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("[ERROR] [server] [middleware] non-admin user got %d, expected 403", rec.Code)
|
||||
}
|
||||
|
||||
// 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)
|
||||
rec2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec2, req2)
|
||||
|
||||
if rec2.Code == http.StatusForbidden || rec2.Code == http.StatusUnauthorized {
|
||||
t.Errorf("[ERROR] [server] [middleware] admin user got %d, expected 200", rec2.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package middleware_test
|
||||
|
||||
// require_admin_test.go — Pre-fix tests for missing RequireAdmin middleware.
|
||||
//
|
||||
// BUG F-A3-13 LOW: RequireAdmin() middleware is referenced in main.go:601
|
||||
// for security settings routes but was never implemented. The 7 security
|
||||
// settings routes are permanently commented out because of this.
|
||||
//
|
||||
// Test 6.1 verifies that the middleware package exports a RequireAdmin symbol.
|
||||
// Test 6.2 (build-tagged //go:build ignore) tests its behavior once implemented.
|
||||
//
|
||||
// Run: cd aggregator-server && go test ./internal/api/middleware/... -v -run TestRequireAdmin
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 6.1 — RequireAdmin middleware function exists in middleware package
|
||||
//
|
||||
// Category: FAIL-NOW / PASS-AFTER-FIX
|
||||
//
|
||||
// BUG F-A3-13: RequireAdmin() does not exist in the middleware package.
|
||||
// Confirmed via grep: zero results for "RequireAdmin" in any .go file.
|
||||
// 7 security settings routes in main.go:600-610 are commented out because
|
||||
// of this missing middleware.
|
||||
//
|
||||
// This test scans the middleware package source files for a function named
|
||||
// RequireAdmin. It does not attempt to call the function (which would fail
|
||||
// to compile if it doesn't exist).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestRequireAdminMiddlewareExists(t *testing.T) {
|
||||
// Scan the middleware package directory for a RequireAdmin function
|
||||
middlewareDir := filepath.Join(".", "..", "..", "..", "internal", "api", "middleware")
|
||||
|
||||
// Resolve relative to the test file location
|
||||
// For go test, the working directory is the package directory
|
||||
middlewareDir = "."
|
||||
|
||||
entries, err := os.ReadDir(middlewareDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read middleware directory: %v", err)
|
||||
}
|
||||
|
||||
found := false
|
||||
fset := token.NewFileSet()
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(entry.Name(), "_test.go") {
|
||||
continue
|
||||
}
|
||||
|
||||
node, err := parser.ParseFile(fset, entry.Name(), nil, parser.AllErrors)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, decl := range node.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if fn.Name.Name == "RequireAdmin" {
|
||||
found = true
|
||||
t.Logf("[INFO] [server] [middleware] RequireAdmin found in %s", entry.Name())
|
||||
break
|
||||
}
|
||||
}
|
||||
if found {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
t.Errorf("[ERROR] [server] [middleware] RequireAdmin() function not found in middleware package.\n"+
|
||||
"BUG F-A3-13: RequireAdmin() is referenced in main.go:601 but never implemented.\n"+
|
||||
"7 security settings routes are permanently disabled as a result.\n"+
|
||||
"After fix: implement RequireAdmin() that checks UserClaims.Role == \"admin\".")
|
||||
}
|
||||
}
|
||||
118
aggregator-server/internal/api/middleware/scheduler_auth_test.go
Normal file
118
aggregator-server/internal/api/middleware/scheduler_auth_test.go
Normal file
@@ -0,0 +1,118 @@
|
||||
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)")
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package middleware_test
|
||||
|
||||
// token_confusion_test.go — Pre-fix tests for cross-type JWT token confusion.
|
||||
//
|
||||
// BUG F-A3-12 MEDIUM: Agent and web JWTs share the same signing secret with
|
||||
// no issuer/audience differentiation. Cross-type token confusion is possible.
|
||||
//
|
||||
// The shared secret is set at main.go:166. Both AuthMiddleware (agent JWT)
|
||||
// and WebAuthMiddleware (admin JWT) use the same HMAC key. Without issuer
|
||||
// or audience claims, a JWT valid for one context may pass signature
|
||||
// validation in the other.
|
||||
//
|
||||
// Run: cd aggregator-server && go test ./internal/api/middleware/... -v -run TestToken
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// makeWebJWT creates a valid web/admin JWT for testing
|
||||
func makeWebJWT(t *testing.T, secret string) string {
|
||||
t.Helper()
|
||||
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)
|
||||
signed, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to sign web JWT: %v", err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 4.1 — Web token SHOULD be rejected by agent AuthMiddleware
|
||||
//
|
||||
// Category: Verify actual behavior — PASS or FAIL depending on claims parsing
|
||||
//
|
||||
// BUG F-A3-12: Shared JWT secret allows cross-type token use. A web token
|
||||
// passes signature validation on agent middleware. The question is whether
|
||||
// claims parsing (AgentClaims expecting AgentID uuid.UUID) rejects the
|
||||
// web token that has UserID string instead.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestWebTokenRejectedByAgentAuthMiddleware(t *testing.T) {
|
||||
sharedSecret := "shared-secret-confusion-test"
|
||||
middleware.JWTSecret = sharedSecret
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware.AuthMiddleware())
|
||||
router.GET("/agent-route", func(c *gin.Context) {
|
||||
agentID, exists := c.Get("agent_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no agent_id"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"agent_id": agentID})
|
||||
})
|
||||
|
||||
// Create a web JWT (UserClaims with UserID, Username, Role)
|
||||
webToken := makeWebJWT(t, sharedSecret)
|
||||
|
||||
req := httptest.NewRequest("GET", "/agent-route", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+webToken)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 4.2 — Agent token SHOULD be rejected by WebAuthMiddleware
|
||||
//
|
||||
// Category: Verify actual behavior — PASS or FAIL depending on claims parsing
|
||||
//
|
||||
// BUG F-A3-12: An agent token (AgentClaims with AgentID uuid.UUID) may pass
|
||||
// signature validation on WebAuthMiddleware. The question is whether the
|
||||
// UserClaims parsing rejects it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestAgentTokenRejectedByWebAuthMiddleware(t *testing.T) {
|
||||
sharedSecret := "shared-secret-confusion-test-2"
|
||||
middleware.JWTSecret = sharedSecret
|
||||
|
||||
authHandler := handlers.NewAuthHandler(sharedSecret, nil)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authHandler.WebAuthMiddleware())
|
||||
router.GET("/admin-route", func(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no user_id"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user_id": userID})
|
||||
})
|
||||
|
||||
// Create an agent JWT (AgentClaims with AgentID uuid.UUID)
|
||||
agentClaims := 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, agentClaims)
|
||||
agentToken, err := token.SignedString([]byte(sharedSecret))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to sign agent JWT: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest("GET", "/admin-route", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+agentToken)
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user