refactor(rbac): address PR 1 review feedback

Tighten correctness, security and observability of the tenant RBAC
foundation introduced in 3c4cdd70 in response to internal review.

Bugfixes
- custom_agents.runnable_by_viewer: drop the GORM `default:true` tag.
  GORM treats a plain bool's zero value as "unspecified" and silently
  rewrites it to the column default on insert, which would prevent
  admins from ever creating an agent with viewer-runtime disabled. The
  column-level DEFAULT TRUE on the database side still backstops rows
  inserted by raw SQL / migrations.
- TenantMemberRepository.HasAnyMembers: replace `Limit(1).Count(&n)`
  with `Take(&probe)`. GORM's Count ignores Limit and scans the whole
  table, which matters because this runs on the auth middleware's
  hot path for users without a cached membership.
- service/user.LoginWithOIDC: include User, Tenant and Memberships in
  the OIDCCallbackResponse so the OIDC flow returns the same shape as
  password login (previously User and friends were left nil).

Security
- middleware/auth.resolveTenantRole: restrict orphan-tenant
  auto-promotion to the caller's home tenant. Cross-tenant superuser
  visits and JWTs minted for foreign tenants no longer trigger silent
  Owner grants. Two regression tests pin the new behaviour.
- service/user.synthFallbackMembership: default the synthesised role
  to Viewer instead of Owner. The login response only feeds UI; the
  backend re-derives the real role from tenant_members on every
  request, so showing a Viewer UI is preferable to a misleading Owner
  UI that would surface admin controls the backend will then 403.
- migrations/versioned/000043_tenant_rbac.down.sql: gate the destructive
  drop behind a `weknora.allow_destructive_migration` GUC so an
  accidental `migrate down` cannot wipe role data in production.
- frontend/src/stores/auth.ts: comment currentTenantRole as
  rendering-only so future PRs cannot mistake the localStorage-backed
  value for an authorisation signal.

API contract
- Memberships in LoginResponse and OIDCCallbackResponse now serialises
  without omitempty, and buildMembershipsForUser / synthFallbackMembership
  always return a non-nil slice — frontend can rely on JSON `[]`.
- handler/auth.GetCurrentUser includes memberships so /auth/me refreshes
  recover currentTenantRole after a page reload.

Performance
- Add TenantService.GetTenantsByIDs (with the matching repo method) and
  use it inside buildMembershipsForUser to batch tenant-name lookups
  instead of issuing one query per membership.

Observability
- Replace the remaining `log.Printf` calls in middleware/auth with
  contextual logger.Warnf / logger.Infof so role resolution events ride
  the standard request-id / Langfuse trace plumbing. The successful
  auto-promote line is tagged `[audit]` for log mining.

Tests
- internal/application/service/tenant_member_test.go: hand-rolled
  fakeTenantMemberRepo plus 11 cases covering AddMember validation,
  EnsureOwner idempotence, "cannot demote/remove the last Owner",
  same-role no-op, ErrInvalidTenantRole / ErrMembershipNotFound, and
  the TenantRole.HasPermission lattice.
- internal/middleware/auth_role_test.go: fakeMemberService plus 8 cases
  pinning every branch of resolveTenantRole, including the two H1
  regressions (cross-tenant superuser must not auto-promote; orphan
  auto-promote requires the home tenant).
This commit is contained in:
wizardchen
2026-05-13 20:24:55 +08:00
committed by lyingbug
parent 7f7a48880f
commit f3d1210577
15 changed files with 792 additions and 46 deletions
+9 -1
View File
@@ -79,7 +79,15 @@ type CustomAgent struct {
// start chat sessions against this agent. Defaults to true so viewers
// can still consume published agents; admins toggle it off for agents
// whose tools should be restricted to contributors and above.
RunnableByViewer bool `yaml:"runnable_by_viewer" json:"runnable_by_viewer" gorm:"default:true"`
//
// Note: no GORM `default:true` tag here. With a plain `bool` field that
// tag causes GORM to treat Go's zero value (false) as "unspecified" and
// silently rewrite it to the DB default (true) on insert — preventing
// admins from ever creating an agent with viewer-runtime disabled. The
// column-level DEFAULT TRUE on the database side still covers rows
// inserted by raw SQL / migrations; GORM Create always writes the
// explicit struct value.
RunnableByViewer bool `yaml:"runnable_by_viewer" json:"runnable_by_viewer"`
// Agent configuration
Config CustomAgentConfig `yaml:"config" json:"config" gorm:"type:json"`
+6
View File
@@ -12,6 +12,10 @@ type TenantService interface {
CreateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error)
// GetTenantByID gets a tenant by ID
GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error)
// GetTenantsByIDs batches GetTenantByID for multiple IDs in a single
// query. Returns a map keyed by tenant ID for O(1) lookup at the
// call site; missing tenants are simply absent from the map.
GetTenantsByIDs(ctx context.Context, ids []uint64) (map[uint64]*types.Tenant, error)
// ListTenants lists all tenants
ListTenants(ctx context.Context) ([]*types.Tenant, error)
// UpdateTenant updates a tenant
@@ -38,6 +42,8 @@ type TenantRepository interface {
CreateTenant(ctx context.Context, tenant *types.Tenant) error
// GetTenantByID gets a tenant by ID
GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error)
// GetTenantsByIDs batches GetTenantByID; see TenantService.GetTenantsByIDs.
GetTenantsByIDs(ctx context.Context, ids []uint64) (map[uint64]*types.Tenant, error)
// ListTenants lists all tenants
ListTenants(ctx context.Context) ([]*types.Tenant, error)
// SearchTenants searches tenants with pagination and filters
+6
View File
@@ -34,6 +34,12 @@ type UserService interface {
ValidatePassword(ctx context.Context, userID string, password string) error
// GenerateTokens generates access and refresh tokens for user
GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error)
// BuildLoginMemberships projects the user's tenant memberships into
// the login-response shape. activeTenant is reused (without an extra
// lookup) for the matching row's TenantName. The slice is guaranteed
// non-nil so callers can serialise it as an empty JSON array when the
// membership table is unavailable.
BuildLoginMemberships(ctx context.Context, user *types.User, activeTenant *types.Tenant) []types.Membership
// SwitchTenant issues a new token pair scoped to targetTenantID and
// returns the corresponding LoginResponse. The caller's previous
// refresh token (passed in for revocation) is invalidated. Membership
+20 -9
View File
@@ -78,13 +78,21 @@ type OIDCConfigResponse struct {
}
type OIDCCallbackResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *User `json:"user,omitempty"`
Tenant *Tenant `json:"tenant,omitempty"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IsNewUser bool `json:"is_new_user,omitempty"`
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *User `json:"user,omitempty"`
// Tenant carries the active tenant for the issued token. The field
// name is preserved for backward compatibility with existing frontend
// OIDC callback handling; LoginResponse uses ActiveTenant for the
// same data.
Tenant *Tenant `json:"tenant,omitempty"`
// Memberships mirrors LoginResponse.Memberships so the OIDC flow
// produces the same role information available to password logins.
// Always populated (length >= 1 for an authenticated user).
Memberships []Membership `json:"memberships"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IsNewUser bool `json:"is_new_user,omitempty"`
}
type OIDCUserInfo struct {
@@ -113,8 +121,11 @@ type LoginResponse struct {
// Memberships lists every tenant the user can authenticate into,
// along with their role in each. Always populated (length 1 for users
// who only belong to their home tenant) so frontends can render a
// tenant switcher without a follow-up request.
Memberships []Membership `json:"memberships,omitempty"`
// tenant switcher without a follow-up request. Serialised without
// omitempty so the field is always present as a JSON array (possibly
// empty) — the "always populated" contract relies on the server side
// guaranteeing a non-nil slice.
Memberships []Membership `json:"memberships"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}