forge
Explore
Log in

Don't you dare go Hollow

Stop swagger offering the ai role as assignable

Browse files at this commit

b97b80281529be34e0a9c48b267b7610fc7eb971Ahmet Kaan GümüşParent: 01f55da
  • fix
    • stop swagger offering the ai role as assignable
Show full message
📝 fix: stop swagger offering the ai role as assignable

The `SetRole` body pointed at the response-side `Role` schema, which names
`ai` — the QUIC bridge's own service principal. Swagger UI therefore offered
`ai` in the try-it-out form for `PATCH /users/{id}/role`, where the server has
always answered 400: `Role::try_from_str` searches `ROLES`, the five human
roles. The "never assignable" note lived on the variant, and utoipa emits only
type-level doc comments, so nothing of it reached the document.

Request bodies now reference a documentation-only `AssignableRole` enum with
exactly those five; the response schema keeps `ai` (a service principal really
does read back as one) and carries the explanation where utoipa will emit it.
No server behavior changes — the string still funnels through
`Role::try_from_str`.

The user-search `?role=` param and the event role-audience DTO are plain
strings in the spec, so neither advertised `ai`; both are left alone.

`role_ai_is_unreachable_over_http` gains step 6, pinning the emitted enums so
the drift cannot come back.
README.mdmodified+3 -1
@@ -3593,7 +3593,9 @@ not the old one) — never as who they used to be.
3593 Without it the principal is the internal role **`ai`**: the lowest privilege in3593 Without it the principal is the internal role **`ai`**: the lowest privilege in
3594 the system, below `parent`. It is not a human role and is never assignable —3594 the system, below `parent`. It is not a human role and is never assignable —
3595 `"ai"` is rejected by every role input, no account can hold it, and it is never3595 `"ai"` is rejected by every role input, no account can hold it, and it is never
3596-stored. It appears in the OpenAPI `Role` schema as documentation only. So a3596+stored. It appears in the OpenAPI *response* schema `Role` as documentation
3597+only — request bodies take `AssignableRole`, the five human roles, so no
3598+generated client or Swagger form offers it. So a
3597 read that needs a role answers `403` — through the `ok` envelope, with that3599 read that needs a role answers `403` — through the `ok` envelope, with that
3598 status, like any other API refusal.3600 status, like any other API refusal.
3599 3601
src/web/dto.rsmodified+29 -8
@@ -15,17 +15,20 @@ use crate::domain::subject::Subject;
15 use crate::domain::user::{User, UserId};15 use crate::domain::user::{User, UserId};
16 use crate::error::AppError;16 use crate::error::AppError;
17 17
18-/// The access roles, lowest to highest privilege (`parent` is a read-only18+/// The access roles a response can carry, lowest to highest privilege (`parent`
19-/// observer of its linked students). The web-facing mirror of19+/// is a read-only observer of its linked students). `ai` is an internal service
20-/// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which20+/// principal — the identity an out-of-process AI service carries over the QUIC
21-/// the domain type deliberately omits), so it renders as a proper `enum` in the21+/// bridge. It is never assignable and never stored on a user row, so it only
22-/// docs. Serializes to the same lowercase strings the domain stores.22+/// ever appears in a response; requests take the five human roles
23+/// (`AssignableRole`), which is also what `GET /limits` lists.
24+///
25+/// The web-facing mirror of [`crate::domain::role::Role`] — it carries the serde
26+/// + OpenAPI derives (which the domain type deliberately omits), so it renders
27+/// as a proper `enum` in the docs. Serializes to the same lowercase strings the
28+/// domain stores.
23 #[derive(Serialize, Clone, Copy, ToSchema)]29 #[derive(Serialize, Clone, Copy, ToSchema)]
24 #[serde(rename_all = "lowercase")]30 #[serde(rename_all = "lowercase")]
25 pub enum Role {31 pub enum Role {
26- /// Internal service principal — never assignable, never stored. It appears
27- /// here only because the mapping from the domain enum is exhaustive; the
28- /// assignable set is what `GET /limits` lists, and that omits it.
29 Ai,32 Ai,
30 Parent,33 Parent,
31 Student,34 Student,
@@ -34,6 +37,24 @@ pub enum Role {
34 Admin,37 Admin,
35 }38 }
36 39
40+/// The roles a request may ask for: the five human ones, exactly
41+/// [`crate::constant::ROLES`]. Documentation only — the handlers still take the
42+/// role as a string and funnel it through
43+/// [`crate::domain::role::Role::try_from_str`], so an unknown value is a uniform
44+/// `400` rather than a deserialization error. It exists because [`Role`] (the
45+/// response schema) also names `ai`, and a request schema pointed at it offered
46+/// callers a value the server has always refused.
47+#[derive(ToSchema)]
48+#[schema(rename_all = "lowercase")]
49+#[allow(dead_code)] // Nothing constructs it: the variants exist to be emitted.
50+pub enum AssignableRole {
51+ Parent,
52+ Student,
53+ Teacher,
54+ Manager,
55+ Admin,
56+}
57+
37 impl From<DomainRole> for Role {58 impl From<DomainRole> for Role {
38 fn from(role: DomainRole) -> Self {59 fn from(role: DomainRole) -> Self {
39 match role {60 match role {
src/web/users.rsmodified+5 -2
@@ -25,6 +25,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
25 use crate::state::AppState;25 use crate::state::AppState;
26 26
27 use super::courses::visible_courses;27 use super::courses::visible_courses;
28+use super::dto::AssignableRole;
28 use super::dto::Role as RoleSchema;29 use super::dto::Role as RoleSchema;
29 use super::{30 use super::{
30 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm,31 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm,
@@ -63,8 +64,10 @@ pub fn routes() -> OpenApiRouter<AppState> {
63 #[derive(Deserialize, ToSchema)]64 #[derive(Deserialize, ToSchema)]
64 struct SetRole {65 struct SetRole {
65 /// The role to assign. Deserialized as a string so an unknown value returns a66 /// The role to assign. Deserialized as a string so an unknown value returns a
66- /// uniform `400`; documented as the `Role` enum so the docs list the choices.67+ /// uniform `400`; documented as the `AssignableRole` enum so the docs list
67- #[schema(value_type = RoleSchema, example = "teacher")]68+ /// exactly the choices the server accepts (the response-side `Role` also
69+ /// names the `ai` service principal, which this endpoint has always refused).
70+ #[schema(value_type = AssignableRole, example = "teacher")]
68 role: String,71 role: String,
69 }72 }
70 73
tests/integration.rsmodified+33 -0
@@ -5265,6 +5265,39 @@ async fn role_ai_is_unreachable_over_http() {
5265 let roles = roles.as_array().expect("limits user.roles array");5265 let roles = roles.as_array().expect("limits user.roles array");
5266 assert_eq!(roles.len(), 5, "{roles:?}");5266 assert_eq!(roles.len(), 5, "{roles:?}");
5267 assert!(!roles.iter().any(|r| r == "ai"), "{roles:?}");5267 assert!(!roles.iter().any(|r| r == "ai"), "{roles:?}");
5268+
5269+ // 6. Neither does the OpenAPI document Swagger UI renders its forms from.
5270+ // The request schema once `$ref`ed the response-side `Role`, which does
5271+ // name `ai` — so the try-it-out form offered a value the funnel above has
5272+ // always refused with a 400. Request schemas carry the five; the response
5273+ // schema keeps `ai` (a service principal really does read back as one)
5274+ // and must say what it is, since utoipa emits only the *type*-level doc
5275+ // comment, never a variant's.
5276+ let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
5277+ .await
5278+ .body;
5279+ let schemas = &spec["components"]["schemas"];
5280+ let human = json!(["parent", "student", "teacher", "manager", "admin"]);
5281+ assert_eq!(schemas["AssignableRole"]["enum"], human, "{schemas:?}");
5282+ assert_eq!(
5283+ spec["paths"]["/users/{id}/role"]["patch"]["requestBody"]["content"]
5284+ ["application/json"]["schema"]["$ref"],
5285+ "#/components/schemas/SetRole"
5286+ );
5287+ assert_eq!(
5288+ schemas["SetRole"]["properties"]["role"]["$ref"],
5289+ "#/components/schemas/AssignableRole"
5290+ );
5291+ let response_role = &schemas["Role"];
5292+ assert_eq!(
5293+ response_role["enum"],
5294+ json!(["ai", "parent", "student", "teacher", "manager", "admin"]),
5295+ "{response_role:?}"
5296+ );
5297+ let described = response_role["description"]
5298+ .as_str()
5299+ .expect("Role schema carries its type-level doc comment");
5300+ assert!(described.contains("never assignable"), "{described:?}");
5268 }5301 }
5269 5302
5270 // --- users: personal info (profile) ---------------------------------------5303 // --- users: personal info (profile) ---------------------------------------