refactor(api-keys): use role field and route-level API key guards
Replace scopes JSON with a viewer/contributor/admin role column, move unsafe-method authorization from path-prefix middleware to declarative APIKey* guards on routes, and close remaining KB-scope gaps in handlers.
This commit is contained in:
@@ -67,7 +67,7 @@ type TenantRepository interface {
|
||||
type TenantAPIKeyCreateRequest struct {
|
||||
TenantID uint64
|
||||
Name string
|
||||
Scopes []string
|
||||
Role types.TenantRole
|
||||
KnowledgeBaseIDs []string
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
@@ -6,16 +6,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
TenantAPIKeyScopeRead = "read"
|
||||
TenantAPIKeyScopeWrite = "write"
|
||||
TenantAPIKeyScopeAdmin = "admin"
|
||||
)
|
||||
|
||||
// TenantAPIKey is a revocable, per-tenant API key. KeyHash is used for
|
||||
// authentication lookup; APIKey is stored encrypted when SYSTEM_AES_KEY is set
|
||||
// and returned by owner-only management APIs.
|
||||
@@ -25,7 +20,7 @@ type TenantAPIKey struct {
|
||||
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
||||
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
|
||||
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
|
||||
Scopes StringArray `json:"scopes" gorm:"type:jsonb;not null;default:'[]'"`
|
||||
Role TenantRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
@@ -59,7 +54,7 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
|
||||
// TenantAPIKeyScope is the request-context projection used by middleware.
|
||||
type TenantAPIKeyScope struct {
|
||||
KeyID uint64
|
||||
Scopes StringArray
|
||||
Role TenantRole
|
||||
KnowledgeBaseIDs StringArray
|
||||
}
|
||||
|
||||
@@ -81,36 +76,27 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
|
||||
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
|
||||
return TenantAPIKeyScope{
|
||||
KeyID: s.KeyID,
|
||||
Scopes: normalizeScopeArray(s.Scopes),
|
||||
Role: NormalizeTenantAPIKeyRole(s.Role),
|
||||
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
|
||||
}
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) HasScope(scope string) bool {
|
||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
||||
if scope == "" {
|
||||
return false
|
||||
// NormalizeTenantAPIKeyRole maps stored/API role strings to tenant RBAC roles.
|
||||
func NormalizeTenantAPIKeyRole(role TenantRole) TenantRole {
|
||||
switch strings.ToLower(strings.TrimSpace(string(role))) {
|
||||
case string(TenantRoleAdmin):
|
||||
return TenantRoleAdmin
|
||||
case string(TenantRoleContributor):
|
||||
return TenantRoleContributor
|
||||
case string(TenantRoleViewer), "":
|
||||
return TenantRoleViewer
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
for _, item := range s.Normalize().Scopes {
|
||||
if item == scope {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TenantRole maps API-key scopes to the tenant RBAC role carried in request
|
||||
// context. Admin scope -> Admin; write -> Contributor; read-only -> Viewer.
|
||||
func (s TenantAPIKeyScope) TenantRole() TenantRole {
|
||||
s = s.Normalize()
|
||||
switch {
|
||||
case s.HasScope(TenantAPIKeyScopeAdmin):
|
||||
return TenantRoleAdmin
|
||||
case s.HasScope(TenantAPIKeyScopeWrite):
|
||||
return TenantRoleContributor
|
||||
default:
|
||||
return TenantRoleViewer
|
||||
}
|
||||
return s.Normalize().Role
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
|
||||
@@ -150,26 +136,6 @@ func (s TenantAPIKeyScope) AllowsKnowledgeBases(kbIDs []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func normalizeScopeArray(in StringArray) StringArray {
|
||||
out := make(StringArray, 0, len(in))
|
||||
seen := map[string]struct{}{}
|
||||
for _, item := range in {
|
||||
item = strings.TrimSpace(strings.ToLower(item))
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[item]; ok {
|
||||
continue
|
||||
}
|
||||
seen[item] = struct{}{}
|
||||
out = append(out, item)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
out = StringArray{TenantAPIKeyScopeRead}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeIDArray(in StringArray) StringArray {
|
||||
out := make(StringArray, 0, len(in))
|
||||
seen := map[string]struct{}{}
|
||||
@@ -186,3 +152,75 @@ func normalizeIDArray(in StringArray) StringArray {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AuthorizeTenantAPIKeyKnowledgeBases rejects KB-restricted API key callers that
|
||||
// target one or more knowledge bases outside their allow-list.
|
||||
func AuthorizeTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) error {
|
||||
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
return nil
|
||||
}
|
||||
if !scope.AllowsKnowledgeBases(kbIDs) {
|
||||
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthorizeTenantAPIKeyKnowledgeTargets rejects KB-restricted API key callers
|
||||
// that reference knowledge_ids without a verified KB binding, or kb_ids outside
|
||||
// the allow-list.
|
||||
func AuthorizeTenantAPIKeyKnowledgeTargets(ctx context.Context, kbIDs, knowledgeIDs []string) error {
|
||||
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
return nil
|
||||
}
|
||||
if len(knowledgeIDs) > 0 {
|
||||
return errors.NewForbiddenError("API key scope does not allow knowledge_ids without a verified knowledge base")
|
||||
}
|
||||
if !scope.AllowsKnowledgeBases(kbIDs) {
|
||||
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthorizeTenantAPIKeyOptionalTagIDs rejects tag_ids for KB-restricted keys
|
||||
// because tag resolution can pull documents from arbitrary knowledge bases.
|
||||
func AuthorizeTenantAPIKeyOptionalTagIDs(ctx context.Context, tagIDs []string) error {
|
||||
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
return nil
|
||||
}
|
||||
if len(tagIDs) > 0 {
|
||||
return errors.NewForbiddenError("API key scope does not allow tag_ids without a verified knowledge base")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FilterKnowledgeBasesForTenantAPIKeyScope intersects resolved KB IDs with the
|
||||
// API key allow-list. When the caller supplied explicit kb_ids, every ID must
|
||||
// be allowed; implicit agent defaults are intersected instead of rejected.
|
||||
func FilterKnowledgeBasesForTenantAPIKeyScope(
|
||||
ctx context.Context, requestedKBIDs, resolvedKBIDs []string,
|
||||
) ([]string, error) {
|
||||
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
return resolvedKBIDs, nil
|
||||
}
|
||||
if len(requestedKBIDs) > 0 {
|
||||
if !scope.AllowsKnowledgeBases(requestedKBIDs) {
|
||||
return nil, errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||
}
|
||||
return resolvedKBIDs, nil
|
||||
}
|
||||
allowed := make(map[string]struct{}, len(scope.KnowledgeBaseIDs))
|
||||
for _, id := range scope.KnowledgeBaseIDs {
|
||||
allowed[id] = struct{}{}
|
||||
}
|
||||
filtered := make([]string, 0, len(resolvedKBIDs))
|
||||
for _, id := range resolvedKBIDs {
|
||||
if _, ok := allowed[id]; ok {
|
||||
filtered = append(filtered, id)
|
||||
}
|
||||
}
|
||||
return filtered, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAuthorizeTenantAPIKeyKnowledgeTargetsRejectsKnowledgeIDs(t *testing.T) {
|
||||
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||
})
|
||||
err := AuthorizeTenantAPIKeyKnowledgeTargets(ctx, []string{"kb-1"}, []string{"doc-1"})
|
||||
if err == nil {
|
||||
t.Fatal("expected forbidden when knowledge_ids supplied under KB-restricted key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeTenantAPIKeyOptionalTagIDsRejectsTags(t *testing.T) {
|
||||
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||
})
|
||||
err := AuthorizeTenantAPIKeyOptionalTagIDs(ctx, []string{"tag-1"})
|
||||
if err == nil {
|
||||
t.Fatal("expected forbidden when tag_ids supplied under KB-restricted key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterKnowledgeBasesForTenantAPIKeyScopeIntersectsAgentDefaults(t *testing.T) {
|
||||
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: StringArray{"kb-1", "kb-2"},
|
||||
})
|
||||
got, err := FilterKnowledgeBasesForTenantAPIKeyScope(ctx, nil, []string{"kb-2", "kb-3"})
|
||||
if err != nil {
|
||||
t.Fatalf("FilterKnowledgeBasesForTenantAPIKeyScope returned error: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0] != "kb-2" {
|
||||
t.Fatalf("filtered = %#v, want only kb-2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterKnowledgeBasesForTenantAPIKeyScopeRejectsExplicitOutOfScope(t *testing.T) {
|
||||
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||
})
|
||||
_, err := FilterKnowledgeBasesForTenantAPIKeyScope(ctx, []string{"kb-1", "kb-2"}, []string{"kb-1", "kb-2"})
|
||||
if err == nil {
|
||||
t.Fatal("expected forbidden for explicit out-of-scope kb_ids")
|
||||
}
|
||||
}
|
||||
@@ -2,30 +2,38 @@ package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTenantAPIKeyScopeNormalizeDefaultsEmptyScopesToRead(t *testing.T) {
|
||||
scope := TenantAPIKeyScope{Scopes: StringArray{}}.Normalize()
|
||||
if len(scope.Scopes) != 1 || scope.Scopes[0] != TenantAPIKeyScopeRead {
|
||||
t.Fatalf("normalized scopes = %v, want [read]", scope.Scopes)
|
||||
func TestTenantAPIKeyScopeNormalizeDefaultsEmptyRoleToViewer(t *testing.T) {
|
||||
scope := TenantAPIKeyScope{Role: ""}.Normalize()
|
||||
if scope.Role != TenantRoleViewer {
|
||||
t.Fatalf("normalized role = %q, want viewer", scope.Role)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyScopeTenantRoleMapping(t *testing.T) {
|
||||
func TestNormalizeTenantAPIKeyRole(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in StringArray
|
||||
in TenantRole
|
||||
want TenantRole
|
||||
}{
|
||||
{name: "read", in: StringArray{TenantAPIKeyScopeRead}, want: TenantRoleViewer},
|
||||
{name: "write", in: StringArray{TenantAPIKeyScopeWrite}, want: TenantRoleContributor},
|
||||
{name: "admin", in: StringArray{TenantAPIKeyScopeAdmin}, want: TenantRoleAdmin},
|
||||
{name: "empty defaults read", in: StringArray{}, want: TenantRoleViewer},
|
||||
{name: "viewer", in: TenantRoleViewer, want: TenantRoleViewer},
|
||||
{name: "contributor", in: TenantRoleContributor, want: TenantRoleContributor},
|
||||
{name: "admin", in: TenantRoleAdmin, want: TenantRoleAdmin},
|
||||
{name: "empty defaults viewer", in: "", want: TenantRoleViewer},
|
||||
{name: "invalid", in: "owner", want: ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := TenantAPIKeyScope{Scopes: tt.in}.TenantRole()
|
||||
got := NormalizeTenantAPIKeyRole(tt.in)
|
||||
if got != tt.want {
|
||||
t.Fatalf("TenantRole() = %q, want %q", got, tt.want)
|
||||
t.Fatalf("NormalizeTenantAPIKeyRole(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyScopeTenantRole(t *testing.T) {
|
||||
got := TenantAPIKeyScope{Role: TenantRoleContributor}.TenantRole()
|
||||
if got != TenantRoleContributor {
|
||||
t.Fatalf("TenantRole() = %q, want contributor", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user