refactor(auth): unify OIDC provisioning under shared default_tenant_mode policy
Drop the standalone OIDC_AUTH_DEFAULT_TENANT_MODE / oidc_auth.default_tenant_mode knob so OIDC auto-provisioning and local password registration share the single auth.default_tenant_mode policy (resolved by the callback handler). Repair tenantless sessions by falling back to the first active membership on the login happy path and stale-preference paths, allow tenantless PUT /auth/me/preferences, clear the tenant snapshot on /auth/me responses without a tenant, and default the frontend canCreateTenant capability to fail-closed until /auth/me confirms it.
This commit is contained in:
@@ -419,8 +419,15 @@ func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI s
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LoginWithOIDC exchanges code for tokens, loads user info, provisions user if needed, and returns local login tokens.
|
||||
func (s *userService) LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error) {
|
||||
// LoginWithOIDC exchanges code for tokens, loads user info, provisions user if
|
||||
// needed, and returns local login tokens. provisioning is the default tenant
|
||||
// mode applied only when a brand-new local user is auto-created; it is resolved
|
||||
// by the caller from the shared auth.default_tenant_mode policy.
|
||||
func (s *userService) LoginWithOIDC(
|
||||
ctx context.Context,
|
||||
code, redirectURI string,
|
||||
provisioning types.TenantProvisioningMode,
|
||||
) (*types.OIDCCallbackResponse, error) {
|
||||
if strings.TrimSpace(code) == "" {
|
||||
return nil, errors.New("code is required")
|
||||
}
|
||||
@@ -452,7 +459,7 @@ func (s *userService) LoginWithOIDC(ctx context.Context, code, redirectURI strin
|
||||
}
|
||||
isNewUser := false
|
||||
if isUserLookupNotFound(err) || user == nil {
|
||||
user, err = s.provisionOIDCUser(ctx, userInfo)
|
||||
user, err = s.provisionOIDCUser(ctx, userInfo, provisioning)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -669,10 +676,7 @@ func (s *userService) resolveLoginTenantID(ctx context.Context, user *types.User
|
||||
}
|
||||
pref := user.Preferences.LastActiveTenantID
|
||||
if pref == nil || *pref == 0 || *pref == user.TenantID {
|
||||
if user.TenantID == 0 {
|
||||
return s.resolveFirstMembershipTenant(ctx, user)
|
||||
}
|
||||
return user.TenantID
|
||||
return s.homeOrFirstMembershipTenant(ctx, user)
|
||||
}
|
||||
preferred := *pref
|
||||
|
||||
@@ -684,7 +688,7 @@ func (s *userService) resolveLoginTenantID(ctx context.Context, user *types.User
|
||||
"clearing preference and falling back to home: %v",
|
||||
preferred, user.ID, err)
|
||||
s.clearLastActiveTenantPreference(ctx, user)
|
||||
return user.TenantID
|
||||
return s.homeOrFirstMembershipTenant(ctx, user)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -704,13 +708,30 @@ func (s *userService) resolveLoginTenantID(ctx context.Context, user *types.User
|
||||
"clearing preference and falling back to home (err=%v)",
|
||||
user.ID, preferred, err)
|
||||
s.clearLastActiveTenantPreference(ctx, user)
|
||||
return user.TenantID
|
||||
return s.homeOrFirstMembershipTenant(ctx, user)
|
||||
}
|
||||
}
|
||||
|
||||
return preferred
|
||||
}
|
||||
|
||||
// homeOrFirstMembershipTenant returns the user's home tenant, or — for a
|
||||
// tenantless identity (TenantID == 0) — the earliest active membership.
|
||||
// Shared by the happy path and the stale-preference fallbacks so a
|
||||
// tenantless session with a valid membership never gets a zero-tenant
|
||||
// token when a usable tenant is available (repairs partial
|
||||
// invitation/admin-assignment flows). resolveFirstMembershipTenant
|
||||
// best-effort persists the resolved tenant as the new home.
|
||||
func (s *userService) homeOrFirstMembershipTenant(ctx context.Context, user *types.User) uint64 {
|
||||
if user == nil {
|
||||
return 0
|
||||
}
|
||||
if user.TenantID == 0 {
|
||||
return s.resolveFirstMembershipTenant(ctx, user)
|
||||
}
|
||||
return user.TenantID
|
||||
}
|
||||
|
||||
// resolveFirstMembershipTenant makes a tenantless identity usable when an
|
||||
// active membership already exists (for example, an invitation was accepted
|
||||
// but persisting the default tenant failed). ListByUser is stably ordered by
|
||||
@@ -1325,19 +1346,23 @@ func (s *userService) fetchOIDCUserInfo(ctx context.Context, endpoint, accessTok
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func (s *userService) provisionOIDCUser(ctx context.Context, info *types.OIDCUserInfo) (*types.User, error) {
|
||||
// provisionOIDCUser auto-creates a local account for a first-time OIDC
|
||||
// login. The provisioning mode is decided by the caller (the OIDC callback
|
||||
// handler resolves it from the same auth.default_tenant_mode system-setting
|
||||
// that governs public password registration) so both entry points share a
|
||||
// single deployment policy. An empty mode falls back to create_personal via
|
||||
// Register's own defaulting.
|
||||
func (s *userService) provisionOIDCUser(
|
||||
ctx context.Context,
|
||||
info *types.OIDCUserInfo,
|
||||
provisioning types.TenantProvisioningMode,
|
||||
) (*types.User, error) {
|
||||
username := s.generateOIDCUsername(ctx, info)
|
||||
randomPassword, err := generateRandomString(32)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate password for OIDC user: %w", err)
|
||||
}
|
||||
|
||||
provisioning := types.TenantProvisioningCreatePersonal
|
||||
if s.config != nil && s.config.OIDCAuth != nil &&
|
||||
strings.TrimSpace(s.config.OIDCAuth.DefaultTenantMode) == config.AuthDefaultTenantModeTenantless {
|
||||
provisioning = types.TenantProvisioningTenantless
|
||||
}
|
||||
|
||||
user, err := s.Register(ctx, &types.RegisterRequest{
|
||||
Username: username,
|
||||
Email: info.Email,
|
||||
|
||||
@@ -318,9 +318,6 @@ type OIDCAuthConfig struct {
|
||||
UserInfoEndpoint string `yaml:"user_info_endpoint" json:"user_info_endpoint"`
|
||||
Scopes []string `yaml:"scopes" json:"scopes"`
|
||||
UserInfoMapping *OIDCUserInfoMapping `yaml:"user_info_mapping" json:"user_info_mapping"`
|
||||
// DefaultTenantMode applies only when OIDC auto-provisions a new local
|
||||
// user. Existing users keep their current home tenant/memberships.
|
||||
DefaultTenantMode string `yaml:"default_tenant_mode" json:"default_tenant_mode"`
|
||||
}
|
||||
|
||||
// PromptTemplateI18n holds localized name and description for a prompt template.
|
||||
@@ -627,11 +624,6 @@ func ValidateConfig(cfg *Config) error {
|
||||
(strings.TrimSpace(cfg.OIDCAuth.AuthorizationEndpoint) == "" || strings.TrimSpace(cfg.OIDCAuth.TokenEndpoint) == "") {
|
||||
errs = append(errs, "oidc_auth.discovery_url or both oidc_auth.authorization_endpoint and oidc_auth.token_endpoint are required when OIDC is enabled")
|
||||
}
|
||||
tenantMode := strings.TrimSpace(cfg.OIDCAuth.DefaultTenantMode)
|
||||
if tenantMode != "" && tenantMode != AuthDefaultTenantModeCreatePersonal && tenantMode != AuthDefaultTenantModeTenantless {
|
||||
errs = append(errs, fmt.Sprintf("oidc_auth.default_tenant_mode must be %q or %q, got %q",
|
||||
AuthDefaultTenantModeCreatePersonal, AuthDefaultTenantModeTenantless, tenantMode))
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Auth != nil {
|
||||
@@ -729,9 +721,6 @@ func applyOIDCEnvOverrides(cfg *Config) {
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_SCOPES")); value != "" {
|
||||
cfg.OIDCAuth.Scopes = strings.Fields(strings.ReplaceAll(value, ",", " "))
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_DEFAULT_TENANT_MODE")); value != "" {
|
||||
cfg.OIDCAuth.DefaultTenantMode = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_USER_INFO_MAPPING_USER_NAME")); value != "" {
|
||||
cfg.OIDCAuth.UserInfoMapping.Username = value
|
||||
}
|
||||
@@ -742,9 +731,6 @@ func applyOIDCEnvOverrides(cfg *Config) {
|
||||
if cfg.OIDCAuth.ProviderDisplayName == "" {
|
||||
cfg.OIDCAuth.ProviderDisplayName = "OIDC"
|
||||
}
|
||||
if strings.TrimSpace(cfg.OIDCAuth.DefaultTenantMode) == "" {
|
||||
cfg.OIDCAuth.DefaultTenantMode = AuthDefaultTenantModeCreatePersonal
|
||||
}
|
||||
if len(cfg.OIDCAuth.Scopes) == 0 {
|
||||
cfg.OIDCAuth.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
|
||||
@@ -353,7 +353,7 @@ func (h *AuthHandler) OIDCRedirectCallback(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.userService.LoginWithOIDC(ctx, code, strings.TrimSpace(decodedState.RedirectURI))
|
||||
resp, err := h.userService.LoginWithOIDC(ctx, code, strings.TrimSpace(decodedState.RedirectURI), h.resolveDefaultTenantMode(ctx))
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to complete OIDC login via redirect callback: %v", err)
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(err.Error()))
|
||||
|
||||
@@ -85,6 +85,8 @@ func isTenantOptionalAPI(path, method string) bool {
|
||||
switch {
|
||||
case path == "/api/v1/auth/me" && (method == http.MethodGet || method == http.MethodPut):
|
||||
return true
|
||||
case path == "/api/v1/auth/me/preferences" && method == http.MethodPut:
|
||||
return true
|
||||
case path == "/api/v1/auth/logout" && method == http.MethodPost:
|
||||
return true
|
||||
case path == "/api/v1/auth/change-password" && method == http.MethodPost:
|
||||
|
||||
@@ -16,6 +16,7 @@ func TestTenantOptionalAPISurface(t *testing.T) {
|
||||
}{
|
||||
{http.MethodGet, "/api/v1/auth/me", true},
|
||||
{http.MethodPut, "/api/v1/auth/me", true},
|
||||
{http.MethodPut, "/api/v1/auth/me/preferences", true},
|
||||
{http.MethodPost, "/api/v1/tenants", true},
|
||||
{http.MethodGet, "/api/v1/me/invitations", true},
|
||||
{http.MethodPost, "/api/v1/me/invitations/12/accept", true},
|
||||
|
||||
@@ -14,8 +14,10 @@ type UserService interface {
|
||||
Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error)
|
||||
// GetOIDCAuthorizationURL builds the third-party OIDC authorization URL
|
||||
GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error)
|
||||
// LoginWithOIDC exchanges the callback code, auto-provisions users if needed, and completes login
|
||||
LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error)
|
||||
// LoginWithOIDC exchanges the callback code, auto-provisions users if needed, and completes login.
|
||||
// provisioning is the default tenant mode for a newly auto-created user
|
||||
// (resolved by the caller from auth.default_tenant_mode).
|
||||
LoginWithOIDC(ctx context.Context, code, redirectURI string, provisioning types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error)
|
||||
// GetUserByID gets a user by ID
|
||||
GetUserByID(ctx context.Context, id string) (*types.User, error)
|
||||
// GetUsersByIDs batch-fetches users by id, returning a map keyed by
|
||||
|
||||
Reference in New Issue
Block a user