test(api-keys): add tests for tenant API key management path rejection

Introduce tests to validate that tenant API keys are correctly restricted from accessing management paths. Implemented new test cases for both allowed and forbidden paths, ensuring proper enforcement of API key scopes. Additionally, refactored existing tests to utilize the new rejection logic.
This commit is contained in:
wizardchen
2026-07-06 13:39:02 +08:00
committed by lyingbug
parent 9a76a24ce6
commit fedb6c3f7e
8 changed files with 77 additions and 174 deletions
+25
View File
@@ -2,6 +2,7 @@ package middleware
import (
"context"
stderrors "errors"
"net/http"
"strings"
@@ -9,6 +10,8 @@ import (
"github.com/gin-gonic/gin"
)
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
// isTenantAPIKeyManagementPath reports tenant API-key lifecycle endpoints that
// no scoped key may call, regardless of role.
func isTenantAPIKeyManagementPath(path string) bool {
@@ -21,6 +24,19 @@ func isTenantAPIKeyManagementPath(path string) bool {
return strings.HasSuffix(path, "/api-key")
}
// rejectTenantAPIKeyManagementPath is a defense-in-depth guard in auth: API keys
// must never reach key-management routes even if a route forgets APIKeyDeny().
// Role and KB checks are enforced by per-route APIKey* guards and types helpers.
func rejectTenantAPIKeyManagementPath(ctx context.Context, path string) error {
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok {
return nil
}
if isTenantAPIKeyManagementPath(path) {
return errTenantAPIKeyScopeForbidden
}
return nil
}
// RequireAPIKeyDeny rejects all X-API-Key callers. JWT sessions pass through.
func RequireAPIKeyDeny() gin.HandlerFunc {
return func(c *gin.Context) {
@@ -81,3 +97,12 @@ func requireTenantAPIKeyMinRole(ctx context.Context, minRole types.TenantRole) e
}
return nil
}
func isSafeHTTPMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return true
default:
return false
}
}