feat(rbac): add multi-use share-link invitations for invite_only mode (#1504)

* 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.
This commit is contained in:
lyingbug
2026-05-27 19:42:01 +08:00
committed by GitHub
parent 6220667517
commit 3611a8607d
24 changed files with 1687 additions and 47 deletions
+7
View File
@@ -27,6 +27,11 @@ type AuthHandler struct {
tenantService interfaces.TenantService
configInfo *config.Config
systemSettingSvc interfaces.SystemSettingService
// invitationSvc is required for the share-link registration path
// (POST /auth/register-by-invite). When nil — e.g. legacy test
// fixtures — the share-link endpoints respond 503 rather than
// blocking the rest of the auth surface.
invitationSvc interfaces.TenantInvitationService
}
// NewAuthHandler creates a new auth handler instance with the provided services
@@ -44,6 +49,7 @@ type AuthHandler struct {
func NewAuthHandler(configInfo *config.Config,
userService interfaces.UserService, tenantService interfaces.TenantService,
systemSettingSvc interfaces.SystemSettingService,
invitationSvc interfaces.TenantInvitationService,
) *AuthHandler {
// Boot-time guard: a nil-or-empty Auth section silently disables the
// invite_only gate (see Register below). Emit a loud one-shot log
@@ -60,6 +66,7 @@ func NewAuthHandler(configInfo *config.Config,
userService: userService,
tenantService: tenantService,
systemSettingSvc: systemSettingSvc,
invitationSvc: invitationSvc,
}
}
+216
View File
@@ -0,0 +1,216 @@
package handler
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// registerByInviteRequest is the body for /auth/register-by-invite.
//
// Email is collected from the invitee themselves: share-link rows have
// no specific invitee, so we cannot pre-bind any address. The token
// IS the authorisation; the email is whatever account the invitee
// wants to register.
type registerByInviteRequest struct {
Token string `json:"token" binding:"required"`
Email string `json:"email" binding:"required,email"`
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
}
// invitationLookupResponse is the public projection of a share-link
// row returned by /auth/invitations/lookup. Kept narrow on purpose:
// just enough for the registration page to render context ("X invited
// you to Y") without exposing inviter audit fields.
type invitationLookupResponse struct {
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name,omitempty"`
Role types.TenantRole `json:"role"`
ExpiresAt string `json:"expires_at"`
}
// invitationLookupRequest carries the token in the request body
// instead of the URL path: GET /auth/invitations/:token would have
// landed the plaintext token in access logs, browser history, and
// tracing spans. POST + body keeps the token out of those surfaces
// at the cost of "this endpoint reads, why is it POST" — worth it
// because the token is the sole authorisation for registration.
type invitationLookupRequest struct {
Token string `json:"token" binding:"required"`
}
// LookupInvitationByToken godoc
// @Summary 解析共享邀请链接 token
// @Description 根据邀请链接中的 token 返回邀请上下文(租户名 / 角色 / 过期时间),
// @Description 供注册页展示。无认证;token 无效或被撤销返回 410。
// @Description 使用 POST + body 而非 GET + path,避免 token 落入访问日志 / 浏览器历史 / tracing。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body invitationLookupRequest true "邀请 token"
// @Success 200 {object} invitationLookupResponse
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
// @Router /auth/invitations/lookup [post]
func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {
ctx := c.Request.Context()
if h.invitationSvc == nil {
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
return
}
var req invitationLookupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("token is required").WithDetails(err.Error()))
return
}
token := strings.TrimSpace(req.Token)
if token == "" {
c.Error(apperrors.NewValidationError("token is required"))
return
}
inv, err := h.invitationSvc.LookupByToken(ctx, token)
if err != nil {
// Collapse "unknown / expired / revoked" into 410 to avoid
// leaking which slot a stolen token used to occupy.
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is invalid or has been revoked",
HTTPCode: http.StatusGone,
})
return
}
resp := invitationLookupResponse{
TenantID: inv.TenantID,
Role: inv.Role,
ExpiresAt: inv.ExpiresAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
}
if tenant, terr := h.tenantService.GetTenantByID(ctx, inv.TenantID); terr == nil && tenant != nil {
resp.TenantName = tenant.Name
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": resp,
})
}
// RegisterByInvite godoc
// @Summary 使用共享链接注册
// @Description 通过 Owner 生成的共享邀请链接 token 完成注册,绕过 invite_only 模式拦截。
// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应租户。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body registerByInviteRequest true "邀请注册请求"
// @Success 201 {object} types.LoginResponse
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 409 {object} errors.AppError "邮箱已注册"
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
// @Router /auth/register-by-invite [post]
//
// RegisterByInvite is intentionally NOT subject to the invite_only gate:
// the gate suppresses public registration, while this endpoint requires
// a valid token issued by an Owner. The token IS the authorisation.
func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
ctx := c.Request.Context()
if h.invitationSvc == nil {
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
return
}
var req registerByInviteRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("Invalid registration parameters").WithDetails(err.Error()))
return
}
req.Token = strings.TrimSpace(req.Token)
req.Email = strings.TrimSpace(strings.ToLower(req.Email))
req.Username = strings.TrimSpace(req.Username)
// Password is intentionally NOT sanitized: SanitizeForLog strips
// \n, \r, \t and control chars to make a string safe to write into
// a log line — applying it to a real password would silently
// rewrite the stored credential and lock the user out. Passwords
// must never be logged, so they don't need that defence here.
if req.Token == "" || req.Email == "" || req.Username == "" || req.Password == "" {
c.Error(apperrors.NewValidationError("token, email, username and password are required"))
return
}
inv, err := h.invitationSvc.LookupByToken(ctx, req.Token)
if err != nil {
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is invalid or has been revoked",
HTTPCode: http.StatusGone,
})
return
}
// If the email already has an account we shouldn't quietly succeed
// here: register would fail with a duplicate-email error, but the
// share-link flow is "create new account + join tenant", not "join
// my existing account". Surface 409 so the SPA can prompt them to
// log in instead, and the invitation can be applied to their
// existing account via /me/invitations once we wire that path.
if existing, _ := h.userService.GetUserByEmail(ctx, req.Email); existing != nil {
c.Error(apperrors.NewConflictError(
"this email already has an account; please log in to join the workspace"))
return
}
user, err := h.userService.Register(ctx, &types.RegisterRequest{
Username: req.Username,
Email: req.Email,
Password: req.Password,
})
if err != nil {
logger.Errorf(ctx, "register-by-invite: user create failed for %s: %v",
secutils.SanitizeForLog(req.Email), err)
c.Error(apperrors.NewBadRequestError(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.
logger.Errorf(ctx, "register-by-invite: accept failed for user %s: %v", user.ID, err)
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is no longer valid; please log in to your new account",
HTTPCode: http.StatusGone,
})
return
}
accessToken, refreshToken, err := h.userService.GenerateTokens(ctx, user)
if err != nil {
logger.Errorf(ctx, "register-by-invite: token generation failed for user %s: %v", user.ID, err)
c.Error(apperrors.NewInternalServerError("token generation failed").WithDetails(err.Error()))
return
}
tenant, _ := h.tenantService.GetTenantByID(ctx, inv.TenantID)
c.JSON(http.StatusCreated, &types.LoginResponse{
Success: true,
Message: "Registration successful",
User: user,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: inv.TenantID,
TenantName: tenantNameOrEmpty(tenant),
Role: inv.Role,
}},
Token: accessToken,
RefreshToken: refreshToken,
})
}
@@ -89,7 +89,7 @@ func TestRegister_InviteOnlyRejects(t *testing.T) {
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},
}, us, nil, nil)
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusForbidden {
@@ -114,7 +114,7 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
}, us, nil, nil)
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
@@ -135,7 +135,7 @@ func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil)
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
+36 -2
View File
@@ -10,6 +10,7 @@ import (
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -26,20 +27,24 @@ type TenantInvitationHandler struct {
invitationService interfaces.TenantInvitationService
userService interfaces.UserService
tenantService interfaces.TenantService
configInfo *config.Config
}
// NewTenantInvitationHandler wires the dependencies. tenantService is
// used to hydrate tenant names in the inbox view so the invitee sees
// "join Foo Workspace" instead of a raw numeric tenant id.
// "join Foo Workspace" instead of a raw numeric tenant id. configInfo
// supplies FrontendBaseURL for share-link URL composition.
func NewTenantInvitationHandler(
invitationService interfaces.TenantInvitationService,
userService interfaces.UserService,
tenantService interfaces.TenantService,
configInfo *config.Config,
) *TenantInvitationHandler {
return &TenantInvitationHandler{
invitationService: invitationService,
userService: userService,
tenantService: tenantService,
configInfo: configInfo,
}
}
@@ -73,6 +78,11 @@ func parseInvitationIDFromPath(c *gin.Context) (uint64, bool) {
// name are filled best-effort: a missing row degrades to the bare id
// rather than dropping the response. usersByID and tenantsByID let the
// caller batch the lookups when projecting a list.
//
// Share-link rows (InviteeUserID == "") get the IsShareLink flag set
// so the SPA can render them differently. invite_url is NOT populated
// here — projectInvitationWithLink layers it on for the management
// view that needs the copy-link affordance.
func projectInvitation(
inv *types.TenantInvitation,
usersByID map[string]*types.User,
@@ -89,6 +99,8 @@ func projectInvitation(
ExpiresAt: inv.ExpiresAt,
RespondedAt: inv.RespondedAt,
CreatedAt: inv.CreatedAt,
IsShareLink: inv.InviteeUserID == "",
AcceptedCount: inv.AcceptedCount,
}
if u, ok := usersByID[inv.InviteeUserID]; ok && u != nil {
resp.InviteeEmail = u.Email
@@ -106,6 +118,26 @@ func projectInvitation(
return resp
}
// projectInvitationWithLink layers invite_url on top of projectInvitation
// for share-link rows that are still pending. The Owner-facing list and
// the create response go through here so a "copy link" button can sit
// on every active row — Owners can dispatch the link on demand without
// the "copy now or revoke" pressure.
//
// The /me/invitations inbox path does NOT use this helper: per-user
// invitees don't have a token to copy.
func (h *TenantInvitationHandler) projectInvitationWithLink(
inv *types.TenantInvitation,
usersByID map[string]*types.User,
tenantsByID map[uint64]*types.Tenant,
) types.TenantInvitationResponse {
resp := projectInvitation(inv, usersByID, tenantsByID)
if inv.Status == types.TenantInvitationStatusPending && inv.Token != "" {
resp.InviteURL = buildInviteRegisterURL(h.configInfo, inv.Token)
}
return resp
}
// hydrateUsers batches GetUsersByIDs over the (invitee, inviter) pairs.
// Best-effort: a transient lookup failure logs and returns an empty
// map so the projection falls back to ids.
@@ -191,7 +223,9 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
for _, inv := range rows {
// Within the tenant view we don't bother hydrating tenant name
// (the caller already knows the tenant). Pass an empty map.
resp = append(resp, projectInvitation(inv, usersByID, nil))
// Use ...WithLink so management UI can re-display invite_url
// for pending share-link rows (re-copy without revoking).
resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
+105
View File
@@ -0,0 +1,105 @@
package handler
import (
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// frontendBaseURLFor returns the externally-visible SPA origin used to
// compose absolute share-link URLs. Lookup order:
// 1. config.FrontendBaseURL (set in YAML or via ${FRONTEND_BASE_URL})
// 2. FRONTEND_BASE_URL env at request time (so an operator can roll
// the value out without restarting the server)
// 3. empty — handler emits a host-relative URL ("/register?token=…")
// and the SPA resolves it against the current origin.
//
// Trailing slashes are stripped so callers can append "/register?…"
// cleanly.
func frontendBaseURLFor(cfg *config.Config) string {
candidate := ""
if cfg != nil {
candidate = strings.TrimSpace(cfg.FrontendBaseURL)
}
if candidate == "" {
candidate = strings.TrimSpace(os.Getenv("FRONTEND_BASE_URL"))
}
return strings.TrimRight(candidate, "/")
}
// buildInviteRegisterURL composes the registration URL Owners hand
// to invitees. Plaintext token is URL-safe by construction (base64url)
// so no extra escaping is required.
func buildInviteRegisterURL(cfg *config.Config, plainToken string) string {
if plainToken == "" {
return ""
}
return frontendBaseURLFor(cfg) + "/register?token=" + plainToken
}
// createInviteLinkRequest is the body for POST /tenants/:id/invite-links.
// Only role + optional message — share-link rows have no specific
// invitee, so the Owner just picks "what role does the holder get".
type createInviteLinkRequest struct {
Role types.TenantRole `json:"role" binding:"required"`
Message string `json:"message"`
}
// CreateInviteLink godoc
// @Summary 生成共享邀请链接
// @Description 生成一条多次使用的共享邀请链接:谁拿到链接谁就能注册并加入当前租户。
// @Description 链接持续有效,直到过期或被撤销。
// @Tags 租户邀请
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param request body createInviteLinkRequest true "共享链接配置"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invite-links [post]
func (h *TenantInvitationHandler) CreateInviteLink(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
var req createInviteLinkRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("invalid request body").WithDetails(err.Error()))
return
}
if !req.Role.IsValid() {
c.Error(apperrors.NewValidationError("role must be one of owner/admin/contributor/viewer"))
return
}
caller, _ := types.UserIDFromContext(ctx)
var invitedBy *string
if caller != "" && !types.IsSyntheticUserID(caller) {
invitedBy = &caller
}
inv, _, err := h.invitationService.CreateShareLink(ctx, tenantID, req.Role, invitedBy, req.Message)
if err != nil {
logger.Errorf(ctx, "CreateShareLink failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to create share link").WithDetails(err.Error()))
return
}
usersByID := map[string]*types.User{}
if invitedBy != nil {
if iu, lookupErr := h.userService.GetUserByID(ctx, *invitedBy); lookupErr == nil && iu != nil {
usersByID[iu.ID] = iu
}
}
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": h.projectInvitationWithLink(inv, usersByID, nil),
})
}