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
248 changes: 243 additions & 5 deletions crates/twigpine-cli/src/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,63 @@ struct EncryptedBlobEntry {
oid: String,
}

/// How many times one envelope fetch is retried after the node sheds it with a
/// 503 or 429, so a blob gets at most this many attempts plus the first.
const ENVELOPE_SHED_RETRIES: u32 = 3;

/// The longest a single `Retry-After` on a 503 shed is honored, so a node cannot
/// stall a clone for as long as it likes on one blob.
const ENVELOPE_RETRY_AFTER_CAP_SECS: u64 = 10;

/// The longest a 429 from the per-IP brake is honored. The brake counts over a
/// one-minute window and its `Retry-After` is the time until that window frees,
/// so a shorter cap would retry inside the same window and skip the blob.
const ENVELOPE_BRAKE_RETRY_AFTER_CAP_SECS: u64 = 60;

/// The wait used when a shed response has no `Retry-After`, or one that is not
/// an integer number of seconds.
const ENVELOPE_RETRY_AFTER_DEFAULT_SECS: u64 = 2;

/// Fetch one encrypted-blob envelope, retrying while the node sheds load.
///
/// The node answers 503 (concurrency cap) or 429 (per-client rate brake) on this
/// route when it is busy, both with `Retry-After` in seconds. That is transient,
/// so skipping the blob on the first one would drop a withheld file from a clone
/// that otherwise succeeds.
async fn fetch_envelope(client: &NodeClient, path: &str) -> Result<reqwest::Response> {
let mut retries_left = ENVELOPE_SHED_RETRIES;
loop {
let resp = client.get_signed(path).await?;
let shed = matches!(
resp.status(),
reqwest::StatusCode::SERVICE_UNAVAILABLE | reqwest::StatusCode::TOO_MANY_REQUESTS
);
if !shed || retries_left == 0 {
return Ok(resp);
}
retries_left -= 1;
let retry_after = resp
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok());
let wait = shed_retry_wait_secs(resp.status(), retry_after);
tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
}
}

/// How long to wait before retrying a shed envelope fetch.
fn shed_retry_wait_secs(status: reqwest::StatusCode, retry_after: Option<&str>) -> u64 {
let cap = if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
ENVELOPE_BRAKE_RETRY_AFTER_CAP_SECS
} else {
ENVELOPE_RETRY_AFTER_CAP_SECS
};
retry_after
.and_then(|v| v.trim().parse::<u64>().ok())
.unwrap_or(ENVELOPE_RETRY_AFTER_DEFAULT_SECS)
.min(cap)
}

/// After the base clone, recover encrypted blobs the caller is authorized for
/// that are missing locally: fetch the envelope, decrypt with the caller's key,
/// install as a loose object. Returns the repo-relative paths recovered.
Expand Down Expand Up @@ -396,11 +453,11 @@ async fn recover_encrypted_blobs(
if present {
continue;
}
let env_resp = match client
.get_signed(&format!(
"/api/v1/repos/{owner}/{name}/encrypted-blob/{oid}"
))
.await
let env_resp = match fetch_envelope(
&client,
&format!("/api/v1/repos/{owner}/{name}/encrypted-blob/{oid}"),
)
.await
{
Ok(r) if r.status().is_success() => r,
// The node path has the same silent exit the gateway path had: a 403, a
Expand Down Expand Up @@ -2284,4 +2341,185 @@ mod tests {
let out = child.wait_with_output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), oid);
}

/// A partial clone whose `secret/b.txt` blob is absent locally and cannot be
/// lazily fetched (the promisor remote is deleted), so only the node's
/// encrypted-blob route can restore it. Returns the tempdir, the clone, and
/// the withheld blob's oid.
fn clone_missing_secret_blob() -> (TempDir, std::path::PathBuf, String) {
let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]);
let dest = td.path().join("dest");
let bare = url.strip_prefix("file://").unwrap().to_string();
assert!(Command::new("git")
.args(["-C", &bare, "config", "uploadpack.allowFilter", "true"])
.status()
.unwrap()
.success());
setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap();
let out = Command::new("git")
.args([
"-C",
dest.to_str().unwrap(),
"rev-parse",
"HEAD:secret/b.txt",
])
.output()
.unwrap();
let oid = String::from_utf8_lossy(&out.stdout).trim().to_string();
std::fs::remove_dir_all(&bare).unwrap();
(td, dest, oid)
}

/// Mock the node's inventory listing the one withheld blob. The envelope
/// route is mocked by each test.
async fn mock_inventory(server: &mut mockito::ServerGuard, oid: &str) -> mockito::Mock {
server
.mock("GET", "/api/v1/repos/alice/myrepo/encrypted-blobs")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(serde_json::json!({ "blobs": [{ "oid": oid }] }).to_string())
.create_async()
.await
}

/// A shed (503 or 429 with `Retry-After`) on the envelope fetch is retried, and
/// the next 200 recovers the blob instead of the clone silently dropping it.
async fn envelope_shed_once_then_ok_recovers(shed_status: usize) {
use twigpine_core::encrypt::seal_blob;
use twigpine_core::identity::Keypair;

let (_td, dest, oid) = clone_missing_secret_blob();
let reader = Keypair::generate();
let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap();

let mut server = mockito::Server::new_async().await;
let _inv = mock_inventory(&mut server, &oid).await;
let path = format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}");
let shed = server
.mock("GET", path.as_str())
.with_status(shed_status)
.with_header("retry-after", "0")
.expect(1)
.create_async()
.await;
let ok = server
.mock("GET", path.as_str())
.with_status(200)
.with_body(envelope)
.expect(1)
.create_async()
.await;

let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader)
.await
.unwrap();
assert_eq!(
paths,
vec!["secret/b.txt".to_string()],
"a {shed_status} shed followed by a 200 must still recover the blob"
);
shed.assert_async().await;
ok.assert_async().await;
}

#[tokio::test]
async fn recover_encrypted_blobs_retries_a_503_shed() {
envelope_shed_once_then_ok_recovers(503).await;
}

#[tokio::test]
async fn recover_encrypted_blobs_retries_a_429_brake() {
envelope_shed_once_then_ok_recovers(429).await;
}

/// The retry is bounded: a node that keeps shedding gets four attempts in
/// total, then the blob is skipped with the last status, as before.
#[tokio::test]
async fn recover_encrypted_blobs_gives_up_after_bounded_retries() {
use twigpine_core::identity::Keypair;

let (_td, dest, oid) = clone_missing_secret_blob();
let reader = Keypair::generate();
let mut server = mockito::Server::new_async().await;
let _inv = mock_inventory(&mut server, &oid).await;
let shed = server
.mock(
"GET",
format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}").as_str(),
)
.with_status(503)
.with_header("retry-after", "0")
.expect(4)
.create_async()
.await;

reset_warnings();
let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader)
.await
.unwrap();
assert!(
paths.is_empty(),
"a node that never stops shedding recovers nothing"
);
shed.assert_async().await;
assert!(
warnings().contains("503"),
"the skip must report the last status, got: {:?}",
warnings()
);
}

/// Only a shed is retried: a 404 is final and is requested exactly once.
/// The per-IP brake's 429 asks for up to its whole window, so the client must
/// be able to wait that long once, or every retry lands inside the same
/// window and the blob is skipped. A 503 shed stays on the short cap.
#[test]
fn shed_retry_wait_honors_a_brake_window_but_caps_a_shed() {
use reqwest::StatusCode;
assert_eq!(
shed_retry_wait_secs(StatusCode::TOO_MANY_REQUESTS, Some("59")),
59
);
assert_eq!(
shed_retry_wait_secs(StatusCode::TOO_MANY_REQUESTS, Some("600")),
60
);
assert_eq!(
shed_retry_wait_secs(StatusCode::SERVICE_UNAVAILABLE, Some("59")),
10
);
assert_eq!(
shed_retry_wait_secs(StatusCode::SERVICE_UNAVAILABLE, None),
2
);
assert_eq!(
shed_retry_wait_secs(StatusCode::TOO_MANY_REQUESTS, Some("soon")),
2
);
}

#[tokio::test]
async fn recover_encrypted_blobs_does_not_retry_a_404() {
use twigpine_core::identity::Keypair;

let (_td, dest, oid) = clone_missing_secret_blob();
let reader = Keypair::generate();
let mut server = mockito::Server::new_async().await;
let _inv = mock_inventory(&mut server, &oid).await;
let missing = server
.mock(
"GET",
format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}").as_str(),
)
.with_status(404)
.expect(1)
.create_async()
.await;

let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader)
.await
.unwrap();
assert!(paths.is_empty(), "a 404 envelope is not recoverable");
missing.assert_async().await;
}
}
2 changes: 1 addition & 1 deletion crates/twigpine-core/src/encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ const VERSION: u8 = 2;
/// answer "not a recipient", so the count has to be capped rather than
/// optimized (#419). Legitimate envelopes carry a handful of authorized
/// readers, so 256 is far above real use.
const MAX_RECIPIENTS: usize = 256;
pub const MAX_RECIPIENTS: usize = 256;

#[derive(Serialize, Deserialize)]
struct Recipient {
Expand Down
Loading
Loading