540 lines
19 KiB
Rust
540 lines
19 KiB
Rust
// 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: 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(());
|
|
}
|