GITv
master
web.rs294 lines, 11.0 KB
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//! The web tests' own helpers: a running `gitv-web` with its own account, and a minimal HTTP
//! client.

use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};

use super::{GITV_WEB, NO_CONFIG, TEST_HOST, scratch, stderr, stdout};

/// A web account made by `gitv-web setup`: where it's stored, and what it printed.
#[derive(Clone)]
pub struct Account {
    pub file: PathBuf,
    pub password: String,
    pub secret: Vec<u8>,
}

impl Account {
    /// Run `gitv-web setup` for a new account in `dir`.
    pub fn create(dir: &Path) -> Account {
        let file = dir.join("login");
        let out =
            Command::new(&*GITV_WEB).args(["setup", "--user", "Um9i"]).env("GITV_WEB_AUTH", &file).output().unwrap();
        assert!(out.status.success(), "setup failed: {}", stderr(&out));
        let printed = stdout(&out);
        let field = |label: &str| {
            printed
                .lines()
                .find_map(|l| l.trim().strip_prefix(label))
                .map(|v| v.trim().to_string())
                .unwrap_or_else(|| panic!("no {label} in: {printed}"))
        };
        let password = field("Password:");
        let secret = data_encoding::BASE32_NOPAD.decode(field("2FA secret:").as_bytes()).unwrap();
        Account { file, password, secret }
    }

    /// The authenticator code `offset` steps from now.
    pub fn code(&self, offset: i64) -> String {
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
        let step = gitv_web::auth::totp_step(now).saturating_add_signed(offset);
        format!("{:06}", gitv_web::auth::totp_code(&self.secret, step))
    }
}

/// A fresh, private directory for one server's account.
fn account_dir() -> PathBuf {
    static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    scratch(&format!("web-account-{}-{n}", std::process::id()))
}

/// A running `gitv-web`, stopped when dropped. Unless started signed out, it has its own
/// account and a signed-in session, which [`Server::get`] uses.
pub struct Server {
    pub child: Child,
    pub port: u16,
    pub account: Account,
    pub cookie: Option<String>,
    /// Where the server's stderr (its log) goes.
    pub log: PathBuf,
}

impl Server {
    /// A server with its own account, already signed in.
    pub fn start(repos: &Path) -> Server {
        let mut server = Server::start_with(repos, None);
        server.sign_in_now();
        server
    }

    /// Like [`Server::start`], with at most `limit` open file descriptors.
    pub fn start_limited(repos: &Path, limit: u64) -> Server {
        let mut server = Server::start_with(repos, Some(limit));
        server.sign_in_now();
        server
    }

    /// A server with its own account, not signed in.
    pub fn start_signed_out(repos: &Path) -> Server {
        Server::start_with(repos, None)
    }

    /// A server using an existing account (another server's, say), not signed in.
    pub fn start_signed_out_as(repos: &Path, account: Account) -> Server {
        Server::launch(repos, None, account)
    }

    /// Sign in with the account's password and the current code, keeping the cookie.
    pub fn sign_in_now(&mut self) {
        let code = self.account.code(0);
        let password = self.account.password.clone();
        let response = self
            .post_signed_out("/login", &[("user", "Um9i"), ("password", &password), ("code", &code), ("next", "/")]);
        assert_eq!(response.status, 303, "sign-in failed: {}", response.text());
        self.cookie = Some(session_cookie(&response).expect("a session cookie"));
    }

    fn start_with(repos: &Path, limit: Option<u64>) -> Server {
        Server::launch(repos, limit, Account::create(&account_dir()))
    }

    fn launch(repos: &Path, limit: Option<u64>, account: Account) -> Server {
        let mut command = Command::new(&*GITV_WEB);
        if let Some(limit) = limit {
            use std::os::unix::process::CommandExt;
            // SAFETY: setrlimit is async-signal-safe and the closure does nothing else.
            unsafe {
                command.pre_exec(move || {
                    nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_NOFILE, limit, limit)
                        .map_err(std::io::Error::from)
                });
            }
        }
        static LAUNCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let number = LAUNCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let log = account.file.with_file_name(format!("server-{}-{number}.log", std::process::id()));
        let mut child = command
            .args(["serve", "--port", "0"])
            .env("GITV_HOST", TEST_HOST)
            .env("GITV_CONFIG", NO_CONFIG)
            .env("GITV_REPOS", repos)
            .env("GITV_WEB_AUTH", &account.file)
            .stdout(Stdio::piped())
            .stderr(fs::File::create(&log).unwrap())
            .spawn()
            .unwrap();
        let mut line = String::new();
        BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap();
        let port = line
            .split("http://127.0.0.1:")
            .nth(1)
            .and_then(|rest| rest.split_whitespace().next())
            .and_then(|p| p.parse().ok())
            .unwrap_or_else(|| panic!("unexpected startup line: {line}"));
        Server { child, port, account, cookie: None, log }
    }

    /// What the server has logged so far.
    pub fn logged(&self) -> String {
        fs::read_to_string(&self.log).unwrap_or_default()
    }

    /// GET with the session cookie, if signed in.
    pub fn get(&self, path: &str) -> Response {
        request(self.port, "GET", path, self.cookie.as_deref(), None)
    }

    /// GET without any cookie.
    pub fn get_signed_out(&self, path: &str) -> Response {
        request(self.port, "GET", path, None, None)
    }

    /// POST a form with the session cookie, if signed in.
    pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Response {
        request(self.port, "POST", path, self.cookie.as_deref(), Some(&form_body(form)))
    }

    /// POST a form without any cookie.
    pub fn post_signed_out(&self, path: &str, form: &[(&str, &str)]) -> Response {
        request(self.port, "POST", path, None, Some(&form_body(form)))
    }

    /// POST a form without any cookie, as Caddy forwards one from the client at `address`.
    pub fn post_signed_out_from(&self, address: &str, path: &str, form: &[(&str, &str)]) -> Response {
        let extra = [("X-Forwarded-For", address)];
        request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra)
    }

    /// Like [`Server::post_signed_out_from`], from a browser carrying the trusted-device token
    /// `device`.
    pub fn post_from_device(&self, address: &str, device: &str, path: &str, form: &[(&str, &str)]) -> Response {
        let cookie = format!("__Host-gitv-device={device}");
        let extra = [("X-Forwarded-For", address), ("Cookie", cookie.as_str())];
        request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra)
    }
}

/// The session token a response's `Set-Cookie` gives, if any.
pub fn session_cookie(response: &Response) -> Option<String> {
    set_cookie(response, "__Host-gitv")
}

/// The value a response's `Set-Cookie` headers give the cookie `name`, if any.
pub fn set_cookie(response: &Response, name: &str) -> Option<String> {
    response
        .header("set-cookie")
        .lines()
        .find_map(|line| line.strip_prefix(name)?.strip_prefix('='))?
        .split(';')
        .next()
        .filter(|t| !t.is_empty())
        .map(String::from)
}

/// `application/x-www-form-urlencoded`, as a browser sends a form.
fn form_body(form: &[(&str, &str)]) -> String {
    let encode = |v: &str| -> String {
        v.bytes()
            .map(|b| match b {
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
                _ => format!("%{b:02X}"),
            })
            .collect()
    };
    form.iter().map(|(k, v)| format!("{}={}", encode(k), encode(v))).collect::<Vec<_>>().join("&")
}

impl Drop for Server {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

pub struct Response {
    pub status: u16,
    pub headers: HashMap<String, String>,
    pub body: Vec<u8>,
}

impl Response {
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    pub fn header(&self, name: &str) -> &str {
        self.headers.get(name).map_or("", String::as_str)
    }
}

/// A plain HTTP/1.1 request, enough for testing a local server.
fn request(port: u16, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Response {
    request_with(port, method, path, cookie, form, &[])
}

fn request_with(
    port: u16,
    method: &str,
    path: &str,
    cookie: Option<&str>,
    form: Option<&str>,
    extra: &[(&str, &str)],
) -> Response {
    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    let mut head = format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n");
    for (name, value) in extra {
        head += &format!("{name}: {value}\r\n");
    }
    if let Some(cookie) = cookie {
        head += &format!("Cookie: __Host-gitv={cookie}\r\n");
    }
    let body = form.unwrap_or("");
    if form.is_some() {
        head += &format!("Content-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\n", body.len());
    }
    write!(stream, "{head}\r\n{body}").unwrap();
    let mut raw = Vec::new();
    stream.read_to_end(&mut raw).unwrap();
    let split = raw.windows(4).position(|w| w == b"\r\n\r\n").expect("no header end");
    let head = String::from_utf8_lossy(&raw[..split]).into_owned();
    let mut lines = head.lines();
    let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap();
    // A repeated header (Set-Cookie, say) keeps every value, one per line.
    let mut headers: HashMap<String, String> = HashMap::new();
    for (name, value) in lines.filter_map(|l| l.split_once(':')) {
        let entry = headers.entry(name.trim().to_ascii_lowercase()).or_default();
        if !entry.is_empty() {
            entry.push('\n');
        }
        entry.push_str(value.trim());
    }
    let mut body = raw[split + 4..].to_vec();
    if headers.get("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) {
        body = dechunk(&body);
    }
    Response { status, headers, body }
}

fn dechunk(mut data: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    while let Some(end) = data.windows(2).position(|w| w == b"\r\n") {
        let size = usize::from_str_radix(String::from_utf8_lossy(&data[..end]).trim(), 16).unwrap_or(0);
        if size == 0 {
            break;
        }
        out.extend_from_slice(&data[end + 2..end + 2 + size]);
        data = &data[end + 2 + size + 2..];
    }
    out
}