Files
Enterprise-Knowledge-Base/internal/application/repository/tenant_api_key.go
T
wizardchen d2ffc1b973 refactor(api-keys): simplify authorization to a single-role gate
Redesign tenant API key authorization around one dimension (role) plus a
central default-deny gate, replacing the previous role + KB-scoped flag model.

- Add APIKeyGate as the single authority for API-key authorization: routes
  declare one policy (MinRole) via apiKeyGroup/apiKeyRoute helpers; undeclared
  routes are denied by default. JWT principals short-circuit the gate and the
  JWT-centric RBAC guards short-circuit for API-key principals.
- Roles: viewer/contributor/admin are knowledge-base data-plane only (KB scope
  is a pure downstream data filter); owner is a full-access tenant tier that
  unlocks tenant-level infrastructure routes and is required for every method.
- Drop the KBScoped policy flag and the KB-restricted-vs-tenant branching.
- Security hardening: never disclose HMAC secret (return presence only), abort
  writes on API-key encryption failure, deny KB-restricted keys on /files, and
  backfill legacy key hashes at startup instead of O(N) plaintext scans.
- Frontend: two-level create dialog (access type -> permission level), rename
  role labels to reflect actual scope, sync en/zh/ko/ru locales.
- Fix startup self-check false-positive on trailing-slash routes and normalize
  gin paths before comparison; add regression tests.
2026-07-07 12:00:13 +08:00

104 lines
3.1 KiB
Go

package repository
import (
"context"
"errors"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var ErrTenantAPIKeyNotFound = errors.New("tenant api key not found")
type tenantAPIKeyRepository struct {
db *gorm.DB
}
func NewTenantAPIKeyRepository(db *gorm.DB) interfaces.TenantAPIKeyRepository {
return &tenantAPIKeyRepository{db: db}
}
func (r *tenantAPIKeyRepository) CreateAPIKey(ctx context.Context, key *types.TenantAPIKey) error {
return r.db.WithContext(ctx).Create(key).Error
}
func (r *tenantAPIKeyRepository) GetAPIKeyByHash(ctx context.Context, hash string) (*types.TenantAPIKey, error) {
var key types.TenantAPIKey
err := r.db.WithContext(ctx).Session(&gorm.Session{SkipHooks: true}).
Where("key_hash = ?", hash).
First(&key).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrTenantAPIKeyNotFound
}
if err != nil {
return nil, err
}
return &key, nil
}
func (r *tenantAPIKeyRepository) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
var keys []*types.TenantAPIKey
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND revoked_at IS NULL", tenantID).
Order("created_at DESC").
Find(&keys).Error
return keys, err
}
func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {
now := time.Now()
res := r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
Where("id = ? AND tenant_id = ? AND revoked_at IS NULL", id, tenantID).
Update("revoked_at", &now)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrTenantAPIKeyNotFound
}
return nil
}
func (r *tenantAPIKeyRepository) RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error {
now := time.Now()
return r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
Where("tenant_id = ? AND revoked_at IS NULL", tenantID).
Update("revoked_at", &now).Error
}
func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error {
return r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
Where("id = ? AND revoked_at IS NULL", id).
Update("key_hash", hash).Error
}
// placeholderKeyHashPrefix mirrors the value written by migration
// 000065_tenant_api_keys.up.sql ('migrated-tenant-' || id). Rows still
// carrying it have never been authenticated since the upgrade, so their
// key_hash is not the real SHA-256 of the API key yet.
const placeholderKeyHashPrefix = "migrated-tenant-"
func (r *tenantAPIKeyRepository) ListKeysWithPlaceholderHash(
ctx context.Context,
) ([]*types.TenantAPIKey, error) {
var keys []*types.TenantAPIKey
// AfterFind decrypts api_key, so callers get the plaintext token needed
// to compute the real hash.
err := r.db.WithContext(ctx).
Where("key_hash LIKE ? AND revoked_at IS NULL", placeholderKeyHashPrefix+"%").
Find(&keys).Error
return keys, err
}
func (r *tenantAPIKeyRepository) UpdateAPIKeyLastUsed(ctx context.Context, id uint64, at time.Time) error {
return r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
Where("id = ? AND revoked_at IS NULL", id).
Update("last_used_at", &at).Error
}