fix(api-keys): harden scoped key auth after code review
Revoke existing keys on reset, unify scope enforcement, default empty scopes to read-only, map API key scopes to tenant roles, and remove dead key-generation helpers left over from the tenant api_key column removal.
This commit is contained in:
@@ -11,14 +11,9 @@ import (
|
||||
|
||||
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
|
||||
|
||||
func authorizeTenantAPIKeyOperation(ctx context.Context, method string) error {
|
||||
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func authorizeTenantAPIKeyRoute(ctx context.Context, method, path string) error {
|
||||
// authorizeTenantAPIKeyAccess enforces per-key operation and route scopes for
|
||||
// X-API-Key callers. Non-API-key principals are not restricted.
|
||||
func authorizeTenantAPIKeyAccess(ctx context.Context, method, path string) error {
|
||||
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok {
|
||||
return nil
|
||||
@@ -99,22 +94,20 @@ func isKnowledgeScopedUnsafePath(path string) bool {
|
||||
|
||||
func allowsTenantAPIKeyRead(scope types.TenantAPIKeyScope) bool {
|
||||
scope = scope.Normalize()
|
||||
return len(scope.Scopes) == 0 ||
|
||||
scope.HasScope(types.TenantAPIKeyScopeRead) ||
|
||||
return scope.HasScope(types.TenantAPIKeyScopeRead) ||
|
||||
scope.HasScope(types.TenantAPIKeyScopeWrite) ||
|
||||
scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
||||
}
|
||||
|
||||
func allowsTenantAPIKeyWrite(scope types.TenantAPIKeyScope) bool {
|
||||
scope = scope.Normalize()
|
||||
return len(scope.Scopes) == 0 ||
|
||||
scope.HasScope(types.TenantAPIKeyScopeWrite) ||
|
||||
return scope.HasScope(types.TenantAPIKeyScopeWrite) ||
|
||||
scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
||||
}
|
||||
|
||||
func allowsTenantAPIKeyAdmin(scope types.TenantAPIKeyScope) bool {
|
||||
scope = scope.Normalize()
|
||||
return len(scope.Scopes) == 0 || scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
||||
return scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
||||
}
|
||||
|
||||
func isTenantAPIKeyReadUnsafePath(method, path string) bool {
|
||||
|
||||
@@ -14,10 +14,10 @@ func TestTenantAPIKeyScopeReadOnlyAllowsSafeMethods(t *testing.T) {
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
||||
})
|
||||
|
||||
if err := authorizeTenantAPIKeyOperation(ctx, http.MethodGet); err != nil {
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
|
||||
t.Fatalf("read scoped key should allow GET: %v", err)
|
||||
}
|
||||
if err := authorizeTenantAPIKeyOperation(ctx, http.MethodHead); err != nil {
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodHead, "/api/v1/knowledge-bases"); err != nil {
|
||||
t.Fatalf("read scoped key should allow HEAD: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -27,9 +27,12 @@ func TestTenantAPIKeyScopeReadOnlyRejectsUnsafeMethods(t *testing.T) {
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
||||
})
|
||||
|
||||
if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("read scoped key POST error = %v, want errTenantAPIKeyScopeForbidden", err)
|
||||
}
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodDelete, "/api/v1/knowledge-bases/kb-1"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("read scoped key DELETE error = %v, want errTenantAPIKeyScopeForbidden", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyScopeReadOnlyAllowsSemanticReadPost(t *testing.T) {
|
||||
@@ -37,7 +40,7 @@ func TestTenantAPIKeyScopeReadOnlyAllowsSemanticReadPost(t *testing.T) {
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
||||
})
|
||||
|
||||
if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/knowledge-search"); err != nil {
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-search"); err != nil {
|
||||
t.Fatalf("read scoped key should allow semantic read POST: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -60,7 +63,7 @@ func TestTenantAPIKeyRouteRejectsAPIKeyManagement(t *testing.T) {
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
|
||||
})
|
||||
|
||||
err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/tenants/1/api-keys")
|
||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/tenants/1/api-keys")
|
||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("api key management error = %v, want errTenantAPIKeyScopeForbidden", err)
|
||||
}
|
||||
@@ -72,7 +75,7 @@ func TestTenantAPIKeyRouteRejectsTenantWriteForKnowledgeRestrictedKey(t *testing
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
})
|
||||
|
||||
err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/tenants/kv/theme")
|
||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme")
|
||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err)
|
||||
}
|
||||
@@ -83,7 +86,7 @@ func TestTenantAPIKeyRouteRejectsTenantWriteForWriteScope(t *testing.T) {
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
|
||||
})
|
||||
|
||||
err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/tenants/1")
|
||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/1")
|
||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err)
|
||||
}
|
||||
@@ -94,7 +97,7 @@ func TestTenantAPIKeyRouteAllowsTenantWriteForAdminScope(t *testing.T) {
|
||||
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
|
||||
})
|
||||
|
||||
if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); err != nil {
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); err != nil {
|
||||
t.Fatalf("admin scoped key should allow tenant management route: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -105,7 +108,7 @@ func TestTenantAPIKeyRouteAllowsKnowledgeWriteForKnowledgeRestrictedKey(t *testi
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
})
|
||||
|
||||
if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/knowledge-bases/kb-1"); err != nil {
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/knowledge-bases/kb-1"); err != nil {
|
||||
t.Fatalf("scoped knowledge write should pass route layer: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -116,8 +119,21 @@ func TestTenantAPIKeyRouteRejectsCrossKnowledgeBatchWriteForKnowledgeRestrictedK
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
})
|
||||
|
||||
err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/knowledge/batch-delete")
|
||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge/batch-delete")
|
||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("batch write error = %v, want errTenantAPIKeyScopeForbidden", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyScopeEmptyScopesDefaultToReadOnly(t *testing.T) {
|
||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||
Scopes: types.StringArray{},
|
||||
})
|
||||
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||
t.Fatalf("empty scopes should default to read-only, got %v", err)
|
||||
}
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
|
||||
t.Fatalf("empty scopes should allow GET: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
+49
-48
@@ -212,54 +212,9 @@ func Auth(
|
||||
apiKey := c.GetHeader("X-API-Key")
|
||||
if apiKey != "" {
|
||||
if apiKeyService != nil {
|
||||
if key, err := apiKeyService.AuthenticateAPIKey(c.Request.Context(), apiKey); err == nil && key != nil {
|
||||
attachAPIKeyAuthContext(c, tenantService, userService, key.TenantID, key)
|
||||
if c.IsAborted() {
|
||||
return
|
||||
}
|
||||
if err := authorizeTenantAPIKeyOperation(c.Request.Context(), c.Request.Method); err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if err := authorizeTenantAPIKeyRoute(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this route"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if authenticateAPIKeyRequest(c, tenantService, userService, apiKeyService, apiKey) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
tenantID, err := tenantService.ExtractTenantIDFromAPIKey(apiKey)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key format",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if key, err := apiKeyService.AuthenticateTenantAPIKey(
|
||||
c.Request.Context(), tenantID, apiKey,
|
||||
); err == nil && key != nil {
|
||||
attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key)
|
||||
if c.IsAborted() {
|
||||
return
|
||||
}
|
||||
if err := authorizeTenantAPIKeyOperation(c.Request.Context(), c.Request.Method); err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if err := authorizeTenantAPIKeyRoute(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this route"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -274,6 +229,45 @@ func Auth(
|
||||
}
|
||||
}
|
||||
|
||||
func authenticateAPIKeyRequest(
|
||||
c *gin.Context,
|
||||
tenantService interfaces.TenantService,
|
||||
userService interfaces.UserService,
|
||||
apiKeyService interfaces.TenantAPIKeyService,
|
||||
apiKey string,
|
||||
) bool {
|
||||
ctx := c.Request.Context()
|
||||
var key *types.TenantAPIKey
|
||||
var tenantID uint64
|
||||
|
||||
if authenticated, err := apiKeyService.AuthenticateAPIKey(ctx, apiKey); err == nil && authenticated != nil {
|
||||
key = authenticated
|
||||
tenantID = key.TenantID
|
||||
} else if tenantIDFromKey, extractErr := tenantService.ExtractTenantIDFromAPIKey(apiKey); extractErr == nil {
|
||||
if authenticated, err := apiKeyService.AuthenticateTenantAPIKey(ctx, tenantIDFromKey, apiKey); err == nil && authenticated != nil {
|
||||
key = authenticated
|
||||
tenantID = tenantIDFromKey
|
||||
}
|
||||
}
|
||||
|
||||
if key == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key"})
|
||||
c.Abort()
|
||||
return false
|
||||
}
|
||||
|
||||
attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key)
|
||||
if c.IsAborted() {
|
||||
return false
|
||||
}
|
||||
if err := authorizeTenantAPIKeyAccess(ctx, c.Request.Method, c.Request.URL.Path); err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"})
|
||||
c.Abort()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func attachAPIKeyAuthContext(
|
||||
c *gin.Context,
|
||||
tenantService interfaces.TenantService,
|
||||
@@ -317,12 +311,19 @@ func attachAPIKeyAuthContext(
|
||||
return
|
||||
}
|
||||
c.Set(types.PrincipalContextKey.String(), principal)
|
||||
c.Set(types.TenantRoleContextKey.String(), types.TenantRoleAdmin)
|
||||
apiKeyRole := types.TenantRoleViewer
|
||||
if key != nil {
|
||||
apiKeyRole = types.TenantAPIKeyScope{
|
||||
Scopes: key.Scopes,
|
||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||
}.TenantRole()
|
||||
}
|
||||
c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
|
||||
c.Set(types.SystemAdminContextKey.String(), false)
|
||||
ctx = context.WithValue(ctx, types.UserContextKey, user)
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
|
||||
ctx = types.WithPrincipal(ctx, principal)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyRole)
|
||||
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
|
||||
if key != nil {
|
||||
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
|
||||
|
||||
@@ -161,10 +161,6 @@ func (f *fakeTenantService) ListTenants(ctx context.Context) ([]*types.Tenant, e
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeTenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (f *fakeTenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user