Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Waiting rooms: `Guard::fail_open` (off by default) lets visitors without a pass through when the Hibira waiting page can't be reached (timeout, network error or 5xx, checked with a 1.5 s timeout and cached 15 s). The Axum and Actix Web middleware add a `FailOpen` extension to those requests; `Guard::reachable()` and `Guard::decide_with_fail_open()` for other frameworks.

## 0.1.0

- First release: realtime trigger, channel auth, user sign-in and webhooks; waiting room passes with Axum and Actix Web middleware; Chat API; Approvals with callback verification; Live Chat verified visitors.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ For any other framework, `Guard::decide(method, uri, headers, https)` returns
place per signed-in customer, set `guard.user` to return
`waiting_room::sign_user(secret, room, user_id, ttl, None)`.

Set `guard.fail_open = true` to let visitors without a pass through when the
waiting page can't be reached. Before sending a visitor to the queue, the
middleware checks the room's status URL (`guard.fail_open_timeout`, 1.5 s by
default, cached for 15 s); a timeout, network error or 5xx lets the request
through with an `Extension<FailOpen>` and no `Pass`. It is off by default, so
the queue stays strict unless you choose availability over order. Other
frameworks can call `guard.decide_with_fail_open(...)`, which returns `None`
for such requests.

## Chat API

```rust,ignore
Expand Down Expand Up @@ -146,7 +155,7 @@ For a single-page app, return `identity(...)` as JSON and call
`hibira` 是 [Hibira](https://hibira.io) 的 Rust 伺服器端 SDK:

- **即時(Pusher 協定)**:發送事件、私有與 presence 頻道授權、pusher-js `signin()`、驗證 webhook。
- **等候室**:驗證訪客從託管排隊頁帶回的簽名 pass,提供 Axum 與 Actix Web middleware;其他框架可用 `Guard::decide()`。
- **等候室**:驗證訪客從託管排隊頁帶回的簽名 pass,提供 Axum 與 Actix Web middleware;其他框架可用 `Guard::decide()`。設定 `fail_open = true` 後,若 Hibira 排隊頁連不上(逾時、網路錯誤或 5xx),訪客會直接放行(`FailOpen` extension),預設關閉。
- **Chat API**:建立對話、發訊息、讀取歷史、標記已讀。
- **Approvals**:發出需要人決定的請求並等待結果,`verify_callback()` 驗證 callback 簽名。
- **Live Chat**:`identity()`、`script_tag()` 讓登入使用者以驗證過的身分聊天。
Expand Down
144 changes: 141 additions & 3 deletions src/waiting_room.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,16 @@
//! visitor brings back is checked, stored in the HttpOnly cookie
//! `hibira_wr_<room>` and removed from the URL. This matches
//! `@hibira-io/waiting-room/server`, the Go module and the framework packages.
//!
//! With [`Guard::fail_open`] (off by default), a visitor without a pass is let
//! through when the waiting page can't be reached (timeout, network error or
//! 5xx); the request then carries a [`FailOpen`] extension and no [`Pass`].

use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
Expand Down Expand Up @@ -205,6 +213,58 @@ pub fn waiting_room_url(o: &UrlOptions<'_>) -> String {
url
}

/// The default time [`Guard::reachable`] waits for the waiting page.
pub const DEFAULT_FAIL_OPEN_TIMEOUT: Duration = Duration::from_millis(1500);
const PROBE_CACHE: Duration = Duration::from_secs(15);

/// A boxed future, as returned by a [`Probe`].
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Returns the HTTP status of a GET to the URL within the timeout, or an
/// error for a network failure or timeout. Set [`Guard::probe`] to replace
/// the default (reqwest, with the `client` feature).
pub type Probe = Arc<dyn Fn(String, Duration) -> BoxFuture<Result<u16, String>> + Send + Sync>;

/// Request extension marking a request let in without a pass because the
/// waiting page couldn't be reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FailOpen;

fn probes() -> &'static Mutex<HashMap<String, (bool, Instant)>> {
static PROBES: OnceLock<Mutex<HashMap<String, (bool, Instant)>>> = OnceLock::new();
PROBES.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Forgets the cached reachability checks (for tests).
pub fn forget_probes() {
if let Ok(mut p) = probes().lock() {
p.clear();
}
}

#[cfg(feature = "client")]
fn default_probe(url: String, timeout: Duration) -> BoxFuture<Result<u16, String>> {
Box::pin(async move {
let client = reqwest::Client::builder()
.timeout(timeout)
.connect_timeout(timeout)
.build()
.map_err(|e| e.to_string())?;
let res = client
.get(&url)
.header("accept", "application/json")
.send()
.await
.map_err(|e| e.to_string())?;
Ok(res.status().as_u16())
})
}

#[cfg(not(feature = "client"))]
fn default_probe(_url: String, _timeout: Duration) -> BoxFuture<Result<u16, String>> {
Box::pin(async { Err("fail-open needs the `client` feature or Guard::probe".to_string()) })
}

/// Protects pages with one waiting room.
#[derive(Clone, Default)]
pub struct Guard {
Expand All @@ -224,6 +284,13 @@ pub struct Guard {
pub user: Option<std::sync::Arc<dyn Fn(&HeaderMap) -> Option<String> + Send + Sync>>,
/// Unix seconds; defaults to now (for tests).
pub now: Option<i64>,
/// Let visitors without a pass through when the waiting page can't be
/// reached (timeout, network error or 5xx). Off by default.
pub fail_open: bool,
/// How long the fail-open check waits; defaults to [`DEFAULT_FAIL_OPEN_TIMEOUT`].
pub fail_open_timeout: Option<Duration>,
/// Replaces the HTTP check used for fail-open (for tests).
pub probe: Option<Probe>,
}

impl std::fmt::Debug for Guard {
Expand Down Expand Up @@ -275,6 +342,63 @@ impl Guard {
.unwrap_or_else(|| format!("hibira_wr_{}", self.room))
}

/// True when the room's status URL answers below 500 within the timeout.
/// The answer is kept for 15 seconds per room.
pub async fn reachable(&self) -> bool {
let host = self
.host
.as_deref()
.unwrap_or(DEFAULT_HOST)
.trim_end_matches('/');
let url = format!(
"{host}/waitroom/{}/{}",
utf8_percent_encode(&self.app_key, PATH_SEGMENT),
utf8_percent_encode(&self.room, PATH_SEGMENT)
);
if let Some((up, until)) = probes().lock().ok().and_then(|p| p.get(&url).copied()) {
if Instant::now() < until {
return up;
}
}
let timeout = self.fail_open_timeout.unwrap_or(DEFAULT_FAIL_OPEN_TIMEOUT);
let fut = match &self.probe {
Some(p) => p(url.clone(), timeout),
None => default_probe(url.clone(), timeout),
};
let up = matches!(fut.await, Ok(status) if status < 500);
if let Ok(mut p) = probes().lock() {
p.insert(url, (up, Instant::now() + PROBE_CACHE));
}
up
}

/// True when fail-open is on and `decision` would send a visitor without
/// a pass to the queue or refuse them, so [`Guard::reachable`] decides.
pub fn needs_fail_open_check(&self, decision: &Decision) -> bool {
self.fail_open
&& match decision {
Decision::Allow(_) => false,
Decision::Deny => true,
Decision::Redirect { set_cookie, .. } => set_cookie.is_none(),
}
}

/// Like [`Guard::decide`], then applies fail-open: returns `None` when the
/// request should go through without a pass.
pub async fn decide_with_fail_open(
&self,
method: &Method,
uri: &Uri,
headers: &HeaderMap,
https: bool,
) -> Option<Decision> {
let decision = self.decide(method, uri, headers, https);
if self.needs_fail_open_check(&decision) && !self.reachable().await {
return None;
}
Some(decision)
}

/// Works out what to do with a request. `https` is whether the request
/// came over TLS; `X-Forwarded-Proto: https` also counts.
pub fn decide(&self, method: &Method, uri: &Uri, headers: &HeaderMap, https: bool) -> Decision {
Expand Down Expand Up @@ -376,7 +500,14 @@ pub async fn axum_guard(
) -> axum::response::Response {
use axum::response::IntoResponse;
let https = request.uri().scheme_str() == Some("https");
match guard.decide(request.method(), request.uri(), request.headers(), https) {
let Some(decision) = guard
.decide_with_fail_open(request.method(), request.uri(), request.headers(), https)
.await
else {
request.extensions_mut().insert(FailOpen);
return next.run(request).await;
};
match decision {
Decision::Allow(pass) => {
request.extensions_mut().insert(pass);
next.run(request).await
Expand Down Expand Up @@ -438,7 +569,14 @@ pub async fn actix_guard<B: actix_web::body::MessageBody + 'static>(
headers.append(k, v);
}
}
let response = match guard.decide(&method, &uri, &headers, https) {
let Some(decision) = guard
.decide_with_fail_open(&method, &uri, &headers, https)
.await
else {
request.extensions_mut().insert(FailOpen);
return Ok(next.call(request).await?.map_into_left_body());
};
let response = match decision {
Decision::Allow(pass) => {
request.extensions_mut().insert(pass);
return Ok(next.call(request).await?.map_into_left_body());
Expand Down
38 changes: 38 additions & 0 deletions tests/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,44 @@ mod axum_tests {
}
}

mod axum_fail_open_tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use axum::routing::get;
use axum::Extension;
use hibira::waiting_room::FailOpen;
use tower::ServiceExt;

#[tokio::test]
async fn lets_visitors_in_when_the_waiting_page_is_down() {
let mut g = Guard::new("key-axum-fo", SECRET, "presale");
g.fail_open = true;
g.probe = Some(Arc::new(|_, _| Box::pin(async { Ok(503) })));
let app = axum::Router::new()
.route(
"/drop",
get(|Extension(f): Extension<FailOpen>| async move { format!("{f:?}") }),
)
.layer(axum::middleware::from_fn_with_state(
Arc::new(g),
axum_guard,
));
let res = app
.oneshot(
Request::get("/drop")
.header("host", "shop.test")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), 200);
let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
assert_eq!(&body[..], b"FailOpen");
}
}

mod actix_tests {
use super::*;
use actix_web::{middleware::from_fn, test, web, App, HttpResponse};
Expand Down
66 changes: 66 additions & 0 deletions tests/waiting_room.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,69 @@ fn guard_passes_a_signed_user() {
other => panic!("{other:?}"),
}
}

fn probe_returning(
status: Result<u16, String>,
calls: std::sync::Arc<std::sync::Mutex<Vec<(String, u128)>>>,
) -> hibira::waiting_room::Probe {
std::sync::Arc::new(move |url, timeout| {
calls.lock().unwrap().push((url, timeout.as_millis()));
let status = status.clone();
Box::pin(async move { status })
})
}

#[tokio::test]
async fn fail_open_lets_visitors_through_when_the_waiting_page_is_down() {
let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let mut g = Guard::new("key-fo", SECRET, "presale");
g.now = Some(NOW);
g.fail_open = true;
g.probe = Some(probe_returning(Ok(522), calls.clone()));
let uri: Uri = "/drop".parse().unwrap();
let h = headers(&[("host", "shop.test")]);
assert_eq!(
g.decide_with_fail_open(&Method::GET, &uri, &h, true).await,
None
);
assert_eq!(
g.decide_with_fail_open(&Method::POST, &uri, &h, true).await,
None
);
assert_eq!(
*calls.lock().unwrap(),
vec![(
"https://ws.hibira.io/waitroom/key-fo/presale".to_string(),
1500
)]
);
}

#[tokio::test]
async fn fail_open_keeps_the_queue_when_up_and_treats_errors_as_down() {
let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let uri: Uri = "/drop".parse().unwrap();
let h = headers(&[("host", "shop.test")]);

let mut up = Guard::new("key-up", SECRET, "presale");
up.fail_open = true;
up.probe = Some(probe_returning(Ok(200), calls.clone()));
assert!(matches!(
up.decide_with_fail_open(&Method::GET, &uri, &h, true).await,
Some(Decision::Redirect { .. })
));

let mut err = Guard::new("key-err", SECRET, "presale");
err.fail_open = true;
err.probe = Some(probe_returning(Err("timed out".into()), calls.clone()));
assert!(!err.reachable().await);

let mut off = Guard::new("key-off", SECRET, "presale");
off.probe = Some(probe_returning(Ok(503), calls.clone()));
assert!(matches!(
off.decide_with_fail_open(&Method::GET, &uri, &h, true)
.await,
Some(Decision::Redirect { .. })
));
assert_eq!(calls.lock().unwrap().len(), 2);
}