fix(auth): honour JWT tenant_id claim in middleware
POST /auth/switch-tenant mints an access token whose `tenant_id` claim
points to the target tenant, but the middleware previously discarded
that claim entirely:
user, err := userService.ValidateToken(ctx, token) // returned only *User
targetTenantID := user.TenantID // always the home tenant
The session therefore stayed scoped to the user's home tenant despite
the supposedly fresh token, making the new endpoint a no-op once
the request hit any tenant-scoped query.
This change widens the contract:
- UserService.ValidateToken now returns (user, activeTenantID, error)
where activeTenantID is the JWT's `tenant_id` claim, falling back to
user.TenantID when the claim is absent (backward compatibility with
pre-RBAC tokens still in the wild).
- middleware/auth.go uses activeTenantID as the default target before
applying any X-Tenant-ID header override, and recomputes
crossTenantSwitch from `activeTenantID != user.TenantID` so the
resolveTenantRole branches stay correct for switch-tenant sessions.
- The non-middleware /auth/validate handler in handler/auth.go absorbs
the new return value (it only cares about user identity).
Tests:
- internal/application/service/user_jwt_test.go pins the JWT->tenant-id
projection (`tenantIDFromClaims`) — claim present beats fallback,
zero/negative/string claims fall back, int64/uint64 are accepted for
test-built tokens.
Required for PR 2 multi-tenant integration tests, where a single user
needs to switch between Owner-in-A and Viewer-in-B sessions and observe
distinct authority on each side.
This commit is contained in:
@@ -45,8 +45,13 @@ type UserService interface {
|
||||
// refresh token (passed in for revocation) is invalidated. Membership
|
||||
// is verified via the TenantMember service before tokens are issued.
|
||||
SwitchTenant(ctx context.Context, user *types.User, targetTenantID uint64, currentRefreshToken string) (*types.LoginResponse, error)
|
||||
// ValidateToken validates an access token
|
||||
ValidateToken(ctx context.Context, token string) (*types.User, error)
|
||||
// ValidateToken validates an access token. It returns the user
|
||||
// referenced by the token plus the active tenant ID encoded in the
|
||||
// JWT's `tenant_id` claim — the latter lets the auth middleware
|
||||
// honour /auth/switch-tenant sessions that were minted with a
|
||||
// non-home tenant. Falls back to user.TenantID when the claim is
|
||||
// missing (old tokens issued before tenant-level RBAC).
|
||||
ValidateToken(ctx context.Context, token string) (*types.User, uint64, error)
|
||||
// RefreshToken refreshes access token using refresh token
|
||||
RefreshToken(ctx context.Context, refreshToken string) (accessToken, newRefreshToken string, err error)
|
||||
// RevokeToken revokes a token
|
||||
|
||||
Reference in New Issue
Block a user