Open registration: REGISTRATION_ENABLED signs up without an invite

60fbb92 · gmorell · 2026-12-03 04:27

19 files +836 -57
Message
{commit_body(@commit)}

Files changed

modified README.md
+54 −4
@@ -20,7 +20,7 @@ Built with:
20 20 allow-list. Otherwise create it once as an admin before deploying.
21 21 - Search needs at least 3 characters, the shortest pattern a trigram
22 22 index can serve.
23 −- **Auth**: Argon2 password hashing, cookie sessions, invite-only registration, email verification (mail through mail-prism), optional "Sign in with NEIAM" (OIDC), and per-device bearer tokens (hashed, 90-day sliding expiry) for the Android app and scripts
23 +- **Auth**: Argon2 password hashing, cookie sessions, invite-only or open registration, email verification (mail through mail-prism), optional "Sign in with NEIAM" (OIDC), and per-device bearer tokens (hashed, 90-day sliding expiry) for the Android app and scripts
24 24 - **Tailwind + DaisyUI** with light and dark themes and a theme switcher (`just assets` to build)
25 25 - Prometheus metrics at `/metrics`, health check at `/healthz`
26 26 - A `Dockerfile` (assets → cargo → debian-slim) and `compose.yml` (Postgres + web)
@@ -204,7 +204,7 @@ by itself, and works signed out.
204 204 **What is collected:** the address an account used when it:
205 205
206 206 - signed in (password or single sign-on);
207 −- registered (redeeming an invite);
207 +- registered (open sign-up or an invite);
208 208 - started a topic or replied;
209 209 - flagged a post;
210 210 - used the app (at most one update per address every ten minutes).
@@ -256,7 +256,10 @@ directly to the internet, no proxy).
256 256 | `SESSION_DURATION_HOURS` | `24` | Cookie session lifetime |
257 257 | `REGISTRATION_TOKEN_DURATION_DAYS` | `7` | Default invite validity |
258 258 | `AUTO_MIGRATE` | `true` | Run migrations on boot |
259 −| `REGISTRATION_ENABLED` | `false` | Allow `/register` without an invite link (token still required) |
259 +| `REGISTRATION_ENABLED` | `false` | Open sign-up: `/register` creates an account without an invite (unverified until the emailed link is followed). Invite links work either way. See [Registration](#registration) |
260 +| `REGISTRATION_PER_IP_PER_DAY` | `3` | Open sign-ups per client address per 24 hours (`0`: no limit). Invites are exempt |
261 +| `REGISTRATION_MIN_FILL_SECS` | `3` | Least time between serving the sign-up form and submitting it (`0`: off). Invites are exempt |
262 +| `REGISTRATION_UNVERIFIED_TTL_DAYS` | `7` | Accounts that never verify their email and never post are deleted after this many days (`0`: kept). Only while `REQUIRE_EMAIL_VERIFICATION` |
260 263 | `PUBLIC_URL` | `http://localhost:<BIND port>` | Public origin: base of email-verification links, the default OIDC redirect URI, the API-token curl example and link-preview URLs. `https://` also marks the session cookie `Secure` |
261 264 | `MIN_TRUST_TO_CREATE_TAG` | `3` | Trust level needed to mint new tags |
262 265 | `MIN_TRUST_TO_FLAG` | `1` | Trust level needed to flag a post (0–4) |
@@ -419,9 +422,46 @@ against a scratch database; `just fixtures` refreshes the responses the app's
419 422 contract test decodes. The plan, and what came out differently, is
420 423 [`docs/android.md`](docs/android.md).
421 424
425 +## Registration
426 +
427 +Invite-only by default: `/register` needs an invite link (`/register?token=…`,
428 +from the Invites page or `manage invite create`), optionally pinned to one
429 +email address. With `REGISTRATION_ENABLED=true` anyone can sign up at
430 +`/register` without one; an invite link still works and is still redeemed
431 +(email pin included). Either way the account starts unverified (below) and is
432 +mailed a verification link, and the sign-up shows in the moderation log
433 +(`Signed up`, "open sign-up" or "with an invite") and at the top of
434 +`/admin/users`, which lists newest accounts first.
435 +
436 +Open sign-ups (no invite) pass three cheap guards (`src/registration.rs`):
437 +
438 +- **Per address:** at most `REGISTRATION_PER_IP_PER_DAY` accounts from one
439 + client address in 24 hours (the address as resolved through
440 + `TRUSTED_PROXIES`, counted from `user_ips`), else 429.
441 +- **Honeypot:** a `website` field people never see; a bot that fills it in is
442 + refused.
443 +- **Fill time:** the form carries a signed timestamp (HMAC, key derived from
444 + `LINK_SECRET`); a submission sooner than `REGISTRATION_MIN_FILL_SECS`, or
445 + with a missing, forged or day-old stamp, is refused and the form is shown
446 + again.
447 +
448 +Redeeming an invite skips all three. An account that never verifies and never
449 +writes anything is deleted after `REGISTRATION_UNVERIFIED_TTL_DAYS`, checked at
450 +start and hourly, with a `Removed unverified account` log entry; staff
451 +accounts are never touched.
452 +
453 +At boot the server logs its registration settings, and warns when
454 +`REGISTRATION_ENABLED=true` is combined with `REQUIRE_EMAIL_VERIFICATION=false`
455 +(anyone could post without a working address) or with no mail-prism configured
456 +(verification links would only be logged, so nobody can verify). It warns
457 +rather than refusing to start.
458 +
459 +Single sign-on is separate: `REGISTRATION_ENABLED` doesn't affect it. See
460 +[Sign in with NEIAM](#sign-in-with-neiam).
461 +
422 462 ## Email verification
423 463
424 −New accounts (registration through an invite) start **unverified**: they can
464 +New accounts (open sign-up or an invite) start **unverified**: they can
425 465 read everything but can't post, reply, react, bookmark or create tags until
426 466 they follow the link mailed to them. A banner says so, with a "Resend link"
427 467 button (also on the profile; at most one link per 10 minutes). Links are
@@ -477,6 +517,16 @@ keeping registration invite-only by default. A taken username or email is
477 517 never taken over, and accounts created this way are never staff. In
478 518 `sso_strict`, password login and local registration are refused.
479 519
520 +`OIDC_PROVISION` is independent of `REGISTRATION_ENABLED`. With
521 +`OIDC_PROVISION=auto`, anyone who can sign in to the provider gets an account
522 +on first login, whether or not password sign-up is open, and it skips the
523 +open sign-up guards (the provider vouched for the login). With
524 +`OIDC_TRUST_EMAIL=true` and a verified email claim the account starts
525 +verified. Otherwise it starts unverified, like any other: no link is mailed at
526 +creation, so the person uses the banner's "Resend link". If they never verify
527 +and never post, the unverified-account sweep removes it (and its NEIAM link).
528 +With `auto` they get a fresh account the next time they sign in.
529 +
480 530 ## Binaries
481 531
482 532 - `recourse` — the web service
modified src/auth/mod.rs
+1 −1
@@ -17,5 +17,5 @@ pub use tokens::{
17 17 };
18 18 pub use users::{
19 19 authenticate_user, change_password, create_user, create_user_direct, deactivate_user, get_user_by_id,
20 − update_user, CreateUserRequest, LoginRequest,
20 + update_user, CreateUserRequest, LoginRequest, RegisterError,
21 21 };
modified src/auth/users.rs
+84 −17
@@ -2,6 +2,7 @@ use crate::auth::{password, tokens};
2 2 use crate::entities::{user_sessions, users};
3 3 use anyhow::{Context, Result};
4 4 use chrono::Utc;
5 +use sea_orm::sea_query::{Expr, Func};
5 6 use sea_orm::*;
6 7 use uuid::Uuid;
7 8
@@ -10,7 +11,11 @@ pub struct CreateUserRequest {
10 11 pub username: String,
11 12 pub email: String,
12 13 pub password: String,
13 − pub registration_token: String,
14 + /// An invite. With one, it must be valid (and match its email, if it's
15 + /// pinned to one) and is redeemed; without one, only when `open`.
16 + pub registration_token: Option<String>,
17 + /// `REGISTRATION_ENABLED`: an account may be created without an invite.
18 + pub open: bool,
14 19 }
15 20
16 21 #[derive(Debug)]
@@ -19,30 +24,90 @@ pub struct LoginRequest {
19 24 pub password: String,
20 25 }
21 26
22 −/// Create a new user, validating the supplied registration token first.
23 −pub async fn create_user(db: &DatabaseConnection, request: CreateUserRequest) -> Result<users::Model> {
24 − let reg_token =
25 − tokens::validate_registration_token(db, &request.registration_token, &request.email)
26 − .await
27 − .context("Failed to validate registration token")?;
27 +/// Why registration refused. Everything but `Internal` is shown to the
28 +/// person registering.
29 +#[derive(Debug)]
30 +pub enum RegisterError {
31 + /// Closed registration and no invite.
32 + InviteRequired,
33 + InvalidInvite,
34 + Taken,
35 + Invalid(&'static str),
36 + Internal(anyhow::Error),
37 +}
38 +
39 +impl RegisterError {
40 + pub fn message(&self) -> &'static str {
41 + match self {
42 + Self::InviteRequired => "You need an invite to register here.",
43 + Self::InvalidInvite => "This invite is invalid, expired, already used, or for a different email address.",
44 + Self::Taken => "That username or email is already registered.",
45 + Self::Invalid(m) => m,
46 + Self::Internal(_) => "Registration failed. Please try again.",
47 + }
48 + }
49 +}
50 +
51 +impl std::fmt::Display for RegisterError {
52 + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 + match self {
54 + Self::Internal(e) => write!(f, "{e:#}"),
55 + other => f.write_str(other.message()),
56 + }
57 + }
58 +}
28 59
29 − let reg_token = match reg_token {
30 − Some(token) => token,
31 − None => return Err(anyhow::anyhow!("Invalid or expired registration token")),
60 +impl From<anyhow::Error> for RegisterError {
61 + fn from(e: anyhow::Error) -> Self {
62 + Self::Internal(e)
63 + }
64 +}
65 +
66 +/// Usernames people type in: 3-32 of letters, digits, `_ . -`.
67 +fn valid_username(name: &str) -> bool {
68 + (3..=32).contains(&name.chars().count())
69 + && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
70 +}
71 +
72 +/// Create an account from the registration form: through an invite (always
73 +/// allowed, redeems it) or, with open registration, without one. The
74 +/// account starts unverified, like every self-made account.
75 +pub async fn create_user(db: &DatabaseConnection, request: CreateUserRequest) -> Result<users::Model, RegisterError> {
76 + let username = request.username.trim().to_string();
77 + let email = request.email.trim().to_string();
78 + if !valid_username(&username) {
79 + return Err(RegisterError::Invalid("Usernames are 3 to 32 letters, digits, dots, dashes or underscores."));
80 + }
81 + if !email.contains('@') || email.len() > 254 || email.chars().any(char::is_whitespace) {
82 + return Err(RegisterError::Invalid("Enter a valid email address."));
83 + }
84 + if request.password.chars().count() < 8 {
85 + return Err(RegisterError::Invalid("Passwords need at least 8 characters."));
86 + }
87 + let token = request.registration_token.as_deref().map(str::trim).filter(|t| !t.is_empty());
88 + let reg_token = match token {
89 + Some(t) => Some(
90 + tokens::validate_registration_token(db, t, &email)
91 + .await
92 + .context("Failed to validate registration token")?
93 + .ok_or(RegisterError::InvalidInvite)?,
94 + ),
95 + None if request.open => None,
96 + None => return Err(RegisterError::InviteRequired),
32 97 };
33 98
34 99 let existing_user = users::Entity::find()
35 100 .filter(
36 101 Condition::any()
37 − .add(users::Column::Username.eq(&request.username))
38 − .add(users::Column::Email.eq(&request.email)),
102 + .add(Expr::expr(Func::lower(Expr::col(users::Column::Username))).eq(username.to_lowercase()))
103 + .add(Expr::expr(Func::lower(Expr::col(users::Column::Email))).eq(email.to_lowercase())),
39 104 )
40 105 .one(db)
41 106 .await
42 107 .context("Failed to check existing users")?;
43 108
44 109 if existing_user.is_some() {
45 − return Err(anyhow::anyhow!("Username or email already exists"));
110 + return Err(RegisterError::Taken);
46 111 }
47 112
48 113 let password_hash =
@@ -50,13 +115,15 @@ pub async fn create_user(db: &DatabaseConnection, request: CreateUserRequest) ->
50 115
51 116 // Staff is never granted implicitly: use `manage user create --staff` or
52 117 // `manage user set-staff`.
53 − let new_user = new_user_model(request.username, request.email, password_hash, false);
118 + let new_user = new_user_model(username, email, password_hash, false);
54 119
55 120 let user = new_user.insert(db).await.context("Failed to create user")?;
56 121
57 − tokens::mark_registration_token_used(db, reg_token.id, user.id)
58 − .await
59 − .context("Failed to mark registration token as used")?;
122 + if let Some(t) = reg_token {
123 + tokens::mark_registration_token_used(db, t.id, user.id)
124 + .await
125 + .context("Failed to mark registration token as used")?;
126 + }
60 127
61 128 Ok(user)
62 129 }
modified src/config.rs
+7 −2
@@ -13,9 +13,13 @@ pub struct Config {
13 13 pub registration_token_duration_days: i64,
14 14 /// Run pending migrations on startup.
15 15 pub auto_migrate: bool,
16 − /// Allow `/register` without an invite link. Invite tokens are still
17 − /// required to actually create the account.
16 + /// Open sign-up: `/register` creates an account without an invite
17 + /// (still unverified until the emailed link is followed). Invites work
18 + /// either way.
18 19 pub registration_enabled: bool,
20 + /// Open sign-up's abuse guards (`REGISTRATION_PER_IP_PER_DAY`,
21 + /// `REGISTRATION_MIN_FILL_SECS`, `REGISTRATION_UNVERIFIED_TTL_DAYS`).
22 + pub registration: crate::registration::Guards,
19 23 /// Minimum trust level required to mint NEW tags (Discourse default: 3).
20 24 /// Lower-tier users can still apply existing tags. Staff always can.
21 25 pub min_trust_to_create_tag: i32,
@@ -107,6 +111,7 @@ impl Config {
107 111 registration_enabled: env::var("REGISTRATION_ENABLED")
108 112 .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
109 113 .unwrap_or(false),
114 + registration: crate::registration::Guards::from_env(),
110 115 trusted_proxies: match env::var("TRUSTED_PROXIES") {
111 116 Ok(v) => crate::client_ip::TrustedProxies::parse(&v)
112 117 .unwrap_or_else(|e| panic!("TRUSTED_PROXIES: {e}")),
modified src/handlers/auth.rs
+87 −20
@@ -120,8 +120,20 @@ pub async fn show_register(
120 120 if invite_token.is_none() && !state.config.registration_enabled {
121 121 return Err(StatusCode::NOT_FOUND);
122 122 }
123 − render(
124 − &state,
123 + register_page(&state, invite_token, None, "", "", StatusCode::OK)
124 +}
125 +
126 +/// The registration form, fresh or with `error` and what was typed.
127 +fn register_page(
128 + state: &AppState,
129 + invite_token: Option<&str>,
130 + error: Option<&str>,
131 + username: &str,
132 + email: &str,
133 + status: StatusCode,
134 +) -> Result<Response, StatusCode> {
135 + let html = render(
136 + state,
125 137 "auth/register.html",
126 138 context! {
127 139 title => "Register",
@@ -129,9 +141,13 @@ pub async fn show_register(
129 141 invite_token => invite_token,
130 142 registration_open => state.config.registration_enabled,
131 143 providers => state.config.oidc.enabled(),
144 + stamp => crate::registration::stamp(&state.config),
145 + error => error,
146 + username => username,
147 + email => email,
132 148 },
133 − )
134 − .map(IntoResponse::into_response)
149 + )?;
150 + Ok((status, html).into_response())
135 151 }
136 152
137 153 /// Show the invite-management page (logged-in users only).
@@ -272,37 +288,78 @@ pub struct RegisterForm {
272 288 pub email: String,
273 289 pub password: String,
274 290 pub confirm_password: String,
275 − pub registration_token: String,
291 + /// Absent (not just empty) on the open form.
292 + #[serde(default)]
293 + pub registration_token: Option<String>,
294 + /// The honeypot: hidden from people, so anything in it is a bot.
295 + #[serde(default)]
296 + pub website: Option<String>,
297 + /// When the form was served, signed ([`crate::registration::stamp`]).
298 + #[serde(default)]
299 + pub stamp: Option<String>,
276 300 }
277 301
278 −/// Handle a registration form submission. The new account starts unverified
279 −/// (it can read, not post) and is mailed a verification link.
302 +/// Handle a registration form submission: through an invite, or (with
303 +/// `REGISTRATION_ENABLED`) without one, past the guards in
304 +/// [`crate::registration`]. The new account starts unverified (it can read,
305 +/// not post) and is mailed a verification link.
280 306 pub async fn handle_register(
281 307 State(state): State<AppState>,
282 308 ip: crate::client_ip::ClientIp,
283 309 Form(form): Form<RegisterForm>,
284 −) -> Result<impl IntoResponse, StatusCode> {
310 +) -> Result<Response, StatusCode> {
285 311 if !local_login(&state) {
286 312 return Err(StatusCode::FORBIDDEN);
287 313 }
314 + let token = form.registration_token.as_deref().map(str::trim).filter(|t| !t.is_empty());
315 + let again = |msg: &str, status: StatusCode| register_page(&state, token, Some(msg), &form.username, &form.email, status);
316 +
317 + // Open sign-up (no invite): the honeypot, the fill time, the per-address
318 + // limit. Closed registration refuses it below anyway.
319 + if token.is_none() && state.config.registration_enabled {
320 + let guard = match crate::registration::check_form(&state.config, form.website.as_deref(), form.stamp.as_deref()) {
321 + Ok(()) => crate::registration::check_rate(state.db.as_ref(), &state.config, ip.0).await,
322 + Err(r) => Err(r),
323 + };
324 + if let Err(r) = guard {
325 + tracing::info!(ip = ?ip.0, refused = ?r, "open sign-up refused");
326 + let status = match r {
327 + crate::registration::Refused::TooMany => StatusCode::TOO_MANY_REQUESTS,
328 + _ => StatusCode::BAD_REQUEST,
329 + };
330 + return again(r.message(), status);
331 + }
332 + }
288 333 if form.password != form.confirm_password {
289 − return Err(StatusCode::BAD_REQUEST);
334 + return again("The passwords don't match.", StatusCode::BAD_REQUEST);
290 335 }
291 336
292 − let user = auth::create_user(
337 + let user = match auth::create_user(
293 338 &state.db,
294 339 CreateUserRequest {
295 − username: form.username,
296 − email: form.email,
297 − password: form.password,
298 − registration_token: form.registration_token,
340 + username: form.username.clone(),
341 + email: form.email.clone(),
342 + password: form.password.clone(),
343 + registration_token: token.map(str::to_string),
344 + open: state.config.registration_enabled,
299 345 },
300 346 )
301 347 .await
302 − .map_err(|e| {
303 − error!(error = %e, "registration failed");
304 − StatusCode::BAD_REQUEST
305 − })?;
348 + {
349 + Ok(u) => u,
350 + Err(auth::RegisterError::InviteRequired) => return Err(StatusCode::NOT_FOUND),
351 + Err(e) => {
352 + if matches!(e, auth::RegisterError::Internal(_)) {
353 + error!(error = %e, "registration failed");
354 + }
355 + let status = match e {
356 + auth::RegisterError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
357 + auth::RegisterError::Taken => StatusCode::CONFLICT,
358 + _ => StatusCode::BAD_REQUEST,
359 + };
360 + return again(e.message(), status);
361 + }
362 + };
306 363
307 364 // Best effort: a failed send is logged, and the banner offers a resend.
308 365 verification::send(&state.db, state.mailer.as_ref(), &state.config, &user).await;
@@ -310,9 +367,19 @@ pub async fn handle_register(
310 367 let session = auth::create_session(&state.db, user.id, state.config.session_duration_hours)
311 368 .await
312 369 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
313 − // Registration always redeems an invite; this is where it came from.
370 + // Where it came from (staff see it; the per-address limit counts it).
314 371 crate::ips::record(state.db.as_ref(), user.id, ip.0, crate::ips::Seen::Register).await;
315 − Ok((session_cookie(&state, &session.session_token), Redirect::to("/")))
372 + crate::moderation::log(
373 + state.db.as_ref(),
374 + crate::moderation::Actor::web(&user),
375 + "register",
376 + "user",
377 + Some(user.id),
378 + &user.username,
379 + Some(if token.is_some() { "with an invite" } else { "open sign-up" }),
380 + )
381 + .await;
382 + Ok((session_cookie(&state, &session.session_token), Redirect::to("/")).into_response())
316 383 }
317 384
318 385 /// Handle logout — delete the session and clear the cookie.
modified src/handlers/moderation.rs
+5 −2

Click to load diff…

modified src/lib.rs
+1 −0

Click to load diff…

modified src/main.rs
+12 −0

Click to load diff…

modified src/moderation.rs
+1 −1

Click to load diff…

added src/registration.rs
+279 −0

Click to load diff…

modified templates/auth/login.html
+1 −1

Click to load diff…

modified templates/auth/register.html
+19 −7

Click to load diff…

modified tests/moderation_db.rs
+285 −2

Click to load diff…

Parents: 83838e8