Files
Enterprise-Knowledge-Base/internal/application/service/tenant_api_key_test.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

230 lines
6.4 KiB
Go

package service
import (
"context"
"errors"
"strings"
"testing"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type fakeTenantAPIKeyRepo struct {
byHash map[string]*types.TenantAPIKey
nextID uint64
}
func TestTenantAPIKeyServiceCreateAPIKeyUsesSKPrefix(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
result, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "integration",
Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
}
if !strings.HasPrefix(result.Token, "sk-") {
t.Fatalf("created token = %q, want sk- prefix", result.Token)
}
if result.APIKey.APIKey != result.Token {
t.Fatalf("created api_key = %q, want token %q", result.APIKey.APIKey, result.Token)
}
}
func newFakeTenantAPIKeyRepo() *fakeTenantAPIKeyRepo {
return &fakeTenantAPIKeyRepo{byHash: map[string]*types.TenantAPIKey{}, nextID: 1}
}
func (r *fakeTenantAPIKeyRepo) CreateAPIKey(_ context.Context, key *types.TenantAPIKey) error {
if _, ok := r.byHash[key.KeyHash]; ok {
return errors.New("duplicate key hash")
}
cp := *key
cp.ID = r.nextID
r.nextID++
r.byHash[cp.KeyHash] = &cp
key.ID = cp.ID
return nil
}
func (r *fakeTenantAPIKeyRepo) GetAPIKeyByHash(_ context.Context, hash string) (*types.TenantAPIKey, error) {
key, ok := r.byHash[hash]
if !ok {
return nil, apprepo.ErrTenantAPIKeyNotFound
}
cp := *key
return &cp, nil
}
func (r *fakeTenantAPIKeyRepo) ListAPIKeys(_ context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
out := []*types.TenantAPIKey{}
for _, key := range r.byHash {
if key.TenantID == tenantID && key.RevokedAt == nil {
cp := *key
out = append(out, &cp)
}
}
return out, nil
}
func (r *fakeTenantAPIKeyRepo) RevokeAPIKey(_ context.Context, tenantID uint64, id uint64) error {
now := time.Now()
for _, key := range r.byHash {
if key.ID == id && key.TenantID == tenantID && key.RevokedAt == nil {
key.RevokedAt = &now
return nil
}
}
return apprepo.ErrTenantAPIKeyNotFound
}
func (r *fakeTenantAPIKeyRepo) RevokeAllAPIKeys(_ context.Context, tenantID uint64) error {
now := time.Now()
for _, key := range r.byHash {
if key.TenantID == tenantID && key.RevokedAt == nil {
key.RevokedAt = &now
}
}
return nil
}
func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, hash string) error {
for oldHash, key := range r.byHash {
if key.ID == id && key.RevokedAt == nil {
delete(r.byHash, oldHash)
key.KeyHash = hash
r.byHash[hash] = key
return nil
}
}
return apprepo.ErrTenantAPIKeyNotFound
}
func (r *fakeTenantAPIKeyRepo) ListKeysWithPlaceholderHash(_ context.Context) ([]*types.TenantAPIKey, error) {
out := []*types.TenantAPIKey{}
for _, key := range r.byHash {
if key.RevokedAt == nil && strings.HasPrefix(key.KeyHash, "migrated-tenant-") {
cp := *key
out = append(out, &cp)
}
}
return out, nil
}
func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64, at time.Time) error {
for _, key := range r.byHash {
if key.ID == id && key.RevokedAt == nil {
key.LastUsedAt = &at
}
}
return nil
}
func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
token := "sk-42-migrated-secret-value"
key := &types.TenantAPIKey{
TenantID: 42,
Name: "Tenant API key",
KeyHash: "migrated-tenant-42",
APIKey: token,
Role: types.TenantRoleAdmin,
}
if err := repo.CreateAPIKey(ctx, key); err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
}
got, err := svc.AuthenticateTenantAPIKey(ctx, 42, token)
if err != nil {
t.Fatalf("AuthenticateTenantAPIKey returned error: %v", err)
}
if got.KeyHash != hashTenantAPIKey(token) {
t.Fatalf("repaired hash = %q, want %q", got.KeyHash, hashTenantAPIKey(token))
}
if _, err := svc.AuthenticateAPIKey(ctx, token); err != nil {
t.Fatalf("AuthenticateAPIKey after repair returned error: %v", err)
}
}
func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
token := "sk-legacy-token-value"
legacy := &types.TenantAPIKey{
TenantID: 7,
Name: "legacy",
KeyHash: "migrated-tenant-7",
APIKey: token,
Role: types.TenantRoleAdmin,
}
if err := repo.CreateAPIKey(ctx, legacy); err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
}
n, err := svc.BackfillMissingKeyHashes(ctx)
if err != nil {
t.Fatalf("BackfillMissingKeyHashes returned error: %v", err)
}
if n != 1 {
t.Fatalf("backfilled = %d, want 1", n)
}
// After backfill the key authenticates via the fast hash path.
if _, err := svc.AuthenticateAPIKey(ctx, token); err != nil {
t.Fatalf("AuthenticateAPIKey after backfill returned error: %v", err)
}
// Idempotent: a second run finds nothing to do.
if n, err := svc.BackfillMissingKeyHashes(ctx); err != nil || n != 0 {
t.Fatalf("second BackfillMissingKeyHashes = (%d, %v), want (0, nil)", n, err)
}
}
func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "first",
Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey first returned error: %v", err)
}
second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "second",
Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey second returned error: %v", err)
}
if err := svc.RevokeAllAPIKeys(ctx, 42); err != nil {
t.Fatalf("RevokeAllAPIKeys returned error: %v", err)
}
if _, err := svc.AuthenticateAPIKey(ctx, first.Token); err == nil {
t.Fatal("first key should be revoked")
}
if _, err := svc.AuthenticateAPIKey(ctx, second.Token); err == nil {
t.Fatal("second key should be revoked")
}
keys, err := svc.ListAPIKeys(ctx, 42)
if err != nil {
t.Fatalf("ListAPIKeys returned error: %v", err)
}
if len(keys) != 0 {
t.Fatalf("active keys count = %d, want 0", len(keys))
}
}