//! `ipx-play` (#447): the page a shared episode opens, at `play.ipxreader.app/e/`, as //! Overcast's links do. When someone shares an episode, their ipx server sends it here with its //! token and gets back a short link; anyone with the link sees the episode, its show and its //! notes, and plays it from the publisher's own file, from the time it was shared at if it was. //! //! Only public episodes come here: ipx sends none from a private or paid feed, and this refuses //! an address that looks like one (`ipx_feed::url_looks_private`), which would hand out the //! sharer's subscription. The files stay the publisher's; this keeps what an episode is and where //! its file is, nothing more. pub mod config; pub mod metrics; mod page; pub mod store; use axum::extract::{MatchedPath, Path, Query, Request, State}; use axum::http::{StatusCode, header}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Extension, Json, Router}; use serde::{Deserialize, Serialize}; use std::sync::Arc; use std::time::Instant; use tracing::Instrument; /// An episode as ipx sends it to be shared. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Episode { pub feed_url: String, pub guid: String, pub feed_title: Option, pub feed_image: Option, pub title: Option, /// The feed's own HTML for it, sanitized here when the page is drawn. pub description: Option, pub link: Option, /// Unix seconds. pub published: Option, /// Seconds. pub duration: Option, /// The publisher's file, which the page plays. pub audio_url: String, pub mime: Option, } /// What ipx gets back: the link to hand on, to which it adds `?t=` for a time. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Shared { pub id: String, pub url: String, } /// An episode kept, by its id. #[derive(Debug, Clone)] pub struct Share { pub id: String, pub episode: Episode, } /// Longer than any real one, short enough that nobody keeps a book here. const MAX_TEXT: usize = 100_000; const MAX_SHORT: usize = 2_000; impl Episode { /// What makes an episode unfit to keep, in words for whoever sent it; None when it is fine. /// Over-long text is cut to fit rather than refused: a show's notes can be long. fn check(&mut self) -> Option<&'static str> { let web = |u: &str| url::Url::parse(u).is_ok_and(|u| matches!(u.scheme(), "http" | "https")); if !web(&self.feed_url) || !web(&self.audio_url) { return Some("the feed and its file need http(s) addresses"); } if ipx_feed::url_looks_private(&self.feed_url) || ipx_feed::url_looks_private(&self.audio_url) { return Some("that looks like a private or paid feed, whose addresses carry someone's access"); } if self.guid.trim().is_empty() || self.guid.len() > MAX_SHORT { return Some("an episode needs its guid"); } if self.feed_image.as_deref().is_some_and(|u| !web(u)) { self.feed_image = None; } if self.link.as_deref().is_some_and(|u| !web(u)) { self.link = None; } for (s, max) in [(&mut self.title, MAX_SHORT), (&mut self.feed_title, MAX_SHORT), (&mut self.description, MAX_TEXT)] { if let Some(t) = s && t.len() > max { let mut end = max; while !t.is_char_boundary(end) { end -= 1; } t.truncate(end); } } None } } /// What every request shares. pub struct Play { pub store: store::Store, pub tokens: Vec, pub base: String, } type St = Arc; /// Each route's protobuf messages (#465), beside its JSON. const WIRE: ipx_wire::Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")]; pub fn router(play: Play) -> Router { let st = Arc::new(play); let api = Router::new() .route("/v1/shares", post(share)) .route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate)) .layer(axum::middleware::from_fn_with_state(st.clone(), authenticate)); Router::new() .route("/healthz", get(healthz)) .route("/e/{id}", get(episode_page)) .route("/play.css", get(|| async { page::asset("text/css; charset=utf-8", include_bytes!("play.css")) })) .route("/logo.svg", get(|| async { page::asset("image/svg+xml", include_bytes!("../../../web/logo.svg")) })) .route("/favicon.png", get(|| async { page::asset("image/png", include_bytes!("../../../web/favicon.png")) })) .merge(api) .fallback(|| async { page::not_found() }) .layer(axum::middleware::from_fn(access_log)) .with_state(st) } /// Which server made the request, for the log and the share, set by `authenticate`. #[derive(Clone)] struct Who(String); async fn authenticate(State(st): State, mut req: Request, next: Next) -> Response { let presented = req .headers() .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) .map(str::trim) .filter(|t| !t.is_empty()); let who = presented.and_then(|t| { let h = ipx_directory::config::hash(t); st.tokens.iter().find(|k| ipx_directory::config::same_secret(&k.sha256, &h)).map(|k| k.name.clone()) }); let Some(who) = who else { return error(StatusCode::UNAUTHORIZED, "a valid token is needed: Authorization: Bearer "); }; req.extensions_mut().insert(Who(who.clone())); let mut resp = next.run(req).await; resp.extensions_mut().insert(Who(who)); resp } fn error(status: StatusCode, msg: &str) -> Response { (status, Json(serde_json::json!({ "error": msg }))).into_response() } #[tracing::instrument(name = "share", skip_all, fields(server = %who.0))] async fn share(State(st): State, Extension(who): Extension, Json(mut e): Json) -> Response { if let Some(why) = e.check() { return error(StatusCode::UNPROCESSABLE_ENTITY, why); } match st.store.put(&who.0, &e).await { Ok(id) => { metrics::SHARES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); tracing::info!(server = %who.0, id = %id, "an episode was shared"); Json(Shared { url: format!("{}/e/{id}", st.base), id }).into_response() } Err(err) => { tracing::error!(error = %format!("{err:#}"), "keeping a share failed"); error(StatusCode::INTERNAL_SERVER_ERROR, "it could not be kept; ipx-play's log says why") } } } #[derive(Deserialize)] struct At { /// Where to start: seconds, or as written, `12:34` or `1:02:03`. t: Option, } async fn episode_page(State(st): State, Path(id): Path, Query(at): Query) -> Response { match st.store.get(&id).instrument(tracing::info_span!("step", of = "get_share")).await { Ok(Some(s)) => page::episode(&s, at.t.as_deref().and_then(page::parse_time), &st.base), Ok(None) => page::not_found(), Err(err) => { tracing::error!(error = %format!("{err:#}"), "reading a share failed"); page::failed() } } } async fn healthz(State(st): State) -> Response { match st.store.ping().await { Ok(()) => (StatusCode::OK, "ok").into_response(), Err(e) => (StatusCode::SERVICE_UNAVAILABLE, format!("database: {e:#}")).into_response(), } } /// A span a request, joined to the caller's trace when it sent a traceparent, as ipx does on its /// calls here; and a line, with the server's name and never its token. async fn access_log(req: Request, next: Next) -> Response { let (method, path) = (req.method().clone(), req.uri().path().to_owned()); // By route, not path: by path each shared episode would be a row of its own. A path no route // has is "", which someone trying addresses cannot multiply. let route = req.extensions().get::().map_or("", |r| r.as_str()).to_owned(); let start = Instant::now(); let span = if path == "/healthz" { tracing::Span::none() } else { tracing::info_span!( "http", otel.name = %format!("{method} {}", if path.starts_with("/e/") { "/e/{id}" } else { path.as_str() }), http.request.method = %method, url.path = %path, http.response.status_code = tracing::field::Empty, ) }; if let Some(parent) = ipx_directory::otel::remote_parent(req.headers(), None) { use tracing_opentelemetry::OpenTelemetrySpanExt; let _ = span.set_parent(parent); } let resp = next.run(req).instrument(span.clone()).await; let status = resp.status().as_u16(); span.record("http.response.status_code", status); if path != "/healthz" { metrics::REQUESTS.observe( &format!( "method=\"{}\",route=\"{}\",status=\"{status}\"", ipx_directory::metrics::method(method.as_str()), ipx_directory::metrics::label(&route) ), start.elapsed().as_secs_f64(), ); let _in = span.enter(); let who = resp.extensions().get::().map_or("", |w| w.0.as_str()).to_owned(); tracing::info!( target: "ipx_play::http", method = %method, path = %path, status, duration_ms = start.elapsed().as_millis() as u64, token = %who, "{method} {path} -> {status}" ); } resp } #[cfg(test)] mod tests { use super::*; use axum::body::Body; use tower::ServiceExt; const TOKEN: &str = "ipxd_test"; async fn app() -> Router { router(Play { store: store::Store::scratch().await, tokens: vec![config::Token { name: "tower".into(), sha256: ipx_directory::config::hash(TOKEN) }], base: "https://play.test".into(), }) } fn episode() -> Episode { Episode { feed_url: "https://example.com/feed.xml".into(), guid: "ep-1".into(), feed_title: Some("A Show".into()), feed_image: Some("https://example.com/art.jpg".into()), title: Some("Episode ".into()), description: Some("

Notes

".into()), link: Some("javascript:alert(1)".into()), published: Some(1_800_000_000), duration: Some(3600), audio_url: "https://example.com/ep1.mp3".into(), mime: Some("audio/mpeg".into()), } } async fn post(app: &Router, token: Option<&str>, e: &Episode) -> (StatusCode, serde_json::Value) { let mut req = axum::http::Request::post("/v1/shares").header("content-type", "application/json"); if let Some(t) = token { req = req.header("authorization", format!("Bearer {t}")); } let resp = app.clone().oneshot(req.body(Body::from(serde_json::to_vec(e).unwrap())).unwrap()).await.unwrap(); let status = resp.status(); let body = axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap(); (status, serde_json::from_slice(&body).unwrap_or_default()) } async fn get(app: &Router, path: &str) -> (StatusCode, String) { let resp = app.clone().oneshot(axum::http::Request::get(path).body(Body::empty()).unwrap()).await.unwrap(); let status = resp.status(); let body = axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap(); (status, String::from_utf8_lossy(&body).into_owned()) } #[tokio::test] async fn a_server_with_a_token_makes_a_link_and_anyone_opens_it() { let app = app().await; assert_eq!(post(&app, None, &episode()).await.0, StatusCode::UNAUTHORIZED); assert_eq!(post(&app, Some("wrong"), &episode()).await.0, StatusCode::UNAUTHORIZED); let (status, body) = post(&app, Some(TOKEN), &episode()).await; assert_eq!(status, StatusCode::OK); let url = body["url"].as_str().unwrap(); assert!(url.starts_with("https://play.test/e/"), "{url}"); let path = url.trim_start_matches("https://play.test"); let (status, html) = get(&app, &format!("{path}?t=12:34")).await; assert_eq!(status, StatusCode::OK); assert!(html.contains("Episode <One>"), "the title, escaped"); assert!(html.contains("ep1.mp3#t=754"), "the player starts at the time shared"); assert!(html.contains("Starts at 12:34")); assert!(html.contains(r#"property="og:title""#), "a link preview"); assert!(!html.contains("