forge
Explore
Log in

Don't you dare go Hollow

33970869bc94d5aeb3cae9bb2d3f0baf904c96aaAhmet Kaan GümüşParent: a6d34e6
  • docs
    • project README
Show full message
📝 docs: project README

Document the service: run instructions (local and container), the
cookie-session auth model, both rate-limit tiers, credential-aware
CORS, the hierarchical role matrix and first-admin bootstrap, the full
endpoint table, a curl quick tour, and the source layout.
README.mdadded+234 -0
@@ -0,0 +1,234 @@
1+# hezarfen_backend
2+
3+Note, attendance + exam backend. **Rust (edition 2024) · axum · SurrealDB 3 (embedded surrealkv) · tokio.**
4+
5+Session-cookie auth with four hierarchical roles (`student < teacher < manager
6+< admin`). Notes are per-user. Attendance is event + attendees: create an event,
7+then mark users present / absent / late / excused.
8+
9+Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)
10+constructed only after its restrictions pass — invalid input can't be
11+represented. Those same types derive `surrealdb::types::SurrealValue`, so one
12+typed value flows from HTTP request into the `SCHEMAFULL` database. Record ids
13+are ULIDs (time-sortable).
14+
15+## Run
16+
17+```sh
18+cp .env.example .env # optional
19+cargo run
20+```
21+
22+Boots on `http://127.0.0.1:8080`, storing data in `./data/hezarfen.db`
23+(embedded surrealkv — no external DB server). Interactive API docs (Swagger UI)
24+are served at `/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`.
25+
26+## Run in a container (podman)
27+
28+```sh
29+podman compose up -d --build # build + start, http://127.0.0.1:8080
30+podman compose logs -f backend
31+podman compose down # stop (data survives in the volume)
32+```
33+
34+The `Containerfile` is a two-stage build (Rust builder with cargo cache
35+mounts, `debian:trixie-slim` runtime, non-root user). Since the database is
36+embedded there is only one service; its data lives in the named volume
37+`hezarfen-data`, mounted at `/data`. `HOST` is forced to `0.0.0.0` inside the
38+container so the published port works. Production knobs (`COOKIE_SECURE`,
39+`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in
40+`compose.yaml` — uncomment as needed. Works with `docker compose` too.
41+
42+Without compose:
43+
44+```sh
45+podman build -t hezarfen-backend .
46+podman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend
47+```
48+
49+## Auth model
50+
51+Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored
52+server-side). Send it back on later requests. Every endpoint below whose `Auth`
53+column names a role requires a valid session; the ones marked `no` (`/health`,
54+the docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent —
55+it clears the session if one is present). Set `COOKIE_SECURE=true` when serving
56+behind TLS to add the cookie's `Secure` attribute.
57+
58+## Rate limiting
59+
60+Requests are limited per client IP over a fixed 60-second window, in two tiers:
61+`/auth/login` + `/auth/register` get a strict budget
62+(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,
63+and every route — Swagger included — shares a generous catch-all
64+(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with
65+a `Retry-After` header (seconds). Set a limit to `0` to disable that tier —
66+useful for load tests.
67+
68+Behind a reverse proxy every connection carries the proxy's address, so also
69+set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry
70+(the one the proxy itself appends). Leave it off when clients reach the server
71+directly — the header is client-forged in that case.
72+
73+## CORS
74+
75+Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`
76+(browsers refuse it on credentialed requests), so the server always advertises
77+`Access-Control-Allow-Credentials: true` and, by default, reflects the
78+request's `Origin` — dev-friendly, effectively open. In production set
79+`CORS_ALLOWED_ORIGINS` to a comma-separated allowlist to restrict which
80+browser origins may call the API.
81+
82+## Roles & access control
83+
84+Every user has one of four roles, ranked lowest to highest:
85+
86+```
87+student < teacher < manager < admin
88+```
89+
90+The check is **hierarchical** — a higher role satisfies any lower requirement
91+(an admin can do anything a teacher can). New accounts always register as
92+`student`; a role read is re-checked on every request, so a role change takes
93+effect on the user's very next call (no re-login).
94+
95+| Action | Minimum role | Notes |
96+|------------------------------------------|--------------|-----------------------------------------------|
97+| Register / login / view own account | (any) | Registration always creates a `student` |
98+| View events, roster, own notes; CRUD notes | student | Everyone can read events and keep notes |
99+| Mark **own** attendance | student | Anyone can mark themselves |
100+| Mark **another user's** attendance | teacher | |
101+| Create events; remove attendance rows | teacher | |
102+| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |
103+| View exams; read **own** exam result | student | |
104+| Create exams; grade students; view all results | teacher | Grading never targets oneself — teachers grade students |
105+| Edit / delete an exam | teacher | Only the **creator**, or a `manager`+ for any exam |
106+| List users; change a user's role | admin | An admin cannot change **their own** role |
107+
108+### Bootstrapping the first admin
109+
110+There is no self-service path to `admin` — the first one is granted out-of-band,
111+directly in the database. Register the account through the API, then (with the
112+server stopped, since the embedded store is single-writer) run:
113+
114+```surql
115+UPDATE user SET role = 'admin' WHERE username = 'ada';
116+```
117+
118+against the embedded database — e.g. with the SurrealDB CLI pointed at the same
119+surrealkv path (`./data/hezarfen.db`, namespace/database `hezarfen`). That admin
120+can then promote everyone else through `PATCH /users/{id}/role`.
121+
122+## Endpoints
123+
124+`Auth` is the minimum role; `no` means no session required, `student` means any
125+logged-in user.
126+
127+| Method | Path | Auth | Description |
128+|--------|----------------------------------|---------|---------------------------------|
129+| GET | `/health` | no | Liveness check |
130+| GET | `/` | no | Same as `/health` |
131+| GET | `/swagger` | no | Interactive API docs (Swagger UI) |
132+| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |
133+| POST | `/auth/register` | no | `{username, password}` (new users are `student`) |
134+| POST | `/auth/login` | no | `{username, password}` -> cookie|
135+| POST | `/auth/logout` | no | Clear session (no-op if none) |
136+| GET | `/auth/me` | student | Current user (incl. `role`) |
137+| GET | `/users` | admin | List all users |
138+| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role |
139+| POST | `/notes` | student | `{title, content?}` |
140+| GET | `/notes` | student | List own notes |
141+| GET | `/notes/{id}` | student | Get own note |
142+| PATCH | `/notes/{id}` | student | `{title?, content?}` |
143+| DELETE | `/notes/{id}` | student | Delete own note |
144+| POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` |
145+| GET | `/events` | student | List all events |
146+| GET | `/events/{id}` | student | Get event |
147+| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any) |
148+| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |
149+| POST | `/events/{id}/attendance` | student | `{status, user_id?}` — self if `user_id` omitted; marking others needs teacher+ |
150+| GET | `/events/{id}/attendance` | student | List attendance for event |
151+| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |
152+| POST | `/exams` | teacher | `{title, description?, kind}` (creator owns it) |
153+| GET | `/exams` | student | List all exams |
154+| GET | `/exams/{id}` | student | Get exam |
155+| PATCH | `/exams/{id}` | teacher | Edit exam (creator, or manager+ for any) |
156+| DELETE | `/exams/{id}` | teacher | Delete exam + its results (creator, or manager+) |
157+| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade a student (upsert) |
158+| GET | `/exams/{id}/results` | teacher | List every result for the exam |
159+| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
160+| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result |
161+
162+`status` ∈ `present | absent | late | excused`. `kind` ∈ `homework | quiz`.
163+`role` ∈ `student | teacher | manager | admin`. Ids in responses are ULIDs.
164+An exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,
165+never in a `note`. Students never grade anyone — grading is teacher+; a
166+student reads just their own mark via `GET /exams/{id}/result`.
167+Event `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both
168+are given, `ends_at` must not precede `starts_at` (else `400`). On `PATCH`, an
169+omitted time keeps its value and an explicit `null` clears it.
170+Reading a child collection of a missing parent (`/events/{id}/attendance`,
171+`/exams/{id}/results`) is a `404`, not an empty list.
172+
173+## Quick tour (curl)
174+
175+```sh
176+BASE=http://127.0.0.1:8080
177+JAR=/tmp/hz.cookies
178+
179+curl -s $BASE/auth/register -H 'content-type: application/json' \
180+ -d '{"username":"ali","password":"secret1"}'
181+
182+curl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \
183+ -d '{"username":"ali","password":"secret1"}'
184+
185+# notes
186+curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \
187+ -d '{"title":"first","content":"hello"}'
188+curl -s -b $JAR $BASE/notes
189+
190+# events + attendance
191+# Creating events needs teacher+; grant it first (see "Bootstrapping" above —
192+# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.
193+EV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \
194+ -d '{"title":"standup"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
195+curl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \
196+ -d '{"status":"present"}'
197+curl -s -b $JAR $BASE/events/$EV/attendance
198+```
199+
200+## Layout
201+
202+```
203+src/
204+ main.rs bootstrap: config, db, router, serve
205+ lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health
206+ config.rs env-sourced Config
207+ constant.rs validation limits
208+ validate.rs field validators (used by every newtype's try_new)
209+ error.rs ValidationError + AppError -> HTTP responses
210+ database.rs embedded surrealkv connect + SCHEMAFULL migration
211+ rate_limit.rs fixed-window per-IP limiter (both tiers) + middleware
212+ state.rs AppState { db, cookie_secure, rate_limit }
213+ domain/ validated newtypes + entities (derive SurrealValue),
214+ each owning its persistence
215+ user.rs UserId · Username · Password · PasswordHash · User (has role)
216+ role.rs Role enum (student < teacher < manager < admin), at_least()
217+ session.rs SessionId · SessionToken · Session (7-day expiry)
218+ timestamp.rs Timestamp (unix-millisecond instant)
219+ note.rs NoteId · NoteTitle · NoteContent · Note
220+ event.rs EventId · EventTitle · EventDescription · Event
221+ attendance.rs AttendanceId · AttendanceStatus · Attendance
222+ exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · Exam
223+ exam_result.rs ExamResultId · Mark · ExamResult (one row per exam+user)
224+ web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +
225+ auth extractors
226+ extractor.rs CurrentUser · RequireTeacher · RequireAdmin
227+ dto.rs shared UserResponse (id · username · role) + Role schema
228+ auth.rs users.rs notes.rs events.rs exams.rs
229+```
230+
231+Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory
232+db), rate-limit (both tiers, proxy-header and peer-address keying, shipped
233+limits over every route), e2e (real TCP + reqwest cookie jar), persistence
234+(tempfile file engine, including close + reopen).