Files
Enterprise-Knowledge-Base/internal/handler/auth_register_invite_only_test.go
T
wizardchen 3f7150cb5c feat(rbac): tenant member management + invite_only gate (PR 3 of 3, #1303)
Wire the human-facing surface for the tenant-RBAC system that PR 1
introduced and PR 2 enforced: REST endpoints + UI for managing tenant
members, plus the long-pending invite_only registration gate.

Backend
- internal/handler/auth.go: Register now rejects with 403 when
  auth.registration_mode=invite_only. PR 1 already exposes the mode via
  /auth/config so the frontend hides the sign-up link; this is the
  server-side enforcement for direct API calls.
- internal/handler/tenant_member.go: new TenantMemberHandler with
  ListMembers / AddMember / UpdateMemberRole / RemoveMember. Maps
  service-layer sentinels onto HTTP semantics (ErrLastOwner -> 409,
  ErrMembershipAlreadyExists -> 409, ErrUserNotFound on AddMember -> 404,
  ErrInvalidTenantRole -> 400). AddMember requires the invitee to
  already have an account; SMTP-driven email invites are deferred.
- internal/types/tenant_member.go: new TenantMemberResponse projection
  carrying the fields the management UI renders (email, username,
  avatar, role, joined_at).
- internal/router/router.go: four routes under /tenants/:id/members
  gated per the matrix (Viewer+ for list, Owner+ for every mutation).
- internal/container/container.go: dig provider for the new handler.

Tests
- handler/tenant_member_test.go: 12 table-driven cases covering happy
  path, dangling-user tolerance, ErrLastOwner -> 409, ErrMembershipNotFound
  -> 404, ErrMembershipAlreadyExists -> 409, unknown email -> 404,
  invalid role rejected before user lookup, bad tenant id -> 400.
- handler/auth_register_invite_only_test.go: invite_only -> 403,
  self_serve -> 201, nil Auth config falls through.

Frontend
- src/api/tenant/members.ts: typed client (TenantRole/TenantMember/...)
  for the four endpoints.
- src/views/settings/TenantMembers.vue: members table with add dialog,
  inline role select, confirm-remove modal. All mutation widgets gated
  behind currentTenantRole === 'owner'; server still enforces.
- src/views/settings/Settings.vue: register the Members tab; show only
  when currentTenantRole is loaded (avoids tab flash on cold nav).
- i18n in en-US/zh-CN/ko-KR/ru-RU: new tenantMember namespace covering
  all UI strings and structured error messages (lastOwner / userNotFound
  / alreadyMember / invalidRole etc).

This completes the #1303 RBAC rollout. With cfg.Tenant.EnableRBAC=true
operators now have a full management surface; with EnableRBAC=false
the routes still exist but mutations log-and-pass per PR 2 contract.
2026-05-18 17:28:58 +08:00

145 lines
4.9 KiB
Go

package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"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"
)
// stubRegisterUserService is a UserService whose ONLY useful method is
// Register; every other call panics. Using an interface embedding plus a
// targeted override keeps the test focused on the Register handler's
// branching logic without dragging in the entire user service surface.
type stubRegisterUserService struct {
interfaces.UserService
register func(ctx context.Context, req *types.RegisterRequest) (*types.User, error)
}
func (s *stubRegisterUserService) Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error) {
return s.register(ctx, req)
}
// errorCapture mirrors gin's default ErrorHandler behaviour for tests:
// when a handler calls c.Error(), we surface it as an HTTP response so the
// recorder reflects the real client-visible status. The production
// middleware does the same thing in middleware/error_handler.go.
func errorCapture() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 {
return
}
err := c.Errors.Last().Err
if appErr, ok := err.(*apperrors.AppError); ok {
c.JSON(appErr.HTTPCode, gin.H{"error": appErr.Message})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
}
func newRegisterTestRouter(h *AuthHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register", h.Register)
return r
}
func doRegister(t *testing.T, r *gin.Engine, body any) *httptest.ResponseRecorder {
t.Helper()
buf, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/auth/register", bytes.NewReader(buf))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
// validRegisterBody returns a payload that passes parameter validation, so
// each test is exercising the gate logic and not the body parser.
func validRegisterBody() map[string]string {
return map[string]string{
"username": "alice",
"email": "alice@example.com",
"password": "supersecret",
}
}
func TestRegister_InviteOnlyRejects(t *testing.T) {
// PR 3 (#1303): when auth.registration_mode=invite_only, Register
// must respond 403 BEFORE touching the user service. The frontend
// already hides the sign-up link via /auth/config; this is the
// server-side enforcement for direct API hits.
called := false
us := &stubRegisterUserService{
register: func(context.Context, *types.RegisterRequest) (*types.User, error) {
called = true
return &types.User{ID: "u1"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},
}, us, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusForbidden {
t.Fatalf("invite_only must return 403, got %d body=%s", w.Code, w.Body.String())
}
if called {
t.Fatalf("UserService.Register must not be called when invite_only blocks the request")
}
}
func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
// Default registration_mode keeps PR 1 behaviour intact: the gate
// is dormant and the request reaches the user service. We don't
// exercise the real service here — just confirm the gate let it
// through by observing the stub being invoked.
called := false
us := &stubRegisterUserService{
register: func(_ context.Context, _ *types.RegisterRequest) (*types.User, error) {
called = true
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
}, us, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
t.Fatalf("self_serve must allow registration, got %d body=%s", w.Code, w.Body.String())
}
if !called {
t.Fatalf("UserService.Register should have been invoked")
}
}
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
// legacy "registration enabled" behaviour. Mirrors the nil guard in
// the handler so a config-loading bug doesn't take the server down.
us := &stubRegisterUserService{
register: func(_ context.Context, _ *types.RegisterRequest) (*types.User, error) {
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
t.Fatalf("nil Auth config must fall back to allow, got %d body=%s", w.Code, w.Body.String())
}
}