[control] Share and token fixes: settle the epoch before minting, mint in its own task so a dropped client frees its key, token checks off the async threads, CLI refuses to run as another user than the state dir's owner

This commit is contained in:
2026-11-07 19:20:05 +01:00
parent 43918943da
commit 7d3af00720
6 changed files with 102 additions and 13 deletions
+26 -8
View File
@@ -997,14 +997,32 @@ pub async fn mint_share_link(
{
return Ok(replay(&st, s));
}
let out = mint_inner(&st, &actor, &hostname, body.value).await;
if let Some(k) = &key {
st.idem_finish(
k,
&fp,
out.as_ref().ok().map(|v| Stored::Json(201, v.clone())),
);
}
// In its own task: a client that goes away mid-request neither cancels the mint nor
// leaves its Idempotency-Key reserved.
let task = tokio::spawn({
let (st, actor, key, fp) = (st.clone(), actor.clone(), key.clone(), fp.clone());
let value = body.value;
async move {
let out = mint_inner(&st, &actor, &hostname, value).await;
if let Some(k) = &key {
st.idem_finish(
k,
&fp,
out.as_ref().ok().map(|v| Stored::Json(201, v.clone())),
);
}
out
}
});
let out = match task.await {
Ok(out) => out,
Err(e) => {
if let Some(k) = &key {
st.idem_finish(k, &fp, None);
}
Err(ApiError::internal(e.to_string()))
}
};
out.map(|v| json(StatusCode::CREATED, &v))
}
+8 -2
View File
@@ -370,8 +370,14 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
let auth = req
.headers()
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok());
let tok = st.ctl.tokens.check(auth).map_err(|r| {
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
// The token store takes a file lock: off the async threads.
let ctl = st.ctl.clone();
let checked = tokio::task::spawn_blocking(move || ctl.tokens.check(auth.as_deref()))
.await
.unwrap_or(Err(Refusal::Unknown));
let tok = checked.map_err(|r| {
let (code, params) = match r {
Refusal::Missing => ("token.missing", Params::new()),
Refusal::Unknown => ("token.unknown", Params::new()),
+29
View File
@@ -80,9 +80,38 @@ fn state_dir(args: &[String]) -> Result<PathBuf, String> {
Err("give --config <control.toml> or --state-dir <dir>".into())
}
/// The token files must stay owned by the user control runs as: refuse to touch them as
/// anyone else (typically root), instead of leaving root-owned files control cannot open.
#[cfg(unix)]
fn same_owner(dir: &std::path::Path) -> Result<(), String> {
use std::os::unix::fs::MetadataExt;
let owner = std::fs::metadata(dir)
.map_err(|e| format!("cannot read {}: {e}", dir.display()))?
.uid();
let probe = dir.join(format!(".owner-probe-{}", std::process::id()));
let me = std::fs::File::create(&probe)
.and_then(|f| f.metadata())
.map(|m| m.uid());
let _ = std::fs::remove_file(&probe);
let me = me.map_err(|e| format!("cannot write in {}: {e}", dir.display()))?;
if me != owner {
return Err(format!(
"{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)",
dir.display()
));
}
Ok(())
}
#[cfg(not(unix))]
fn same_owner(_: &std::path::Path) -> Result<(), String> {
Ok(())
}
fn token(args: &[String]) -> Result<(), String> {
let dir = state_dir(args)?;
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
same_owner(&dir)?;
let tokens = Tokens::new(&dir);
match args.first().map(String::as_str) {
Some("create") => {
+3
View File
@@ -248,6 +248,9 @@ impl Shares {
};
old.stopped_at.get_or_insert(now());
}
// Settle the epoch first (lost records, an overflowing deny list): a link minted
// below the epoch that is about to be published would be dead on arrival.
let _ = self.reconcile(&mut f);
let id = ShareId(random::<16>().map_err(|e| MintError::Store(e.to_string()))?);
let t = now();
let spec = LinkSpec {
+11 -3
View File
@@ -641,12 +641,16 @@ mod unix {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
assert_eq!(env.add_host(host("a.test", &good.url(), false)).await["state"], "kept");
assert_eq!(
env.add_host(host("a.test", &good.url(), false)).await["state"],
"kept"
);
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]);
let r = env.add_host(host("b.test", &good.url(), false)).await;
assert_eq!(r["state"], "kept", "{r}");
let j: serde_json::Value = serde_json::from_str(&env.file("state/journal.json")).expect("journal kept");
let j: serde_json::Value =
serde_json::from_str(&env.file("state/journal.json")).expect("journal kept");
assert_eq!(j["stage"], "confirmed", "{j}");
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
@@ -661,7 +665,11 @@ mod unix {
env.start_control(None);
let o = env.call("GET", "/api/v1/overview", None).await;
assert!(o.json["paused"].is_null(), "{}", o.text);
assert!(env.head_files().iter().any(|(p, _)| p == "hosts/b.test.toml"));
assert!(
env.head_files()
.iter()
.any(|(p, _)| p == "hosts/b.test.toml")
);
env.assert_consistent().await;
}
+25
View File
@@ -171,3 +171,28 @@ fn a_deny_list_that_would_overflow_raises_the_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"
);
}