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:
+2
-2
@@ -716,8 +716,8 @@ DOCREADER_TRANSPORT=grpc
|
||||
|
||||
# OIDC_AUTH_SCOPES="openid profile email"
|
||||
|
||||
# OIDC 首次自动开户后的空间策略:create_personal(默认)或 tenantless。
|
||||
# OIDC_AUTH_DEFAULT_TENANT_MODE=create_personal
|
||||
# 说明:OIDC 首次自动开户后的空间策略与本地注册共用同一开关
|
||||
# WEKNORA_AUTH_DEFAULT_TENANT_MODE(create_personal / tenantless),无独立配置。
|
||||
|
||||
# 用于OIDC用于信息中提取用户数据
|
||||
# OIDC_USER_INFO_MAPPING_USER_NAME=name
|
||||
|
||||
@@ -75,7 +75,6 @@ services:
|
||||
- DISABLE_REGISTRATION=${DISABLE_REGISTRATION:-false}
|
||||
- WEKNORA_AUTH_DEFAULT_TENANT_MODE=${WEKNORA_AUTH_DEFAULT_TENANT_MODE:-}
|
||||
- WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED=${WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED:-}
|
||||
- OIDC_AUTH_DEFAULT_TENANT_MODE=${OIDC_AUTH_DEFAULT_TENANT_MODE:-}
|
||||
- DB_DRIVER=${DB_DRIVER:-postgres}
|
||||
- DB_HOST=${DB_HOST:-postgres}
|
||||
- DB_PORT=${DB_PORT:-5432}
|
||||
|
||||
+3
-1
@@ -314,11 +314,13 @@ GET /api/v1/auth/oidc/callback
|
||||
若 `state` 与 `code` 都合法,则调用:
|
||||
|
||||
```go
|
||||
LoginWithOIDC(ctx, code, decodedState.RedirectURI)
|
||||
LoginWithOIDC(ctx, code, decodedState.RedirectURI, h.resolveDefaultTenantMode(ctx))
|
||||
```
|
||||
|
||||
注意这里传入的是 **state 中保存的 redirect_uri**,而不是重新拼接的地址,这样保证了 code 交换时使用的 `redirect_uri` 和授权时完全一致。
|
||||
|
||||
第四个参数是首次自动开户时的默认租户策略,由 `resolveDefaultTenantMode` 从 `auth.default_tenant_mode`(SystemSetting,DB > `WEKNORA_AUTH_DEFAULT_TENANT_MODE` > 配置文件)解析,与本地密码注册共用同一开关;OIDC 不再有独立的 `OIDC_AUTH_DEFAULT_TENANT_MODE`。
|
||||
|
||||
---
|
||||
|
||||
## 7. 后端用 code 换 token 并解析用户身份
|
||||
|
||||
@@ -556,7 +556,8 @@ const loadUserInfo = async () => {
|
||||
// (同时污染 localStorage),系统管理入口在 hover 工作空间触发
|
||||
// refreshFromAuthMe 后才出现。新增字段请只改 userInfoFromApi。
|
||||
authStore.setUser(userInfoFromApi(user))
|
||||
// 如果返回了租户信息,也更新租户信息
|
||||
// 如果返回了租户信息,也更新租户信息;tenantless 用户(/auth/me
|
||||
// 无 tenant)必须显式清空,否则会残留上一账号/上一会话的租户快照。
|
||||
if (response.data.tenant) {
|
||||
authStore.setTenant({
|
||||
id: String(response.data.tenant.id),
|
||||
@@ -565,6 +566,8 @@ const loadUserInfo = async () => {
|
||||
created_at: response.data.tenant.created_at,
|
||||
updated_at: response.data.tenant.updated_at
|
||||
})
|
||||
} else {
|
||||
authStore.setTenant(null)
|
||||
}
|
||||
const membershipsSync = response.data.memberships
|
||||
if (Array.isArray(membershipsSync)) {
|
||||
|
||||
@@ -53,8 +53,11 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// staleness window is acceptable for an inbox indicator.
|
||||
const pendingInvitationCount = ref<number>(0)
|
||||
// Authoritative deployment capability returned by /auth/me. Defaults to
|
||||
// true for compatibility with older backends that do not return it yet.
|
||||
const canCreateTenant = ref(true)
|
||||
// false (fail-closed): we hide the "create workspace" affordance until
|
||||
// /auth/me confirms the deployment allows it, so an invitation-only
|
||||
// deployment never briefly flashes a create action the backend would
|
||||
// then reject with 403/2005.
|
||||
const canCreateTenant = ref(false)
|
||||
|
||||
// 计算属性
|
||||
const isLoggedIn = computed(() => {
|
||||
@@ -408,7 +411,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
allTenants.value = []
|
||||
memberships.value = []
|
||||
pendingInvitationCount.value = 0
|
||||
canCreateTenant.value = true
|
||||
canCreateTenant.value = false
|
||||
clearSessionResourceCaches()
|
||||
|
||||
// 清空localStorage
|
||||
|
||||
@@ -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