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.

239 lignes · 6957 octetsBrut · Historique
1/// Cookies (RFC 6265): reading a request's `Cookie` headers and building
2/// `Set-Cookie` response headers.
3///
4/// import std/http/cookie
5///
6/// match cookie.cookie(req, "session") {
7/// Some(token) -> home(token),
8/// None -> http.html(views.login("")),
9/// }
10///
11/// http.text(200, "ok") |> cookie.set_cookie(cookie.new("session", token))
12///
13/// `new` fills in the safe defaults (`Path=/`, `Secure`, `HttpOnly`,
14/// `SameSite=Lax`); change them with a record update:
15/// `SetCookie(..cookie.new("theme", "dark"), http_only: False)`.
16/// (`set_cookie` is here, not in `std/http`: imports form a DAG, and this
17/// module already imports that one for `Request` and `Response`.)
18///
19/// Out of scope, on purpose: signing cookies (a `std/crypto`
20/// `hmac_sha256` helper could follow), and `Expires` (`Max-Age` covers
21/// it). Names prefixed `__Host-` or `__Secure-` promise the browser a
22/// `Secure` cookie (and, for `__Host-`, `Path=/` and no `Domain`): that
23/// is what `new` builds, but it is not checked here.
24
25import std/bytes
26import std/http
27import std/list
28import std/option
29import std/string
30
31/// The `SameSite` attribute. `NoneSite` is RFC 6265bis's `SameSite=None`
32/// (a cross-site cookie, which must also be `Secure`): it is not called
33/// `None`, which is `Option`'s and would shadow it in this module, and
34/// clash with it for anyone importing both. For no `SameSite` attribute
35/// at all, set `same_site` to `None`.
36@derive Eq Show
37pub type SameSite { Lax, Strict, NoneSite }
38
39/// A `Set-Cookie` header, as a record: `new` fills in the defaults,
40/// record updates change them.
41@derive Eq Show
42pub type SetCookie
43{ SetCookie(
44 name: String
45 , value: String
46 , path: Option<String>
47 , domain: Option<String>
48 /// Seconds the cookie lives; 0 deletes it (see `expire`).
49 , max_age: Option<Int>
50 , secure: Bool
51 , http_only: Bool
52 /// `None`: no `SameSite` attribute at all.
53 , same_site: Option<SameSite>
54 )
55}
56
57/// A cookie named `name` holding `value`, with safe defaults: `Path=/`,
58/// `Secure`, `HttpOnly`, `SameSite=Lax`. Panics if `name` or `value`
59/// contains a character a cookie cannot (see `to_header`).
60pub fn new :: name: String value: String -> SetCookie
61{
62 SetCookie( name: checked_name name
63 , value: checked value "value"
64 , path: Some("/")
65 , domain: None
66 , max_age: None
67 , secure: True
68 , http_only: True
69 , same_site: Some(Lax)
70 )
71}
72
73/// A cookie that deletes `name` (an empty value, `Max-Age=0`): the
74/// answer to a logout.
75pub fn expire :: name: String -> SetCookie
76{
77 SetCookie(..new name "", max_age: Some(0))
78}
79
80/// The `Set-Cookie` header value for `c`. Panics when a field holds a
81/// character a header cannot — `;`, `,`, a space or a control character
82/// (RFC 6265's cookie-octets), and for a name also `=` or emptiness —
83/// which a record update can introduce past `new`'s check.
84pub fn to_header :: c: SetCookie -> String
85{
86 let path = attribute "Path" c.path
87 let domain = attribute "Domain" c.domain
88 let max_age =
89 option.map c.max_age fn n { "; Max-Age=" <> show n } |> option.unwrap_or ""
90 let secure = if c.secure { "; Secure" } else { "" }
91 let http_only = if c.http_only { "; HttpOnly" } else { "" }
92 let same_site =
93 option.map c.same_site same_site_attribute |> option.unwrap_or ""
94 string.concat
95 [ checked_name c.name
96 , "="
97 , checked c.value "value"
98 , path
99 , domain
100 , max_age
101 , secure
102 , http_only
103 , same_site
104 ]
105}
106
107/// `resp` with a `Set-Cookie` header for `c` added (a response can set
108/// several cookies: each is its own header).
109pub fn set_cookie :: resp: http.Response c: SetCookie -> http.Response
110{
111 http.with_header resp "Set-Cookie" (to_header c)
112}
113
114/// The request's cookies: the `(name, value)` pairs of its `Cookie`
115/// headers (a request can have several), parsed per RFC 6265 §5.4: each
116/// pair is split on its first `=`, trimmed of surrounding spaces and
117/// unquoted; a pair without `=` or with an empty name is skipped.
118pub fn cookies :: req: http.Request -> List<(String, String)>
119{
120 use h <- list.flat_map req.headers
121 if string.to_lower h.0 == "cookie"
122 {
123 pairs h.1
124 }
125 else
126 {
127 []
128 }
129}
130
131/// The value of the request's cookie `name` (the first, if repeated).
132pub fn cookie :: req: http.Request name: String -> Option<String>
133{
134 find (cookies req) name
135}
136
137fn find :: pairs: List<(String, String)> name: String -> Option<String>
138{
139 match pairs
140 { [] -> None
141 , [(k, v), ..rest] -> if k == name { Some(v) } else { find rest name }
142 }
143}
144
145/// The pairs of one `Cookie` header's value.
146fn pairs :: header: String -> List<(String, String)>
147{
148 use part <- list.flat_map (string.split header ";")
149 match pair (string.trim part) { Some(p) -> [p], None -> [] }
150}
151
152/// One `name=value` pair: split on the first `=` (the value may hold
153/// more), name and value trimmed, the value unquoted; `None` when there
154/// is no `=` or the name is empty.
155fn pair :: part: String -> Option<(String, String)>
156{
157 match string.split part "="
158 { [name, value, ..rest] ->
159 {
160 let name = string.trim name
161 if name == ""
162 {
163 None
164 }
165 else
166 {
167 Some((name, unquote (string.trim (string.join [value, ..rest] "="))))
168 }
169 }
170 , _ -> None
171 }
172}
173
174/// `v` without its surrounding quotes, if it is `"quoted"` (a cookie
175/// value may be, RFC 6265 §4.1.1).
176fn unquote :: v: String -> String
177{
178 let b = bytes.from_string v
179 if bytes.length b >= 2 && string.starts_with v "\"" && string.ends_with v "\""
180 {
181 bytes.to_string_lossy (bytes.slice b 1 (bytes.length b - 1))
182 }
183 else
184 {
185 v
186 }
187}
188
189/// `; Name=value` for a present attribute; its value checked.
190fn attribute :: name: String value: Option<String> -> String
191{
192 option.map
193 value
194 fn v { "; " <> name <> "=" <> checked v (string.to_lower name) }
195 |> option.unwrap_or ""
196}
197
198fn same_site_attribute :: s: SameSite -> String
199{
200 "; SameSite="
201 <> match s { Lax -> "Lax", Strict -> "Strict", NoneSite -> "None" }
202}
203
204/// `s`, when it can go in a cookie; panics otherwise. A name or value
205/// cannot contain `;`, `,`, a space or a control character (RFC 6265's
206/// cookie-octets: printable ASCII but those two).
207fn checked :: s: String what: String -> String
208{
209 if list.all (string.chars s) cookie_char
210 {
211 s
212 }
213 else
214 {
215 panic
216 "cookie: a {what} cannot contain `;`, `,`, a space or a control character: {s:?}"
217 }
218}
219
220/// `name`, when it can name a cookie: `checked`, and neither empty nor
221/// holding `=` (which would split it in two when read back).
222fn checked_name :: name: String -> String
223{
224 if name == "" || string.contains name "="
225 {
226 panic "cookie: a name cannot be empty or contain `=`: {name:?}"
227 }
228 else
229 {
230 checked name "name"
231 }
232}
233
234/// A cookie-octet (RFC 6265 §4.1.1): a printable ASCII character but `;`
235/// and `,`.
236fn cookie_char :: c: String -> Bool
237{
238 c > " " && c < "\u{7f}" && c != ";" && c != ","
239}