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:
wizardchen
2026-07-06 17:34:52 +08:00
committed by lyingbug
parent fedb6c3f7e
commit d2ffc1b973
26 changed files with 1045 additions and 500 deletions
+15
View File
@@ -38,6 +38,21 @@ const bootstrapEnvVar = "WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL"
// here as additional dig.Invoke calls.
func runStartupBootstrap(c *dig.Container) {
ctx := context.Background()
// One-shot: backfill SHA-256 key_hash for legacy tenant API keys that
// migration 000065 seeded with a placeholder. Without this, the first
// authentication of each migrated key falls back to an O(n) plaintext
// scan of the tenant's keys. Best-effort: warn, never abort startup.
if err := c.Invoke(func(apiKeySvc interfaces.TenantAPIKeyService) {
if n, err := apiKeySvc.BackfillMissingKeyHashes(ctx); err != nil {
logger.Warnf(ctx, "[bootstrap] tenant api key hash backfill failed: %v", err)
} else if n > 0 {
logger.Infof(ctx, "[bootstrap] backfilled %d legacy tenant api key hash(es)", n)
}
}); err != nil {
logger.Warnf(ctx, "[bootstrap] failed to resolve TenantAPIKeyService: %v", err)
}
email := strings.TrimSpace(os.Getenv(bootstrapEnvVar))
if email == "" {
return