Skip to main content

runnerd_web/
lib.rs

1//! `runnerd-web`: the dashboard the daemon serves on a loopback TCP port. It is a client of the daemon's API like
2//! `runnerctl`: it reads `runnerd_core::api` types over the daemon's Unix socket (`runnerd_core::client`), renders
3//! HTML on the server (`views`, `chart`), and keeps open pages current over SSE with Datastar (`live`). Writes
4//! (pause, reseed, the config) are passed on to the same API (`actions`). It holds no state of its own beyond the
5//! session and its login codes (`auth`), and never talks to Docker or GitHub.
6
7use std::future::Future;
8use std::io;
9use std::net::SocketAddr;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use axum::Router;
15use axum::extract::rejection::QueryRejection;
16use axum::extract::{Path as UrlPath, Query, Request, State};
17use axum::http::{HeaderValue, StatusCode, header};
18use axum::middleware::{self, Next};
19use axum::response::{Html, IntoResponse, Response};
20use axum::routing::{delete, get, post};
21use maud::Markup;
22use runnerd_core::client::{Client, ClientError};
23use runnerd_core::config::Origin;
24use tokio::net::TcpListener;
25use tokio::sync::watch;
26use tokio::task::JoinHandle;
27use tracing::{info, warn};
28
29mod actions;
30mod assets;
31mod auth;
32mod chart;
33mod format;
34mod live;
35mod views;
36
37pub use auth::{PAIRING_LIFETIME, PAIRING_MAX, PairError, Sessions, login_file, session_file};
38use views::caches::CachesView;
39use views::config::{ConfigQuery, ConfigView};
40use views::history::{Filter, History};
41use views::insights::InsightsView;
42use views::job::JobView;
43use views::overview::Overview;
44use views::records::RecordsView;
45use views::sizing::SizingView;
46
47/// The dashboard's default address.
48pub const DEFAULT_ADDR: &str = "127.0.0.1:7477";
49
50/// What every handler shares.
51#[derive(Clone)]
52pub(crate) struct App {
53    daemon: Client,
54    /// `[web] origins`, where the config page offers to sign a phone in.
55    proxies: Arc<[String]>,
56    /// Set when the dashboard stops, so live pages end.
57    stopping: watch::Receiver<bool>,
58}
59
60pub(crate) fn now() -> u64 {
61    SystemTime::now()
62        .duration_since(UNIX_EPOCH)
63        .map_or(0, |since| since.as_secs())
64}
65
66/// Binds the dashboard's port from `runnerd serve --web`: a loopback address, or `off` for no dashboard. Only
67/// loopback: the session cookie travels in the clear.
68pub async fn listen(flag: &str) -> io::Result<Option<TcpListener>> {
69    if flag == "off" {
70        return Ok(None);
71    }
72    let addr: SocketAddr = flag
73        .parse()
74        .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
75    if !addr.ip().is_loopback() {
76        return Err(io::Error::new(
77            io::ErrorKind::InvalidInput,
78            format!("the dashboard listens on loopback only, not {addr}"),
79        ));
80    }
81    TcpListener::bind(addr).await.map(Some)
82}
83
84/// Runs `serve` as a task, logging why it stopped if it failed.
85pub fn spawn(
86    listener: TcpListener,
87    socket: PathBuf,
88    proxies: Vec<Origin>,
89    sessions: Arc<Sessions>,
90    stop: impl Future + Send + 'static,
91) -> JoinHandle<()> {
92    tokio::spawn(async move {
93        let stop = async {
94            stop.await;
95        };
96        if let Err(error) = serve(listener, &socket, &proxies, sessions, stop).await {
97            warn!("the dashboard stopped: {error}");
98        }
99    })
100}
101
102/// Serves the dashboard on `listener` for the daemon whose API is on `socket`, until `stop` completes. Pages from
103/// `proxies` (`[web] origins`), reverse proxies in front of it, may write too. A browser signed in to `sessions`
104/// is let in. Writes a one-time login link per address to `login_file(socket)` and removes it when done.
105pub async fn serve(
106    listener: TcpListener,
107    socket: &Path,
108    proxies: &[Origin],
109    sessions: Arc<Sessions>,
110    stop: impl Future<Output = ()> + Send + 'static,
111) -> io::Result<()> {
112    let addr = listener.local_addr()?;
113    let file = login_file(socket);
114    let auth = auth::Auth::new(addr, proxies, sessions, file.clone())?;
115    info!(
116        "serving the dashboard on http://{addr}; `runnerctl web` opens it (login links in {})",
117        file.display()
118    );
119    let (stopping, stopping_receiver) = watch::channel(false);
120    let app = router(
121        Client::new(socket.to_owned()),
122        auth.clone(),
123        stopping_receiver,
124    );
125    let served = axum::serve(listener, app)
126        .with_graceful_shutdown(async move {
127            stop.await;
128            let _ = stopping.send(true);
129        })
130        .await;
131    auth.remove_login_file();
132    served
133}
134
135fn router(daemon: Client, auth: Arc<auth::Auth>, stopping: watch::Receiver<bool>) -> Router {
136    let proxies = auth.proxies().into();
137    let pages = Router::new()
138        .route("/", get(overview))
139        .route("/history", get(history))
140        .route("/records", get(records))
141        .route("/caches", get(caches))
142        .route("/sizing", get(sizing))
143        .route("/insights", get(insights))
144        .route("/jobs/{id}", get(job))
145        .route("/jobs/{id}/log", get(job_log))
146        .route("/jobs/{id}/cancel", post(actions::cancel_job))
147        .route("/jobs/{id}/rerun", post(actions::rerun_job))
148        .route("/live/overview", get(live::overview))
149        .route("/live/jobs/{id}", get(live::job))
150        .route("/config", get(config).put(actions::save_config))
151        .route("/config/check", post(actions::check_config))
152        .route("/config/diff", post(actions::review_config))
153        .route("/config/doctor", get(config_doctor))
154        .route(
155            "/v1/repositories/{owner}/{name}/pause",
156            post(actions::pause),
157        )
158        .route(
159            "/v1/repositories/{owner}/{name}/resume",
160            post(actions::resume),
161        )
162        .route("/v1/repositories/pause", post(actions::pause_all))
163        .route("/v1/repositories/resume", post(actions::resume_all))
164        .route("/v1/profiles/{name}/reseed", post(actions::reseed))
165        .route("/v1/caches/{name}/clean", post(actions::clean))
166        .route("/v1/records", delete(actions::remove_all_records))
167        .route("/v1/records/{job}", delete(actions::remove_record))
168        .route("/assets/{name}", get(assets::serve))
169        .fallback(|| async { not_found() })
170        .with_state(App {
171            daemon,
172            proxies,
173            stopping,
174        });
175    let login = Router::new()
176        .route("/login", get(auth::login))
177        .route("/pair", post(auth::pair))
178        .with_state(auth.clone());
179    pages
180        .merge(login)
181        .layer(middleware::from_fn_with_state(auth, auth::require_session))
182        .layer(middleware::from_fn(security_headers))
183}
184
185/// No framing, no sniffing, no referrer, and a policy that lets the page load only what this server serves.
186/// Datastar evaluates its attributes with `Function`, hence `'unsafe-eval'`; regions size their blocks with
187/// `style` attributes. `'inline-speculation-rules'` lets the page's speculation rules prefetch the pages it links to
188/// and runs no script.
189async fn security_headers(request: Request, next: Next) -> Response {
190    let mut response = next.run(request).await;
191    let headers = response.headers_mut();
192    headers.insert(
193        header::CONTENT_SECURITY_POLICY,
194        HeaderValue::from_static(
195            "default-src 'none'; script-src 'self' 'unsafe-eval' 'inline-speculation-rules'; style-src 'self' 'unsafe-inline'; \
196             img-src 'self' data:; font-src 'self'; connect-src 'self'; manifest-src 'self'; form-action 'self'; \
197             base-uri 'none'; frame-ancestors 'none'",
198        ),
199    );
200    headers.insert(
201        header::X_CONTENT_TYPE_OPTIONS,
202        HeaderValue::from_static("nosniff"),
203    );
204    headers.insert(
205        header::REFERRER_POLICY,
206        HeaderValue::from_static("no-referrer"),
207    );
208    response
209}
210
211/// The page for an address nothing is at.
212fn not_found() -> Response {
213    (
214        StatusCode::NOT_FOUND,
215        views::error_page("Not found", "There is no page at this address."),
216    )
217        .into_response()
218}
219
220/// A page's query string as it reads, or none of it when it does not: an old or mistyped link shows the page
221/// rather than a plain-text error.
222fn lenient<T: Default>(query: Result<Query<T>, QueryRejection>) -> T {
223    query.map(|Query(query)| query).unwrap_or_default()
224}
225
226/// A page, or the daemon's error as one.
227fn page(rendered: Result<Markup, ClientError>) -> Response {
228    match rendered {
229        Ok(markup) => Html(markup.into_string()).into_response(),
230        Err(ClientError::Api {
231            status: StatusCode::NOT_FOUND,
232            message,
233            ..
234        }) => (
235            StatusCode::NOT_FOUND,
236            views::error_page("Not found", &message),
237        )
238            .into_response(),
239        Err(error) => (
240            StatusCode::BAD_GATEWAY,
241            views::error_page("runnerd did not answer", &error.to_string()),
242        )
243            .into_response(),
244    }
245}
246
247async fn overview(State(app): State<App>) -> Response {
248    page(
249        Overview::load(&app.daemon, now())
250            .await
251            .map(|overview| views::overview::render(&overview)),
252    )
253}
254
255async fn history(
256    State(app): State<App>,
257    filter: Result<Query<Filter>, QueryRejection>,
258) -> Response {
259    let filter = lenient(filter);
260    page(
261        History::load(&app.daemon, filter, now())
262            .await
263            .map(|history| views::history::render(&history)),
264    )
265}
266
267async fn records(State(app): State<App>) -> Response {
268    page(
269        RecordsView::load(&app.daemon, now())
270            .await
271            .map(|records| views::records::render(&records)),
272    )
273}
274
275async fn caches(State(app): State<App>) -> Response {
276    page(
277        CachesView::load(&app.daemon, now())
278            .await
279            .map(|caches| views::caches::render(&caches)),
280    )
281}
282
283async fn sizing(State(app): State<App>) -> Response {
284    page(
285        SizingView::load(&app.daemon, now())
286            .await
287            .map(|sizing| views::sizing::render(&sizing)),
288    )
289}
290
291async fn insights(State(app): State<App>) -> Response {
292    page(
293        InsightsView::load(&app.daemon, now())
294            .await
295            .map(|insights| views::insights::render(&insights)),
296    )
297}
298
299async fn config(
300    State(app): State<App>,
301    query: Result<Query<ConfigQuery>, QueryRejection>,
302) -> Response {
303    let query = lenient(query);
304    page(
305        ConfigView::load(&app.daemon, query, now())
306            .await
307            .map(|config| views::config::render(&config, &app.proxies)),
308    )
309}
310
311/// `GET /config/doctor`: the doctor's region, which the config page asks for once it shows. A daemon that fails or
312/// does not answer in time is a region that says so, since Datastar applies only 200 responses.
313async fn config_doctor(State(app): State<App>) -> Response {
314    let doctor = app.daemon.get("/v1/doctor").await;
315    Html(views::config::doctor(&doctor, now()).into_string()).into_response()
316}
317
318async fn job(
319    State(app): State<App>,
320    UrlPath(id): UrlPath<String>,
321    query: Result<Query<views::job::JobPageQuery>, QueryRejection>,
322) -> Response {
323    // No job has a number past a u64's, which the palette never offers: an address no job is at.
324    let Ok(id) = id.parse::<u64>() else {
325        return not_found();
326    };
327    let query = lenient(query);
328    page(
329        JobView::load(&app.daemon, id, now(), &query)
330            .await
331            .map(|job| views::job::render(&job)),
332    )
333}
334
335/// `GET /jobs/{id}/log`: the whole stored log as text.
336async fn job_log(State(app): State<App>, UrlPath(id): UrlPath<u64>) -> Response {
337    match app.daemon.text(&format!("/v1/jobs/{id}/logs")).await {
338        Ok(text) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text).into_response(),
339        Err(ClientError::Api {
340            status, message, ..
341        }) => (status, message).into_response(),
342        Err(error) => (StatusCode::BAD_GATEWAY, error.to_string()).into_response(),
343    }
344}
345
346#[cfg(test)]
347mod tests;