Files
ianitor/crates/control/tests/stores.rs
T

199 lines
6.7 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
//! Token and share-link stores (QC fix round 1, M2 and M4): a CLI revoke is never lost to the
//! server recording token use at the same time, and losing `share-links.json` never revives a
//! stopped link.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_control::shares::Shares;
use ianitor_control::tokens::{Refusal, Tokens};
use ianitor_core::share::ShareKey;
use ianitor_testkit::proc::TempDir;
use serde_json::Value;
fn revocations(p: &std::path::Path) -> Value {
serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap()
}
#[test]
fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
let bin = env!("CARGO_BIN_EXE_ianitor-control");
let rounds = 20;
let mut lost = 0;
for _ in 0..rounds {
let d = TempDir::new("tok-race");
let server = Tokens::new(d.path());
let values: Vec<_> = (0..150)
.map(|i| server.create(&format!("t{i}"), None).unwrap())
.collect();
let victim = values[75].0.id.clone();
let mut cli = std::process::Command::new(bin)
.args(["token", "revoke", &victim, "--state-dir"])
.arg(d.path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
for (_, v) in &values {
let _ = server.check(Some(&format!("Bearer {v}")));
}
assert!(cli.wait().unwrap().success());
if !matches!(
server.check(Some(&format!("Bearer {}", values[75].1))),
Err(Refusal::Revoked(_))
) {
lost += 1;
}
}
assert_eq!(
lost, 0,
"the CLI said revoked but the token still worked in {lost}/{rounds} rounds"
);
}
#[test]
fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
let bin = env!("CARGO_BIN_EXE_ianitor-control");
let d = TempDir::new("tok-create");
let server = Tokens::new(d.path());
let mut clis: Vec<_> = (0..8)
.map(|i| {
std::process::Command::new(bin)
.args([
"token",
"create",
"--name",
&format!("cli{i}"),
"--state-dir",
])
.arg(d.path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap()
})
.collect();
for i in 0..40 {
server.create(&format!("srv{i}"), None).unwrap();
}
for c in &mut clis {
assert!(c.wait().unwrap().success());
}
assert_eq!(server.list().unwrap().len(), 48);
}
#[test]
fn losing_share_links_json_never_lowers_the_revocation_epoch() {
let d = TempDir::new("epoch");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let m = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&m.record.id).unwrap();
s.stop_all().unwrap();
s.stop_all().unwrap();
assert_eq!(revocations(&rev)["epoch"], 2);
std::fs::remove_file(d.join("share-links.json")).unwrap();
Shares::new(d.path(), &rev)
.ensure_revocation_file()
.unwrap();
assert!(
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
"{}",
revocations(&rev)
);
// Minting after the loss continues from there.
let m2 = Shares::new(d.path(), &rev)
.mint(&key, "a.test", "/", 3600, None, None, "t")
.unwrap();
assert!(m2.record.epoch >= 2);
}
#[test]
fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() {
let d = TempDir::new("deny");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
let _b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&a.record.id).unwrap();
let before = revocations(&rev);
assert_eq!(before["deny"][0], a.record.id);
assert_eq!(before["epoch"], 0);
// The records are gone (or an older backup without the stop is restored).
std::fs::remove_file(d.join("share-links.json")).unwrap();
Shares::new(d.path(), &rev)
.ensure_revocation_file()
.unwrap();
let after = revocations(&rev);
let still_denied = after["deny"]
.as_array()
.unwrap()
.iter()
.any(|x| x == &before["deny"][0]);
assert!(
still_denied || after["epoch"].as_u64().unwrap() > 0,
"stopped link {} works again: {after}",
a.record.id
);
}
#[test]
fn a_deny_list_that_would_overflow_raises_the_epoch() {
let d = TempDir::new("overflow");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let t = ianitor_control::util::now();
let links: Vec<Value> = (0..10_050u32)
.map(|i| {
serde_json::json!({
"id": format!("{:032x}", i + 1), "hostname": "a.test", "path_prefix": "/", "epoch": 0,
"created_at": t, "expires_at": t + 3600, "has_password": false, "created_by": "t",
"stopped_at": t
})
})
.collect();
std::fs::write(
d.join("share-links.json"),
serde_json::json!({ "epoch": 0, "links": links }).to_string(),
)
.unwrap();
s.ensure_revocation_file().unwrap();
let r = revocations(&rev);
assert!(
r["epoch"].as_u64().unwrap() >= 1,
"an overflowing deny list must raise the epoch: {}",
r["epoch"]
);
assert!(r["deny"].as_array().unwrap().len() < 10_000);
}
#[test]
fn a_link_minted_after_the_records_were_lost_works() {
let d = TempDir::new("doa");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&a.record.id).unwrap();
std::fs::remove_file(d.join("share-links.json")).unwrap();
let b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
let published = revocations(&rev);
assert!(
u64::from(b.record.epoch) >= published["epoch"].as_u64().unwrap(),
"dead on arrival: link epoch {} < published {}",
b.record.epoch,
published["epoch"]
);
let list = s.load().unwrap();
let rec = list.links.iter().find(|l| l.id == b.record.id).unwrap();
assert_eq!(
rec.state(list.epoch, ianitor_control::util::now()),
"active"
);
}