Refine scoped API key capabilities

This commit is contained in:
wizardchen
2026-07-07 11:09:10 +08:00
committed by lyingbug
parent b5cc7d2a28
commit 2c6f082062
38 changed files with 1718 additions and 655 deletions
+2 -1
View File
@@ -65,8 +65,9 @@ type TenantRepository interface {
type TenantAPIKeyCreateRequest struct {
TenantID uint64
Name string
Role types.TenantRole
FullAccess bool
KnowledgeBaseIDs []string
Capabilities []string
ExpiresAt *time.Time
}
+152 -27
View File
@@ -20,19 +20,148 @@ 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:''"`
Role TenantRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
FullAccess bool `json:"full_access" gorm:"not null;default:false"`
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"`
RevokedAt *time.Time `json:"revoked_at,omitempty" gorm:"index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Capabilities are bounded grants for non-full-access keys. Each
// capability maps to an integration persona (retrieval, chat, ingest,
// tenant infrastructure management, and history access). KB scoping
// (KnowledgeBaseIDs) still applies on top where a route targets knowledge
// bases.
Capabilities StringArray `json:"capabilities" gorm:"type:jsonb;not null;default:'[]'"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
RevokedAt *time.Time `json:"revoked_at,omitempty" gorm:"index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (TenantAPIKey) TableName() string {
return "tenant_api_keys"
}
// APIKeyCapability is a bounded grant on a tenant API key. See
// TenantAPIKey.Capabilities.
type APIKeyCapability string
const (
// APIKeyCapabilityRetrieve lets a key read and search knowledge-base data
// within its allowed KB scope without granting chat or content writes.
APIKeyCapabilityRetrieve APIKeyCapability = "retrieve"
// APIKeyCapabilityChat lets a scoped key run the conversation flow
// (sessions + agent listing + self identity) without granting broader
// tenant management access.
APIKeyCapabilityChat APIKeyCapability = "chat"
// APIKeyCapabilityReadAgents lets a scoped key list and inspect agents
// without allowing chat sessions or agent authoring.
APIKeyCapabilityReadAgents APIKeyCapability = "read_agents"
// APIKeyCapabilityIngest lets a key write content into its allowed
// knowledge bases (upload documents, edit chunks/FAQ/tags/wiki). It only
// lifts the content-write routes: it never allows creating new knowledge
// bases or agents, nor destructive KB clears, and the key's
// knowledge_base_ids allow-list still bounds every write.
APIKeyCapabilityIngest APIKeyCapability = "ingest"
// APIKeyCapabilityManageKnowledgeBases lets a scoped key manage existing
// knowledge-base metadata/configuration within its allowed KB scope. It is
// separate from ingest: uploading or editing KB contents does not imply
// permission to rename, reconfigure, or delete the KB itself.
APIKeyCapabilityManageKnowledgeBases APIKeyCapability = "manage_kbs"
// APIKeyCapabilityManageAgents lets a key create/read/update/delete/copy
// agents. Agent config can carry sensitive model/MCP bindings, so this is
// opt-in and off by default.
APIKeyCapabilityManageAgents APIKeyCapability = "manage_agents"
// APIKeyCapabilityMessageHistory lets a key search and inspect the
// tenant-level chat-history knowledge base without granting full Owner
// access. It is separate from chat: chat only covers the caller's own
// live conversation flow, while message_history can expose historical
// messages across the tenant.
APIKeyCapabilityMessageHistory APIKeyCapability = "message_history"
// APIKeyCapabilityManageModels lets a key manage tenant model
// definitions, credentials, model checks, and WeKnoraCloud credentials.
APIKeyCapabilityManageModels APIKeyCapability = "manage_models"
// APIKeyCapabilityManageMCPServices lets a key manage tenant MCP service
// definitions, credentials, tool policies, and per-principal OAuth state.
APIKeyCapabilityManageMCPServices APIKeyCapability = "manage_mcp_services"
// APIKeyCapabilityManageDataSources lets a key manage data-source
// connectors and sync jobs. KB scoping applies to data sources bound to a
// knowledge base.
APIKeyCapabilityManageDataSources APIKeyCapability = "manage_datasources"
// APIKeyCapabilityManageChannels lets a key manage embed and IM channel
// integrations for agents.
APIKeyCapabilityManageChannels APIKeyCapability = "manage_channels"
// APIKeyCapabilityManageVectorStores lets a key manage retrieval
// infrastructure such as vector stores, parser engines, and storage checks.
APIKeyCapabilityManageVectorStores APIKeyCapability = "manage_vector_stores"
// APIKeyCapabilityManageWebSearch lets a key manage tenant web-search
// provider configurations and credentials.
APIKeyCapabilityManageWebSearch APIKeyCapability = "manage_web_search"
// APIKeyCapabilityRunEvaluations lets a key run and inspect evaluation
// jobs without full tenant ownership.
APIKeyCapabilityRunEvaluations APIKeyCapability = "run_evaluations"
// APIKeyCapabilityManageTenantSettings lets a key read and update
// tenant-scoped integration settings exposed under /tenants, such as API
// principal mode, request headers, and tenant KV. It does not include API
// key management, member management, tenant deletion, or ownership transfer.
APIKeyCapabilityManageTenantSettings APIKeyCapability = "manage_tenant_settings"
)
// NormalizeAPIKeyCapability maps an input capability string to a known
// capability, returning "" for anything unrecognised so callers can drop it.
func NormalizeAPIKeyCapability(c APIKeyCapability) APIKeyCapability {
switch APIKeyCapability(strings.ToLower(strings.TrimSpace(string(c)))) {
case APIKeyCapabilityRetrieve:
return APIKeyCapabilityRetrieve
case APIKeyCapabilityChat:
return APIKeyCapabilityChat
case APIKeyCapabilityReadAgents:
return APIKeyCapabilityReadAgents
case APIKeyCapabilityIngest:
return APIKeyCapabilityIngest
case APIKeyCapabilityManageKnowledgeBases:
return APIKeyCapabilityManageKnowledgeBases
case APIKeyCapabilityManageAgents:
return APIKeyCapabilityManageAgents
case APIKeyCapabilityMessageHistory:
return APIKeyCapabilityMessageHistory
case APIKeyCapabilityManageModels:
return APIKeyCapabilityManageModels
case APIKeyCapabilityManageMCPServices:
return APIKeyCapabilityManageMCPServices
case APIKeyCapabilityManageDataSources:
return APIKeyCapabilityManageDataSources
case APIKeyCapabilityManageChannels:
return APIKeyCapabilityManageChannels
case APIKeyCapabilityManageVectorStores:
return APIKeyCapabilityManageVectorStores
case APIKeyCapabilityManageWebSearch:
return APIKeyCapabilityManageWebSearch
case APIKeyCapabilityRunEvaluations:
return APIKeyCapabilityRunEvaluations
case APIKeyCapabilityManageTenantSettings:
return APIKeyCapabilityManageTenantSettings
default:
return ""
}
}
// NormalizeAPIKeyCapabilities dedups and drops unknown capabilities.
func NormalizeAPIKeyCapabilities(in StringArray) StringArray {
out := make(StringArray, 0, len(in))
seen := map[string]struct{}{}
for _, item := range in {
norm := NormalizeAPIKeyCapability(APIKeyCapability(item))
if norm == "" {
continue
}
s := string(norm)
if _, ok := seen[s]; ok {
continue
}
seen[s] = struct{}{}
out = append(out, s)
}
return out
}
func (k *TenantAPIKey) BeforeSave(tx *gorm.DB) error {
if key := utils.GetAESKey(); key != nil && k.APIKey != "" {
encrypted, err := utils.EncryptAESGCM(k.APIKey, key)
@@ -59,8 +188,9 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
// TenantAPIKeyScope is the request-context projection used by middleware.
type TenantAPIKeyScope struct {
KeyID uint64
Role TenantRole
FullAccess bool
KnowledgeBaseIDs StringArray
Capabilities StringArray
}
func WithTenantAPIKeyScope(ctx context.Context, scope TenantAPIKeyScope) context.Context {
@@ -81,29 +211,24 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
return TenantAPIKeyScope{
KeyID: s.KeyID,
Role: NormalizeTenantAPIKeyRole(s.Role),
FullAccess: s.FullAccess,
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
Capabilities: NormalizeAPIKeyCapabilities(s.Capabilities),
}
}
// NormalizeTenantAPIKeyRole maps stored/API role strings to tenant RBAC roles.
func NormalizeTenantAPIKeyRole(role TenantRole) TenantRole {
switch strings.ToLower(strings.TrimSpace(string(role))) {
case string(TenantRoleOwner):
return TenantRoleOwner
case string(TenantRoleAdmin):
return TenantRoleAdmin
case string(TenantRoleContributor):
return TenantRoleContributor
case string(TenantRoleViewer), "":
return TenantRoleViewer
default:
return ""
// HasCapability reports whether the scope carries the given additive grant.
func (s TenantAPIKeyScope) HasCapability(c APIKeyCapability) bool {
c = NormalizeAPIKeyCapability(c)
if c == "" {
return false
}
}
func (s TenantAPIKeyScope) TenantRole() TenantRole {
return s.Normalize().Role
for _, item := range NormalizeAPIKeyCapabilities(s.Capabilities) {
if item == string(c) {
return true
}
}
return false
}
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
@@ -167,7 +292,7 @@ func AuthorizeTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) e
if !ok || !scope.IsKnowledgeBaseRestricted() {
return nil
}
if !scope.AllowsKnowledgeBases(kbIDs) {
if len(kbIDs) > 0 && !scope.AllowsKnowledgeBases(kbIDs) {
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
}
return nil
@@ -184,7 +309,7 @@ func AuthorizeTenantAPIKeyKnowledgeTargets(ctx context.Context, kbIDs, knowledge
if len(knowledgeIDs) > 0 {
return errors.NewForbiddenError("API key scope does not allow knowledge_ids without a verified knowledge base")
}
if !scope.AllowsKnowledgeBases(kbIDs) {
if len(kbIDs) > 0 && !scope.AllowsKnowledgeBases(kbIDs) {
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
}
return nil
@@ -15,6 +15,16 @@ func TestAuthorizeTenantAPIKeyKnowledgeTargetsRejectsKnowledgeIDs(t *testing.T)
}
}
func TestAuthorizeTenantAPIKeyKnowledgeTargetsAllowsUnspecifiedTargets(t *testing.T) {
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
KnowledgeBaseIDs: StringArray{"kb-1"},
})
err := AuthorizeTenantAPIKeyKnowledgeTargets(ctx, nil, nil)
if err != nil {
t.Fatalf("expected unspecified targets to be allowed, got %v", err)
}
}
func TestAuthorizeTenantAPIKeyOptionalTagIDsRejectsTags(t *testing.T) {
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
KnowledgeBaseIDs: StringArray{"kb-1"},
@@ -47,3 +57,39 @@ func TestFilterKnowledgeBasesForTenantAPIKeyScopeRejectsExplicitOutOfScope(t *te
t.Fatal("expected forbidden for explicit out-of-scope kb_ids")
}
}
func TestScopeHasCapability(t *testing.T) {
s := TenantAPIKeyScope{Capabilities: StringArray{"chat"}}
if !s.HasCapability(APIKeyCapabilityChat) {
t.Fatal("expected chat capability to be present")
}
if (TenantAPIKeyScope{}).HasCapability(APIKeyCapabilityChat) {
t.Fatal("empty scope must not report chat capability")
}
// Unknown capability is never satisfied.
if s.HasCapability(APIKeyCapability("bogus")) {
t.Fatal("unknown capability must not be satisfied")
}
}
func TestNormalizeAPIKeyCapabilities(t *testing.T) {
got := NormalizeAPIKeyCapabilities(StringArray{
" Retrieve ",
"chat",
"read_agents",
"manage_kbs",
"message_history",
"manage_mcp_services",
"bogus",
"",
})
want := []string{"retrieve", "chat", "read_agents", "manage_kbs", "message_history", "manage_mcp_services"}
if len(got) != len(want) {
t.Fatalf("normalized = %#v, want %#v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("normalized = %#v, want %#v", got, want)
}
}
}
+20 -28
View File
@@ -2,39 +2,31 @@ package types
import "testing"
func TestTenantAPIKeyScopeNormalizeDefaultsEmptyRoleToViewer(t *testing.T) {
scope := TenantAPIKeyScope{Role: ""}.Normalize()
if scope.Role != TenantRoleViewer {
t.Fatalf("normalized role = %q, want viewer", scope.Role)
func TestTenantAPIKeyScopeNormalizePreservesFullAccess(t *testing.T) {
scope := TenantAPIKeyScope{FullAccess: true}.Normalize()
if !scope.FullAccess {
t.Fatal("normalized scope lost full access")
}
}
func TestNormalizeTenantAPIKeyRole(t *testing.T) {
tests := []struct {
name string
in TenantRole
want TenantRole
}{
{name: "viewer", in: TenantRoleViewer, want: TenantRoleViewer},
{name: "contributor", in: TenantRoleContributor, want: TenantRoleContributor},
{name: "admin", in: TenantRoleAdmin, want: TenantRoleAdmin},
{name: "owner", in: TenantRoleOwner, want: TenantRoleOwner},
{name: "empty defaults viewer", in: "", want: TenantRoleViewer},
{name: "invalid", in: "superuser", want: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NormalizeTenantAPIKeyRole(tt.in)
if got != tt.want {
t.Fatalf("NormalizeTenantAPIKeyRole(%q) = %q, want %q", tt.in, got, tt.want)
}
})
func TestTenantAPIKeyScopeNormalizeDefaultsToScopedAccess(t *testing.T) {
scope := TenantAPIKeyScope{}.Normalize()
if scope.FullAccess {
t.Fatal("empty scope must not become full access")
}
}
func TestTenantAPIKeyScopeTenantRole(t *testing.T) {
got := TenantAPIKeyScope{Role: TenantRoleContributor}.TenantRole()
if got != TenantRoleContributor {
t.Fatalf("TenantRole() = %q, want contributor", got)
func TestTenantAPIKeyScopeNormalizeDropsInvalidCapabilities(t *testing.T) {
scope := TenantAPIKeyScope{
Capabilities: StringArray{"chat", "bogus", "retrieve", "chat"},
}.Normalize()
want := StringArray{"chat", "retrieve"}
if len(scope.Capabilities) != len(want) {
t.Fatalf("capabilities = %#v, want %#v", scope.Capabilities, want)
}
for i := range want {
if scope.Capabilities[i] != want[i] {
t.Fatalf("capabilities = %#v, want %#v", scope.Capabilities, want)
}
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ type TenantRole string
const (
// TenantRoleOwner has full control over the tenant, including tenant
// deletion, ownership transfer, and rotating the tenant API key.
// deletion, ownership transfer, and managing tenant API keys.
TenantRoleOwner TenantRole = "owner"
// TenantRoleAdmin manages users, integrations, and tenant-scoped
// configuration such as model providers, vector stores, MCP services