louise
The Louise language: compiler, runtime, std, tooling
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#115 · main · 21 min 41 s
0Étoiles
0Forks
40Issues
| 1 | /// The application: routes written against two effects, `log` and |
| 2 | /// `users`. `main` runs them with production handlers (the console and |
| 3 | /// the session store actor); the tests run them with mocks. |
| 4 | |
| 5 | import argon2 |
| 6 | import assets |
| 7 | import credentials.{type Password, type Username} |
| 8 | import std/bytes |
| 9 | import std/http.{type Request, type Response, Request, Response, Whole} |
| 10 | import std/http/cookie |
| 11 | import std/http/sse |
| 12 | import std/io |
| 13 | import std/option |
| 14 | import std/process.{type proc} |
| 15 | import std/random.{type random} |
| 16 | import std/result |
| 17 | import std/string |
| 18 | import std/test.{assert_equal} |
| 19 | import views |
| 20 | |
| 21 | pub type User { User(name: String, password_hash: String) } |
| 22 | |
| 23 | /// Why a registration failed. (A name or password too short never gets |
| 24 | /// this far: see `credentials`.) |
| 25 | @derive Eq Show |
| 26 | pub type RegisterError |
| 27 | { NameTaken |
| 28 | /// The password could not be hashed: the reason. |
| 29 | , HashFailed(String) |
| 30 | } |
| 31 | |
| 32 | /// Why a login failed. |
| 33 | pub type LoginError |
| 34 | { UnknownUser |
| 35 | , WrongPassword |
| 36 | /// The stored hash cannot be checked: the reason. |
| 37 | , BadHash(String) |
| 38 | } |
| 39 | |
| 40 | /// Logging. |
| 41 | pub effect log |
| 42 | { |
| 43 | fn log :: message: String -> () |
| 44 | } |
| 45 | |
| 46 | /// Users and sessions. |
| 47 | pub effect users |
| 48 | { |
| 49 | fn find_user :: name: String -> Option<User> |
| 50 | /// `Error(NameTaken)` if the name is taken. |
| 51 | fn add_user :: user: User -> Result<(), RegisterError> |
| 52 | /// A new session for `name`; its token. |
| 53 | fn new_session :: name: String -> String |
| 54 | fn session_user :: token: String -> Option<String> |
| 55 | } |
| 56 | |
| 57 | /// Password hashing cost: 2 passes over 19 MiB (OWASP's minimum for |
| 58 | /// Argon2id). |
| 59 | pub fn hashing :: -> argon2.Params |
| 60 | { |
| 61 | argon2.Params(t_cost: 2, m_cost_kib: 19456, parallelism: 1) |
| 62 | } |
| 63 | |
| 64 | pub fn route :: req: Request -> Response / <log, users, io, ffi, random> |
| 65 | { |
| 66 | log "{req.method} {req.path}" |
| 67 | match (req.method, req.path) |
| 68 | { ("GET", "/") -> match current_user req |
| 69 | { Some(name) -> http.html (views.home name) |
| 70 | , None -> http.html (views.login "") |
| 71 | } |
| 72 | , ("POST", "/login") -> login (http.form_body req) |
| 73 | , ("POST", "/register") -> register (http.form_body req) |
| 74 | , ("GET", "/logout") -> redirect "/" (cookie.expire "session") |
| 75 | // Files on disk, from ./static/ next to the server's working |
| 76 | // directory (std/file) — the stylesheet is /static/style.css. |
| 77 | , ("GET", path) if string.starts_with path "/static/" -> |
| 78 | assets.static_file path |
| 79 | , ("GET", "/boom") -> |
| 80 | panic "boom: a handler crashed (the server keeps running)" |
| 81 | // A streamed page (ADR 0053): the shell first, each item as it |
| 82 | // "finishes", the closing tags last — the end-to-end test reads the |
| 83 | // chunks. |
| 84 | , ("GET", "/stream") -> |
| 85 | http.stream "text/html; charset=utf-8" fn w { stream_page w } |
| 86 | // Server-Sent Events (ADR 0053 §1b): a heartbeat comment, then four |
| 87 | // ticks, then the stream ends (the end-to-end test reads the frames). |
| 88 | , ("GET", "/events") -> sse.stream fn w { events_page w } |
| 89 | , _ -> http.not_found () |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// The SSE demo stream: a heartbeat comment, then four ticks 50 ms |
| 94 | /// apart, then done. |
| 95 | fn events_page :: w: http.Writer -> () / <io, proc> |
| 96 | { |
| 97 | let _ = sse.send w (sse.comment "hb") |
| 98 | sse_ticks w 0 |
| 99 | } |
| 100 | |
| 101 | fn sse_ticks :: w: http.Writer n: Int -> () / <io, proc> |
| 102 | { |
| 103 | if n < 4 |
| 104 | { |
| 105 | process.sleep 50 |
| 106 | match sse.send |
| 107 | w |
| 108 | (sse.frame sse.Event(..sse.new_event "tick {n}", id: Some("{n}"))) |
| 109 | { Ok(()) -> sse_ticks w (n + 1) |
| 110 | // The client is gone: the stream ends. |
| 111 | , Error(_) -> () |
| 112 | } |
| 113 | } |
| 114 | else |
| 115 | { |
| 116 | () |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// The streamed demo page: the shell, three items with a small wait |
| 121 | /// between them (as if components took time), the closing tags. |
| 122 | fn stream_page :: w: http.Writer -> () / <io, proc> |
| 123 | { |
| 124 | let opening = "<!doctype html><html><head><title>streamed</title></head><body><ul>" |
| 125 | match http.write_string w opening |
| 126 | { Ok(()) -> stream_rest w |
| 127 | , Error(reason) -> io.println "[log] stream stopped: {reason}" |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | fn stream_rest :: w: http.Writer -> () / <io, proc> |
| 132 | { |
| 133 | stream_items w 3 |
| 134 | // An empty write sends nothing: its frame would end the body. |
| 135 | let _ = http.write_string w "" |
| 136 | let _ = http.write_string w "</ul></body></html>" |
| 137 | () |
| 138 | } |
| 139 | |
| 140 | fn stream_items :: w: http.Writer n: Int -> () / <io, proc> |
| 141 | { |
| 142 | if n > 0 |
| 143 | { |
| 144 | process.sleep 50 |
| 145 | let _ = http.write_string w "<li>item {4 - n}</li>" |
| 146 | stream_items w (n - 1) |
| 147 | } |
| 148 | else |
| 149 | { |
| 150 | () |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn login :: fields |
| 155 | { |
| 156 | let name = field fields "name" |
| 157 | match check_password name (field fields "password") |
| 158 | { Ok(()) -> |
| 159 | { |
| 160 | log "login {name}" |
| 161 | start_session name |
| 162 | } |
| 163 | , Error(BadHash(reason)) -> |
| 164 | { |
| 165 | log "cannot check the password of {name}: {reason}" |
| 166 | http.text 500 "cannot check the password" |
| 167 | } |
| 168 | // The same answer for both, so it does not tell which names exist. |
| 169 | , Error(UnknownUser) | Error(WrongPassword) -> |
| 170 | { |
| 171 | log "failed login {name}" |
| 172 | with_status 401 (http.html (views.login "Wrong name or password.")) |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn check_password :: |
| 178 | name: String |
| 179 | password: String |
| 180 | -> Result<(), LoginError> / <users, ffi> |
| 181 | { |
| 182 | match find_user name |
| 183 | { None -> |
| 184 | { |
| 185 | // Check the password anyway, against a hash of no one's, so that a |
| 186 | // login takes as long whether or not the name exists. |
| 187 | let _ = argon2.verify password (decoy_hash ()) |
| 188 | Error(UnknownUser) |
| 189 | } |
| 190 | , Some(user) -> |
| 191 | { |
| 192 | use matches <- |
| 193 | result.try |
| 194 | ( argon2.verify password user.password_hash |
| 195 | |> result.map_error BadHash |
| 196 | ) |
| 197 | if matches |
| 198 | { |
| 199 | Ok(()) |
| 200 | } |
| 201 | else |
| 202 | { |
| 203 | Error(WrongPassword) |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /// A hash made with `hashing()` from a password no one uses, to check |
| 210 | /// unknown names against (a test checks its parameters match `hashing()`). |
| 211 | pub fn decoy_hash :: -> String |
| 212 | { |
| 213 | "$argon2id$v=19$m=19456,t=2,p=1$bG91aXNlLWRlbW8tZGVjb3k$T+0onNjn9MFpeIw/gphM0Kvy8zmuLm7EfjuE6ip94Io" |
| 214 | } |
| 215 | |
| 216 | fn register :: fields |
| 217 | { |
| 218 | // The form is checked here, once: past this point a name and a password |
| 219 | // are a `Username` and a `Password`, which only `credentials` can make. |
| 220 | let checked = |
| 221 | ( credentials.username (field fields "name") |
| 222 | , credentials.password (field fields "password") |
| 223 | ) |
| 224 | let (name, password) = match checked |
| 225 | { (Some(name), Some(password)) -> (name, password) |
| 226 | , _ -> |
| 227 | return with_status |
| 228 | 400 |
| 229 | (http.html (views.login "Names need 2 characters and passwords 8.")) |
| 230 | } |
| 231 | match new_user name password |
| 232 | { Ok(()) -> |
| 233 | { |
| 234 | log "registered {name}" |
| 235 | start_session (credentials.name name) |
| 236 | } |
| 237 | , Error(NameTaken) -> |
| 238 | with_status 409 (http.html (views.login "That name is taken.")) |
| 239 | , Error(HashFailed(reason)) -> http.text 500 reason |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// Register `name`: no length to check, its type says it was. |
| 244 | fn new_user :: |
| 245 | name: Username |
| 246 | password: Password |
| 247 | -> Result<(), RegisterError> / <users, ffi, random> |
| 248 | { |
| 249 | use hash <- |
| 250 | result.try |
| 251 | ( argon2.hash_password (credentials.secret password) (hashing ()) |
| 252 | |> result.map_error HashFailed |
| 253 | ) |
| 254 | add_user User(credentials.name name, hash) |
| 255 | } |
| 256 | |
| 257 | /// Users and sessions for the tests here: no users, and one session, |
| 258 | /// `abc`, for `ada`. |
| 259 | fn with_one_session :: action: fn() -> a / <users | e> -> a / <e> |
| 260 | { |
| 261 | handle |
| 262 | { |
| 263 | action () |
| 264 | } |
| 265 | with |
| 266 | { find_user _ -> None |
| 267 | , add_user _ -> Ok(()) |
| 268 | , new_session _ -> "abc" |
| 269 | , session_user token -> if token == "abc" { Some("ada") } else { None } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// What `new_user` answers for valid credentials, with one session open. |
| 274 | fn added :: |
| 275 | name: String |
| 276 | password: String |
| 277 | -> Result<(), RegisterError> / <ffi, random> |
| 278 | { |
| 279 | use <- with_one_session |
| 280 | match (credentials.username name, credentials.password password) |
| 281 | { (Some(name), Some(password)) -> new_user name password |
| 282 | , _ -> panic "invalid credentials in a test" |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | @test |
| 287 | fn valid_credentials_register :: -> () / <ffi, random> |
| 288 | { |
| 289 | assert_equal (added "ab" "12345678") Ok(()) |
| 290 | } |
| 291 | |
| 292 | fn start_session :: name: String -> Response / <users> |
| 293 | { |
| 294 | redirect "/" (cookie.new "session" (new_session name)) |
| 295 | } |
| 296 | |
| 297 | /// The user of the request's session cookie, if it is valid. |
| 298 | fn current_user :: req: Request -> Option<String> / <users> |
| 299 | { |
| 300 | match cookie.cookie req "session" |
| 301 | { Some(token) -> session_user token, None -> None } |
| 302 | } |
| 303 | |
| 304 | fn with_cookie :: cookie_header: String -> Request |
| 305 | { |
| 306 | Request("GET", "/", [("Cookie", cookie_header)], bytes.empty ()) |
| 307 | } |
| 308 | |
| 309 | @test |
| 310 | fn the_session_cookie_is_found_among_others :: |
| 311 | { |
| 312 | use <- with_one_session |
| 313 | assert_equal |
| 314 | (current_user (with_cookie "theme=dark;session=abc; lang=fr")) |
| 315 | Some("ada") |
| 316 | } |
| 317 | |
| 318 | @test |
| 319 | fn without_a_session_cookie_there_is_no_user :: |
| 320 | { |
| 321 | use <- with_one_session |
| 322 | assert_equal (current_user Request("GET", "/", [], bytes.empty ())) None |
| 323 | assert_equal (current_user (with_cookie "theme=dark")) None |
| 324 | assert_equal (current_user (with_cookie "xsession=abc")) None |
| 325 | } |
| 326 | |
| 327 | @test |
| 328 | fn an_unknown_session_token_has_no_user :: |
| 329 | { |
| 330 | use <- with_one_session |
| 331 | assert_equal (current_user (with_cookie "session=abd")) None |
| 332 | assert_equal (current_user (with_cookie "session=")) None |
| 333 | } |
| 334 | |
| 335 | @test |
| 336 | fn cookie_parsing_follows_rfc_6265 :: |
| 337 | { |
| 338 | let req = |
| 339 | Request( "GET" |
| 340 | , "/" |
| 341 | , [("Cookie", "a=1; b=two=2"), ("cookie", "c=\"three\"")] |
| 342 | , bytes.empty () |
| 343 | ) |
| 344 | // A value may hold `=` (a pair splits on its first) and be "quoted"; |
| 345 | // a request can send several Cookie headers. |
| 346 | assert_equal (cookie.cookies req) [("a", "1"), ("b", "two=2"), ("c", "three")] |
| 347 | assert_equal (cookie.cookie req "b") Some("two=2") |
| 348 | assert_equal (cookie.cookie req "nope") None |
| 349 | } |
| 350 | |
| 351 | @test |
| 352 | fn malformed_cookie_pairs_are_skipped :: |
| 353 | { |
| 354 | let req = |
| 355 | Request( "GET" |
| 356 | , "/" |
| 357 | , [("Cookie", "no-equals; =empty-name; ok=1")] |
| 358 | , bytes.empty () |
| 359 | ) |
| 360 | assert_equal (cookie.cookies req) [("ok", "1")] |
| 361 | } |
| 362 | |
| 363 | fn field :: fields name |
| 364 | { |
| 365 | http.field fields name |> option.unwrap_or "" |
| 366 | } |
| 367 | |
| 368 | @test |
| 369 | fn a_missing_field_is_empty :: |
| 370 | { |
| 371 | let fields = [("name", "ada"), ("password", "")] |
| 372 | assert_equal (field fields "name") "ada" |
| 373 | assert_equal (field fields "password") "" |
| 374 | assert_equal (field fields "email") "" |
| 375 | } |
| 376 | |
| 377 | fn redirect :: to: String c: cookie.SetCookie -> Response |
| 378 | { |
| 379 | cookie.set_cookie Response(303, [("Location", to)], Whole(bytes.empty ())) c |
| 380 | } |
| 381 | |
| 382 | @test |
| 383 | fn a_redirect_sets_its_location_and_cookie :: |
| 384 | { |
| 385 | let resp = redirect "/home" (cookie.new "session" "abc") |
| 386 | assert_equal resp.status 303 |
| 387 | assert_equal |
| 388 | resp.headers |
| 389 | [ ("Location", "/home") |
| 390 | , ("Set-Cookie", "session=abc; Path=/; Secure; HttpOnly; SameSite=Lax") |
| 391 | ] |
| 392 | assert_equal |
| 393 | (bytes.length (option.unwrap_or (http.whole_body resp) (bytes.empty ()))) |
| 394 | 0 |
| 395 | } |
| 396 | |
| 397 | fn with_status :: status: Int resp: Response -> Response |
| 398 | { |
| 399 | Response(..resp, status: status) |
| 400 | } |
| 401 | |
| 402 | @test |
| 403 | fn with_status_keeps_the_headers_and_body :: |
| 404 | { |
| 405 | let resp = with_status 401 (http.text 200 "no") |
| 406 | assert_equal resp.status 401 |
| 407 | assert_equal resp.headers [("Content-Type", "text/plain; charset=utf-8")] |
| 408 | assert_equal |
| 409 | ( bytes.to_string_lossy |
| 410 | (option.unwrap_or (http.whole_body resp) (bytes.empty ())) |
| 411 | ) |
| 412 | "no" |
| 413 | } |