[control] API fixes: atomic Idempotency-Key reservation, no echo of odd field names or path parameters, askpass answers only password prompts, file protocol not forced, token test split on the known prefix, serialisation test without second-resolution times

This commit is contained in:
2026-11-07 18:57:54 +01:00
parent 54574702ea
commit f382fe2f76
7 changed files with 158 additions and 51 deletions
+40 -15
View File
@@ -38,11 +38,10 @@ fn check_hostname_param(h: &str) -> Result<(), ApiError> {
.bytes() .bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.' || c == b'-') .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.' || c == b'-')
{ {
return Err(ApiError::new( // Not a hostname: say so without repeating what was sent.
StatusCode::NOT_FOUND, let mut e = ApiError::new(StatusCode::NOT_FOUND, "host.not_found", Params::new());
"host.not_found", e.body.message = "There is no such host.".into();
messages::params([("hostname", h.chars().take(253).collect())]), return Err(e);
));
} }
Ok(()) Ok(())
} }
@@ -79,13 +78,21 @@ fn submit(
) -> Result<Response, ApiError> { ) -> Result<Response, ApiError> {
let key = idem_key(headers)?.map(|k| format!("{}:{k}", actor.token_id)); let key = idem_key(headers)?.map(|k| format!("{}:{k}", actor.token_id));
if let Some(k) = &key if let Some(k) = &key
&& let Some(stored) = st.idem_get(k, &fp)? && let Some(stored) = st.idem_begin(k, &fp)?
{ {
return Ok(replay(st, stored)); return Ok(replay(st, stored));
} }
let rec = st.ctl.submit(change, base_rev, &actor.name)?; let rec = match st.ctl.submit(change, base_rev, &actor.name) {
Ok(r) => r,
Err(f) => {
if let Some(k) = &key { if let Some(k) = &key {
st.idem_put(k, &fp, Stored::Apply(rec.id.clone())); st.idem_finish(k, &fp, None);
}
return Err(f.into());
}
};
if let Some(k) = &key {
st.idem_finish(k, &fp, Some(Stored::Apply(rec.id.clone())));
} }
Ok(json( Ok(json(
StatusCode::ACCEPTED, StatusCode::ACCEPTED,
@@ -107,6 +114,11 @@ fn replay(st: &AppState, s: Stored) -> Response {
None => ApiError::internal("the remembered apply is gone").into_response(), None => ApiError::internal("the remembered apply is gone").into_response(),
}, },
Stored::Json(status, v) => json(StatusCode::from_u16(status).unwrap_or(StatusCode::OK), &v), Stored::Json(status, v) => json(StatusCode::from_u16(status).unwrap_or(StatusCode::OK), &v),
Stored::Pending => {
ApiError::new(StatusCode::CONFLICT, "request.in_progress", Params::new())
.retry(1)
.into_response()
}
} }
} }
@@ -981,10 +993,28 @@ pub async fn mint_share_link(
); );
let key = idem_key(&headers)?.map(|k| format!("{}:{k}", actor.token_id)); let key = idem_key(&headers)?.map(|k| format!("{}:{k}", actor.token_id));
if let Some(k) = &key if let Some(k) = &key
&& let Some(s) = st.idem_get(k, &fp)? && let Some(s) = st.idem_begin(k, &fp)?
{ {
return Ok(replay(&st, s)); 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())),
);
}
out.map(|v| json(StatusCode::CREATED, &v))
}
async fn mint_inner(
st: &AppState,
actor: &Actor,
hostname: &str,
b: MintBody,
) -> Result<serde_json::Value, ApiError> {
let hostname = hostname.to_owned();
st.limit(&format!("share-mint:{}", actor.token_id), 30, 60) st.limit(&format!("share-mint:{}", actor.token_id), 30, 60)
.map_err(|s| { .map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
@@ -1016,7 +1046,6 @@ pub async fn mint_share_link(
Params::new(), Params::new(),
)); ));
}; };
let b = body.value;
let field_err = |code: &str, field: &str| { let field_err = |code: &str, field: &str| {
let mut e = ApiError::new( let mut e = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY, StatusCode::UNPROCESSABLE_ENTITY,
@@ -1078,11 +1107,7 @@ pub async fn mint_share_link(
), ),
}), }),
}; };
let v = serde_json::to_value(&out).map_err(|e| ApiError::internal(e.to_string()))?; serde_json::to_value(&out).map_err(|e| ApiError::internal(e.to_string()))
if let Some(k) = &key {
st.idem_put(k, &fp, Stored::Json(201, v.clone()));
}
Ok(json(StatusCode::CREATED, &v))
} }
/// Every share link, newest first (without tokens). /// Every share link, newest first (without tokens).
+67 -19
View File
@@ -51,10 +51,15 @@ pub struct Actor {
} }
pub enum Stored { pub enum Stored {
/// The first request with this key is still being handled.
Pending,
Apply(String), Apply(String),
Json(u16, serde_json::Value), Json(u16, serde_json::Value),
} }
/// Most Idempotency-Keys held at once (each for 24 h).
const MAX_IDEM_KEYS: usize = 2000;
pub struct AppState { pub struct AppState {
pub ctl: Arc<Control>, pub ctl: Arc<Control>,
idem: Mutex<HashMap<String, (String, Stored, u64)>>, idem: Mutex<HashMap<String, (String, Stored, u64)>>,
@@ -91,32 +96,65 @@ impl AppState {
Ok(()) Ok(())
} }
/// Look up an Idempotency-Key. `Ok(Some)` replays, `Err` when the key was used for /// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier
/// another request. /// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when
pub fn idem_get(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> { /// the key was used for another request, is still in progress, or no key can be held.
let Ok(m) = self.idem.lock() else { pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
return Ok(None); let mut m = self
}; .idem
.lock()
.map_err(|_| ApiError::internal("idempotency store"))?;
let t = now();
match m.get(key) { match m.get(key) {
Some((fp, _, _)) if fp != fingerprint => Err(ApiError::new( Some((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => {
return Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY, StatusCode::UNPROCESSABLE_ENTITY,
"request.idempotency", "request.idempotency",
Params::new(), Params::new(),
)), ));
Some((_, Stored::Apply(id), _)) => Ok(Some(Stored::Apply(id.clone()))),
Some((_, Stored::Json(s, v), _)) => Ok(Some(Stored::Json(*s, v.clone()))),
None => Ok(None),
} }
Some((_, Stored::Pending, at)) if t.saturating_sub(*at) < 86_400 => {
return Err(ApiError::new(
StatusCode::CONFLICT,
"request.in_progress",
Params::new(),
)
.retry(1));
}
Some((_, Stored::Apply(id), at)) if t.saturating_sub(*at) < 86_400 => {
return Ok(Some(Stored::Apply(id.clone())));
}
Some((_, Stored::Json(s, v), at)) if t.saturating_sub(*at) < 86_400 => {
return Ok(Some(Stored::Json(*s, v.clone())));
}
_ => {}
}
if m.len() >= MAX_IDEM_KEYS {
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
}
if m.len() >= MAX_IDEM_KEYS {
return Err(ApiError::new(
StatusCode::TOO_MANY_REQUESTS,
"rate.limited",
Params::new(),
)
.retry(60));
}
m.insert(key.to_owned(), (fingerprint.to_owned(), Stored::Pending, t));
Ok(None)
} }
pub fn idem_put(&self, key: &str, fingerprint: &str, s: Stored) { /// Finish a reserved key: remember the answer, or (on `None`, a refusal) free the key.
pub fn idem_finish(&self, key: &str, fingerprint: &str, s: Option<Stored>) {
if let Ok(mut m) = self.idem.lock() { if let Ok(mut m) = self.idem.lock() {
let t = now(); match s {
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400); Some(s) => {
if m.len() >= 2000 { m.insert(key.to_owned(), (fingerprint.to_owned(), s, now()));
return; }
None => {
m.remove(key);
}
} }
m.insert(key.to_owned(), (fingerprint.to_owned(), s, t));
} }
} }
} }
@@ -234,12 +272,22 @@ fn body_error(e: &serde_json::Error) -> ApiError {
Some(rest.split('`').next()?.to_owned()) Some(rest.split('`').next()?.to_owned())
}; };
if let Some(f) = quoted("unknown field `") { if let Some(f) = quoted("unknown field `") {
// The name is the sender's: repeat it only if it is a plain field name.
let plain = !f.is_empty()
&& f.len() <= 64
&& f.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_');
let shown = if plain {
f
} else {
"(a field name)".to_owned()
};
let mut err = ApiError::new( let mut err = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY, StatusCode::UNPROCESSABLE_ENTITY,
"request.body_unknown_field", "request.body_unknown_field",
messages::params([("field", f.clone())]), messages::params([("field", shown.clone())]),
); );
err.body.field = Some(f); err.body.field = plain.then_some(shown);
return err; return err;
} }
if let Some(f) = quoted("missing field `") { if let Some(f) = quoted("missing field `") {
+6
View File
@@ -40,6 +40,12 @@ fn askpass() -> ExitCode {
); );
return ExitCode::SUCCESS; return ExitCode::SUCCESS;
} }
// Answer only the password prompt; anything else (a passphrase, a host key question)
// gets no answer, so the push fails instead of handing out the token.
if !prompt.starts_with("Password for") {
eprintln!("ianitor-control askpass: not answering {prompt:?}");
return ExitCode::FAILURE;
}
let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else { let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else {
return ExitCode::FAILURE; return ExitCode::FAILURE;
}; };
+3
View File
@@ -220,6 +220,9 @@ fn template(code: &str) -> &'static str {
"request.host" => "This request was sent to an address Ianitor does not answer on.", "request.host" => "This request was sent to an address Ianitor does not answer on.",
"request.not_found" => "There is no such API call.", "request.not_found" => "There is no such API call.",
"request.method" => "This API call does not take that method.", "request.method" => "This API call does not take that method.",
"request.in_progress" => {
"The first request with this Idempotency-Key is still being handled. Try again in a moment."
}
"request.idempotency" => "This Idempotency-Key was already used for a different request.", "request.idempotency" => "This Idempotency-Key was already used for a different request.",
"request.base_rev" => "base_rev is not a commit in the routes history.", "request.base_rev" => "base_rev is not a commit in the routes history.",
"health.unavailable" => { "health.unavailable" => {
-2
View File
@@ -194,8 +194,6 @@ impl Repo {
"core.fsync=all", "core.fsync=all",
"-c", "-c",
"core.fsyncMethod=fsync", "core.fsyncMethod=fsync",
"-c",
"protocol.file.allow=always",
]); ]);
c c
} }
+22 -2
View File
@@ -202,7 +202,11 @@ mod unix {
} }
everything.push_str(&env.file("edge/edge.json")); everything.push_str(&env.file("edge/edge.json"));
everything.push_str(&env.git(&["log", "-p", "--all"])); everything.push_str(&env.git(&["log", "-p", "--all"]));
let secret_part = |t: &str| t.rsplit('_').next().unwrap().to_owned(); // `ian_<16 hex>_<secret>`; the secret itself may contain '_'.
let secret_part = |t: &str| {
assert!(t.starts_with("ian_") && t.as_bytes()[20] == b'_');
t[21..].to_owned()
};
for t in [&env.token, &revoked] { for t in [&env.token, &revoked] {
assert!( assert!(
!everything.contains(secret_part(t).as_str()), !everything.contains(secret_part(t).as_str()),
@@ -265,6 +269,22 @@ mod unix {
.await; .await;
assert_eq!(r.status, 400, "{}", r.text); assert_eq!(r.status, 400, "{}", r.text);
assert!(!r.text.contains("secret-ish-value"), "{}", r.text); assert!(!r.text.contains("secret-ish-value"), "{}", r.text);
// Nor do odd field names, path parameters or credentials in an upstream URL.
let r = env
.call("POST", "/api/v1/tokens", Some(json!({ "pass:hunter2": 1 })))
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert!(!r.text.contains("hunter2"), "{}", r.text);
let r = env.call("GET", "/api/v1/hosts/x%3Chunter2%3E", None).await;
assert_eq!(r.status, 404, "{}", r.text);
assert!(!r.text.contains("hunter2"), "{}", r.text);
let mut leaky = host("a.test", "http://admin:hunter2@10.0.0.2:3000", false);
leaky["upstreams"] = json!(["http://admin:hunter2@10.0.0.2:3000", "ftp://u:hunter2@x"]);
let r = env
.call("POST", "/api/v1/hosts", Some(json!({ "host": leaky })))
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert!(!r.text.contains("hunter2"), "{}", r.text);
// Not JSON, wrong content type, too large. // Not JSON, wrong content type, too large.
let raw = format!( let raw = format!(
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{", "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{",
@@ -518,6 +538,6 @@ mod unix {
.output() .output()
.unwrap(); .unwrap();
let text = String::from_utf8_lossy(&out.stdout); let text = String::from_utf8_lossy(&out.stdout);
assert!(text.contains("test") && !text.contains(env.token.rsplit('_').next().unwrap())); assert!(text.contains("test") && !text.contains(&env.token[21..]));
} }
} }
+17 -10
View File
@@ -386,17 +386,24 @@ mod unix {
r["commit"].as_str().unwrap().to_owned(), r["commit"].as_str().unwrap().to_owned(),
)); ));
} }
// One after another: each starts after the previous finished, and each commit's // One after another: the five commits form one linear chain at the head (nothing
// parent is the previous commit (a linear history, nothing lost). // lost, nothing interleaved). Timestamps have one-second resolution, so they are not
spans.sort(); // compared.
for w in spans.windows(2) { let commits: Vec<String> = spans.iter().map(|s| s.2.clone()).collect();
assert!(w[1].0 >= w[0].1, "overlap: {w:?}"); let mut chain = Vec::new();
assert_eq!( let mut c = env.head();
env.git(&["rev-parse", &format!("{}^", w[1].2)]), for _ in 0..commits.len() {
w[0].2, chain.push(c.clone());
"linear" c = env.git(&["rev-parse", &format!("{c}^")]);
);
} }
let mut sorted_chain = chain.clone();
sorted_chain.sort();
let mut sorted_commits = commits.clone();
sorted_commits.sort();
assert_eq!(
sorted_chain, sorted_commits,
"a linear chain of the five commits"
);
let files = env.head_files(); let files = env.head_files();
for n in names { for n in names {
assert!( assert!(