[control] Previews: POST/GET/DELETE /api/v1/previews, tokens scoped to previews only, the upstream allow list, expiry; Windows drive paths in compile options (tests first)
This commit is contained in:
Generated
+1
@@ -1326,6 +1326,7 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"toml",
|
"toml",
|
||||||
|
"url",
|
||||||
"utoipa",
|
"utoipa",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ test-hooks = []
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
ianitor-core.workspace = true
|
ianitor-core.workspace = true
|
||||||
|
url.workspace = true
|
||||||
rustls.workspace = true
|
rustls.workspace = true
|
||||||
rustls-pki-types.workspace = true
|
rustls-pki-types.workspace = true
|
||||||
tokio-rustls.workspace = true
|
tokio-rustls.workspace = true
|
||||||
|
|||||||
@@ -935,6 +935,9 @@ pub struct TokenCreate {
|
|||||||
pub expires_in_days: Option<u64>,
|
pub expires_in_days: Option<u64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub never_expires: bool,
|
pub never_expires: bool,
|
||||||
|
/// `full` (default) or `previews`: a token for Fabrica that may only use `/api/v1/previews`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub scope: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Make a token. Its value is in this response only.
|
/// Make a token. Its value is in this response only.
|
||||||
@@ -966,7 +969,19 @@ pub async fn create_token(
|
|||||||
let name = b
|
let name = b
|
||||||
.name
|
.name
|
||||||
.unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now())));
|
.unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now())));
|
||||||
let (rec, value) = st.ctl.tokens.create(&name, expires).map_err(|e| {
|
let scope = match b.scope.as_deref() {
|
||||||
|
None => crate::tokens::Scope::Full,
|
||||||
|
Some(s) => crate::tokens::Scope::parse(s).ok_or_else(|| {
|
||||||
|
let mut e = ApiError::new(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"token.scope_value",
|
||||||
|
Params::new(),
|
||||||
|
);
|
||||||
|
e.body.field = Some("scope".into());
|
||||||
|
e
|
||||||
|
})?,
|
||||||
|
};
|
||||||
|
let (rec, value) = st.ctl.tokens.create(&name, expires, scope).map_err(|e| {
|
||||||
if e == "token.name" {
|
if e == "token.name" {
|
||||||
let mut err = ApiError::new(
|
let mut err = ApiError::new(
|
||||||
StatusCode::UNPROCESSABLE_ENTITY,
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
@@ -1384,7 +1399,9 @@ impl Modify for Bearer {
|
|||||||
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
|
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
|
||||||
super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
|
super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
|
||||||
super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
|
super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
|
||||||
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine
|
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine,
|
||||||
|
super::previews::list_previews, super::previews::open_preview, super::previews::get_preview,
|
||||||
|
super::previews::kill_preview, super::previews::close_preview
|
||||||
),
|
),
|
||||||
components(schemas(
|
components(schemas(
|
||||||
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
|
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
|
||||||
@@ -1394,13 +1411,15 @@ impl Modify for Bearer {
|
|||||||
HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
|
HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
|
||||||
super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
|
super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
|
||||||
super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
|
super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
|
||||||
FallbackReady
|
FallbackReady, crate::hostspec::PreviewSpec, super::previews::PreviewOpen, super::previews::PreviewClose,
|
||||||
|
super::previews::PreviewView, super::previews::PreviewOpened, super::previews::PreviewOne,
|
||||||
|
super::previews::PreviewList, super::previews::PreviewClosed
|
||||||
)),
|
)),
|
||||||
modifiers(&Bearer),
|
modifiers(&Bearer),
|
||||||
tags(
|
tags(
|
||||||
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
|
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
|
||||||
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
|
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
|
||||||
(name = "certs"), (name = "engine")
|
(name = "certs"), (name = "engine"), (name = "previews")
|
||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
pub struct ApiDoc;
|
pub struct ApiDoc;
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
|
|
||||||
pub mod handlers;
|
pub mod handlers;
|
||||||
pub mod pki;
|
pub mod pki;
|
||||||
|
pub mod previews;
|
||||||
pub mod ui;
|
pub mod ui;
|
||||||
pub mod views;
|
pub mod views;
|
||||||
|
|
||||||
@@ -45,11 +46,20 @@ use views::{ErrorBody, ErrorEnvelope};
|
|||||||
pub const MAX_BODY: usize = 64 * 1024;
|
pub const MAX_BODY: usize = 64 * 1024;
|
||||||
const RATE_PER_MINUTE: u32 = 120;
|
const RATE_PER_MINUTE: u32 = 120;
|
||||||
|
|
||||||
/// Who is calling: the API token's id and name.
|
/// Who is calling: the API token's id and name, and what the token may do.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Actor {
|
pub struct Actor {
|
||||||
pub token_id: String,
|
pub token_id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub scope: crate::tokens::Scope,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The only routes a `previews` token may call (T4: it can never touch another host).
|
||||||
|
fn in_preview_scope(path: &str) -> bool {
|
||||||
|
path == "/api/v1/previews"
|
||||||
|
|| path
|
||||||
|
.strip_prefix("/api/v1/previews/")
|
||||||
|
.is_some_and(|rest| !rest.is_empty() && !rest.contains('/'))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Stored {
|
pub enum Stored {
|
||||||
@@ -461,6 +471,7 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
|
|||||||
req.extensions_mut().insert(Actor {
|
req.extensions_mut().insert(Actor {
|
||||||
token_id: format!("user:{user}"),
|
token_id: format!("user:{user}"),
|
||||||
name: display,
|
name: display,
|
||||||
|
scope: crate::tokens::Scope::Full,
|
||||||
});
|
});
|
||||||
return Ok(next.run(req).await);
|
return Ok(next.run(req).await);
|
||||||
}
|
}
|
||||||
@@ -490,6 +501,13 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
|
|||||||
};
|
};
|
||||||
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
|
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
|
||||||
})?;
|
})?;
|
||||||
|
if tok.scope == crate::tokens::Scope::Previews && !in_preview_scope(req.uri().path()) {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"token.scope",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
|
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 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)
|
||||||
@@ -497,6 +515,7 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
|
|||||||
req.extensions_mut().insert(Actor {
|
req.extensions_mut().insert(Actor {
|
||||||
token_id: tok.id,
|
token_id: tok.id,
|
||||||
name: tok.name,
|
name: tok.name,
|
||||||
|
scope: tok.scope,
|
||||||
});
|
});
|
||||||
Ok(next.run(req).await)
|
Ok(next.run(req).await)
|
||||||
}
|
}
|
||||||
@@ -620,6 +639,15 @@ pub fn router(st: Arc<AppState>) -> Router {
|
|||||||
"/api/v1/engine",
|
"/api/v1/engine",
|
||||||
get(pki::get_engine).post(pki::switch_engine),
|
get(pki::get_engine).post(pki::switch_engine),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/previews",
|
||||||
|
get(previews::list_previews).post(previews::open_preview),
|
||||||
|
)
|
||||||
|
.route("/api/v1/previews/close", post(previews::close_preview))
|
||||||
|
.route(
|
||||||
|
"/api/v1/previews/{hostname}",
|
||||||
|
get(previews::get_preview).delete(previews::kill_preview),
|
||||||
|
)
|
||||||
.route("/api/v1/health", get(h::health))
|
.route("/api/v1/health", get(h::health))
|
||||||
.route("/api/v1/openapi.json", get(h::openapi))
|
.route("/api/v1/openapi.json", get(h::openapi))
|
||||||
.method_not_allowed_fallback(method_not_allowed)
|
.method_not_allowed_fallback(method_not_allowed)
|
||||||
|
|||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! `/api/v1/previews`: Fabrica's branch previews (T4). The only routes a `previews` token may
|
||||||
|
//! call (the guard in `api` refuses every other route for it).
|
||||||
|
|
||||||
|
// An error answer is built once per failed request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
use super::views::{ApplyView, apply_view};
|
||||||
|
use super::{Actor, ApiError, AppState, Body};
|
||||||
|
use crate::messages::Params;
|
||||||
|
use crate::util::rfc3339;
|
||||||
|
|
||||||
|
type Shared = State<Arc<AppState>>;
|
||||||
|
|
||||||
|
fn json<T: Serialize>(status: StatusCode, v: &T) -> Response {
|
||||||
|
(status, axum::Json(v)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewOpen {
|
||||||
|
/// Fabrica's project, e.g. `mnovak/Arca` or `github:acme/web`.
|
||||||
|
pub project: String,
|
||||||
|
/// The git branch, as the git host names it.
|
||||||
|
pub branch: String,
|
||||||
|
/// Where the branch's build runs, e.g. `http://10.0.0.5:8080` (must be in `[previews] upstreams`).
|
||||||
|
pub upstream: String,
|
||||||
|
/// Seconds until the preview closes by itself (default from `[previews]`).
|
||||||
|
pub ttl: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewClose {
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewView {
|
||||||
|
pub hostname: String,
|
||||||
|
/// `https://<hostname>/`
|
||||||
|
pub url: String,
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
pub upstream: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
/// `applying`, `live` or `failed`.
|
||||||
|
pub state: String,
|
||||||
|
/// Why it failed, in plain English.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub problem: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewOpened {
|
||||||
|
pub preview: PreviewView,
|
||||||
|
pub apply: ApplyView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewOne {
|
||||||
|
pub preview: PreviewView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewList {
|
||||||
|
pub items: Vec<PreviewView>,
|
||||||
|
/// The domain previews live under; absent when previews are off.
|
||||||
|
pub domain: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewClosed {
|
||||||
|
pub apply: ApplyView,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view(st: &AppState, p: &crate::previews::Listed) -> PreviewView {
|
||||||
|
let (state, problem) = st
|
||||||
|
.ctl
|
||||||
|
.preview_state(&p.hostname)
|
||||||
|
.unwrap_or(("live".into(), None));
|
||||||
|
PreviewView {
|
||||||
|
url: format!("https://{}/", p.hostname),
|
||||||
|
hostname: p.hostname.clone(),
|
||||||
|
project: p.project.clone(),
|
||||||
|
branch: p.branch.clone(),
|
||||||
|
upstream: p.upstream.clone(),
|
||||||
|
expires_at: rfc3339(p.expires_at),
|
||||||
|
state,
|
||||||
|
problem,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every open preview.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/previews", tag = "previews",
|
||||||
|
responses((status = 200, body = PreviewList)), security(("bearer" = [])))]
|
||||||
|
pub async fn list_previews(State(st): Shared) -> Result<Response, ApiError> {
|
||||||
|
let domain = st.ctl.cfg.previews.as_ref().map(|p| p.domain.clone());
|
||||||
|
let items = if domain.is_some() {
|
||||||
|
st.ctl.previews()?.iter().map(|p| view(&st, p)).collect()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
Ok(json(StatusCode::OK, &PreviewList { items, domain }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a branch's preview, or move it to a new upstream and lifetime. The host is
|
||||||
|
/// `<branch>--<project>.<preview domain>`; it is live when its apply is kept.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/previews", tag = "previews", request_body = PreviewOpen,
|
||||||
|
responses((status = 202, body = PreviewOpened), (status = 403, body = super::views::ErrorEnvelope),
|
||||||
|
(status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn open_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<PreviewOpen>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let b = body.value;
|
||||||
|
let (hostname, expires_at, rec) =
|
||||||
|
st.ctl
|
||||||
|
.open_preview(&b.project, &b.branch, &b.upstream, b.ttl, &actor.name)?;
|
||||||
|
let preview = PreviewView {
|
||||||
|
url: format!("https://{hostname}/"),
|
||||||
|
hostname,
|
||||||
|
project: b.project,
|
||||||
|
branch: b.branch,
|
||||||
|
upstream: b.upstream,
|
||||||
|
expires_at: rfc3339(expires_at),
|
||||||
|
state: "applying".into(),
|
||||||
|
problem: None,
|
||||||
|
};
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::ACCEPTED,
|
||||||
|
&PreviewOpened {
|
||||||
|
preview,
|
||||||
|
apply: apply_view(&st.ctl, &rec),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One preview and where it stands (Fabrica polls this after opening one).
|
||||||
|
#[utoipa::path(get, path = "/api/v1/previews/{hostname}", tag = "previews",
|
||||||
|
params(("hostname" = String, Path)),
|
||||||
|
responses((status = 200, body = PreviewOne), (status = 404, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn get_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(hostname): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
st.ctl.previews_cfg()?;
|
||||||
|
let not_found = || ApiError::new(StatusCode::NOT_FOUND, "preview.not_found", Params::new());
|
||||||
|
if let Some(p) = st
|
||||||
|
.ctl
|
||||||
|
.previews()?
|
||||||
|
.into_iter()
|
||||||
|
.find(|p| p.hostname == hostname)
|
||||||
|
{
|
||||||
|
return Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&PreviewOne {
|
||||||
|
preview: view(&st, &p),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Not at the head: a preview whose apply is still running or failed.
|
||||||
|
let (state, problem) = st.ctl.preview_state(&hostname).ok_or_else(not_found)?;
|
||||||
|
let rec = st
|
||||||
|
.ctl
|
||||||
|
.records()
|
||||||
|
.into_iter()
|
||||||
|
.rev()
|
||||||
|
.find(|r| r.hosts.contains(&hostname))
|
||||||
|
.ok_or_else(not_found)?;
|
||||||
|
let pv = rec
|
||||||
|
.attempted_host
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|h| h.preview.clone())
|
||||||
|
.ok_or_else(not_found)?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&PreviewOne {
|
||||||
|
preview: PreviewView {
|
||||||
|
url: format!("https://{hostname}/"),
|
||||||
|
hostname,
|
||||||
|
project: pv.project,
|
||||||
|
branch: pv.branch,
|
||||||
|
upstream: rec
|
||||||
|
.attempted_host
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|h| h.upstreams.first().cloned())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
expires_at: rfc3339(u64::try_from(pv.expires_at).unwrap_or(0)),
|
||||||
|
state,
|
||||||
|
problem,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a preview now (the previews screen's Close, or Fabrica after a merge).
|
||||||
|
#[utoipa::path(delete, path = "/api/v1/previews/{hostname}", tag = "previews",
|
||||||
|
params(("hostname" = String, Path)),
|
||||||
|
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn kill_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
Path(hostname): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::ACCEPTED,
|
||||||
|
&PreviewClosed {
|
||||||
|
apply: apply_view(&st.ctl, &rec),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a branch's preview by project and branch (Fabrica, when the branch is merged or
|
||||||
|
/// deleted).
|
||||||
|
#[utoipa::path(post, path = "/api/v1/previews/close", tag = "previews", request_body = PreviewClose,
|
||||||
|
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn close_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<PreviewClose>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let b = body.value;
|
||||||
|
let p = st.ctl.previews_cfg()?;
|
||||||
|
let hostname = ianitor_core::preview::hostname(&b.project, &b.branch, &p.domain)
|
||||||
|
.map_err(crate::previews::name_fail)?;
|
||||||
|
let mine = st
|
||||||
|
.ctl
|
||||||
|
.previews()?
|
||||||
|
.into_iter()
|
||||||
|
.any(|x| x.hostname == hostname && x.project == b.project && x.branch == b.branch);
|
||||||
|
if !mine {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"preview.not_found",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::ACCEPTED,
|
||||||
|
&PreviewClosed {
|
||||||
|
apply: apply_view(&st.ctl, &rec),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -746,6 +746,8 @@ pub struct TokenView {
|
|||||||
pub last_used_at: Option<String>,
|
pub last_used_at: Option<String>,
|
||||||
pub expires_at: Option<String>,
|
pub expires_at: Option<String>,
|
||||||
pub revoked_at: Option<String>,
|
pub revoked_at: Option<String>,
|
||||||
|
/// `full` or `previews`.
|
||||||
|
pub scope: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&crate::tokens::TokenRecord> for TokenView {
|
impl From<&crate::tokens::TokenRecord> for TokenView {
|
||||||
@@ -757,6 +759,7 @@ impl From<&crate::tokens::TokenRecord> for TokenView {
|
|||||||
last_used_at: t(r.last_used_at),
|
last_used_at: t(r.last_used_at),
|
||||||
expires_at: t(r.expires_at),
|
expires_at: t(r.expires_at),
|
||||||
revoked_at: t(r.revoked_at),
|
revoked_at: t(r.revoked_at),
|
||||||
|
scope: r.scope.as_str().into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,61 @@ pub struct Config {
|
|||||||
/// Switching between Pingora and the Caddy fallback at runtime.
|
/// Switching between Pingora and the Caddy fallback at runtime.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub engine: Option<EngineConfig>,
|
pub engine: Option<EngineConfig>,
|
||||||
|
/// Branch previews for Fabrica (`POST /api/v1/previews`); off without it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub previews: Option<PreviewsConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `[previews]`: where branch previews live and what they may point at.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewsConfig {
|
||||||
|
/// Previews are `<branch>--<project>.<domain>`; a wildcard DNS record points here.
|
||||||
|
pub domain: String,
|
||||||
|
/// `domi` (the Domi CA, internal) or `letsencrypt` (public; one certificate per preview).
|
||||||
|
#[serde(default = "default_preview_tls")]
|
||||||
|
pub tls: String,
|
||||||
|
/// `none` (anyone with the address) or `forward-auth` (behind the site's sign-in).
|
||||||
|
#[serde(default = "default_preview_auth")]
|
||||||
|
pub auth: String,
|
||||||
|
/// Where previews may send traffic: `10.0.0.0/8`, `127.0.0.1:20000-29999`, `app.internal`,
|
||||||
|
/// `*.svc.internal:8080`. Nothing else is accepted; control's own port and Caddy's admin
|
||||||
|
/// port never are. Empty: every preview is refused.
|
||||||
|
#[serde(default)]
|
||||||
|
pub upstreams: Vec<String>,
|
||||||
|
#[serde(default = "default_preview_ttl")]
|
||||||
|
pub default_ttl_secs: u64,
|
||||||
|
#[serde(default = "default_preview_min_ttl")]
|
||||||
|
pub min_ttl_secs: u64,
|
||||||
|
#[serde(default = "default_preview_max_ttl")]
|
||||||
|
pub max_ttl_secs: u64,
|
||||||
|
#[serde(default = "default_preview_max")]
|
||||||
|
pub max_previews: usize,
|
||||||
|
/// How often expired previews are looked for.
|
||||||
|
#[serde(default = "default_preview_sweep")]
|
||||||
|
pub sweep_secs: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_preview_tls() -> String {
|
||||||
|
"domi".into()
|
||||||
|
}
|
||||||
|
fn default_preview_auth() -> String {
|
||||||
|
"none".into()
|
||||||
|
}
|
||||||
|
fn default_preview_ttl() -> u64 {
|
||||||
|
72 * 3600
|
||||||
|
}
|
||||||
|
fn default_preview_min_ttl() -> u64 {
|
||||||
|
300
|
||||||
|
}
|
||||||
|
fn default_preview_max_ttl() -> u64 {
|
||||||
|
30 * 86_400
|
||||||
|
}
|
||||||
|
fn default_preview_max() -> usize {
|
||||||
|
100
|
||||||
|
}
|
||||||
|
fn default_preview_sweep() -> u64 {
|
||||||
|
30
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -120,13 +175,14 @@ pub struct Compile {
|
|||||||
|
|
||||||
impl Compile {
|
impl Compile {
|
||||||
pub fn options(&self) -> CompileOptions {
|
pub fn options(&self) -> CompileOptions {
|
||||||
|
use ianitor_core::compile::windows_path as w;
|
||||||
CompileOptions {
|
CompileOptions {
|
||||||
http_listen: self.http_listen,
|
http_listen: self.http_listen,
|
||||||
https_listen: self.https_listen,
|
https_listen: self.https_listen,
|
||||||
cert_dir: self.cert_dir.clone(),
|
cert_dir: w(&self.cert_dir),
|
||||||
state_dir: self.state_dir.clone(),
|
state_dir: w(&self.state_dir),
|
||||||
access_log: self.access_log.clone(),
|
access_log: w(&self.access_log),
|
||||||
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
|
caddy_credentials_dir: w(&self.caddy_credentials_dir),
|
||||||
caddy_admin: self.caddy_admin,
|
caddy_admin: self.caddy_admin,
|
||||||
caddy_admin_socket: self.caddy_admin_socket.clone(),
|
caddy_admin_socket: self.caddy_admin_socket.clone(),
|
||||||
trusted_proxies: self.trusted_proxies.clone(),
|
trusted_proxies: self.trusted_proxies.clone(),
|
||||||
@@ -240,6 +296,9 @@ impl Config {
|
|||||||
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
|
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
if let Some(p) = &self.previews {
|
||||||
|
crate::previews::check_config(p, self).map_err(ConfigError::Invalid)?;
|
||||||
|
}
|
||||||
if let Some(m) = empty_model() {
|
if let Some(m) = empty_model() {
|
||||||
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
|
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
|
||||||
ianitor_core::compile::edge(&m, &c.options())
|
ianitor_core::compile::edge(&m, &c.options())
|
||||||
|
|||||||
@@ -170,11 +170,23 @@ pub async fn run(args: &[String]) -> Result<(), String> {
|
|||||||
logout_url: None,
|
logout_url: None,
|
||||||
}),
|
}),
|
||||||
engine: None,
|
engine: None,
|
||||||
|
// Branch previews on a name nobody can own (RFC 2606), from loopback test upstreams.
|
||||||
|
previews: Some(ianitor_control::config::PreviewsConfig {
|
||||||
|
domain: "preview.dev.test".into(),
|
||||||
|
tls: "domi".into(),
|
||||||
|
auth: "none".into(),
|
||||||
|
upstreams: vec!["127.0.0.1:20000-29999".into(), "10.0.0.0/8".into()],
|
||||||
|
default_ttl_secs: 72 * 3600,
|
||||||
|
min_ttl_secs: 60,
|
||||||
|
max_ttl_secs: 30 * 86_400,
|
||||||
|
max_previews: 100,
|
||||||
|
sweep_secs: 10,
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
cfg.check().map_err(|e| e.to_string())?;
|
cfg.check().map_err(|e| e.to_string())?;
|
||||||
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
|
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?;
|
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None, Default::default())?;
|
||||||
|
|
||||||
// Control writes edge.json first; then edge can start from it.
|
// Control writes edge.json first; then edge can start from it.
|
||||||
let ctl_cfg = cfg.clone();
|
let ctl_cfg = cfg.clone();
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ struct Job {
|
|||||||
id: String,
|
id: String,
|
||||||
change: Change,
|
change: Change,
|
||||||
base_rev: Option<String>,
|
base_rev: Option<String>,
|
||||||
|
/// Replaces the plan's summary (and so the commit message), e.g. for previews.
|
||||||
|
summary: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A refusal, before or during an apply.
|
/// A refusal, before or during an apply.
|
||||||
@@ -740,6 +742,18 @@ impl Control {
|
|||||||
change: Change,
|
change: Change,
|
||||||
base_rev: Option<String>,
|
base_rev: Option<String>,
|
||||||
actor: &str,
|
actor: &str,
|
||||||
|
) -> Result<ApplyRecord, Fail> {
|
||||||
|
self.submit_as(change, base_rev, actor, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Control::submit`] with a summary of the caller's own (the history line and commit
|
||||||
|
/// message), e.g. "Opened the preview of fix-42 (shop)".
|
||||||
|
pub fn submit_as(
|
||||||
|
&self,
|
||||||
|
change: Change,
|
||||||
|
base_rev: Option<String>,
|
||||||
|
actor: &str,
|
||||||
|
summary: Option<String>,
|
||||||
) -> Result<ApplyRecord, Fail> {
|
) -> Result<ApplyRecord, Fail> {
|
||||||
if let Some(p) = self.paused_for(&change, false) {
|
if let Some(p) = self.paused_for(&change, false) {
|
||||||
return Err(Fail::new(
|
return Err(Fail::new(
|
||||||
@@ -749,7 +763,10 @@ impl Control {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let (head, tree) = self.head_and_tree()?;
|
let (head, tree) = self.head_and_tree()?;
|
||||||
let plan = self.plan(&change, &head, &tree, base_rev.as_deref())?;
|
let mut plan = self.plan(&change, &head, &tree, base_rev.as_deref())?;
|
||||||
|
if let Some(s) = &summary {
|
||||||
|
plan.summary = s.clone();
|
||||||
|
}
|
||||||
self.compile(&plan.model)?;
|
self.compile(&plan.model)?;
|
||||||
let id = format!(
|
let id = format!(
|
||||||
"ch_{}",
|
"ch_{}",
|
||||||
@@ -792,6 +809,7 @@ impl Control {
|
|||||||
id,
|
id,
|
||||||
change,
|
change,
|
||||||
base_rev,
|
base_rev,
|
||||||
|
summary,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
self.wake.notify_one();
|
self.wake.notify_one();
|
||||||
@@ -930,7 +948,14 @@ impl Control {
|
|||||||
Ok(x) => x,
|
Ok(x) => x,
|
||||||
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
|
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
|
||||||
};
|
};
|
||||||
let plan = match self.plan(&job.change, &head, &tree, job.base_rev.as_deref()) {
|
let plan = match self
|
||||||
|
.plan(&job.change, &head, &tree, job.base_rev.as_deref())
|
||||||
|
.map(|mut p| {
|
||||||
|
if let Some(s) = &job.summary {
|
||||||
|
p.summary = s.clone();
|
||||||
|
}
|
||||||
|
p
|
||||||
|
}) {
|
||||||
Ok(p) => p,
|
Ok(p) => p,
|
||||||
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
|
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
|
||||||
};
|
};
|
||||||
@@ -1000,7 +1025,7 @@ impl Control {
|
|||||||
}
|
}
|
||||||
crash::point("committed");
|
crash::point("committed");
|
||||||
|
|
||||||
if !self.edge.attached() {
|
if !self.edge.attached() && self.engine_running() != "caddy" {
|
||||||
// Development without an edge: write the files directly, nothing to watch.
|
// Development without an edge: write the files directly, nothing to watch.
|
||||||
let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
|
let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
|
||||||
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644));
|
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644));
|
||||||
|
|||||||
@@ -38,6 +38,18 @@ pub struct HostSpec {
|
|||||||
pub request_headers: Vec<HeaderRuleSpec>,
|
pub request_headers: Vec<HeaderRuleSpec>,
|
||||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
pub response_headers: Vec<HeaderRuleSpec>,
|
pub response_headers: Vec<HeaderRuleSpec>,
|
||||||
|
/// Set on a branch preview (Fabrica); written by `/api/v1/previews`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub preview: Option<PreviewSpec>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewSpec {
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub expires_at: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||||
@@ -178,6 +190,7 @@ mod tests {
|
|||||||
secret: None,
|
secret: None,
|
||||||
}],
|
}],
|
||||||
response_headers: vec![],
|
response_headers: vec![],
|
||||||
|
preview: None,
|
||||||
};
|
};
|
||||||
let text = h.to_toml().unwrap();
|
let text = h.to_toml().unwrap();
|
||||||
assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
|
assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ pub mod logger;
|
|||||||
pub mod messages;
|
pub mod messages;
|
||||||
pub mod pki;
|
pub mod pki;
|
||||||
pub mod pki_ctl;
|
pub mod pki_ctl;
|
||||||
|
pub mod previews;
|
||||||
pub mod records;
|
pub mod records;
|
||||||
pub mod repo;
|
pub mod repo;
|
||||||
pub mod shares;
|
pub mod shares;
|
||||||
@@ -42,6 +43,7 @@ pub async fn serve(
|
|||||||
tokio::spawn(ctl.clone().health_poller());
|
tokio::spawn(ctl.clone().health_poller());
|
||||||
tokio::spawn(ctl.clone().pusher());
|
tokio::spawn(ctl.clone().pusher());
|
||||||
tokio::spawn(ctl.clone().pki_poller());
|
tokio::spawn(ctl.clone().pki_poller());
|
||||||
|
tokio::spawn(ctl.clone().preview_sweeper());
|
||||||
let app = api::router(api::AppState::new(ctl.clone()));
|
let app = api::router(api::AppState::new(ctl.clone()));
|
||||||
if !listen.ip().is_loopback() {
|
if !listen.ip().is_loopback() {
|
||||||
return Err("ianitor-control only listens on loopback".into());
|
return Err("ianitor-control only listens on loopback".into());
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
//! ```text
|
//! ```text
|
||||||
//! ianitor-control --config <control.toml> run the control plane
|
//! ianitor-control --config <control.toml> run the control plane
|
||||||
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
|
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
|
||||||
//! ianitor-control token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
|
//! ianitor-control token create --name <name> [--scope full|previews] [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
|
||||||
//! ianitor-control token list (--config <c> | --state-dir <d>)
|
//! ianitor-control token list (--config <c> | --state-dir <d>)
|
||||||
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
|
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
|
||||||
//! ianitor-control openapi print the OpenAPI document
|
//! ianitor-control openapi print the OpenAPI document
|
||||||
@@ -139,12 +139,19 @@ fn token(args: &[String]) -> Result<(), String> {
|
|||||||
match args.first().map(String::as_str) {
|
match args.first().map(String::as_str) {
|
||||||
Some("create") => {
|
Some("create") => {
|
||||||
let mut name = None;
|
let mut name = None;
|
||||||
|
let mut scope = ianitor_control::tokens::Scope::Full;
|
||||||
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
|
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
|
||||||
let mut it = args.iter().skip(1);
|
let mut it = args.iter().skip(1);
|
||||||
while let Some(a) = it.next() {
|
while let Some(a) = it.next() {
|
||||||
match a.as_str() {
|
match a.as_str() {
|
||||||
"--name" => name = it.next().cloned(),
|
"--name" => name = it.next().cloned(),
|
||||||
"--never" => expires = None,
|
"--never" => expires = None,
|
||||||
|
"--scope" => {
|
||||||
|
scope = it
|
||||||
|
.next()
|
||||||
|
.and_then(|s| ianitor_control::tokens::Scope::parse(s))
|
||||||
|
.ok_or("--scope must be full or previews")?;
|
||||||
|
}
|
||||||
"--expires-days" => {
|
"--expires-days" => {
|
||||||
let d: u64 = it
|
let d: u64 = it
|
||||||
.next()
|
.next()
|
||||||
@@ -157,7 +164,7 @@ fn token(args: &[String]) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let name = name.ok_or("--name <name> is required")?;
|
let name = name.ok_or("--name <name> is required")?;
|
||||||
let (rec, value) = tokens.create(&name, expires).map_err(|e| {
|
let (rec, value) = tokens.create(&name, expires, scope).map_err(|e| {
|
||||||
if e == "token.name" {
|
if e == "token.name" {
|
||||||
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
|
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
|
||||||
.to_owned()
|
.to_owned()
|
||||||
@@ -166,8 +173,10 @@ fn token(args: &[String]) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Token {} ({}) created. It is shown once; save it in Custos now:",
|
"Token {} ({}, scope {}) created. It is shown once; save it in Custos now:",
|
||||||
rec.id, rec.name
|
rec.id,
|
||||||
|
rec.name,
|
||||||
|
rec.scope.as_str()
|
||||||
);
|
);
|
||||||
println!("{value}");
|
println!("{value}");
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -186,6 +195,9 @@ fn token(args: &[String]) -> Result<(), String> {
|
|||||||
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
|
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
);
|
);
|
||||||
|
if t.scope != ianitor_control::tokens::Scope::Full {
|
||||||
|
println!(" scope {}", t.scope.as_str());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -205,6 +205,29 @@ fn template(code: &str) -> &'static str {
|
|||||||
"token.not_found" => "There is no API token with that id.",
|
"token.not_found" => "There is no API token with that id.",
|
||||||
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
|
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
|
||||||
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
||||||
|
"token.scope" => {
|
||||||
|
"This API token may only open and close branch previews (/api/v1/previews)."
|
||||||
|
}
|
||||||
|
"token.scope_value" => "A token's scope is full or previews.",
|
||||||
|
"preview.off" => {
|
||||||
|
"Previews are off on this server: set a preview domain under [previews] in control.toml."
|
||||||
|
}
|
||||||
|
"preview.taken" => {
|
||||||
|
"{hostname} is already used by another host or branch, so this branch's preview cannot have it."
|
||||||
|
}
|
||||||
|
"preview.not_found" => "There is no preview at that address.",
|
||||||
|
"preview.branch" => "The branch name {problem}.",
|
||||||
|
"preview.project" => "The project name {problem}.",
|
||||||
|
"preview.domain" => "The preview address is not usable: {problem}.",
|
||||||
|
"preview.ttl" => "Choose a lifetime between {min} and {max} seconds.",
|
||||||
|
"preview.upstream" => {
|
||||||
|
"Write the preview's address as http://host:port or https://host:port, without a path, user or password."
|
||||||
|
}
|
||||||
|
"preview.upstream_not_allowed" => {
|
||||||
|
"{upstream} is not an address previews may use. Allowed: {allowed}."
|
||||||
|
}
|
||||||
|
"preview.too_many" => "There are already {max} previews. Close some first.",
|
||||||
|
"preview.expired" => "Preview of {branch} expired",
|
||||||
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
|
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
|
||||||
"control.files_unwritten" => {
|
"control.files_unwritten" => {
|
||||||
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
|
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
|
||||||
|
|||||||
@@ -0,0 +1,537 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Branch previews for Fabrica (Fabrica docs/32_coherence.md, T4). A preview is an ordinary
|
||||||
|
//! host file in the routes repository with a `[preview]` table, so it goes through the same
|
||||||
|
//! validation, compilers, differential tests and commit-confirmed apply as any host. This
|
||||||
|
//! module holds what is preview-only: the host body control writes, the upstream allow list
|
||||||
|
//! (a preview token is hostile: it must not be able to publish this machine's admin ports),
|
||||||
|
//! and the sweeper that closes expired previews.
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::config::{Config, PreviewsConfig};
|
||||||
|
use crate::engine::{Change, Control, Fail};
|
||||||
|
use crate::hostspec::{HeaderRuleSpec, HostSpec, PreviewSpec};
|
||||||
|
use crate::messages::{self, Params};
|
||||||
|
use crate::util::now;
|
||||||
|
|
||||||
|
/// The actor name the sweeper's removals carry in the history.
|
||||||
|
pub const EXPIRY_ACTOR: &str = "Preview expiry";
|
||||||
|
|
||||||
|
/// One entry of `[previews] upstreams`.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
enum Target {
|
||||||
|
Net(IpAddr, u8),
|
||||||
|
Name(String),
|
||||||
|
/// `*.suffix`: any name ending in `.suffix`.
|
||||||
|
Suffix(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct Allowed {
|
||||||
|
target: Target,
|
||||||
|
ports: Option<(u16, u16)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ports(p: &str) -> Option<(u16, u16)> {
|
||||||
|
let (lo, hi) = match p.split_once('-') {
|
||||||
|
Some((a, b)) => (a.parse().ok()?, b.parse().ok()?),
|
||||||
|
None => {
|
||||||
|
let x: u16 = p.parse().ok()?;
|
||||||
|
(x, x)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(lo >= 1 && lo <= hi).then_some((lo, hi))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_entry(e: &str) -> Option<Allowed> {
|
||||||
|
let e = e.trim();
|
||||||
|
// IPv6 networks carry no port (`fd00::/8`); everything else may end in `:port[-port]`.
|
||||||
|
if e.matches(':').count() > 1 {
|
||||||
|
let (ip, bits) = e.split_once('/').unwrap_or((e, "128"));
|
||||||
|
let ip: Ipv6Addr = ip.parse().ok()?;
|
||||||
|
let bits: u8 = bits.parse().ok().filter(|b| *b <= 128)?;
|
||||||
|
return Some(Allowed {
|
||||||
|
target: Target::Net(IpAddr::V6(ip), bits),
|
||||||
|
ports: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let (host, ports) = match e.rsplit_once(':') {
|
||||||
|
Some((h, p)) => (h, Some(parse_ports(p)?)),
|
||||||
|
None => (e, None),
|
||||||
|
};
|
||||||
|
if let Some((ip, bits)) = host.split_once('/') {
|
||||||
|
let ip: Ipv4Addr = ip.parse().ok()?;
|
||||||
|
let bits: u8 = bits.parse().ok().filter(|b| *b <= 32)?;
|
||||||
|
return Some(Allowed {
|
||||||
|
target: Target::Net(IpAddr::V4(ip), bits),
|
||||||
|
ports,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Ok(ip) = host.parse::<Ipv4Addr>() {
|
||||||
|
return Some(Allowed {
|
||||||
|
target: Target::Net(IpAddr::V4(ip), 32),
|
||||||
|
ports,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let name = host.to_ascii_lowercase();
|
||||||
|
let plain = |n: &str| {
|
||||||
|
!n.is_empty()
|
||||||
|
&& n.len() <= 253
|
||||||
|
&& n.split('.').all(|l| {
|
||||||
|
!l.is_empty()
|
||||||
|
&& l.len() <= 63
|
||||||
|
&& l.bytes()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
|
||||||
|
})
|
||||||
|
};
|
||||||
|
if let Some(suffix) = name.strip_prefix("*.") {
|
||||||
|
return plain(suffix).then(|| Allowed {
|
||||||
|
target: Target::Suffix(suffix.to_owned()),
|
||||||
|
ports,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
plain(&name).then(|| Allowed {
|
||||||
|
target: Target::Name(name),
|
||||||
|
ports,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn in_net(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
|
||||||
|
match (ip, net) {
|
||||||
|
(IpAddr::V4(a), IpAddr::V4(n)) => {
|
||||||
|
let mask = if bits == 0 {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
u32::MAX << (32 - u32::from(bits))
|
||||||
|
};
|
||||||
|
u32::from(a) & mask == u32::from(n) & mask
|
||||||
|
}
|
||||||
|
(IpAddr::V6(a), IpAddr::V6(n)) => {
|
||||||
|
let mask = if bits == 0 {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
u128::MAX << (128 - u32::from(bits))
|
||||||
|
};
|
||||||
|
u128::from(a) & mask == u128::from(n) & mask
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Addresses no preview may ever use, whatever the allow list says.
|
||||||
|
fn never(ip: IpAddr) -> bool {
|
||||||
|
match ip {
|
||||||
|
IpAddr::V4(v) => {
|
||||||
|
v.is_unspecified() || v.is_link_local() || v.is_multicast() || v.is_broadcast()
|
||||||
|
}
|
||||||
|
IpAddr::V6(v) => {
|
||||||
|
v.is_unspecified()
|
||||||
|
|| v.is_multicast()
|
||||||
|
|| (v.segments()[0] & 0xffc0) == 0xfe80
|
||||||
|
|| v.to_ipv4_mapped().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check the `[previews]` section at start.
|
||||||
|
pub fn check_config(p: &PreviewsConfig, cfg: &Config) -> Result<(), String> {
|
||||||
|
ianitor_core::preview::hostname("p", "main", &p.domain)
|
||||||
|
.map_err(|e| format!("previews.domain: {e}"))?;
|
||||||
|
if !["domi", "letsencrypt"].contains(&p.tls.as_str()) {
|
||||||
|
return Err("previews.tls must be domi or letsencrypt".into());
|
||||||
|
}
|
||||||
|
if !["none", "forward-auth"].contains(&p.auth.as_str()) {
|
||||||
|
return Err("previews.auth must be none or forward-auth".into());
|
||||||
|
}
|
||||||
|
for u in &p.upstreams {
|
||||||
|
if parse_entry(u).is_none() {
|
||||||
|
return Err(format!(
|
||||||
|
"previews.upstreams: {u:?} is not a network (10.0.0.0/8), an address with ports (127.0.0.1:20000-29999) or a name (app.internal, *.svc.internal)"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.min_ttl_secs == 0
|
||||||
|
|| p.min_ttl_secs > p.max_ttl_secs
|
||||||
|
|| !(p.min_ttl_secs..=p.max_ttl_secs).contains(&p.default_ttl_secs)
|
||||||
|
{
|
||||||
|
return Err(
|
||||||
|
"previews: min_ttl_secs ≤ default_ttl_secs ≤ max_ttl_secs, and min_ttl_secs > 0".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !(1..=3600).contains(&p.sweep_secs) || !(1..=10_000).contains(&p.max_previews) {
|
||||||
|
return Err("previews: sweep_secs 1 to 3600, max_previews 1 to 10000".into());
|
||||||
|
}
|
||||||
|
let _ = cfg;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail(status: u16, code: &str, params: Params) -> Fail {
|
||||||
|
Fail::new(status, code, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a preview may send traffic to `upstream`; the parsed URL's host and port.
|
||||||
|
pub fn check_upstream(cfg: &Config, p: &PreviewsConfig, upstream: &str) -> Result<(), Fail> {
|
||||||
|
let bad = || fail(422, "preview.upstream", Params::new());
|
||||||
|
if upstream.is_empty()
|
||||||
|
|| upstream.len() > 512
|
||||||
|
|| !upstream.bytes().all(|c| c.is_ascii_graphic())
|
||||||
|
{
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let u = url::Url::parse(upstream).map_err(|_| bad())?;
|
||||||
|
if !["http", "https"].contains(&u.scheme())
|
||||||
|
|| !u.username().is_empty()
|
||||||
|
|| u.password().is_some()
|
||||||
|
|| u.query().is_some()
|
||||||
|
|| u.fragment().is_some()
|
||||||
|
|| !(u.path().is_empty() || u.path() == "/")
|
||||||
|
{
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let port = u.port_or_known_default().ok_or_else(bad)?;
|
||||||
|
let host = u.host().ok_or_else(bad)?;
|
||||||
|
let shown = || {
|
||||||
|
messages::params([
|
||||||
|
("upstream", upstream.to_owned()),
|
||||||
|
("allowed", {
|
||||||
|
if p.upstreams.is_empty() {
|
||||||
|
"nothing yet (set [previews] upstreams)".to_owned()
|
||||||
|
} else {
|
||||||
|
p.upstreams.join(", ")
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
};
|
||||||
|
let not_allowed = || fail(403, "preview.upstream_not_allowed", shown());
|
||||||
|
let ip = match &host {
|
||||||
|
url::Host::Ipv4(v) => Some(IpAddr::V4(*v)),
|
||||||
|
url::Host::Ipv6(v) => Some(IpAddr::V6(*v)),
|
||||||
|
url::Host::Domain(_) => None,
|
||||||
|
};
|
||||||
|
if let Some(ip) = ip {
|
||||||
|
if never(ip) {
|
||||||
|
return Err(not_allowed());
|
||||||
|
}
|
||||||
|
// This machine's own control API and Caddy admin API, whatever the list says.
|
||||||
|
if ip.is_loopback() {
|
||||||
|
let admin_ports = std::iter::once(cfg.listen.port()).chain(
|
||||||
|
[cfg.compile.caddy_admin, cfg.caddy_compile().caddy_admin]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|a| a.port()),
|
||||||
|
);
|
||||||
|
if admin_ports.into_iter().any(|a| a == port) || port == 2019 {
|
||||||
|
return Err(not_allowed());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let name = match &host {
|
||||||
|
url::Host::Domain(d) => Some(d.to_ascii_lowercase()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let ok = p.upstreams.iter().filter_map(|e| parse_entry(e)).any(|a| {
|
||||||
|
let port_ok = a.ports.is_none_or(|(lo, hi)| (lo..=hi).contains(&port));
|
||||||
|
let host_ok = match (&a.target, ip, &name) {
|
||||||
|
(Target::Net(net, bits), Some(ip), _) => in_net(ip, *net, *bits),
|
||||||
|
(Target::Name(n), _, Some(h)) => n == h,
|
||||||
|
(Target::Suffix(s), _, Some(h)) => h.ends_with(&format!(".{s}")),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
port_ok && host_ok
|
||||||
|
});
|
||||||
|
if ok { Ok(()) } else { Err(not_allowed()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host body of a branch's preview.
|
||||||
|
pub fn spec(
|
||||||
|
p: &PreviewsConfig,
|
||||||
|
hostname: &str,
|
||||||
|
project: &str,
|
||||||
|
branch: &str,
|
||||||
|
upstream: &str,
|
||||||
|
expires_at: u64,
|
||||||
|
) -> HostSpec {
|
||||||
|
HostSpec {
|
||||||
|
hostname: hostname.to_owned(),
|
||||||
|
upstreams: vec![upstream.trim_end_matches('/').to_owned()],
|
||||||
|
tls: p.tls.clone(),
|
||||||
|
auth: p.auth.clone(),
|
||||||
|
websockets: true,
|
||||||
|
share_links: false,
|
||||||
|
device_certs: false,
|
||||||
|
access_log: "off".into(),
|
||||||
|
health_check: None,
|
||||||
|
request_headers: Vec::new(),
|
||||||
|
// A preview is not for search engines.
|
||||||
|
response_headers: vec![HeaderRuleSpec {
|
||||||
|
action: "set".into(),
|
||||||
|
name: "X-Robots-Tag".into(),
|
||||||
|
value: Some("noindex, nofollow".into()),
|
||||||
|
secret: None,
|
||||||
|
}],
|
||||||
|
preview: Some(PreviewSpec {
|
||||||
|
project: project.to_owned(),
|
||||||
|
branch: branch.to_owned(),
|
||||||
|
expires_at: i64::try_from(expires_at).unwrap_or(i64::MAX),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A preview's field problem as an API refusal.
|
||||||
|
pub fn name_fail(e: ianitor_core::preview::PreviewError) -> Fail {
|
||||||
|
use ianitor_core::preview::PreviewError as P;
|
||||||
|
let (code, problem) = match &e {
|
||||||
|
P::Branch(r) => ("preview.branch", (*r).to_owned()),
|
||||||
|
P::Project(r) => ("preview.project", (*r).to_owned()),
|
||||||
|
P::Domain(r) => ("preview.domain", r.clone()),
|
||||||
|
};
|
||||||
|
let mut f = fail(422, code, messages::params([("problem", problem)]));
|
||||||
|
f.reason.field = Some(
|
||||||
|
match e {
|
||||||
|
P::Branch(_) => "branch",
|
||||||
|
P::Project(_) => "project",
|
||||||
|
P::Domain(_) => "domain",
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the previews screen and Fabrica see.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Listed {
|
||||||
|
pub hostname: String,
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
pub upstream: String,
|
||||||
|
pub expires_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Control {
|
||||||
|
pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> {
|
||||||
|
self.cfg
|
||||||
|
.previews
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| fail(409, "preview.off", Params::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every preview at the branch head, by host name.
|
||||||
|
pub fn previews(&self) -> Result<Vec<Listed>, Fail> {
|
||||||
|
let (_, _, model) = self.head_model()?;
|
||||||
|
Ok(model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|h| {
|
||||||
|
let p = h.preview.as_ref()?;
|
||||||
|
Some(Listed {
|
||||||
|
hostname: h.hostname.to_string(),
|
||||||
|
project: p.project.clone(),
|
||||||
|
branch: p.branch.clone(),
|
||||||
|
upstream: h
|
||||||
|
.upstreams
|
||||||
|
.first()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
expires_at: p.expires_at,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open (or move) a branch's preview.
|
||||||
|
pub fn open_preview(
|
||||||
|
&self,
|
||||||
|
project: &str,
|
||||||
|
branch: &str,
|
||||||
|
upstream: &str,
|
||||||
|
ttl: Option<u64>,
|
||||||
|
actor: &str,
|
||||||
|
) -> Result<(String, u64, crate::records::ApplyRecord), Fail> {
|
||||||
|
let p = self.previews_cfg()?;
|
||||||
|
let hostname =
|
||||||
|
ianitor_core::preview::hostname(project, branch, &p.domain).map_err(name_fail)?;
|
||||||
|
let ttl = ttl.unwrap_or(p.default_ttl_secs);
|
||||||
|
if !(p.min_ttl_secs..=p.max_ttl_secs).contains(&ttl) {
|
||||||
|
let mut f = fail(
|
||||||
|
422,
|
||||||
|
"preview.ttl",
|
||||||
|
messages::params([
|
||||||
|
("min", p.min_ttl_secs.to_string()),
|
||||||
|
("max", p.max_ttl_secs.to_string()),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
f.reason.field = Some("ttl".into());
|
||||||
|
return Err(f);
|
||||||
|
}
|
||||||
|
check_upstream(&self.cfg, p, upstream)?;
|
||||||
|
let previews = self.previews()?;
|
||||||
|
let (_, tree, model) = self.head_model()?;
|
||||||
|
let existing = model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.find(|h| h.hostname.as_str() == hostname);
|
||||||
|
let create = match existing {
|
||||||
|
None => {
|
||||||
|
if previews.len() >= p.max_previews {
|
||||||
|
return Err(fail(
|
||||||
|
409,
|
||||||
|
"preview.too_many",
|
||||||
|
messages::params([("max", p.max_previews.to_string())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Some(h) => match &h.preview {
|
||||||
|
Some(pv) if pv.project == project && pv.branch == branch => false,
|
||||||
|
_ => {
|
||||||
|
return Err(fail(
|
||||||
|
409,
|
||||||
|
"preview.taken",
|
||||||
|
messages::params([("hostname", hostname.clone())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
drop(tree);
|
||||||
|
let expires_at = now().saturating_add(ttl);
|
||||||
|
let spec = spec(p, &hostname, project, branch, upstream, expires_at);
|
||||||
|
let summary = format!(
|
||||||
|
"{} the preview of {branch} ({project})",
|
||||||
|
if create { "Opened" } else { "Moved" }
|
||||||
|
);
|
||||||
|
let rec = self.submit_as(Change::Put { spec, create }, None, actor, Some(summary))?;
|
||||||
|
Ok((hostname, expires_at, rec))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a preview by its host name. Only preview hosts.
|
||||||
|
pub fn close_preview(
|
||||||
|
&self,
|
||||||
|
hostname: &str,
|
||||||
|
actor: &str,
|
||||||
|
why: &str,
|
||||||
|
) -> Result<crate::records::ApplyRecord, Fail> {
|
||||||
|
self.previews_cfg()?;
|
||||||
|
let pv = self
|
||||||
|
.previews()?
|
||||||
|
.into_iter()
|
||||||
|
.find(|p| p.hostname == hostname)
|
||||||
|
.ok_or_else(|| fail(404, "preview.not_found", Params::new()))?;
|
||||||
|
let summary = format!("{why} preview of {} ({})", pv.branch, pv.project);
|
||||||
|
self.submit_as(
|
||||||
|
Change::Delete {
|
||||||
|
hostname: hostname.to_owned(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
actor,
|
||||||
|
Some(summary),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a preview stands: `applying`, `live`, `failed` (with why), or not a preview.
|
||||||
|
pub fn preview_state(&self, hostname: &str) -> Option<(String, Option<String>)> {
|
||||||
|
let live = self.previews().ok()?.iter().any(|p| p.hostname == hostname);
|
||||||
|
let last = self
|
||||||
|
.records()
|
||||||
|
.into_iter()
|
||||||
|
.rev()
|
||||||
|
.find(|r| r.hosts.iter().any(|h| h == hostname));
|
||||||
|
let pending = last
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()));
|
||||||
|
if pending {
|
||||||
|
return Some(("applying".into(), None));
|
||||||
|
}
|
||||||
|
if live {
|
||||||
|
return Some(("live".into(), None));
|
||||||
|
}
|
||||||
|
let r = last?;
|
||||||
|
// A preview that never went live because its apply failed.
|
||||||
|
(r.summary.contains("the preview of") && r.state != "kept").then(|| {
|
||||||
|
(
|
||||||
|
"failed".into(),
|
||||||
|
r.reason.as_ref().map(|x| x.message.clone()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close expired previews, every `sweep_secs`.
|
||||||
|
pub async fn preview_sweeper(self: Arc<Self>) {
|
||||||
|
let Some(p) = self.cfg.previews.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(Duration::from_secs(p.sweep_secs)).await;
|
||||||
|
let Ok(list) = self.previews() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let t = now();
|
||||||
|
let busy: Vec<String> = self
|
||||||
|
.records()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()))
|
||||||
|
.flat_map(|r| r.hosts)
|
||||||
|
.collect();
|
||||||
|
for pv in list.iter().filter(|p| p.expires_at <= t) {
|
||||||
|
if busy.contains(&pv.hostname) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match self.close_preview(&pv.hostname, EXPIRY_ACTOR, "Closed the expired") {
|
||||||
|
Ok(_) => {
|
||||||
|
log::info!(target: "ianitor::previews", "the preview {} expired; closing it", pv.hostname)
|
||||||
|
}
|
||||||
|
Err(f) => {
|
||||||
|
log::warn!(target: "ianitor::previews", "cannot close the expired preview {}: {}", pv.hostname, f.reason.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn allow_list_entries_parse() {
|
||||||
|
for ok in [
|
||||||
|
"10.0.0.0/8",
|
||||||
|
"127.0.0.1:20000-29999",
|
||||||
|
"192.168.1.5:8080",
|
||||||
|
"app.internal",
|
||||||
|
"app.internal:3000",
|
||||||
|
"*.svc.internal",
|
||||||
|
"fd00::/8",
|
||||||
|
] {
|
||||||
|
assert!(parse_entry(ok).is_some(), "{ok}");
|
||||||
|
}
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"10.0.0.0/33",
|
||||||
|
"a b",
|
||||||
|
"x:0",
|
||||||
|
"x:9-1",
|
||||||
|
"*.",
|
||||||
|
"http://x",
|
||||||
|
"1.2.3.4/8:70000",
|
||||||
|
] {
|
||||||
|
assert!(parse_entry(bad).is_none(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn networks_match() {
|
||||||
|
let n = |s: &str| s.parse::<IpAddr>().unwrap();
|
||||||
|
assert!(in_net(n("10.1.2.3"), n("10.0.0.0"), 8));
|
||||||
|
assert!(!in_net(n("11.1.2.3"), n("10.0.0.0"), 8));
|
||||||
|
assert!(in_net(n("fd12::1"), n("fd00::"), 8));
|
||||||
|
assert!(in_net(n("1.2.3.4"), n("0.0.0.0"), 0));
|
||||||
|
assert!(never(n("0.0.0.0")) && never(n("169.254.169.254")) && never(n("::ffff:127.0.0.1")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,34 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
|
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
|
||||||
|
|
||||||
|
/// What a token may do. `full` (the default, and every token made before T4) may do
|
||||||
|
/// everything the API offers; `previews` may only use `/api/v1/previews` (Fabrica's branch
|
||||||
|
/// previews), so a leaked preview token can never touch another host.
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum Scope {
|
||||||
|
#[default]
|
||||||
|
Full,
|
||||||
|
Previews,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scope {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Scope::Full => "full",
|
||||||
|
Scope::Previews => "previews",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(s: &str) -> Option<Scope> {
|
||||||
|
match s {
|
||||||
|
"full" => Some(Scope::Full),
|
||||||
|
"previews" => Some(Scope::Previews),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct TokenRecord {
|
pub struct TokenRecord {
|
||||||
@@ -33,6 +61,8 @@ pub struct TokenRecord {
|
|||||||
pub expires_at: Option<u64>,
|
pub expires_at: Option<u64>,
|
||||||
pub last_used_at: Option<u64>,
|
pub last_used_at: Option<u64>,
|
||||||
pub revoked_at: Option<u64>,
|
pub revoked_at: Option<u64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub scope: Scope,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
@@ -117,6 +147,7 @@ impl Tokens {
|
|||||||
&self,
|
&self,
|
||||||
name: &str,
|
name: &str,
|
||||||
expires_at: Option<u64>,
|
expires_at: Option<u64>,
|
||||||
|
scope: Scope,
|
||||||
) -> Result<(TokenRecord, String), String> {
|
) -> Result<(TokenRecord, String), String> {
|
||||||
let _g = self.guard()?;
|
let _g = self.guard()?;
|
||||||
if !valid_name(name) {
|
if !valid_name(name) {
|
||||||
@@ -137,6 +168,7 @@ impl Tokens {
|
|||||||
expires_at,
|
expires_at,
|
||||||
last_used_at: None,
|
last_used_at: None,
|
||||||
revoked_at: None,
|
revoked_at: None,
|
||||||
|
scope,
|
||||||
};
|
};
|
||||||
f.tokens.push(rec.clone());
|
f.tokens.push(rec.clone());
|
||||||
self.save(&f)?;
|
self.save(&f)?;
|
||||||
@@ -231,7 +263,7 @@ mod tests {
|
|||||||
fn create_check_revoke() {
|
fn create_check_revoke() {
|
||||||
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
|
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
|
||||||
let t = Tokens::new(&d);
|
let t = Tokens::new(&d);
|
||||||
let (rec, value) = t.create("laptop", None).unwrap();
|
let (rec, value) = t.create("laptop", None, Scope::Full).unwrap();
|
||||||
assert!(value.starts_with("ian_"));
|
assert!(value.starts_with("ian_"));
|
||||||
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
|
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
|
||||||
assert!(!stored.contains(&value[21..]), "only the hash is stored");
|
assert!(!stored.contains(&value[21..]), "only the hash is stored");
|
||||||
@@ -253,7 +285,7 @@ mod tests {
|
|||||||
t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
|
t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
|
||||||
Refusal::Revoked(_)
|
Refusal::Revoked(_)
|
||||||
));
|
));
|
||||||
let (_, v2) = t.create("old", Some(1)).unwrap();
|
let (_, v2) = t.create("old", Some(1), Scope::Full).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
|
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
|
||||||
Refusal::Expired(1)
|
Refusal::Expired(1)
|
||||||
|
|||||||
@@ -0,0 +1,539 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Branch previews for Fabrica (T4, tests first). `POST /api/v1/previews {project, branch,
|
||||||
|
//! upstream, ttl}` gives the branch the host `<branch>--<project>.<preview domain>`; a token
|
||||||
|
//! scoped to previews may do that and nothing else. These tests run control in this process
|
||||||
|
//! without an edge (applies are kept at once), so they run on Windows too; the end-to-end
|
||||||
|
//! runs through Pingora and Caddy are in tests/diff and scripts/preview-smoke.*.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use ianitor_control::Config;
|
||||||
|
use ianitor_control::tokens::{Scope, Tokens};
|
||||||
|
use ianitor_testkit::more::{JsonResp, tcp_json};
|
||||||
|
use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
const DOMAIN: &str = "pv.example.test";
|
||||||
|
|
||||||
|
struct Ctl {
|
||||||
|
dir: TempDir,
|
||||||
|
api: SocketAddr,
|
||||||
|
admin: String,
|
||||||
|
preview: String,
|
||||||
|
stop: Option<tokio::sync::oneshot::Sender<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Ctl {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(s) = self.stop.take() {
|
||||||
|
let _ = s.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn s(p: &std::path::Path) -> String {
|
||||||
|
p.to_string_lossy().replace('\\', "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ctl {
|
||||||
|
async fn start(extra: &str) -> Ctl {
|
||||||
|
let dir = TempDir::new("pv");
|
||||||
|
for d in ["state", "edge", "caddy", "certs", "creds", "edge-state"] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||||
|
}
|
||||||
|
let api = local(free_port());
|
||||||
|
let text = format!(
|
||||||
|
r#"listen = "{api}"
|
||||||
|
state_dir = "{state}"
|
||||||
|
credentials_dir = "{creds}"
|
||||||
|
|
||||||
|
[routes]
|
||||||
|
repo = "{repo}"
|
||||||
|
|
||||||
|
[edge]
|
||||||
|
config = "{edge}/edge.json"
|
||||||
|
share_revocations = "{edge}/share-revocations.json"
|
||||||
|
|
||||||
|
[caddy]
|
||||||
|
config = "{caddy}/caddy.json"
|
||||||
|
|
||||||
|
[compile]
|
||||||
|
http_listen = "127.0.0.1:{http}"
|
||||||
|
https_listen = "127.0.0.1:{https}"
|
||||||
|
cert_dir = "{certs}"
|
||||||
|
state_dir = "{edge_state}"
|
||||||
|
access_log = "{edge_state}/access.log"
|
||||||
|
caddy_credentials_dir = "{creds}"
|
||||||
|
|
||||||
|
[previews]
|
||||||
|
domain = "{DOMAIN}"
|
||||||
|
tls = "letsencrypt"
|
||||||
|
upstreams = ["10.0.0.0/8", "127.0.0.1:20000-29999", "app.internal"]
|
||||||
|
min_ttl_secs = 1
|
||||||
|
sweep_secs = 1
|
||||||
|
{extra}
|
||||||
|
"#,
|
||||||
|
state = s(&dir.join("state")),
|
||||||
|
creds = s(&dir.join("creds")),
|
||||||
|
repo = s(&dir.join("routes.git")),
|
||||||
|
edge = s(&dir.join("edge")),
|
||||||
|
caddy = s(&dir.join("caddy")),
|
||||||
|
certs = s(&dir.join("certs")),
|
||||||
|
edge_state = s(&dir.join("edge-state")),
|
||||||
|
http = free_port(),
|
||||||
|
https = free_port(),
|
||||||
|
);
|
||||||
|
let path = dir.join("control.toml");
|
||||||
|
std::fs::write(&path, text).unwrap();
|
||||||
|
let cfg = Config::load(&path).unwrap();
|
||||||
|
let tokens = Tokens::new(&dir.join("state"));
|
||||||
|
let (_, admin) = tokens.create("admin", None, Scope::Full).unwrap();
|
||||||
|
let (_, preview) = tokens
|
||||||
|
.create("fabrica previews", None, Scope::Previews)
|
||||||
|
.unwrap();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = ianitor_control::serve(cfg, async {
|
||||||
|
let _ = rx.await;
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
panic!("control stopped: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
wait_for_port(api, Duration::from_secs(20)),
|
||||||
|
"control did not listen"
|
||||||
|
);
|
||||||
|
Ctl {
|
||||||
|
dir,
|
||||||
|
api,
|
||||||
|
admin,
|
||||||
|
preview,
|
||||||
|
stop: Some(tx),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(&self, token: &str, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
let auth = format!("Bearer {token}");
|
||||||
|
tcp_json(
|
||||||
|
self.api,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
&[("Authorization", &auth)],
|
||||||
|
body.as_ref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn admin(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
self.call(&self.admin, method, path, body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fabrica(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
self.call(&self.preview, method, path, body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for an apply to end; returns its final state.
|
||||||
|
async fn settle(&self, apply: &Value) -> String {
|
||||||
|
let id = apply["id"].as_str().expect("an apply id").to_owned();
|
||||||
|
let t = Instant::now();
|
||||||
|
loop {
|
||||||
|
let r = self
|
||||||
|
.admin("GET", &format!("/api/v1/applies/{id}"), None)
|
||||||
|
.await;
|
||||||
|
let state = r.json["state"].as_str().unwrap_or("").to_owned();
|
||||||
|
if ["kept", "reverted", "failed"].contains(&state.as_str()) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
t.elapsed() < Duration::from_secs(30),
|
||||||
|
"apply {id} stuck: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn host_names(&self) -> Vec<String> {
|
||||||
|
let r = self.admin("GET", "/api/v1/hosts", None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
r.json["hosts"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|h| h["hostname"].as_str().unwrap().to_owned())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn add_plain_host(&self, hostname: &str) {
|
||||||
|
let r = self
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(json!({"host": {"hostname": hostname, "upstreams": ["http://10.0.0.9:80"]}})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(self.settle(&r.json["apply"]).await, "kept");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_preview(&self, project: &str, branch: &str, upstream: &str) -> JsonResp {
|
||||||
|
self.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
Some(json!({"project": project, "branch": branch, "upstream": upstream, "ttl": 3600})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_preview_token_cannot_touch_non_preview_hosts() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
c.add_plain_host("www.example.test").await;
|
||||||
|
let www =
|
||||||
|
json!({"host": {"hostname": "www.example.test", "upstreams": ["http://10.6.6.6:80"]}});
|
||||||
|
|
||||||
|
// Everything outside /api/v1/previews is refused, reads included.
|
||||||
|
let refused: Vec<(&str, &str, Option<Value>)> = vec![
|
||||||
|
("GET", "/api/v1/overview", None),
|
||||||
|
("GET", "/api/v1/hosts", None),
|
||||||
|
("GET", "/api/v1/hosts/www.example.test", None),
|
||||||
|
(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(
|
||||||
|
json!({"host": {"hostname": "evil.example.test", "upstreams": ["http://10.6.6.6:80"]}}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("PUT", "/api/v1/hosts/www.example.test", Some(www.clone())),
|
||||||
|
(
|
||||||
|
"PATCH",
|
||||||
|
"/api/v1/hosts/www.example.test",
|
||||||
|
Some(json!({"share_links": true})),
|
||||||
|
),
|
||||||
|
("DELETE", "/api/v1/hosts/www.example.test", None),
|
||||||
|
("POST", "/api/v1/hosts/validate", Some(www["host"].clone())),
|
||||||
|
("POST", "/api/v1/undo", Some(json!({}))),
|
||||||
|
("POST", "/api/v1/restore", Some(json!({"change_id": "x"}))),
|
||||||
|
("GET", "/api/v1/history", None),
|
||||||
|
("GET", "/api/v1/applies", None),
|
||||||
|
("GET", "/api/v1/tokens", None),
|
||||||
|
("POST", "/api/v1/tokens", Some(json!({"name": "escalate"}))),
|
||||||
|
(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts/www.example.test/share-links",
|
||||||
|
Some(json!({})),
|
||||||
|
),
|
||||||
|
("POST", "/api/v1/share-links/stop-all", None),
|
||||||
|
("GET", "/api/v1/certs", None),
|
||||||
|
("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))),
|
||||||
|
("POST", "/api/v1/repo/push", None),
|
||||||
|
("GET", "/api/v1/settings", None),
|
||||||
|
("GET", "/api/v1/team", None),
|
||||||
|
];
|
||||||
|
for (m, p, b) in refused {
|
||||||
|
let r = c.fabrica(m, p, b).await;
|
||||||
|
assert_eq!(r.status, 403, "{m} {p}: {}", r.text);
|
||||||
|
assert_eq!(
|
||||||
|
r.json["error"]["code"], "token.scope",
|
||||||
|
"{m} {p}: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The previews API refuses a host that is not a preview.
|
||||||
|
let r = c
|
||||||
|
.fabrica("DELETE", "/api/v1/previews/www.example.test", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "preview.not_found");
|
||||||
|
let r = c
|
||||||
|
.fabrica("GET", "/api/v1/previews/www.example.test", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
|
||||||
|
// A non-preview host at exactly the name a preview would get is not taken over.
|
||||||
|
let taken = format!("main--shop.{DOMAIN}");
|
||||||
|
c.add_plain_host(&taken).await;
|
||||||
|
let r = c.open_preview("shop", "main", "http://10.0.0.5:8080").await;
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "preview.taken");
|
||||||
|
let r = c
|
||||||
|
.admin("GET", &format!("/api/v1/hosts/{taken}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
r.json["host"]["upstreams"][0], "http://10.0.0.9:80",
|
||||||
|
"{}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
let r = c
|
||||||
|
.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews/close",
|
||||||
|
Some(json!({"project": "shop", "branch": "main"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
|
||||||
|
// A preview the token made touches only its own file, and the list holds only previews.
|
||||||
|
let r = c
|
||||||
|
.open_preview("shop", "fix-1", "http://10.0.0.5:8080")
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let hosts = r.json["apply"]["hosts"].as_array().unwrap().clone();
|
||||||
|
assert_eq!(hosts, vec![json!(format!("fix-1--shop.{DOMAIN}"))]);
|
||||||
|
let r = c.fabrica("GET", "/api/v1/previews", None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let listed: Vec<&str> = r.json["items"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|p| p["hostname"].as_str().unwrap())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(listed, vec![format!("fix-1--shop.{DOMAIN}").as_str()]);
|
||||||
|
let mut names = c.host_names().await;
|
||||||
|
names.sort();
|
||||||
|
assert_eq!(
|
||||||
|
names,
|
||||||
|
vec![
|
||||||
|
format!("fix-1--shop.{DOMAIN}"),
|
||||||
|
taken.clone(),
|
||||||
|
"www.example.test".into()
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// An admin can still kill a preview; the scoped token was never needed for that.
|
||||||
|
let r = c
|
||||||
|
.admin(
|
||||||
|
"DELETE",
|
||||||
|
&format!("/api/v1/previews/fix-1--shop.{DOMAIN}"),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
assert!(
|
||||||
|
!c.host_names()
|
||||||
|
.await
|
||||||
|
.iter()
|
||||||
|
.any(|h| h.starts_with("fix-1--"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_preview_token_cannot_point_a_preview_at_this_machine_s_admin_ports() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
let control_port = c.api.port();
|
||||||
|
for upstream in [
|
||||||
|
// control itself, Caddy's admin API, anything on loopback outside the allowed range
|
||||||
|
format!("http://127.0.0.1:{control_port}"),
|
||||||
|
"http://127.0.0.1:2019".to_owned(),
|
||||||
|
"http://localhost:20001".to_owned(),
|
||||||
|
"http://[::1]:20001".to_owned(),
|
||||||
|
"http://0.0.0.0:20001".to_owned(),
|
||||||
|
"http://169.254.169.254:80".to_owned(),
|
||||||
|
// not in the allow list
|
||||||
|
"http://192.168.1.10:8080".to_owned(),
|
||||||
|
"http://other.internal:8080".to_owned(),
|
||||||
|
// not an upstream at all
|
||||||
|
"http://user:pw@10.0.0.5:8080".to_owned(),
|
||||||
|
"http://10.0.0.5:8080/path".to_owned(),
|
||||||
|
"file:///etc/passwd".to_owned(),
|
||||||
|
"".to_owned(),
|
||||||
|
] {
|
||||||
|
let r = c.open_preview("shop", "main", &upstream).await;
|
||||||
|
assert!(
|
||||||
|
r.status == 422 || r.status == 403,
|
||||||
|
"{upstream}: {} {}",
|
||||||
|
r.status,
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.json["error"]["code"].as_str().is_some_and(
|
||||||
|
|c| c.starts_with("preview.upstream") || c.starts_with("host.upstream")
|
||||||
|
),
|
||||||
|
"{upstream}: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(c.host_names().await.is_empty());
|
||||||
|
// Allowed: the private range, the loopback port range, the listed name.
|
||||||
|
for (b, u) in [
|
||||||
|
("a", "http://10.1.2.3:8080"),
|
||||||
|
("b", "http://127.0.0.1:20001"),
|
||||||
|
("c", "http://app.internal:3000"),
|
||||||
|
] {
|
||||||
|
let r = c.open_preview("shop", b, u).await;
|
||||||
|
assert_eq!(r.status, 202, "{u}: {}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_preview_lives_until_closed_or_expired() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
// Open, with a hostile branch name: the host is safe and the API says where it is.
|
||||||
|
let r = c
|
||||||
|
.open_preview(
|
||||||
|
"github:acme/Web.App",
|
||||||
|
"feature/Ünï ../../etc",
|
||||||
|
"http://10.0.0.5:8080",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
|
||||||
|
assert!(host.ends_with(&format!(".{DOMAIN}")), "{host}");
|
||||||
|
assert!(host.split('.').next().unwrap().contains("--"));
|
||||||
|
assert_eq!(r.json["preview"]["url"], format!("https://{host}/"));
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let r = c
|
||||||
|
.fabrica("GET", &format!("/api/v1/previews/{host}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(r.json["preview"]["branch"], "feature/Ünï ../../etc");
|
||||||
|
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
|
||||||
|
|
||||||
|
// A new deploy of the same branch moves the same host, it does not add one.
|
||||||
|
let r = c
|
||||||
|
.open_preview(
|
||||||
|
"github:acme/Web.App",
|
||||||
|
"feature/Ünï ../../etc",
|
||||||
|
"http://10.0.0.6:8080",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(r.json["preview"]["hostname"], host.as_str());
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let r = c.admin("GET", &format!("/api/v1/hosts/{host}"), None).await;
|
||||||
|
assert_eq!(r.json["host"]["upstreams"][0], "http://10.0.0.6:8080");
|
||||||
|
assert_eq!(c.host_names().await.len(), 1);
|
||||||
|
|
||||||
|
// Closed on merge, by project and branch.
|
||||||
|
let r = c
|
||||||
|
.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews/close",
|
||||||
|
Some(json!({"project": "github:acme/Web.App", "branch": "feature/Ünï ../../etc"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
assert!(c.host_names().await.is_empty());
|
||||||
|
|
||||||
|
// Expired: removed by control by itself.
|
||||||
|
let r = c
|
||||||
|
.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
Some(json!({"project": "shop", "branch": "short", "upstream": "http://10.0.0.5:80", "ttl": 2})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let t = Instant::now();
|
||||||
|
while !c.host_names().await.is_empty() {
|
||||||
|
assert!(
|
||||||
|
t.elapsed() < Duration::from_secs(30),
|
||||||
|
"the expired preview stayed"
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||||
|
}
|
||||||
|
let r = c.admin("GET", "/api/v1/history", None).await;
|
||||||
|
assert!(r.text.contains("expired"), "{}", r.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn bad_preview_requests_are_refused_with_a_reason() {
|
||||||
|
let c = Ctl::start(
|
||||||
|
"max_ttl_secs = 86400
|
||||||
|
default_ttl_secs = 3600",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
for (body, code) in [
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "a\nb", "upstream": "http://10.0.0.5:80"}),
|
||||||
|
"preview.branch",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "", "upstream": "http://10.0.0.5:80"}),
|
||||||
|
"preview.branch",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "sh op", "branch": "main", "upstream": "http://10.0.0.5:80"}),
|
||||||
|
"preview.project",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 0}),
|
||||||
|
"preview.ttl",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 864000}),
|
||||||
|
"preview.ttl",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "auth": "none"}),
|
||||||
|
"request.body_unknown_field",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let r = c
|
||||||
|
.fabrica("POST", "/api/v1/previews", Some(body.clone()))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.json["error"]["code"], code, "{body}: {}", r.text);
|
||||||
|
assert!(r.status == 422 || r.status == 400, "{body}: {}", r.text);
|
||||||
|
}
|
||||||
|
assert!(c.host_names().await.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn without_a_preview_domain_the_api_says_previews_are_off() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
// Replace the config with one that has no [previews] section, then restart.
|
||||||
|
drop(c);
|
||||||
|
let c2 = {
|
||||||
|
let dir = TempDir::new("pv-off");
|
||||||
|
std::fs::create_dir_all(dir.join("state")).unwrap();
|
||||||
|
let api = local(free_port());
|
||||||
|
let text = format!(
|
||||||
|
"listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n",
|
||||||
|
st = s(&dir.join("state")),
|
||||||
|
repo = s(&dir.join("routes.git")),
|
||||||
|
d = s(dir.path()),
|
||||||
|
h = free_port(),
|
||||||
|
hs = free_port(),
|
||||||
|
);
|
||||||
|
std::fs::write(dir.join("control.toml"), text).unwrap();
|
||||||
|
let cfg = Config::load(&dir.join("control.toml")).unwrap();
|
||||||
|
let (_, tok) = Tokens::new(&dir.join("state"))
|
||||||
|
.create("fabrica", None, Scope::Previews)
|
||||||
|
.unwrap();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
tokio::spawn(ianitor_control::serve(cfg, async {
|
||||||
|
let _ = rx.await;
|
||||||
|
}));
|
||||||
|
assert!(wait_for_port(api, Duration::from_secs(20)));
|
||||||
|
(dir, api, tok, tx)
|
||||||
|
};
|
||||||
|
let auth = format!("Bearer {}", c2.2);
|
||||||
|
let r = tcp_json(
|
||||||
|
c2.1,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
&[("Authorization", &auth)],
|
||||||
|
Some(&json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80"})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "preview.off");
|
||||||
|
let _ = c2.3.send(());
|
||||||
|
}
|
||||||
@@ -27,7 +27,11 @@ fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
|
|||||||
let d = TempDir::new("tok-race");
|
let d = TempDir::new("tok-race");
|
||||||
let server = Tokens::new(d.path());
|
let server = Tokens::new(d.path());
|
||||||
let values: Vec<_> = (0..150)
|
let values: Vec<_> = (0..150)
|
||||||
.map(|i| server.create(&format!("t{i}"), None).unwrap())
|
.map(|i| {
|
||||||
|
server
|
||||||
|
.create(&format!("t{i}"), None, Default::default())
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let victim = values[75].0.id.clone();
|
let victim = values[75].0.id.clone();
|
||||||
let mut cli = std::process::Command::new(bin)
|
let mut cli = std::process::Command::new(bin)
|
||||||
@@ -77,7 +81,9 @@ fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
for i in 0..40 {
|
for i in 0..40 {
|
||||||
server.create(&format!("srv{i}"), None).unwrap();
|
server
|
||||||
|
.create(&format!("srv{i}"), None, Default::default())
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
for c in &mut clis {
|
for c in &mut clis {
|
||||||
assert!(c.wait().unwrap().success());
|
assert!(c.wait().unwrap().success());
|
||||||
|
|||||||
@@ -109,9 +109,13 @@ fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders.
|
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. Absolute: `/…` on
|
||||||
|
/// Linux, or a drive path with forward slashes on Windows (`C:/ProgramData/Ianitor/…`, which
|
||||||
|
/// Caddy and Go read as is; control writes backslashes as `/`, see [`windows_path`]).
|
||||||
fn check_path(p: &str) -> Result<(), &'static str> {
|
fn check_path(p: &str) -> Result<(), &'static str> {
|
||||||
if !p.starts_with('/') {
|
let drive =
|
||||||
|
p.len() >= 3 && p.as_bytes()[0].is_ascii_alphabetic() && &p.as_bytes()[1..3] == b":/";
|
||||||
|
if !p.starts_with('/') && !drive {
|
||||||
return Err("it must be an absolute path");
|
return Err("it must be an absolute path");
|
||||||
}
|
}
|
||||||
if p.len() > 1024 {
|
if p.len() > 1024 {
|
||||||
@@ -126,6 +130,19 @@ fn check_path(p: &str) -> Result<(), &'static str> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A Windows path as the compilers take it: `C:\ProgramData\Ianitor` → `C:/ProgramData/Ianitor`.
|
||||||
|
/// Anything that is not a drive path is returned unchanged (and a Linux path with a backslash
|
||||||
|
/// is still refused by the option check).
|
||||||
|
pub fn windows_path(p: &str) -> String {
|
||||||
|
let b = p.as_bytes();
|
||||||
|
if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')
|
||||||
|
{
|
||||||
|
p.replace('\\', "/")
|
||||||
|
} else {
|
||||||
|
p.to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
|
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
|
||||||
/// any other configured copy header (case-insensitive, no duplicates).
|
/// any other configured copy header (case-insensitive, no duplicates).
|
||||||
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
|
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ use ring::rand::{SecureRandom, SystemRandom};
|
|||||||
|
|
||||||
pub use domi_pki::{
|
pub use domi_pki::{
|
||||||
CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair,
|
CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair,
|
||||||
KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem,
|
KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, match_code,
|
||||||
match_code, openssl_sign_command, sha256_hex,
|
openssl_sign_command, sha256_hex,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this.
|
/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this.
|
||||||
|
|||||||
@@ -124,7 +124,11 @@ fn part(shown: &str, original: &str, max: usize, min: usize) -> String {
|
|||||||
cut.pop();
|
cut.pop();
|
||||||
}
|
}
|
||||||
let h = short_hash(original);
|
let h = short_hash(original);
|
||||||
if cut.is_empty() { h } else { format!("{cut}-{h}") }
|
if cut.is_empty() {
|
||||||
|
h
|
||||||
|
} else {
|
||||||
|
format!("{cut}-{h}")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The DNS label of a branch's preview.
|
/// The DNS label of a branch's preview.
|
||||||
|
|||||||
@@ -23,13 +23,22 @@ fn assert_safe_label(l: &str) {
|
|||||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-'),
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-'),
|
||||||
"{l:?} is not lowercase LDH"
|
"{l:?} is not lowercase LDH"
|
||||||
);
|
);
|
||||||
assert!(!l.starts_with('-') && !l.ends_with('-'), "{l:?} has an edge dash");
|
assert!(
|
||||||
assert!(l.get(2..4) != Some("--"), "{l:?} has -- in positions 3 and 4");
|
!l.starts_with('-') && !l.ends_with('-'),
|
||||||
|
"{l:?} has an edge dash"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
l.get(2..4) != Some("--"),
|
||||||
|
"{l:?} has -- in positions 3 and 4"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn plain_names_stay_readable() {
|
fn plain_names_stay_readable() {
|
||||||
assert_eq!(preview::label("mnovak/Arca", "main").unwrap(), "main--arca-4a93cc");
|
assert_eq!(
|
||||||
|
preview::label("mnovak/Arca", "main").unwrap(),
|
||||||
|
"main--arca-4a93cc"
|
||||||
|
);
|
||||||
assert_eq!(preview::label("shop", "fix-42").unwrap(), "fix-42--shop");
|
assert_eq!(preview::label("shop", "fix-42").unwrap(), "fix-42--shop");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
preview::hostname("shop", "fix-42", "preview.example.org").unwrap(),
|
preview::hostname("shop", "fix-42", "preview.example.org").unwrap(),
|
||||||
@@ -107,11 +116,18 @@ fn different_branches_never_share_a_label() {
|
|||||||
// Long branches that differ only after the cut.
|
// Long branches that differ only after the cut.
|
||||||
let a = format!("{}-one", "release".repeat(10));
|
let a = format!("{}-one", "release".repeat(10));
|
||||||
let b = format!("{}-two", "release".repeat(10));
|
let b = format!("{}-two", "release".repeat(10));
|
||||||
assert_ne!(preview::label("p", &a).unwrap(), preview::label("p", &b).unwrap());
|
assert_ne!(
|
||||||
|
preview::label("p", &a).unwrap(),
|
||||||
|
preview::label("p", &b).unwrap()
|
||||||
|
);
|
||||||
// And a broad sweep: many similar names, all distinct.
|
// And a broad sweep: many similar names, all distinct.
|
||||||
let mut seen = BTreeMap::new();
|
let mut seen = BTreeMap::new();
|
||||||
for i in 0..2000 {
|
for i in 0..2000 {
|
||||||
for b in [format!("feature/{i}"), format!("feature-{i}"), format!("Feature/{i}")] {
|
for b in [
|
||||||
|
format!("feature/{i}"),
|
||||||
|
format!("feature-{i}"),
|
||||||
|
format!("Feature/{i}"),
|
||||||
|
] {
|
||||||
let l = preview::label("p", &b).unwrap();
|
let l = preview::label("p", &b).unwrap();
|
||||||
assert_safe_label(&l);
|
assert_safe_label(&l);
|
||||||
if let Some(prev) = seen.insert(l.clone(), b.clone()) {
|
if let Some(prev) = seen.insert(l.clone(), b.clone()) {
|
||||||
@@ -127,21 +143,39 @@ fn same_input_same_label() {
|
|||||||
if b.len() > preview::MAX_BRANCH_BYTES {
|
if b.len() > preview::MAX_BRANCH_BYTES {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
assert_eq!(preview::label("p/q", b).unwrap(), preview::label("p/q", b).unwrap());
|
assert_eq!(
|
||||||
|
preview::label("p/q", b).unwrap(),
|
||||||
|
preview::label("p/q", b).unwrap()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unusable_names_are_refused_not_mangled() {
|
fn unusable_names_are_refused_not_mangled() {
|
||||||
let too_long = "b".repeat(preview::MAX_BRANCH_BYTES + 1);
|
let too_long = "b".repeat(preview::MAX_BRANCH_BYTES + 1);
|
||||||
let bad_branches = ["", "tab\there", "with\nnewline", "nul\0byte", "bell\u{7}", too_long.as_str()];
|
let bad_branches = [
|
||||||
|
"",
|
||||||
|
"tab\there",
|
||||||
|
"with\nnewline",
|
||||||
|
"nul\0byte",
|
||||||
|
"bell\u{7}",
|
||||||
|
too_long.as_str(),
|
||||||
|
];
|
||||||
for b in bad_branches {
|
for b in bad_branches {
|
||||||
assert!(
|
assert!(
|
||||||
matches!(preview::label("p", b), Err(PreviewError::Branch(_))),
|
matches!(preview::label("p", b), Err(PreviewError::Branch(_))),
|
||||||
"{b:?}"
|
"{b:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let bad_projects = ["", "/", "owner/", "has space", "semi;colon", "ü/name", &"p".repeat(129)];
|
let bad_projects = [
|
||||||
|
"",
|
||||||
|
"/",
|
||||||
|
"owner/",
|
||||||
|
"has space",
|
||||||
|
"semi;colon",
|
||||||
|
"ü/name",
|
||||||
|
&"p".repeat(129),
|
||||||
|
];
|
||||||
for p in bad_projects {
|
for p in bad_projects {
|
||||||
assert!(
|
assert!(
|
||||||
matches!(preview::label(p, "main"), Err(PreviewError::Project(_))),
|
matches!(preview::label(p, "main"), Err(PreviewError::Project(_))),
|
||||||
@@ -153,7 +187,7 @@ fn unusable_names_are_refused_not_mangled() {
|
|||||||
preview::hostname("p", "main", "bad domain"),
|
preview::hostname("p", "main", "bad domain"),
|
||||||
Err(PreviewError::Domain(_))
|
Err(PreviewError::Domain(_))
|
||||||
));
|
));
|
||||||
let deep = format!("{}.example.org", "d".repeat(60).repeat(1) + &".d".repeat(90));
|
let deep = format!("{}.example.org", "d".repeat(60) + &".d".repeat(90));
|
||||||
assert!(preview::hostname("p", "main", &deep).is_err());
|
assert!(preview::hostname("p", "main", &deep).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,7 +245,10 @@ fn the_model_carries_the_preview() {
|
|||||||
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
|
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
|
||||||
let m = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
|
let m = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
|
||||||
let p = m.hosts()[0].preview.as_ref().expect("a preview");
|
let p = m.hosts()[0].preview.as_ref().expect("a preview");
|
||||||
assert_eq!((p.project.as_str(), p.branch.as_str(), p.expires_at), ("shop", "fix-42", 1_900_000_000));
|
assert_eq!(
|
||||||
|
(p.project.as_str(), p.branch.as_str(), p.expires_at),
|
||||||
|
("shop", "fix-42", 1_900_000_000)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -220,8 +257,11 @@ fn a_preview_table_must_match_its_host_name() {
|
|||||||
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
|
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
|
||||||
let e = load_one(&host, &preview_file(&host, "shop", "other")).unwrap_err();
|
let e = load_one(&host, &preview_file(&host, "shop", "other")).unwrap_err();
|
||||||
assert!(e.to_string().contains("preview"), "{e}");
|
assert!(e.to_string().contains("preview"), "{e}");
|
||||||
let e = load_one("plain.pv.example.org", &preview_file("plain.pv.example.org", "shop", "fix-42"))
|
let e = load_one(
|
||||||
.unwrap_err();
|
"plain.pv.example.org",
|
||||||
|
&preview_file("plain.pv.example.org", "shop", "fix-42"),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert!(e.to_string().contains("preview"), "{e}");
|
assert!(e.to_string().contains("preview"), "{e}");
|
||||||
// Unknown keys and bad values in the table are refused like everywhere else.
|
// Unknown keys and bad values in the table are refused like everywhere else.
|
||||||
let text = preview_file(&host, "shop", "fix-42").replace("expires_at", "expires");
|
let text = preview_file(&host, "shop", "fix-42").replace("expires_at", "expires");
|
||||||
@@ -237,11 +277,7 @@ fn compilers_ignore_the_preview_table() {
|
|||||||
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
|
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
|
||||||
let with = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
|
let with = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
|
||||||
let text = preview_file(&host, "shop", "fix-42");
|
let text = preview_file(&host, "shop", "fix-42");
|
||||||
let without_text: String = text
|
let without_text: String = text.split("[preview]").next().unwrap().to_owned();
|
||||||
.split("[preview]")
|
|
||||||
.next()
|
|
||||||
.unwrap()
|
|
||||||
.to_owned();
|
|
||||||
let without = load_one(&host, &without_text).unwrap();
|
let without = load_one(&host, &without_text).unwrap();
|
||||||
let o = ianitor_core::compile::CompileOptions {
|
let o = ianitor_core::compile::CompileOptions {
|
||||||
http_listen: "0.0.0.0:80".parse().unwrap(),
|
http_listen: "0.0.0.0:80".parse().unwrap(),
|
||||||
|
|||||||
Reference in New Issue
Block a user