// The routes, run with mock handlers: no server, no store actor. Run with // `louise test --native` (argon2 is a native dependency). import app. { type User , type log , type users , NameTaken , User , add_user , find_user , log , new_session , session_user } import argon2 import std/bytes import std/dict import std/http.{type Request, type Response, Request} import std/http/cookie import std/list import std/option import std/random.{type random} import std/ref import std/result import std/string import std/test.{assert, assert_equal} /// Collect the log instead of printing it. fn with_mock_log :: action: fn() -> a / -> (a, List) / { region { let lines = ref.new [] let res = handle { action () } with { log message -> ref.set lines [message, ..ref.get lines] } (res, list.reverse (ref.get lines)) } } /// Users and sessions in memory. Session tokens are predictable here. fn with_mock_users :: seed: List action: fn() -> a / -> a / { region { let users = ref.new (dict.from_list (list.map seed fn u { (u.name, u) })) let sessions = ref.new (dict.empty ()) handle { action () } with { find_user name -> dict.get (ref.get users) name , add_user user -> if dict.has (ref.get users) user.name { Error(NameTaken) } else { ref.set users (dict.insert (ref.get users) user.name user) Ok(()) } , new_session name -> { let token = "token-{name}" ref.set sessions (dict.insert (ref.get sessions) token name) token } , session_user token -> dict.get (ref.get sessions) token } } } fn ada :: -> User / { match argon2.hash "lovelace" "seed-salt" argon2.Params(t_cost: 1, m_cost_kib: 64, parallelism: 1) { Ok(hash) -> User("ada", hash), Error(e) -> panic e } } fn get :: path: String cookie_header: String -> Request { Request( "GET" , path , if cookie_header == "" { [] } else { [("Cookie", cookie_header)] } , bytes.empty () ) } fn post :: path: String body: String -> Request { Request("POST", path, [], bytes.from_string body) } fn header :: resp: Response name: String -> String { match list.filter resp.headers fn h { h.0 == name } { [(_, v), ..] -> v, _ -> "" } } /// The response body as text. fn text :: resp: Response -> String { bytes.to_string_lossy (option.unwrap_or (http.whole_body resp) (bytes.empty ())) } fn at :: xs: List i: Int -> Response { match xs { [x, ..rest] -> if i == 0 { x } else { at rest (i - 1) } , [] -> panic "no response {i}" } } /// Run requests one after another against the same mock users, with /// seeded randomness: the same session tokens and salts on every run. fn run :: requests: List -> (List, List) / { // `eve`'s stored hash is corrupted. let seed = [ada (), User("eve", "not a hash")] use <- random.with_seed 1 use <- with_mock_log use <- with_mock_users seed list.map requests app.route } @test fn anonymous_visitors_get_the_login_page :: -> () / { let (rs, logs) = run [get "/" ""] let home = at rs 0 assert_equal home.status 200 assert (string.contains (text home) "Log in") "login page" assert_equal logs ["GET /"] } @test fn the_stylesheet_is_served_from_disk :: -> () / { let (rs, logs) = run [get "/static/style.css" ""] let style = at rs 0 assert_equal style.status 200 assert_equal (header style "Content-Type") "text/css; charset=utf-8" assert (string.contains (text style) "backdrop-filter") "the glass panels" assert_equal logs ["GET /static/style.css"] } @test fn static_files_are_served_from_disk :: -> () / { let (rs, logs) = run [get "/static/robots.txt" ""] let robots = at rs 0 assert_equal robots.status 200 assert_equal (header robots "Content-Type") "text/plain; charset=utf-8" assert (string.contains (text robots) "User-agent:") "the file's content" assert_equal logs ["GET /static/robots.txt"] } @test fn a_missing_static_file_and_a_traversal_are_404s :: -> () / { let (rs, _) = run [get "/static/nope.txt" "", get "/static/../louise.toml" ""] assert_equal ((at rs 0).status) 404 assert_equal ((at rs 1).status) 404 } @test fn a_wrong_password_is_rejected :: -> () / { let (rs, logs) = run [post "/login" "name=ada&password=nope"] let resp = at rs 0 assert_equal resp.status 401 assert (string.contains (text resp) "Wrong name or password.") "error message" assert_equal logs ["POST /login", "failed login ada"] } @test fn an_unknown_user_gets_the_same_answer :: -> () / { let (rs, logs) = run [post "/login" "name=bob&password=lovelace"] let resp = at rs 0 assert_equal resp.status 401 assert (string.contains (text resp) "Wrong name or password.") "error message" assert_equal logs ["POST /login", "failed login bob"] } @test fn a_corrupted_hash_is_a_server_error :: -> () / { let (rs, logs) = run [post "/login" "name=eve&password=anything"] assert_equal ((at rs 0).status) 500 assert_equal logs ["POST /login", "cannot check the password of eve: Decoding failed"] } @test fn logging_in_starts_a_session :: -> () / { let (rs, _) = run [post "/login" "name=ada&password=lovelace", get "/" "session=token-ada"] let login = at rs 0 let home = at rs 1 assert_equal login.status 303 assert_equal (header login "Set-Cookie") "session=token-ada; Path=/; Secure; HttpOnly; SameSite=Lax" assert (string.contains (text home) "Welcome, ada!") "home page" } @test fn registration_checks_its_input :: -> () / { let (rs, _) = run [ post "/register" "name=bob&password=short" , post "/register" "name=ada&password=long+enough" , post "/register" "name=bob&password=long+enough" , get "/" "theme=dark; session=token-bob" ] let short = at rs 0 let taken = at rs 1 let ok = at rs 2 let home = at rs 3 assert_equal short.status 400 assert_equal taken.status 409 assert_equal ok.status 303 assert (string.contains (text home) "Welcome, bob!") "the new user is logged in" } @test fn unknown_pages_are_not_found :: -> () / { let (rs, _) = run [get "/nope" ""] let resp = at rs 0 assert_equal resp.status 404 } @test fn a_new_cookie_has_safe_defaults :: { assert_equal (cookie.to_header (cookie.new "session" "abc")) "session=abc; Path=/; Secure; HttpOnly; SameSite=Lax" } @test fn a_cookie_is_adjusted_with_a_record_update :: { let c = cookie.SetCookie( ..cookie.new "theme" "dark" , secure: False , http_only: False , domain: Some("example.com") , max_age: Some(3600) , same_site: Some(cookie.Strict) ) assert_equal (cookie.to_header c) "theme=dark; Path=/; Domain=example.com; Max-Age=3600; SameSite=Strict" } @test fn expiring_a_cookie_empties_it_with_max_age_0 :: { assert_equal (cookie.to_header (cookie.expire "session")) "session=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Lax" } @test fn same_site_none_is_written_nonesite :: { // `NoneSite`, not `None` (which is `Option`'s), for `SameSite=None`. let c = cookie.SetCookie(..cookie.new "x" "y", same_site: Some(cookie.NoneSite)) assert (string.contains (cookie.to_header c) "; SameSite=None") "SameSite=None" let unset = cookie.SetCookie(..cookie.new "x" "y", same_site: None) assert (!string.contains (cookie.to_header unset) "SameSite") "no SameSite attribute" } @test fn set_cookie_appends_a_header :: { let resp = cookie.set_cookie (http.text 200 "ok") (cookie.new "a" "1") assert_equal (header resp "Content-Type") "text/plain; charset=utf-8" assert_equal (header resp "Set-Cookie") "a=1; Path=/; Secure; HttpOnly; SameSite=Lax" } @test @should_panic "cannot contain" fn a_cookie_name_with_a_space_is_rejected :: { let _ = cookie.new "a b" "x" () } @test @should_panic "cannot contain" fn a_cookie_value_with_a_semicolon_is_rejected :: { let _ = cookie.new "a" "x;y" () } @test @should_panic "cannot be empty or contain" fn a_cookie_name_with_an_equals_is_rejected :: { let _ = cookie.new "a=b" "x" () } @test @should_panic "boom" fn the_boom_route_crashes_its_handler :: -> () / { let _ = run [get "/boom" ""] () } @test fn the_decoy_hash_costs_as_much_as_a_real_one :: -> () / { // Same algorithm and parameters as a stored hash, so checking a // password against it takes as long. let real = argon2.hash_password "lovelace" (app.hashing ()) assert_equal (real |> result.map cost) Ok(cost (app.decoy_hash ())) // A well-formed hash, that no password here matches. assert_equal (argon2.verify "lovelace" (app.decoy_hash ())) Ok(False) } /// A PHC string's algorithm, version and parameters, before the salt. fn cost :: phc: String -> List { match string.split phc "$" { [_, algorithm, version, params, ..] -> [algorithm, version, params] , parts -> parts } }