CI / Check (push) Successful in 5m59s
Pages polled `/api/version` every three seconds, then fetched the pending list and replaced it, or reloaded a request's page. Now each page follows one stream from `/events`, whose `morph` events carry a region of the page: the pending list, or the request, as a whole element with its `id`, rendered by the page's own templates. The page script morphs it into the page with idiomorph, vendored, so open details, the focus and typing stay. The stream starts with the current region, so a page catches up when the browser reconnects, and it ends when the approver signs out. `/api/version` and `/pending` are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
188 lines
7.1 KiB
Rust
188 lines
7.1 KiB
Rust
//! Keeps open pages current with one stream of Server-Sent Events each.
|
|
//!
|
|
//! - Each `morph` event carries a region of the page: a whole element with its `id`, which the
|
|
//! page script morphs into the one it has, so open details and the focus stay. The main page's
|
|
//! region is the pending list (`#pending`), and a request's page's is the request (`#request`).
|
|
//! - A region comes when the stream starts, so a page catches up after reconnecting, and then
|
|
//! whenever it changes.
|
|
//! - `signed-out` ends the stream, when the approver signs out or the session expires.
|
|
use std::convert::Infallible;
|
|
use std::future::Future;
|
|
use std::pin::Pin;
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use axum::response::sse::{Event, KeepAlive, Sse};
|
|
use axum::response::{IntoResponse, Response};
|
|
use tokio::sync::watch;
|
|
use tower_sessions::Session;
|
|
|
|
use super::{User, page};
|
|
use crate::server::Broker;
|
|
|
|
/// How often a page gets updates at most.
|
|
const INTERVAL: Duration = Duration::from_secs(1);
|
|
|
|
/// The signed-in approver's CSRF token, or `None` once they've signed out.
|
|
type SignedIn = Box<dyn FnMut() -> Pin<Box<dyn Future<Output = Option<String>> + Send>> + Send>;
|
|
|
|
pub fn stream(broker: Arc<Broker>, session: Session, request: Option<String>) -> Response {
|
|
let signed_in: SignedIn = Box::new(move || {
|
|
let session = session.clone();
|
|
Box::pin(async move { session.get::<User>(super::USER).await.ok().flatten().map(|user| user.csrf) })
|
|
});
|
|
let updates = Updates::new(broker, signed_in, request);
|
|
|
|
let events = futures_util::stream::unfold(updates, |mut updates| async move {
|
|
let (name, data) = updates.next().await?;
|
|
Some((Ok::<_, Infallible>(Event::default().event(name).data(data)), updates))
|
|
});
|
|
|
|
let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response();
|
|
// Proxies such as nginx would otherwise hold events back.
|
|
response.headers_mut().insert("x-accel-buffering", axum::http::HeaderValue::from_static("no"));
|
|
response
|
|
}
|
|
|
|
struct Updates {
|
|
broker: Arc<Broker>,
|
|
signed_in: SignedIn,
|
|
/// The request whose page it is, or none for the main page.
|
|
request: Option<String>,
|
|
queue: watch::Receiver<u64>,
|
|
/// The region last sent.
|
|
sent: Option<String>,
|
|
last: Option<Instant>,
|
|
ended: bool,
|
|
}
|
|
|
|
impl Updates {
|
|
fn new(broker: Arc<Broker>, signed_in: SignedIn, request: Option<String>) -> Updates {
|
|
let queue = broker.queue.subscribe();
|
|
Updates { broker, signed_in, request, queue, sent: None, last: None, ended: false }
|
|
}
|
|
|
|
/// The next event, as a name and data, once something changes; `None` ends the stream.
|
|
async fn next(&mut self) -> Option<(&'static str, String)> {
|
|
if self.ended {
|
|
return None;
|
|
}
|
|
|
|
loop {
|
|
// The region at first, then when it changes, at most once an interval
|
|
if let Some(last) = self.last {
|
|
self.queue.changed().await.ok()?;
|
|
tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await;
|
|
}
|
|
self.last = Some(Instant::now());
|
|
self.queue.borrow_and_update();
|
|
|
|
// Signing out, or the session expiring, ends it.
|
|
let Some(csrf) = (self.signed_in)().await else {
|
|
self.ended = true;
|
|
return Some(("signed-out", "signed out".into()));
|
|
};
|
|
|
|
let region = self.region(&csrf);
|
|
if self.sent.as_ref() != Some(®ion) {
|
|
self.sent = Some(region.clone());
|
|
return Some(("morph", region));
|
|
}
|
|
}
|
|
}
|
|
|
|
fn region(&self, csrf: &str) -> String {
|
|
match &self.request {
|
|
None => page::pending(csrf, &self.broker.queue.list(), &self.broker.queue.all_leases()),
|
|
Some(id) => {
|
|
let entry = self.broker.queue.list().into_iter().find(|e| &e.id == id);
|
|
let past = super::past(&self.broker, id);
|
|
let view = page::RequestView { id, entry: entry.as_ref(), past: past.as_ref() };
|
|
page::request_region(csrf, &view)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use super::*;
|
|
use crate::detail::Detail;
|
|
use crate::queue::NewRequest;
|
|
|
|
fn broker() -> Arc<Broker> {
|
|
let config = serde_json::from_value(serde_json::json!({
|
|
"requesters": {},
|
|
"policies": {},
|
|
"approve_socket": "/unused",
|
|
"approver_group": "root",
|
|
}))
|
|
.unwrap();
|
|
Arc::new(Broker::new(config).unwrap())
|
|
}
|
|
|
|
fn submit(broker: &Broker, id: &str) -> tokio::sync::oneshot::Receiver<crate::queue::Outcome> {
|
|
let request = NewRequest {
|
|
requester: "agent".into(),
|
|
op: "ssh".into(),
|
|
lease_key: "k".into(),
|
|
summary: "ssh river".into(),
|
|
detail: Detail::new(),
|
|
label: None,
|
|
sensitive: false,
|
|
passkey: false,
|
|
leases: vec![300],
|
|
};
|
|
broker.queue.submit(id, request, 4).unwrap()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_main_page_gets_its_list_as_it_changes() {
|
|
let broker = broker();
|
|
let signed_out = Arc::new(AtomicBool::new(false));
|
|
let check = signed_out.clone();
|
|
let signed_in: SignedIn = Box::new(move || {
|
|
let out = check.load(Ordering::SeqCst);
|
|
Box::pin(async move { (!out).then(|| "token".to_owned()) })
|
|
});
|
|
let mut updates = Updates::new(broker.clone(), signed_in, None);
|
|
|
|
// The list to start with, as a whole element
|
|
let (name, data) = updates.next().await.unwrap();
|
|
assert_eq!(name, "morph");
|
|
assert!(data.starts_with(r#"<div id="pending">"#) && data.contains("Nothing is waiting"), "{data}");
|
|
|
|
// A new request, then its leaving
|
|
let _reply = submit(&broker, "abc");
|
|
let (_, data) = updates.next().await.unwrap();
|
|
assert!(data.contains("ssh river"), "{data}");
|
|
broker.queue.cancel("abc");
|
|
let (_, data) = updates.next().await.unwrap();
|
|
assert!(data.contains("Nothing is waiting"), "{data}");
|
|
|
|
signed_out.store(true, Ordering::SeqCst);
|
|
let _reply = submit(&broker, "def");
|
|
assert_eq!(updates.next().await.unwrap().0, "signed-out");
|
|
assert!(updates.next().await.is_none());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_request_page_gets_its_request() {
|
|
let broker = broker();
|
|
let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) }));
|
|
let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into()));
|
|
|
|
let (_, data) = updates.next().await.unwrap();
|
|
assert!(data.starts_with(r#"<div id="request" data-id="abc">"#), "{data}");
|
|
assert!(data.contains("The audit log has nothing"), "{data}");
|
|
|
|
// Other requests change nothing here, so nothing comes until this one does
|
|
let _other = submit(&broker, "xyz");
|
|
let _reply = submit(&broker, "abc");
|
|
let (_, data) = updates.next().await.unwrap();
|
|
assert!(data.contains("<h1>ssh river</h1>"), "{data}");
|
|
}
|
|
}
|