merge: worktree-agent-ae4267aa66ffa0b0a
This commit is contained in:
@@ -582,3 +582,275 @@ async fn sso_endpoints_are_rate_limited_per_source() {
|
||||
);
|
||||
assert!(h.state.limits.oidc_login_allowed(other));
|
||||
}
|
||||
|
||||
// ---- pairing, the ways it must say no ----
|
||||
|
||||
const START: &str = "/api/v1/wormhole/pairing";
|
||||
const CLAIM: &str = "/api/v1/wormhole/claim";
|
||||
|
||||
/// A different source address each time, so the per-source claim limit does not interfere.
|
||||
fn fresh_peer() -> String {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
format!("192.0.{}.{}", (n >> 8) & 255, n & 255)
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
async fn start_code(&self) -> String {
|
||||
let start = self
|
||||
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
|
||||
.await;
|
||||
assert_eq!(start.status(), StatusCode::OK);
|
||||
json_of(start).await["code"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
async fn claim(&self, _peer: &str, body: Value) -> Response<Body> {
|
||||
self.call(request("POST", CLAIM, &fresh_peer(), None, Some(body)))
|
||||
.await
|
||||
}
|
||||
|
||||
fn outposts(&self) -> i64 {
|
||||
self.scalar("SELECT COUNT(*) FROM outposts")
|
||||
}
|
||||
|
||||
fn credentials(&self) -> i64 {
|
||||
self.scalar("SELECT COUNT(*) FROM outpost_credentials")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_an_admin_can_start_a_pairing() {
|
||||
let h = harness().await;
|
||||
for auth in [None, Some("wrong-token"), Some("")] {
|
||||
let status = h
|
||||
.status(request("POST", START, "127.0.0.1", auth, None))
|
||||
.await;
|
||||
assert!(
|
||||
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
|
||||
"{auth:?} must not start a pairing, got {status}"
|
||||
);
|
||||
}
|
||||
// a paired agent's upload token is not an operator credential either
|
||||
let (_, token) = h.pair("agent").await;
|
||||
let status = h
|
||||
.status(as_outpost(
|
||||
request("POST", START, "198.51.100.20", None, None),
|
||||
&token,
|
||||
))
|
||||
.await;
|
||||
assert!(
|
||||
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
|
||||
"an outpost token must not start a pairing, got {status}"
|
||||
);
|
||||
let codes: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes WHERE consumed_at IS NULL");
|
||||
assert_eq!(codes, 0, "a refused request leaves no code behind");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_started_code_is_twelve_unambiguous_characters_valid_for_about_ten_minutes() {
|
||||
let h = harness().await;
|
||||
let start = h
|
||||
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
|
||||
.await;
|
||||
let body = json_of(start).await;
|
||||
let code = body["code"].as_str().unwrap();
|
||||
assert_eq!(code.len(), 12);
|
||||
assert!(
|
||||
code.chars()
|
||||
.all(|c| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(c)),
|
||||
"no 0/O/1/I lookalikes: {code}"
|
||||
);
|
||||
let expires = chrono::DateTime::parse_from_rfc3339(body["expires_at"].as_str().unwrap())
|
||||
.unwrap()
|
||||
.timestamp();
|
||||
let in_secs = expires - chrono::Utc::now().timestamp();
|
||||
assert!((595..=600).contains(&in_secs), "expires in {in_secs}s");
|
||||
assert_ne!(code, h.start_code().await, "codes are not repeated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_claim_that_is_refused_creates_no_outpost_and_no_credential() {
|
||||
let h = harness().await;
|
||||
let code = h.start_code().await;
|
||||
let lower = code.to_lowercase();
|
||||
let spaced = format!(" {code} ");
|
||||
let truncated = code[..11].to_string();
|
||||
for wrong in [
|
||||
lower.as_str(),
|
||||
spaced.as_str(),
|
||||
truncated.as_str(),
|
||||
"",
|
||||
"AAAAAAAAAAAA",
|
||||
"'; DROP TABLE pairing_codes;--",
|
||||
] {
|
||||
let response = h
|
||||
.claim("198.51.100.20", json!({"code": wrong, "outpost_name": "x"}))
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::GONE, "code {wrong:?}");
|
||||
}
|
||||
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||
let failed: i64 = h.scalar(
|
||||
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
|
||||
);
|
||||
assert_eq!(failed, 6, "every refusal is audited");
|
||||
let leaked: i64 = h.scalar(&format!(
|
||||
"SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{code}%'"
|
||||
));
|
||||
assert_eq!(leaked, 0, "the code is never written to the audit log");
|
||||
// the real code still works afterwards: wrong guesses do not burn it
|
||||
let ok = h
|
||||
.claim(
|
||||
"198.51.100.20",
|
||||
json!({"code": code, "outpost_name": "real"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(ok.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_claim_with_a_bad_name_is_refused_before_the_code_is_spent() {
|
||||
let h = harness().await;
|
||||
let code = h.start_code().await;
|
||||
let too_long = "n".repeat(129);
|
||||
for name in [
|
||||
"",
|
||||
" ",
|
||||
"\t\n",
|
||||
"tab\there",
|
||||
"nul\u{0}byte",
|
||||
too_long.as_str(),
|
||||
] {
|
||||
let response = h
|
||||
.claim("198.51.100.20", json!({"code": code, "outpost_name": name}))
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "name {name:?}");
|
||||
}
|
||||
assert_eq!(h.outposts(), 0);
|
||||
let longest = "n".repeat(128);
|
||||
let ok = h
|
||||
.claim(
|
||||
"198.51.100.20",
|
||||
json!({"code": code, "outpost_name": longest}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(ok.status(), StatusCode::OK, "128 characters is allowed");
|
||||
assert_eq!(h.outposts(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_claims_are_client_errors_and_never_touch_a_code() {
|
||||
let h = harness().await;
|
||||
let code = h.start_code().await;
|
||||
for body in [
|
||||
json!({}),
|
||||
json!({"code": code}),
|
||||
json!({"outpost_name": "x"}),
|
||||
json!({"code": 12345, "outpost_name": "x"}),
|
||||
json!({"code": null, "outpost_name": "x"}),
|
||||
json!({"code": ["a"], "outpost_name": "x"}),
|
||||
] {
|
||||
let status = h.claim("198.51.100.20", body.clone()).await.status();
|
||||
assert!(
|
||||
status.is_client_error() && status != StatusCode::GONE,
|
||||
"{body} gave {status}"
|
||||
);
|
||||
}
|
||||
let good = format!(r#"{{"code":"{code}","outpost_name":"x"}}"#);
|
||||
let raw = |content_type: Option<&str>, body: &str| {
|
||||
let mut builder = Request::builder()
|
||||
.method("POST")
|
||||
.uri(CLAIM)
|
||||
.extension(ConnectInfo(
|
||||
format!("{}:4000", fresh_peer())
|
||||
.parse::<SocketAddr>()
|
||||
.unwrap(),
|
||||
));
|
||||
if let Some(content_type) = content_type {
|
||||
builder = builder.header(header::CONTENT_TYPE, content_type);
|
||||
}
|
||||
builder.body(Body::from(body.to_string())).unwrap()
|
||||
};
|
||||
for request in [
|
||||
raw(Some("application/json"), "{not json"),
|
||||
raw(None, &good),
|
||||
raw(Some("text/plain"), &good),
|
||||
] {
|
||||
let status = h.status(request).await;
|
||||
assert!(status.is_client_error(), "got {status}");
|
||||
}
|
||||
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||
let ok = h
|
||||
.claim("198.51.100.20", json!({"code": code, "outpost_name": "x"}))
|
||||
.await;
|
||||
assert_eq!(
|
||||
ok.status(),
|
||||
StatusCode::OK,
|
||||
"the code survived every bad request"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_enormous_code_is_refused_without_trouble() {
|
||||
let h = harness().await;
|
||||
let huge = "A".repeat(1 << 20);
|
||||
let status = h
|
||||
.claim("198.51.100.20", json!({"code": huge, "outpost_name": "x"}))
|
||||
.await
|
||||
.status();
|
||||
assert!(
|
||||
status == StatusCode::GONE || status == StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"got {status}"
|
||||
);
|
||||
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_claimed_code_cannot_be_replayed_and_the_replay_is_audited() {
|
||||
let h = harness().await;
|
||||
let code = h.start_code().await;
|
||||
let first = h
|
||||
.claim(
|
||||
"198.51.100.20",
|
||||
json!({"code": code, "outpost_name": "first"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(first.status(), StatusCode::OK);
|
||||
let second = h
|
||||
.claim(
|
||||
"198.51.100.21",
|
||||
json!({"code": code, "outpost_name": "second"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(second.status(), StatusCode::GONE);
|
||||
assert_eq!((h.outposts(), h.credentials()), (1, 1), "no second outpost");
|
||||
let failed: i64 = h.scalar(
|
||||
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
|
||||
);
|
||||
assert_eq!(failed, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_expired_code_is_refused_and_old_ones_are_swept_by_the_next_pairing() {
|
||||
let h = harness().await;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
h.state
|
||||
.db
|
||||
.insert_pairing("old-outpost", "STALECODE234", now - 1)
|
||||
.unwrap();
|
||||
h.state
|
||||
.db
|
||||
.insert_pairing("ancient-outpost", "ANCIENTCODE2", now - 200_000)
|
||||
.unwrap();
|
||||
let response = h
|
||||
.claim(
|
||||
"198.51.100.20",
|
||||
json!({"code": "STALECODE234", "outpost_name": "late"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::GONE);
|
||||
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||
h.start_code().await;
|
||||
// a code that expired a moment ago lingers (the claim still refuses it); one a day old is deleted
|
||||
let rows: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes");
|
||||
assert_eq!(rows, 2, "the recent stale code and the fresh one remain");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,10 @@ use axum::body::Bytes;
|
||||
use futures_core::Stream;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{
|
||||
atomic::{AtomicU64, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use uuid::Uuid;
|
||||
@@ -170,6 +173,26 @@ pub struct ExportGate {
|
||||
permits: Arc<Semaphore>,
|
||||
/// Free space that must remain after the export has been written.
|
||||
min_free: u64,
|
||||
/// Bytes promised to exports that are admitted and not finished yet. Free space alone cannot say
|
||||
/// that, because an export that has only just started has barely written anything.
|
||||
reserved: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
/// The most one export may reserve: 64 of them (the concurrency ceiling) still fit in a `u64`.
|
||||
const MAX_RESERVATION: u64 = 1 << 57;
|
||||
|
||||
/// An admitted export: its place among the running ones and the disk it was promised. Both are given
|
||||
/// back when this is dropped.
|
||||
pub struct Admission {
|
||||
_permit: OwnedSemaphorePermit,
|
||||
reserved: Arc<AtomicU64>,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
impl Drop for Admission {
|
||||
fn drop(&mut self) {
|
||||
self.reserved.fetch_sub(self.size, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Refused {
|
||||
@@ -184,6 +207,7 @@ impl ExportGate {
|
||||
Self {
|
||||
permits: Arc::new(Semaphore::new(concurrency)),
|
||||
min_free,
|
||||
reserved: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,17 +224,31 @@ impl ExportGate {
|
||||
)
|
||||
}
|
||||
|
||||
/// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body.
|
||||
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<OwnedSemaphorePermit, Refused> {
|
||||
/// Admit one export of about `size` bytes into `dir`. The slot and the bytes are held for as long as the
|
||||
/// response body, so exports admitted together cannot each count on the same free space.
|
||||
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<Admission, Refused> {
|
||||
let permit = self
|
||||
.permits
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| Refused::Busy)?;
|
||||
// No disk is that large, and the cap keeps the running total from overflowing.
|
||||
let size = size.min(MAX_RESERVATION);
|
||||
// Reserve first, then check: concurrent callers can only over-refuse, never over-admit.
|
||||
let earlier = self.reserved.fetch_add(size, Ordering::SeqCst);
|
||||
let admission = Admission {
|
||||
_permit: permit,
|
||||
reserved: self.reserved.clone(),
|
||||
size,
|
||||
};
|
||||
match free_bytes(dir) {
|
||||
// `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies.
|
||||
Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace),
|
||||
_ => Ok(permit),
|
||||
// Bytes already written by running exports are no longer free and are counted again in `earlier`; being
|
||||
// that cautious is deliberate.
|
||||
Some(free) if free < earlier.saturating_add(size).saturating_add(self.min_free) => {
|
||||
Err(Refused::NoSpace)
|
||||
}
|
||||
_ => Ok(admission),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,7 +286,7 @@ pub fn sweep_stale(data_dir: &std::path::Path) -> usize {
|
||||
/// the client went away, or the response was discarded) releases the permit and deletes the export.
|
||||
pub struct Guarded<S> {
|
||||
inner: Pin<Box<S>>,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
_permit: Admission,
|
||||
_dir: tempfile::TempDir,
|
||||
db: Db,
|
||||
principal: Principal,
|
||||
@@ -261,7 +299,7 @@ pub struct Guarded<S> {
|
||||
impl<S> Guarded<S> {
|
||||
pub fn new(
|
||||
inner: S,
|
||||
permit: OwnedSemaphorePermit,
|
||||
permit: Admission,
|
||||
dir: tempfile::TempDir,
|
||||
db: Db,
|
||||
principal: Principal,
|
||||
@@ -596,4 +634,45 @@ mod tests {
|
||||
"a snapshot bigger than the disk"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_exports_cannot_each_count_on_the_same_free_space() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let free = free_bytes(dir.path()).expect("statvfs works on the temp dir");
|
||||
// each export needs a bit over a third of what is free, so two fit on paper but not together
|
||||
// (the disk may move under us a little, which is why the margin is generous)
|
||||
let size = free / 3 + free / 20;
|
||||
let gate = ExportGate::new(8, 0);
|
||||
let first = gate.admit(dir.path(), size).ok().expect("one fits");
|
||||
let second = gate.admit(dir.path(), size).ok().expect("two fit");
|
||||
assert!(
|
||||
matches!(gate.admit(dir.path(), size), Err(Refused::NoSpace)),
|
||||
"the third would need more than the disk has once the first two are counted"
|
||||
);
|
||||
drop(first);
|
||||
assert!(
|
||||
gate.admit(dir.path(), size).is_ok(),
|
||||
"a finished export gives its bytes back"
|
||||
);
|
||||
drop(second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_export_leaves_nothing_reserved() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gate = ExportGate::new(2, 0);
|
||||
for _ in 0..3 {
|
||||
assert!(matches!(
|
||||
gate.admit(dir.path(), u64::MAX),
|
||||
Err(Refused::NoSpace)
|
||||
));
|
||||
}
|
||||
assert_eq!(gate.reserved.load(Ordering::SeqCst), 0);
|
||||
let busy = ExportGate::new(1, 0);
|
||||
let held = busy.admit(dir.path(), 5).ok().unwrap();
|
||||
assert!(matches!(busy.admit(dir.path(), 7), Err(Refused::Busy)));
|
||||
assert_eq!(busy.reserved.load(Ordering::SeqCst), 5);
|
||||
drop(held);
|
||||
assert_eq!(busy.reserved.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user