tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

359 lignes · 9112 octetsBrut · Historique
1// The routes, run with mock handlers: no server, no store actor. Run with
2// `louise test --native` (argon2 is a native dependency).
3
4import app.
5{ type User
6, type log
7, type users
8, NameTaken
9, User
10, add_user
11, find_user
12, log
13, new_session
14, session_user
15}
16import argon2
17import std/bytes
18import std/dict
19import std/http.{type Request, type Response, Request}
20import std/http/cookie
21import std/list
22import std/option
23import std/random.{type random}
24import std/ref
25import std/result
26import std/string
27import std/test.{assert, assert_equal}
28
29/// Collect the log instead of printing it.
30fn with_mock_log :: action: fn() -> a / <log | e> -> (a, List<String>) / <e>
31{
32 region
33 {
34 let lines = ref.new []
35 let res = handle
36 {
37 action ()
38 }
39 with
40 { log message -> ref.set lines [message, ..ref.get lines] }
41 (res, list.reverse (ref.get lines))
42 }
43}
44
45/// Users and sessions in memory. Session tokens are predictable here.
46fn with_mock_users ::
47 seed: List<User>
48 action: fn() -> a / <users | e>
49 -> a / <e>
50{
51 region
52 {
53 let users = ref.new (dict.from_list (list.map seed fn u { (u.name, u) }))
54 let sessions = ref.new (dict.empty ())
55 handle
56 {
57 action ()
58 }
59 with
60 { find_user name -> dict.get (ref.get users) name
61 , add_user user -> if dict.has (ref.get users) user.name
62 {
63 Error(NameTaken)
64 }
65 else
66 {
67 ref.set users (dict.insert (ref.get users) user.name user)
68 Ok(())
69 }
70 , new_session name ->
71 {
72 let token = "token-{name}"
73 ref.set sessions (dict.insert (ref.get sessions) token name)
74 token
75 }
76 , session_user token -> dict.get (ref.get sessions) token
77 }
78 }
79}
80
81fn ada :: -> User / <ffi>
82{
83 match argon2.hash
84 "lovelace"
85 "seed-salt"
86 argon2.Params(t_cost: 1, m_cost_kib: 64, parallelism: 1)
87 { Ok(hash) -> User("ada", hash), Error(e) -> panic e }
88}
89
90fn get :: path: String cookie_header: String -> Request
91{
92 Request( "GET"
93 , path
94 , if cookie_header == "" { [] } else { [("Cookie", cookie_header)] }
95 , bytes.empty ()
96 )
97}
98
99fn post :: path: String body: String -> Request
100{
101 Request("POST", path, [], bytes.from_string body)
102}
103
104fn header :: resp: Response name: String -> String
105{
106 match list.filter resp.headers fn h { h.0 == name }
107 { [(_, v), ..] -> v, _ -> "" }
108}
109
110/// The response body as text.
111fn text :: resp: Response -> String
112{
113 bytes.to_string_lossy
114 (option.unwrap_or (http.whole_body resp) (bytes.empty ()))
115}
116
117fn at :: xs: List<Response> i: Int -> Response
118{
119 match xs
120 { [x, ..rest] -> if i == 0 { x } else { at rest (i - 1) }
121 , [] -> panic "no response {i}"
122 }
123}
124
125/// Run requests one after another against the same mock users, with
126/// seeded randomness: the same session tokens and salts on every run.
127fn run :: requests: List<Request> -> (List<Response>, List<String>) / <ffi, io>
128{
129 // `eve`'s stored hash is corrupted.
130 let seed = [ada (), User("eve", "not a hash")]
131 use <- random.with_seed 1
132 use <- with_mock_log
133 use <- with_mock_users seed
134 list.map requests app.route
135}
136
137@test
138fn anonymous_visitors_get_the_login_page :: -> () / <ffi, io>
139{
140 let (rs, logs) = run [get "/" ""]
141 let home = at rs 0
142 assert_equal home.status 200
143 assert (string.contains (text home) "<title>Log in</title>") "login page"
144 assert_equal logs ["GET /"]
145}
146
147@test
148fn the_stylesheet_is_served_from_disk :: -> () / <ffi, io>
149{
150 let (rs, logs) = run [get "/static/style.css" ""]
151 let style = at rs 0
152 assert_equal style.status 200
153 assert_equal (header style "Content-Type") "text/css; charset=utf-8"
154 assert (string.contains (text style) "backdrop-filter") "the glass panels"
155 assert_equal logs ["GET /static/style.css"]
156}
157
158@test
159fn static_files_are_served_from_disk :: -> () / <ffi, io>
160{
161 let (rs, logs) = run [get "/static/robots.txt" ""]
162 let robots = at rs 0
163 assert_equal robots.status 200
164 assert_equal (header robots "Content-Type") "text/plain; charset=utf-8"
165 assert (string.contains (text robots) "User-agent:") "the file's content"
166 assert_equal logs ["GET /static/robots.txt"]
167}
168
169@test
170fn a_missing_static_file_and_a_traversal_are_404s :: -> () / <ffi, io>
171{
172 let (rs, _) = run [get "/static/nope.txt" "", get "/static/../louise.toml" ""]
173 assert_equal ((at rs 0).status) 404
174 assert_equal ((at rs 1).status) 404
175}
176
177@test
178fn a_wrong_password_is_rejected :: -> () / <ffi, io>
179{
180 let (rs, logs) = run [post "/login" "name=ada&password=nope"]
181 let resp = at rs 0
182 assert_equal resp.status 401
183 assert (string.contains (text resp) "Wrong name or password.") "error message"
184 assert_equal logs ["POST /login", "failed login ada"]
185}
186
187@test
188fn an_unknown_user_gets_the_same_answer :: -> () / <ffi, io>
189{
190 let (rs, logs) = run [post "/login" "name=bob&password=lovelace"]
191 let resp = at rs 0
192 assert_equal resp.status 401
193 assert (string.contains (text resp) "Wrong name or password.") "error message"
194 assert_equal logs ["POST /login", "failed login bob"]
195}
196
197@test
198fn a_corrupted_hash_is_a_server_error :: -> () / <ffi, io>
199{
200 let (rs, logs) = run [post "/login" "name=eve&password=anything"]
201 assert_equal ((at rs 0).status) 500
202 assert_equal
203 logs
204 ["POST /login", "cannot check the password of eve: Decoding failed"]
205}
206
207@test
208fn logging_in_starts_a_session :: -> () / <ffi, io>
209{
210 let (rs, _) =
211 run
212 [post "/login" "name=ada&password=lovelace", get "/" "session=token-ada"]
213 let login = at rs 0
214 let home = at rs 1
215 assert_equal login.status 303
216 assert_equal
217 (header login "Set-Cookie")
218 "session=token-ada; Path=/; Secure; HttpOnly; SameSite=Lax"
219 assert (string.contains (text home) "Welcome, ada!") "home page"
220}
221
222@test
223fn registration_checks_its_input :: -> () / <ffi, io>
224{
225 let (rs, _) =
226 run
227 [ post "/register" "name=bob&password=short"
228 , post "/register" "name=ada&password=long+enough"
229 , post "/register" "name=bob&password=long+enough"
230 , get "/" "theme=dark; session=token-bob"
231 ]
232 let short = at rs 0
233 let taken = at rs 1
234 let ok = at rs 2
235 let home = at rs 3
236 assert_equal short.status 400
237 assert_equal taken.status 409
238 assert_equal ok.status 303
239 assert
240 (string.contains (text home) "Welcome, bob!")
241 "the new user is logged in"
242}
243
244@test
245fn unknown_pages_are_not_found :: -> () / <ffi, io>
246{
247 let (rs, _) = run [get "/nope" ""]
248 let resp = at rs 0
249 assert_equal resp.status 404
250}
251
252@test
253fn a_new_cookie_has_safe_defaults ::
254{
255 assert_equal
256 (cookie.to_header (cookie.new "session" "abc"))
257 "session=abc; Path=/; Secure; HttpOnly; SameSite=Lax"
258}
259
260@test
261fn a_cookie_is_adjusted_with_a_record_update ::
262{
263 let c =
264 cookie.SetCookie( ..cookie.new "theme" "dark"
265 , secure: False
266 , http_only: False
267 , domain: Some("example.com")
268 , max_age: Some(3600)
269 , same_site: Some(cookie.Strict)
270 )
271 assert_equal
272 (cookie.to_header c)
273 "theme=dark; Path=/; Domain=example.com; Max-Age=3600; SameSite=Strict"
274}
275
276@test
277fn expiring_a_cookie_empties_it_with_max_age_0 ::
278{
279 assert_equal
280 (cookie.to_header (cookie.expire "session"))
281 "session=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Lax"
282}
283
284@test
285fn same_site_none_is_written_nonesite ::
286{
287 // `NoneSite`, not `None` (which is `Option`'s), for `SameSite=None`.
288 let c =
289 cookie.SetCookie(..cookie.new "x" "y", same_site: Some(cookie.NoneSite))
290 assert
291 (string.contains (cookie.to_header c) "; SameSite=None")
292 "SameSite=None"
293 let unset = cookie.SetCookie(..cookie.new "x" "y", same_site: None)
294 assert
295 (!string.contains (cookie.to_header unset) "SameSite")
296 "no SameSite attribute"
297}
298
299@test
300fn set_cookie_appends_a_header ::
301{
302 let resp = cookie.set_cookie (http.text 200 "ok") (cookie.new "a" "1")
303 assert_equal (header resp "Content-Type") "text/plain; charset=utf-8"
304 assert_equal
305 (header resp "Set-Cookie")
306 "a=1; Path=/; Secure; HttpOnly; SameSite=Lax"
307}
308
309@test
310@should_panic "cannot contain"
311fn a_cookie_name_with_a_space_is_rejected ::
312{
313 let _ = cookie.new "a b" "x"
314 ()
315}
316
317@test
318@should_panic "cannot contain"
319fn a_cookie_value_with_a_semicolon_is_rejected ::
320{
321 let _ = cookie.new "a" "x;y"
322 ()
323}
324
325@test
326@should_panic "cannot be empty or contain"
327fn a_cookie_name_with_an_equals_is_rejected ::
328{
329 let _ = cookie.new "a=b" "x"
330 ()
331}
332
333@test
334@should_panic "boom"
335fn the_boom_route_crashes_its_handler :: -> () / <ffi, io>
336{
337 let _ = run [get "/boom" ""]
338 ()
339}
340
341@test
342fn the_decoy_hash_costs_as_much_as_a_real_one :: -> () / <ffi, random>
343{
344 // Same algorithm and parameters as a stored hash, so checking a
345 // password against it takes as long.
346 let real = argon2.hash_password "lovelace" (app.hashing ())
347 assert_equal (real |> result.map cost) Ok(cost (app.decoy_hash ()))
348 // A well-formed hash, that no password here matches.
349 assert_equal (argon2.verify "lovelace" (app.decoy_hash ())) Ok(False)
350}
351
352/// A PHC string's algorithm, version and parameters, before the salt.
353fn cost :: phc: String -> List<String>
354{
355 match string.split phc "$"
356 { [_, algorithm, version, params, ..] -> [algorithm, version, params]
357 , parts -> parts
358 }
359}