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