feat(auth): support tenantless provisioning and gated self-service workspace creation

Allow deployments to register users without auto-creating a personal tenant, expose creation policy via /auth/me, and guide tenantless accounts through a workspace onboarding flow.
This commit is contained in:
wizardchen
2026-07-13 18:04:14 +08:00
committed by lyingbug
parent 50b8c0a72e
commit ecf2c1fb9b
36 changed files with 1543 additions and 89 deletions
+35 -3
View File
@@ -101,6 +101,31 @@ func (h *AuthHandler) resolveRegistrationMode(ctx context.Context) string {
return h.systemSettingSvc.GetString(ctx, "auth.registration_mode", "", def)
}
// resolveDefaultTenantMode returns the provisioning policy for ordinary
// public password registrations. Invitation registration never uses this
// value: the invitation itself supplies the target tenant.
func (h *AuthHandler) resolveDefaultTenantMode(ctx context.Context) types.TenantProvisioningMode {
def := config.AuthDefaultTenantModeCreatePersonal
if h.configInfo != nil && h.configInfo.Auth != nil {
if mode := strings.TrimSpace(h.configInfo.Auth.DefaultTenantMode); mode != "" {
def = mode
}
}
mode := def
if h.systemSettingSvc != nil {
mode = h.systemSettingSvc.GetString(
ctx,
"auth.default_tenant_mode",
"WEKNORA_AUTH_DEFAULT_TENANT_MODE",
def,
)
}
if mode == config.AuthDefaultTenantModeTenantless {
return types.TenantProvisioningTenantless
}
return types.TenantProvisioningCreatePersonal
}
// Register godoc
// @Summary 用户注册
// @Description 注册新用户账号
@@ -150,6 +175,7 @@ func (h *AuthHandler) Register(c *gin.Context) {
}
req.Username = secutils.SanitizeForLog(req.Username)
req.Email = secutils.SanitizeForLog(req.Email)
req.TenantProvisioning = h.resolveDefaultTenantMode(ctx)
// Call service to register user
user, err := h.userService.Register(ctx, &req)
if err != nil {
@@ -536,12 +562,18 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
// 同步返回当前用户的 memberships,让前端在页面刷新(仅命中 /auth/me)
// 后也能恢复 currentTenantRole,避免角色信息只在 login 那一刻可用。
memberships := h.userService.BuildLoginMemberships(ctx, user, tenant)
canCreateTenant := user.CanAccessAllTenants ||
resolveTenantSelfServiceCreationEnabled(ctx, h.configInfo, h.systemSettingSvc)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"user": userInfo,
"tenant": dto.NewTenantResponse(ctx, tenant),
"memberships": memberships,
"user": userInfo,
"tenant": dto.NewTenantResponse(ctx, tenant),
"memberships": memberships,
"tenant_required": tenant == nil,
"capabilities": gin.H{
"can_create_tenant": canCreateTenant,
},
},
})
}
+22 -5
View File
@@ -170,9 +170,10 @@ func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
}
user, err := h.userService.Register(ctx, &types.RegisterRequest{
Username: req.Username,
Email: req.Email,
Password: req.Password,
Username: req.Username,
Email: req.Email,
Password: req.Password,
TenantProvisioning: types.TenantProvisioningTenantless,
})
if err != nil {
logger.Errorf(ctx, "register-by-invite: user create failed for %s: %v",
@@ -181,10 +182,26 @@ func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
return
}
// The invited tenant becomes the user's initial/default tenant. No
user.TenantID = inv.TenantID
if err := h.userService.UpdateUser(ctx, user); err != nil {
logger.Errorf(ctx, "register-by-invite: failed to set home tenant for user %s: %v", user.ID, err)
_ = h.userService.DeleteUser(ctx, user.ID)
c.Error(apperrors.NewInternalServerError("failed to finalise invited account").WithDetails(err.Error()))
return
}
if _, err := h.invitationSvc.AcceptByToken(ctx, req.Token, user.ID); err != nil {
// Race: link was revoked between Lookup and Accept. The user
// account is created either way — they can still log in.
// Race: link was revoked between Lookup and Accept. Keep the new
// account, but restore it to tenantless so it does not point at a
// tenant for which no membership was created. If even that repair
// fails, remove the half-provisioned identity.
logger.Errorf(ctx, "register-by-invite: accept failed for user %s: %v", user.ID, err)
user.TenantID = 0
if rollbackErr := h.userService.UpdateUser(ctx, user); rollbackErr != nil {
logger.Errorf(ctx, "register-by-invite: failed to restore tenantless user %s: %v", user.ID, rollbackErr)
_ = h.userService.DeleteUser(ctx, user.ID)
}
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is no longer valid; please log in to your new account",
@@ -0,0 +1,122 @@
package handler
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type invitedRegistrationUserService struct {
interfaces.UserService
registeredMode types.TenantProvisioningMode
updatedTenant uint64
updateCalls []uint64
}
func (s *invitedRegistrationUserService) GetUserByEmail(context.Context, string) (*types.User, error) {
return nil, nil
}
func (s *invitedRegistrationUserService) Register(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
s.registeredMode = req.TenantProvisioning
return &types.User{ID: "new-user", Username: req.Username, Email: req.Email, IsActive: true}, nil
}
func (s *invitedRegistrationUserService) UpdateUser(_ context.Context, user *types.User) error {
s.updatedTenant = user.TenantID
s.updateCalls = append(s.updateCalls, user.TenantID)
return nil
}
func (s *invitedRegistrationUserService) GenerateTokens(context.Context, *types.User) (string, string, error) {
return "access", "refresh", nil
}
type invitedRegistrationInvitationService struct {
interfaces.TenantInvitationService
acceptErr error
}
func (s *invitedRegistrationInvitationService) LookupByToken(context.Context, string) (*types.TenantInvitation, error) {
return &types.TenantInvitation{TenantID: 42, Role: types.TenantRoleViewer}, nil
}
func (s *invitedRegistrationInvitationService) AcceptByToken(context.Context, string, string) (*types.TenantMember, error) {
if s.acceptErr != nil {
return nil, s.acceptErr
}
return &types.TenantMember{TenantID: 42, Role: types.TenantRoleViewer}, nil
}
type invitedRegistrationTenantService struct {
interfaces.TenantService
}
func TestRegisterByInviteRestoresTenantlessAccountWhenInviteExpiresDuringRegistration(t *testing.T) {
gin.SetMode(gin.TestMode)
users := &invitedRegistrationUserService{}
h := &AuthHandler{
userService: users,
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{acceptErr: errors.New("expired")},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register-by-invite", h.RegisterByInvite)
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusGone {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.updatedTenant != 0 {
t.Fatalf("updated tenant=%d, want tenantless rollback", users.updatedTenant)
}
if len(users.updateCalls) != 2 || users.updateCalls[0] != 42 || users.updateCalls[1] != 0 {
t.Fatalf("update calls=%v, want [42 0]", users.updateCalls)
}
}
func (s *invitedRegistrationTenantService) GetTenantByID(context.Context, uint64) (*types.Tenant, error) {
return &types.Tenant{ID: 42, Name: "Invited Workspace"}, nil
}
func TestRegisterByInviteUsesInvitedTenantWithoutPersonalTenant(t *testing.T) {
gin.SetMode(gin.TestMode)
users := &invitedRegistrationUserService{}
h := &AuthHandler{
userService: users,
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register-by-invite", h.RegisterByInvite)
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.registeredMode != types.TenantProvisioningTenantless {
t.Fatalf("register mode=%q, want tenantless", users.registeredMode)
}
if users.updatedTenant != 42 {
t.Fatalf("updated tenant=%d, want 42", users.updatedTenant)
}
}
@@ -107,8 +107,11 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
// through by observing the stub being invoked.
called := false
us := &stubRegisterUserService{
register: func(_ context.Context, _ *types.RegisterRequest) (*types.User, error) {
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
called = true
if req.TenantProvisioning != types.TenantProvisioningCreatePersonal {
t.Fatalf("default provisioning = %q, want create_personal", req.TenantProvisioning)
}
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
@@ -125,6 +128,28 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
}
}
func TestRegister_TenantlessProvisioningFromConfig(t *testing.T) {
us := &stubRegisterUserService{
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
if req.TenantProvisioning != types.TenantProvisioningTenantless {
t.Fatalf("provisioning = %q, want tenantless", req.TenantProvisioning)
}
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{
RegistrationMode: config.AuthRegistrationModeSelfServe,
DefaultTenantMode: config.AuthDefaultTenantModeTenantless,
},
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
t.Fatalf("tenantless self-serve registration got %d body=%s", w.Code, w.Body.String())
}
}
func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
// Defensive: a nil Auth section means the operator hasn't set the
// registration mode at all, which must not crash and must keep the
+30 -2
View File
@@ -31,8 +31,8 @@ type TenantHandler struct {
memberService interfaces.TenantMemberService
kbService interfaces.KnowledgeBaseService
config *config.Config
// systemSettingSvc resolves runtime tunables for tenant limits
// (currently `tenant.max_owned_per_user`). Reading goes DB > ENV >
// systemSettingSvc resolves runtime tenant policies and limits.
// Reading goes DB > ENV >
// in-code default, so a SystemAdmin's UI override applies on the
// very next CreateTenant call.
systemSettingSvc interfaces.SystemSettingService
@@ -228,6 +228,17 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
return
}
// Deployment-level policy: ordinary users may be restricted to joining
// existing workspaces by invitation. This check is authoritative; the
// frontend capability only improves UX and cannot bypass it. Cross-tenant
// superusers retain the catalog-management create path.
if !caller.CanAccessAllTenants &&
!resolveTenantSelfServiceCreationEnabled(ctx, h.config, h.systemSettingSvc) {
logger.Warnf(ctx, "Self-service tenant creation denied by policy for user %s", caller.ID)
c.Error(errors.NewTenantCreationDisabledError())
return
}
var tenantData types.Tenant
if caller.CanAccessAllTenants {
@@ -402,6 +413,23 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
}
}
// When a tenantless user creates their first workspace, make it their
// default login tenant. Roll the just-created resources back if this
// finalisation fails so the user is not left with an unreachable tenant.
if caller.TenantID == 0 {
caller.TenantID = createdTenant.ID
if err := h.userService.UpdateUser(ctx, caller); err != nil {
logger.Errorf(ctx, "Failed to set first tenant %d as default for user %s: %v",
createdTenant.ID, caller.ID, err)
if h.memberService != nil {
_ = h.memberService.RemoveMember(ctx, caller.ID, createdTenant.ID)
}
_ = h.service.DeleteTenant(ctx, createdTenant.ID)
c.Error(errors.NewInternalServerError("Failed to finalise default tenant").WithDetails(err.Error()))
return
}
}
logger.Infof(
ctx,
"Tenant created successfully, ID: %d, name: %s",
+13
View File
@@ -490,6 +490,19 @@ func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
return
}
// A tenantless account adopts the first accepted invitation as its
// default tenant. Membership remains the authorization source; TenantID
// only supplies the login/navigation default.
if user, userErr := h.userService.GetUserByID(ctx, caller); userErr == nil && user != nil && user.TenantID == 0 {
user.TenantID = member.TenantID
if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {
logger.Errorf(ctx, "AcceptMyInvitation failed to set default tenant: user=%s tenant=%d err=%v",
caller, member.TenantID, updateErr)
c.Error(apperrors.NewInternalServerError("invitation accepted but default tenant update failed").WithDetails(updateErr.Error()))
return
}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
+37
View File
@@ -0,0 +1,37 @@
package handler
import (
"context"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const (
tenantSelfServiceCreationSettingKey = "tenant.self_service_creation_enabled"
tenantSelfServiceCreationEnvName = "WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED"
)
// resolveTenantSelfServiceCreationEnabled is the shared policy resolver used
// both by POST /tenants enforcement and /auth/me capability projection. Keeping
// both on one function prevents the UI from advertising a capability that the
// backend would reject.
func resolveTenantSelfServiceCreationEnabled(
ctx context.Context,
cfg *config.Config,
settings interfaces.SystemSettingService,
) bool {
enabled := true
if cfg != nil && cfg.Tenant != nil {
enabled = cfg.Tenant.IsSelfServiceCreationEnabled()
}
if settings == nil {
return enabled
}
return settings.GetBool(
ctx,
tenantSelfServiceCreationSettingKey,
tenantSelfServiceCreationEnvName,
enabled,
)
}
@@ -0,0 +1,146 @@
package handler
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
func tenantPolicyErrorCapture() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 {
return
}
if appErr, ok := c.Errors.Last().Err.(*apperrors.AppError); ok {
c.JSON(appErr.HTTPCode, gin.H{"error": appErr})
}
}
}
type tenantPolicySettingService struct {
interfaces.SystemSettingService
enabled bool
}
func (s *tenantPolicySettingService) GetBool(context.Context, string, string, bool) bool {
return s.enabled
}
func (s *tenantPolicySettingService) GetInt(_ context.Context, _ string, _ string, def int64) int64 {
return def
}
type tenantPolicyUserService struct {
interfaces.UserService
user *types.User
}
func (s *tenantPolicyUserService) GetCurrentUser(context.Context) (*types.User, error) {
return s.user, nil
}
func (s *tenantPolicyUserService) BuildLoginMemberships(context.Context, *types.User, *types.Tenant) []types.Membership {
return []types.Membership{}
}
type tenantPolicyTenantService struct {
interfaces.TenantService
createCalls int
}
func (s *tenantPolicyTenantService) CreateTenant(_ context.Context, tenant *types.Tenant) (*types.Tenant, error) {
s.createCalls++
tenant.ID = 99
return tenant, nil
}
func TestCreateTenantRejectsRegularUserWhenSelfServiceDisabled(t *testing.T) {
gin.SetMode(gin.TestMode)
tenants := &tenantPolicyTenantService{}
h := &TenantHandler{
service: tenants,
userService: &tenantPolicyUserService{user: &types.User{ID: "regular-user"}},
config: &config.Config{Tenant: &config.TenantConfig{}},
systemSettingSvc: &tenantPolicySettingService{enabled: false},
}
r := gin.New()
r.Use(tenantPolicyErrorCapture())
r.POST("/tenants", h.CreateTenant)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/tenants", bytes.NewBufferString(`{"name":"blocked"}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if tenants.createCalls != 0 {
t.Fatalf("CreateTenant called %d times, want 0", tenants.createCalls)
}
if !strings.Contains(w.Body.String(), `"code":2005`) {
t.Fatalf("response missing typed disabled code: %s", w.Body.String())
}
}
func TestCreateTenantAllowsCrossTenantSuperuserWhenSelfServiceDisabled(t *testing.T) {
gin.SetMode(gin.TestMode)
tenants := &tenantPolicyTenantService{}
h := &TenantHandler{
service: tenants,
userService: &tenantPolicyUserService{user: &types.User{
ID: "super-user",
TenantID: 1,
CanAccessAllTenants: true,
}},
config: &config.Config{Tenant: &config.TenantConfig{}},
systemSettingSvc: &tenantPolicySettingService{enabled: false},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/tenants", h.CreateTenant)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/tenants", bytes.NewBufferString(`{"name":"admin-created"}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if tenants.createCalls != 1 {
t.Fatalf("CreateTenant called %d times, want 1", tenants.createCalls)
}
}
func TestAuthMeProjectsTenantCreationCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &AuthHandler{
userService: &tenantPolicyUserService{user: &types.User{
ID: "tenantless-user",
Username: "tenantless",
Email: "tenantless@example.com",
}},
configInfo: &config.Config{Tenant: &config.TenantConfig{}},
systemSettingSvc: &tenantPolicySettingService{enabled: false},
}
r := gin.New()
r.GET("/auth/me", h.GetCurrentUser)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/auth/me", nil))
if w.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `"can_create_tenant":false`) {
t.Fatalf("response missing capability: %s", w.Body.String())
}
}