forge
Explore
Log in

Don't you dare go Hollow

Strict username charset + reserved names

Browse files at this commit

43849142f1aa0be0e853a462b14060b592d59f34Ahmet Kaan GümüşParent: 3a5526f
  • feat
    • strict username charset + reserved names
Show full message
✨ feat(auth): strict username charset + reserved names

Usernames accepted any ASCII between the length checks — control
characters, spaces, quotes, and HTML metacharacters all passed, which
enables log injection (\n, ESC), lookalike impersonation ('admin
support'), and stored XSS wherever a frontend renders names unescaped.

- allowlist: lowercase letters, digits, single interior . _ -
- must start and end with a letter or digit; no consecutive separators
- staff-looking names (admin, administrator, root, support, system,
  moderator, staff) rejected at /auth/register only — the
  ADMIN_USERNAME bootstrap still seeds them through the same newtype
- duplicate-register 409 kept: usernames are public handles, the
  existence leak is deliberate

Existing rows are not revalidated or migrated.
src/constant.rsmodified+17 -0
@@ -3,6 +3,23 @@
3 pub const MIN_USERNAME_LEN: usize = 3;3 pub const MIN_USERNAME_LEN: usize = 3;
4 pub const MAX_USERNAME_LEN: usize = 32;4 pub const MAX_USERNAME_LEN: usize = 32;
5 5
6+/// Separators allowed inside a username (never at the edges, never doubled).
7+pub const USERNAME_SEPARATORS: [char; 3] = ['.', '_', '-'];
8+
9+/// Names nobody may claim through `/auth/register`: they read as staff and
10+/// invite impersonation. Enforced at the registration endpoint, not in
11+/// `Username` itself, so the `ADMIN_USERNAME` bootstrap can still seed
12+/// accounts like `admin`.
13+pub const RESERVED_USERNAMES: [&str; 7] = [
14+ "admin",
15+ "administrator",
16+ "root",
17+ "support",
18+ "system",
19+ "moderator",
20+ "staff",
21+];
22+
6 pub const MIN_PASSWORD_LEN: usize = 6;23 pub const MIN_PASSWORD_LEN: usize = 6;
7 pub const MAX_PASSWORD_LEN: usize = 128;24 pub const MAX_PASSWORD_LEN: usize = 128;
8 25
src/domain/user.rsmodified+3 -0
@@ -354,6 +354,9 @@ mod tests {
354 assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali");354 assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali");
355 assert!(Username::try_new("").is_err());355 assert!(Username::try_new("").is_err());
356 assert!(Username::try_new("ab").is_err());356 assert!(Username::try_new("ab").is_err());
357+ assert!(Username::try_new("Ali").is_err());
358+ assert!(Username::try_new("-ali").is_err());
359+ assert!(Username::try_new("ali-").is_err());
357 }360 }
358 361
359 #[tokio::test]362 #[tokio::test]
src/validate.rsmodified+74 -1
@@ -5,7 +5,7 @@ use crate::constant::{
5 ATTENDANCE_STATUSES, EXAM_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS,5 ATTENDANCE_STATUSES, EXAM_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS,
6 MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS,6 MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS,
7 MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN,7 MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN,
8- MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS,8+ MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, USERNAME_SEPARATORS,
9 };9 };
10 use crate::error::ValidationError;10 use crate::error::ValidationError;
11 11
@@ -34,6 +34,43 @@ pub fn validate_username(value: &str) -> Result<(), ValidationError> {
34 got: len,34 got: len,
35 });35 });
36 }36 }
37+ if value.chars().any(|c| c.is_ascii_uppercase()) {
38+ return Err(ValidationError::Invalid {
39+ field: "username",
40+ reason: "must be all lowercase",
41+ });
42+ }
43+ // Allowlist, not "any ASCII": control characters, spaces, quotes, and HTML
44+ // metacharacters inside a username enable log injection, impersonation
45+ // ("admin support"), and stored XSS in sloppy frontends.
46+ if !value
47+ .chars()
48+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || USERNAME_SEPARATORS.contains(&c))
49+ {
50+ return Err(ValidationError::Invalid {
51+ field: "username",
52+ reason: "may contain only lowercase letters, digits, '.', '_' and '-'",
53+ });
54+ }
55+ if !value.starts_with(|c: char| c.is_ascii_alphanumeric())
56+ || !value.ends_with(|c: char| c.is_ascii_alphanumeric())
57+ {
58+ return Err(ValidationError::Invalid {
59+ field: "username",
60+ reason: "must start and end with a letter or digit",
61+ });
62+ }
63+ let mut chars = value.chars().peekable();
64+ while let Some(c) = chars.next() {
65+ if USERNAME_SEPARATORS.contains(&c)
66+ && chars.peek().is_some_and(|n| USERNAME_SEPARATORS.contains(n))
67+ {
68+ return Err(ValidationError::Invalid {
69+ field: "username",
70+ reason: "must not contain consecutive '.', '_' or '-'",
71+ });
72+ }
73+ }
37 Ok(())74 Ok(())
38 }75 }
39 76
@@ -258,6 +295,42 @@ mod tests {
258 assert!(validate_username(&"x".repeat(33)).is_err()); // too long295 assert!(validate_username(&"x".repeat(33)).is_err()); // too long
259 assert!(validate_username("naïve").is_err()); // non-ascii296 assert!(validate_username("naïve").is_err()); // non-ascii
260 assert!(validate_username("a ").is_err()); // padding can't defeat the minimum297 assert!(validate_username("a ").is_err()); // padding can't defeat the minimum
298+ assert!(validate_username("Ali").is_err()); // uppercase
299+ assert!(validate_username("aLi").is_err()); // uppercase inside
300+ assert!(validate_username("ali9").is_ok()); // digits fine, no case
301+ assert!(validate_username("a-li").is_ok()); // separator inside is fine
302+ assert!(validate_username("a.li").is_ok());
303+ assert!(validate_username("a_li").is_ok());
304+ assert!(validate_username("a.b-c_d").is_ok()); // mixed single separators
305+ assert!(validate_username("-ali").is_err()); // must start alphanumeric
306+ assert!(validate_username("ali-").is_err()); // must end alphanumeric
307+ assert!(validate_username("_ali_").is_err());
308+ assert!(validate_username("9ali").is_ok()); // digit edges count as alphanumeric
309+ assert!(validate_username(" ali ").is_ok()); // trimmed before edge check
310+ }
311+
312+ #[tokio::test]
313+ async fn username_interior_is_an_allowlist_not_any_ascii() {
314+ // ASCII control characters and metacharacters between valid edges must
315+ // die here: they enable log injection, spoofing, and stored XSS.
316+ assert!(validate_username("a b").is_err()); // interior space
317+ assert!(validate_username("a\nb").is_err()); // newline survives trim mid-string
318+ assert!(validate_username("a\x1bb").is_err()); // terminal escape
319+ assert!(validate_username("a\x00b").is_err()); // null byte
320+ assert!(validate_username("a<b>c").is_err()); // html metacharacters
321+ assert!(validate_username("a\"b").is_err()); // quote
322+ assert!(validate_username("a@b.c").is_err()); // looks like an email
323+ assert!(validate_username("a/b").is_err());
324+ }
325+
326+ #[tokio::test]
327+ async fn username_separators_must_not_repeat() {
328+ assert!(validate_username("a--b").is_err());
329+ assert!(validate_username("a..b").is_err());
330+ assert!(validate_username("a__b").is_err());
331+ assert!(validate_username("a.-b").is_err()); // mixed pairs count too
332+ assert!(validate_username("a_-b").is_err());
333+ assert!(validate_username("a-b-c").is_ok()); // separated singles are fine
261 }334 }
262 335
263 #[tokio::test]336 #[tokio::test]
src/web/auth.rsmodified+12 -2
@@ -9,10 +9,10 @@ use utoipa::ToSchema;
9 use utoipa_axum::router::OpenApiRouter;9 use utoipa_axum::router::OpenApiRouter;
10 use utoipa_axum::routes;10 use utoipa_axum::routes;
11 11
12-use crate::constant::SESSION_DURATION_DAYS;12+use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};
13 use crate::domain::session::Session;13 use crate::domain::session::Session;
14 use crate::domain::user::{Password, PasswordHash, User, Username};14 use crate::domain::user::{Password, PasswordHash, User, Username};
15-use crate::error::{AppError, ErrorResponse};15+use crate::error::{AppError, ErrorResponse, ValidationError};
16 use crate::rate_limit::{RateLimitConfig, RateLimiter};16 use crate::rate_limit::{RateLimitConfig, RateLimiter};
17 use crate::state::AppState;17 use crate::state::AppState;
18 18
@@ -62,6 +62,16 @@ async fn register(
62 Json(req): Json<Credentials>,62 Json(req): Json<Credentials>,
63 ) -> Result<(StatusCode, Json<UserResponse>), AppError> {63 ) -> Result<(StatusCode, Json<UserResponse>), AppError> {
64 let username = Username::try_new(&req.username)?;64 let username = Username::try_new(&req.username)?;
65+ // Registration-level policy, not a `Username` invariant: these names read
66+ // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap
67+ // must still be able to seed e.g. `admin` through the same newtype.
68+ if RESERVED_USERNAMES.contains(&username.as_str()) {
69+ return Err(ValidationError::Invalid {
70+ field: "username",
71+ reason: "this username is reserved",
72+ }
73+ .into());
74+ }
65 let password_hash = Password::try_new(&req.password)?.hash()?;75 let password_hash = Password::try_new(&req.password)?.hash()?;
66 let user = User::create(username, password_hash, &st.db).await?;76 let user = User::create(username, password_hash, &st.db).await?;
67 Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))77 Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))
tests/integration.rsmodified+66 -2
@@ -58,6 +58,40 @@ async fn register_validates_input() {
58 let res = send(&app, "POST", "/auth/register", None, Some(blank)).await;58 let res = send(&app, "POST", "/auth/register", None, Some(blank)).await;
59 assert_eq!(res.status, StatusCode::BAD_REQUEST);59 assert_eq!(res.status, StatusCode::BAD_REQUEST);
60 60
61+ // Uppercase anywhere in the username -> 400.
62+ for bad in ["Bob", "bOb", "BOB"] {
63+ let upper = json!({ "username": bad, "password": "secret1" });
64+ let res = send(&app, "POST", "/auth/register", None, Some(upper)).await;
65+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
66+ }
67+
68+ // Username must start and end with a letter or digit -> 400.
69+ for bad in ["-bob", "bob-", "_bob", "bob_", ".bob"] {
70+ let edge = json!({ "username": bad, "password": "secret1" });
71+ let res = send(&app, "POST", "/auth/register", None, Some(edge)).await;
72+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
73+ }
74+
75+ // Interior characters are an allowlist: lowercase, digits, . _ - only.
76+ for bad in ["a b", "a\nb", "a\u{1b}[31mb", "a<b>c", "a@b.c", "a/b", "a\"b"] {
77+ let ugly = json!({ "username": bad, "password": "secret1" });
78+ let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await;
79+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted");
80+ }
81+
82+ // Consecutive separators -> 400.
83+ for bad in ["a--b", "a..b", "a__b", "a.-b"] {
84+ let doubled = json!({ "username": bad, "password": "secret1" });
85+ let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await;
86+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
87+ }
88+
89+ // Single separators between alphanumerics are fine -> 201.
90+ let dotted = json!({ "username": "ali.k_1-b", "password": "secret1" });
91+ let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await;
92+ assert_eq!(res.status, StatusCode::CREATED);
93+ assert_eq!(res.body["username"], "ali.k_1-b");
94+
61 // Valid -> 201, no password echoed back, defaults to the student role.95 // Valid -> 201, no password echoed back, defaults to the student role.
62 let ok = json!({ "username": "bob", "password": "secret1" });96 let ok = json!({ "username": "bob", "password": "secret1" });
63 let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await;97 let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await;
@@ -71,6 +105,36 @@ async fn register_validates_input() {
71 assert_eq!(res.status, StatusCode::CONFLICT);105 assert_eq!(res.status, StatusCode::CONFLICT);
72 }106 }
73 107
108+#[tokio::test]
109+async fn register_rejects_reserved_usernames() {
110+ let app = mem_app().await;
111+
112+ // Staff-looking names can't be claimed through public registration.
113+ for name in [
114+ "admin",
115+ "administrator",
116+ "root",
117+ "support",
118+ "system",
119+ "moderator",
120+ "staff",
121+ ] {
122+ let creds = json!({ "username": name, "password": "secret1" });
123+ let res = send(&app, "POST", "/auth/register", None, Some(creds)).await;
124+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted");
125+ let msg = res.body["error"].as_str().unwrap_or_default();
126+ assert!(msg.contains("reserved"), "unexpected error for {name}: {msg}");
127+ }
128+
129+ // The reservation is registration-only policy: the seeded bootstrap admin
130+ // (created through `ensure_admin`, not `/auth/register`) still logs in.
131+ // Covered by the admin bootstrap tests; here just prove a reserved name
132+ // is not permanently poisoned for login by the register-level check.
133+ let creds = json!({ "username": "admin", "password": "wrong" });
134+ let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
135+ assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved"
136+}
137+
74 #[tokio::test]138 #[tokio::test]
75 async fn login_rejects_bad_credentials() {139 async fn login_rejects_bad_credentials() {
76 let app = mem_app().await;140 let app = mem_app().await;
@@ -2362,7 +2426,7 @@ async fn event_management_follows_hierarchy() {
2362 #[tokio::test]2426 #[tokio::test]
2363 async fn admin_manages_roles_with_guards() {2427 async fn admin_manages_roles_with_guards() {
2364 let (app, db) = app_and_db().await;2428 let (app, db) = app_and_db().await;
2365- let admin = login_as(&app, &db, "admin", "admin").await;2429+ let admin = login_as(&app, &db, "boss", "admin").await;
2366 let alice = login(&app, "alice").await; // student2430 let alice = login(&app, "alice").await; // student
2367 let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);2431 let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
2368 2432
@@ -2567,7 +2631,7 @@ async fn profile_rejects_invalid_fields() {
2567 #[tokio::test]2631 #[tokio::test]
2568 async fn admin_reads_and_edits_any_profile_with_guards() {2632 async fn admin_reads_and_edits_any_profile_with_guards() {
2569 let (app, db) = app_and_db().await;2633 let (app, db) = app_and_db().await;
2570- let admin = login_as(&app, &db, "admin", "admin").await;2634+ let admin = login_as(&app, &db, "boss", "admin").await;
2571 let alice = login(&app, "alice").await;2635 let alice = login(&app, "alice").await;
2572 let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);2636 let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
2573 let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body);2637 let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body);