summaryrefslogtreecommitdiffstats
path: root/src/http/mod.rs
blob: e3a21817476e6b53c17496ae952e5471af696772 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
mod auth;
mod forms;
mod render;
mod routes;
pub mod sse;

use std::sync::Arc;

use crate::config::Config;
use crate::db::Db;

struct State {
    pub cfg: Config,
    pub db: Db,
}

struct Req {
    pub method: String,
    pub path: String,
    pub cookies: Vec<(String, String)>,
    pub query_pairs: Vec<(String, String)>,
    pub form_pairs: Vec<(String, String)>,
    pub accept_gzip: bool,
}

impl Req {
    fn form(&self) -> &[(String, String)] {
        &self.form_pairs
    }
    fn form_get(&self, key: &str) -> Option<String> {
        self.form_pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
    }
    fn query_get(&self, key: &str) -> Option<String> {
        self.query_pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
    }
    /// Reading a cookie off a request is internal plumbing; the auth tests need it in order to forge one.
    #[cfg(feature = "test-support")]
    pub fn cookie(&self, name: &str) -> Option<String> {
        Self::cookie_impl(self, name)
    }

    #[cfg(not(feature = "test-support"))]
    fn cookie(&self, name: &str) -> Option<String> {
        Self::cookie_impl(self, name)
    }

    fn cookie_impl(&self, name: &str) -> Option<String> {
        self.cookies.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())
    }
}

struct Res {
    pub status: u16,
    pub content_type: String,
    pub body: Vec<u8>,
    pub headers: Vec<(String, String)>,
    pub stream: Option<Box<dyn std::io::Read + Send>>,
    pub stream_len: Option<usize>,
}

impl Res {
    /// `pub(crate)`, not `pub`: the census counted it as test-only because the word appears in `tests/http.rs`, but only inside a string — a route path, a content type, the word "redirect" in an assertion message. Nothing in the test tier calls it.
    fn html(status: u16, body: String) -> Self {
        Self {
            status,
            content_type: "text/html; charset=utf-8".into(),
            body: body.into_bytes(),
            headers: Vec::new(),
            stream: None,
            stream_len: None,
        }
    }
    pub fn text(status: u16, body: String) -> Self {
        Self {
            status,
            content_type: "text/plain; charset=utf-8".into(),
            body: body.into_bytes(),
            headers: Vec::new(),
            stream: None,
            stream_len: None,
        }
    }
    pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self {
        Self {
            status: 200,
            content_type: content_type.into(),
            body: Vec::new(),
            headers: Vec::new(),
            stream: Some(Box::new(reader)),
            stream_len: known_len,
        }
    }
    /// `pub(crate)`, not `pub`: the census counted it as test-only because the word appears in `tests/http.rs`, but only inside a string — a route path, a content type, the word "redirect" in an assertion message. Nothing in the test tier calls it.
    fn redirect(location: &str) -> Self {
        Self {
            status: 303,
            content_type: "text/plain".into(),
            body: b"redirecting".to_vec(),
            headers: vec![("Location".into(), location.into())],
            stream: None,
            stream_len: None,
        }
    }
    fn header(&mut self, name: &str, value: &str) {
        self.headers.push((name.into(), value.into()));
    }
}

/// The real definition; the alias below carries the visibility.
mod server {
    pub struct Server {
        pub addr: String,
    }
}

/// The handle to a running HTTP listener.
#[cfg(feature = "test-support")]
pub use server::Server;

#[cfg(not(feature = "test-support"))]
pub(crate) use server::Server;

pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> {
    let server = tiny_http::Server::http(&cfg.bind).map_err(|e| std::io::Error::other(e.to_string()))?;
    let addr = server.server_addr().to_ip().map_or_else(|| cfg.bind.clone(), |a| a.to_string());
    let state = Arc::new(State { cfg, db });
    eprintln!("aur-build listening on http://{addr}");
    // Detached on purpose: the accept loop owns the listener and runs until the
    // process ends, and nothing joins it, so the handle would be stored unread.
    std::thread::Builder::new().name("http-accept".into()).spawn(crate::time::inherit(move || {
        for request in server.incoming_requests() {
            let state = state.clone();
            std::thread::Builder::new()
                .name("http-conn".into())
                .spawn(crate::time::inherit(move || {
                    if let Err(e) = serve(&state, request) {
                        eprintln!("http: {e}");
                    }
                }))
                .ok();
        }
    }))?;
    Ok(Server { addr })
}

fn serve(state: &State, mut request: tiny_http::Request) -> std::io::Result<()> {
    let url = request.url().to_string();
    let (path, query) = match url.split_once('?') {
        Some((p, q)) => (p.to_string(), q.to_string()),
        None => (url.clone(), String::new()),
    };
    let mut body = String::new();
    let _ = request.as_reader().read_to_string(&mut body);
    let cookies = request
        .headers()
        .iter()
        .find(|h| h.field.equiv("Cookie"))
        .map_or_default(|h| auth::parse_cookies(h.value.as_str()));
    let accept_gzip = request
        .headers()
        .iter()
        .find(|h| h.field.equiv("Accept-Encoding"))
        .is_some_and(|h| h.value.as_str().contains("gzip"));
    let form_pairs = forms::parse(&body);
    let req = Req {
        method: request.method().as_str().to_string(),
        path: percent_decode(&path),
        cookies,
        query_pairs: forms::parse(&query),
        form_pairs,
        accept_gzip,
    };

    let mut res = dispatch(state, &req);
    if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) {
        res.headers.retain(|(k, _)| k != "X-New-Session");
        res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict"));
    }
    let mut headers = Vec::new();
    if let Ok(h) = tiny_http::Header::from_bytes(b"Content-Type", res.content_type.as_bytes()) {
        headers.push(h);
    }
    for (k, v) in &res.headers {
        if let Ok(h) = tiny_http::Header::from_bytes(k.as_bytes(), v.as_bytes()) {
            headers.push(h);
        }
    }
    if let Some(reader) = res.stream.take() {
        let mut resp =
            tiny_http::Response::new(tiny_http::StatusCode(res.status), headers, reader, res.stream_len, None);
        if res.stream_len.is_some() {
            resp = resp.with_chunked_threshold(usize::MAX);
        }
        return request.respond(resp);
    }
    let mut builder = tiny_http::Response::from_data(std::mem::take(&mut res.body))
        .with_status_code(tiny_http::StatusCode(res.status));
    for h in headers {
        builder = builder.with_header(h);
    }
    request.respond(builder)
}

fn dispatch(state: &State, req: &Req) -> Res {
    let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect();
    let is_get = req.method == "GET";

    match (req.method.as_str(), seg.as_slice()) {
        ("GET", ["static", name]) => return render::static_asset(name, req.accept_gzip),
        ("GET", ["login"]) => return routes::login_form(state, req),
        ("POST", ["login"]) => return routes::login(state, req),
        ("GET", ["healthz"]) => return Res::text(200, "ok\n".into()),
        ("GET", ["metrics"]) => return routes::metrics(state),
        _ => {}
    }

    let (sid, new_session) = match req.cookie("sid") {
        Some(s) if auth::is_valid_session(&s) => (s, false),
        _ => match auth::new_session() {
            Some(s) => (s, true),
            None => return Res::text(500, "500: could not mint a session\n".into()),
        },
    };
    let gated = routes::gate(state, req, &sid);
    if let Some(mut res) = gated {
        if new_session {
            res.header("X-New-Session", &sid);
        }
        return finish(state, req, res, &sid, new_session);
    }

    if !is_get {
        let token = req.form_get("csrf").or_else(|| req.query_get("csrf")).unwrap_or_default();
        if !auth::csrf_ok(&sid, &token) {
            return Res::text(403, "403 forbidden: CSRF token missing or wrong\n".into());
        }
    }

    let mut res = routes::route(state, req, &seg);
    if new_session {
        res.header("X-New-Session", &sid);
    }
    finish(state, req, res, &sid, new_session)
}

fn finish(_state: &State, _req: &Req, mut res: Res, _sid: &str, _new: bool) -> Res {
    res.header("X-Content-Type-Options", "nosniff");
    res.header("Referrer-Policy", "same-origin");
    res
}

fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
                out.push(v);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}