feat: add scoped tenant api keys
This commit is contained in:
@@ -18,6 +18,8 @@ const (
|
||||
UserIDContextKey ContextKey = "UserID"
|
||||
// PrincipalContextKey is the context key for the terminal caller principal.
|
||||
PrincipalContextKey ContextKey = "Principal"
|
||||
// TenantAPIKeyScopeContextKey carries per-API-key operation and KB scopes.
|
||||
TenantAPIKeyScopeContextKey ContextKey = "TenantAPIKeyScope"
|
||||
// TenantRoleContextKey is the context key for the caller's TenantRole
|
||||
// in the currently active tenant (loaded by the auth middleware from
|
||||
// the tenant_members table). See TenantRoleFromContext.
|
||||
|
||||
@@ -2,6 +2,7 @@ package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
@@ -64,3 +65,34 @@ type TenantRepository interface {
|
||||
// BulkSetStorageQuota — see TenantService.BulkSetStorageQuota.
|
||||
BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error)
|
||||
}
|
||||
|
||||
type TenantAPIKeyCreateRequest struct {
|
||||
TenantID uint64
|
||||
Name string
|
||||
Scopes []string
|
||||
KnowledgeBaseIDs []string
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
type TenantAPIKeyCreateResult struct {
|
||||
APIKey *types.TenantAPIKey
|
||||
Token string
|
||||
}
|
||||
|
||||
type TenantAPIKeyRepository interface {
|
||||
CreateAPIKey(ctx context.Context, key *types.TenantAPIKey) error
|
||||
GetAPIKeyByHash(ctx context.Context, hash string) (*types.TenantAPIKey, error)
|
||||
ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)
|
||||
RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error
|
||||
UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error
|
||||
UpdateAPIKeyLastUsed(ctx context.Context, id uint64, at time.Time) error
|
||||
}
|
||||
|
||||
type TenantAPIKeyService interface {
|
||||
CreateAPIKey(ctx context.Context, req TenantAPIKeyCreateRequest) (*TenantAPIKeyCreateResult, error)
|
||||
AuthenticateAPIKey(ctx context.Context, token string) (*types.TenantAPIKey, error)
|
||||
AuthenticateTenantAPIKey(ctx context.Context, tenantID uint64, token string) (*types.TenantAPIKey, error)
|
||||
EnsureTenantAPIKey(ctx context.Context, tenantID uint64, apiKey string) error
|
||||
ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)
|
||||
RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error
|
||||
}
|
||||
|
||||
@@ -90,8 +90,6 @@ type Tenant struct {
|
||||
Name string `yaml:"name" json:"name"`
|
||||
// Description
|
||||
Description string `yaml:"description" json:"description"`
|
||||
// API key
|
||||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
// Status
|
||||
Status string `yaml:"status" json:"status" gorm:"default:'active'"`
|
||||
// Retriever engines
|
||||
@@ -147,31 +145,6 @@ func (t *Tenant) BeforeCreate(tx *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeforeSave encrypts APIKey before persisting to database.
|
||||
// Uses tx.Statement.SetColumn to avoid polluting the in-memory struct.
|
||||
func (t *Tenant) BeforeSave(tx *gorm.DB) error {
|
||||
if key := utils.GetAESKey(); key != nil && t.APIKey != "" {
|
||||
if encrypted, err := utils.EncryptAESGCM(t.APIKey, key); err == nil {
|
||||
tx.Statement.SetColumn("api_key", encrypted)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AfterFind decrypts APIKey after loading from database.
|
||||
// Legacy plaintext (without enc:v1: prefix) is returned as-is. When the value
|
||||
// is encrypted but SYSTEM_AES_KEY is missing/rotated and the data cannot be
|
||||
// decrypted, the error is propagated so the read fails loudly instead of
|
||||
// returning ciphertext to callers.
|
||||
func (t *Tenant) AfterFind(tx *gorm.DB) error {
|
||||
decrypted, err := utils.DecryptStoredSecret(t.APIKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt tenants.api_key (id=%d): %w", t.ID, err)
|
||||
}
|
||||
t.APIKey = decrypted
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface, used to convert RetrieverEngines to database value
|
||||
func (c RetrieverEngines) Value() (driver.Value, error) {
|
||||
return json.Marshal(c)
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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.
|
||||
type TenantAPIKey struct {
|
||||
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
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:'[]'"`
|
||||
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"`
|
||||
}
|
||||
|
||||
func (TenantAPIKey) TableName() string {
|
||||
return "tenant_api_keys"
|
||||
}
|
||||
|
||||
func (k *TenantAPIKey) BeforeSave(tx *gorm.DB) error {
|
||||
if key := utils.GetAESKey(); key != nil && k.APIKey != "" {
|
||||
if encrypted, err := utils.EncryptAESGCM(k.APIKey, key); err == nil {
|
||||
tx.Statement.SetColumn("api_key", encrypted)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
|
||||
decrypted, err := utils.DecryptStoredSecret(k.APIKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt tenant_api_keys.api_key (id=%d): %w", k.ID, err)
|
||||
}
|
||||
k.APIKey = decrypted
|
||||
return nil
|
||||
}
|
||||
|
||||
// TenantAPIKeyScope is the request-context projection used by middleware.
|
||||
type TenantAPIKeyScope struct {
|
||||
KeyID uint64
|
||||
Scopes StringArray
|
||||
KnowledgeBaseIDs StringArray
|
||||
}
|
||||
|
||||
func WithTenantAPIKeyScope(ctx context.Context, scope TenantAPIKeyScope) context.Context {
|
||||
return context.WithValue(ctx, TenantAPIKeyScopeContextKey, scope.Normalize())
|
||||
}
|
||||
|
||||
func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool) {
|
||||
if ctx == nil {
|
||||
return TenantAPIKeyScope{}, false
|
||||
}
|
||||
scope, ok := ctx.Value(TenantAPIKeyScopeContextKey).(TenantAPIKeyScope)
|
||||
if !ok {
|
||||
return TenantAPIKeyScope{}, false
|
||||
}
|
||||
return scope.Normalize(), true
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
|
||||
return TenantAPIKeyScope{
|
||||
KeyID: s.KeyID,
|
||||
Scopes: normalizeScopeArray(s.Scopes),
|
||||
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
|
||||
}
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) HasScope(scope string) bool {
|
||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
||||
if scope == "" {
|
||||
return false
|
||||
}
|
||||
for _, item := range s.Normalize().Scopes {
|
||||
if item == scope {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) AllowsUnsafeOperation() bool {
|
||||
s = s.Normalize()
|
||||
if len(s.Scopes) == 0 {
|
||||
return true
|
||||
}
|
||||
return s.HasScope(TenantAPIKeyScopeWrite) || s.HasScope(TenantAPIKeyScopeAdmin)
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
|
||||
kbID = strings.TrimSpace(kbID)
|
||||
if kbID == "" {
|
||||
return false
|
||||
}
|
||||
s = s.Normalize()
|
||||
if len(s.KnowledgeBaseIDs) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, allowed := range s.KnowledgeBaseIDs {
|
||||
if allowed == kbID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) IsKnowledgeBaseRestricted() bool {
|
||||
return len(s.Normalize().KnowledgeBaseIDs) > 0
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) AllowsKnowledgeBases(kbIDs []string) bool {
|
||||
s = s.Normalize()
|
||||
if len(s.KnowledgeBaseIDs) == 0 {
|
||||
return true
|
||||
}
|
||||
if len(kbIDs) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, kbID := range kbIDs {
|
||||
if !s.AllowsKnowledgeBase(kbID) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeIDArray(in StringArray) StringArray {
|
||||
out := make(StringArray, 0, len(in))
|
||||
seen := map[string]struct{}{}
|
||||
for _, item := range in {
|
||||
item = strings.TrimSpace(item)
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[item]; ok {
|
||||
continue
|
||||
}
|
||||
seen[item] = struct{}{}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user