/// The application: routes written against `log`, `users` and `fs` effects. /// `main` runs them with production handlers (the console, session store actor /// and real filesystem); the tests run them with lexical mocks. import argon2 import assets import credentials.{type Password, type Username} import std/bytes import std/file.{type fs} import std/http.{type Request, type Response, Request, Response, Whole} import std/http/cookie import std/http/sse import std/io import std/option import std/process.{type proc} import std/random.{type random} import std/result import std/string import std/test.{assert_equal} import views pub type User { User(name: String, password_hash: String) } /// Why a registration failed. (A name or password too short never gets /// this far: see `credentials`.) @derive Eq Show pub type RegisterError { NameTaken /// The password could not be hashed: the reason. , HashFailed(String) } /// Why a login failed. pub type LoginError { UnknownUser , WrongPassword /// The stored hash cannot be checked: the reason. , BadHash(String) } /// Logging. pub effect log { fn log :: message: String -> () } /// Users and sessions. pub effect users { fn find_user :: name: String -> Option /// `Error(NameTaken)` if the name is taken. fn add_user :: user: User -> Result<(), RegisterError> /// A new session for `name`; its token. fn new_session :: name: String -> String fn session_user :: token: String -> Option } /// Password hashing cost: 2 passes over 19 MiB (OWASP's minimum for /// Argon2id). pub fn hashing :: -> argon2.Params { argon2.Params(t_cost: 2, m_cost_kib: 19456, parallelism: 1) } pub fn route :: req: Request -> Response / { log "{req.method} {req.path}" match (req.method, req.path) { ("GET", "/") -> match current_user req { Some(name) -> http.html (views.home name) , None -> http.html (views.login "") } , ("POST", "/login") -> login (http.form_body req) , ("POST", "/register") -> register (http.form_body req) , ("GET", "/logout") -> redirect "/" (cookie.expire "session") // Files on disk, from ./static/ next to the server's working // directory (std/file) — the stylesheet is /static/style.css. , ("GET", path) if string.starts_with path "/static/" -> assets.static_file path , ("GET", "/boom") -> panic "boom: a handler crashed (the server keeps running)" // A streamed page (ADR 0053): the shell first, each item as it // "finishes", the closing tags last — the end-to-end test reads the // chunks. , ("GET", "/stream") -> http.stream "text/html; charset=utf-8" fn w { stream_page w } // Server-Sent Events (ADR 0053 §1b): a heartbeat comment, then four // ticks, then the stream ends (the end-to-end test reads the frames). , ("GET", "/events") -> sse.stream fn w { events_page w } , _ -> http.not_found () } } /// The SSE demo stream: a heartbeat comment, then four ticks 50 ms /// apart, then done. fn events_page :: w: http.Writer -> () / { let _ = sse.send w (sse.comment "hb") sse_ticks w 0 } fn sse_ticks :: w: http.Writer n: Int -> () / { if n < 4 { process.sleep 50 match sse.send w (sse.frame sse.Event(..sse.new_event "tick {n}", id: Some("{n}"))) { Ok(()) -> sse_ticks w (n + 1) // The client is gone: the stream ends. , Error(_) -> () } } else { () } } /// The streamed demo page: the shell, three items with a small wait /// between them (as if components took time), the closing tags. fn stream_page :: w: http.Writer -> () / { let opening = "streamed
    " match http.write_string w opening { Ok(()) -> stream_rest w , Error(reason) -> io.println "[log] stream stopped: {reason}" } } fn stream_rest :: w: http.Writer -> () / { stream_items w 3 // An empty write sends nothing: its frame would end the body. let _ = http.write_string w "" let _ = http.write_string w "
" () } fn stream_items :: w: http.Writer n: Int -> () / { if n > 0 { process.sleep 50 let _ = http.write_string w "
  • item {4 - n}
  • " stream_items w (n - 1) } else { () } } fn login :: fields { let name = field fields "name" match check_password name (field fields "password") { Ok(()) -> { log "login {name}" start_session name } , Error(BadHash(reason)) -> { log "cannot check the password of {name}: {reason}" http.text 500 "cannot check the password" } // The same answer for both, so it does not tell which names exist. , Error(UnknownUser) | Error(WrongPassword) -> { log "failed login {name}" with_status 401 (http.html (views.login "Wrong name or password.")) } } } fn check_password :: name: String password: String -> Result<(), LoginError> / { match find_user name { None -> { // Check the password anyway, against a hash of no one's, so that a // login takes as long whether or not the name exists. let _ = argon2.verify password (decoy_hash ()) Error(UnknownUser) } , Some(user) -> { use matches <- result.try ( argon2.verify password user.password_hash |> result.map_error BadHash ) if matches { Ok(()) } else { Error(WrongPassword) } } } } /// A hash made with `hashing()` from a password no one uses, to check /// unknown names against (a test checks its parameters match `hashing()`). pub fn decoy_hash :: -> String { "$argon2id$v=19$m=19456,t=2,p=1$bG91aXNlLWRlbW8tZGVjb3k$T+0onNjn9MFpeIw/gphM0Kvy8zmuLm7EfjuE6ip94Io" } fn register :: fields { // The form is checked here, once: past this point a name and a password // are a `Username` and a `Password`, which only `credentials` can make. let checked = ( credentials.username (field fields "name") , credentials.password (field fields "password") ) let (name, password) = match checked { (Some(name), Some(password)) -> (name, password) , _ -> return with_status 400 (http.html (views.login "Names need 2 characters and passwords 8.")) } match new_user name password { Ok(()) -> { log "registered {name}" start_session (credentials.name name) } , Error(NameTaken) -> with_status 409 (http.html (views.login "That name is taken.")) , Error(HashFailed(reason)) -> http.text 500 reason } } /// Register `name`: no length to check, its type says it was. fn new_user :: name: Username password: Password -> Result<(), RegisterError> / { use hash <- result.try ( argon2.hash_password (credentials.secret password) (hashing ()) |> result.map_error HashFailed ) add_user User(credentials.name name, hash) } /// Users and sessions for the tests here: no users, and one session, /// `abc`, for `ada`. fn with_one_session :: action: fn() -> a / -> a / { handle { action () } with { find_user _ -> None , add_user _ -> Ok(()) , new_session _ -> "abc" , session_user token -> if token == "abc" { Some("ada") } else { None } } } /// What `new_user` answers for valid credentials, with one session open. fn added :: name: String password: String -> Result<(), RegisterError> / { use <- with_one_session match (credentials.username name, credentials.password password) { (Some(name), Some(password)) -> new_user name password , _ -> panic "invalid credentials in a test" } } @test fn valid_credentials_register :: -> () / { assert_equal (added "ab" "12345678") Ok(()) } fn start_session :: name: String -> Response / { redirect "/" (cookie.new "session" (new_session name)) } /// The user of the request's session cookie, if it is valid. fn current_user :: req: Request -> Option / { match cookie.cookie req "session" { Some(token) -> session_user token, None -> None } } fn with_cookie :: cookie_header: String -> Request { Request("GET", "/", [("Cookie", cookie_header)], bytes.empty ()) } @test fn the_session_cookie_is_found_among_others :: { use <- with_one_session assert_equal (current_user (with_cookie "theme=dark;session=abc; lang=fr")) Some("ada") } @test fn without_a_session_cookie_there_is_no_user :: { use <- with_one_session assert_equal (current_user Request("GET", "/", [], bytes.empty ())) None assert_equal (current_user (with_cookie "theme=dark")) None assert_equal (current_user (with_cookie "xsession=abc")) None } @test fn an_unknown_session_token_has_no_user :: { use <- with_one_session assert_equal (current_user (with_cookie "session=abd")) None assert_equal (current_user (with_cookie "session=")) None } @test fn cookie_parsing_follows_rfc_6265 :: { let req = Request( "GET" , "/" , [("Cookie", "a=1; b=two=2"), ("cookie", "c=\"three\"")] , bytes.empty () ) // A value may hold `=` (a pair splits on its first) and be "quoted"; // a request can send several Cookie headers. assert_equal (cookie.cookies req) [("a", "1"), ("b", "two=2"), ("c", "three")] assert_equal (cookie.cookie req "b") Some("two=2") assert_equal (cookie.cookie req "nope") None } @test fn malformed_cookie_pairs_are_skipped :: { let req = Request( "GET" , "/" , [("Cookie", "no-equals; =empty-name; ok=1")] , bytes.empty () ) assert_equal (cookie.cookies req) [("ok", "1")] } fn field :: fields name { http.field fields name |> option.unwrap_or "" } @test fn a_missing_field_is_empty :: { let fields = [("name", "ada"), ("password", "")] assert_equal (field fields "name") "ada" assert_equal (field fields "password") "" assert_equal (field fields "email") "" } fn redirect :: to: String c: cookie.SetCookie -> Response { cookie.set_cookie Response(303, [("Location", to)], Whole(bytes.empty ())) c } @test fn a_redirect_sets_its_location_and_cookie :: { let resp = redirect "/home" (cookie.new "session" "abc") assert_equal resp.status 303 assert_equal resp.headers [ ("Location", "/home") , ("Set-Cookie", "session=abc; Path=/; Secure; HttpOnly; SameSite=Lax") ] assert_equal (bytes.length (option.unwrap_or (http.whole_body resp) (bytes.empty ()))) 0 } fn with_status :: status: Int resp: Response -> Response { Response(..resp, status: status) } @test fn with_status_keeps_the_headers_and_body :: { let resp = with_status 401 (http.text 200 "no") assert_equal resp.status 401 assert_equal resp.headers [("Content-Type", "text/plain; charset=utf-8")] assert_equal ( bytes.to_string_lossy (option.unwrap_or (http.whole_body resp) (bytes.empty ())) ) "no" }