Person-scoped login
Browse files at this commitfae1f79778677f6f130df5f188f0692bcc01499eParent: ef463c1- feat
- person-scoped login
- select school after
35 changed files +1861 -270
- .sqlx/query-01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824.json +15 -0
- .sqlx/query-1bfbfdda9c9f0ab663b4651140dce0f3b0196ca0355fdf049e62ceddc6017bff.json +52 -0
- .sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.json +14 -0
- .sqlx/query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.json +52 -0
- .sqlx/query-54397a2cfa6a966570c0cc11f975d59ebc441e47fd930fa7225107f7d2d8ef86.json +52 -0
- .sqlx/query-555997d1e51e989f709006559bcc3cd105225857d07202eea06b47f8073d2f3b.json +14 -0
- .sqlx/query-8cc33f7b39c738d18a5e9bb0fa414f3ef51dd0b837b5560f9173f0783b44fa6c.json +14 -0
- .sqlx/query-9c0f4b46e5844508e846ea2ffce36742785e2ab2764e6ef842f8e87ecd1c7fca.json +52 -0
- .sqlx/query-b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3.json +16 -0
- .sqlx/query-de369e1a6d5cca38c622c4864689aa460775d44d2462f6550cc858842da6bf31.json +15 -0
- .sqlx/query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.json +53 -0
- .sqlx/query-ed268fc50f19973adecd34405d20d9faeb663f6ea8b6b8c3c55c2d120fb06aea.json +56 -0
- README.md +59 -32
- migrations/control/20260913000001_person.sql +42 -0
- src/db/mod.rs +1 -0
- src/db/person.rs +212 -0
- src/domain/mod.rs +1 -0
- src/domain/person.rs +105 -0
- src/lib.rs +1 -1
- src/service/mod.rs +1 -0
- src/service/person.rs +112 -0
- src/service/user.rs +26 -6
- src/tenant.rs +11 -4
- src/web/auth.rs +252 -69
- src/web/builder.rs +36 -9
- src/web/extractor.rs +8 -0
- src/web/mod.rs +2 -2
- tests/auth_enumeration.rs +18 -4
- tests/builder_api.rs +106 -24
- tests/common/mod.rs +55 -7
- tests/e2e.rs +3 -3
- tests/integration.rs +341 -76
- tests/persistence.rs +43 -23
- tests/rate_limit.rs +20 -6
- tests/regress_roles.rs +1 -4
.sqlx/query-01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824.jsonadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "INSERT INTO person_school (person, school) VALUES ($1, $2) ON CONFLICT DO NOTHING", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Text" | ||
| 10 | + ] | ||
| 11 | + }, | ||
| 12 | + "nullable": [] | ||
| 13 | + }, | ||
| 14 | + "hash": "01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824" | ||
| 15 | +} | ||
.sqlx/query-1bfbfdda9c9f0ab663b4651140dce0f3b0196ca0355fdf049e62ceddc6017bff.jsonadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT person AS \"person: PersonId\",\n token AS \"token: SessionToken\",\n expires_at AS \"expires_at: Timestamp\"\n FROM person_session WHERE token = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "person: PersonId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "person_session", | ||
| 13 | + "name": "person" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "token: SessionToken", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "person_session", | ||
| 24 | + "name": "token" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "expires_at: Timestamp", | ||
| 31 | + "type_info": "Int8", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "person_session", | ||
| 35 | + "name": "expires_at" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + ], | ||
| 40 | + "parameters": { | ||
| 41 | + "Left": [ | ||
| 42 | + "Text" | ||
| 43 | + ] | ||
| 44 | + }, | ||
| 45 | + "nullable": [ | ||
| 46 | + false, | ||
| 47 | + false, | ||
| 48 | + false | ||
| 49 | + ] | ||
| 50 | + }, | ||
| 51 | + "hash": "1bfbfdda9c9f0ab663b4651140dce0f3b0196ca0355fdf049e62ceddc6017bff" | ||
| 52 | +} | ||
.sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.jsonadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM person_school WHERE school = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Text" | ||
| 9 | + ] | ||
| 10 | + }, | ||
| 11 | + "nullable": [] | ||
| 12 | + }, | ||
| 13 | + "hash": "32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1" | ||
| 14 | +} | ||
.sqlx/query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.jsonadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.slug = ps.school\n WHERE ps.person = $1\n ORDER BY s.slug", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "slug: Slug", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "school", | ||
| 13 | + "name": "slug" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "name", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "school", | ||
| 24 | + "name": "name" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "status: SchoolStatus", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "school", | ||
| 35 | + "name": "status" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + ], | ||
| 40 | + "parameters": { | ||
| 41 | + "Left": [ | ||
| 42 | + "Uuid" | ||
| 43 | + ] | ||
| 44 | + }, | ||
| 45 | + "nullable": [ | ||
| 46 | + false, | ||
| 47 | + false, | ||
| 48 | + false | ||
| 49 | + ] | ||
| 50 | + }, | ||
| 51 | + "hash": "409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7" | ||
| 52 | +} | ||
.sqlx/query-54397a2cfa6a966570c0cc11f975d59ebc441e47fd930fa7225107f7d2d8ef86.jsonadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: PersonId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\"\n FROM person WHERE id = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: PersonId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "person", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "username: Username", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "person", | ||
| 24 | + "name": "username" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "password_hash: PasswordHash", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "person", | ||
| 35 | + "name": "password_hash" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + ], | ||
| 40 | + "parameters": { | ||
| 41 | + "Left": [ | ||
| 42 | + "Uuid" | ||
| 43 | + ] | ||
| 44 | + }, | ||
| 45 | + "nullable": [ | ||
| 46 | + false, | ||
| 47 | + false, | ||
| 48 | + false | ||
| 49 | + ] | ||
| 50 | + }, | ||
| 51 | + "hash": "54397a2cfa6a966570c0cc11f975d59ebc441e47fd930fa7225107f7d2d8ef86" | ||
| 52 | +} | ||
.sqlx/query-555997d1e51e989f709006559bcc3cd105225857d07202eea06b47f8073d2f3b.jsonadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM person_session WHERE person = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid" | ||
| 9 | + ] | ||
| 10 | + }, | ||
| 11 | + "nullable": [] | ||
| 12 | + }, | ||
| 13 | + "hash": "555997d1e51e989f709006559bcc3cd105225857d07202eea06b47f8073d2f3b" | ||
| 14 | +} | ||
.sqlx/query-8cc33f7b39c738d18a5e9bb0fa414f3ef51dd0b837b5560f9173f0783b44fa6c.jsonadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM person_session WHERE token = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Text" | ||
| 9 | + ] | ||
| 10 | + }, | ||
| 11 | + "nullable": [] | ||
| 12 | + }, | ||
| 13 | + "hash": "8cc33f7b39c738d18a5e9bb0fa414f3ef51dd0b837b5560f9173f0783b44fa6c" | ||
| 14 | +} | ||
.sqlx/query-9c0f4b46e5844508e846ea2ffce36742785e2ab2764e6ef842f8e87ecd1c7fca.jsonadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: PersonId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\"\n FROM person WHERE username = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: PersonId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "person", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "username: Username", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "person", | ||
| 24 | + "name": "username" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "password_hash: PasswordHash", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "person", | ||
| 35 | + "name": "password_hash" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + ], | ||
| 40 | + "parameters": { | ||
| 41 | + "Left": [ | ||
| 42 | + "Text" | ||
| 43 | + ] | ||
| 44 | + }, | ||
| 45 | + "nullable": [ | ||
| 46 | + false, | ||
| 47 | + false, | ||
| 48 | + false | ||
| 49 | + ] | ||
| 50 | + }, | ||
| 51 | + "hash": "9c0f4b46e5844508e846ea2ffce36742785e2ab2764e6ef842f8e87ecd1c7fca" | ||
| 52 | +} | ||
.sqlx/query-b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3.jsonadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "INSERT INTO person (id, username, password_hash) VALUES ($1, $2, $3)", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Text", | ||
| 10 | + "Text" | ||
| 11 | + ] | ||
| 12 | + }, | ||
| 13 | + "nullable": [] | ||
| 14 | + }, | ||
| 15 | + "hash": "b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3" | ||
| 16 | +} | ||
.sqlx/query-de369e1a6d5cca38c622c4864689aa460775d44d2462f6550cc858842da6bf31.jsonadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "UPDATE person SET password_hash = $2 WHERE username = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Text", | ||
| 9 | + "Text" | ||
| 10 | + ] | ||
| 11 | + }, | ||
| 12 | + "nullable": [] | ||
| 13 | + }, | ||
| 14 | + "hash": "de369e1a6d5cca38c622c4864689aa460775d44d2462f6550cc858842da6bf31" | ||
| 15 | +} | ||
.sqlx/query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.jsonadded+53 -0
| @@ -0,0 +1,53 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.slug = ps.school\n WHERE ps.person = $1 AND ps.school = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "slug: Slug", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "school", | ||
| 13 | + "name": "slug" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "name", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "school", | ||
| 24 | + "name": "name" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "status: SchoolStatus", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "school", | ||
| 35 | + "name": "status" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + ], | ||
| 40 | + "parameters": { | ||
| 41 | + "Left": [ | ||
| 42 | + "Uuid", | ||
| 43 | + "Text" | ||
| 44 | + ] | ||
| 45 | + }, | ||
| 46 | + "nullable": [ | ||
| 47 | + false, | ||
| 48 | + false, | ||
| 49 | + false | ||
| 50 | + ] | ||
| 51 | + }, | ||
| 52 | + "hash": "ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834" | ||
| 53 | +} | ||
.sqlx/query-ed268fc50f19973adecd34405d20d9faeb663f6ea8b6b8c3c55c2d120fb06aea.jsonadded+56 -0
| @@ -0,0 +1,56 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "INSERT INTO person_session (id, person, token, created_at, expires_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING person AS \"person: PersonId\",\n token AS \"token: SessionToken\",\n expires_at AS \"expires_at: Timestamp\"", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "person: PersonId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "person_session", | ||
| 13 | + "name": "person" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "token: SessionToken", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "person_session", | ||
| 24 | + "name": "token" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "expires_at: Timestamp", | ||
| 31 | + "type_info": "Int8", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "person_session", | ||
| 35 | + "name": "expires_at" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + ], | ||
| 40 | + "parameters": { | ||
| 41 | + "Left": [ | ||
| 42 | + "Uuid", | ||
| 43 | + "Uuid", | ||
| 44 | + "Text", | ||
| 45 | + "Int8", | ||
| 46 | + "Int8" | ||
| 47 | + ] | ||
| 48 | + }, | ||
| 49 | + "nullable": [ | ||
| 50 | + false, | ||
| 51 | + false, | ||
| 52 | + false | ||
| 53 | + ] | ||
| 54 | + }, | ||
| 55 | + "hash": "ed268fc50f19973adecd34405d20d9faeb663f6ea8b6b8c3c55c2d120fb06aea" | ||
| 56 | +} | ||
README.mdmodified+59 -32
| @@ -301,13 +301,15 @@ school database sees only its own rows, so no query carries a | |||
| 301 | `WHERE school = ...` somebody could forget. | 301 | `WHERE school = ...` somebody could forget. |
| 302 | 302 | ||
| 303 | **Slugs.** 2-32 characters of `a-z`, `0-9` and `-`, starting with a letter or | 303 | **Slugs.** 2-32 characters of `a-z`, `0-9` and `-`, starting with a letter or |
| 304 | -digit (`MIN_SLUG_LEN`/`MAX_SLUG_LEN`); `builder` and `control` are reserved and | 304 | +digit (`MIN_SLUG_LEN`/`MAX_SLUG_LEN`); `builder`, `control` and `person` are |
| 305 | -refused. A slug names the school's database, its blob directory and its cookie | 305 | +reserved and refused. A slug names the school's database, its blob directory |
| 306 | -prefix, so it is immutable once taken — a rename changes the display name only. | 306 | +and its cookie prefix, so it is immutable once taken — a rename changes the |
| 307 | +display name only. | ||
| 307 | 308 | ||
| 308 | **Cookies.** A school session is `session=<slug>.<token>`, the vendor's is | 309 | **Cookies.** A school session is `session=<slug>.<token>`, the vendor's is |
| 309 | -`session=builder.<token>`, split at the *first* dot so a token can never be | 310 | +`session=builder.<token>`, and a person who still has to pick a school carries |
| 310 | -read as a slug. Neither cookie is accepted on the other's surface (`401` both | 311 | +`session=person.<token>` — all split at the *first* dot so a token can never |
| 312 | +be read as a slug. No cookie is accepted on another's surface (`401` all | ||
| 311 | ways), and a cookie with no dot names no school and is refused everywhere. | 313 | ways), and a cookie with no dot names no school and is refused everywhere. |
| 312 | 314 | ||
| 313 | **How a request finds its school.** Every school-scoped handler takes the | 315 | **How a request finds its school.** Every school-scoped handler takes the |
| @@ -329,8 +331,10 @@ working on a suspended school — that is how it comes back — except | |||
| 329 | operator account at boot (both or neither; half a pair aborts startup, and an | 331 | operator account at boot (both or neither; half a pair aborts startup, and an |
| 330 | existing account is never rewritten). From there: `POST /builder/login` → | 332 | existing account is never rewritten). From there: `POST /builder/login` → |
| 331 | `POST /schools` (registry row, database, schema and the school's first admin — | 333 | `POST /schools` (registry row, database, schema and the school's first admin — |
| 332 | -one call or none of it) → that admin logs in at `POST /auth/login` naming the | 334 | +one call or none of it) → that admin (a **person** in the control database) |
| 333 | -school → `PATCH /schools/{slug}` renames, suspends or resumes → | 335 | +logs in at `POST /auth/login` with just username + password, and is entered |
| 336 | +into the school straight away → `PATCH /schools/{slug}` renames, suspends or | ||
| 337 | +resumes → | ||
| 334 | `POST /schools/{slug}/admin-password` re-keys a locked-out admin and revokes | 338 | `POST /schools/{slug}/admin-password` re-keys a locked-out admin and revokes |
| 335 | every session it held → `POST /schools/{slug}/enter` mints an ordinary school | 339 | every session it held → `POST /schools/{slug}/enter` mints an ordinary school |
| 336 | session for one of its admins (support access, no builder power inside) → | 340 | session for one of its admins (support access, no builder power inside) → |
| @@ -464,29 +468,51 @@ curl -b v.txt -X POST localhost:6060/schools/demo/modules/meals # 200, an | |||
| 464 | 468 | ||
| 465 | ## Auth model | 469 | ## Auth model |
| 466 | 470 | ||
| 467 | -Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored | 471 | +The account is a **person**: one global username + password, held in the |
| 468 | -server-side); its value is `<school-slug>.<token>`, so `POST /auth/login` and | 472 | +control database, that can belong to any number of schools. Login never names |
| 469 | -`POST /auth/register` name the school alongside the username (see | 473 | +a school — `POST /auth/login` takes `{username, password}` alone. A person |
| 470 | -"Multi-school (SaaS)"). Send the cookie back on later requests. Every endpoint | 474 | +with exactly one active membership is logged straight into it: the response is |
| 471 | -below whose `Auth` column names a role requires a valid session; the ones marked `no` (`/health`, | 475 | +the full user object and the cookie is the school's own |
| 472 | -the docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent — | 476 | +`session=<school-slug>.<token>`. A person with two or more active memberships |
| 473 | -it clears the session if one is present). Set `COOKIE_SECURE=true` when serving | 477 | +answers `{username, schools: [{slug, name}]}` with a `session=person.<token>` |
| 474 | -behind TLS to add the cookie's `Secure` attribute. | 478 | +cookie instead, and names a school with `POST /auth/school` |
| 475 | - | 479 | +(`{"school": "<slug>"}`), which swaps the cookie for that school's |
| 476 | -**Register never reveals whether a username is taken.** `POST /auth/register` | 480 | +`<slug>.<token>` and revokes the person session. Register still names the |
| 477 | -answers `201` either way with the *same* body — `{username, role}`, the echoed | 481 | +school: `POST /auth/register` takes `{school, username, password}` (see |
| 478 | -name and the `student` role every fresh account gets. Both outcomes return one | 482 | +"Multi-school (SaaS)"). |
| 479 | -value built before the insert is even attempted, so they are byte-identical by | 483 | + |
| 480 | -construction. This is deliberate: the route is unauthenticated, so a `409` (or a | 484 | +Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, |
| 481 | -faster reply) would let anyone enumerate the school's users. The password is | 485 | +stored server-side), split at the *first* dot so a token can never be read as |
| 482 | -hashed *before* the availability check so both outcomes cost the same ~33ms. | 486 | +a slug. Send the cookie back on later requests. Every endpoint below whose |
| 483 | - | 487 | +`Auth` column names a role requires a valid school session; the ones marked |
| 484 | -The reply carries **no `id`**: on the taken path there is no row to name, and a | 488 | +`no` (`/health`, the docs pages, `register` / `login` / `school` / `logout`) |
| 485 | -fabricated one would leave the client holding an id that matches nothing. Log | 489 | +don't (`logout` is idempotent — it clears whichever session the cookie names: |
| 486 | -in and read `GET /auth/me` to learn who you are. The accepted cost: a caller who | 490 | +school, person, or builder). `GET /auth/me` is school-cookie only: a person |
| 487 | -collides with an existing account gets no distinct error and simply cannot log | 491 | +cookie answers `401`, because who you *are* depends on the school you have not |
| 488 | -in with that password — they pick another name. Do not "fix" this back to a | 492 | +picked yet. Set `COOKIE_SECURE=true` when serving behind TLS to add the |
| 489 | -`409`, and do not add an `id` back. | 493 | +cookie's `Secure` attribute. |
| 494 | + | ||
| 495 | +**Register never reveals anything.** `POST /auth/register` answers `201` in | ||
| 496 | +every outcome with the *same* body — `{username, role}`, the echoed name and | ||
| 497 | +the `student` role every fresh account gets. A username that is new creates | ||
| 498 | +the person plus the school's `app_user`; a person who already exists is | ||
| 499 | +attached to this school as one more membership — but only when the password | ||
| 500 | +matches the person credential, and a wrong password joins nothing while the | ||
| 501 | +reply stays the same. All outcomes return one value built before any branch, | ||
| 502 | +and the password is hashed before any lookup, so they cost the same ~33ms | ||
| 503 | +up front. This is deliberate: the route is unauthenticated, so a `409` (or a | ||
| 504 | +faster reply) would let anyone enumerate accounts. The same holds on login: | ||
| 505 | +an unknown username burns the same argon2 work against a decoy hash as a | ||
| 506 | +wrong password, and a person with no memberships left to enter answers the | ||
| 507 | +same `401`. Do not "fix" any of this back to a distinct error, and do not add | ||
| 508 | +an `id` to the register reply. | ||
| 509 | + | ||
| 510 | +The reply carries **no `id`**: on the taken path there is no row to name, and | ||
| 511 | +a fabricated one would leave the client holding an id that matches nothing. | ||
| 512 | +Log in and read `GET /auth/me` to learn who you are. The accepted cost: a | ||
| 513 | +caller who collides with an existing person's name gets no distinct error and | ||
| 514 | +cannot join another school with that name without the right password — they | ||
| 515 | +pick another name. | ||
| 490 | 516 | ||
| 491 | ## Time policy | 517 | ## Time policy |
| 492 | 518 | ||
| @@ -1047,10 +1073,11 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 1047 | | PATCH | `/appointments/{id}/reschedule/decline` | student | Refuse the teacher's counter-proposal. The requester's call alone, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing left to fall back to — book another slot instead. The slot frees up, and the original request stays readable as `cancelled` with the refused proposal still on it. Declining is a cancel, so it answers to the same deadline: `409` once the meeting's effective window has started. | | 1073 | | PATCH | `/appointments/{id}/reschedule/decline` | student | Refuse the teacher's counter-proposal. The requester's call alone, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing left to fall back to — book another slot instead. The slot frees up, and the original request stays readable as `cancelled` with the refused proposal still on it. Declining is a cancel, so it answers to the same deadline: `409` once the meeting's effective window has started. | |
| 1048 | | GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. | | 1074 | | GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. | |
| 1049 | | GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees the event tallies plus only the roll-call blocks of the target's courses they manage. | | 1075 | | GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees the event tallies plus only the roll-call blocks of the target's courses they manage. | |
| 1050 | -| POST | `/auth/login` | no | Log in with school + username + password. Sets a `session` cookie (`<school>.<token>`) on success. | | 1076 | +| POST | `/auth/login` | no | Log in with username + password — no school. Sets a `session` cookie on success: exactly one active membership enters that school right away (`<slug>.<token>` and the full [`UserResponse`], unchanged for single-school clients), several answer a [`SchoolChoiceResponse`] with a `person.<token>` cookie that `POST /auth/school` binds. | |
| 1051 | | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. | | 1077 | | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. | |
| 1052 | | GET | `/auth/me` | student | Return the currently authenticated user. | | 1078 | | GET | `/auth/me` | student | Return the currently authenticated user. | |
| 1053 | -| POST | `/auth/register` | no | Register a new user account: `{school, username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201`, even if the name was already taken — see "Auth model". | | 1079 | +| POST | `/auth/register` | no | Register a new user account, or attach an existing person to one more school: `{school, username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201` — see below. | |
| 1080 | +| POST | `/auth/school` | no | Bind a `person.<token>` session to one of the person's schools: the cookie is replaced with that school's own `<slug>.<token>` and the person session is revoked. Deliberately outside the credential rate-limit tier — this is not a credential guess, and it requires a session cookie already. | | ||
| 1054 | | GET | `/bank-questions` | teacher | The bank the caller may see — their own templates plus the ones published to the school (admins see every one), **newest first**. `?subject=` narrows to one origin subject; `?owner=` to one owner (a user id, or `me` for the caller); `?q=` to a case-insensitive fragment of the question text; `?visibility=private\|school` to one shelf — it narrows what the caller may already see and never widens it, so `private` is "my drafts" and `school` the published library. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope, where `total` counts every match under the same filters, not just this page. Each item carries the resolved `subject_name`/`owner_name` so a client needn't look them up per row, plus `used_count` — how many exam questions were copied out of that template (one grouped query for the page, not one per row). | | 1081 | | GET | `/bank-questions` | teacher | The bank the caller may see — their own templates plus the ones published to the school (admins see every one), **newest first**. `?subject=` narrows to one origin subject; `?owner=` to one owner (a user id, or `me` for the caller); `?q=` to a case-insensitive fragment of the question text; `?visibility=private\|school` to one shelf — it narrows what the caller may already see and never widens it, so `private` is "my drafts" and `school` the published library. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope, where `total` counts every match under the same filters, not just this page. Each item carries the resolved `subject_name`/`owner_name` so a client needn't look them up per row, plus `used_count` — how many exam questions were copied out of that template (one grouped query for the page, not one per row). | |
| 1055 | | POST | `/bank-questions` | teacher | Add a template to the bank. Requires teacher+. `subject_id` is origin metadata (any subject — the same-course rule lives at instantiate time), so it need only exist (an unknown subject is a `400`). `choice` templates carry 2–10 `choices` plus `correct` naming one of them by id; `text` templates carry neither. The caller becomes the owner. | | 1082 | | POST | `/bank-questions` | teacher | Add a template to the bank. Requires teacher+. `subject_id` is origin metadata (any subject — the same-course rule lives at instantiate time), so it need only exist (an unknown subject is a `400`). `choice` templates carry 2–10 `choices` plus `correct` naming one of them by id; `text` templates carry neither. The caller becomes the owner. | |
| 1056 | | GET | `/bank-questions/{bid}` | teacher | One template by id. Visible ones only: a `private` template belonging to someone else is a 404, not a 403 — a 403 would confirm it exists. | | 1083 | | GET | `/bank-questions/{bid}` | teacher | One template by id. Visible ones only: a `private` template belonging to someone else is a 404, not a 403 — a 403 would confirm it exists. | |
migrations/control/20260913000001_person.sqladded+42 -0
| @@ -0,0 +1,42 @@ | |||
| 1 | +-- Person identity (control database). | ||
| 2 | +-- | ||
| 3 | +-- DISJOINTNESS INVARIANT: the tables here (person, person_school, | ||
| 4 | +-- person_session) and every other control table together with all of | ||
| 5 | +-- migrations/school/*.sql form ONE union schema, applied to a single prepare | ||
| 6 | +-- database by scripts/prepare_db.sh for sqlx's compile-time query macros. | ||
| 7 | +-- The sets must never collide on a table name; the prepare script fails | ||
| 8 | +-- loudly if they do. | ||
| 9 | +-- | ||
| 10 | +-- A person is the global account behind a school's `app_user` rows: one | ||
| 11 | +-- username + password in the control plane, any number of school | ||
| 12 | +-- memberships. Login verifies `person.password_hash` only; the school-side | ||
| 13 | +-- copy stays written (same hash) so school queries keep compiling. Timestamps | ||
| 14 | +-- stay BIGINT unix-ms; all FKs ON DELETE NO ACTION — cascades stay explicit | ||
| 15 | +-- application transactions (Tenants::drop deletes person_school before the | ||
| 16 | +-- school row). | ||
| 17 | + | ||
| 18 | +CREATE TABLE person ( | ||
| 19 | + id uuid PRIMARY KEY, | ||
| 20 | + username TEXT NOT NULL, | ||
| 21 | + password_hash TEXT NOT NULL, | ||
| 22 | + -- Globally unique: the same username in two school databases is one and | ||
| 23 | + -- the same person, copied into each school's `app_user`. | ||
| 24 | + CONSTRAINT person_username UNIQUE (username) | ||
| 25 | +); | ||
| 26 | + | ||
| 27 | +CREATE TABLE person_school ( | ||
| 28 | + person uuid NOT NULL REFERENCES person(id) ON DELETE NO ACTION, | ||
| 29 | + school TEXT NOT NULL REFERENCES school(slug) ON DELETE NO ACTION, | ||
| 30 | + CONSTRAINT person_school_person_school PRIMARY KEY (person, school) | ||
| 31 | +); | ||
| 32 | + | ||
| 33 | +CREATE TABLE person_session ( | ||
| 34 | + id uuid PRIMARY KEY, | ||
| 35 | + person uuid NOT NULL REFERENCES person(id) ON DELETE NO ACTION, | ||
| 36 | + token TEXT NOT NULL, | ||
| 37 | + created_at BIGINT NOT NULL, | ||
| 38 | + expires_at BIGINT NOT NULL, | ||
| 39 | + CONSTRAINT person_session_token UNIQUE (token) | ||
| 40 | +); | ||
| 41 | + | ||
| 42 | +CREATE INDEX person_session_expires ON person_session (expires_at); | ||
src/db/mod.rsmodified+1 -0
| @@ -46,6 +46,7 @@ pub mod note; | |||
| 46 | pub mod note_file; | 46 | pub mod note_file; |
| 47 | pub mod page; | 47 | pub mod page; |
| 48 | pub mod parent_link; | 48 | pub mod parent_link; |
| 49 | +pub mod person; | ||
| 49 | pub mod payment_ledger; | 50 | pub mod payment_ledger; |
| 50 | pub mod pomodoro; | 51 | pub mod pomodoro; |
| 51 | pub mod pool_question; | 52 | pub mod pool_question; |
src/db/person.rsadded+212 -0
| @@ -0,0 +1,212 @@ | |||
| 1 | +//! The person tables against the **control** database: the global account, | ||
| 2 | +//! its school memberships, and its login sessions keyed by cookie token. A | ||
| 3 | +//! person row exists once no matter how many school databases hold an | ||
| 4 | +//! `app_user` copy; the credential newtypes are [`crate::domain::user`]'s and | ||
| 5 | +//! the register-side workflow is [`crate::service::person`]. | ||
| 6 | + | ||
| 7 | +use crate::constant::SESSION_DURATION_DAYS; | ||
| 8 | +use crate::database::Database; | ||
| 9 | +use crate::domain::person::{Membership, Person, PersonId, PersonSession}; | ||
| 10 | +use crate::domain::session::{SessionId, SessionToken}; | ||
| 11 | +use crate::domain::timestamp::Timestamp; | ||
| 12 | +use crate::domain::user::{PasswordHash, Username}; | ||
| 13 | +use crate::error::AppError; | ||
| 14 | +use crate::tenant::{SchoolStatus, Slug}; | ||
| 15 | + | ||
| 16 | +/// The raw account insert behind [`crate::service::person::create_or_load`]. | ||
| 17 | +/// The unique index on `username` is the whole availability check; the loser | ||
| 18 | +/// of a race gets the same `Conflict` a sequential duplicate would. | ||
| 19 | +pub async fn create(db: &Database, person: Person) -> Result<(), AppError> { | ||
| 20 | + match sqlx::query!( | ||
| 21 | + "INSERT INTO person (id, username, password_hash) VALUES ($1, $2, $3)", | ||
| 22 | + person.id.uuid(), | ||
| 23 | + person.username.as_str(), | ||
| 24 | + person.password_hash.as_str(), | ||
| 25 | + ) | ||
| 26 | + .execute(db) | ||
| 27 | + .await | ||
| 28 | + { | ||
| 29 | + Ok(_) => Ok(()), | ||
| 30 | + Err(err) if crate::database::unique_violation(&err) == Some("person_username") => { | ||
| 31 | + Err(AppError::Conflict("username already taken")) | ||
| 32 | + } | ||
| 33 | + Err(err) => Err(err.into()), | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +pub async fn read(db: &Database, id: &PersonId) -> Result<Option<Person>, AppError> { | ||
| 38 | + let person = sqlx::query_as!( | ||
| 39 | + Person, | ||
| 40 | + r#"SELECT id AS "id: PersonId", | ||
| 41 | + username AS "username: Username", | ||
| 42 | + password_hash AS "password_hash: PasswordHash" | ||
| 43 | + FROM person WHERE id = $1"#, | ||
| 44 | + id.uuid() | ||
| 45 | + ) | ||
| 46 | + .fetch_optional(db) | ||
| 47 | + .await?; | ||
| 48 | + Ok(person) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// The login lookup. Usernames are stored trimmed; callers trim the same way | ||
| 52 | +/// so a padded attempt matches the canonical name. | ||
| 53 | +pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Person>, AppError> { | ||
| 54 | + let person = sqlx::query_as!( | ||
| 55 | + Person, | ||
| 56 | + r#"SELECT id AS "id: PersonId", | ||
| 57 | + username AS "username: Username", | ||
| 58 | + password_hash AS "password_hash: PasswordHash" | ||
| 59 | + FROM person WHERE username = $1"#, | ||
| 60 | + username.trim() | ||
| 61 | + ) | ||
| 62 | + .fetch_optional(db) | ||
| 63 | + .await?; | ||
| 64 | + Ok(person) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// Every school the person belongs to, slug order, with the registry's name | ||
| 68 | +/// and status joined in. Suspended schools are part of the answer — the | ||
| 69 | +/// caller decides what to offer. | ||
| 70 | +pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Membership>, AppError> { | ||
| 71 | + let rows = sqlx::query_as!( | ||
| 72 | + Membership, | ||
| 73 | + r#"SELECT s.slug AS "slug: Slug", | ||
| 74 | + s.name, | ||
| 75 | + s.status AS "status: SchoolStatus" | ||
| 76 | + FROM person_school ps | ||
| 77 | + JOIN school s ON s.slug = ps.school | ||
| 78 | + WHERE ps.person = $1 | ||
| 79 | + ORDER BY s.slug"#, | ||
| 80 | + person.uuid() | ||
| 81 | + ) | ||
| 82 | + .fetch_all(db) | ||
| 83 | + .await?; | ||
| 84 | + Ok(rows) | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// The person's membership in exactly one school — the `POST /auth/school` | ||
| 88 | +/// gate. A slug the person does not hold is the same `None` a malformed one | ||
| 89 | +/// is: no existence signal either way. | ||
| 90 | +pub async fn membership_of( | ||
| 91 | + db: &Database, | ||
| 92 | + person: &PersonId, | ||
| 93 | + slug: &Slug, | ||
| 94 | +) -> Result<Option<Membership>, AppError> { | ||
| 95 | + let row = sqlx::query_as!( | ||
| 96 | + Membership, | ||
| 97 | + r#"SELECT s.slug AS "slug: Slug", | ||
| 98 | + s.name, | ||
| 99 | + s.status AS "status: SchoolStatus" | ||
| 100 | + FROM person_school ps | ||
| 101 | + JOIN school s ON s.slug = ps.school | ||
| 102 | + WHERE ps.person = $1 AND ps.school = $2"#, | ||
| 103 | + person.uuid(), | ||
| 104 | + slug.as_str() | ||
| 105 | + ) | ||
| 106 | + .fetch_optional(db) | ||
| 107 | + .await?; | ||
| 108 | + Ok(row) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// Attach a person to a school. Idempotent by the primary key: a racing or | ||
| 112 | +/// repeated join is a no-op, not an error. | ||
| 113 | +pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Result<(), AppError> { | ||
| 114 | + sqlx::query!( | ||
| 115 | + "INSERT INTO person_school (person, school) VALUES ($1, $2) ON CONFLICT DO NOTHING", | ||
| 116 | + person.uuid(), | ||
| 117 | + slug.as_str() | ||
| 118 | + ) | ||
| 119 | + .execute(db) | ||
| 120 | + .await?; | ||
| 121 | + Ok(()) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Drop every membership pointing at a school — [`crate::tenant::Tenants::drop`]'s | ||
| 125 | +/// first control-plane half, so `ON DELETE NO ACTION` never refuses the | ||
| 126 | +/// registry delete. Persons themselves survive: a person is a global | ||
| 127 | +/// account, not the school's. | ||
| 128 | +pub async fn delete_memberships_by_school(db: &Database, slug: &Slug) -> Result<(), AppError> { | ||
| 129 | + sqlx::query!("DELETE FROM person_school WHERE school = $1", slug.as_str()) | ||
| 130 | + .execute(db) | ||
| 131 | + .await?; | ||
| 132 | + Ok(()) | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// Mint and store one person login session (the `person.` cookie). | ||
| 136 | +pub async fn create_session(db: &Database, person: &PersonId) -> Result<PersonSession, AppError> { | ||
| 137 | + let id = SessionId::generate(); | ||
| 138 | + let token = SessionToken::generate()?; | ||
| 139 | + let expires_at = Timestamp::in_days(SESSION_DURATION_DAYS); | ||
| 140 | + let session = sqlx::query_as!( | ||
| 141 | + PersonSession, | ||
| 142 | + r#"INSERT INTO person_session (id, person, token, created_at, expires_at) | ||
| 143 | + VALUES ($1, $2, $3, $4, $5) | ||
| 144 | + RETURNING person AS "person: PersonId", | ||
| 145 | + token AS "token: SessionToken", | ||
| 146 | + expires_at AS "expires_at: Timestamp""#, | ||
| 147 | + id.uuid(), | ||
| 148 | + person.uuid(), | ||
| 149 | + token.as_str(), | ||
| 150 | + Timestamp::now().as_millis(), | ||
| 151 | + expires_at.as_millis(), | ||
| 152 | + ) | ||
| 153 | + .fetch_one(db) | ||
| 154 | + .await?; | ||
| 155 | + Ok(session) | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +pub async fn find_session_by_token( | ||
| 159 | + db: &Database, | ||
| 160 | + token: &str, | ||
| 161 | +) -> Result<Option<PersonSession>, AppError> { | ||
| 162 | + let session = sqlx::query_as!( | ||
| 163 | + PersonSession, | ||
| 164 | + r#"SELECT person AS "person: PersonId", | ||
| 165 | + token AS "token: SessionToken", | ||
| 166 | + expires_at AS "expires_at: Timestamp" | ||
| 167 | + FROM person_session WHERE token = $1"#, | ||
| 168 | + token | ||
| 169 | + ) | ||
| 170 | + .fetch_optional(db) | ||
| 171 | + .await?; | ||
| 172 | + Ok(session) | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +pub async fn delete_session_by_token(db: &Database, token: &str) -> Result<(), AppError> { | ||
| 176 | + sqlx::query!("DELETE FROM person_session WHERE token = $1", token) | ||
| 177 | + .execute(db) | ||
| 178 | + .await?; | ||
| 179 | + Ok(()) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Revoke every person-login session for this account — the other half of a | ||
| 183 | +/// password reset. School sessions are deleted separately against the school | ||
| 184 | +/// database; leaving these alive would let a `person.<token>` cookie mint a | ||
| 185 | +/// new school session with the old credential. | ||
| 186 | +pub async fn delete_sessions_by_person(db: &Database, person: &PersonId) -> Result<(), AppError> { | ||
| 187 | + sqlx::query!( | ||
| 188 | + "DELETE FROM person_session WHERE person = $1", | ||
| 189 | + person.uuid() | ||
| 190 | + ) | ||
| 191 | + .execute(db) | ||
| 192 | + .await?; | ||
| 193 | + Ok(()) | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +/// Move the person credential — the one login reads. The school-side | ||
| 197 | +/// `app_user` copy is rewritten separately by the same caller, so the two | ||
| 198 | +/// stay in step. | ||
| 199 | +pub async fn set_password_hash( | ||
| 200 | + db: &Database, | ||
| 201 | + username: &Username, | ||
| 202 | + password_hash: &PasswordHash, | ||
| 203 | +) -> Result<(), AppError> { | ||
| 204 | + sqlx::query!( | ||
| 205 | + "UPDATE person SET password_hash = $2 WHERE username = $1", | ||
| 206 | + username.as_str(), | ||
| 207 | + password_hash.as_str() | ||
| 208 | + ) | ||
| 209 | + .execute(db) | ||
| 210 | + .await?; | ||
| 211 | + Ok(()) | ||
| 212 | +} | ||
src/domain/mod.rsmodified+1 -0
| @@ -57,6 +57,7 @@ pub mod profile; | |||
| 57 | pub mod question_image; | 57 | pub mod question_image; |
| 58 | pub mod rag_output; | 58 | pub mod rag_output; |
| 59 | pub mod registration; | 59 | pub mod registration; |
| 60 | +pub mod person; | ||
| 60 | pub mod role; | 61 | pub mod role; |
| 61 | pub mod session; | 62 | pub mod session; |
| 62 | pub mod session_attendance; | 63 | pub mod session_attendance; |
src/domain/person.rsadded+105 -0
| @@ -0,0 +1,105 @@ | |||
| 1 | +//! Pure person shapes: the typed id, the control-plane account row, the | ||
| 2 | +//! school memberships read off the registry join, and the `person.` login | ||
| 3 | +//! session. Persistence lives in [`crate::db::person`]; the register-side | ||
| 4 | +//! create-or-load in [`crate::service::person`]. | ||
| 5 | +//! | ||
| 6 | +//! A person is the global account behind a school's [`crate::domain::user`] | ||
| 7 | +//! rows: one username + password in the control database, any number of | ||
| 8 | +//! memberships. Role and profile stay per-school — a person has neither | ||
| 9 | +//! here, only the credential and where they belong. | ||
| 10 | + | ||
| 11 | +use uuid::Uuid; | ||
| 12 | + | ||
| 13 | +use crate::domain::monotonic_id::next_uuid; | ||
| 14 | +use crate::domain::session::SessionToken; | ||
| 15 | +use crate::domain::timestamp::Timestamp; | ||
| 16 | +use crate::domain::user::{PasswordHash, Username}; | ||
| 17 | +use crate::tenant::{SchoolStatus, Slug}; | ||
| 18 | + | ||
| 19 | +/// Typed person row id (control database). A UUIDv7 minted by the | ||
| 20 | +/// process-wide monotonic generator, so `id` order is mint order. | ||
| 21 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 22 | +#[sqlx(transparent)] | ||
| 23 | +pub struct PersonId(Uuid); | ||
| 24 | + | ||
| 25 | +impl PersonId { | ||
| 26 | + pub fn generate() -> Self { | ||
| 27 | + Self(next_uuid()) | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that | ||
| 31 | + /// cannot take the newtype. Static `query!` binds take `self` directly. | ||
| 32 | + pub fn uuid(&self) -> Uuid { | ||
| 33 | + self.0 | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// The control-plane account row. Fields are crate-visible: | ||
| 38 | +/// [`crate::db::person`] mints rows, exactly like the other split domains. | ||
| 39 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 40 | +pub struct Person { | ||
| 41 | + pub(crate) id: PersonId, | ||
| 42 | + pub(crate) username: Username, | ||
| 43 | + pub(crate) password_hash: PasswordHash, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +impl Person { | ||
| 47 | + pub fn get_id(&self) -> &PersonId { | ||
| 48 | + &self.id | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + pub fn get_username(&self) -> &Username { | ||
| 52 | + &self.username | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + pub fn get_password_hash(&self) -> &PasswordHash { | ||
| 56 | + &self.password_hash | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// One school a person belongs to, joined off the control registry. | ||
| 61 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 62 | +pub struct Membership { | ||
| 63 | + pub(crate) slug: Slug, | ||
| 64 | + pub(crate) name: String, | ||
| 65 | + pub(crate) status: SchoolStatus, | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +impl Membership { | ||
| 69 | + pub fn slug(&self) -> &Slug { | ||
| 70 | + &self.slug | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + pub fn name(&self) -> &str { | ||
| 74 | + &self.name | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + /// A suspended school is not offered at login and cannot be selected. | ||
| 78 | + pub fn is_active(&self) -> bool { | ||
| 79 | + self.status == SchoolStatus::Active | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// A control-plane login session — the row behind a `person.<token>` cookie. | ||
| 84 | +/// It names no school: it is exactly the not-yet-chosen state, and | ||
| 85 | +/// `POST /auth/school` exchanges it for a school session. | ||
| 86 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 87 | +pub struct PersonSession { | ||
| 88 | + pub(crate) person: PersonId, | ||
| 89 | + pub(crate) token: SessionToken, | ||
| 90 | + pub(crate) expires_at: Timestamp, | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +impl PersonSession { | ||
| 94 | + pub fn token(&self) -> &SessionToken { | ||
| 95 | + &self.token | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + pub fn person(&self) -> &PersonId { | ||
| 99 | + &self.person | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + pub fn is_expired(&self) -> bool { | ||
| 103 | + self.expires_at.is_past() | ||
| 104 | + } | ||
| 105 | +} | ||
src/lib.rsmodified+1 -1
| @@ -52,7 +52,7 @@ use crate::web::module_gate::gate; | |||
| 52 | (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"), | 52 | (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"), |
| 53 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), | 53 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), |
| 54 | (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."), | 54 | (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."), |
| 55 | - (name = "auth", description = "Registration, login, session lifecycle. Both bodies name the **school**: `{school, username, password}`, since one deployment serves many schools and a username identifies an account only inside one of them; login sets a `session` cookie valued `<slug>.<token>` (see the `builder` tag). `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), | 55 | + (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"), |
| 56 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), | 56 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), |
| 57 | (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), | 57 | (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), |
| 58 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), | 58 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), |
src/service/mod.rsmodified+1 -0
| @@ -43,6 +43,7 @@ pub mod note; | |||
| 43 | pub mod note_file; | 43 | pub mod note_file; |
| 44 | pub mod parent_link; | 44 | pub mod parent_link; |
| 45 | pub mod payment_ledger; | 45 | pub mod payment_ledger; |
| 46 | +pub mod person; | ||
| 46 | pub mod pomodoro; | 47 | pub mod pomodoro; |
| 47 | pub mod pool_question; | 48 | pub mod pool_question; |
| 48 | pub mod profile; | 49 | pub mod profile; |
src/service/person.rsadded+112 -0
| @@ -0,0 +1,112 @@ | |||
| 1 | +//! Person workflows on the control database: the create-or-load behind the | ||
| 2 | +//! register and school-create paths, and the credential mirroring that keeps | ||
| 3 | +//! a person and their school `app_user` copies in step. The queries live in | ||
| 4 | +//! [`crate::db::person`]; login itself stays in the web layer, which is the | ||
| 5 | +//! one place that sees both the control handle and the school handles. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::person; | ||
| 9 | +use crate::domain::person::{Membership, Person, PersonId, PersonSession}; | ||
| 10 | +use crate::domain::user::{PasswordHash, Username}; | ||
| 11 | +use crate::error::AppError; | ||
| 12 | +use crate::tenant::Slug; | ||
| 13 | + | ||
| 14 | +/// Create the person, or hand back the one already standing under | ||
| 15 | +/// `username`. The incoming hash is stored only on the create path — an | ||
| 16 | +/// existing person's stored credential is never rewritten here, because the | ||
| 17 | +/// caller has not yet proven they know it. The register and school-create | ||
| 18 | +/// callers verify against the returned row before joining. | ||
| 19 | +pub async fn create_or_load( | ||
| 20 | + control: &Database, | ||
| 21 | + username: Username, | ||
| 22 | + password_hash: PasswordHash, | ||
| 23 | +) -> Result<Person, AppError> { | ||
| 24 | + let created = person::create( | ||
| 25 | + control, | ||
| 26 | + Person { | ||
| 27 | + id: PersonId::generate(), | ||
| 28 | + username: username.clone(), | ||
| 29 | + password_hash, | ||
| 30 | + }, | ||
| 31 | + ) | ||
| 32 | + .await; | ||
| 33 | + match created { | ||
| 34 | + Ok(()) | Err(AppError::Conflict(_)) => person::find_by_username(control, username.as_str()) | ||
| 35 | + .await? | ||
| 36 | + .ok_or_else(|| AppError::Internal("the person vanished as it was written".into())), | ||
| 37 | + Err(err) => Err(err), | ||
| 38 | + } | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// Attach a person to a school. Idempotent — see [`person::add_membership`]. | ||
| 42 | +pub async fn link_school( | ||
| 43 | + control: &Database, | ||
| 44 | + person: &PersonId, | ||
| 45 | + slug: &Slug, | ||
| 46 | +) -> Result<(), AppError> { | ||
| 47 | + person::add_membership(control, person, slug).await | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +pub async fn read(control: &Database, id: &PersonId) -> Result<Option<Person>, AppError> { | ||
| 51 | + person::read(control, id).await | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The login lookup. Usernames are stored trimmed; callers trim the same way | ||
| 55 | +/// so a padded attempt matches the canonical name. | ||
| 56 | +pub async fn find_by_username( | ||
| 57 | + control: &Database, | ||
| 58 | + username: &str, | ||
| 59 | +) -> Result<Option<Person>, AppError> { | ||
| 60 | + person::find_by_username(control, username).await | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +pub async fn memberships( | ||
| 64 | + control: &Database, | ||
| 65 | + person: &PersonId, | ||
| 66 | +) -> Result<Vec<Membership>, AppError> { | ||
| 67 | + person::memberships(control, person).await | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +pub async fn membership_of( | ||
| 71 | + control: &Database, | ||
| 72 | + person: &PersonId, | ||
| 73 | + slug: &Slug, | ||
| 74 | +) -> Result<Option<Membership>, AppError> { | ||
| 75 | + person::membership_of(control, person, slug).await | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +pub async fn create_session( | ||
| 79 | + control: &Database, | ||
| 80 | + person: &PersonId, | ||
| 81 | +) -> Result<PersonSession, AppError> { | ||
| 82 | + person::create_session(control, person).await | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +pub async fn find_session_by_token( | ||
| 86 | + control: &Database, | ||
| 87 | + token: &str, | ||
| 88 | +) -> Result<Option<PersonSession>, AppError> { | ||
| 89 | + person::find_session_by_token(control, token).await | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +pub async fn delete_session_by_token(control: &Database, token: &str) -> Result<(), AppError> { | ||
| 93 | + person::delete_session_by_token(control, token).await | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +pub async fn delete_sessions_by_person( | ||
| 97 | + control: &Database, | ||
| 98 | + person: &PersonId, | ||
| 99 | +) -> Result<(), AppError> { | ||
| 100 | + person::delete_sessions_by_person(control, person).await | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// The school-user password writes mirror the person credential: login reads | ||
| 104 | +/// `person.password_hash` and nothing else, so a reset that moved only the | ||
| 105 | +/// school row would reset nothing. | ||
| 106 | +pub async fn set_password_hash( | ||
| 107 | + control: &Database, | ||
| 108 | + username: &Username, | ||
| 109 | + password_hash: &PasswordHash, | ||
| 110 | +) -> Result<(), AppError> { | ||
| 111 | + person::set_password_hash(control, username, password_hash).await | ||
| 112 | +} | ||
src/service/user.rsmodified+26 -6
| @@ -4,6 +4,7 @@ | |||
| 4 | //! the row mint, and the field-scoped writers live in [`crate::db::user`]. | 4 | //! the row mint, and the field-scoped writers live in [`crate::db::user`]. |
| 5 | 5 | ||
| 6 | use crate::database::Database; | 6 | use crate::database::Database; |
| 7 | +use crate::tenant::{Slug, Tenants}; | ||
| 7 | use crate::db::user; | 8 | use crate::db::user; |
| 8 | use crate::domain::board::Board; | 9 | use crate::domain::board::Board; |
| 9 | use crate::domain::note_file::FileContentType; | 10 | use crate::domain::note_file::FileContentType; |
| @@ -20,18 +21,20 @@ use crate::error::AppError; | |||
| 20 | /// a warning: silently promoting an account someone else registered would | 21 | /// a warning: silently promoting an account someone else registered would |
| 21 | /// be a privilege escalation, so that conflict is resolved out-of-band. | 22 | /// be a privilege escalation, so that conflict is resolved out-of-band. |
| 22 | pub async fn ensure_admin( | 23 | pub async fn ensure_admin( |
| 23 | - db: &Database, | 24 | + tenants: &Tenants, |
| 25 | + slug: &Slug, | ||
| 24 | username: Username, | 26 | username: Username, |
| 25 | password: Password, | 27 | password: Password, |
| 26 | ) -> Result<(), AppError> { | 28 | ) -> Result<(), AppError> { |
| 27 | - match user::find_by_username(db, username.as_str()).await? { | 29 | + let db = tenants.get(slug).await?; |
| 28 | - Some(user) if user.role == Role::Admin => Ok(()), | 30 | + match user::find_by_username(&db, username.as_str()).await? { |
| 31 | + Some(user) if user.role == Role::Admin => {} | ||
| 29 | Some(_) => { | 32 | Some(_) => { |
| 30 | tracing::warn!( | 33 | tracing::warn!( |
| 31 | "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ | 34 | "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ |
| 32 | Grant the role through an existing admin or a hand-run SQL session." | 35 | Grant the role through an existing admin or a hand-run SQL session." |
| 33 | ); | 36 | ); |
| 34 | - Ok(()) | 37 | + return Ok(()); |
| 35 | } | 38 | } |
| 36 | None => { | 39 | None => { |
| 37 | // One statement, admin from birth. Never create-then-promote: | 40 | // One statement, admin from birth. Never create-then-promote: |
| @@ -41,13 +44,30 @@ pub async fn ensure_admin( | |||
| 41 | // is no marker that could tell such a row apart from a stranger | 44 | // is no marker that could tell such a row apart from a stranger |
| 42 | // who registered the name first, so the hole cannot be healed | 45 | // who registered the name first, so the hole cannot be healed |
| 43 | // later; it has to be impossible to open. | 46 | // later; it has to be impossible to open. |
| 44 | - user::create_with_role(db, username, password.hash_async().await?, Role::Admin).await?; | 47 | + user::create_with_role( |
| 48 | + &db, | ||
| 49 | + username.clone(), | ||
| 50 | + password.hash_async().await?, | ||
| 51 | + Role::Admin, | ||
| 52 | + ) | ||
| 53 | + .await?; | ||
| 45 | // No `username` field: with OTLP on every event is exported as a | 54 | // No `username` field: with OTLP on every event is exported as a |
| 46 | // log record, so an account name here leaves the process. | 55 | // log record, so an account name here leaves the process. |
| 47 | tracing::info!("seeded the admin account named by ADMIN_USERNAME"); | 56 | tracing::info!("seeded the admin account named by ADMIN_USERNAME"); |
| 48 | - Ok(()) | ||
| 49 | } | 57 | } |
| 50 | } | 58 | } |
| 59 | + // The person half: login reads the control-plane credential, so the | ||
| 60 | + // seeded admin needs their `person` row and the membership too. Both | ||
| 61 | + // writes are idempotent (create-or-load never re-keys an existing | ||
| 62 | + // person's password; the membership insert is `ON CONFLICT DO NOTHING`), | ||
| 63 | + // so every boot re-runs them — and a school whose seed predates the | ||
| 64 | + // person half heals on the next boot instead of stranding an admin who | ||
| 65 | + // cannot log in. | ||
| 66 | + let password_hash = password.hash_async().await?; | ||
| 67 | + let person = | ||
| 68 | + crate::service::person::create_or_load(tenants.control(), username, password_hash).await?; | ||
| 69 | + crate::service::person::link_school(tenants.control(), person.get_id(), slug).await?; | ||
| 70 | + Ok(()) | ||
| 51 | } | 71 | } |
| 52 | 72 | ||
| 53 | /// Overwrite this user's role **and** shed every grant the new role may not | 73 | /// Overwrite this user's role **and** shed every grant the new role may not |
src/tenant.rsmodified+11 -4
| @@ -38,10 +38,11 @@ use crate::web::tenant_state::ResolvedTenant; | |||
| 38 | /// the suites agree on. | 38 | /// the suites agree on. |
| 39 | pub const DEMO_SLUG: &str = "demo"; | 39 | pub const DEMO_SLUG: &str = "demo"; |
| 40 | 40 | ||
| 41 | -/// Slugs that name something other than a school: the builder cookie prefix and | 41 | +/// Slugs that name something other than a school: the builder cookie prefix, |
| 42 | -/// the control database itself. Refused at construction, so neither a login nor | 42 | +/// the control database itself, and the person cookie prefix. Refused at |
| 43 | -/// a `CREATE DATABASE` can ever be aimed at them. | 43 | +/// construction, so neither a login nor a `CREATE DATABASE` can ever be |
| 44 | -pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"]; | 44 | +/// aimed at them. |
| 45 | +pub const RESERVED_SLUGS: [&str; 3] = ["builder", "control", "person"]; | ||
| 45 | 46 | ||
| 46 | /// A school's identity everywhere it is named: the cookie prefix, the database | 47 | /// A school's identity everywhere it is named: the cookie prefix, the database |
| 47 | /// name, and the files subdirectory. The character set is deliberately the | 48 | /// name, and the files subdirectory. The character set is deliberately the |
| @@ -503,6 +504,12 @@ impl Tenants { | |||
| 503 | // database is about to go away, and `WITH (FORCE)` should never find | 504 | // database is about to go away, and `WITH (FORCE)` should never find |
| 504 | // one of our connections to kill. | 505 | // one of our connections to kill. |
| 505 | self.evict(slug).await; | 506 | self.evict(slug).await; |
| 507 | + // The control-plane membership rows point at the school by slug, and | ||
| 508 | + // `ON DELETE NO ACTION` would refuse the registry delete while any | ||
| 509 | + // stand. Person sessions carry no school, so only memberships go — | ||
| 510 | + // the persons themselves survive (a person is a global account, not | ||
| 511 | + // the school's). | ||
| 512 | + crate::db::person::delete_memberships_by_school(&self.control, slug).await?; | ||
| 506 | sqlx::query("DELETE FROM school WHERE slug = $1") | 513 | sqlx::query("DELETE FROM school WHERE slug = $1") |
| 507 | .bind(slug.as_str()) | 514 | .bind(slug.as_str()) |
| 508 | .execute(&self.control) | 515 | .execute(&self.control) |
src/web/auth.rsmodified+252 -69
| @@ -20,7 +20,7 @@ use crate::tenant::Slug; | |||
| 20 | 20 | ||
| 21 | use super::dto::Role; | 21 | use super::dto::Role; |
| 22 | use super::tenant_state::split_cookie; | 22 | use super::tenant_state::split_cookie; |
| 23 | -use super::{BUILDER_COOKIE_PREFIX, CurrentUser, UserResponse}; | 23 | +use super::{BUILDER_COOKIE_PREFIX, CurrentUser, PERSON_COOKIE_PREFIX, UserResponse}; |
| 24 | 24 | ||
| 25 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | 25 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { |
| 26 | // Strict per-IP limit on the two credential endpoints only — the | 26 | // Strict per-IP limit on the two credential endpoints only — the |
| @@ -40,15 +40,19 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | |||
| 40 | let limiter = limiter.clone(); | 40 | let limiter = limiter.clone(); |
| 41 | async move { limiter.enforce(req, next).await } | 41 | async move { limiter.enforce(req, next).await } |
| 42 | })) | 42 | })) |
| 43 | + .routes(routes!(select_school)) | ||
| 43 | .routes(routes!(logout)) | 44 | .routes(routes!(logout)) |
| 44 | .routes(routes!(me)) | 45 | .routes(routes!(me)) |
| 45 | } | 46 | } |
| 46 | 47 | ||
| 48 | +/// What `POST /auth/register` takes: registration is still aimed at a school. | ||
| 49 | +/// Split from the login body — a login names no school, it picks the school | ||
| 50 | +/// afterwards. Serde ignores unknown fields, so a frontend that still sends | ||
| 51 | +/// `school` to login is merely ignored, not broken. | ||
| 47 | #[derive(Deserialize, ToSchema)] | 52 | #[derive(Deserialize, ToSchema)] |
| 48 | -struct Credentials { | 53 | +struct RegisterCredentials { |
| 49 | - /// The school's slug — the name in front of the dot in the session cookie. | 54 | + /// The school's slug — where the new account (or the new membership of an |
| 50 | - /// One backend serves many schools, so a username only identifies an | 55 | + /// existing person) lives. |
| 51 | - /// account together with this. | ||
| 52 | #[schema(example = "demo", min_length = 2, max_length = 32)] | 56 | #[schema(example = "demo", min_length = 2, max_length = 32)] |
| 53 | school: String, | 57 | school: String, |
| 54 | #[schema(example = "ada", min_length = 3, max_length = 32)] | 58 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| @@ -57,6 +61,55 @@ struct Credentials { | |||
| 57 | password: String, | 61 | password: String, |
| 58 | } | 62 | } |
| 59 | 63 | ||
| 64 | +/// What `POST /auth/login` takes. The account is a **person**: one global | ||
| 65 | +/// username + password, no school — a person with several memberships chooses | ||
| 66 | +/// one afterwards (`POST /auth/school`). | ||
| 67 | +#[derive(Deserialize, ToSchema)] | ||
| 68 | +struct LoginCredentials { | ||
| 69 | + #[schema(example = "ada", min_length = 3, max_length = 32)] | ||
| 70 | + username: String, | ||
| 71 | + #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] | ||
| 72 | + password: String, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// One school offered to a multi-school person. | ||
| 76 | +#[derive(Serialize, ToSchema)] | ||
| 77 | +struct SchoolChoice { | ||
| 78 | + #[schema(example = "demo")] | ||
| 79 | + slug: String, | ||
| 80 | + #[schema(example = "Demo")] | ||
| 81 | + name: String, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// What `POST /auth/login` answers when the person belongs to more than one | ||
| 85 | +/// active school: no `id` (no school is entered yet, so there is no school | ||
| 86 | +/// row to speak of), and no school cookie. The `schools` list is in slug | ||
| 87 | +/// order and omits suspended schools. | ||
| 88 | +#[derive(Serialize, ToSchema)] | ||
| 89 | +struct SchoolChoiceResponse { | ||
| 90 | + #[schema(example = "ada")] | ||
| 91 | + username: String, | ||
| 92 | + schools: Vec<SchoolChoice>, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// The two login outcomes, told apart by shape: a school was entered (a | ||
| 96 | +/// [`UserResponse`] and a `<slug>.<token>` cookie), or one must be chosen (a | ||
| 97 | +/// [`SchoolChoiceResponse`] and a `person.<token>` cookie). Disjoint by the | ||
| 98 | +/// `id` field, so an untagged `oneOf` is unambiguous on the wire. | ||
| 99 | +#[derive(Serialize, ToSchema)] | ||
| 100 | +#[serde(untagged)] | ||
| 101 | +enum LoginResponse { | ||
| 102 | + LoggedIn(UserResponse), | ||
| 103 | + ChooseSchool(SchoolChoiceResponse), | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// What `POST /auth/school` takes: which of the person's memberships to bind. | ||
| 107 | +#[derive(Deserialize, ToSchema)] | ||
| 108 | +struct SelectSchool { | ||
| 109 | + #[schema(example = "demo", min_length = 2, max_length = 32)] | ||
| 110 | + school: String, | ||
| 111 | +} | ||
| 112 | + | ||
| 60 | /// What `POST /auth/register` answers with — deliberately *not* [`UserResponse`]. | 113 | /// What `POST /auth/register` answers with — deliberately *not* [`UserResponse`]. |
| 61 | /// It carries only what is true of both outcomes (created, and already-taken): | 114 | /// It carries only what is true of both outcomes (created, and already-taken): |
| 62 | /// the echoed username and the role every fresh account gets. No `id`, because | 115 | /// the echoed username and the role every fresh account gets. No `id`, because |
| @@ -70,25 +123,30 @@ struct RegisterResponse { | |||
| 70 | role: Role, | 123 | role: Role, |
| 71 | } | 124 | } |
| 72 | 125 | ||
| 73 | -/// Register a new user account: `{school, username, password}` in, `{username, role}` | 126 | +/// Register a new user account, or attach an existing person to one more |
| 74 | -/// back (no `id`; new accounts are `student`). Always `201`, even if the name | 127 | +/// school: `{school, username, password}` in, `{username, role}` back (no |
| 75 | -/// was already taken — see "Auth model". | 128 | +/// `id`; new accounts are `student`). Always `201` — see below. |
| 129 | +/// | ||
| 130 | +/// The account is a **person**: a global username in the control plane that | ||
| 131 | +/// can hold memberships in many schools. Registering a username that is new | ||
| 132 | +/// everywhere creates the person and the school's `app_user` (student). A | ||
| 133 | +/// person who already exists is attached to this school too — but only when | ||
| 134 | +/// the password matches the person credential; a wrong password is the same | ||
| 135 | +/// `201` and joins nothing. | ||
| 76 | /// | 136 | /// |
| 77 | -/// Answers `201` whether or not the username was free: a distinguishable | 137 | +/// Every outcome answers `201` with the *same* body, built once before the |
| 78 | -/// "already taken" reply lets anyone unauthenticated enumerate every account in | 138 | +/// branch: a distinguishable "already taken" reply would let anyone |
| 79 | -/// the school, which would make the constant-cost decoy on the login path | 139 | +/// unauthenticated enumerate accounts, making the login decoy pointless. |
| 80 | -/// pointless. A taken username is *not* re-created or overwritten — only the | 140 | +/// The UX cost (a typo-collision looks like success until the user tries to |
| 81 | -/// reply is uniform. The UX cost (a typo-collision looks like success until the | 141 | +/// log in) is deliberate. The hash comes before any lookup, so every path |
| 82 | -/// user tries to log in) is deliberate. Both outcomes return the *same* | 142 | +/// pays the same argon2 bill first. |
| 83 | -/// [`RegisterResponse`] value, built once before the branch — there is no | ||
| 84 | -/// per-path body that could drift apart. | ||
| 85 | #[utoipa::path( | 143 | #[utoipa::path( |
| 86 | post, | 144 | post, |
| 87 | path = "/register", | 145 | path = "/register", |
| 88 | tag = "auth", | 146 | tag = "auth", |
| 89 | - request_body = Credentials, | 147 | + request_body = RegisterCredentials, |
| 90 | responses( | 148 | responses( |
| 91 | - (status = 201, description = "Account created, or the username was already taken — deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse), | 149 | + (status = 201, description = "Account created, the username was already taken, or an existing person was attached to this school — deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse), |
| 92 | (status = 400, description = "Invalid username or password", body = ErrorResponse), | 150 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 93 | (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), | 151 | (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), |
| 94 | (status = 403, description = "The school is suspended", body = ErrorResponse), | 152 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| @@ -98,7 +156,7 @@ struct RegisterResponse { | |||
| 98 | )] | 156 | )] |
| 99 | async fn register( | 157 | async fn register( |
| 100 | State(st): State<AppState>, | 158 | State(st): State<AppState>, |
| 101 | - Json(req): Json<Credentials>, | 159 | + Json(req): Json<RegisterCredentials>, |
| 102 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { | 160 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { |
| 103 | // The school first: a registration into a school that does not exist, or | 161 | // The school first: a registration into a school that does not exist, or |
| 104 | // one that is suspended, must not reach the (expensive) hashing path — and | 162 | // one that is suspended, must not reach the (expensive) hashing path — and |
| @@ -117,44 +175,59 @@ async fn register( | |||
| 117 | } | 175 | } |
| 118 | .into()); | 176 | .into()); |
| 119 | } | 177 | } |
| 120 | - // Hash BEFORE the availability check inside the user-create path, never | 178 | + // Hash BEFORE any lookup, never after: the ~33ms of argon2 is what makes |
| 121 | - // after: the | 179 | + // every outcome cost the same up front, so taken-vs-free can't be spotted |
| 122 | - // ~33ms of argon2 is what makes both outcomes cost the same, so a taken | 180 | + // by a fast reply. |
| 123 | - // username can't be spotted by a fast reply. The only work the taken path | 181 | + let password = Password::try_new(&req.password)?; |
| 124 | - // skips is the insert itself, orders of magnitude below hashing. | 182 | + let password_hash = password.hash_async().await?; |
| 125 | - let password_hash = Password::try_new(&req.password)?.hash_async().await?; | 183 | + // Built once, before the branch: every path answers with the very same |
| 126 | - // Built once, before the branch: the created and the taken path answer with | 184 | + // value, so they cannot be told apart by construction rather than by |
| 127 | - // the very same value, so they cannot be told apart by construction rather | 185 | + // keeping two field lists in sync. Every fresh account starts as a |
| 128 | - // than by keeping two field lists in sync. Every fresh account starts as a | 186 | + // student, so this holds whichever way the writes go. |
| 129 | - // student (`service::user::create`), so this holds whichever way the insert goes. | ||
| 130 | let body = RegisterResponse { | 187 | let body = RegisterResponse { |
| 131 | username: username.as_str().to_string(), | 188 | username: username.as_str().to_string(), |
| 132 | role: DomainRole::Student.into(), | 189 | role: DomainRole::Student.into(), |
| 133 | }; | 190 | }; |
| 134 | - match crate::service::user::create(&db, username, password_hash).await { | 191 | + |
| 135 | - Ok(_) => {} | 192 | + // Person half (control database): create the global account, or meet the |
| 136 | - // Taken. Log the real reason server-side; the caller gets the same 201 | 193 | + // one already standing. The stored credential is never overwritten here — |
| 137 | - // and the same body, because telling the two apart is the whole thing | 194 | + // the caller has not proven they know it until the verify below. |
| 138 | - // we're denying. The account is not re-created or overwritten. | 195 | + let person = |
| 139 | - Err(AppError::Conflict(_)) => { | 196 | + service::person::create_or_load(&st.db, username.clone(), password_hash.clone()).await?; |
| 140 | - tracing::info!("register: username already taken, answering 201"); | 197 | + if person.get_password_hash().verify_async(&password).await { |
| 198 | + // School half, in the cross-database order `app_user` then | ||
| 199 | + // membership (no distributed transaction spans the two databases, so | ||
| 200 | + // each half is idempotent and a retry after a torn pair completes | ||
| 201 | + // it). A taken school username means the person is already a member | ||
| 202 | + // — the same 201. | ||
| 203 | + match service::user::create(&db, username, password_hash).await { | ||
| 204 | + Ok(_) => {} | ||
| 205 | + Err(AppError::Conflict(_)) => { | ||
| 206 | + tracing::info!("register: school username already taken, answering 201"); | ||
| 207 | + } | ||
| 208 | + Err(err) => return Err(err), | ||
| 141 | } | 209 | } |
| 142 | - Err(err) => return Err(err), | 210 | + service::person::link_school(&st.db, person.get_id(), &school).await?; |
| 211 | + } else { | ||
| 212 | + tracing::info!("register: username taken, password does not match, answering 201"); | ||
| 143 | } | 213 | } |
| 144 | Ok((StatusCode::CREATED, Json(body))) | 214 | Ok((StatusCode::CREATED, Json(body))) |
| 145 | } | 215 | } |
| 146 | 216 | ||
| 147 | -/// Log in with school + username + password. Sets a `session` cookie | 217 | +/// Log in with username + password — no school. Sets a `session` cookie on |
| 148 | -/// (`<school>.<token>`) on success. | 218 | +/// success: exactly one active membership enters that school right away |
| 219 | +/// (`<slug>.<token>` and the full [`UserResponse`], unchanged for | ||
| 220 | +/// single-school clients), several answer a [`SchoolChoiceResponse`] with a | ||
| 221 | +/// `person.<token>` cookie that `POST /auth/school` binds. | ||
| 149 | #[utoipa::path( | 222 | #[utoipa::path( |
| 150 | post, | 223 | post, |
| 151 | path = "/login", | 224 | path = "/login", |
| 152 | tag = "auth", | 225 | tag = "auth", |
| 153 | - request_body = Credentials, | 226 | + request_body = LoginCredentials, |
| 154 | responses( | 227 | responses( |
| 155 | - (status = 200, description = "Logged in; session cookie set", body = UserResponse), | 228 | + (status = 200, description = "Logged in — either straight into the one school (a `UserResponse` and a `<slug>.<token>` cookie), or as a multi-school person (a `{username, schools}` choice list and a `person.<token>` cookie to bind with `POST /auth/school`). Suspended schools appear in neither shape", body = LoginResponse), |
| 156 | - (status = 401, description = "Bad credentials, or no such school — deliberately indistinguishable", body = ErrorResponse), | 229 | + (status = 401, description = "Bad credentials — unknown username, wrong password, or no school membership left to enter, all deliberately indistinguishable", body = ErrorResponse), |
| 157 | - (status = 403, description = "The school is suspended", body = ErrorResponse), | 230 | + (status = 403, description = "Every school the person belongs to is suspended", body = ErrorResponse), |
| 158 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), | 231 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 159 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | 232 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 160 | ), | 233 | ), |
| @@ -162,30 +235,28 @@ async fn register( | |||
| 162 | async fn login( | 235 | async fn login( |
| 163 | State(st): State<AppState>, | 236 | State(st): State<AppState>, |
| 164 | jar: CookieJar, | 237 | jar: CookieJar, |
| 165 | - Json(req): Json<Credentials>, | 238 | + Json(req): Json<LoginCredentials>, |
| 166 | -) -> Result<(CookieJar, Json<UserResponse>), AppError> { | 239 | +) -> Result<(CookieJar, Json<LoginResponse>), AppError> { |
| 167 | - // Resolved *before* the argon2 work: a login aimed at a school that does | 240 | + // A malformed password is a bad credential (`401`, not a `422`): the body |
| 168 | - // not exist is a bad credential (`401`, indistinguishable from a bad | 241 | + // parsed, the credential did not. Same answer an unknown username gets — |
| 169 | - // password — the school list is not public), and a suspended school is | 242 | + // neither may help a caller tell them apart. |
| 170 | - // `403` for every request including this one, so neither should buy an | ||
| 171 | - // attacker a hash. | ||
| 172 | - let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; | ||
| 173 | - let db = st.tenants.get(&school).await?; | ||
| 174 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; | 243 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 175 | - // Usernames are stored trimmed (see `Username::try_new`); trim the lookup | 244 | + // The account is a person in the control database; a school is picked |
| 176 | - // the same way so a padded login attempt matches the canonical name. | 245 | + // after login, not named by it. Usernames are stored trimmed (see |
| 177 | - let user = match crate::service::user::find_by_username(&db, req.username.trim()).await? { | 246 | + // `Username::try_new`); trim the lookup the same way so a padded attempt |
| 247 | + // matches the canonical name. | ||
| 248 | + let person = match service::person::find_by_username(&st.db, req.username.trim()).await? { | ||
| 178 | // Verification is `.await`ed so argon2 runs on the blocking pool instead | 249 | // Verification is `.await`ed so argon2 runs on the blocking pool instead |
| 179 | // of stalling an async worker; that rules out a match guard, which | 250 | // of stalling an async worker; that rules out a match guard, which |
| 180 | // cannot await. | 251 | // cannot await. |
| 181 | - Some(user) => { | 252 | + Some(person) => { |
| 182 | - if !user.get_password_hash().verify_async(&password).await { | 253 | + if !person.get_password_hash().verify_async(&password).await { |
| 183 | return Err(AppError::Unauthorized); | 254 | return Err(AppError::Unauthorized); |
| 184 | } | 255 | } |
| 185 | - user | 256 | + person |
| 186 | } | 257 | } |
| 187 | None => { | 258 | None => { |
| 188 | - // No such user. Still do the argon2 work against a decoy so the reply | 259 | + // No such person. Still do the argon2 work against a decoy so the reply |
| 189 | // takes as long as a real (wrong-password) check — otherwise the | 260 | // takes as long as a real (wrong-password) check — otherwise the |
| 190 | // timing difference leaks which usernames exist. | 261 | // timing difference leaks which usernames exist. |
| 191 | PasswordHash::verify_decoy_async(&password).await; | 262 | PasswordHash::verify_decoy_async(&password).await; |
| @@ -193,17 +264,127 @@ async fn login( | |||
| 193 | } | 264 | } |
| 194 | }; | 265 | }; |
| 195 | 266 | ||
| 196 | - // The caller is genuine; opportunistically drop any expired session rows. | 267 | + let memberships = service::person::memberships(&st.db, person.get_id()).await?; |
| 197 | - let _ = service::session::purge_expired(&db).await; | 268 | + let active: Vec<_> = memberships.iter().filter(|m| m.is_active()).collect(); |
| 269 | + match active.as_slice() { | ||
| 270 | + // A person with no membership cannot enter anything: the same `401` | ||
| 271 | + // a bad credential gets, so a register that created only the person | ||
| 272 | + // half (a torn cross-database pair) is not a signal either. | ||
| 273 | + [] if memberships.is_empty() => Err(AppError::Unauthorized), | ||
| 274 | + // Every membership sits in a suspended school: closed to its users, | ||
| 275 | + // including this one. | ||
| 276 | + [] => Err(AppError::Forbidden("school is suspended")), | ||
| 277 | + [only] => { | ||
| 278 | + let db = st.tenants.get(only.slug()).await?; | ||
| 279 | + // The school-side row the session binds to. A membership without | ||
| 280 | + // its `app_user` (a torn create) refuses like a bad credential | ||
| 281 | + // rather than confirm anything. | ||
| 282 | + let Some(user) = | ||
| 283 | + service::user::find_by_username(&db, person.get_username().as_str()).await? | ||
| 284 | + else { | ||
| 285 | + return Err(AppError::Unauthorized); | ||
| 286 | + }; | ||
| 287 | + // The caller is genuine; opportunistically drop expired session rows. | ||
| 288 | + let _ = service::session::purge_expired(&db).await; | ||
| 289 | + let session = service::session::create(&db, user.get_id()).await?; | ||
| 290 | + // `<slug>.<token>`: the cookie carries the school, so every later | ||
| 291 | + // request finds its database without a second lookup path that | ||
| 292 | + // could disagree. | ||
| 293 | + let cookie = session_cookie( | ||
| 294 | + format!("{}.{}", only.slug(), session.token().as_str()), | ||
| 295 | + st.cookie_secure, | ||
| 296 | + ); | ||
| 297 | + Ok(( | ||
| 298 | + jar.add(cookie), | ||
| 299 | + Json(LoginResponse::LoggedIn(UserResponse::new(&user))), | ||
| 300 | + )) | ||
| 301 | + } | ||
| 302 | + many => { | ||
| 303 | + // Not entering any school yet: the `person.<token>` cookie is the | ||
| 304 | + // not-chosen state, and `POST /auth/school` exchanges it. The | ||
| 305 | + // list carries slug and display name, suspended schools omitted. | ||
| 306 | + let session = service::person::create_session(&st.db, person.get_id()).await?; | ||
| 307 | + let cookie = session_cookie( | ||
| 308 | + format!("{PERSON_COOKIE_PREFIX}.{}", session.token().as_str()), | ||
| 309 | + st.cookie_secure, | ||
| 310 | + ); | ||
| 311 | + let schools = many | ||
| 312 | + .iter() | ||
| 313 | + .map(|m| SchoolChoice { | ||
| 314 | + slug: m.slug().as_str().to_string(), | ||
| 315 | + name: m.name().to_string(), | ||
| 316 | + }) | ||
| 317 | + .collect(); | ||
| 318 | + Ok(( | ||
| 319 | + jar.add(cookie), | ||
| 320 | + Json(LoginResponse::ChooseSchool(SchoolChoiceResponse { | ||
| 321 | + username: person.get_username().as_str().to_string(), | ||
| 322 | + schools, | ||
| 323 | + })), | ||
| 324 | + )) | ||
| 325 | + } | ||
| 326 | + } | ||
| 327 | +} | ||
| 198 | 328 | ||
| 199 | - let session = service::session::create(&db, user.get_id()).await?; | 329 | +/// Bind a `person.<token>` session to one of the person's schools: the |
| 200 | - // `<slug>.<token>`: the cookie carries the school, so every later request | 330 | +/// cookie is replaced with that school's own `<slug>.<token>` and the person |
| 201 | - // finds its database without a second lookup path that could disagree. | 331 | +/// session is revoked. Deliberately outside the credential rate-limit tier — |
| 332 | +/// this is not a credential guess, and it requires a session cookie already. | ||
| 333 | +#[utoipa::path( | ||
| 334 | + post, | ||
| 335 | + path = "/school", | ||
| 336 | + tag = "auth", | ||
| 337 | + request_body = SelectSchool, | ||
| 338 | + responses( | ||
| 339 | + (status = 200, description = "School selected; the person cookie is replaced by the school session cookie", body = UserResponse), | ||
| 340 | + (status = 401, description = "No person session, or the school is not among the caller's memberships — deliberately indistinguishable (no cookie at all, a school or builder cookie, and a slug the person does not hold all answer the same)", body = ErrorResponse), | ||
| 341 | + (status = 403, description = "The school is suspended", body = ErrorResponse), | ||
| 342 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 343 | + ), | ||
| 344 | +)] | ||
| 345 | +async fn select_school( | ||
| 346 | + State(st): State<AppState>, | ||
| 347 | + jar: CookieJar, | ||
| 348 | + Json(req): Json<SelectSchool>, | ||
| 349 | +) -> Result<(CookieJar, Json<UserResponse>), AppError> { | ||
| 350 | + // Only a person cookie binds a school: a school cookie already names its | ||
| 351 | + // school (switching is logout + login again), and a builder cookie names | ||
| 352 | + // no school at all — the same `401` every school surface gives them. | ||
| 353 | + let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) else { | ||
| 354 | + return Err(AppError::Unauthorized); | ||
| 355 | + }; | ||
| 356 | + if prefix != PERSON_COOKIE_PREFIX { | ||
| 357 | + return Err(AppError::Unauthorized); | ||
| 358 | + } | ||
| 359 | + let session = service::person::find_session_by_token(&st.db, token) | ||
| 360 | + .await? | ||
| 361 | + .filter(|s| !s.is_expired()) | ||
| 362 | + .ok_or(AppError::Unauthorized)?; | ||
| 363 | + // Membership required, and a slug that names nothing is the same refusal | ||
| 364 | + // as one the person does not hold — the list login already gave them is | ||
| 365 | + // not a directory of the deployment. | ||
| 366 | + let slug = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; | ||
| 367 | + service::person::membership_of(&st.db, session.person(), &slug) | ||
| 368 | + .await? | ||
| 369 | + .ok_or(AppError::Unauthorized)?; | ||
| 370 | + // Suspended → `403` here, like on every school door. | ||
| 371 | + let db = st.tenants.get(&slug).await?; | ||
| 372 | + let person = service::person::read(&st.db, session.person()) | ||
| 373 | + .await? | ||
| 374 | + .ok_or(AppError::Unauthorized)?; | ||
| 375 | + let Some(user) = service::user::find_by_username(&db, person.get_username().as_str()).await? | ||
| 376 | + else { | ||
| 377 | + return Err(AppError::Unauthorized); | ||
| 378 | + }; | ||
| 379 | + // The school session first, then the person session goes: if the create | ||
| 380 | + // fails the person cookie still works and the same request can be | ||
| 381 | + // retried — a revoked cookie with no school session is a lockout. | ||
| 382 | + let school_session = service::session::create(&db, user.get_id()).await?; | ||
| 383 | + service::person::delete_session_by_token(&st.db, token).await?; | ||
| 202 | let cookie = session_cookie( | 384 | let cookie = session_cookie( |
| 203 | - format!("{school}.{}", session.token().as_str()), | 385 | + format!("{slug}.{}", school_session.token().as_str()), |
| 204 | st.cookie_secure, | 386 | st.cookie_secure, |
| 205 | ); | 387 | ); |
| 206 | - | ||
| 207 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) | 388 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| 208 | } | 389 | } |
| 209 | 390 | ||
| @@ -236,12 +417,14 @@ async fn logout( | |||
| 236 | State(st): State<AppState>, | 417 | State(st): State<AppState>, |
| 237 | jar: CookieJar, | 418 | jar: CookieJar, |
| 238 | ) -> Result<(CookieJar, StatusCode), AppError> { | 419 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 239 | - // Best-effort: the cookie names its own school, so a logout resolves that | 420 | + // Best-effort: the cookie names its own session kind, so a logout |
| 240 | - // school and deletes the row there. A cookie naming a school that is gone | 421 | + // resolves it and deletes the row there. A cookie naming a school that is |
| 241 | - // or suspended still clears below — logging out must never fail. | 422 | + // gone or suspended still clears below — logging out must never fail. |
| 242 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { | 423 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { |
| 243 | if prefix == BUILDER_COOKIE_PREFIX { | 424 | if prefix == BUILDER_COOKIE_PREFIX { |
| 244 | crate::service::builder::delete_by_token(&st.db, token).await?; | 425 | crate::service::builder::delete_by_token(&st.db, token).await?; |
| 426 | + } else if prefix == PERSON_COOKIE_PREFIX { | ||
| 427 | + service::person::delete_session_by_token(&st.db, token).await?; | ||
| 245 | } else if let Ok(slug) = Slug::try_new(prefix) | 428 | } else if let Ok(slug) = Slug::try_new(prefix) |
| 246 | && let Ok(db) = st.tenants.get(&slug).await | 429 | && let Ok(db) = st.tenants.get(&slug).await |
| 247 | { | 430 | { |
src/web/builder.rsmodified+36 -9
| @@ -331,7 +331,7 @@ async fn builder_me(RequireBuilder(builder): RequireBuilder) -> Json<BuilderResp | |||
| 331 | (status = 201, description = "School created, with its first admin", body = SchoolResponse), | 331 | (status = 201, description = "School created, with its first admin", body = SchoolResponse), |
| 332 | (status = 400, description = "Invalid slug, name, admin credentials, or module name", body = ErrorResponse, example = json!({"error": "module: `kantin` is not a known module"})), | 332 | (status = 400, description = "Invalid slug, name, admin credentials, or module name", body = ErrorResponse, example = json!({"error": "module: `kantin` is not a known module"})), |
| 333 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), | 333 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 334 | - (status = 409, description = "That slug is already taken, or the module set is unsatisfiable", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})), | 334 | + (status = 409, description = "That slug is already taken, the module set is unsatisfiable, or the admin username exists under a different password", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})), |
| 335 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | 335 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 336 | ), | 336 | ), |
| 337 | )] | 337 | )] |
| @@ -346,7 +346,8 @@ async fn create_school( | |||
| 346 | let slug = Slug::try_new(&req.slug)?; | 346 | let slug = Slug::try_new(&req.slug)?; |
| 347 | let name = school_name(&req.name)?; | 347 | let name = school_name(&req.name)?; |
| 348 | let username = Username::try_new(&req.admin_username)?; | 348 | let username = Username::try_new(&req.admin_username)?; |
| 349 | - let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?; | 349 | + let password = Password::try_new(&req.admin_password)?; |
| 350 | + let password_hash = password.hash_async().await?; | ||
| 350 | 351 | ||
| 351 | let modules = match req.modules.as_deref() { | 352 | let modules = match req.modules.as_deref() { |
| 352 | Some(names) => ModuleSet::from_names(names)?, | 353 | Some(names) => ModuleSet::from_names(names)?, |
| @@ -355,11 +356,29 @@ async fn create_school( | |||
| 355 | // Before `create`, so an unsatisfiable set is a refusal and not a school | 356 | // Before `create`, so an unsatisfiable set is a refusal and not a school |
| 356 | // that has to be deleted again. | 357 | // that has to be deleted again. |
| 357 | modules.validate()?; | 358 | modules.validate()?; |
| 359 | + // The school's first admin is also a *person*: create the control-plane | ||
| 360 | + // account, or meet the one already standing. A taken username under a | ||
| 361 | + // different password is a `409` — a builder is authenticated, so there | ||
| 362 | + // is nothing to enumerate — and it refuses here, before anything is | ||
| 363 | + // provisioned, so there is nothing to clean up either. | ||
| 364 | + let person = | ||
| 365 | + service::person::create_or_load(&st.db, username.clone(), password_hash.clone()).await?; | ||
| 366 | + if !person.get_password_hash().verify_async(&password).await { | ||
| 367 | + return Err(AppError::Conflict( | ||
| 368 | + "an account with that username exists under a different password", | ||
| 369 | + )); | ||
| 370 | + } | ||
| 358 | 371 | ||
| 359 | let db = st.tenants.create(&slug, &name, modules).await?; | 372 | let db = st.tenants.create(&slug, &name, modules).await?; |
| 360 | - if let Err(err) = | 373 | + let seeded = async { |
| 361 | - crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await | 374 | + crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await?; |
| 362 | - { | 375 | + // The admin's person gets the membership the school row answers for — |
| 376 | + // idempotent, so a retried create after a torn pair completes it. | ||
| 377 | + service::person::link_school(&st.db, person.get_id(), &slug).await?; | ||
| 378 | + Ok::<(), AppError>(()) | ||
| 379 | + } | ||
| 380 | + .await; | ||
| 381 | + if let Err(err) = seeded { | ||
| 363 | // A school nobody can log into is worse than no school: take the | 382 | // A school nobody can log into is worse than no school: take the |
| 364 | // database back so the very same request can simply be retried. | 383 | // database back so the very same request can simply be retried. |
| 365 | if let Err(cleanup) = st.tenants.drop(&slug).await { | 384 | if let Err(cleanup) = st.tenants.drop(&slug).await { |
| @@ -751,18 +770,26 @@ async fn reset_admin_password( | |||
| 751 | Json(req): Json<AdminPassword>, | 770 | Json(req): Json<AdminPassword>, |
| 752 | ) -> Result<StatusCode, AppError> { | 771 | ) -> Result<StatusCode, AppError> { |
| 753 | let slug = path_slug(&slug)?; | 772 | let slug = path_slug(&slug)?; |
| 754 | - // `get_any_status`, not `get`: a lockout is exactly the situation a school | ||
| 755 | - // may be suspended in, and the vendor must still be able to fix it. | ||
| 756 | let (db, _status) = st.tenants.get_any_status(&slug).await?; | 773 | let (db, _status) = st.tenants.get_any_status(&slug).await?; |
| 757 | let user = school_admin(&req.username, &db).await?; | 774 | let user = school_admin(&req.username, &db).await?; |
| 758 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; | 775 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 759 | 776 | ||
| 760 | - crate::service::user::set_password_hash(&db, user.get_id(), password_hash) | 777 | + crate::service::user::set_password_hash(&db, user.get_id(), password_hash.clone()) |
| 761 | .await? | 778 | .await? |
| 762 | .ok_or(AppError::NotFound)?; | 779 | .ok_or(AppError::NotFound)?; |
| 780 | + // The person credential is the one login reads; the school row's copy | ||
| 781 | + // exists so school-side queries keep compiling. Both move together, or a | ||
| 782 | + // reset would leave the old password working everywhere. | ||
| 783 | + service::person::set_password_hash(&st.db, user.get_username(), &password_hash).await?; | ||
| 763 | // The other half: the new password means nothing while a cookie minted | 784 | // The other half: the new password means nothing while a cookie minted |
| 764 | - // under the old one still authenticates. | 785 | + // under the old one still authenticates — school sessions *and* any |
| 786 | + // unbound `person.<token>` that could mint a fresh school session. | ||
| 765 | service::session::delete_by_user(&db, user.get_id()).await?; | 787 | service::session::delete_by_user(&db, user.get_id()).await?; |
| 788 | + if let Some(person) = | ||
| 789 | + service::person::find_by_username(&st.db, user.get_username().as_str()).await? | ||
| 790 | + { | ||
| 791 | + service::person::delete_sessions_by_person(&st.db, person.get_id()).await?; | ||
| 792 | + } | ||
| 766 | Ok(StatusCode::NO_CONTENT) | 793 | Ok(StatusCode::NO_CONTENT) |
| 767 | } | 794 | } |
| 768 | 795 | ||
src/web/extractor.rsmodified+8 -0
| @@ -192,3 +192,11 @@ where | |||
| 192 | /// The cookie prefix a builder session carries in place of a school slug. | 192 | /// The cookie prefix a builder session carries in place of a school slug. |
| 193 | /// `Slug::try_new` reserves this word, so it can never also name a school. | 193 | /// `Slug::try_new` reserves this word, so it can never also name a school. |
| 194 | pub const BUILDER_COOKIE_PREFIX: &str = "builder"; | 194 | pub const BUILDER_COOKIE_PREFIX: &str = "builder"; |
| 195 | + | ||
| 196 | +/// The cookie prefix a not-yet-bound person session carries in place of a | ||
| 197 | +/// school slug: a person who belongs to several schools logs into the | ||
| 198 | +/// control plane first and names a school afterwards (`POST /auth/school`). | ||
| 199 | +/// `Slug::try_new` reserves this word (`RESERVED_SLUGS`), so it can never | ||
| 200 | +/// also name a school — a `person.` cookie is `401` on every school surface, | ||
| 201 | +/// exactly like `builder.`. | ||
| 202 | +pub const PERSON_COOKIE_PREFIX: &str = "person"; | ||
src/web/mod.rsmodified+2 -2
| @@ -52,8 +52,8 @@ pub use dto::{ | |||
| 52 | UserResponse, course_people, person_map, | 52 | UserResponse, course_people, person_map, |
| 53 | }; | 53 | }; |
| 54 | pub use extractor::{ | 54 | pub use extractor::{ |
| 55 | - BUILDER_COOKIE_PREFIX, CurrentUser, RequireAdmin, RequireBuilder, RequireManager, | 55 | + BUILDER_COOKIE_PREFIX, CurrentUser, PERSON_COOKIE_PREFIX, RequireAdmin, RequireBuilder, |
| 56 | - RequireStudent, RequireTeacher, | 56 | + RequireManager, RequireStudent, RequireTeacher, |
| 57 | }; | 57 | }; |
| 58 | pub(crate) use image::{ImageUpload, read_image_upload, store_blob}; | 58 | pub(crate) use image::{ImageUpload, read_image_upload, store_blob}; |
| 59 | pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; | 59 | pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; |
tests/auth_enumeration.rsmodified+18 -4
| @@ -14,7 +14,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { | |||
| 14 | let (app, db) = app_and_db().await; | 14 | let (app, db) = app_and_db().await; |
| 15 | let taken = json!({ "school": "demo", "username": "ada", "password": "secret1" }); | 15 | let taken = json!({ "school": "demo", "username": "ada", "password": "secret1" }); |
| 16 | 16 | ||
| 17 | - let first = send(&app, "POST", "/auth/register", None, Some(taken.clone())).await; | 17 | + let first = send(&app, "POST", "/auth/register", None, Some(taken)).await; |
| 18 | assert_eq!(first.status, StatusCode::CREATED); | 18 | assert_eq!(first.status, StatusCode::CREATED); |
| 19 | 19 | ||
| 20 | // Same username again, different password: still 201, same body shape. | 20 | // Same username again, different password: still 201, same body shape. |
| @@ -25,7 +25,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { | |||
| 25 | "POST", | 25 | "POST", |
| 26 | "/auth/register", | 26 | "/auth/register", |
| 27 | None, | 27 | None, |
| 28 | - Some(dup_creds.clone()), | 28 | + Some(dup_creds), |
| 29 | ) | 29 | ) |
| 30 | .await; | 30 | .await; |
| 31 | let dup_elapsed = started.elapsed(); | 31 | let dup_elapsed = started.elapsed(); |
| @@ -79,13 +79,27 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { | |||
| 79 | 79 | ||
| 80 | // The original account is untouched: its password still works and the | 80 | // The original account is untouched: its password still works and the |
| 81 | // attacker's does not. | 81 | // attacker's does not. |
| 82 | - let login = send(&app, "POST", "/auth/login", None, Some(taken)).await; | 82 | + let login = send( |
| 83 | + &app, | ||
| 84 | + "POST", | ||
| 85 | + "/auth/login", | ||
| 86 | + None, | ||
| 87 | + Some(json!({ "username": "ada", "password": "secret1" })), | ||
| 88 | + ) | ||
| 89 | + .await; | ||
| 83 | assert_eq!( | 90 | assert_eq!( |
| 84 | login.status, | 91 | login.status, |
| 85 | StatusCode::OK, | 92 | StatusCode::OK, |
| 86 | "original password stopped working" | 93 | "original password stopped working" |
| 87 | ); | 94 | ); |
| 88 | - let hijack = send(&app, "POST", "/auth/login", None, Some(dup_creds)).await; | 95 | + let hijack = send( |
| 96 | + &app, | ||
| 97 | + "POST", | ||
| 98 | + "/auth/login", | ||
| 99 | + None, | ||
| 100 | + Some(json!({ "username": "ada", "password": "attacker" })), | ||
| 101 | + ) | ||
| 102 | + .await; | ||
| 89 | assert_eq!( | 103 | assert_eq!( |
| 90 | hijack.status, | 104 | hijack.status, |
| 91 | StatusCode::UNAUTHORIZED, | 105 | StatusCode::UNAUTHORIZED, |
tests/builder_api.rsmodified+106 -24
| @@ -60,15 +60,38 @@ async fn create_school(app: &Router, cookie: &str, slug: &str, admin_pass: &str) | |||
| 60 | .await | 60 | .await |
| 61 | } | 61 | } |
| 62 | 62 | ||
| 63 | +/// Log `username` into the school named `slug`. The login itself names no | ||
| 64 | +/// school any more — the admin fixtures reuse one username across many | ||
| 65 | +/// schools, which makes that admin one *person* with several memberships — | ||
| 66 | +/// so when login answers a choice list, bind the requested school before | ||
| 67 | +/// returning. The result is whatever a plain school login would have said. | ||
| 63 | async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res { | 68 | async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res { |
| 64 | - send( | 69 | + let res = send( |
| 65 | app, | 70 | app, |
| 66 | "POST", | 71 | "POST", |
| 67 | "/auth/login", | 72 | "/auth/login", |
| 68 | None, | 73 | None, |
| 69 | - Some(json!({ "school": slug, "username": username, "password": password })), | 74 | + Some(json!({ "username": username, "password": password })), |
| 70 | ) | 75 | ) |
| 71 | - .await | 76 | + .await; |
| 77 | + if res.body["schools"].is_array() { | ||
| 78 | + assert_eq!(res.status, StatusCode::OK, "choice login {username}"); | ||
| 79 | + let selected = send( | ||
| 80 | + app, | ||
| 81 | + "POST", | ||
| 82 | + "/auth/school", | ||
| 83 | + res.cookie.as_deref(), | ||
| 84 | + Some(json!({ "school": slug })), | ||
| 85 | + ) | ||
| 86 | + .await; | ||
| 87 | + assert_eq!( | ||
| 88 | + selected.status, | ||
| 89 | + StatusCode::OK, | ||
| 90 | + "select {slug} for {username}" | ||
| 91 | + ); | ||
| 92 | + return selected; | ||
| 93 | + } | ||
| 94 | + res | ||
| 72 | } | 95 | } |
| 73 | 96 | ||
| 74 | fn slugs(body: &Value) -> Vec<String> { | 97 | fn slugs(body: &Value) -> Vec<String> { |
| @@ -215,10 +238,14 @@ async fn creating_a_school_seeds_an_admin_who_can_log_in() { | |||
| 215 | StatusCode::BAD_REQUEST | 238 | StatusCode::BAD_REQUEST |
| 216 | ); | 239 | ); |
| 217 | } | 240 | } |
| 218 | - assert_eq!( | 241 | + // A refused create must not have made a school: the admin's login has |
| 219 | - school_login(&app, "yeni", "admin", "secret1").await.status, | 242 | + // only the one school they actually have to enter — `yeni` names nothing. |
| 220 | - StatusCode::UNAUTHORIZED, | 243 | + let refused_create = school_login(&app, "yeni", "admin", "secret1").await; |
| 221 | - "a refused create must not have made a school" | 244 | + assert_eq!(refused_create.status, StatusCode::OK); |
| 245 | + let cookie = refused_create.cookie.expect("cookie"); | ||
| 246 | + assert!( | ||
| 247 | + cookie.starts_with("session=ata-koleji."), | ||
| 248 | + "a refused create must not have made a school: {cookie:?}" | ||
| 222 | ); | 249 | ); |
| 223 | } | 250 | } |
| 224 | 251 | ||
| @@ -364,10 +391,21 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | |||
| 364 | let (app, _db, _tenants) = deployment().await; | 391 | let (app, _db, _tenants) = deployment().await; |
| 365 | let builder = builder_login(&app).await; | 392 | let builder = builder_login(&app).await; |
| 366 | create_school(&app, &builder, "gamma", "secret1").await; | 393 | create_school(&app, &builder, "gamma", "secret1").await; |
| 394 | + create_school(&app, &builder, "delta", "secret1").await; | ||
| 367 | let old_cookie = school_login(&app, "gamma", "admin", "secret1") | 395 | let old_cookie = school_login(&app, "gamma", "admin", "secret1") |
| 368 | .await | 396 | .await |
| 369 | .cookie | 397 | .cookie |
| 370 | .expect("school cookie"); | 398 | .expect("school cookie"); |
| 399 | + let person_cookie = send( | ||
| 400 | + &app, | ||
| 401 | + "POST", | ||
| 402 | + "/auth/login", | ||
| 403 | + None, | ||
| 404 | + Some(json!({ "username": "admin", "password": "secret1" })), | ||
| 405 | + ) | ||
| 406 | + .await | ||
| 407 | + .cookie | ||
| 408 | + .expect("person cookie from a two-school login"); | ||
| 371 | 409 | ||
| 372 | // An account that is not an admin of that school, and one that is not there | 410 | // An account that is not an admin of that school, and one that is not there |
| 373 | // at all, are told apart. | 411 | // at all, are told apart. |
| @@ -438,6 +476,19 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | |||
| 438 | StatusCode::UNAUTHORIZED, | 476 | StatusCode::UNAUTHORIZED, |
| 439 | "a reset that leaves the old cookie working resets nothing" | 477 | "a reset that leaves the old cookie working resets nothing" |
| 440 | ); | 478 | ); |
| 479 | + assert_eq!( | ||
| 480 | + send( | ||
| 481 | + &app, | ||
| 482 | + "POST", | ||
| 483 | + "/auth/school", | ||
| 484 | + Some(&person_cookie), | ||
| 485 | + Some(json!({ "school": "gamma" })), | ||
| 486 | + ) | ||
| 487 | + .await | ||
| 488 | + .status, | ||
| 489 | + StatusCode::UNAUTHORIZED, | ||
| 490 | + "a person cookie minted under the old password must die too" | ||
| 491 | + ); | ||
| 441 | } | 492 | } |
| 442 | 493 | ||
| 443 | /// `enter` mints an ordinary school session: full admin power inside that | 494 | /// `enter` mints an ordinary school session: full admin power inside that |
| @@ -581,10 +632,13 @@ async fn deleting_a_school_takes_its_data_and_its_files() { | |||
| 581 | .status, | 632 | .status, |
| 582 | StatusCode::NOT_FOUND | 633 | StatusCode::NOT_FOUND |
| 583 | ); | 634 | ); |
| 584 | - assert_eq!( | 635 | + // A deleted school is not a door any more. The person's login has only |
| 585 | - school_login(&app, "delta", "admin", "secret1").await.status, | 636 | + // `epsilon` left to enter — the dropped slug is neither offered nor 403'd. |
| 586 | - StatusCode::UNAUTHORIZED, | 637 | + let after_delete = school_login(&app, "delta", "admin", "secret1").await; |
| 587 | - "a deleted school is an unknown school, never a 403" | 638 | + assert_eq!(after_delete.status, StatusCode::OK); |
| 639 | + assert!( | ||
| 640 | + after_delete.cookie.expect("cookie").contains("epsilon."), | ||
| 641 | + "the deleted school must not be reachable at login" | ||
| 588 | ); | 642 | ); |
| 589 | assert!( | 643 | assert!( |
| 590 | !files_dir().join("delta").exists(), | 644 | !files_dir().join("delta").exists(), |
| @@ -775,20 +829,22 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | |||
| 775 | send(&app, "GET", "/auth/me", Some(&a), None).await.status, | 829 | send(&app, "GET", "/auth/me", Some(&a), None).await.status, |
| 776 | StatusCode::UNAUTHORIZED | 830 | StatusCode::UNAUTHORIZED |
| 777 | ); | 831 | ); |
| 778 | - assert_eq!( | 832 | + // The person behind `admin` still belongs to p2b: the login has that |
| 779 | - school_login(&app, "p2a", "admin", "secret1").await.status, | 833 | + // school left to enter, and the dropped slug is not among the choices. |
| 780 | - StatusCode::UNAUTHORIZED | 834 | + let after_drop = school_login(&app, "p2a", "admin", "secret1").await; |
| 835 | + assert_eq!(after_drop.status, StatusCode::OK); | ||
| 836 | + assert!( | ||
| 837 | + after_drop.cookie.expect("cookie").contains("p2b."), | ||
| 838 | + "the dropped school must not come back at login" | ||
| 781 | ); | 839 | ); |
| 782 | 840 | ||
| 783 | - // Re-created with the same slug: nothing of the old school comes back. | 841 | + // Re-created with the same slug. `admin` is one *person*: the same |
| 784 | - let again = create_school(&app, &builder, "p2a", "secret2").await; | 842 | + // username under the same password links that person into the new |
| 843 | + // school, and under a *different* password the create itself refuses | ||
| 844 | + // with a 409 — a builder is authenticated, there is nothing to enumerate. | ||
| 845 | + let again = create_school(&app, &builder, "p2a", "secret1").await; | ||
| 785 | assert_eq!(again.status, StatusCode::CREATED, "{:?}", again.body); | 846 | assert_eq!(again.status, StatusCode::CREATED, "{:?}", again.body); |
| 786 | - assert_eq!( | 847 | + let fresh = school_login(&app, "p2a", "admin", "secret1") |
| 787 | - school_login(&app, "p2a", "admin", "secret1").await.status, | ||
| 788 | - StatusCode::UNAUTHORIZED, | ||
| 789 | - "the OLD admin credential still opens the re-created school" | ||
| 790 | - ); | ||
| 791 | - let fresh = school_login(&app, "p2a", "admin", "secret2") | ||
| 792 | .await | 848 | .await |
| 793 | .cookie | 849 | .cookie |
| 794 | .expect("fresh admin cookie"); | 850 | .expect("fresh admin cookie"); |
| @@ -803,6 +859,23 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | |||
| 803 | let notes = send(&app, "GET", "/notes", Some(&fresh), None).await; | 859 | let notes = send(&app, "GET", "/notes", Some(&fresh), None).await; |
| 804 | assert_eq!(notes.status, StatusCode::OK); | 860 | assert_eq!(notes.status, StatusCode::OK); |
| 805 | assert_eq!(total(¬es.body), 0, "old rows survived the drop"); | 861 | assert_eq!(total(¬es.body), 0, "old rows survived the drop"); |
| 862 | + | ||
| 863 | + // A *different* password for an existing person is a plain 409, and no | ||
| 864 | + // school is left behind by the refusal. | ||
| 865 | + let mismatched = create_school(&app, &builder, "p2c", "secret9").await; | ||
| 866 | + assert_eq!( | ||
| 867 | + mismatched.status, | ||
| 868 | + StatusCode::CONFLICT, | ||
| 869 | + "{:?}", | ||
| 870 | + mismatched.body | ||
| 871 | + ); | ||
| 872 | + assert_eq!( | ||
| 873 | + send(&app, "GET", "/schools/p2c", Some(&builder), None) | ||
| 874 | + .await | ||
| 875 | + .status, | ||
| 876 | + StatusCode::NOT_FOUND, | ||
| 877 | + "a refused create must not leave a school behind" | ||
| 878 | + ); | ||
| 806 | } | 879 | } |
| 807 | 880 | ||
| 808 | /// Claim 2, the school lifecycle: `Tenants::create`/`drop` interpolate the slug | 881 | /// Claim 2, the school lifecycle: `Tenants::create`/`drop` interpolate the slug |
| @@ -1290,10 +1363,19 @@ async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { | |||
| 1290 | ); | 1363 | ); |
| 1291 | assert_eq!(deleted.status, StatusCode::NO_CONTENT); | 1364 | assert_eq!(deleted.status, StatusCode::NO_CONTENT); |
| 1292 | assert!(!listed(&after_delete.body)); | 1365 | assert!(!listed(&after_delete.body)); |
| 1366 | + // The person still has `atakoleji` to enter; the deleted slug is neither | ||
| 1367 | + // offered nor 403'd — it is simply not a door. | ||
| 1293 | assert_eq!( | 1368 | assert_eq!( |
| 1294 | login_after_delete.status, | 1369 | login_after_delete.status, |
| 1295 | - StatusCode::UNAUTHORIZED, | 1370 | + StatusCode::OK, |
| 1296 | - "a deleted school is unknown at login" | 1371 | + "the person keeps their other membership" |
| 1372 | + ); | ||
| 1373 | + assert!( | ||
| 1374 | + login_after_delete | ||
| 1375 | + .cookie | ||
| 1376 | + .expect("cookie") | ||
| 1377 | + .contains("atakoleji."), | ||
| 1378 | + "the deleted school must not come back at login" | ||
| 1297 | ); | 1379 | ); |
| 1298 | } | 1380 | } |
| 1299 | 1381 | ||
tests/common/mod.rsmodified+55 -7
| @@ -211,13 +211,48 @@ pub async fn login_as_school( | |||
| 211 | username: &str, | 211 | username: &str, |
| 212 | role: &str, | 212 | role: &str, |
| 213 | ) -> String { | 213 | ) -> String { |
| 214 | - let creds = json!({ "school": school, "username": username, "password": "secret1" }); | 214 | + let reg = send( |
| 215 | - let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; | 215 | + app, |
| 216 | + "POST", | ||
| 217 | + "/auth/register", | ||
| 218 | + None, | ||
| 219 | + Some(json!({ "school": school, "username": username, "password": "secret1" })), | ||
| 220 | + ) | ||
| 221 | + .await; | ||
| 216 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); | 222 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| 217 | set_role(db, username, role).await; | 223 | set_role(db, username, role).await; |
| 218 | - let res = send(app, "POST", "/auth/login", None, Some(creds)).await; | 224 | + let res = send( |
| 225 | + app, | ||
| 226 | + "POST", | ||
| 227 | + "/auth/login", | ||
| 228 | + None, | ||
| 229 | + Some(json!({ "username": username, "password": "secret1" })), | ||
| 230 | + ) | ||
| 231 | + .await; | ||
| 219 | assert_eq!(res.status, StatusCode::OK, "login {username}"); | 232 | assert_eq!(res.status, StatusCode::OK, "login {username}"); |
| 220 | - res.cookie.expect("session cookie set on login") | 233 | + // The account is a person: if `username` already belongs to another |
| 234 | + // school, login answers a choice list and never names a school — bind | ||
| 235 | + // the school this helper was called for. | ||
| 236 | + let cookie = if res.body["schools"].is_array() { | ||
| 237 | + let selected = send( | ||
| 238 | + app, | ||
| 239 | + "POST", | ||
| 240 | + "/auth/school", | ||
| 241 | + res.cookie.as_deref(), | ||
| 242 | + Some(json!({ "school": school })), | ||
| 243 | + ) | ||
| 244 | + .await; | ||
| 245 | + assert_eq!( | ||
| 246 | + selected.status, | ||
| 247 | + StatusCode::OK, | ||
| 248 | + "select {school} for {username}: {}", | ||
| 249 | + selected.body | ||
| 250 | + ); | ||
| 251 | + selected.cookie.expect("school cookie after selection") | ||
| 252 | + } else { | ||
| 253 | + res.cookie.expect("session cookie set on login") | ||
| 254 | + }; | ||
| 255 | + cookie | ||
| 221 | } | 256 | } |
| 222 | 257 | ||
| 223 | /// Send one request through `app`. `cookie` is a raw `Cookie` header value. | 258 | /// Send one request through `app`. `cookie` is a raw `Cookie` header value. |
| @@ -385,10 +420,23 @@ pub async fn upload_course_note_file( | |||
| 385 | 420 | ||
| 386 | /// Register (password `secret1`) then log in; returns the session `Cookie` value. | 421 | /// Register (password `secret1`) then log in; returns the session `Cookie` value. |
| 387 | pub async fn login(app: &Router, username: &str) -> String { | 422 | pub async fn login(app: &Router, username: &str) -> String { |
| 388 | - let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" }); | 423 | + let reg = send( |
| 389 | - let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; | 424 | + app, |
| 425 | + "POST", | ||
| 426 | + "/auth/register", | ||
| 427 | + None, | ||
| 428 | + Some(json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" })), | ||
| 429 | + ) | ||
| 430 | + .await; | ||
| 390 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); | 431 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| 391 | - let res = send(app, "POST", "/auth/login", None, Some(creds)).await; | 432 | + let res = send( |
| 433 | + app, | ||
| 434 | + "POST", | ||
| 435 | + "/auth/login", | ||
| 436 | + None, | ||
| 437 | + Some(json!({ "username": username, "password": "secret1" })), | ||
| 438 | + ) | ||
| 439 | + .await; | ||
| 392 | assert_eq!(res.status, StatusCode::OK, "login {username}"); | 440 | assert_eq!(res.status, StatusCode::OK, "login {username}"); |
| 393 | res.cookie.expect("session cookie set on login") | 441 | res.cookie.expect("session cookie set on login") |
| 394 | } | 442 | } |
tests/e2e.rsmodified+3 -3
| @@ -94,7 +94,7 @@ async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response | |||
| 94 | async fn login(client: &Client, base: &str, user: &str) { | 94 | async fn login(client: &Client, base: &str, user: &str) { |
| 95 | let res = client | 95 | let res = client |
| 96 | .post(format!("{base}/auth/login")) | 96 | .post(format!("{base}/auth/login")) |
| 97 | - .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) | 97 | + .json(&json!({ "username": user, "password": "secret1" })) |
| 98 | .send() | 98 | .send() |
| 99 | .await | 99 | .await |
| 100 | .unwrap(); | 100 | .unwrap(); |
| @@ -440,7 +440,7 @@ async fn attendance_rollup_across_users() { | |||
| 440 | async fn raw_session_cookie(base: &str, user: &str) -> String { | 440 | async fn raw_session_cookie(base: &str, user: &str) -> String { |
| 441 | let res = Client::new() | 441 | let res = Client::new() |
| 442 | .post(format!("{base}/auth/login")) | 442 | .post(format!("{base}/auth/login")) |
| 443 | - .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) | 443 | + .json(&json!({ "username": user, "password": "secret1" })) |
| 444 | .send() | 444 | .send() |
| 445 | .await | 445 | .await |
| 446 | .unwrap(); | 446 | .unwrap(); |
| @@ -3709,7 +3709,7 @@ async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() { | |||
| 3709 | let admin = client(); | 3709 | let admin = client(); |
| 3710 | let res = admin | 3710 | let res = admin |
| 3711 | .post(format!("{base}/auth/login")) | 3711 | .post(format!("{base}/auth/login")) |
| 3712 | - .json(&json!({ "school": "tcp-koleji", "username": "admin", "password": "secret1" })) | 3712 | + .json(&json!({ "username": "admin", "password": "secret1" })) |
| 3713 | .send() | 3713 | .send() |
| 3714 | .await | 3714 | .await |
| 3715 | .unwrap(); | 3715 | .unwrap(); |
tests/integration.rsmodified+341 -76
| @@ -274,7 +274,7 @@ async fn register_validates_input() { | |||
| 274 | 274 | ||
| 275 | // Valid -> 201, no password echoed back, defaults to the student role. | 275 | // Valid -> 201, no password echoed back, defaults to the student role. |
| 276 | let ok = json!({ "school": "demo", "username": "bob", "password": "secret1" }); | 276 | let ok = json!({ "school": "demo", "username": "bob", "password": "secret1" }); |
| 277 | - let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await; | 277 | + let res = send(&app, "POST", "/auth/register", None, Some(ok)).await; |
| 278 | assert_eq!(res.status, StatusCode::CREATED); | 278 | assert_eq!(res.status, StatusCode::CREATED); |
| 279 | assert_eq!(res.body["username"], "bob"); | 279 | assert_eq!(res.body["username"], "bob"); |
| 280 | assert_eq!(res.body["role"], "student"); | 280 | assert_eq!(res.body["role"], "student"); |
| @@ -285,15 +285,29 @@ async fn register_validates_input() { | |||
| 285 | // write is still rejected: the original password keeps working and the | 285 | // write is still rejected: the original password keeps working and the |
| 286 | // second one never becomes valid. | 286 | // second one never becomes valid. |
| 287 | let dup = json!({ "school": "demo", "username": "bob", "password": "hijack1" }); | 287 | let dup = json!({ "school": "demo", "username": "bob", "password": "hijack1" }); |
| 288 | - let res = send(&app, "POST", "/auth/register", None, Some(dup.clone())).await; | 288 | + let res = send(&app, "POST", "/auth/register", None, Some(dup)).await; |
| 289 | assert_eq!(res.status, StatusCode::CREATED); | 289 | assert_eq!(res.status, StatusCode::CREATED); |
| 290 | - let res = send(&app, "POST", "/auth/login", None, Some(ok)).await; | 290 | + let res = send( |
| 291 | + &app, | ||
| 292 | + "POST", | ||
| 293 | + "/auth/login", | ||
| 294 | + None, | ||
| 295 | + Some(json!({ "username": "bob", "password": "secret1" })), | ||
| 296 | + ) | ||
| 297 | + .await; | ||
| 291 | assert_eq!( | 298 | assert_eq!( |
| 292 | res.status, | 299 | res.status, |
| 293 | StatusCode::OK, | 300 | StatusCode::OK, |
| 294 | "original password stopped working" | 301 | "original password stopped working" |
| 295 | ); | 302 | ); |
| 296 | - let res = send(&app, "POST", "/auth/login", None, Some(dup)).await; | 303 | + let res = send( |
| 304 | + &app, | ||
| 305 | + "POST", | ||
| 306 | + "/auth/login", | ||
| 307 | + None, | ||
| 308 | + Some(json!({ "username": "bob", "password": "hijack1" })), | ||
| 309 | + ) | ||
| 310 | + .await; | ||
| 297 | assert_eq!( | 311 | assert_eq!( |
| 298 | res.status, | 312 | res.status, |
| 299 | StatusCode::UNAUTHORIZED, | 313 | StatusCode::UNAUTHORIZED, |
| @@ -329,7 +343,7 @@ async fn register_rejects_reserved_usernames() { | |||
| 329 | // (created through `ensure_admin`, not `/auth/register`) still logs in. | 343 | // (created through `ensure_admin`, not `/auth/register`) still logs in. |
| 330 | // Covered by the admin bootstrap tests; here just prove a reserved name | 344 | // Covered by the admin bootstrap tests; here just prove a reserved name |
| 331 | // is not permanently poisoned for login by the register-level check. | 345 | // is not permanently poisoned for login by the register-level check. |
| 332 | - let creds = json!({ "school": "demo", "username": "admin", "password": "wrong" }); | 346 | + let creds = json!({ "username": "admin", "password": "wrong" }); |
| 333 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 347 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 334 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved" | 348 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved" |
| 335 | } | 349 | } |
| @@ -352,7 +366,7 @@ async fn login_rejects_bad_credentials() { | |||
| 352 | "POST", | 366 | "POST", |
| 353 | "/auth/login", | 367 | "/auth/login", |
| 354 | None, | 368 | None, |
| 355 | - Some(json!({ "school": "demo", "username": "kate", "password": "wrong" })), | 369 | + Some(json!({ "username": "kate", "password": "wrong" })), |
| 356 | ) | 370 | ) |
| 357 | .await; | 371 | .await; |
| 358 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); | 372 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| @@ -363,7 +377,7 @@ async fn login_rejects_bad_credentials() { | |||
| 363 | "POST", | 377 | "POST", |
| 364 | "/auth/login", | 378 | "/auth/login", |
| 365 | None, | 379 | None, |
| 366 | - Some(json!({ "school": "demo", "username": "ghost", "password": "secret1" })), | 380 | + Some(json!({ "username": "ghost", "password": "secret1" })), |
| 367 | ) | 381 | ) |
| 368 | .await; | 382 | .await; |
| 369 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); | 383 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| @@ -383,6 +397,9 @@ const PUBLIC: &[(&str, &str)] = &[ | |||
| 383 | ("GET", "/modules/catalog"), | 397 | ("GET", "/modules/catalog"), |
| 384 | ("POST", "/auth/register"), | 398 | ("POST", "/auth/register"), |
| 385 | ("POST", "/auth/login"), | 399 | ("POST", "/auth/login"), |
| 400 | + // Person-cookie gated, not a school session: OpenAPI declares no | ||
| 401 | + // session_cookie security, so the public-route audit lists it here. | ||
| 402 | + ("POST", "/auth/school"), | ||
| 386 | // Idempotent: revokes the session if there is one, `204` either way. | 403 | // Idempotent: revokes the session if there is one, `204` either way. |
| 387 | ("POST", "/auth/logout"), | 404 | ("POST", "/auth/logout"), |
| 388 | // A server certificate is handed to every peer in the TLS handshake, so | 405 | // A server certificate is handed to every peer in the TLS handshake, so |
| @@ -531,6 +548,12 @@ async fn logout_invalidates_the_session_server_side() { | |||
| 531 | 548 | ||
| 532 | let res = send(&app, "POST", "/auth/logout", Some(&ali), None).await; | 549 | let res = send(&app, "POST", "/auth/logout", Some(&ali), None).await; |
| 533 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 550 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 551 | + assert_eq!( | ||
| 552 | + res.cookie.as_deref(), | ||
| 553 | + Some("session="), | ||
| 554 | + "logout must send a clearing Set-Cookie, got {:?}", | ||
| 555 | + res.cookie | ||
| 556 | + ); | ||
| 534 | 557 | ||
| 535 | // Re-using the same token now fails: the session row is gone. | 558 | // Re-using the same token now fails: the session row is gone. |
| 536 | let res = send(&app, "GET", "/auth/me", Some(&ali), None).await; | 559 | let res = send(&app, "GET", "/auth/me", Some(&ali), None).await; |
| @@ -4931,12 +4954,11 @@ async fn a_subject_delete_racing_question_creates_leaves_no_orphan() { | |||
| 4931 | } | 4954 | } |
| 4932 | let killed = killer.await.unwrap(); | 4955 | let killed = killer.await.unwrap(); |
| 4933 | 4956 | ||
| 4934 | - let counter: i64 = | 4957 | + let counter: i64 = sqlx::query_scalar("SELECT exam_question_count FROM subject WHERE id = $1") |
| 4935 | - sqlx::query_scalar("SELECT exam_question_count FROM subject WHERE id = $1") | 4958 | + .bind(Uuid::parse_str(&subject).expect("subject id")) |
| 4936 | - .bind(Uuid::parse_str(&subject).expect("subject id")) | 4959 | + .fetch_one(&db) |
| 4937 | - .fetch_one(&db) | 4960 | + .await |
| 4938 | - .await | 4961 | + .expect("counter read"); |
| 4939 | - .expect("counter read"); | ||
| 4940 | let landed: i64 = sqlx::query_scalar("SELECT count(*) FROM exam_question WHERE subject = $1") | 4962 | let landed: i64 = sqlx::query_scalar("SELECT count(*) FROM exam_question WHERE subject = $1") |
| 4941 | .bind(Uuid::parse_str(&subject).expect("subject id")) | 4963 | .bind(Uuid::parse_str(&subject).expect("subject id")) |
| 4942 | .fetch_one(&db) | 4964 | .fetch_one(&db) |
| @@ -5900,13 +5922,15 @@ async fn login_purges_expired_sessions() { | |||
| 5900 | // Inject a session that has already expired. The FK forces the row to | 5922 | // Inject a session that has already expired. The FK forces the row to |
| 5901 | // point at a real user; the old engine allowed a dangling one. | 5923 | // point at a real user; the old engine allowed a dangling one. |
| 5902 | let ali_id = me_id(&app, &ali).await; | 5924 | let ali_id = me_id(&app, &ali).await; |
| 5903 | - sqlx::query("INSERT INTO user_session (id, app_user, token, expires_at) \ | 5925 | + sqlx::query( |
| 5904 | - VALUES ($1, $2, 'expired-token', 1)") | 5926 | + "INSERT INTO user_session (id, app_user, token, expires_at) \ |
| 5905 | - .bind(Uuid::now_v7()) | 5927 | + VALUES ($1, $2, 'expired-token', 1)", |
| 5906 | - .bind(Uuid::parse_str(&ali_id).expect("user id")) | 5928 | + ) |
| 5907 | - .execute(&db) | 5929 | + .bind(Uuid::now_v7()) |
| 5908 | - .await | 5930 | + .bind(Uuid::parse_str(&ali_id).expect("user id")) |
| 5909 | - .unwrap(); | 5931 | + .execute(&db) |
| 5932 | + .await | ||
| 5933 | + .unwrap(); | ||
| 5910 | assert!( | 5934 | assert!( |
| 5911 | session::find_by_token(&db, "expired-token") | 5935 | session::find_by_token(&db, "expired-token") |
| 5912 | .await | 5936 | .await |
| @@ -6021,7 +6045,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | |||
| 6021 | "POST", | 6045 | "POST", |
| 6022 | "/auth/login", | 6046 | "/auth/login", |
| 6023 | None, | 6047 | None, |
| 6024 | - Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })), | 6048 | + Some(json!({ "username": attempt, "password": "secret1" })), |
| 6025 | ) | 6049 | ) |
| 6026 | .await; | 6050 | .await; |
| 6027 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); | 6051 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); |
| @@ -6030,7 +6054,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | |||
| 6030 | "POST", | 6054 | "POST", |
| 6031 | "/auth/login", | 6055 | "/auth/login", |
| 6032 | None, | 6056 | None, |
| 6033 | - Some(json!({ "school": "demo", "username": attempt, "password": "spoof1" })), | 6057 | + Some(json!({ "username": attempt, "password": "spoof1" })), |
| 6034 | ) | 6058 | ) |
| 6035 | .await; | 6059 | .await; |
| 6036 | assert_eq!( | 6060 | assert_eq!( |
| @@ -6059,7 +6083,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | |||
| 6059 | "POST", | 6083 | "POST", |
| 6060 | "/auth/login", | 6084 | "/auth/login", |
| 6061 | None, | 6085 | None, |
| 6062 | - Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })), | 6086 | + Some(json!({ "username": attempt, "password": "secret1" })), |
| 6063 | ) | 6087 | ) |
| 6064 | .await; | 6088 | .await; |
| 6065 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); | 6089 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); |
| @@ -6371,10 +6395,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | |||
| 6371 | .fetch_one(&db) | 6395 | .fetch_one(&db) |
| 6372 | .await | 6396 | .await |
| 6373 | .unwrap(); | 6397 | .unwrap(); |
| 6374 | - assert_eq!( | 6398 | + assert_eq!(users, 1, "exactly one user row for the duplicated name"); |
| 6375 | - users, 1, | ||
| 6376 | - "exactly one user row for the duplicated name" | ||
| 6377 | - ); | ||
| 6378 | 6399 | ||
| 6379 | // And the winner's credentials survived the pile-up: a further duplicate | 6400 | // And the winner's credentials survived the pile-up: a further duplicate |
| 6380 | // asking for a different password does not replace them. | 6401 | // asking for a different password does not replace them. |
| @@ -6392,7 +6413,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | |||
| 6392 | "POST", | 6413 | "POST", |
| 6393 | "/auth/login", | 6414 | "/auth/login", |
| 6394 | None, | 6415 | None, |
| 6395 | - Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })), | 6416 | + Some(json!({ "username": "dup", "password": "secret1" })), |
| 6396 | ) | 6417 | ) |
| 6397 | .await; | 6418 | .await; |
| 6398 | assert_eq!(res.status, StatusCode::OK, "the winning password broke"); | 6419 | assert_eq!(res.status, StatusCode::OK, "the winning password broke"); |
| @@ -6401,7 +6422,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | |||
| 6401 | "POST", | 6422 | "POST", |
| 6402 | "/auth/login", | 6423 | "/auth/login", |
| 6403 | None, | 6424 | None, |
| 6404 | - Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })), | 6425 | + Some(json!({ "username": "dup", "password": "hijack1" })), |
| 6405 | ) | 6426 | ) |
| 6406 | .await; | 6427 | .await; |
| 6407 | assert_eq!( | 6428 | assert_eq!( |
| @@ -6472,16 +6493,17 @@ async fn session_cookie_secure_attribute_follows_config() { | |||
| 6472 | async fn login_set_cookie(app: &axum::Router) -> String { | 6493 | async fn login_set_cookie(app: &axum::Router) -> String { |
| 6473 | let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" }); | 6494 | let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" }); |
| 6474 | assert_eq!( | 6495 | assert_eq!( |
| 6475 | - send(app, "POST", "/auth/register", None, Some(creds.clone())) | 6496 | + send(app, "POST", "/auth/register", None, Some(creds)) |
| 6476 | .await | 6497 | .await |
| 6477 | .status, | 6498 | .status, |
| 6478 | StatusCode::CREATED | 6499 | StatusCode::CREATED |
| 6479 | ); | 6500 | ); |
| 6501 | + let login = json!({ "username": "ada", "password": "secret1" }); | ||
| 6480 | let req = Request::builder() | 6502 | let req = Request::builder() |
| 6481 | .method("POST") | 6503 | .method("POST") |
| 6482 | .uri("/auth/login") | 6504 | .uri("/auth/login") |
| 6483 | .header("content-type", "application/json") | 6505 | .header("content-type", "application/json") |
| 6484 | - .body(Body::from(creds.to_string())) | 6506 | + .body(Body::from(login.to_string())) |
| 6485 | .unwrap(); | 6507 | .unwrap(); |
| 6486 | let res = app.clone().oneshot(req).await.unwrap(); | 6508 | let res = app.clone().oneshot(req).await.unwrap(); |
| 6487 | assert_eq!(res.status(), StatusCode::OK); | 6509 | assert_eq!(res.status(), StatusCode::OK); |
| @@ -6860,14 +6882,19 @@ async fn cors_exposes_retry_after_and_content_disposition() { | |||
| 6860 | /// credentials and the account can reach admin-only endpoints immediately. | 6882 | /// credentials and the account can reach admin-only endpoints immediately. |
| 6861 | #[tokio::test] | 6883 | #[tokio::test] |
| 6862 | async fn admin_seed_creates_working_admin() { | 6884 | async fn admin_seed_creates_working_admin() { |
| 6863 | - let (app, db) = app_and_db().await; | 6885 | + let (app, _db, tenants) = app_and_tenants().await; |
| 6864 | let username = Username::try_new("root").unwrap(); | 6886 | let username = Username::try_new("root").unwrap(); |
| 6865 | let password = Password::try_new("secret1").unwrap(); | 6887 | let password = Password::try_new("secret1").unwrap(); |
| 6866 | - hezarfen_backend::service::user::ensure_admin(&db, username, password) | 6888 | + hezarfen_backend::service::user::ensure_admin( |
| 6867 | - .await | 6889 | + &tenants, |
| 6868 | - .unwrap(); | 6890 | + &hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap(), |
| 6891 | + username, | ||
| 6892 | + password, | ||
| 6893 | + ) | ||
| 6894 | + .await | ||
| 6895 | + .unwrap(); | ||
| 6869 | 6896 | ||
| 6870 | - let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); | 6897 | + let creds = json!({ "username": "root", "password": "secret1" }); |
| 6871 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 6898 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 6872 | assert_eq!(res.status, StatusCode::OK); | 6899 | assert_eq!(res.status, StatusCode::OK); |
| 6873 | assert_eq!(res.body["role"], "admin"); | 6900 | assert_eq!(res.body["role"], "admin"); |
| @@ -6881,17 +6908,22 @@ async fn admin_seed_creates_working_admin() { | |||
| 6881 | /// demote it, or overwrite its password. | 6908 | /// demote it, or overwrite its password. |
| 6882 | #[tokio::test] | 6909 | #[tokio::test] |
| 6883 | async fn admin_seed_is_idempotent() { | 6910 | async fn admin_seed_is_idempotent() { |
| 6884 | - let (app, db) = app_and_db().await; | 6911 | + let (app, _db, tenants) = app_and_tenants().await; |
| 6885 | for _ in 0..2 { | 6912 | for _ in 0..2 { |
| 6886 | let username = Username::try_new("root").unwrap(); | 6913 | let username = Username::try_new("root").unwrap(); |
| 6887 | let password = Password::try_new("secret1").unwrap(); | 6914 | let password = Password::try_new("secret1").unwrap(); |
| 6888 | - hezarfen_backend::service::user::ensure_admin(&db, username, password) | 6915 | + hezarfen_backend::service::user::ensure_admin( |
| 6889 | - .await | 6916 | + &tenants, |
| 6890 | - .unwrap(); | 6917 | + &hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap(), |
| 6918 | + username, | ||
| 6919 | + password, | ||
| 6920 | + ) | ||
| 6921 | + .await | ||
| 6922 | + .unwrap(); | ||
| 6891 | } | 6923 | } |
| 6892 | 6924 | ||
| 6893 | let cookie = { | 6925 | let cookie = { |
| 6894 | - let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); | 6926 | + let creds = json!({ "username": "root", "password": "secret1" }); |
| 6895 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 6927 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 6896 | assert_eq!(res.status, StatusCode::OK); | 6928 | assert_eq!(res.status, StatusCode::OK); |
| 6897 | res.cookie.expect("session cookie") | 6929 | res.cookie.expect("session cookie") |
| @@ -6906,21 +6938,26 @@ async fn admin_seed_is_idempotent() { | |||
| 6906 | /// password replaced) by the seed — that would be privilege escalation. | 6938 | /// password replaced) by the seed — that would be privilege escalation. |
| 6907 | #[tokio::test] | 6939 | #[tokio::test] |
| 6908 | async fn admin_seed_refuses_existing_non_admin() { | 6940 | async fn admin_seed_refuses_existing_non_admin() { |
| 6909 | - let (app, db) = app_and_db().await; | 6941 | + let (app, _db, tenants) = app_and_tenants().await; |
| 6910 | let cookie = login(&app, "squatter").await; // registers with password `secret1` | 6942 | let cookie = login(&app, "squatter").await; // registers with password `secret1` |
| 6911 | 6943 | ||
| 6912 | let username = Username::try_new("squatter").unwrap(); | 6944 | let username = Username::try_new("squatter").unwrap(); |
| 6913 | let password = Password::try_new("attacker-pw").unwrap(); | 6945 | let password = Password::try_new("attacker-pw").unwrap(); |
| 6914 | - hezarfen_backend::service::user::ensure_admin(&db, username, password) | 6946 | + hezarfen_backend::service::user::ensure_admin( |
| 6915 | - .await | 6947 | + &tenants, |
| 6916 | - .unwrap(); | 6948 | + &hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap(), |
| 6949 | + username, | ||
| 6950 | + password, | ||
| 6951 | + ) | ||
| 6952 | + .await | ||
| 6953 | + .unwrap(); | ||
| 6917 | 6954 | ||
| 6918 | // Still a student: the admin-only listing stays closed... | 6955 | // Still a student: the admin-only listing stays closed... |
| 6919 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; | 6956 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; |
| 6920 | assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted"); | 6957 | assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted"); |
| 6921 | 6958 | ||
| 6922 | // ...and the original password still logs in (nothing was overwritten). | 6959 | // ...and the original password still logs in (nothing was overwritten). |
| 6923 | - let creds = json!({ "school": "demo", "username": "squatter", "password": "secret1" }); | 6960 | + let creds = json!({ "username": "squatter", "password": "secret1" }); |
| 6924 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 6961 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 6925 | assert_eq!(res.status, StatusCode::OK); | 6962 | assert_eq!(res.status, StatusCode::OK); |
| 6926 | assert_eq!(res.body["role"], "student"); | 6963 | assert_eq!(res.body["role"], "student"); |
| @@ -13817,11 +13854,10 @@ async fn messages_remember_the_folder_a_filed_copy_came_from() { | |||
| 13817 | ) | 13854 | ) |
| 13818 | .await; | 13855 | .await; |
| 13819 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 13856 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13820 | - let origins: Vec<Option<String>> = | 13857 | + let origins: Vec<Option<String>> = sqlx::query_scalar("SELECT sender_origin FROM message") |
| 13821 | - sqlx::query_scalar("SELECT sender_origin FROM message") | 13858 | + .fetch_all(&db) |
| 13822 | - .fetch_all(&db) | 13859 | + .await |
| 13823 | - .await | 13860 | + .expect("read origins"); |
| 13824 | - .expect("read origins"); | ||
| 13825 | assert_eq!(origins, vec![None], "the deleted side keeps no origin"); | 13861 | assert_eq!(origins, vec![None], "the deleted side keeps no origin"); |
| 13826 | } | 13862 | } |
| 13827 | 13863 | ||
| @@ -15450,15 +15486,7 @@ async fn homework_grading_gates_and_bounds() { | |||
| 15450 | assert_eq!(res.status, StatusCode::FORBIDDEN, "students never grade"); | 15486 | assert_eq!(res.status, StatusCode::FORBIDDEN, "students never grade"); |
| 15451 | let res = grade_hw(&app, &w.teacher, &hw, &teacher_id, "done", None).await; | 15487 | let res = grade_hw(&app, &w.teacher, &hw, &teacher_id, "done", None).await; |
| 15452 | assert_eq!(res.status, StatusCode::FORBIDDEN, "no self-grading"); | 15488 | assert_eq!(res.status, StatusCode::FORBIDDEN, "no self-grading"); |
| 15453 | - let res = grade_hw( | 15489 | + let res = grade_hw(&app, &w.teacher, &hw, common::ABSENT_ID, "done", None).await; |
| 15454 | - &app, | ||
| 15455 | - &w.teacher, | ||
| 15456 | - &hw, | ||
| 15457 | - common::ABSENT_ID, | ||
| 15458 | - "done", | ||
| 15459 | - None, | ||
| 15460 | - ) | ||
| 15461 | - .await; | ||
| 15462 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "target must exist"); | 15490 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "target must exist"); |
| 15463 | let rival = login_as(&app, &db, "rival", "teacher").await; | 15491 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 15464 | let rival_id = me_id(&app, &rival).await; | 15492 | let rival_id = me_id(&app, &rival).await; |
| @@ -24542,9 +24570,7 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { | |||
| 24542 | "POST", | 24570 | "POST", |
| 24543 | "/auth/login", | 24571 | "/auth/login", |
| 24544 | None, | 24572 | None, |
| 24545 | - Some( | 24573 | + Some(json!({ "username": "ali", "password": "secret1" })), |
| 24546 | - json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }), | ||
| 24547 | - ), | ||
| 24548 | ) | 24574 | ) |
| 24549 | .await | 24575 | .await |
| 24550 | .cookie | 24576 | .cookie |
| @@ -27850,7 +27876,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27850 | "POST", | 27876 | "POST", |
| 27851 | "/auth/login", | 27877 | "/auth/login", |
| 27852 | None, | 27878 | None, |
| 27853 | - Some(json!({ "school": "beta", "username": "boran", "password": "secret1" })), | 27879 | + Some(json!({ "username": "boran", "password": "secret1" })), |
| 27854 | ) | 27880 | ) |
| 27855 | .await; | 27881 | .await; |
| 27856 | assert_eq!( | 27882 | assert_eq!( |
| @@ -28080,14 +28106,15 @@ async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, ten | |||
| 28080 | assert_eq!(found, 1, "exactly one 'ayse' in {slug}"); | 28106 | assert_eq!(found, 1, "exactly one 'ayse' in {slug}"); |
| 28081 | } | 28107 | } |
| 28082 | 28108 | ||
| 28083 | - // Unknown school: same 401 and same body as a bad credential — no | 28109 | + // The login body names no school, so the customer list is not probeable |
| 28084 | - // enumeration of the customer list. | 28110 | + // there at all. The parity that remains is unknown-username vs bad |
| 28085 | - let unknown = send( | 28111 | + // password: same 401, same body, same argon2 bill. |
| 28112 | + let unknown_user = send( | ||
| 28086 | app, | 28113 | app, |
| 28087 | "POST", | 28114 | "POST", |
| 28088 | "/auth/login", | 28115 | "/auth/login", |
| 28089 | None, | 28116 | None, |
| 28090 | - Some(json!({ "school": "not-a-school", "username": "ayse", "password": "secret1" })), | 28117 | + Some(json!({ "username": "nobody-here", "password": "secret1" })), |
| 28091 | ) | 28118 | ) |
| 28092 | .await; | 28119 | .await; |
| 28093 | let bad_pass = send( | 28120 | let bad_pass = send( |
| @@ -28095,15 +28122,20 @@ async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, ten | |||
| 28095 | "POST", | 28122 | "POST", |
| 28096 | "/auth/login", | 28123 | "/auth/login", |
| 28097 | None, | 28124 | None, |
| 28098 | - Some(json!({ "school": DEMO_SLUG, "username": "ayse", "password": "wrongpw1" })), | 28125 | + Some(json!({ "username": "ayse", "password": "wrongpw1" })), |
| 28099 | ) | 28126 | ) |
| 28100 | .await; | 28127 | .await; |
| 28101 | - assert_eq!(unknown.status, StatusCode::UNAUTHORIZED, "{}", unknown.body); | ||
| 28102 | - assert_eq!(unknown.status, bad_pass.status, "status differs"); | ||
| 28103 | assert_eq!( | 28128 | assert_eq!( |
| 28104 | - unknown.body, bad_pass.body, | 28129 | + unknown_user.status, |
| 28105 | - "an unknown school answers differently from a bad password: {} vs {}", | 28130 | + StatusCode::UNAUTHORIZED, |
| 28106 | - unknown.body, bad_pass.body | 28131 | + "{}", |
| 28132 | + unknown_user.body | ||
| 28133 | + ); | ||
| 28134 | + assert_eq!(unknown_user.status, bad_pass.status, "status differs"); | ||
| 28135 | + assert_eq!( | ||
| 28136 | + unknown_user.body, bad_pass.body, | ||
| 28137 | + "an unknown username answers differently from a bad password: {} vs {}", | ||
| 28138 | + unknown_user.body, bad_pass.body | ||
| 28107 | ); | 28139 | ); |
| 28108 | 28140 | ||
| 28109 | // Register against an unknown school: same treatment. | 28141 | // Register against an unknown school: same treatment. |
| @@ -28334,7 +28366,9 @@ async fn remote_probe_remote_mode_keeps_two_schools_apart() { | |||
| 28334 | let slug_a = Slug::try_new("ata-koleji").unwrap(); | 28366 | let slug_a = Slug::try_new("ata-koleji").unwrap(); |
| 28335 | let slug_b = Slug::try_new("2024school").unwrap(); | 28367 | let slug_b = Slug::try_new("2024school").unwrap(); |
| 28336 | 28368 | ||
| 28337 | - // The same username in both schools, over the real router. | 28369 | + // Same username in both schools is one person with two memberships. |
| 28370 | + // Login into the second school therefore returns a person cookie; bind | ||
| 28371 | + // each membership so the rest of the test holds two school sessions. | ||
| 28338 | let mut cookies = Vec::new(); | 28372 | let mut cookies = Vec::new(); |
| 28339 | for slug in [&slug_a, &slug_b] { | 28373 | for slug in [&slug_a, &slug_b] { |
| 28340 | let creds = json!({ "school": slug.as_str(), "username": "ada", "password": "secret1" }); | 28374 | let creds = json!({ "school": slug.as_str(), "username": "ada", "password": "secret1" }); |
| @@ -28349,7 +28383,26 @@ async fn remote_probe_remote_mode_keeps_two_schools_apart() { | |||
| 28349 | common::set_role(&db, "ada", "admin").await; | 28383 | common::set_role(&db, "ada", "admin").await; |
| 28350 | let res = send(app, "POST", "/auth/login", None, Some(creds)).await; | 28384 | let res = send(app, "POST", "/auth/login", None, Some(creds)).await; |
| 28351 | assert_eq!(res.status, StatusCode::OK, "login in {slug}: {}", res.body); | 28385 | assert_eq!(res.status, StatusCode::OK, "login in {slug}: {}", res.body); |
| 28352 | - cookies.push(res.cookie.expect("cookie")); | 28386 | + let cookie = if res.body["schools"].is_array() { |
| 28387 | + let selected = send( | ||
| 28388 | + app, | ||
| 28389 | + "POST", | ||
| 28390 | + "/auth/school", | ||
| 28391 | + res.cookie.as_deref(), | ||
| 28392 | + Some(json!({ "school": slug.as_str() })), | ||
| 28393 | + ) | ||
| 28394 | + .await; | ||
| 28395 | + assert_eq!( | ||
| 28396 | + selected.status, | ||
| 28397 | + StatusCode::OK, | ||
| 28398 | + "select {slug}: {}", | ||
| 28399 | + selected.body | ||
| 28400 | + ); | ||
| 28401 | + selected.cookie.expect("school cookie") | ||
| 28402 | + } else { | ||
| 28403 | + res.cookie.expect("cookie") | ||
| 28404 | + }; | ||
| 28405 | + cookies.push(cookie); | ||
| 28353 | } | 28406 | } |
| 28354 | let (a, b) = (cookies[0].clone(), cookies[1].clone()); | 28407 | let (a, b) = (cookies[0].clone(), cookies[1].clone()); |
| 28355 | 28408 | ||
| @@ -29163,3 +29216,215 @@ async fn the_catalog_lists_every_module() { | |||
| 29163 | ); | 29216 | ); |
| 29164 | } | 29217 | } |
| 29165 | } | 29218 | } |
| 29219 | + | ||
| 29220 | +// --- person-scoped login --------------------------------------------------- | ||
| 29221 | + | ||
| 29222 | +/// A person registered at exactly one school is entered straight into it: the | ||
| 29223 | +/// login body carries no school, the reply names the person, and the session | ||
| 29224 | +/// cookie is that school's. | ||
| 29225 | +#[tokio::test] | ||
| 29226 | +async fn login_without_school_enters_a_single_school_person() { | ||
| 29227 | + let (app, _db) = app_and_db().await; | ||
| 29228 | + let reg = send( | ||
| 29229 | + &app, | ||
| 29230 | + "POST", | ||
| 29231 | + "/auth/register", | ||
| 29232 | + None, | ||
| 29233 | + Some(json!({ "school": DEMO_SLUG, "username": "personada", "password": "secret1" })), | ||
| 29234 | + ) | ||
| 29235 | + .await; | ||
| 29236 | + assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body); | ||
| 29237 | + | ||
| 29238 | + let res = send( | ||
| 29239 | + &app, | ||
| 29240 | + "POST", | ||
| 29241 | + "/auth/login", | ||
| 29242 | + None, | ||
| 29243 | + Some(json!({ "username": "personada", "password": "secret1" })), | ||
| 29244 | + ) | ||
| 29245 | + .await; | ||
| 29246 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29247 | + assert!(res.body["id"].is_string(), "the person's id: {}", res.body); | ||
| 29248 | + assert_eq!(res.body["username"], "personada"); | ||
| 29249 | + let cookie = res.cookie.expect("school cookie"); | ||
| 29250 | + assert!(cookie.starts_with("session=demo."), "cookie: {cookie}"); | ||
| 29251 | + | ||
| 29252 | + let res = send(&app, "GET", "/auth/me", Some(&cookie), None).await; | ||
| 29253 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29254 | +} | ||
| 29255 | + | ||
| 29256 | +/// A person registered at two schools is entered nowhere by login: the reply | ||
| 29257 | +/// lists both schools and the cookie is a person cookie that has chosen | ||
| 29258 | +/// nothing yet; `POST /auth/school` then binds it to one school. | ||
| 29259 | +#[tokio::test] | ||
| 29260 | +async fn a_multischool_person_selects_a_school() { | ||
| 29261 | + let d = common::deployment_with(TWO_SCHOOLS).await; | ||
| 29262 | + let app = &d.app; | ||
| 29263 | + for school in [DEMO_SLUG, "beta"] { | ||
| 29264 | + let reg = send( | ||
| 29265 | + app, | ||
| 29266 | + "POST", | ||
| 29267 | + "/auth/register", | ||
| 29268 | + None, | ||
| 29269 | + Some(json!({ "school": school, "username": "personada", "password": "secret1" })), | ||
| 29270 | + ) | ||
| 29271 | + .await; | ||
| 29272 | + assert_eq!( | ||
| 29273 | + reg.status, | ||
| 29274 | + StatusCode::CREATED, | ||
| 29275 | + "register into {school}: {}", | ||
| 29276 | + reg.body | ||
| 29277 | + ); | ||
| 29278 | + } | ||
| 29279 | + | ||
| 29280 | + let res = send( | ||
| 29281 | + app, | ||
| 29282 | + "POST", | ||
| 29283 | + "/auth/login", | ||
| 29284 | + None, | ||
| 29285 | + Some(json!({ "username": "personada", "password": "secret1" })), | ||
| 29286 | + ) | ||
| 29287 | + .await; | ||
| 29288 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29289 | + assert_eq!(res.body["username"], "personada"); | ||
| 29290 | + let mut slugs: Vec<&str> = res.body["schools"] | ||
| 29291 | + .as_array() | ||
| 29292 | + .expect("schools list") | ||
| 29293 | + .iter() | ||
| 29294 | + .map(|s| s["slug"].as_str().expect("school slug")) | ||
| 29295 | + .collect(); | ||
| 29296 | + slugs.sort_unstable(); | ||
| 29297 | + assert_eq!(slugs, ["beta", "demo"]); | ||
| 29298 | + assert!( | ||
| 29299 | + res.body.get("id").is_none(), | ||
| 29300 | + "no school chosen yet: {}", | ||
| 29301 | + res.body | ||
| 29302 | + ); | ||
| 29303 | + let person = res.cookie.expect("person cookie"); | ||
| 29304 | + assert!(person.starts_with("session=person."), "cookie: {person}"); | ||
| 29305 | + | ||
| 29306 | + // A person cookie alone is not a session: `/auth/me` refuses it. | ||
| 29307 | + let res = send(app, "GET", "/auth/me", Some(&person), None).await; | ||
| 29308 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | ||
| 29309 | + | ||
| 29310 | + let res = send( | ||
| 29311 | + app, | ||
| 29312 | + "POST", | ||
| 29313 | + "/auth/school", | ||
| 29314 | + Some(&person), | ||
| 29315 | + Some(json!({ "school": DEMO_SLUG })), | ||
| 29316 | + ) | ||
| 29317 | + .await; | ||
| 29318 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29319 | + assert!(res.body["id"].is_string(), "the person's id: {}", res.body); | ||
| 29320 | + let cookie = res.cookie.expect("school cookie"); | ||
| 29321 | + assert!(cookie.starts_with("session=demo."), "cookie: {cookie}"); | ||
| 29322 | + let res = send(app, "GET", "/auth/me", Some(&cookie), None).await; | ||
| 29323 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29324 | +} | ||
| 29325 | + | ||
| 29326 | +/// `POST /auth/school` is member-only and cookie-strict: a slug the person is | ||
| 29327 | +/// not registered under, a missing cookie, and an already-bound school cookie | ||
| 29328 | +/// all refuse. | ||
| 29329 | +#[tokio::test] | ||
| 29330 | +async fn school_selection_refuses_non_members_and_wrong_cookies() { | ||
| 29331 | + let d = common::deployment_with(TWO_SCHOOLS).await; | ||
| 29332 | + let app = &d.app; | ||
| 29333 | + for school in [DEMO_SLUG, "beta"] { | ||
| 29334 | + let reg = send( | ||
| 29335 | + app, | ||
| 29336 | + "POST", | ||
| 29337 | + "/auth/register", | ||
| 29338 | + None, | ||
| 29339 | + Some(json!({ "school": school, "username": "personada", "password": "secret1" })), | ||
| 29340 | + ) | ||
| 29341 | + .await; | ||
| 29342 | + assert_eq!( | ||
| 29343 | + reg.status, | ||
| 29344 | + StatusCode::CREATED, | ||
| 29345 | + "register into {school}: {}", | ||
| 29346 | + reg.body | ||
| 29347 | + ); | ||
| 29348 | + } | ||
| 29349 | + let res = send( | ||
| 29350 | + app, | ||
| 29351 | + "POST", | ||
| 29352 | + "/auth/login", | ||
| 29353 | + None, | ||
| 29354 | + Some(json!({ "username": "personada", "password": "secret1" })), | ||
| 29355 | + ) | ||
| 29356 | + .await; | ||
| 29357 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29358 | + let person = res.cookie.expect("person cookie"); | ||
| 29359 | + | ||
| 29360 | + // Not a member of the requested school. | ||
| 29361 | + let res = send( | ||
| 29362 | + app, | ||
| 29363 | + "POST", | ||
| 29364 | + "/auth/school", | ||
| 29365 | + Some(&person), | ||
| 29366 | + Some(json!({ "school": "ghost-slug" })), | ||
| 29367 | + ) | ||
| 29368 | + .await; | ||
| 29369 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | ||
| 29370 | + | ||
| 29371 | + // No cookie at all. | ||
| 29372 | + let res = send( | ||
| 29373 | + app, | ||
| 29374 | + "POST", | ||
| 29375 | + "/auth/school", | ||
| 29376 | + None, | ||
| 29377 | + Some(json!({ "school": DEMO_SLUG })), | ||
| 29378 | + ) | ||
| 29379 | + .await; | ||
| 29380 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | ||
| 29381 | + | ||
| 29382 | + // Selecting a school for real... | ||
| 29383 | + let res = send( | ||
| 29384 | + app, | ||
| 29385 | + "POST", | ||
| 29386 | + "/auth/school", | ||
| 29387 | + Some(&person), | ||
| 29388 | + Some(json!({ "school": DEMO_SLUG })), | ||
| 29389 | + ) | ||
| 29390 | + .await; | ||
| 29391 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29392 | + let school_cookie = res.cookie.expect("school cookie"); | ||
| 29393 | + | ||
| 29394 | + // ...and asking again with the school cookie: refused. | ||
| 29395 | + let res = send( | ||
| 29396 | + app, | ||
| 29397 | + "POST", | ||
| 29398 | + "/auth/school", | ||
| 29399 | + Some(&school_cookie), | ||
| 29400 | + Some(json!({ "school": DEMO_SLUG })), | ||
| 29401 | + ) | ||
| 29402 | + .await; | ||
| 29403 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | ||
| 29404 | +} | ||
| 29405 | + | ||
| 29406 | +/// The old client shape — a leftover `"school"` field in the login body — is | ||
| 29407 | +/// ignored, not refused: serde drops fields the login no longer knows. | ||
| 29408 | +#[tokio::test] | ||
| 29409 | +async fn login_ignores_a_leftover_school_field() { | ||
| 29410 | + let (app, _db) = app_and_db().await; | ||
| 29411 | + let reg = send( | ||
| 29412 | + &app, | ||
| 29413 | + "POST", | ||
| 29414 | + "/auth/register", | ||
| 29415 | + None, | ||
| 29416 | + Some(json!({ "school": DEMO_SLUG, "username": "personada", "password": "secret1" })), | ||
| 29417 | + ) | ||
| 29418 | + .await; | ||
| 29419 | + assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body); | ||
| 29420 | + | ||
| 29421 | + let res = send( | ||
| 29422 | + &app, | ||
| 29423 | + "POST", | ||
| 29424 | + "/auth/login", | ||
| 29425 | + None, | ||
| 29426 | + Some(json!({ "school": "demo", "username": "personada", "password": "secret1" })), | ||
| 29427 | + ) | ||
| 29428 | + .await; | ||
| 29429 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 29430 | +} | ||
tests/persistence.rsmodified+43 -23
| @@ -45,9 +45,10 @@ async fn settings_and_terms_survive_remigration() { | |||
| 45 | let (app, db, tenants) = common::app_and_tenants().await; | 45 | let (app, db, tenants) = common::app_and_tenants().await; |
| 46 | 46 | ||
| 47 | let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | 47 | let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); |
| 48 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | 48 | + send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 49 | set_role(&db, "boss", "manager").await; | 49 | set_role(&db, "boss", "manager").await; |
| 50 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | 50 | + let login = json!({ "username": "boss", "password": "secret1" }); |
| 51 | + let cookie = send(&app, "POST", "/auth/login", None, Some(login.clone())) | ||
| 51 | .await | 52 | .await |
| 52 | .cookie | 53 | .cookie |
| 53 | .unwrap(); | 54 | .unwrap(); |
| @@ -91,7 +92,7 @@ async fn settings_and_terms_survive_remigration() { | |||
| 91 | 92 | ||
| 92 | // Second boot: migration re-applied over live data. | 93 | // Second boot: migration re-applied over live data. |
| 93 | let app = reboot(&db, &tenants).await; | 94 | let app = reboot(&db, &tenants).await; |
| 94 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | 95 | + let cookie = send(&app, "POST", "/auth/login", None, Some(login)) |
| 95 | .await | 96 | .await |
| 96 | .cookie | 97 | .cookie |
| 97 | .unwrap(); | 98 | .unwrap(); |
| @@ -146,7 +147,7 @@ async fn appointments_survive_remigration() { | |||
| 146 | "POST", | 147 | "POST", |
| 147 | "/auth/login", | 148 | "/auth/login", |
| 148 | None, | 149 | None, |
| 149 | - Some(teacher_creds.clone()), | 150 | + Some(json!({ "username": "ali", "password": "secret1" })), |
| 150 | ) | 151 | ) |
| 151 | .await | 152 | .await |
| 152 | .cookie | 153 | .cookie |
| @@ -156,7 +157,7 @@ async fn appointments_survive_remigration() { | |||
| 156 | "POST", | 157 | "POST", |
| 157 | "/auth/login", | 158 | "/auth/login", |
| 158 | None, | 159 | None, |
| 159 | - Some(student_creds.clone()), | 160 | + Some(json!({ "username": "ayse", "password": "secret1" })), |
| 160 | ) | 161 | ) |
| 161 | .await | 162 | .await |
| 162 | .cookie | 163 | .cookie |
| @@ -292,7 +293,7 @@ async fn attempt_history_survives_remigration() { | |||
| 292 | "POST", | 293 | "POST", |
| 293 | "/auth/login", | 294 | "/auth/login", |
| 294 | None, | 295 | None, |
| 295 | - Some(teacher_creds.clone()), | 296 | + Some(json!({ "username": "ali", "password": "secret1" })), |
| 296 | ) | 297 | ) |
| 297 | .await | 298 | .await |
| 298 | .cookie | 299 | .cookie |
| @@ -302,7 +303,7 @@ async fn attempt_history_survives_remigration() { | |||
| 302 | "POST", | 303 | "POST", |
| 303 | "/auth/login", | 304 | "/auth/login", |
| 304 | None, | 305 | None, |
| 305 | - Some(student_creds.clone()), | 306 | + Some(json!({ "username": "ayse", "password": "secret1" })), |
| 306 | ) | 307 | ) |
| 307 | .await | 308 | .await |
| 308 | .cookie | 309 | .cookie |
| @@ -378,10 +379,16 @@ async fn attempt_history_survives_remigration() { | |||
| 378 | 379 | ||
| 379 | // Second boot: migration re-applied over the two sittings' live rows. | 380 | // Second boot: migration re-applied over the two sittings' live rows. |
| 380 | let app = reboot(&db, &tenants).await; | 381 | let app = reboot(&db, &tenants).await; |
| 381 | - let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) | 382 | + let teacher = send( |
| 382 | - .await | 383 | + &app, |
| 383 | - .cookie | 384 | + "POST", |
| 384 | - .unwrap(); | 385 | + "/auth/login", |
| 386 | + None, | ||
| 387 | + Some(json!({ "username": "ali", "password": "secret1" })), | ||
| 388 | + ) | ||
| 389 | + .await | ||
| 390 | + .cookie | ||
| 391 | + .unwrap(); | ||
| 385 | 392 | ||
| 386 | let res = send( | 393 | let res = send( |
| 387 | &app, | 394 | &app, |
| @@ -556,14 +563,15 @@ async fn settings_slots_without_a_serving_minute_still_patch() { | |||
| 556 | let (app, db, tenants) = common::app_and_tenants().await; | 563 | let (app, db, tenants) = common::app_and_tenants().await; |
| 557 | 564 | ||
| 558 | let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | 565 | let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); |
| 559 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | 566 | + send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 560 | set_role(&db, "boss", "manager").await; | 567 | set_role(&db, "boss", "manager").await; |
| 568 | + let login = json!({ "username": "boss", "password": "secret1" }); | ||
| 561 | 569 | ||
| 562 | let res = send( | 570 | let res = send( |
| 563 | &app, | 571 | &app, |
| 564 | "PATCH", | 572 | "PATCH", |
| 565 | "/settings", | 573 | "/settings", |
| 566 | - Some(&send(&app, "POST", "/auth/login", None, Some(creds.clone())) | 574 | + Some(&send(&app, "POST", "/auth/login", None, Some(login.clone())) |
| 567 | .await | 575 | .await |
| 568 | .cookie | 576 | .cookie |
| 569 | .unwrap()), | 577 | .unwrap()), |
| @@ -574,7 +582,7 @@ async fn settings_slots_without_a_serving_minute_still_patch() { | |||
| 574 | 582 | ||
| 575 | // Second boot, then read and patch again. | 583 | // Second boot, then read and patch again. |
| 576 | let app = reboot(&db, &tenants).await; | 584 | let app = reboot(&db, &tenants).await; |
| 577 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | 585 | + let cookie = send(&app, "POST", "/auth/login", None, Some(login)) |
| 578 | .await | 586 | .await |
| 579 | .cookie | 587 | .cookie |
| 580 | .unwrap(); | 588 | .unwrap(); |
| @@ -616,14 +624,26 @@ async fn fee_plans_and_their_charges_survive_remigration() { | |||
| 616 | ); | 624 | ); |
| 617 | } | 625 | } |
| 618 | set_role(&db, "ali", "manager").await; | 626 | set_role(&db, "ali", "manager").await; |
| 619 | - let manager = send(&app, "POST", "/auth/login", None, Some(manager_creds)) | 627 | + let manager = send( |
| 620 | - .await | 628 | + &app, |
| 621 | - .cookie | 629 | + "POST", |
| 622 | - .unwrap(); | 630 | + "/auth/login", |
| 623 | - let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) | 631 | + None, |
| 624 | - .await | 632 | + Some(json!({ "username": "ali", "password": "secret1" })), |
| 625 | - .cookie | 633 | + ) |
| 626 | - .unwrap(); | 634 | + .await |
| 635 | + .cookie | ||
| 636 | + .unwrap(); | ||
| 637 | + let student = send( | ||
| 638 | + &app, | ||
| 639 | + "POST", | ||
| 640 | + "/auth/login", | ||
| 641 | + None, | ||
| 642 | + Some(json!({ "username": "ayse", "password": "secret1" })), | ||
| 643 | + ) | ||
| 644 | + .await | ||
| 645 | + .cookie | ||
| 646 | + .unwrap(); | ||
| 627 | let student_id = me_id(&app, &student).await; | 647 | let student_id = me_id(&app, &student).await; |
| 628 | 648 | ||
| 629 | let res = send( | 649 | let res = send( |
| @@ -693,7 +713,7 @@ async fn fee_plans_and_their_charges_survive_remigration() { | |||
| 693 | #[tokio::test] | 713 | #[tokio::test] |
| 694 | async fn boards_and_their_strokes_survive_remigration() { | 714 | async fn boards_and_their_strokes_survive_remigration() { |
| 695 | let (app, db, tenants) = common::app_and_tenants().await; | 715 | let (app, db, tenants) = common::app_and_tenants().await; |
| 696 | - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | 716 | + let creds = json!({ "username": "ali", "password": "secret1" }); |
| 697 | let cookie = common::login(&app, "ali").await; | 717 | let cookie = common::login(&app, "ali").await; |
| 698 | let veli = common::login(&app, "veli").await; | 718 | let veli = common::login(&app, "veli").await; |
| 699 | let ali_id = me_id(&app, &cookie).await; | 719 | let ali_id = me_id(&app, &cookie).await; |
tests/rate_limit.rsmodified+20 -6
| @@ -69,7 +69,7 @@ async fn send_as( | |||
| 69 | } | 69 | } |
| 70 | 70 | ||
| 71 | fn bad_login() -> Option<Value> { | 71 | fn bad_login() -> Option<Value> { |
| 72 | - Some(json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) | 72 | + Some(json!({ "username": "ghost", "password": "wrong-pass" })) |
| 73 | } | 73 | } |
| 74 | 74 | ||
| 75 | fn auth_only(per_minute: u32) -> RateLimitConfig { | 75 | fn auth_only(per_minute: u32) -> RateLimitConfig { |
| @@ -111,16 +111,30 @@ async fn register_and_login_share_the_auth_bucket() { | |||
| 111 | "1.1.1.1", | 111 | "1.1.1.1", |
| 112 | "POST", | 112 | "POST", |
| 113 | "/auth/register", | 113 | "/auth/register", |
| 114 | - Some(creds.clone()), | 114 | + Some(creds), |
| 115 | ) | 115 | ) |
| 116 | .await; | 116 | .await; |
| 117 | assert_eq!(status, StatusCode::CREATED); | 117 | assert_eq!(status, StatusCode::CREATED); |
| 118 | - let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", Some(creds.clone())).await; | 118 | + let (status, _, _) = send_as( |
| 119 | + &app, | ||
| 120 | + "1.1.1.1", | ||
| 121 | + "POST", | ||
| 122 | + "/auth/login", | ||
| 123 | + Some(json!({ "username": "ada", "password": "secret1" })), | ||
| 124 | + ) | ||
| 125 | + .await; | ||
| 119 | assert_eq!(status, StatusCode::OK); | 126 | assert_eq!(status, StatusCode::OK); |
| 120 | 127 | ||
| 121 | // Two credential requests spent the whole budget; the third is metered | 128 | // Two credential requests spent the whole budget; the third is metered |
| 122 | // regardless of whether it would have succeeded. | 129 | // regardless of whether it would have succeeded. |
| 123 | - let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", Some(creds)).await; | 130 | + let (status, _, _) = send_as( |
| 131 | + &app, | ||
| 132 | + "1.1.1.1", | ||
| 133 | + "POST", | ||
| 134 | + "/auth/login", | ||
| 135 | + Some(json!({ "username": "ada", "password": "secret1" })), | ||
| 136 | + ) | ||
| 137 | + .await; | ||
| 124 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); | 138 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 125 | } | 139 | } |
| 126 | 140 | ||
| @@ -596,7 +610,7 @@ async fn real_connections_are_keyed_by_peer_address() { | |||
| 596 | let res = client | 610 | let res = client |
| 597 | .post(format!("{base}/auth/login")) | 611 | .post(format!("{base}/auth/login")) |
| 598 | .header("x-forwarded-for", spoof) | 612 | .header("x-forwarded-for", spoof) |
| 599 | - .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) | 613 | + .json(&json!({ "username": "ghost", "password": "wrong-pass" })) |
| 600 | .send() | 614 | .send() |
| 601 | .await | 615 | .await |
| 602 | .unwrap(); | 616 | .unwrap(); |
| @@ -606,7 +620,7 @@ async fn real_connections_are_keyed_by_peer_address() { | |||
| 606 | let res = client | 620 | let res = client |
| 607 | .post(format!("{base}/auth/login")) | 621 | .post(format!("{base}/auth/login")) |
| 608 | .header("x-forwarded-for", "3.3.3.3") | 622 | .header("x-forwarded-for", "3.3.3.3") |
| 609 | - .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) | 623 | + .json(&json!({ "username": "ghost", "password": "wrong-pass" })) |
| 610 | .send() | 624 | .send() |
| 611 | .await | 625 | .await |
| 612 | .unwrap(); | 626 | .unwrap(); |
tests/regress_roles.rsmodified+1 -4
| @@ -184,10 +184,7 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() { | |||
| 184 | "POST", | 184 | "POST", |
| 185 | "/auth/login", | 185 | "/auth/login", |
| 186 | None, | 186 | None, |
| 187 | - Some(json!({ | 187 | + Some(json!({ "username": "ali", "password": "secret1" })), |
| 188 | - "school": "demo", | ||
| 189 | - "school": "demo", "username": "ali", "password": "secret1" | ||
| 190 | - })), | ||
| 191 | ) | 188 | ) |
| 192 | .await | 189 | .await |
| 193 | .cookie | 190 | .cookie |