forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

role.rs201 lines, 7.9 KiBHistoryRawDownload
1use sqlx::Type;
2
3use crate::error::ValidationError;
4
5/// The access levels, in ascending order of privilege.
6///
7/// The variants are declared low-to-high, so the derived `Ord` matches the
8/// hierarchy: `Role::Admin > Role::Teacher`. That ordering is exactly what
9/// [`Role::at_least`] relies on — a higher role satisfies any lower requirement.
10///
11/// `Ai` is not a human role at all: it is the principal an out-of-process AI
12/// service carries over the QUIC bridge. It is declared first so it clears no
13/// `at_least` bar above itself, it is absent from [`ROLES`] (the assignable
14/// set) so [`Role::try_from_str`] rejects `"ai"`, and no HTTP surface can put
15/// it on a user row — the only value of it lives in `User::ai_principal`.
16///
17/// `Parent` sits at the bottom: a read-only observer of the students linked to
18/// it (see `domain::parent_link`). It clears no `at_least` bar and fails every
19/// exact `== Student` gate, so parents can't sit exams, enroll, or be marked on
20/// a roll call — they only read their own students' reports.
21///
22/// [`Role`] derives [`sqlx::Type`] as a bare TEXT enum: each variant stores as
23/// its lowercase name (`"student"`, `"teacher"`, …) and round-trips straight
24/// back, which the `role` column's `CHECK` lists and every `role = 'teacher'`
25/// filter spells. [`Role::as_str`] must stay in lockstep with it.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Type)]
27#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
28pub enum Role {
29 Ai,
30 Parent,
31 Student,
32 Teacher,
33 Manager,
34 Admin,
35}
36
37impl Role {
38 /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`.
39 pub fn as_str(self) -> &'static str {
40 match self {
41 Role::Ai => "ai",
42 Role::Parent => "parent",
43 Role::Student => "student",
44 Role::Teacher => "teacher",
45 Role::Manager => "manager",
46 Role::Admin => "admin",
47 }
48 }
49
50 /// Parse a wire string into a role — the inverse of [`Role::as_str`] for
51 /// the assignable roles only. It searches [`ROLES`], which excludes
52 /// [`Role::Ai`], so `"ai"` is rejected like any other unknown word.
53 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
54 ROLES
55 .into_iter()
56 .find(|role| role.as_str() == value)
57 .ok_or(ValidationError::Invalid {
58 field: "role",
59 reason: "must be one of: parent, student, teacher, manager, admin",
60 })
61 }
62
63 /// True when `self` is at least as privileged as `min` (the hierarchy check).
64 pub fn at_least(self, min: Role) -> bool {
65 self >= min
66 }
67
68 /// May `self` open a message thread with `recipient`? Messaging is upward
69 /// only for the two roles below staff: a `Student` or `Parent` writes to
70 /// teachers and above, never sideways or down (issue #23). Staff
71 /// (`Teacher`+) write to anyone. [`Role::Ai`] is a service principal with
72 /// no mailbox, so it neither sends nor receives.
73 pub fn may_message(self, recipient: Role) -> bool {
74 if self == Role::Ai || recipient == Role::Ai {
75 return false;
76 }
77 self.at_least(Role::Teacher) || recipient.at_least(Role::Teacher)
78 }
79
80 /// The roles `self` is allowed to write to, when that set is narrower than
81 /// "everyone" — `None` means unrestricted. Backs the `/users/search`
82 /// restriction, which must land in the query so `total` stays right.
83 pub fn messageable_roles(self) -> Option<&'static [Role]> {
84 match self.at_least(Role::Teacher) {
85 true => None,
86 false => Some(&[Role::Teacher, Role::Manager, Role::Admin]),
87 }
88 }
89}
90
91/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately
92/// absent: it is a service principal, so leaving it out of this table is what
93/// keeps `Role::try_from_str` (and every surface that lists roles) from ever
94/// handing it to a user.
95pub const ROLES: [Role; 5] = [
96 Role::Parent,
97 Role::Student,
98 Role::Teacher,
99 Role::Manager,
100 Role::Admin,
101];
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[tokio::test]
108 async fn hierarchy_orders_low_to_high() {
109 assert!(Role::Parent < Role::Student);
110 assert!(Role::Student < Role::Teacher);
111 assert!(Role::Teacher < Role::Manager);
112 assert!(Role::Manager < Role::Admin);
113 }
114
115 #[tokio::test]
116 async fn parent_clears_no_bar_above_itself() {
117 // A parent is an observer: it must never satisfy a staff (or even
118 // student) requirement through the hierarchy.
119 assert!(Role::Parent.at_least(Role::Parent));
120 assert!(!Role::Parent.at_least(Role::Student));
121 assert!(!Role::Parent.at_least(Role::Teacher));
122 }
123
124 #[tokio::test]
125 async fn at_least_is_inclusive_and_upward() {
126 // A teacher clears the teacher bar and everything below it.
127 assert!(Role::Teacher.at_least(Role::Teacher));
128 assert!(Role::Teacher.at_least(Role::Student));
129 assert!(!Role::Teacher.at_least(Role::Manager));
130 // Admin clears every bar.
131 assert!(ROLES.iter().all(|&r| Role::Admin.at_least(r)));
132 }
133
134 #[tokio::test]
135 async fn ai_is_a_service_principal_no_client_can_reach() {
136 // Lowest ordinal: it satisfies no requirement a real role can be asked
137 // for, so an AI request clears nothing through the hierarchy.
138 assert!(ROLES.iter().all(|&r| !Role::Ai.at_least(r)));
139 assert!(ROLES.iter().all(|&r| r.at_least(Role::Ai)));
140 // Not assignable: absent from ROLES, so no wire string parses to it.
141 assert!(!ROLES.contains(&Role::Ai));
142 assert!(Role::try_from_str("ai").is_err());
143 assert_eq!(Role::Ai.as_str(), "ai");
144 }
145
146 #[tokio::test]
147 async fn messaging_is_upward_only_below_staff() {
148 // Sideways and downward writes from the two non-staff roles: refused.
149 for sender in [Role::Student, Role::Parent] {
150 for recipient in [Role::Student, Role::Parent] {
151 assert!(!sender.may_message(recipient));
152 }
153 for staff in [Role::Teacher, Role::Manager, Role::Admin] {
154 assert!(sender.may_message(staff));
155 }
156 assert_eq!(
157 sender.messageable_roles(),
158 Some(&[Role::Teacher, Role::Manager, Role::Admin][..])
159 );
160 }
161 // Staff write to anyone, in any direction, and are unrestricted in search.
162 for sender in [Role::Teacher, Role::Manager, Role::Admin] {
163 assert!(ROLES.iter().all(|&r| sender.may_message(r)));
164 assert_eq!(sender.messageable_roles(), None);
165 }
166 // The service principal has no mailbox in either direction.
167 assert!(ROLES.iter().all(|&r| !Role::Ai.may_message(r)));
168 assert!(ROLES.iter().all(|&r| !r.may_message(Role::Ai)));
169 }
170
171 #[tokio::test]
172 async fn str_round_trips() {
173 for role in ROLES {
174 assert_eq!(Role::try_from_str(role.as_str()).unwrap(), role);
175 }
176 assert!(Role::try_from_str("wizard").is_err());
177 assert!(Role::try_from_str("").is_err());
178 }
179
180 #[test]
181 fn sqlx_encodes_the_storage_form() {
182 // The whole point of the TEXT encoding: the stored value is the bare
183 // lowercase string, so the `role` column accepts it and every
184 // `role = 'teacher'` filter matches. Guard that the sqlx encoding
185 // never drifts from `as_str` — the CHECK constraint and the filters
186 // spell these same words.
187 let mut buf = sqlx::postgres::PgArgumentBuffer::default();
188 for role in [
189 Role::Ai,
190 Role::Parent,
191 Role::Student,
192 Role::Teacher,
193 Role::Manager,
194 Role::Admin,
195 ] {
196 buf.clear();
197 let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&role, &mut buf).unwrap();
198 assert_eq!(std::str::from_utf8(&buf).unwrap(), role.as_str());
199 }
200 }
201}