#![forbid(unsafe_code)]
#![cfg(all(feature = "s3", feature = "verify-gpg"))]
mod common;
#[path = "common/pull.rs"]
mod pull;
use std::path::{Path, PathBuf};
use std::process::Command;
use common::TmpDir;
use common::s3::{ACCESS_KEY, Rclone, SECRET_KEY, StandIn, rclone_available};
use ostrya::endpoint::EndpointOverrides;
use ostrya::remote::s3::{Address, Credentials, Location, S3Endpoint};
use ostrya::remote::{Endpoint, PullSession, StreamSessionOptions};
use ostrya::verify::PullTrust;
use ostrya::{
Checksum, CommitState, CreateOptions, Error, Proxy, PullOptions, Repo, RepoMode, SummaryOptions,
};
use ostrya_rt::block_on;
use pull::{FIXED_TS, ID_X, build_tree, commit_bound, commit_tree, commit_tree_related};
const CASE: &str = "OSTRYA_TEST_S3_CASE";
const SCRATCH: &str = "OSTRYA_TEST_S3_SCRATCH";
const ENDPOINT: &str = "OSTRYA_TEST_S3_ENDPOINT";
const PROXY_VARIABLES: [&str; 7] = [
"http_proxy",
"HTTP_PROXY",
"https_proxy",
"HTTPS_PROXY",
"all_proxy",
"ALL_PROXY",
"no_proxy",
];
struct GpgHome {
dir: PathBuf,
}
impl GpgHome {
fn create(dir: PathBuf, uid: &str) -> GpgHome {
use std::os::unix::fs::DirBuilderExt;
std::fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
let home = GpgHome { dir };
let status = home
.gpg()
.args(["--pinentry-mode", "loopback", "--passphrase", ""])
.args(["--quick-gen-key", uid, "ed25519", "sign", "never"])
.status()
.unwrap();
assert!(status.success(), "gpg --quick-gen-key failed");
home
}
fn gpg(&self) -> Command {
let mut cmd = Command::new("gpg");
cmd.arg("--homedir").arg(&self.dir).arg("--batch");
cmd
}
fn fingerprint(&self) -> String {
let out = self
.gpg()
.args(["--with-colons", "--list-keys"])
.output()
.unwrap();
assert!(out.status.success());
let text = String::from_utf8(out.stdout).unwrap();
text.lines()
.find_map(|line| {
let mut fields = line.split(':');
(fields.next() == Some("fpr")).then(|| fields.nth(8).unwrap().to_owned())
})
.expect("a fpr record in the key listing")
}
fn export_to(&self, path: &Path) {
let out = self.gpg().arg("--export").output().unwrap();
assert!(out.status.success() && !out.stdout.is_empty());
std::fs::write(path, out.stdout).unwrap();
}
}
impl Drop for GpgHome {
fn drop(&mut self) {
common::remove_gnupg_sockets(&self.dir);
}
}
fn copy_tree(from: &Path, to: &Path) {
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
let status = Command::new("cp")
.arg("-r")
.arg(from)
.arg(to)
.status()
.unwrap();
assert!(status.success(), "cp -r {}", from.display());
}
const REF: &str = "test/main";
fn fixture_commit() -> Checksum {
Checksum::from_hex(common::COMMIT).unwrap()
}
fn object_names(repo: &Path) -> Vec<String> {
common::file_inventory(repo, "objects")
.into_iter()
.map(|(name, _)| name)
.collect()
}
#[test]
fn the_port_pulls_a_signed_archive_fixture_over_s3() {
let test = "the_port_pulls_a_signed_archive_fixture_over_s3";
if !rclone_available(test) {
return;
}
if !common::ostree_available() {
eprintln!("skipping {test}: ostree is not installed");
return;
}
if !common::gnupg_available(&["gpg"]) {
return;
}
let scratch = TmpDir::new("pull-s3");
let root = scratch.path().join("root");
let repo = root.join("bkt").join("repo");
copy_tree(&common::fixture_repo("archive"), &repo);
common::add_empty_ref_dirs(&repo);
let home = GpgHome::create(scratch.path().join("gnupg"), "S3 Pull <s3@example.com>");
let out = Command::new("ostree")
.arg("summary")
.arg("-u")
.arg(format!("--repo={}", repo.display()))
.arg(format!("--gpg-sign={}", home.fingerprint()))
.arg(format!("--gpg-homedir={}", home.dir.display()))
.output()
.unwrap();
assert!(
out.status.success(),
"ostree summary -u: {}",
String::from_utf8_lossy(&out.stderr)
);
home.export_to(&scratch.path().join("key.gpg"));
let tampered = root.join("tampered").join("repo");
copy_tree(&repo, &tampered);
let mut summary = std::fs::read(tampered.join("summary")).unwrap();
let middle = summary.len() / 2;
summary[middle] ^= 0x01;
std::fs::write(tampered.join("summary"), summary).unwrap();
let server = Rclone::start(scratch.path(), &root);
for (case, secret) in [("pull", SECRET_KEY), ("wrong-secret", "wrong-secret-key")] {
let mut child = Command::new(std::env::current_exe().unwrap());
child
.args(["pull_s3_subprocess", "--exact", "--ignored", "--nocapture"])
.env(CASE, case)
.env(SCRATCH, scratch.path())
.env(ENDPOINT, server.endpoint())
.env("AWS_ACCESS_KEY_ID", ACCESS_KEY)
.env("AWS_SECRET_ACCESS_KEY", secret)
.env("AWS_CONFIG_FILE", scratch.path().join("absent-aws-config"))
.env(
"AWS_SHARED_CREDENTIALS_FILE",
scratch.path().join("absent-aws-credentials"),
);
for (name, _) in std::env::vars_os() {
let text = name.to_string_lossy();
if text.starts_with("AWS_") && !child.get_envs().any(|(set, _)| set == name) {
child.env_remove(&name);
}
}
for name in PROXY_VARIABLES {
child.env_remove(name);
}
let output = child.output().expect("re-execute this test binary");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"the child of the case {case} reported {}:\n{stdout}{}",
output.status,
String::from_utf8_lossy(&output.stderr),
);
}
}
#[test]
#[ignore = "helper process for the_port_pulls_a_signed_archive_fixture_over_s3"]
fn pull_s3_subprocess() {
let Some(case) = std::env::var_os(CASE) else {
return;
};
let scratch = PathBuf::from(std::env::var_os(SCRATCH).unwrap());
let endpoint = std::env::var(ENDPOINT).unwrap();
block_on(async {
match case.to_str().unwrap() {
"pull" => pull_and_verify(&scratch, &endpoint).await,
"wrong-secret" => pull_with_a_wrong_secret(&scratch, &endpoint).await,
other => panic!("unknown case {other}"),
}
});
}
async fn dest(scratch: &Path, name: &str, endpoint: &str) -> (PathBuf, Repo) {
let path = scratch.join(name);
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
drop(repo);
let config = path.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str("min-free-space-percent=0\n");
for (remote, bucket) in [("origin", "bkt"), ("tampered", "tampered")] {
text.push_str(&format!(
"\n[remote \"{remote}\"]\npull-url=s3://{bucket}/repo\ns3-endpoint={endpoint}\n\
gpg-verify=false\ngpg-verify-summary=true\n"
));
}
std::fs::write(&config, text).unwrap();
let repo = Repo::open(&path).await.unwrap();
let keys = std::fs::read(scratch.join("key.gpg")).unwrap();
for remote in ["origin", "tampered"] {
assert_eq!(
repo.gpg_import_keys(remote, &[&keys], &[]).await.unwrap(),
1
);
}
(path, repo)
}
fn options() -> PullOptions {
PullOptions {
refs: vec![REF.to_owned()],
overrides: EndpointOverrides {
allow_cleartext_credentials: true,
..EndpointOverrides::default()
},
..PullOptions::default()
}
}
async fn pull_and_verify(scratch: &Path, endpoint: &str) {
let bucket = scratch.join("root").join("bkt").join("repo");
let (path, repo) = dest(scratch, "dest", endpoint).await;
let stats = repo.pull("origin", options()).await.unwrap();
assert!(stats.bytes_transferred > 0);
assert_eq!(
repo.resolve_rev(&format!("origin:{REF}"), false)
.await
.unwrap(),
Some(fixture_commit())
);
assert_eq!(object_names(&path), object_names(&bucket));
common::tool_fsck(&path);
match repo.pull("tampered", options()).await {
Err(Error::Signature(message)) => assert!(message.contains("summary"), "{message}"),
other => panic!("a pull of a changed summary: {other:?}"),
}
assert_eq!(
repo.resolve_rev(&format!("tampered:{REF}"), true)
.await
.unwrap(),
None
);
}
async fn pull_with_a_wrong_secret(scratch: &Path, endpoint: &str) {
let (path, repo) = dest(scratch, "dest-wrong-secret", endpoint).await;
let error = repo.pull("origin", options()).await.unwrap_err();
let message = error.to_string();
assert!(message.contains("SignatureDoesNotMatch"), "{message}");
assert!(matches!(error, Error::Remote(_)), "{error:?}");
assert!(repo.list_refs(None).await.unwrap().is_empty());
assert!(
repo.list_refs(Some("refs/remotes"))
.await
.unwrap()
.is_empty()
);
assert!(object_names(&path).is_empty());
}
#[test]
fn a_session_to_an_s3_endpoint_pulls_with_the_session() {
if !rclone_available("a_session_to_an_s3_endpoint_pulls_with_the_session") {
return;
}
let scratch = TmpDir::new("pull-s3-session");
let root = scratch.path().join("root");
let bucket = root.join("bkt").join("repo");
copy_tree(&common::fixture_repo("archive"), &bucket);
let server = Rclone::start(scratch.path(), &root);
block_on(async {
let location = Location::new(
Address::parse("s3://bkt/repo").unwrap(),
"us-east-1",
Some(&server.endpoint()),
None,
)
.unwrap();
let credentials = Credentials::new(ACCESS_KEY.into(), SECRET_KEY.into(), None).unwrap();
let mut s3 = S3Endpoint::new(location, credentials);
s3.http.allow_cleartext_credentials = true;
s3.http.proxy = Proxy::None;
let session = PullSession::connect(Endpoint::S3(s3), StreamSessionOptions::default())
.await
.unwrap();
let path = scratch.path().join("dest");
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let opts = PullOptions {
refs: vec![REF.to_owned()],
..PullOptions::default()
};
repo.pull_with_session(session, PullTrust::unverified(), opts)
.await
.unwrap();
assert_eq!(
repo.resolve_rev(REF, false).await.unwrap(),
Some(fixture_commit())
);
assert_eq!(object_names(&path), object_names(&bucket));
});
}
#[test]
fn a_session_to_an_s3_endpoint_fetches_an_attachment() {
if !rclone_available("a_session_to_an_s3_endpoint_fetches_an_attachment") {
return;
}
let scratch = TmpDir::new("pull-s3-dependency");
let root = scratch.path().join("root");
let bucket = root.join("bkt").join("repo");
std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
let (tip, att) = block_on(async {
build_tree(&scratch.path().join("uki"), b"uki\n");
build_tree(&scratch.path().join("main"), b"main\n");
let remote = Repo::create(&bucket, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let att = commit_tree(&remote, scratch.path(), "uki", "dep/uki", None, FIXED_TS).await;
let tip = commit_tree_related(
&remote,
scratch.path(),
"main",
REF,
None,
&[("boot/uki", att)],
)
.await;
remote
.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
(tip, att)
});
let server = Rclone::start(scratch.path(), &root);
block_on(async {
let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
.await
.unwrap();
let path = scratch.path().join("dest");
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let opts = PullOptions {
refs: vec![REF.to_owned()],
..PullOptions::default()
};
repo.pull_with_session(session, PullTrust::unverified(), opts)
.await
.unwrap();
assert_eq!(repo.list_refs(None).await.unwrap(), [(REF.to_owned(), tip)]);
assert!(repo.list_remote_refs().await.unwrap().is_empty());
assert_eq!(repo.commit_state(&att).await.unwrap(), CommitState::Normal);
assert_eq!(object_names(&path), object_names(&bucket));
});
}
#[test]
fn a_session_to_an_s3_endpoint_takes_the_full_set_of_attachments() {
if !rclone_available("a_session_to_an_s3_endpoint_takes_the_full_set_of_attachments") {
return;
}
let scratch = TmpDir::new("pull-s3-attachment-chain");
let root = scratch.path().join("root");
let bucket = root.join("bkt").join("repo");
std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
let chain = block_on(async {
let remote = Repo::create(&bucket, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let chain = common::write_chain(&remote, &scratch.path().join("trees"), REF).await;
remote
.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
chain
});
let server = Rclone::start(scratch.path(), &root);
block_on(async {
let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
.await
.unwrap();
let path = scratch.path().join("dest");
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let opts = PullOptions {
refs: vec![REF.to_owned()],
..PullOptions::default()
};
repo.pull_with_session(session, PullTrust::unverified(), opts)
.await
.unwrap();
assert_eq!(
repo.list_refs(None).await.unwrap(),
[(REF.to_owned(), chain.r)]
);
assert!(repo.list_remote_refs().await.unwrap().is_empty());
for commit in [chain.r, chain.c, chain.d] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
CommitState::Normal
);
}
assert_eq!(object_names(&path), object_names(&bucket));
});
}
async fn build_operand_remote(repo: &Path, base: &Path) -> [Checksum; 3] {
build_tree(&base.join("one"), b"one\n");
build_tree(&base.join("two"), b"two\n");
let remote = Repo::create(repo, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let first = commit_tree(&remote, base, "one", REF, None, FIXED_TS).await;
let second = commit_tree(&remote, base, "two", REF, Some(first), FIXED_TS + 1).await;
let a = commit_bound(
&remote,
base,
"one",
&ostrya::Ref::collection(ID_X, "a"),
Some(ID_X),
)
.await;
remote
.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
[first, second, a]
}
fn operand_options([first, second, a]: [Checksum; 3]) -> PullOptions {
PullOptions {
refs: vec![
second.to_hex(),
format!("{REF}@{first}"),
format!("@{ID_X}:a@{a}"),
],
..PullOptions::default()
}
}
async fn assert_operands_pulled(repo: &Repo, [first, second, a]: [Checksum; 3]) {
assert_eq!(
repo.list_refs(None).await.unwrap(),
[(REF.to_owned(), first)]
);
assert_eq!(
repo.list_mirror_refs().await.unwrap(),
[(ID_X.to_owned(), "a".to_owned(), a)]
);
assert!(repo.list_remote_refs().await.unwrap().is_empty());
for commit in [first, second, a] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
CommitState::Normal
);
}
}
#[test]
fn a_session_to_an_s3_endpoint_takes_commit_operands() {
if !rclone_available("a_session_to_an_s3_endpoint_takes_commit_operands") {
return;
}
let scratch = TmpDir::new("pull-s3-checksum-forms");
let root = scratch.path().join("root");
let bucket = root.join("bkt").join("repo");
std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
let commits = block_on(build_operand_remote(&bucket, scratch.path()));
std::fs::write(bucket.join("summary"), b"not a summary").unwrap();
let server = Rclone::start(scratch.path(), &root);
block_on(async {
let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
.await
.unwrap();
let path = scratch.path().join("dest");
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
repo.pull_with_session(session, PullTrust::unverified(), operand_options(commits))
.await
.unwrap();
assert_operands_pulled(&repo, commits).await;
assert_eq!(object_names(&path), object_names(&bucket));
});
}
#[test]
fn a_pull_of_commit_operands_from_a_bucket_requests_no_summary() {
let scratch = TmpDir::new("pull-s3-checksum-requests");
let source = scratch.path().join("remote");
let commits = block_on(build_operand_remote(&source, scratch.path()));
let server = StandIn::start();
let mut pending = vec![source.clone()];
while let Some(at) = pending.pop() {
for entry in std::fs::read_dir(&at).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
pending.push(path);
} else {
let key = path.strip_prefix(&source).unwrap().to_str().unwrap();
let bytes = std::fs::read(&path).unwrap();
server.state().store(&format!("repo/{key}"), &bytes);
}
}
}
block_on(async {
let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
.await
.unwrap();
let repo = Repo::create(
&scratch.path().join("dest"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
repo.pull_with_session(session, PullTrust::unverified(), operand_options(commits))
.await
.unwrap();
assert_operands_pulled(&repo, commits).await;
});
let requests = server.state().requests.clone();
assert!(
requests
.iter()
.any(|(method, target)| method == "GET" && target == "/bkt/repo/config"),
"{requests:?}"
);
assert!(
!requests
.iter()
.any(|(_, target)| target.contains("summary") || target.contains("/refs/")),
"{requests:?}"
);
}
#[test]
fn a_session_to_an_s3_endpoint_fetches_an_attachment_below_a_held_attachment() {
let name = "a_session_to_an_s3_endpoint_fetches_an_attachment_below_a_held_attachment";
if !rclone_available(name) {
return;
}
let scratch = TmpDir::new("pull-s3-below-held");
let root = scratch.path().join("root");
let bucket = root.join("bkt").join("repo");
std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
let chain = block_on(async {
let remote = Repo::create(&bucket, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let chain = common::write_chain(&remote, &scratch.path().join("trees"), REF).await;
remote
.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
chain
});
let server = Rclone::start(scratch.path(), &root);
block_on(async {
let path = scratch.path().join("dest");
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let pull = || async {
let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
let session =
PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
.await
.unwrap();
let opts = PullOptions {
refs: vec![REF.to_owned()],
..PullOptions::default()
};
repo.pull_with_session(session, PullTrust::unverified(), opts)
.await
.unwrap();
};
pull().await;
let hex = chain.d.to_hex();
let object = path.join(format!("objects/{}/{}.commit", &hex[..2], &hex[2..]));
std::fs::remove_file(&object).unwrap();
assert_eq!(
repo.commit_state(&chain.c).await.unwrap(),
CommitState::Normal
);
pull().await;
assert!(object.exists());
for commit in [chain.r, chain.c, chain.d] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
CommitState::Normal
);
}
assert_eq!(object_names(&path), object_names(&bucket));
});
}
#[test]
fn a_session_to_a_bucket_reads_a_403_as_absent() {
let scratch = TmpDir::new("pull-s3-session-absent");
let source = scratch.path().join("remote");
let server = StandIn::start();
let tip = block_on(async {
build_tree(&scratch.path().join("tree"), b"tree\n");
let remote = Repo::create(&source, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let tip = commit_tree(&remote, scratch.path(), "tree", REF, None, FIXED_TS).await;
remote
.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
tip
});
let mut pending = vec![source.clone()];
while let Some(at) = pending.pop() {
for entry in std::fs::read_dir(&at).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
pending.push(path);
} else {
let key = path.strip_prefix(&source).unwrap().to_str().unwrap();
let bytes = std::fs::read(&path).unwrap();
server.state().store(&format!("repo/{key}"), &bytes);
}
}
}
server.state().forbid_absent = true;
let pull = |name: &'static str| {
let path = scratch.path().join(name);
let url = server.endpoint();
async move {
let endpoint = common::s3::endpoint(&url, "s3://bkt/repo");
let session =
PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
.await
.unwrap();
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let opts = PullOptions {
refs: vec![REF.to_owned()],
..PullOptions::default()
};
let result = repo
.pull_with_session(session, PullTrust::unverified(), opts)
.await;
(repo, result)
}
};
block_on(async {
let (repo, result) = pull("dest").await;
result.unwrap();
assert_eq!(repo.resolve_rev(REF, false).await.unwrap(), Some(tip));
});
assert!(
server
.state()
.requests
.iter()
.any(|(method, target)| method == "GET" && target == "/bkt/repo/summary.sig")
);
server.state().refuse = Some(("GET", "repo/config".to_owned()));
block_on(async {
let (repo, result) = pull("dest-config").await;
let err = result.unwrap_err();
assert!(
matches!(&err, Error::HttpStatus { status: 403, url } if url.ends_with("/repo/config")),
"{err}"
);
assert!(repo.list_refs(None).await.unwrap().is_empty());
});
}