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
6 changes: 6 additions & 0 deletions .cargo/mutants.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# cargo-mutants settings, used by scripts/mutants.sh.
# Build and test with the lock file, as CI does.
additional_cargo_args = ["--locked"]

exclude_re = [
# After the reset statement, a game that it changed is pending with zero attempts,
# so the state check in the fallback also returns Ok. The row count only skips a read.
"replace > with < in OracleDatabase::reset_completion_attempts$",
]
13 changes: 13 additions & 0 deletions crates/common/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ mod tests {
assert_eq!(parse_integer(Some("\u{feff}42 "), 5, None, None, "K"), 42);
}

#[test]
fn infinity_is_an_invalid_number_not_a_fraction() {
if std::env::var_os("TIMBA_CHILD").is_some() {
assert_eq!(parse_integer(Some("Infinity"), 5, None, None, "K"), 5);
return;
}
let output = crate::log::tests::run_child("env::tests::infinity_is_an_invalid_number_not_a_fraction");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{output:?}");
assert!(stderr.contains("Ignoring invalid numeric value 'Infinity' for K; using 5."), "{stderr}");
assert!(!stderr.contains("must be an integer"), "{stderr}");
}

#[test]
fn trims_like_javascript() {
// Bun: "\ufeff\u0085\u00a0\u3000x\u2028\n".trim() === "x", while U+200B stays.
Expand Down
17 changes: 16 additions & 1 deletion crates/common/src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ pub fn read_protected_secret(file_path: &str, label: &str) -> Result<String, Str
let resolved = resolve_path(file_path);
let meta = std::fs::symlink_metadata(&resolved)
.map_err(|e| format!("ENOENT: {label} could not be read ({}): {e}", resolved.display()))?;
if !meta.file_type().is_file() || meta.file_type().is_symlink() {
// `symlink_metadata` does not follow links, so a symlink is not a file here.
if !meta.file_type().is_file() {
return Err(format!("{label} must be a regular file, not a symlink"));
}
if meta.len() == 0 || meta.len() > 4096 {
Expand Down Expand Up @@ -64,6 +65,20 @@ mod tests {
std::fs::write(&file, "x".repeat(size)).unwrap();
assert_eq!(read_protected_secret(path, "T").unwrap_err(), "T has an invalid size");
}
std::fs::write(&file, "x".repeat(4096)).unwrap();
assert_eq!(read_protected_secret(path, "T").unwrap(), "x".repeat(4096));
}

#[test]
fn rejects_a_directory() {
let dir = tempfile::tempdir().unwrap();
let secret = dir.path().join("token");
std::fs::create_dir(&secret).unwrap();
std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o700)).unwrap();
assert_eq!(
read_protected_secret(secret.to_str().unwrap(), "T").unwrap_err(),
"T must be a regular file, not a symlink"
);
}

#[test]
Expand Down
40 changes: 31 additions & 9 deletions crates/common/src/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,20 @@ impl RouteRateLimiter {
};
let now = (self.now)();
let mut windows = self.windows.lock().unwrap();
match windows.get_mut(path) {
Some((started, count)) if now - *started < WINDOW_MS => {
if let Some((started, count)) = windows.get_mut(path) {
let elapsed = now - *started;
if elapsed < WINDOW_MS {
*count += 1;
if *count <= limit {
return RateLimitResult { allowed: true, retry_after_seconds: None };
}
let remaining = WINDOW_MS - (now - *started);
let retry = ((remaining as f64) / 1000.0).ceil().max(1.0) as u64;
RateLimitResult { allowed: false, retry_after_seconds: Some(retry) }
}
_ => {
windows.insert(path, (now, 1));
RateLimitResult { allowed: true, retry_after_seconds: None }
// `elapsed < WINDOW_MS`, so at least 1 ms of the window is left.
let retry = (WINDOW_MS - elapsed).unsigned_abs().div_ceil(1000);
return RateLimitResult { allowed: false, retry_after_seconds: Some(retry) };
}
}
windows.insert(path, (now, 1));
RateLimitResult { allowed: true, retry_after_seconds: None }
}
}

Expand Down Expand Up @@ -130,6 +129,29 @@ mod tests {
assert!(!has_valid_bearer_token(Some("abc"), "abc"));
assert!(!has_valid_bearer_token(None, "abc"));
assert!(!has_valid_bearer_token(Some("Bearer "), ""));
// Two bytes that differ the same way cancel out under `^` but not under `|`.
assert!(!has_valid_bearer_token(Some("Bearer ab"), "ba"));
}

#[test]
fn request_bodies_stop_at_16_kib_like_api_security_ts() {
assert_eq!(MAX_REQUEST_BODY_BYTES, 16_384);
}

#[test]
fn a_window_counts_from_its_first_request() {
let clock = Arc::new(AtomicI64::new(600));
let c = clock.clone();
let limiter = RouteRateLimiter::new(Box::new(move || c.load(Ordering::SeqCst)));
for _ in 0..10 {
assert!(limiter.check("/stats").allowed);
}
clock.store(1_000, Ordering::SeqCst);
assert_eq!(limiter.check("/stats"), RateLimitResult { allowed: false, retry_after_seconds: Some(1) });
clock.store(1_599, Ordering::SeqCst);
assert!(!limiter.check("/stats").allowed);
clock.store(1_600, Ordering::SeqCst);
assert!(limiter.check("/stats").allowed);
}

#[test]
Expand Down
4 changes: 3 additions & 1 deletion crates/common/src/shutdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ impl Shutdown {

/// Sleeps for `ms` or until shutdown, whichever comes first.
pub async fn sleep(&self, ms: u64) {
if ms == 0 || self.is_triggered() {
// A triggered shutdown also returns at once: `wait` sees the current value first.
if ms == 0 {
return;
}
tokio::select! {
Expand Down Expand Up @@ -67,6 +68,7 @@ mod tests {
});
shutdown.sleep(60_000).await;
assert_eq!(started.elapsed(), Duration::from_millis(60));
assert!(shutdown.is_triggered());
shutdown.wait().await;
shutdown.sleep(60_000).await;
assert_eq!(started.elapsed(), Duration::from_millis(60));
Expand Down
30 changes: 27 additions & 3 deletions crates/evm-oracle/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,8 @@ pub async fn run_cycles<F, Fut>(
last_warning = now_ms();
warn(CYCLE_FAILED_MESSAGE);
}
if !shutdown.is_triggered() {
shutdown.sleep(poll_ms).await;
}
// `sleep` returns at once after a trigger.
shutdown.sleep(poll_ms).await;
}
}

Expand Down Expand Up @@ -96,6 +95,31 @@ mod tests {
}
}

#[tokio::test]
async fn a_failure_exactly_one_minute_after_a_warning_is_not_warned_again() {
let shutdown = Shutdown::new();
let ticks = Cell::new(0);
let warnings = RefCell::new(0);
let clock = Cell::new(1_000_000);
run_cycles(
|| {
ticks.set(ticks.get() + 1);
if ticks.get() == 2 {
clock.set(1_000_000 + WARNING_INTERVAL_MS);
shutdown.trigger();
}
async { anyhow::bail!("rpc unavailable") }
},
1,
&shutdown,
|| clock.get(),
|_| *warnings.borrow_mut() += 1,
)
.await;
assert_eq!(ticks.get(), 2);
assert_eq!(*warnings.borrow(), 1);
}

#[tokio::test]
async fn warns_once_per_minute_about_failed_cycles_and_stops_on_shutdown() {
let shutdown = Shutdown::new();
Expand Down
7 changes: 7 additions & 0 deletions crates/evm-oracle/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,13 @@ mod tests {
assert!(error.contains("Duplicate token policy"), "{error}");
}

#[test]
fn accepts_the_largest_safe_start_block() {
let mut value = example();
value["startBlock"] = Value::from("9007199254740991");
assert_eq!(parse_config(&value).unwrap().start_block, 9_007_199_254_740_991);
}

#[test]
fn rejects_unknown_keys_and_invalid_values() {
let mut value = example();
Expand Down
11 changes: 7 additions & 4 deletions crates/evm-oracle/src/erc8010.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,16 @@ pub fn is_wrapped(signature: &[u8]) -> bool {

/// ox `SignatureErc8010.unwrap`, or `None` when the wrapper is malformed.
pub fn unwrap(wrapped: &[u8]) -> Option<Wrapped> {
if !is_wrapped(wrapped) || wrapped.len() < 64 {
if !is_wrapped(wrapped) {
return None;
}
let length_word = U256::from_be_slice(&wrapped[wrapped.len() - 64..wrapped.len() - 32]);
// The magic is the last 32 bytes, and the suffix length the 32 bytes before it.
let length_end = wrapped.len() - 32;
let length_start = length_end.checked_sub(32)?;
let length_word = U256::from_be_slice(&wrapped[length_start..length_end]);
let suffix_length = usize::try_from(length_word).ok()?;
let signature_end = (wrapped.len() - 64).checked_sub(suffix_length)?;
let suffix = &wrapped[signature_end..wrapped.len() - 64];
let signature_end = length_start.checked_sub(suffix_length)?;
let suffix = &wrapped[signature_end..length_start];
let (auth, to, data) = Suffix::abi_decode_params(suffix).ok()?;
Some(Wrapped {
authorization: SignedAuthorization {
Expand Down
14 changes: 13 additions & 1 deletion crates/evm-oracle/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,17 @@ mod tests {
RpcError::Node { code, message: message.into(), data }
}

#[test]
fn a_null_base_fee_means_a_chain_without_one() {
let block = parse_block(&json!({
"hash": format!("0x{}", "ab".repeat(32)),
"timestamp": "0x1",
"baseFeePerGas": null,
}))
.unwrap();
assert_eq!(block.base_fee_per_gas, None);
}

#[test]
fn classifies_reverts_like_viem() {
assert!(node(3, "execution reverted", Some(json!("0x1234"))).is_contract_revert());
Expand Down Expand Up @@ -736,7 +747,8 @@ mod tests {
assert_eq!((wrapped.signature, wrapped.init), (inner.clone(), Some(init)));
assert_eq!(wrapped.authorization.authority(), Some(account().address()));
let plain = unwrap(&hex(&fixture["plain"])).unwrap();
assert_eq!((plain.signature, plain.init), (inner, None));
assert_eq!((plain.signature, plain.init), (inner.clone(), None));
assert!(unwrap(&inner).is_none(), "a signature without the magic suffix is not wrapped");
}

#[tokio::test]
Expand Down
7 changes: 6 additions & 1 deletion crates/evm-oracle/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,12 @@ async fn refuses_to_start_when_the_operator_does_not_own_the_proxy() {
chain.state().owner = creator();
let url = rpc_endpoint(chain).await;
let deployment = deployment(vec![url], &operator_key());
let error = app::run(Some(deployment.config_file.clone()), Shutdown::new()).await.unwrap_err();
// If the check passes by mistake, the oracle runs until shutdown, so the test must not wait for it.
let error =
tokio::time::timeout(Duration::from_secs(10), app::run(Some(deployment.config_file.clone()), Shutdown::new()))
.await
.expect("the oracle refuses to start")
.unwrap_err();
assert_eq!(error.to_string(), "EVM operator does not own configured proxy");
}

Expand Down
19 changes: 19 additions & 0 deletions crates/evm-oracle/tests/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ async fn all_routes_require_bearer_auth_and_body_limits_cannot_be_bypassed() {
.unwrap();
assert_eq!(send(&router, streamed).await.status(), StatusCode::PAYLOAD_TOO_LARGE);

// A streamed body of exactly 16 KiB is read, then rejected as invalid JSON.
let chunks =
futures::stream::iter((0..16).map(|_| Ok::<_, std::io::Error>(axum::body::Bytes::from(vec![b'x'; 1_024]))));
let exact = Request::post("/evm/private-join")
.header("authorization", "Bearer test-token")
.body(Body::from_stream(chunks))
.unwrap();
assert_eq!(send(&router, exact).await.status(), StatusCode::BAD_REQUEST);

let invalid = Request::post("/evm/authorize")
.header("authorization", "Bearer test-token")
.body(Body::from("not json"))
Expand Down Expand Up @@ -169,6 +178,12 @@ async fn health_allows_three_long_poll_intervals() {
assert_eq!(body(response).await["status"], "healthy");
fake.service.last_cycle_at.store(fake.service.now_ms() - 60_001, std::sync::atomic::Ordering::SeqCst);
assert_eq!(send(&app, get("/evm/health")).await.status(), StatusCode::SERVICE_UNAVAILABLE);
// Exactly three intervals old is already stale.
fake.set_now_ms(1_700_000_000_000);
fake.service.last_cycle_at.store(1_700_000_000_000 - 60_000, std::sync::atomic::Ordering::SeqCst);
assert_eq!(send(&app, get("/evm/health")).await.status(), StatusCode::SERVICE_UNAVAILABLE);
fake.service.last_cycle_at.store(1_700_000_000_000 - 59_999, std::sync::atomic::Ordering::SeqCst);
assert_eq!(send(&app, get("/evm/health")).await.status(), StatusCode::OK);
}

#[tokio::test]
Expand Down Expand Up @@ -239,6 +254,10 @@ async fn pages_public_games_with_their_on_chain_state() {
let second_ids: Vec<&Value> = second["games"].as_array().unwrap().iter().map(|game| &game["id"]).collect();
assert_eq!(second_ids, [&json!(ids[0].to_string())]);
assert_eq!(second["nextOffset"], Value::Null);
// Exactly one full page left has no next page.
let last_page = body(send(&router, get("/evm/games?offset=1")).await).await;
assert_eq!(last_page["games"].as_array().unwrap().len(), 20);
assert_eq!(last_page["nextOffset"], Value::Null);
}

#[tokio::test]
Expand Down
56 changes: 56 additions & 0 deletions crates/evm-oracle/tests/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,28 @@ mod authorize {
}
}

#[tokio::test]
async fn accepts_terms_exactly_on_the_window_limits_and_overflow_bound() {
let fake = setup();
let now = fake.chain.state().now;
fake.chain.state().limits = [5, 600, 300, 3600, 10];
for overrides in [
json!({ "deadline": (now + 300).to_string() }),
json!({ "maxPlayers": 10 }),
json!({ "amount": (U256::MAX / U256::from(2)).to_string() }),
] {
let input = creation_intent(&fake, overrides.clone());
let result = fake.service.authorize(&input).await;
assert!(result.is_ok(), "{overrides}: {:?}", result.err());
}
let input =
creation_intent(&fake, json!({ "amount": (U256::MAX / U256::from(2) + U256::from(1)).to_string() }));
assert_eq!(error_of(fake.service.authorize(&input)).await, "Invalid game terms");
fake.chain.state().limits = [5, 600, 300, 3599, 10];
let input = creation_intent(&fake, json!({}));
assert_eq!(error_of(fake.service.authorize(&input)).await, "Game exceeds current oracle limits");
}

#[tokio::test]
async fn rejects_timeouts_and_player_counts_beyond_the_oracle_limits() {
let fake = setup();
Expand Down Expand Up @@ -300,6 +322,15 @@ mod private_join {
assert_eq!(result.to_json(), json!({ "deadline": result.deadline, "signature": result.signature.to_string() }));
}

#[tokio::test]
async fn accepts_an_invitation_that_ends_exactly_with_the_window() {
let fake = setup();
fake.chain.state().games.insert(game_id(), private_game(1, true));
let now = fake.chain.state().now;
let input = invitation(&fake, Some(now + 300));
assert!(fake.service.private_join(&input).await.is_ok());
}

#[tokio::test]
async fn rejects_invitations_outside_the_five_minute_window() {
let fake = setup();
Expand Down Expand Up @@ -382,6 +413,7 @@ mod tick_settlement {
assert_eq!((simulated[0].gameId, simulated[0].secret), (GAME_A, SECRET_A));
let simulation = &fake.chain.contract_calls(completeGameCall::SELECTOR)[0][0];
assert_eq!(simulation["from"], operator().to_checksum(None));
assert_eq!(simulation["to"], PROXY.to_checksum(None));
let estimate = &fake.chain.calls("eth_estimateGas")[0][0];
let data = complete_game_transaction(&fake.service.deployment, GAME_A, SECRET_A).unwrap().data;
assert_eq!(estimate["from"], operator().to_checksum(None));
Expand Down Expand Up @@ -824,6 +856,28 @@ mod index {
assert_eq!(fake.service.store().cursor().unwrap(), None);
}

#[tokio::test]
async fn indexes_block_1_once_the_head_reaches_the_confirmation_depth() {
let fake = setup();
fake.chain.state().head = 2;

fake.service.index().await.unwrap();

assert_eq!(log_ranges(&fake), [("0x0".to_string(), "0x1".to_string())]);
}

#[tokio::test]
async fn scans_a_single_new_confirmed_block() {
let fake = setup();
fake.chain.state().head = 10;
fake.service.index().await.unwrap();
fake.chain.state().head = 11;

fake.service.index().await.unwrap();

assert_eq!(log_ranges(&fake)[1], ("0xa".to_string(), "0xa".to_string()));
}

#[tokio::test]
async fn stores_decoded_deployment_events_and_advances_the_cursor() {
let fake = setup();
Expand Down Expand Up @@ -898,6 +952,8 @@ mod index {
fake.service.index().await.unwrap();

assert_eq!(fake.chain.calls("eth_getLogs").len(), 1);
// A cursor exactly at the confirmed head is not a reorganization.
assert_eq!(fake.service.store().cursor().unwrap().map(|cursor| cursor.block), Some(9));
}

#[tokio::test]
Expand Down
Loading