forge
Explore
Log in

Don't you dare go Hollow

An empty user search lists everyone the caller may see

Browse files at this commit

6cf86404f90a6bf902298dd1699c85a108fd19f3Ahmet Kaan GümüşParent: 57de5b3
  • feat
    • an empty user search lists everyone the caller may see
Show full message
✨ feat: an empty user search lists everyone the caller may see

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.mdmodified+1 -1
@@ -1407,7 +1407,7 @@ window filtering, before paging; negative values are a `400` naming the field.
1407 | 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`. |1407 | 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`. |
1408 | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. |1408 | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. |
1409 | 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=`. |1409 | 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=`. |
1410-| 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. |1410+| 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. |
1411 | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. |1411 | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. |
1412 | 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'. |1412 | 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'. |
1413 | 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. |1413 | 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. |
src/db/user.rsmodified+2 -2
@@ -213,8 +213,8 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppErr
213 /// narrows the *visible* set (the roles a non-staff caller may message —213 /// narrows the *visible* set (the roles a non-staff caller may message —
214 /// see [`Role::messageable_roles`]); it is part of the query, not a214 /// see [`Role::messageable_roles`]); it is part of the query, not a
215 /// post-filter, so `total` counts only what the caller may see. A blank215 /// post-filter, so `total` counts only what the caller may see. A blank
216-/// `query`216+/// `query` matches everyone visible: blank alone is the caller's whole
217-/// matches everyone, so blank + `role` is a role-scoped listing. Returns217+/// directory, blank + `role` a role-scoped listing. Returns
218 /// every match, ordered by username; the HTTP layer pages the result like218 /// every match, ordered by username; the HTTP layer pages the result like
219 /// any other list (no built-in cap — an over-broad fragment is windowed219 /// any other list (no built-in cap — an over-broad fragment is windowed
220 /// by `?limit`).220 /// by `?limit`).
src/web/users.rsmodified+21 -18
@@ -182,9 +182,10 @@ async fn apply_preferences(
182 182
183 #[derive(Deserialize, IntoParams)]183 #[derive(Deserialize, IntoParams)]
184 struct SearchUsers {184 struct SearchUsers {
185- /// Case-insensitive fragment of a username, name, or surname. May be185+ /// Case-insensitive fragment of a username, name, or surname. Omit it —
186- /// blank when `role` is given — that lists the whole role.186+ /// or leave it blank — to list everyone the caller may see, optionally
187- q: String,187+ /// narrowed by `role`.
188+ q: Option<String>,
188 /// Restrict matches to one role: `parent`, `student`, `teacher`,189 /// Restrict matches to one role: `parent`, `student`, `teacher`,
189 /// `manager`, or `admin`. Omit to search every role.190 /// `manager`, or `admin`. Omit to search every role.
190 role: Option<String>,191 role: Option<String>,
@@ -200,12 +201,13 @@ struct SearchUsers {
200 /// attendance) and, for a student or parent, the one way to find the staff201 /// attendance) and, for a student or parent, the one way to find the staff
201 /// member they are allowed to message. Any authenticated user may ask; a202 /// member they are allowed to message. Any authenticated user may ask; a
202 /// caller below teacher only ever sees the roles they may message (teacher,203 /// caller below teacher only ever sees the roles they may message (teacher,
203-/// manager, admin), in the items *and* in `total`. `role` narrows to one role204+/// manager, admin), in the items *and* in `total`. A blank or omitted `q`
204-/// (e.g. `role=student` for an enroll picker) — a student or parent naming a205+/// lists everyone the caller may see — what the pickers open with; `role`
205-/// role they may not message is refused; a blank `q` with a `role` lists206+/// narrows to one role (e.g. `role=student` for an enroll picker), and a
206-/// everyone in that role. Paged via `?limit=&offset=` like the other lists207+/// student or parent naming a role they may not message is refused. Paged
207-/// (omit `limit` for every match); returns a `{items, total, limit, offset}`208+/// via `?limit=&offset=` like the other lists (omit `limit` for every
208-/// envelope carrying only id/username/display name — no contact details.209+/// match); returns a `{items, total, limit, offset}` envelope carrying only
210+/// id/username/display name — no contact details.
209 #[utoipa::path(211 #[utoipa::path(
210 get,212 get,
211 path = "/search",213 path = "/search",
@@ -214,7 +216,7 @@ struct SearchUsers {
214 params(SearchUsers),216 params(SearchUsers),
215 responses(217 responses(
216 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),218 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
217- (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse),219+ (status = 400, description = "Unknown role, or invalid limit/offset", body = ErrorResponse),
218 (status = 401, description = "Not authenticated", body = ErrorResponse),220 (status = 401, description = "Not authenticated", body = ErrorResponse),
219 (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse),221 (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse),
220 ),222 ),
@@ -224,12 +226,6 @@ async fn search_users(
224 CurrentUser(user): CurrentUser,226 CurrentUser(user): CurrentUser,
225 Query(req): Query<SearchUsers>,227 Query(req): Query<SearchUsers>,
226 ) -> Result<Json<Page<PersonRef>>, AppError> {228 ) -> Result<Json<Page<PersonRef>>, AppError> {
227- if req.q.trim().is_empty() && req.role.is_none() {
228- return Err(AppError::Validation(ValidationError::Invalid {
229- field: "q",
230- reason: "must not be empty unless role is given",
231- }));
232- }
233 let (limit, offset) = PageParams {229 let (limit, offset) = PageParams {
234 limit: req.limit,230 limit: req.limit,
235 offset: req.offset,231 offset: req.offset,
@@ -246,8 +242,15 @@ async fn search_users(
246 "students and parents may only search staff (teacher or higher)",242 "students and parents may only search staff (teacher or higher)",
247 ));243 ));
248 }244 }
249- let (users, total) =245+ let (users, total) = crate::service::user::search(
250- crate::service::user::search(&st.db, &req.q, role, allowed, limit, offset).await?;246+ &st.db,
247+ req.q.as_deref().unwrap_or(""),
248+ role,
249+ allowed,
250+ limit,
251+ offset,
252+ )
253+ .await?;
251 let items = users.iter().map(PersonRef::new).collect();254 let items = users.iter().map(PersonRef::new).collect();
252 Ok(Json(Page::new(items, total, limit, offset)))255 Ok(Json(Page::new(items, total, limit, offset)))
253 }256 }
tests/integration.rsmodified+52 -6
@@ -11398,6 +11398,26 @@ async fn search_below_staff_sees_only_staff() {
11398 .await;11398 .await;
11399 assert_eq!(res.status, StatusCode::OK, "{}", res.body);11399 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11400 assert_eq!(common::items(&res.body)[0]["username"], "ayse");11400 assert_eq!(common::items(&res.body)[0]["username"], "ayse");
11401+
11402+ // A blank `q` opens the directory, and below staff that directory is
11403+ // still staff only: the narrowing lives in the query, so it holds for the
11404+ // whole list and not just for a fragment.
11405+ for (who, cookie) in [("student", &ayse), ("parent", &anne)] {
11406+ let res = send(&app, "GET", "/users/search?q=", Some(cookie), None).await;
11407+ assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body);
11408+ let items = common::items(&res.body);
11409+ assert_eq!(res.body["total"], items.len(), "{who}: {}", res.body);
11410+ assert!(
11411+ !items
11412+ .iter()
11413+ .any(|user| user["username"] == "ayse" || user["username"] == "anne"),
11414+ "{who} must not see students or parents: {items:?}"
11415+ );
11416+ assert!(
11417+ items.iter().any(|user| user["username"] == "ayhan"),
11418+ "{who} must see the teacher: {items:?}"
11419+ );
11420+ }
11401 }11421 }
11402 11422
11403 // --- users: search matching semantics --------------------------------------11423 // --- users: search matching semantics --------------------------------------
@@ -11455,20 +11475,46 @@ async fn search_matches_are_literal_not_like_wildcards() {
11455 assert_eq!(hits[0]["username"], "under_score");11475 assert_eq!(hits[0]["username"], "under_score");
11456 }11476 }
11457 11477
11458-/// A blank search fragment is refused, not treated as match-everything.11478+/// A blank search fragment is the pickers' opening directory: it lists
11479+/// everyone the caller may see, exactly like a blank `q` scoped to a role.
11459 #[tokio::test]11480 #[tokio::test]
11460-async fn search_rejects_a_blank_query() {11481+async fn search_allows_a_blank_query() {
11461 let (app, db) = app_and_db().await;11482 let (app, db) = app_and_db().await;
11462 let teacher = login_as(&app, &db, "teacher", "teacher").await;11483 let teacher = login_as(&app, &db, "teacher", "teacher").await;
11463 login(&app, "alice").await;11484 login(&app, "alice").await;
11464 11485
11465- // Whitespace-only (url-encoded spaces) -> 400, not the full user list.11486+ // Whitespace-only (url-encoded spaces) is the same blank, not an error.
11466 let res = send(&app, "GET", "/users/search?q=%20%20", Some(&teacher), None).await;11487 let res = send(&app, "GET", "/users/search?q=%20%20", Some(&teacher), None).await;
11467- assert_eq!(res.status, StatusCode::BAD_REQUEST);11488+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11489+ let blank = common::items(&res.body);
11490+ assert!(
11491+ blank.iter().any(|user| user["username"] == "alice"),
11492+ "{blank:?}"
11493+ );
11494+ assert_eq!(res.body["total"], blank.len(), "{}", res.body);
11468 11495
11469- // Missing `q` entirely is a deserialization failure, not a wildcard.11496+ // An omitted `q` is the same blank.
11470 let res = send(&app, "GET", "/users/search", Some(&teacher), None).await;11497 let res = send(&app, "GET", "/users/search", Some(&teacher), None).await;
11471- assert_eq!(res.status, StatusCode::BAD_REQUEST);11498+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11499+ assert_eq!(common::items(&res.body), blank);
11500+
11501+ // So is an explicit empty one.
11502+ let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await;
11503+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11504+ assert_eq!(common::items(&res.body), blank);
11505+
11506+ // The blank directory still honors the paging window.
11507+ let res = send(
11508+ &app,
11509+ "GET",
11510+ "/users/search?q=&limit=1&offset=1",
11511+ Some(&teacher),
11512+ None,
11513+ )
11514+ .await;
11515+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11516+ assert_eq!(common::items(&res.body).len(), 1);
11517+ assert_eq!(res.body["total"], blank.len());
11472 }11518 }
11473 11519
11474 /// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130)11520 /// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130)
tests/pagination.rsmodified+6 -6
@@ -350,7 +350,7 @@ async fn user_search_is_paged_not_capped() {
350 assert_eq!(total(&res.body), 12);350 assert_eq!(total(&res.body), 12);
351 assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2");351 assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2");
352 352
353- // Paging bounds are enforced, and a blank query is still refused.353+ // Paging bounds are enforced.
354 let res = send(354 let res = send(
355 &app,355 &app,
356 "GET",356 "GET",
@@ -360,12 +360,12 @@ async fn user_search_is_paged_not_capped() {
360 )360 )
361 .await;361 .await;
362 assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400");362 assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400");
363+
364+ // A blank `q` is the opening directory, not an error: everyone the caller
365+ // may see — the 12 `grp` accounts plus the teacher themselves.
363 let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await;366 let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await;
364- assert_eq!(367+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
365- res.status,368+ assert_eq!(total(&res.body), 13, "blank q lists everyone visible");
366- StatusCode::BAD_REQUEST,
367- "blank q without a role is still a 400"
368- );
369 369
370 // Blank q scoped to a role is a listing, not an error.370 // Blank q scoped to a role is a listing, not an error.
371 let res = send(371 let res = send(