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.
This commit is contained in:
@@ -77,6 +77,24 @@ func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64
|
||||
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{}).
|
||||
|
||||
@@ -134,6 +134,28 @@ func (s *tenantAPIKeyService) RevokeAllAPIKeys(ctx context.Context, tenantID uin
|
||||
return s.repo.RevokeAllAPIKeys(ctx, tenantID)
|
||||
}
|
||||
|
||||
func (s *tenantAPIKeyService) BackfillMissingKeyHashes(ctx context.Context) (int, error) {
|
||||
keys, err := s.repo.ListKeysWithPlaceholderHash(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
backfilled := 0
|
||||
for _, key := range keys {
|
||||
if key == nil || strings.TrimSpace(key.APIKey) == "" {
|
||||
continue
|
||||
}
|
||||
hash := hashTenantAPIKey(key.APIKey)
|
||||
if key.KeyHash == hash {
|
||||
continue
|
||||
}
|
||||
if err := s.repo.UpdateAPIKeyHash(ctx, key.ID, hash); err != nil {
|
||||
return backfilled, err
|
||||
}
|
||||
backfilled++
|
||||
}
|
||||
return backfilled, nil
|
||||
}
|
||||
|
||||
func generateTenantAPIKeyToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
|
||||
@@ -107,6 +107,17 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, ha
|
||||
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 {
|
||||
@@ -126,7 +137,7 @@ func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testi
|
||||
Name: "Tenant API key",
|
||||
KeyHash: "migrated-tenant-42",
|
||||
APIKey: token,
|
||||
Role: types.TenantRoleAdmin,
|
||||
Role: types.TenantRoleAdmin,
|
||||
}
|
||||
if err := repo.CreateAPIKey(ctx, key); err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
@@ -143,6 +154,40 @@ func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testi
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -151,7 +196,7 @@ func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
|
||||
first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "first",
|
||||
Role: types.TenantRoleViewer,
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey first returned error: %v", err)
|
||||
@@ -159,7 +204,7 @@ func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
|
||||
second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "second",
|
||||
Role: types.TenantRoleViewer,
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey second returned error: %v", err)
|
||||
|
||||
Reference in New Issue
Block a user