[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:
@@ -38,11 +38,10 @@ fn check_hostname_param(h: &str) -> Result<(), ApiError> {
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.' || c == b'-')
|
||||
{
|
||||
return Err(ApiError::new(
|
||||
StatusCode::NOT_FOUND,
|
||||
"host.not_found",
|
||||
messages::params([("hostname", h.chars().take(253).collect())]),
|
||||
));
|
||||
// Not a hostname: say so without repeating what was sent.
|
||||
let mut e = ApiError::new(StatusCode::NOT_FOUND, "host.not_found", Params::new());
|
||||
e.body.message = "There is no such host.".into();
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -79,13 +78,21 @@ fn submit(
|
||||
) -> Result<Response, ApiError> {
|
||||
let key = idem_key(headers)?.map(|k| format!("{}:{k}", actor.token_id));
|
||||
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));
|
||||
}
|
||||
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 {
|
||||
st.idem_finish(k, &fp, None);
|
||||
}
|
||||
return Err(f.into());
|
||||
}
|
||||
};
|
||||
if let Some(k) = &key {
|
||||
st.idem_put(k, &fp, Stored::Apply(rec.id.clone()));
|
||||
st.idem_finish(k, &fp, Some(Stored::Apply(rec.id.clone())));
|
||||
}
|
||||
Ok(json(
|
||||
StatusCode::ACCEPTED,
|
||||
@@ -107,6 +114,11 @@ fn replay(st: &AppState, s: Stored) -> 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::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));
|
||||
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));
|
||||
}
|
||||
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)
|
||||
.map_err(|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(),
|
||||
));
|
||||
};
|
||||
let b = body.value;
|
||||
let field_err = |code: &str, field: &str| {
|
||||
let mut e = ApiError::new(
|
||||
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()))?;
|
||||
if let Some(k) = &key {
|
||||
st.idem_put(k, &fp, Stored::Json(201, v.clone()));
|
||||
}
|
||||
Ok(json(StatusCode::CREATED, &v))
|
||||
serde_json::to_value(&out).map_err(|e| ApiError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
/// Every share link, newest first (without tokens).
|
||||
|
||||
@@ -51,10 +51,15 @@ pub struct Actor {
|
||||
}
|
||||
|
||||
pub enum Stored {
|
||||
/// The first request with this key is still being handled.
|
||||
Pending,
|
||||
Apply(String),
|
||||
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 ctl: Arc<Control>,
|
||||
idem: Mutex<HashMap<String, (String, Stored, u64)>>,
|
||||
@@ -91,32 +96,65 @@ impl AppState {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Look up an Idempotency-Key. `Ok(Some)` replays, `Err` when the key was used for
|
||||
/// another request.
|
||||
pub fn idem_get(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
|
||||
let Ok(m) = self.idem.lock() else {
|
||||
return Ok(None);
|
||||
};
|
||||
/// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier
|
||||
/// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when
|
||||
/// the key was used for another request, is still in progress, or no key can be held.
|
||||
pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
|
||||
let mut m = self
|
||||
.idem
|
||||
.lock()
|
||||
.map_err(|_| ApiError::internal("idempotency store"))?;
|
||||
let t = now();
|
||||
match m.get(key) {
|
||||
Some((fp, _, _)) if fp != fingerprint => Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.idempotency",
|
||||
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((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.idempotency",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
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() {
|
||||
let t = now();
|
||||
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
|
||||
if m.len() >= 2000 {
|
||||
return;
|
||||
match s {
|
||||
Some(s) => {
|
||||
m.insert(key.to_owned(), (fingerprint.to_owned(), s, now()));
|
||||
}
|
||||
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())
|
||||
};
|
||||
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(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"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;
|
||||
}
|
||||
if let Some(f) = quoted("missing field `") {
|
||||
|
||||
@@ -40,6 +40,12 @@ fn askpass() -> ExitCode {
|
||||
);
|
||||
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 {
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
|
||||
@@ -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.not_found" => "There is no such API call.",
|
||||
"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.base_rev" => "base_rev is not a commit in the routes history.",
|
||||
"health.unavailable" => {
|
||||
|
||||
@@ -194,8 +194,6 @@ impl Repo {
|
||||
"core.fsync=all",
|
||||
"-c",
|
||||
"core.fsyncMethod=fsync",
|
||||
"-c",
|
||||
"protocol.file.allow=always",
|
||||
]);
|
||||
c
|
||||
}
|
||||
|
||||
@@ -202,7 +202,11 @@ mod unix {
|
||||
}
|
||||
everything.push_str(&env.file("edge/edge.json"));
|
||||
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] {
|
||||
assert!(
|
||||
!everything.contains(secret_part(t).as_str()),
|
||||
@@ -265,6 +269,22 @@ mod unix {
|
||||
.await;
|
||||
assert_eq!(r.status, 400, "{}", 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.
|
||||
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{{{{{{{{{{",
|
||||
@@ -518,6 +538,6 @@ mod unix {
|
||||
.output()
|
||||
.unwrap();
|
||||
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..]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,17 +386,24 @@ mod unix {
|
||||
r["commit"].as_str().unwrap().to_owned(),
|
||||
));
|
||||
}
|
||||
// One after another: each starts after the previous finished, and each commit's
|
||||
// parent is the previous commit (a linear history, nothing lost).
|
||||
spans.sort();
|
||||
for w in spans.windows(2) {
|
||||
assert!(w[1].0 >= w[0].1, "overlap: {w:?}");
|
||||
assert_eq!(
|
||||
env.git(&["rev-parse", &format!("{}^", w[1].2)]),
|
||||
w[0].2,
|
||||
"linear"
|
||||
);
|
||||
// One after another: the five commits form one linear chain at the head (nothing
|
||||
// lost, nothing interleaved). Timestamps have one-second resolution, so they are not
|
||||
// compared.
|
||||
let commits: Vec<String> = spans.iter().map(|s| s.2.clone()).collect();
|
||||
let mut chain = Vec::new();
|
||||
let mut c = env.head();
|
||||
for _ in 0..commits.len() {
|
||||
chain.push(c.clone());
|
||||
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();
|
||||
for n in names {
|
||||
assert!(
|
||||
|
||||
Reference in New Issue
Block a user