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