tobogganSe connecter

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.

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