From 6cf86404f90a6bf902298dd1699c85a108fd19f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 16 Sep 2026 05:06:32 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20an=20empty=20user=20search?= =?UTF-8?q?=20lists=20everyone=20the=20caller=20may=20see?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /users/search no longer refuses a blank `q`. Omitted, empty and whitespace-only are the same input now: each returns the caller's visible directory, which is what a receiver picker opens with — staff see the school, while a student or parent still see only the staff they may write to, and naming a role outside that set is still a 403. `role` still narrows, an unknown role is still a 400, and `limit`/`offset` bounds are unchanged. The store already treated a blank needle as "no clause"; this drops the web-layer guard that contradicted it and pins the behavior on both sides (blank == omitted == whitespace-only, and blank still narrowed below staff). --- README.md | 2 +- src/db/user.rs | 4 +-- src/web/users.rs | 39 +++++++++++++++-------------- tests/integration.rs | 58 +++++++++++++++++++++++++++++++++++++++----- tests/pagination.rs | 12 ++++----- 5 files changed, 82 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index ec3222d..0d4b0be 100644 --- a/README.md +++ b/README.md @@ -1407,7 +1407,7 @@ window filtering, before paging; negative values are a `400` naming the field. | PATCH | `/users/me/preferences` | student | Update the caller's own UI preferences: `theme` (`light`/`dark`), `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`). Any authenticated role. Omitted fields stay as they are; an empty string clears one back to "never chose" (the client then follows the device preference). Read them back on any user response, e.g. `GET /auth/me`. | | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. | | GET | `/users/me/students` | parent | The students the calling parent observes, sorted by username. Requires the `parent` role. Each entry's reports live at `GET /marks/{user}`, `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via `?limit=&offset=`. | -| GET | `/users/search` | student | Find users by username or name — backs the pickers (enroll, grade, mark attendance) and, for a student or parent, the one way to find the staff member they are allowed to message. Any authenticated user may ask; a caller below teacher only ever sees the roles they may message (teacher, manager, admin), in the items *and* in `total`. `role` narrows to one role (e.g. `role=student` for an enroll picker) — a student or parent naming a role they may not message is refused; a blank `q` with a `role` lists everyone in that role. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | +| GET | `/users/search` | student | Find users by username or name — backs the pickers (enroll, grade, mark attendance) and, for a student or parent, the one way to find the staff member they are allowed to message. Any authenticated user may ask; a caller below teacher only ever sees the roles they may message (teacher, manager, admin), in the items *and* in `total`. A blank or omitted `q` lists everyone the caller may see — what the pickers open with; `role` narrows to one role (e.g. `role=student` for an enroll picker), and a student or parent naming a role they may not message is refused. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. | | GET | `/users/{id}/avatar` | student | The avatar bytes. Same reach as the profile itself: every authenticated account, except a parent, who is limited to their own and their linked students'. | | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar. Admin only — the moderation path: an offensive picture is a school problem, and no route deletes the account it hangs on. | diff --git a/src/db/user.rs b/src/db/user.rs index db6ba6d..34c6950 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -213,8 +213,8 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result, AppErr /// narrows the *visible* set (the roles a non-staff caller may message — /// see [`Role::messageable_roles`]); it is part of the query, not a /// post-filter, so `total` counts only what the caller may see. A blank -/// `query` -/// matches everyone, so blank + `role` is a role-scoped listing. Returns +/// `query` matches everyone visible: blank alone is the caller's whole +/// directory, blank + `role` a role-scoped listing. Returns /// every match, ordered by username; the HTTP layer pages the result like /// any other list (no built-in cap — an over-broad fragment is windowed /// by `?limit`). diff --git a/src/web/users.rs b/src/web/users.rs index dee6cf8..8b67d36 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -182,9 +182,10 @@ async fn apply_preferences( #[derive(Deserialize, IntoParams)] struct SearchUsers { - /// Case-insensitive fragment of a username, name, or surname. May be - /// blank when `role` is given — that lists the whole role. - q: String, + /// Case-insensitive fragment of a username, name, or surname. Omit it — + /// or leave it blank — to list everyone the caller may see, optionally + /// narrowed by `role`. + q: Option, /// Restrict matches to one role: `parent`, `student`, `teacher`, /// `manager`, or `admin`. Omit to search every role. role: Option, @@ -200,12 +201,13 @@ struct SearchUsers { /// attendance) and, for a student or parent, the one way to find the staff /// member they are allowed to message. Any authenticated user may ask; a /// caller below teacher only ever sees the roles they may message (teacher, -/// manager, admin), in the items *and* in `total`. `role` narrows to one role -/// (e.g. `role=student` for an enroll picker) — a student or parent naming a -/// role they may not message is refused; a blank `q` with a `role` lists -/// everyone in that role. Paged via `?limit=&offset=` like the other lists -/// (omit `limit` for every match); returns a `{items, total, limit, offset}` -/// envelope carrying only id/username/display name — no contact details. +/// manager, admin), in the items *and* in `total`. A blank or omitted `q` +/// lists everyone the caller may see — what the pickers open with; `role` +/// narrows to one role (e.g. `role=student` for an enroll picker), and a +/// student or parent naming a role they may not message is refused. Paged +/// via `?limit=&offset=` like the other lists (omit `limit` for every +/// match); returns a `{items, total, limit, offset}` envelope carrying only +/// id/username/display name — no contact details. #[utoipa::path( get, path = "/search", @@ -214,7 +216,7 @@ struct SearchUsers { params(SearchUsers), responses( (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page), - (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse), + (status = 400, description = "Unknown role, or invalid limit/offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse), ), @@ -224,12 +226,6 @@ async fn search_users( CurrentUser(user): CurrentUser, Query(req): Query, ) -> Result>, AppError> { - if req.q.trim().is_empty() && req.role.is_none() { - return Err(AppError::Validation(ValidationError::Invalid { - field: "q", - reason: "must not be empty unless role is given", - })); - } let (limit, offset) = PageParams { limit: req.limit, offset: req.offset, @@ -246,8 +242,15 @@ async fn search_users( "students and parents may only search staff (teacher or higher)", )); } - let (users, total) = - crate::service::user::search(&st.db, &req.q, role, allowed, limit, offset).await?; + let (users, total) = crate::service::user::search( + &st.db, + req.q.as_deref().unwrap_or(""), + role, + allowed, + limit, + offset, + ) + .await?; let items = users.iter().map(PersonRef::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/tests/integration.rs b/tests/integration.rs index 53877af..9b9b12b 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -11398,6 +11398,26 @@ async fn search_below_staff_sees_only_staff() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(common::items(&res.body)[0]["username"], "ayse"); + + // A blank `q` opens the directory, and below staff that directory is + // still staff only: the narrowing lives in the query, so it holds for the + // whole list and not just for a fragment. + for (who, cookie) in [("student", &ayse), ("parent", &anne)] { + let res = send(&app, "GET", "/users/search?q=", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); + let items = common::items(&res.body); + assert_eq!(res.body["total"], items.len(), "{who}: {}", res.body); + assert!( + !items + .iter() + .any(|user| user["username"] == "ayse" || user["username"] == "anne"), + "{who} must not see students or parents: {items:?}" + ); + assert!( + items.iter().any(|user| user["username"] == "ayhan"), + "{who} must see the teacher: {items:?}" + ); + } } // --- users: search matching semantics -------------------------------------- @@ -11455,20 +11475,46 @@ async fn search_matches_are_literal_not_like_wildcards() { assert_eq!(hits[0]["username"], "under_score"); } -/// A blank search fragment is refused, not treated as match-everything. +/// A blank search fragment is the pickers' opening directory: it lists +/// everyone the caller may see, exactly like a blank `q` scoped to a role. #[tokio::test] -async fn search_rejects_a_blank_query() { +async fn search_allows_a_blank_query() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "teacher", "teacher").await; login(&app, "alice").await; - // Whitespace-only (url-encoded spaces) -> 400, not the full user list. + // Whitespace-only (url-encoded spaces) is the same blank, not an error. let res = send(&app, "GET", "/users/search?q=%20%20", Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::BAD_REQUEST); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let blank = common::items(&res.body); + assert!( + blank.iter().any(|user| user["username"] == "alice"), + "{blank:?}" + ); + assert_eq!(res.body["total"], blank.len(), "{}", res.body); - // Missing `q` entirely is a deserialization failure, not a wildcard. + // An omitted `q` is the same blank. let res = send(&app, "GET", "/users/search", Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::BAD_REQUEST); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body), blank); + + // So is an explicit empty one. + let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body), blank); + + // The blank directory still honors the paging window. + let res = send( + &app, + "GET", + "/users/search?q=&limit=1&offset=1", + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body).len(), 1); + assert_eq!(res.body["total"], blank.len()); } /// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130) diff --git a/tests/pagination.rs b/tests/pagination.rs index 96aa2e0..5d59a2c 100644 --- a/tests/pagination.rs +++ b/tests/pagination.rs @@ -350,7 +350,7 @@ async fn user_search_is_paged_not_capped() { assert_eq!(total(&res.body), 12); assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2"); - // Paging bounds are enforced, and a blank query is still refused. + // Paging bounds are enforced. let res = send( &app, "GET", @@ -360,12 +360,12 @@ async fn user_search_is_paged_not_capped() { ) .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400"); + + // A blank `q` is the opening directory, not an error: everyone the caller + // may see — the 12 `grp` accounts plus the teacher themselves. let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; - assert_eq!( - res.status, - StatusCode::BAD_REQUEST, - "blank q without a role is still a 400" - ); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(total(&res.body), 13, "blank q lists everyone visible"); // Blank q scoped to a role is a listing, not an error. let res = send(