summaryrefslogtreecommitdiffstats
path: root/src/http/routes/mod.rs
blob: 0dfed52de12b5ba1c8d95c6f770ae3e95a4587f7 (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
use crate::db::{self, builds, model::*};
use crate::review::candidates;
use crate::time;
use super::auth;
use super::render::*;
use super::{Req, Res, State};

mod mutations;
mod pages;

// The handlers live in two files by direction of travel — reads in `pages`,
// writes in `mutations` — and are pulled back into scope here so the routing
// table below still reads as one flat list of endpoints (n-4).
pub(crate) use mutations::*;
pub(crate) use pages::*;

pub fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> {
    if !auth::auth_required(&state.cfg) {
        return None;
    }
    if auth::is_authenticated(sid) || req.path == "/login" {
        return None;
    }
    Some(Res::redirect("/login"))
}

pub fn login_form(state: &State, req: &Req) -> Res {
    let page = Page::new("Sign in", csrf(state, req));
    page_to_res(Login { page, error: String::new() }, 200)
}

/// Forget the session server-side and clear the cookie. The CSRF token is
/// derived from the sid, so dropping the sid invalidates every form a browser
/// still has open — which is exactly what logout should do.
pub fn logout(req: &Req) -> Res {
    if let Some(sid) = req.cookie("sid") {
        auth::drop_session(&sid);
    }
    let mut res = Res::redirect("/login");
    res.header("Set-Cookie", "sid=; Path=/; Max-Age=0");
    res
}

pub fn login(state: &State, req: &Req) -> Res {
    let given = req.form_get("password").unwrap_or_default();
    let page = Page::new("Sign in", csrf(state, req));
    if auth::password_ok(&state.cfg, &given) {
        // Rotate rather than promote: the sid the visitor arrived with (if any)
        // is dropped, so the session that existed before the password was typed
        // is never the one that carries the privilege afterwards.
        if let Some(old) = req.cookie("sid") {
            auth::drop_session(&old);
        }
        let sid = match auth::new_session() {
            Some(sid) => sid,
            None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500),
        };
        auth::authenticate(&sid);
        let mut res = Res::redirect("/");
        // `serve` turns this into the `Set-Cookie: sid=…` header.
        res.header("X-New-Session", &sid);
        res
    } else {
        page_to_res(Login { page, error: "wrong password".into() }, 401)
    }
}

pub fn route(state: &State, req: &Req, seg: &[&str]) -> Res {
    match (req.method.as_str(), seg) {
        ("GET", []) => dashboard(state, req),
        ("GET", ["reviews"]) => reviews(state, req),
        ("GET", ["reviews", id]) => review_detail(state, req, id),
        ("POST", ["reviews", id, "approve"]) => review_approve(state, req, id),
        ("POST", ["reviews", id, "reject"]) => review_reject(state, req, id),
        ("POST", ["reviews", "bulk"]) => reviews_bulk(state, req),
        ("POST", ["logout"]) => logout(req),
        ("GET", ["subscriptions"]) => subscriptions(state, req),
        ("POST", ["subscriptions", "add"]) => sub_add(state, req),
        ("POST", ["subscriptions", "pause"]) => sub_pause(state, req),
        ("POST", ["subscriptions", "remove"]) => sub_remove(state, req),
        ("GET", ["attention"]) => attention(state, req),
        ("POST", ["attention", "ack"]) => notice_ack(state, req),
        ("GET", ["packages"]) => packages(state, req),
        ("GET", ["packages", name]) => package_detail(state, req, name),
        ("POST", ["packages", name, "rebuild"]) => package_rebuild(state, req, name),
        ("POST", ["packages", name, "withdraw"]) => package_withdraw(state, req, name),
        ("GET", ["builds"]) => builds_page(state, req),
        ("GET", ["builds", id]) => build_detail(state, req, id),
        ("GET", ["builds", id, "log.txt"]) => build_log(state, id),
        ("GET", ["builds", id, "log.stream"]) => build_log_stream(state, req, id),
        ("POST", ["builds", id, "cancel"]) => build_cancel(state, req, id),
        ("POST", ["builds", id, "requeue"]) => build_retry(state, req, id),
        ("GET", ["audit"]) => audit(state, req),
        ("GET", ["settings"]) => settings(state, req),
        _ => not_found(state, req),
    }
}

fn not_found(state: &State, req: &Req) -> Res {
    let page = chrome(state, req, "Not found", "nav_packages");
    page_to_res(
        ErrorPage {
            page,
            status: "404".into(),
            message: "no such page".into(),
            detail: String::new(),
        },
        404,
    )
}

/// The shared chrome: counts for the nav badges and the active-tab marker.
fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page {
    let db = &state.db;
    let mut page = Page::new(title, csrf(state, req));
    page.pending = candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0);
    page.running = builds::in_flight(db).map(|v| v as i64).unwrap_or(0)
        + builds::queue_depth(db).map(|v| v as i64).unwrap_or(0);
    page.attention = db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0)
        + builds::blocked_builds(db).map(|v| v.len() as i64).unwrap_or(0);
    page.nav_reviews = if active == "nav_reviews" { "on" } else { "" };
    page.nav_builds = if active == "nav_builds" { "on" } else { "" };
    page.nav_attention = if active == "nav_attention" { "on" } else { "" };
    page.nav_packages = if active == "nav_packages" { "on" } else { "" };
    page.nav_subscriptions = if active == "nav_subscriptions" { "on" } else { "" };
    page.nav_audit = if active == "nav_audit" { "on" } else { "" };
    page.nav_settings = if active == "nav_settings" { "on" } else { "" };
    page.gated = auth::auth_required(&state.cfg);
    page
}

fn csrf(_state: &State, req: &Req) -> String {
    req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default()
}

/// A byte count a human can read at a glance.
fn human_size(bytes: i64) -> String {
    const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"];
    let mut v = bytes as f64;
    let mut i = 0;
    while v >= 1024.0 && i < UNITS.len() - 1 {
        v /= 1024.0;
        i += 1;
    }
    if i == 0 {
        format!("{bytes} {}", UNITS[0])
    } else {
        format!("{v:.1} {}", UNITS[i])
    }
}

fn short(id: &str) -> String {
    id.chars().take(10).collect()
}

fn age(detected_at: &str) -> String {
    let now = time::now();
    format!("{detected_at} → {now}")
}

/// Who the audit trail says made a decision. With no password configured the
/// UI is open on loopback and every session is the operator's; with one, only
/// a session that passed the gate gets a name.
fn actor(state: &State, req: &Req) -> &'static str {
    let sid = req.cookie("sid").unwrap_or_default();
    if !auth::auth_required(&state.cfg) || auth::is_authenticated(&sid) {
        "web"
    } else {
        "web-anon"
    }
}

fn flash_sub(state: &State, req: &Req, msg: &str, err: bool) -> Res {
    let page = chrome(state, req, "Subscriptions", "nav_subscriptions").flash(msg.into(), err);
    let pending = candidates::pending_candidates(&state.db).unwrap_or_default();
    let rows = db::list_subscriptions(&state.db)
        .unwrap_or_default()
        .into_iter()
        .map(|s| SubRow {
            pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64,
            name: s.pkgbase.clone(),
            state: s.state.to_string(),
            maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()),
            last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()),
            next_check: s.next_check_at.unwrap_or_else(|| "soon".into()),
            last_error: s.last_error.clone().unwrap_or_default(),
            has_error: s.last_error.is_some(),
            pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" },
        })
        .collect();
    page_to_res(Subscriptions { page, rows }, 200)
}

// ------------------------------------------------------------ rendering --

fn page_to_res<T: askama::Template>(t: T, status: u16) -> Res {
    match askama::Template::render(&t) {
        Ok(body) => Res::html(status, body),
        Err(e) => Res::text(500, format!("template error: {e}")),
    }
}