[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev
This commit is contained in:
@@ -0,0 +1,467 @@
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! The REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the
|
||||
//! handlers (utoipa).
|
||||
//!
|
||||
//! Every request: the `Host` header must name this server (against DNS rebinding); a browser
|
||||
//! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API
|
||||
//! token is required (nothing else identifies the caller: control trusts no `Remote-*`
|
||||
//! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no
|
||||
//! unknown fields. Errors are one typed envelope with a plain-English message. Logs show
|
||||
//! method, route template, status and time only.
|
||||
|
||||
// An error answer is built once per failed request; boxing it buys nothing.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
pub mod handlers;
|
||||
pub mod views;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::{Body as AxumBody, Bytes};
|
||||
use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post};
|
||||
use serde::de::DeserializeOwned;
|
||||
use utoipa::OpenApi;
|
||||
|
||||
pub use views::health_state;
|
||||
|
||||
use crate::engine::{Control, Fail};
|
||||
use crate::messages::{self, Params, message};
|
||||
use crate::tokens::Refusal;
|
||||
use crate::util::{hex, now, random, rfc3339, sha256_hex};
|
||||
use views::{ErrorBody, ErrorEnvelope};
|
||||
|
||||
pub const MAX_BODY: usize = 64 * 1024;
|
||||
const RATE_PER_MINUTE: u32 = 120;
|
||||
|
||||
/// Who is calling: the API token's id and name.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Actor {
|
||||
pub token_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub enum Stored {
|
||||
Apply(String),
|
||||
Json(u16, serde_json::Value),
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub ctl: Arc<Control>,
|
||||
idem: Mutex<HashMap<String, (String, Stored, u64)>>,
|
||||
rate: Mutex<HashMap<String, (u64, u32)>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(ctl: Arc<Control>) -> Arc<AppState> {
|
||||
Arc::new(AppState {
|
||||
ctl,
|
||||
idem: Mutex::new(HashMap::new()),
|
||||
rate: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Count one request against `bucket`; `Err(seconds to wait)` over the limit.
|
||||
pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> {
|
||||
let Ok(mut m) = self.rate.lock() else {
|
||||
return Ok(());
|
||||
};
|
||||
let t = now();
|
||||
let slot = t / window;
|
||||
if m.len() > 10_000 {
|
||||
m.retain(|_, (s, _)| *s + 1 >= slot);
|
||||
}
|
||||
let e = m.entry(bucket.to_owned()).or_insert((slot, 0));
|
||||
if e.0 != slot {
|
||||
*e = (slot, 0);
|
||||
}
|
||||
if e.1 >= per_window {
|
||||
return Err((slot + 1) * window - t);
|
||||
}
|
||||
e.1 += 1;
|
||||
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);
|
||||
};
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn idem_put(&self, key: &str, fingerprint: &str, s: 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;
|
||||
}
|
||||
m.insert(key.to_owned(), (fingerprint.to_owned(), s, t));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- errors
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ApiError {
|
||||
pub status: StatusCode,
|
||||
pub body: ErrorBody,
|
||||
pub errors: Vec<ErrorBody>,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError {
|
||||
ApiError {
|
||||
status,
|
||||
body: ErrorBody {
|
||||
code: code.into(),
|
||||
message: message(code, ¶ms),
|
||||
field: params.get("field").cloned(),
|
||||
params,
|
||||
retry_after_s: None,
|
||||
detail: None,
|
||||
},
|
||||
errors: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn internal(detail: impl Into<String>) -> ApiError {
|
||||
let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new());
|
||||
e.body.detail = Some(detail.into());
|
||||
e
|
||||
}
|
||||
|
||||
pub fn retry(mut self, secs: u64) -> ApiError {
|
||||
self.body.retry_after_s = Some(secs);
|
||||
self.body.params.insert("seconds".into(), secs.to_string());
|
||||
self.body.message = message(&self.body.code, &self.body.params);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Fail> for ApiError {
|
||||
fn from(f: Fail) -> ApiError {
|
||||
ApiError {
|
||||
status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
body: ErrorBody::from(&f.reason),
|
||||
errors: f.errors.iter().map(ErrorBody::from).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let retry = self.body.retry_after_s;
|
||||
let env = ErrorEnvelope {
|
||||
error: self.body,
|
||||
errors: self.errors,
|
||||
request_id: String::new(),
|
||||
};
|
||||
let mut r = (self.status, axum::Json(env)).into_response();
|
||||
if let Some(s) = retry
|
||||
&& let Ok(v) = HeaderValue::from_str(&s.to_string())
|
||||
{
|
||||
r.headers_mut().insert(header::RETRY_AFTER, v);
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- JSON bodies
|
||||
|
||||
/// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values.
|
||||
pub struct Body<T> {
|
||||
pub value: T,
|
||||
pub raw: Bytes,
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned, S: Send + Sync> FromRequest<S> for Body<T> {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
|
||||
let json_type = req
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|v| v.starts_with("application/json"));
|
||||
let raw = Bytes::from_request(req, state).await.map_err(|_| {
|
||||
ApiError::new(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"request.too_large",
|
||||
Params::new(),
|
||||
)
|
||||
})?;
|
||||
let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw };
|
||||
if !raw.is_empty() && !json_type {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||
"request.body",
|
||||
messages::params([("problem", "send it as application/json.".into())]),
|
||||
));
|
||||
}
|
||||
match serde_json::from_slice::<T>(text) {
|
||||
Ok(value) => Ok(Body { value, raw }),
|
||||
Err(e) => Err(body_error(&e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn body_error(e: &serde_json::Error) -> ApiError {
|
||||
let m = e.to_string();
|
||||
let quoted = |prefix: &str| -> Option<String> {
|
||||
let rest = m.split(prefix).nth(1)?;
|
||||
Some(rest.split('`').next()?.to_owned())
|
||||
};
|
||||
if let Some(f) = quoted("unknown field `") {
|
||||
let mut err = ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.body_unknown_field",
|
||||
messages::params([("field", f.clone())]),
|
||||
);
|
||||
err.body.field = Some(f);
|
||||
return err;
|
||||
}
|
||||
if let Some(f) = quoted("missing field `") {
|
||||
return ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"request.body",
|
||||
messages::params([
|
||||
("problem", format!("the field \"{f}\" is missing.")),
|
||||
("field", f),
|
||||
]),
|
||||
);
|
||||
}
|
||||
// Other serde messages can quote the value sent; say only where the problem is.
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON",
|
||||
_ => "a value has the wrong type or form",
|
||||
};
|
||||
ApiError::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"request.body",
|
||||
messages::params([(
|
||||
"problem",
|
||||
format!("{what} (line {}, column {}).", e.line(), e.column()),
|
||||
)]),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- middleware
|
||||
|
||||
fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
||||
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
|
||||
return false;
|
||||
};
|
||||
let port = ctl.cfg.listen.port();
|
||||
let ok = [
|
||||
ctl.cfg.listen.to_string(),
|
||||
format!("localhost:{port}"),
|
||||
format!("127.0.0.1:{port}"),
|
||||
format!("[::1]:{port}"),
|
||||
];
|
||||
ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|
||||
|| ctl
|
||||
.cfg
|
||||
.allowed_hosts
|
||||
.iter()
|
||||
.any(|a| a.eq_ignore_ascii_case(host))
|
||||
}
|
||||
|
||||
/// Host check, CSRF check, token, rate limit; logs method, route template, status, time.
|
||||
async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||
let started = Instant::now();
|
||||
let method = req.method().clone();
|
||||
let route = req
|
||||
.extensions()
|
||||
.get::<MatchedPath>()
|
||||
.map(|p| p.as_str().to_owned())
|
||||
.unwrap_or_else(|| "(no route)".into());
|
||||
let resp = async {
|
||||
if !host_allowed(&st.ctl, req.headers()) {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"request.host",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let browser = req.headers().contains_key(header::ORIGIN)
|
||||
|| req.headers().contains_key("sec-fetch-site");
|
||||
let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS");
|
||||
let ui = req
|
||||
.headers()
|
||||
.get("x-ianitor-ui")
|
||||
.is_some_and(|v| v.as_bytes() == b"1");
|
||||
if browser && write && !ui {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"request.csrf",
|
||||
Params::new(),
|
||||
));
|
||||
}
|
||||
let auth = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok());
|
||||
let tok = st.ctl.tokens.check(auth).map_err(|r| {
|
||||
let (code, params) = match r {
|
||||
Refusal::Missing => ("token.missing", Params::new()),
|
||||
Refusal::Unknown => ("token.unknown", Params::new()),
|
||||
Refusal::Expired(t) => (
|
||||
"token.expired",
|
||||
messages::params([("date", ianitor_core::time::long_date(t))]),
|
||||
),
|
||||
Refusal::Revoked(t) => (
|
||||
"token.revoked",
|
||||
messages::params([("date", ianitor_core::time::long_date(t))]),
|
||||
),
|
||||
};
|
||||
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
|
||||
})?;
|
||||
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
|
||||
.map_err(|s| {
|
||||
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||
})?;
|
||||
req.extensions_mut().insert(Actor {
|
||||
token_id: tok.id,
|
||||
name: tok.name,
|
||||
});
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
.await;
|
||||
let resp = resp.unwrap_or_else(IntoResponse::into_response);
|
||||
log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis());
|
||||
resp
|
||||
}
|
||||
|
||||
/// Adds `server_time` to every JSON object answer and `request_id` to error envelopes.
|
||||
async fn finish(req: Request, next: Next) -> Response {
|
||||
let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default();
|
||||
let resp = next.run(req).await;
|
||||
let json = resp
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.is_some_and(|v| v.as_bytes().starts_with(b"application/json"));
|
||||
let (mut parts, body) = resp.into_parts();
|
||||
if let Ok(v) = HeaderValue::from_str(&request_id) {
|
||||
parts.headers.insert("x-request-id", v);
|
||||
}
|
||||
if !json {
|
||||
return Response::from_parts(parts, body);
|
||||
}
|
||||
let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else {
|
||||
return Response::from_parts(parts, AxumBody::empty());
|
||||
};
|
||||
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
|
||||
Ok(serde_json::Value::Object(mut m)) => {
|
||||
m.insert("server_time".into(), rfc3339(now()).into());
|
||||
if m.contains_key("error") {
|
||||
m.insert("request_id".into(), request_id.into());
|
||||
}
|
||||
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
|
||||
}
|
||||
_ => bytes.to_vec(),
|
||||
};
|
||||
parts.headers.remove(header::CONTENT_LENGTH);
|
||||
Response::from_parts(parts, AxumBody::from(out))
|
||||
}
|
||||
|
||||
async fn not_found() -> ApiError {
|
||||
ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||
}
|
||||
|
||||
async fn method_not_allowed() -> ApiError {
|
||||
ApiError::new(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
"request.method",
|
||||
Params::new(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String {
|
||||
sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes())
|
||||
}
|
||||
|
||||
pub fn router(st: Arc<AppState>) -> Router {
|
||||
use handlers as h;
|
||||
let api = Router::new()
|
||||
.route("/api/v1/overview", get(h::overview))
|
||||
.route("/api/v1/hosts", get(h::list_hosts).post(h::create_host))
|
||||
.route("/api/v1/hosts/validate", post(h::validate_host))
|
||||
.route(
|
||||
"/api/v1/hosts/{hostname}",
|
||||
get(h::get_host)
|
||||
.put(h::update_host)
|
||||
.patch(h::patch_host)
|
||||
.delete(h::delete_host),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/hosts/{hostname}/share-links",
|
||||
post(h::mint_share_link),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/hosts/{hostname}/certificate/retry",
|
||||
post(h::retry_certificate),
|
||||
)
|
||||
.route("/api/v1/applies", get(h::list_applies))
|
||||
.route(
|
||||
"/api/v1/applies/{id}",
|
||||
get(h::get_apply).delete(h::cancel_apply),
|
||||
)
|
||||
.route("/api/v1/history", get(h::history))
|
||||
.route("/api/v1/history/{change_id}", get(h::history_entry))
|
||||
.route(
|
||||
"/api/v1/history/{change_id}/restore-preview",
|
||||
get(h::restore_preview),
|
||||
)
|
||||
.route("/api/v1/undo", get(h::get_undo).post(h::undo))
|
||||
.route("/api/v1/restore", post(h::restore))
|
||||
.route("/api/v1/repo/push", post(h::push_now))
|
||||
.route("/api/v1/settings", get(h::settings))
|
||||
.route("/api/v1/tokens", get(h::list_tokens).post(h::create_token))
|
||||
.route(
|
||||
"/api/v1/tokens/{id}",
|
||||
delete(h::revoke_token).patch(h::rename_token),
|
||||
)
|
||||
.route("/api/v1/share-links", get(h::list_share_links))
|
||||
.route(
|
||||
"/api/v1/share-links/stop-all",
|
||||
post(h::stop_all_share_links),
|
||||
)
|
||||
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
|
||||
.route("/api/v1/health", get(h::health))
|
||||
.route("/api/v1/openapi.json", get(h::openapi))
|
||||
.method_not_allowed_fallback(method_not_allowed)
|
||||
.fallback(not_found)
|
||||
.layer(middleware::from_fn_with_state(st.clone(), guard))
|
||||
.layer(DefaultBodyLimit::max(MAX_BODY))
|
||||
.with_state(st);
|
||||
api.layer(middleware::from_fn(finish))
|
||||
}
|
||||
|
||||
/// The OpenAPI document.
|
||||
pub fn openapi_json() -> String {
|
||||
handlers::ApiDoc::openapi()
|
||||
.to_pretty_json()
|
||||
.unwrap_or_else(|_| "{}".into())
|
||||
}
|
||||
Reference in New Issue
Block a user