3611a8607d
* feat(rbac): add multi-use share-link invitations for invite_only mode When the auth.registration_mode toggle flips to invite_only, the public /auth/register endpoint returns 403 — but until now there was no channel for unregistered users to actually join a tenant. The existing invitation table required a registered invitee, so new emails could not enter the system at all. This change introduces a share-link model: - Owner generates a multi-use registration link with a per-tenant role - Recipient opens the link, registers with their own email, and is added to the tenant on the same request - Token is stored in plaintext (not hashed) so the management UI can re-display the URL on demand without a "copy now or revoke" trap. Threat model is bounded by 7-day TTL, revocability, and the fact that all the link grants is membership in one tenant. - accepted_count tracks how many users joined through the link so the Owner can tell whether a link is fresh or has already been spread Per-user invitations (registered email -> in-app inbox accept) are unchanged. Share-link rows use empty invitee_user_id as discriminator; the partial unique index on (tenant_id, invitee_user_id) was relaxed to skip empty values so multiple share links can coexist per tenant. Frontend reuses Login.vue for /register?token=xxx instead of a parallel page, and adds icon-only revoke / remove actions plus a distinct "active" status tag for share-link rows. Migration 000054 adds the token column, the accepted_count column, and the relaxed pending unique index in a single step. * feat(auth): update invitation token handling and add rate limiting - Refactor the invitation token retrieval to use POST instead of GET, enhancing security by preventing the plaintext token from appearing in logs and browser history. - Update the API endpoint from `/auth/invitations/:token` to `/auth/invitations/lookup` to reflect the new method. - Introduce a rate limiter for unauthenticated share-link endpoints to mitigate brute-force attacks and abuse, ensuring a maximum of 30 requests per minute per IP. - Adjust the registration flow to maintain user experience while securing the invitation process.
145 lines
4.9 KiB
Go
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, nil, 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, nil, 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, nil, 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())
|
|
}
|
|
}
|