use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use ostrya_core::{Checksum, Commit, ObjectType, Ref, RefSelector, Value, is_valid_collection_id};
use crate::endpoint::{EndpointOverrides, local_pull_path, resolve_pull};
use crate::error::{Error, Result};
use crate::fetch::Fetcher;
use crate::refs::{check_ref_path, is_ref_path};
use crate::related::RelatedRule;
use crate::remote::proto::{MAX_REF_ENTRY_LEN, MAX_REF_ENTRY_PARTS, MAX_REF_PATTERNS};
#[cfg(feature = "s3")]
use crate::remote::s3::{Bucket, S3Endpoint};
use crate::remote::{Endpoint, PullSession, StreamSession, StreamSessionOptions};
use crate::repo::Repo;
use crate::send::write_escaped;
use crate::summary::{
COMMIT_TIMESTAMP_KEY, SUMMARY_FILE, Summary, SummaryRef, collection_map_refs, parse_ref_list,
summary_collection_id,
};
use crate::verify::PullTrust;
use crate::verify::trust::FieldGroup;
#[cfg(feature = "s3")]
use super::http::s3_fetcher;
use super::http::{Wanted, connect, session_options};
use super::source::{Connection, RemoteSource};
use super::subpath::Subpaths;
use super::verify::Verification;
use super::{
LocalWanted, Pinned, PullFlags, PullOptions, PullStats, PullVerify, RefPlace, check_depth,
read_checked_local_summary,
};
const LISTING_PATH: &str = "_ostrya/refs/v1";
const MAX_LISTING_TARGET: usize = 16 * 1024;
const LISTING_BUDGET: usize = MAX_LISTING_TARGET - LISTING_PATH.len();
#[derive(Default)]
#[non_exhaustive]
pub struct CollectionPullOptions {
pub pull: PullOptions,
pub on_event: Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
pub allow_unbound: bool,
}
impl fmt::Debug for CollectionPullOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CollectionPullOptions")
.field("pull", &self.pull)
.field("on_event", &self.on_event.as_ref().map(|_| "<callback>"))
.field("allow_unbound", &self.allow_unbound)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CollectionPullEvent {
#[non_exhaustive]
RemoteSkipped {
remote: String,
message: String,
},
#[non_exhaustive]
RefSkipped {
remote: String,
name: String,
},
}
impl fmt::Display for CollectionPullEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CollectionPullEvent::RemoteSkipped { remote, message } => {
f.write_str("remote ")?;
write_escaped(f, remote)?;
f.write_str(" skipped: ")?;
write_escaped(f, message)
}
CollectionPullEvent::RefSkipped { remote, name } => {
f.write_str("remote ")?;
write_escaped(f, remote)?;
f.write_str(" skipped the ref ")?;
write_escaped(f, name)?;
f.write_str(": the name fails the ref-name rule")
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionPullStats {
pub refs: Vec<CollectionPullRef>,
pub stats: PullStats,
pub local: PullStats,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionPullRef {
pub name: String,
pub remote: String,
pub commit: Checksum,
pub timestamp: u64,
}
struct Candidate<'a> {
name: &'a str,
transport: Transport,
trust: PullTrust,
}
enum Transport {
Http(Fetcher),
Ssh(Box<Endpoint>, StreamSessionOptions),
#[cfg(feature = "s3")]
S3(Fetcher, Box<S3Endpoint>),
Local(PathBuf),
}
impl Transport {
async fn new(endpoint: Endpoint, max_outstanding: Option<usize>) -> Result<Transport> {
let (endpoint, stream) = session_options(endpoint, max_outstanding);
Ok(match endpoint {
Endpoint::Http(_) => {
let PullSession::Http(fetcher) = connect(endpoint, stream).await?.session else {
unreachable!("an HTTP endpoint opens an HTTP session");
};
Transport::Http(fetcher)
}
Endpoint::Ssh {
ref address,
ref options,
} => {
StreamSession::check_command_line(address, options)?;
Transport::Ssh(Box::new(endpoint), stream)
}
#[cfg(feature = "s3")]
Endpoint::S3(s3) => Transport::S3(s3_fetcher(&s3, stream).await?, Box::new(s3)),
_ => {
return Err(crate::endpoint::neither_ssh_nor_http(
"a read of collection refs",
));
}
})
}
async fn open(&self) -> Result<Session> {
match self {
Transport::Http(fetcher) => {
Ok(Session::Remote(PullSession::Http(fetcher.clone()).into()))
}
Transport::Ssh(endpoint, stream) => connect(Endpoint::clone(endpoint), stream.clone())
.await
.map(Session::Remote),
#[cfg(feature = "s3")]
Transport::S3(fetcher, s3) => Ok(Session::Remote(Connection {
session: PullSession::Http(fetcher.clone()),
bucket: Some(Bucket::from_fetcher(s3, fetcher.clone())),
})),
Transport::Local(path) => Repo::open(path).await.map(Session::Local),
}
}
}
enum Session {
Remote(Connection),
Local(Repo),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Listed {
pub(crate) name: String,
pub(crate) commit: Checksum,
pub(crate) timestamp: u64,
}
struct Probed {
listed: Vec<Listed>,
skipped: Vec<String>,
summary: Option<Arc<Vec<u8>>>,
session: Session,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ListedRefs {
pub(crate) listed: Vec<Listed>,
skipped: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Selected {
remote: usize,
listed: Listed,
}
impl Repo {
pub async fn pull_collection(
&self,
collection_id: &str,
remotes: &[&str],
opts: CollectionPullOptions,
) -> Result<CollectionPullStats> {
let started = Instant::now();
let CollectionPullOptions {
pull: opts,
mut on_event,
allow_unbound,
} = opts;
let (subpaths, names) = check_collection_pull(collection_id, remotes, &opts)?;
let related = RelatedRule::of(self.config())?;
self.config().generate_composefs()?;
let names = first_of_each(names.iter().map(String::as_str));
let mut candidates = Vec::with_capacity(remotes.len());
let mut group = opts.trust_group.as_deref().map(FieldGroup::new);
for name in first_of_each(remotes.iter().copied()) {
let trust = TrustScope::Pull(group.as_mut());
candidates.push(resolve_candidate(self, name, &opts, trust).await?);
}
if !opts.subpaths.is_empty()
&& let Some(local) = candidates
.iter()
.find(|candidate| matches!(candidate.transport, Transport::Local(_)))
{
return Err(Error::Unsupported(format!(
"the pull address of remote '{}' is a local repository, and a pull of \
collection refs from a local repository takes no subpath",
local.name
)));
}
let found = find_refs(
&candidates,
collection_id,
&names,
|candidate, probed| match probed {
Ok(probed) => report_skipped_refs(&mut on_event, candidate, probed),
Err(e) => {
let Some(on_event) = on_event.as_mut() else {
return;
};
let message = match &candidate.transport {
Transport::Local(path) => {
format!("local repository '{}': {e}", path.display())
}
_ => e.to_string(),
};
on_event(CollectionPullEvent::RemoteSkipped {
remote: candidate.name.to_owned(),
message,
});
}
},
)
.await;
let mut answers = Vec::with_capacity(found.len());
let mut sessions = Vec::with_capacity(found.len());
let mut summaries = Vec::with_capacity(found.len());
for probed in found {
match probed {
Ok(probed) => {
answers.push(Some(probed.listed));
sessions.push(Some(probed.session));
summaries.push(probed.summary);
}
Err(_) => {
answers.push(None);
sessions.push(None);
summaries.push(None);
}
}
}
let selected = match select(collection_id, &names, &answers) {
Ok(selected) => selected,
Err(e) => {
end_sessions(sessions.into_iter().flatten()).await;
return Err(e);
}
};
drop(answers);
let unselected = take_unselected(&mut sessions, &mut summaries, |index| {
selected.iter().any(|s| s.remote == index)
});
end_sessions(unselected).await;
let place = RefPlace::of_collection(self, collection_id);
let candidate_names: Vec<&str> = candidates.iter().map(|c| c.name).collect();
let mut stats = PullStats::default();
let mut local = PullStats::default();
for (index, candidate) in candidates.into_iter().enumerate() {
let Some(session) = sessions[index].take() else {
continue;
};
let from_local = matches!(session, Session::Local(_));
let mine: Vec<&Listed> = selected
.iter()
.filter(|selected| selected.remote == index)
.map(|selected| &selected.listed)
.collect();
let targets: Vec<(String, Checksum)> =
mine.iter().map(|l| (l.name.clone(), l.commit)).collect();
let listed: HashMap<String, u64> =
mine.iter().map(|l| (l.name.clone(), l.timestamp)).collect();
let summary = summaries[index].take();
let run = PullOptions {
refs: targets.iter().map(|(name, _)| name.clone()).collect(),
verify: PullVerify::default(),
trust_group: None,
max_outstanding_fetches: None,
overrides: EndpointOverrides::default(),
..opts.clone()
};
let pinned = Pinned {
targets,
listed,
collection: collection_id,
allow_unbound,
place,
summary: Mutex::new(summary),
};
let pulled = match session {
Session::Remote(connection) => {
self.run_session(
connection,
candidate.trust,
related,
run,
Wanted::Pinned(&pinned),
subpaths.clone(),
None,
Instant::now(),
)
.await
}
Session::Local(src) => {
self.pull_local_candidate(&src, candidate.trust, related, run, &pinned)
.await
}
};
match pulled {
Ok(pulled) => {
add_stats(&mut stats, &pulled);
if from_local {
add_stats(&mut local, &pulled);
local.elapsed += pulled.elapsed;
}
}
Err(e) => {
end_sessions(sessions.into_iter().flatten()).await;
return Err(e);
}
}
}
stats.elapsed = started.elapsed();
let refs = selected
.into_iter()
.map(|selected| CollectionPullRef {
name: selected.listed.name,
remote: candidate_names[selected.remote].to_owned(),
commit: selected.listed.commit,
timestamp: selected.listed.timestamp,
})
.collect();
Ok(CollectionPullStats { refs, stats, local })
}
pub async fn remote_list_collection_refs(
&self,
remote: &str,
collection_id: &str,
names: &[&str],
) -> Result<Vec<(String, Checksum)>> {
self.remote_list_collection_refs_with(
remote,
collection_id,
names,
EndpointOverrides::default(),
None,
)
.await
}
pub async fn remote_list_collection_refs_with(
&self,
remote: &str,
collection_id: &str,
names: &[&str],
overrides: EndpointOverrides,
mut on_event: Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
) -> Result<Vec<(String, Checksum)>> {
check_collection_id(collection_id)?;
check_ref_names(collection_id, names)?;
if overrides.url.is_some() {
return Err(Error::InvalidInput(
"a listing of collection refs reads the address of the remote from the \
config, and takes no url override"
.into(),
));
}
let names = first_of_each(names.iter().copied());
let opts = PullOptions {
overrides,
..PullOptions::default()
};
let candidate = resolve_candidate(self, remote, &opts, TrustScope::Summary).await?;
let Some(found) = find_refs(
std::slice::from_ref(&candidate),
collection_id,
&names,
|candidate, probed| {
if let Ok(probed) = probed {
report_skipped_refs(&mut on_event, candidate, probed);
}
},
)
.await
.pop() else {
unreachable!("the find step gives one result for each candidate");
};
let Probed {
listed, session, ..
} = found?;
if let Session::Remote(connection) = session {
RemoteSource::new(connection, Vec::new())
.finish(Ok(()))
.await?;
}
let mut refs: Vec<(String, Checksum)> = listed
.into_iter()
.map(|listed| (listed.name, listed.commit))
.collect();
refs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
Ok(refs)
}
async fn pull_local_candidate(
&self,
src: &Repo,
trust: PullTrust,
related: RelatedRule,
run: PullOptions,
pinned: &Pinned<'_>,
) -> Result<PullStats> {
let started = Instant::now();
let flags = if trust.checks_signatures() {
run.flags | PullFlags::UNTRUSTED
} else {
run.flags
};
let run = PullOptions { flags, ..run };
self.pull_local_from(
src,
trust,
related,
run,
LocalWanted::Pinned(pinned),
None,
started,
)
.await
}
}
fn first_of_each<'a>(values: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
let mut seen = HashSet::new();
values.filter(|value| seen.insert(*value)).collect()
}
fn take_unselected<S, M>(
sessions: &mut [Option<S>],
summaries: &mut [Option<M>],
selected: impl Fn(usize) -> bool,
) -> Vec<S> {
sessions
.iter_mut()
.zip(summaries.iter_mut())
.enumerate()
.filter(|(index, _)| !selected(*index))
.filter_map(|(_, (session, summary))| {
*summary = None;
session.take()
})
.collect()
}
async fn end_sessions(sessions: impl IntoIterator<Item = Session>) {
for session in sessions {
if let Session::Remote(connection) = session {
let _ = connection.session.finish().await;
}
}
}
enum TrustScope<'g, 'f> {
Pull(Option<&'g mut FieldGroup<'f>>),
Summary,
}
async fn resolve_candidate<'a>(
repo: &Repo,
name: &'a str,
opts: &PullOptions,
trust: TrustScope<'_, '_>,
) -> Result<Candidate<'a>> {
enum Address {
Local(PathBuf),
Endpoint(Box<Endpoint>),
}
let address = match local_pull_path(repo.config(), name, &opts.overrides)? {
Some(path) => Address::Local(path),
None => Address::Endpoint(Box::new(
resolve_pull(Some(repo.config()), name, opts.overrides.clone()).await?,
)),
};
let trust = match trust {
TrustScope::Pull(group) => PullTrust::for_pull(repo, name, &opts.verify, group).await?,
TrustScope::Summary => PullTrust::for_summary(repo, name).await?,
};
let transport = match address {
Address::Local(path) => Transport::Local(path),
Address::Endpoint(endpoint) => {
Transport::new(*endpoint, opts.max_outstanding_fetches).await?
}
};
Ok(Candidate {
name,
transport,
trust,
})
}
fn check_collection_pull(
collection_id: &str,
remotes: &[&str],
opts: &PullOptions,
) -> Result<(Option<Subpaths>, Vec<String>)> {
check_collection_id(collection_id)?;
if remotes.is_empty() {
return Err(Error::InvalidInput(
"a collection pull needs at least one remote".into(),
));
}
let subpaths = Subpaths::parse(&opts.subpaths)?;
check_depth(opts.depth)?;
if opts.remote.is_some() {
return Err(Error::InvalidInput(
"a collection pull writes the refs of the collection, and takes no remote option"
.into(),
));
}
if opts.flags.contains(PullFlags::MIRROR) {
return Err(Error::InvalidInput(
"a collection pull takes no MIRROR flag".into(),
));
}
if opts.flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS) {
return Err(Error::InvalidInput(
"a collection pull checks the bindings of each commit, and takes no \
DISABLE_VERIFY_BINDINGS flag"
.into(),
));
}
if opts.static_deltas.is_some() {
return Err(Error::InvalidInput(
"a collection pull takes no static_deltas list".into(),
));
}
if opts.overrides.url.is_some() {
return Err(Error::InvalidInput(
"a collection pull reads the address of each remote from the config, and takes \
no url override"
.into(),
));
}
let names = collection_names(collection_id, &opts.refs)?;
Ok((subpaths, names))
}
fn collection_names(collection_id: &str, names: &[String]) -> Result<Vec<String>> {
let mut out = Vec::with_capacity(names.len());
for name in names {
if !name.starts_with('@') {
out.push(name.clone());
continue;
}
match name.parse::<Ref>() {
Ok(Ref::Collection { id, name }) if id == collection_id => out.push(name),
Ok(Ref::Collection { .. }) => {
return Err(Error::InvalidInput(format!(
"the ref {name} is not a ref of the collection {collection_id}"
)));
}
_ => return Err(Error::InvalidRefspec(name.clone())),
}
}
check_ref_names(collection_id, &out)?;
Ok(out)
}
fn check_collection_id(collection_id: &str) -> Result<()> {
if !is_valid_collection_id(collection_id) {
return Err(Error::InvalidInput(format!(
"invalid collection id: {collection_id}"
)));
}
Ok(())
}
fn check_ref_names<S: AsRef<str>>(collection_id: &str, names: &[S]) -> Result<()> {
for name in names {
check_ref_path(name.as_ref())?;
}
for name in names {
check_listing_name(collection_id, name.as_ref())?;
}
Ok(())
}
fn check_listing_name(id: &str, name: &str) -> Result<()> {
let entry_len = id.len() + 1 + name.len();
let parts = 1 + name.split('/').count();
if entry_len > MAX_REF_ENTRY_LEN
|| parts > MAX_REF_ENTRY_PARTS
|| name_cost(id, name) > LISTING_BUDGET
{
return Err(Error::InvalidInput(format!(
"the ref name '{name}' is too long for a ref listing request of the collection \
'{id}'"
)));
}
Ok(())
}
fn encoded_len(value: &str) -> usize {
value
.bytes()
.map(|byte| {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
1
} else {
3
}
})
.sum()
}
fn name_cost(id: &str, name: &str) -> usize {
let pattern = "pattern=".len() + encoded_len(name);
let collection = "collection=".len() + encoded_len(id) + encoded_len("/") + encoded_len(name);
pattern + collection + 2
}
async fn probe(candidate: &Candidate<'_>, id: &str, names: &[&str]) -> Result<Probed> {
let connection = match candidate.transport.open().await? {
Session::Remote(connection) => connection,
Session::Local(src) => {
let verification = Verification::from_trust(candidate.trust.clone());
let ListedRefs { listed, skipped } =
probe_local(&src, &verification, id, names).await?;
return Ok(Probed {
listed,
skipped,
summary: None,
session: Session::Local(src),
});
}
};
let http = matches!(connection.session, PullSession::Http(_));
let source = RemoteSource::new(connection, Vec::new());
let verification = Verification::from_trust(candidate.trust.clone());
match probe_source(&source, &verification, id, names, http).await {
Ok((ListedRefs { listed, skipped }, summary)) => Ok(Probed {
listed,
skipped,
summary,
session: Session::Remote(source.into_connection()),
}),
Err(e) => source.finish(Err(e)).await,
}
}
async fn find_refs(
candidates: &[Candidate<'_>],
id: &str,
names: &[&str],
mut on_probed: impl FnMut(&Candidate<'_>, &mut Result<Probed>),
) -> Vec<Result<Probed>> {
let mut found = Vec::with_capacity(candidates.len());
for candidate in candidates {
let mut probed = Box::pin(probe(candidate, id, names)).await;
on_probed(candidate, &mut probed);
found.push(probed);
}
found
}
fn report_skipped_refs(
on_event: &mut Option<Box<dyn FnMut(CollectionPullEvent) + Send>>,
candidate: &Candidate<'_>,
probed: &mut Probed,
) {
let skipped = std::mem::take(&mut probed.skipped);
let Some(on_event) = on_event.as_mut() else {
return;
};
for name in skipped {
on_event(CollectionPullEvent::RefSkipped {
remote: candidate.name.to_owned(),
name,
});
}
}
type Refs = (ListedRefs, Option<Arc<Vec<u8>>>);
async fn probe_local(
src: &Repo,
verification: &Verification,
id: &str,
names: &[&str],
) -> Result<ListedRefs> {
if verification.checks_summary() {
let Some(bytes) = read_checked_local_summary(src, verification, false).await? else {
unreachable!("the summary check needs a summary");
};
let (_, refs) = parse_refs(bytes, id, names).await?;
return Ok(refs);
}
let refs = src
.list_collection_refs_in(id, &RefSelector::parse(names.iter().copied())?)
.await?;
let (refs, invalid): (Vec<_>, Vec<_>) =
refs.into_iter().partition(|(name, _)| is_ref_path(name));
let skipped = invalid.into_iter().map(|(name, _)| name).collect();
let src = src.clone();
let listed = ostrya_rt::unblock(move || {
let mut timestamps: HashMap<Checksum, u64> = HashMap::new();
refs.into_iter()
.map(|(name, commit)| {
let timestamp = match timestamps.entry(commit) {
Entry::Occupied(known) => *known.get(),
Entry::Vacant(slot) => {
let bytes = src.load_object_bytes_blocking(ObjectType::Commit, &commit)?;
*slot.insert(Commit::parse_timestamp(&bytes)?)
}
};
Ok(Listed {
name,
commit,
timestamp,
})
})
.collect::<Result<Vec<Listed>>>()
})
.await?;
Ok(ListedRefs { listed, skipped })
}
async fn probe_source(
source: &RemoteSource,
verification: &Verification,
id: &str,
names: &[&str],
http: bool,
) -> Result<Refs> {
if verification.checks_summary() || source.has_bucket() {
return summary_refs(source, verification, id, names).await;
}
if names.is_empty() {
return every_ref(source, verification, id).await;
}
let mut listed = ListedRefs::default();
for chunk in listing_chunks(id, names, http) {
let refs = RefSelector::parse(chunk.iter().copied())?;
let entries: Vec<String> = chunk.iter().map(|name| format!("{id}/{name}")).collect();
let collections = RefSelector::parse(entries.iter().map(String::as_str))?;
let Some(bytes) = read_listing(source, &refs, Some(&collections)).await? else {
return summary_refs(source, verification, id, names).await;
};
let (_, parsed) = parse_refs(Arc::new(bytes), id, chunk).await?;
listed.listed.extend(parsed.listed);
listed.skipped.extend(parsed.skipped);
}
Ok((listed, None))
}
async fn every_ref(source: &RemoteSource, verification: &Verification, id: &str) -> Result<Refs> {
let no_local = RefSelector::parse(["!**"])?;
let entry = format!("{id}/**");
let collections = RefSelector::parse([entry.as_str()])?;
let Some(bytes) = read_listing(source, &no_local, Some(&collections)).await? else {
return summary_refs(source, verification, id, &[]).await;
};
let (own, listed) = parse_refs(Arc::new(bytes), id, &[]).await?;
if !own {
return Ok((listed, None));
}
let each_local = RefSelector::parse(std::iter::empty())?;
let Some(bytes) = read_listing(source, &each_local, None).await? else {
return summary_refs(source, verification, id, &[]).await;
};
Ok((parse_refs(Arc::new(bytes), id, &[]).await?.1, None))
}
async fn read_listing(
source: &RemoteSource,
refs: &RefSelector,
collections: Option<&RefSelector>,
) -> Result<Option<Vec<u8>>> {
match source.ref_listing(refs, collections).await {
Err(Error::HttpStatus {
status: 400..=499, ..
}) => Ok(None),
other => other,
}
}
async fn summary_refs(
source: &RemoteSource,
verification: &Verification,
id: &str,
names: &[&str],
) -> Result<Refs> {
let summary = if verification.checks_summary() {
let (summary, signature) = source.summary_files().await?;
let summary = summary.map(Arc::new);
verification
.check_summary(summary.as_ref(), signature)
.await?;
summary
} else {
source.read_root(SUMMARY_FILE).await?.map(Arc::new)
};
let Some(bytes) = summary else {
if source.has_bucket() {
return Err(Error::Pull(
"the bucket repository has no summary, and the summary is the one source of \
the refs of a bucket repository"
.into(),
));
}
return Ok((ListedRefs::default(), None));
};
let (_, listed) = parse_refs(Arc::clone(&bytes), id, names).await?;
Ok((listed, Some(bytes)))
}
async fn parse_refs(bytes: Arc<Vec<u8>>, id: &str, names: &[&str]) -> Result<(bool, ListedRefs)> {
let id = id.to_owned();
let wanted: Option<HashSet<String>> =
(!names.is_empty()).then(|| names.iter().map(|name| (*name).to_owned()).collect());
ostrya_rt::unblock(move || collection_refs(&bytes, &id, wanted.as_ref())).await
}
pub(crate) fn collection_refs(
bytes: &[u8],
id: &str,
wanted: Option<&HashSet<String>>,
) -> Result<(bool, ListedRefs)> {
let metadata = Summary::parse_metadata(bytes)?;
let own = summary_collection_id(&metadata) == Some(id);
let entries = if own {
drop(metadata);
parse_ref_list(bytes)?
} else {
collection_map_refs(&metadata, id)?
};
let mut seen = HashSet::new();
let mut out = ListedRefs::default();
for entry in &entries {
if wanted.is_some_and(|wanted| !wanted.contains(&entry.name))
|| !seen.insert(entry.name.as_str())
{
continue;
}
if !is_ref_path(&entry.name) {
out.skipped.push(entry.name.clone());
continue;
}
out.listed.push(Listed {
name: entry.name.clone(),
commit: entry.commit,
timestamp: listed_timestamp(entry)?,
});
}
Ok((own, out))
}
fn listed_timestamp(entry: &SummaryRef) -> Result<u64> {
match entry
.metadata
.dict_get(COMMIT_TIMESTAMP_KEY)
.and_then(Value::as_variant)
{
Some((ty, Value::U64(raw))) if ty.signature() == "t" => Ok(raw.swap_bytes()),
_ => Err(Error::InvalidFormat(format!(
"the ref '{}' is listed with no {COMMIT_TIMESTAMP_KEY} of type t",
entry.name
))),
}
}
fn listing_chunks<'n, 'a>(id: &str, names: &'n [&'a str], http: bool) -> Vec<&'n [&'a str]> {
let mut chunks = Vec::new();
let mut start = 0;
let mut cost = 0;
for (index, name) in names.iter().enumerate() {
let this = if http { name_cost(id, name) } else { 0 };
if index > start
&& (2 * (index - start) >= MAX_REF_PATTERNS || cost + this > LISTING_BUDGET)
{
chunks.push(&names[start..index]);
start = index;
cost = 0;
}
cost += this;
}
if start < names.len() {
chunks.push(&names[start..]);
}
chunks
}
fn select(id: &str, names: &[&str], answers: &[Option<Vec<Listed>>]) -> Result<Vec<Selected>> {
if answers.iter().all(Option::is_none) {
return Err(Error::Pull(format!(
"no remote of collection '{id}' answered"
)));
}
let mut best: HashMap<&str, (usize, &Listed)> = HashMap::new();
for (remote, listed) in answers.iter().enumerate() {
for listed in listed.iter().flatten() {
best.entry(listed.name.as_str())
.and_modify(|current| {
if listed.timestamp > current.1.timestamp {
*current = (remote, listed);
}
})
.or_insert((remote, listed));
}
}
let order: Vec<&str> = if names.is_empty() {
if best.is_empty() {
return Err(Error::Pull(format!(
"no remote lists a ref of collection '{id}'"
)));
}
let mut all: Vec<&str> = best.keys().copied().collect();
all.sort_unstable();
all
} else {
names.to_vec()
};
order
.into_iter()
.map(|name| match best.get(name) {
Some((remote, listed)) => Ok(Selected {
remote: *remote,
listed: (*listed).clone(),
}),
None => Err(Error::Pull(format!(
"no remote of collection '{id}' lists the ref '{name}'"
))),
})
.collect()
}
fn add_stats(total: &mut PullStats, pulled: &PullStats) {
total.metadata_imported += pulled.metadata_imported;
total.content_imported += pulled.content_imported;
total.content_bytes_written += pulled.content_bytes_written;
total.content_bytes_unpacked += pulled.content_bytes_unpacked;
total.metadata_fetched += pulled.metadata_fetched;
total.content_fetched += pulled.content_fetched;
total.delta_parts += pulled.delta_parts;
total.bytes_transferred += pulled.bytes_transferred;
}
const _: fn() = || {
fn assert_send<T: Send>(_: &T) {}
fn assert_send_sync<T: Send + Sync>() {}
let _ = |repo: &Repo| {
assert_send(&repo.pull_collection(
"org.example.Os",
&["origin"],
CollectionPullOptions::default(),
))
};
let _ = |repo: &Repo| {
assert_send(&repo.remote_list_collection_refs("origin", "org.example.Os", &[]))
};
let _ = |repo: &Repo| {
assert_send(&repo.remote_list_collection_refs_with(
"origin",
"org.example.Os",
&[],
EndpointOverrides::default(),
None,
))
};
assert_send_sync::<CollectionPullStats>();
assert_send_sync::<CollectionPullEvent>();
};
#[cfg(test)]
mod tests {
use std::path::Path;
use ostrya_core::{Type, to_bytes};
use super::*;
use crate::fetch::FetcherOptions;
use crate::pull::import_seam;
use crate::summary::COLLECTION_ID_KEY;
#[cfg(feature = "s3")]
#[test]
fn the_transport_of_an_s3_endpoint_sends_no_request() {
use crate::remote::s3::{Address, Credentials, Location, S3Endpoint};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let location = Location::new(
Address::parse("s3://bkt/repo").unwrap(),
"us-east-1",
Some(&url),
None,
)
.unwrap();
let credentials =
Credentials::new("AKIDEXAMPLE".into(), "SECRETEXAMPLE".into(), None).unwrap();
let mut s3 = S3Endpoint::new(location, credentials);
s3.http.allow_cleartext_credentials = true;
s3.http.proxy = crate::fetch::Proxy::None;
ostrya_rt::block_on(async {
let transport = Transport::new(Endpoint::S3(s3), None).await.unwrap();
assert!(matches!(transport, Transport::S3(..)));
let Session::Remote(connection) = transport.open().await.unwrap() else {
panic!("an S3 transport opens a remote session");
};
assert!(matches!(connection.session, PullSession::Http(_)));
assert!(connection.bucket.is_some());
});
assert_eq!(
listener.accept().map(drop).map_err(|e| e.kind()),
Err(std::io::ErrorKind::WouldBlock),
"the transport connects to no server"
);
}
#[cfg(feature = "s3")]
#[test]
fn a_collection_pull_resolves_an_s3_remote() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let dir = std::env::temp_dir().join(format!(
"ostrya-collection-s3-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&dir);
ostrya_rt::block_on(async {
drop(
Repo::create(&dir, crate::CreateOptions::new(crate::RepoMode::Archive))
.await
.unwrap(),
);
let mut config = std::fs::read_to_string(dir.join("config")).unwrap();
config.push_str(&format!(
"\n[remote \"bkt\"]\npull-url=s3://bkt/repo\ns3-endpoint=http://{}\n",
listener.local_addr().unwrap()
));
std::fs::write(dir.join("config"), config).unwrap();
let repo = Repo::open(&dir).await.unwrap();
let mut opts = CollectionPullOptions::default();
opts.pull.refs = vec!["exampleos/stable".to_owned()];
match repo.pull_collection("org.example.Os", &["bkt"], opts).await {
Err(Error::InvalidInput(_)) => {}
Err(e) => panic!("{e:?}"),
Ok(_) => panic!("a collection pull over a refused endpoint"),
}
});
assert_eq!(
listener.accept().map(drop).map_err(|e| e.kind()),
Err(std::io::ErrorKind::WouldBlock),
"the refusal connects to no server"
);
let _ = std::fs::remove_dir_all(&dir);
}
fn csum(byte: u8) -> Checksum {
Checksum::from_bytes([byte; 32])
}
fn listed(name: &str, byte: u8, timestamp: u64) -> Listed {
Listed {
name: name.to_owned(),
commit: csum(byte),
timestamp,
}
}
type TestRefs<'a> = &'a [(&'a str, u8, u64)];
fn ref_value(name: &str, byte: u8, metadata: Value) -> Value {
Value::Tuple(vec![
Value::Str(name.to_owned()),
Value::Tuple(vec![
Value::U64(1),
Value::Bytes(csum(byte).as_bytes().to_vec()),
metadata,
]),
])
}
fn ref_values(refs: TestRefs<'_>) -> Vec<Value> {
refs.iter()
.map(|(name, byte, ts)| {
let timestamp = Value::Tuple(vec![
Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
Value::Variant(Box::new((
Type::parse("t").unwrap(),
Value::U64(ts.swap_bytes()),
))),
]);
ref_value(name, *byte, Value::Array(vec![timestamp]))
})
.collect()
}
fn summary_of(field0: Vec<Value>, map: &[(&str, TestRefs<'_>)], own: Option<&str>) -> Vec<u8> {
let mut metadata = Vec::new();
if !map.is_empty() {
let entries = map
.iter()
.map(|(id, refs)| {
Value::Tuple(vec![
Value::Str((*id).to_owned()),
Value::Array(ref_values(refs)),
])
})
.collect();
metadata.push(Value::Tuple(vec![
Value::Str("ostree.summary.collection-map".to_owned()),
Value::Variant(Box::new((
Type::parse("a{sa(s(taya{sv}))}").unwrap(),
Value::Array(entries),
))),
]));
}
if let Some(own) = own {
metadata.push(Value::Tuple(vec![
Value::Str(COLLECTION_ID_KEY.to_owned()),
Value::Variant(Box::new((
Type::parse("s").unwrap(),
Value::Str(own.to_owned()),
))),
]));
}
let value = Value::Tuple(vec![Value::Array(field0), Value::Array(metadata)]);
to_bytes(&Type::parse("(a(s(taya{sv}))a{sv})").unwrap(), &value).unwrap()
}
fn summary(field0: TestRefs<'_>, map: &[(&str, TestRefs<'_>)], own: Option<&str>) -> Vec<u8> {
summary_of(ref_values(field0), map, own)
}
#[test]
fn the_unselected_remotes_leave_their_sessions_and_summaries() {
let mut sessions = vec![Some('a'), None, Some('c'), Some('d')];
let mut summaries = vec![Some(1), None, Some(3), Some(4)];
let taken = take_unselected(&mut sessions, &mut summaries, |index| index == 2);
assert_eq!(taken, ['a', 'd']);
assert_eq!(sessions, [None, None, Some('c'), None]);
assert_eq!(summaries, [None, None, Some(3), None]);
}
#[test]
fn the_own_collection_reads_field_0() {
let s = summary(
&[("os/stable", 1, 10), ("os/next", 2, 20)],
&[("org.example.Os", &[("os/stable", 9, 99)])],
Some("org.example.Os"),
);
let refs = collection_refs(&s, "org.example.Os", None).unwrap();
assert!(refs.0);
assert_eq!(
refs.1.listed,
[listed("os/stable", 1, 10), listed("os/next", 2, 20)]
);
assert!(refs.1.skipped.is_empty());
}
#[test]
fn another_collection_reads_the_map_and_ignores_field_0() {
let s = summary(
&[("os/stable", 1, 10)],
&[
("org.example.Other", &[("os/stable", 7, 70)]),
(
"org.example.Os",
&[("os/stable", 3, 30), ("os/next", 4, 40)],
),
],
Some("org.example.Mine"),
);
let wanted: HashSet<String> = ["os/stable".to_owned()].into();
let refs = collection_refs(&s, "org.example.Os", Some(&wanted)).unwrap();
assert_eq!(
refs,
(
false,
ListedRefs {
listed: vec![listed("os/stable", 3, 30)],
skipped: Vec::new(),
}
)
);
let s = summary(&[("os/stable", 1, 10)], &[], None);
assert_eq!(
collection_refs(&s, "org.example.Os", None).unwrap(),
(false, ListedRefs::default())
);
}
#[test]
fn a_ref_with_no_valid_timestamp_fails() {
let no_key = summary_of(
vec![ref_value("os/stable", 1, Value::Array(Vec::new()))],
&[],
Some("org.example.Os"),
);
let other_type = summary_of(
vec![ref_value(
"os/stable",
1,
Value::Array(vec![Value::Tuple(vec![
Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
Value::Variant(Box::new((Type::parse("u").unwrap(), Value::U32(1)))),
])]),
)],
&[],
Some("org.example.Os"),
);
for s in [no_key, other_type] {
assert!(matches!(
collection_refs(&s, "org.example.Os", None),
Err(Error::InvalidFormat(_))
));
}
}
#[test]
fn a_name_that_fails_the_ref_name_rule_is_skipped() {
let mut field0 = ref_values(&[
("origin:main", 1, 10),
("os/stable", 2, 20),
("origin:main", 3, 30),
]);
field0.push(ref_value("bad name", 4, Value::Array(Vec::new())));
let own = summary_of(field0, &[], Some("org.example.Os"));
let expected = ListedRefs {
listed: vec![listed("os/stable", 2, 20)],
skipped: vec!["origin:main".to_owned(), "bad name".to_owned()],
};
assert_eq!(
collection_refs(&own, "org.example.Os", None).unwrap(),
(true, expected)
);
let map = summary(
&[],
&[("org.example.Os", &[("os/next", 5, 50), ("a/../b", 6, 60)])],
None,
);
let expected = ListedRefs {
listed: vec![listed("os/next", 5, 50)],
skipped: vec!["a/../b".to_owned()],
};
assert_eq!(
collection_refs(&map, "org.example.Os", None).unwrap(),
(false, expected)
);
}
#[test]
fn the_newest_commit_wins_and_a_tie_goes_to_the_earlier_remote() {
let answers = vec![
Some(vec![listed("a", 1, 10), listed("b", 2, 20)]),
None,
Some(vec![listed("a", 3, 30), listed("b", 4, 20)]),
];
let selected = select("org.example.Os", &["b", "a"], &answers).unwrap();
assert_eq!(
selected,
[
Selected {
remote: 0,
listed: listed("b", 2, 20)
},
Selected {
remote: 2,
listed: listed("a", 3, 30)
},
]
);
}
#[test]
fn selection_takes_each_listed_ref_or_fails_a_missing_one() {
let answers = vec![
Some(vec![listed("b", 2, 20)]),
Some(vec![listed("a", 1, 10)]),
];
let names: Vec<String> = select("org.example.Os", &[], &answers)
.unwrap()
.into_iter()
.map(|s| s.listed.name)
.collect();
assert_eq!(names, ["a", "b"]);
let err = select("org.example.Os", &["c"], &answers).unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("'c'") && m.contains("org.example.Os")),
"{err:?}"
);
let err = select("org.example.Os", &["a"], &[None, None]).unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err:?}");
let err = select("org.example.Os", &[], &[Some(Vec::new()), None]).unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m == "no remote lists a ref of collection 'org.example.Os'"),
"{err:?}"
);
}
#[test]
fn the_names_split_by_the_entry_limit_and_the_byte_budget() {
let short: Vec<String> = (0..300).map(|n| format!("r{n}")).collect();
let short: Vec<&str> = short.iter().map(String::as_str).collect();
for http in [true, false] {
let chunks = listing_chunks("org.example.Os", &short, http);
assert_eq!(
chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
[
MAX_REF_PATTERNS / 2,
MAX_REF_PATTERNS / 2,
300 - MAX_REF_PATTERNS
]
);
}
let long = "x".repeat(4000);
let names = [long.as_str(), long.as_str(), long.as_str(), "a"];
let chunks = listing_chunks("org.example.Os", &names, true);
assert_eq!(chunks.iter().map(|c| c.len()).collect::<Vec<_>>(), [2, 2]);
assert_eq!(listing_chunks("org.example.Os", &names, false).len(), 1);
assert!(listing_chunks("org.example.Os", &[], true).is_empty());
}
#[test]
fn the_byte_budget_matches_the_request_target_of_the_client() {
ostrya_rt::block_on(async {
let id = "org.example.Oss";
let mut opts = FetcherOptions::new("http://127.0.0.1:1/");
opts.max_retries = 0;
let session = PullSession::Http(Fetcher::new(opts).await.unwrap());
let fetch = |names: Vec<String>| {
let session = &session;
async move {
let refs = RefSelector::parse(names.iter().map(String::as_str)).unwrap();
let entries: Vec<String> =
names.iter().map(|name| format!("{id}/{name}")).collect();
let collections =
RefSelector::parse(entries.iter().map(String::as_str)).unwrap();
session.fetch_refs(&refs, Some(&collections)).await
}
};
let fill = |last: usize| -> Vec<String> {
let mut names: Vec<String> =
(0..4).map(|n| format!("{n}{}", "x".repeat(1616))).collect();
names.push("y".repeat(last));
names
};
let exact = fill(1619);
let cost: usize = exact.iter().map(|name| name_cost(id, name)).sum();
assert_eq!(cost, LISTING_BUDGET);
let names: Vec<&str> = exact.iter().map(String::as_str).collect();
assert_eq!(listing_chunks(id, &names, true).len(), 1);
let sent = fetch(exact.clone()).await;
assert!(
!matches!(sent, Err(crate::remote::Error::InvalidInput(_))),
"{sent:?}"
);
let over = fill(1620);
let names: Vec<&str> = over.iter().map(String::as_str).collect();
assert_eq!(listing_chunks(id, &names, true).len(), 2);
let refused = fetch(over.clone()).await;
assert!(
matches!(refused, Err(crate::remote::Error::InvalidInput(_))),
"{refused:?}"
);
});
}
#[test]
fn a_name_that_no_listing_request_can_hold_is_refused() {
let id = "org.example.Os";
let at_len = "x".repeat(MAX_REF_ENTRY_LEN - id.len() - 1);
let over_len = format!("{at_len}x");
let at_parts = vec!["p"; MAX_REF_ENTRY_PARTS - 1].join("/");
let over_parts = format!("{at_parts}/p");
let wide = "é".repeat(2000);
assert!(id.len() + 1 + wide.len() <= MAX_REF_ENTRY_LEN);
for name in [&at_len, &at_parts] {
check_listing_name(id, name).unwrap();
}
for name in [&over_len, &over_parts, &wide] {
let err = check_listing_name(id, name).unwrap_err();
assert!(
matches!(&err, Error::InvalidInput(m) if m.contains("too long")),
"{err:?}"
);
}
}
#[test]
fn the_skip_event_escapes_control_characters() {
let event = CollectionPullEvent::RemoteSkipped {
remote: "mirror".to_owned(),
message: "bad\nline".to_owned(),
};
assert_eq!(event.to_string(), "remote mirror skipped: bad\\nline");
}
#[test]
fn the_ref_skip_event_escapes_control_characters() {
let event = CollectionPullEvent::RefSkipped {
remote: "mir\tror".to_owned(),
name: "origin:main\n".to_owned(),
};
assert_eq!(
event.to_string(),
"remote mir\\tror skipped the ref origin:main\\n: the name fails the ref-name rule"
);
}
const LOCAL_ID: &str = "org.example.Os";
const SECRET_B64: &str =
"o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
fn ed25519_keys() -> crate::verify::TrustedKeys {
use crate::sign::{Ed25519Verifier, Verifier};
let verifier = Ed25519Verifier::new(
[ostrya_core::base64::decode(PUBLIC_B64).unwrap()],
Vec::<Vec<u8>>::new(),
)
.unwrap();
crate::verify::TrustedKeys::new(vec![Arc::new(verifier) as Arc<dyn Verifier>]).unwrap()
}
fn ed25519_signer() -> crate::sign::Ed25519Signer {
crate::sign::Ed25519Signer::from_base64(SECRET_B64).unwrap()
}
struct Scratch {
root: PathBuf,
}
impl Scratch {
fn new() -> Scratch {
let root = std::env::temp_dir().join(format!(
"ostrya-collection-local-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
Scratch { root }
}
async fn create(&self, name: &str) -> Repo {
let mode = crate::CreateOptions::new(crate::RepoMode::Archive);
Repo::create(&self.root.join(name), mode).await.unwrap()
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
async fn local_commit(
repo: &Repo,
names: &[&str],
parent: Option<Checksum>,
timestamp: u64,
content: &[u8],
) -> Checksum {
let options = crate::commit::CommitOptions {
parent,
timestamp: Some(timestamp),
..crate::commit::CommitOptions::default()
};
local_commit_with(repo, names, options, content).await
}
async fn local_commit_with(
repo: &Repo,
names: &[&str],
options: crate::commit::CommitOptions,
content: &[u8],
) -> Checksum {
let txn = repo.transaction().await.unwrap();
let dirmeta = ostrya_core::DirMeta {
uid: 0,
gid: 0,
mode: 0o40755,
xattrs: Default::default(),
};
let dirmeta = txn
.write_metadata(ObjectType::DirMeta, None, &dirmeta.serialize().unwrap())
.await
.unwrap();
let file = txn
.write_regfile_inline(None, &crate::write::FileMeta::regular(0, 0, 0o644), content)
.await
.unwrap();
let mut mtree = crate::mtree::MutableTree::new();
mtree.set_metadata_checksum(dirmeta);
mtree.replace_file("f", file).unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn.write_commit(options, &root).await.unwrap();
txn.commit().await.unwrap();
for name in names {
let cref = crate::Ref::collection(LOCAL_ID, *name);
repo.set_ref_immediate(&cref, Some(&commit)).await.unwrap();
}
commit
}
async fn probe_and_pull(
dst: &Repo,
src: &Repo,
trust: PullTrust,
names: &[&str],
flags: PullFlags,
depth: i32,
) -> Result<PullStats> {
let verification = Verification::from_trust(trust.clone());
let listed = probe_local(src, &verification, LOCAL_ID, names)
.await?
.listed;
let run = PullOptions {
refs: listed.iter().map(|l| l.name.clone()).collect(),
flags,
depth,
..PullOptions::default()
};
let pinned = pinned_of(dst, &listed);
let related = RelatedRule::of(dst.config()).unwrap();
dst.pull_local_candidate(src, trust, related, run, &pinned)
.await
}
fn pinned_of<'a>(dst: &Repo, listed: &[Listed]) -> Pinned<'a> {
Pinned {
targets: listed.iter().map(|l| (l.name.clone(), l.commit)).collect(),
listed: listed
.iter()
.map(|l| (l.name.clone(), l.timestamp))
.collect(),
collection: LOCAL_ID,
allow_unbound: true,
place: RefPlace::of_collection(dst, LOCAL_ID),
summary: Mutex::new(None),
}
}
fn object_file(dir: &Path, checksum: &Checksum, ty: ObjectType) -> PathBuf {
dir.join("objects").join(ostrya_core::loose_path(
checksum,
ty,
crate::RepoMode::Archive,
))
}
fn replace_object_file(dir: &Path, ty: ObjectType, to: &Checksum, from: &Checksum) {
let _ = std::fs::remove_file(object_file(dir, to, ty));
std::fs::copy(object_file(dir, from, ty), object_file(dir, to, ty)).unwrap();
}
fn replace_commit_file(dir: &Path, to: &Checksum, from: &Checksum) {
replace_object_file(dir, ObjectType::Commit, to, from);
}
fn restore_object_file(
dir: &Path,
checksum: &Checksum,
ty: ObjectType,
) -> impl FnOnce() + Send + 'static {
let path = object_file(dir, checksum, ty);
let bytes = std::fs::read(&path).unwrap();
move || {
std::fs::remove_file(&path).unwrap();
std::fs::write(&path, bytes).unwrap();
}
}
async fn assert_nothing_written(dst: &Repo, dir: &Path) {
let objects = dst.list_objects().await.unwrap();
assert!(objects.is_empty(), "{objects:?}");
let leftovers: Vec<String> = ["state", "tmp"]
.into_iter()
.flat_map(|sub| std::fs::read_dir(dir.join(sub)).unwrap())
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.ends_with(".commitpartial") || name.starts_with("staging-"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
let refs = dst
.list_collection_refs_in(LOCAL_ID, &RefSelector::parse(std::iter::empty()).unwrap())
.await
.unwrap();
assert!(refs.is_empty(), "{refs:?}");
}
#[test]
fn the_local_probe_reads_the_timestamp_of_each_tip_commit() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let one = local_commit(&src, &["os/a", "os/b"], None, 1_700_000_001, b"one").await;
let two = local_commit(&src, &["os/c"], None, 1_700_000_002, b"two").await;
let unverified = Verification::from_trust(PullTrust::unverified());
let listed = probe_local(&src, &unverified, LOCAL_ID, &[])
.await
.unwrap()
.listed;
assert_eq!(listed.len(), 3);
let timestamps: HashMap<Checksum, u64> =
listed.iter().map(|l| (l.commit, l.timestamp)).collect();
assert_eq!(timestamps.len(), 2);
assert_eq!(timestamps[&one], 1_700_000_001);
assert_eq!(timestamps[&two], 1_700_000_002);
src.regenerate_summary(&crate::SummaryOptions::default())
.await
.unwrap();
src.sign_summary(&ed25519_signer()).await.unwrap();
let policy =
Verification::from_trust(PullTrust::unverified().with_summary(ed25519_keys()));
let mut from_summary = probe_local(&src, &policy, LOCAL_ID, &[])
.await
.unwrap()
.listed;
let mut expected = listed;
from_summary.sort_unstable_by(|a, b| a.name.cmp(&b.name));
expected.sort_unstable_by(|a, b| a.name.cmp(&b.name));
assert_eq!(from_summary, expected);
});
}
#[test]
fn a_local_candidate_reads_and_checks_the_summary_again() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let tip = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
src.generate_static_delta(None, &tip, &crate::DeltaOptions::default())
.await
.unwrap();
src.regenerate_summary(&crate::SummaryOptions::default())
.await
.unwrap();
src.sign_summary(&ed25519_signer()).await.unwrap();
let trust = PullTrust::unverified().with_summary(ed25519_keys());
let verification = Verification::from_trust(trust.clone());
let listed = probe_local(&src, &verification, LOCAL_ID, &["os/a"])
.await
.unwrap()
.listed;
let run = PullOptions {
refs: vec!["os/a".to_owned()],
require_static_deltas: true,
..PullOptions::default()
};
let dst = scratch.create("dst").await;
let pinned = pinned_of(&dst, &listed);
let related = RelatedRule::of(dst.config()).unwrap();
let stats = dst
.pull_local_candidate(&src, trust.clone(), related, run.clone(), &pinned)
.await
.unwrap();
assert!(stats.delta_parts > 0, "{stats:?}");
let cref = crate::Ref::collection(LOCAL_ID, "os/a");
assert_eq!(dst.resolve_ref_tip(&cref).await.unwrap(), Some(tip));
std::fs::remove_file(scratch.root.join("src").join("summary.sig")).unwrap();
let plain = PullOptions {
refs: vec!["os/a".to_owned()],
..PullOptions::default()
};
for (name, run) in [("unsigned", run), ("unsigned-plain", plain)] {
let dst = scratch.create(name).await;
let pinned = pinned_of(&dst, &listed);
let related = RelatedRule::of(dst.config()).unwrap();
let pulled = dst
.pull_local_candidate(&src, trust.clone(), related, run, &pinned)
.await;
assert!(
matches!(pulled, Err(Error::Signature(_))),
"{name}: {pulled:?}"
);
assert_nothing_written(&dst, &scratch.root.join(name)).await;
}
});
}
#[test]
fn a_selected_tip_that_is_a_parent_of_another_is_pulled_in_each_order() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
for (at, (child_ref, parent_ref)) in
[("os/a", "os/b"), ("os/b", "os/a")].into_iter().enumerate()
{
let src = scratch.create(&format!("src{at}")).await;
let parent = local_commit(&src, &[parent_ref], None, 1_700_000_001, b"one").await;
let child =
local_commit(&src, &[child_ref], Some(parent), 1_700_000_002, b"two").await;
let dst = scratch.create(&format!("dst{at}")).await;
let src = Repo::open(&scratch.root.join(format!("src{at}")))
.await
.unwrap();
probe_and_pull(
&dst,
&src,
PullTrust::unverified(),
&["os/a", "os/b"],
PullFlags::NONE,
1,
)
.await
.unwrap();
for (name, commit) in [(child_ref, child), (parent_ref, parent)] {
let cref = crate::Ref::collection(LOCAL_ID, name);
assert_eq!(dst.resolve_ref_tip(&cref).await.unwrap(), Some(commit));
}
}
});
}
#[test]
fn a_commit_that_does_not_hash_to_its_name_fails_an_untrusted_pull() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let one = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
let two = local_commit(&src, &[], None, 1_700_000_001, b"two").await;
replace_commit_file(&scratch.root.join("src"), &one, &two);
let dst = scratch.create("dst").await;
let pulled = probe_and_pull(
&dst,
&src,
PullTrust::unverified(),
&["os/a"],
PullFlags::UNTRUSTED,
0,
)
.await;
match pulled {
Err(Error::ChecksumMismatch { expected, actual }) => {
assert_eq!((expected, actual), (one, two));
}
other => panic!("{other:?}"),
}
assert_nothing_written(&dst, &scratch.root.join("dst")).await;
});
}
#[test]
fn a_tip_commit_that_changes_after_the_probe_fails_the_listed_check() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let one = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
let two = local_commit(&src, &[], None, 1_700_000_002, b"two").await;
let unverified = Verification::from_trust(PullTrust::unverified());
let listed = probe_local(&src, &unverified, LOCAL_ID, &["os/a"])
.await
.unwrap()
.listed;
assert_eq!(
listed,
[Listed {
name: "os/a".to_owned(),
commit: one,
timestamp: 1_700_000_001,
}]
);
replace_commit_file(&scratch.root.join("src"), &one, &two);
for (at, flags) in [PullFlags::NONE, PullFlags::UNTRUSTED]
.into_iter()
.enumerate()
{
let name = format!("dst{at}");
let dst = scratch.create(&name).await;
let run = PullOptions {
refs: vec!["os/a".to_owned()],
flags,
..PullOptions::default()
};
let pinned = pinned_of(&dst, &listed);
let related = RelatedRule::of(dst.config()).unwrap();
let pulled = dst
.pull_local_candidate(&src, PullTrust::unverified(), related, run, &pinned)
.await;
match pulled {
Err(Error::Pull(message)) if flags == PullFlags::NONE => {
assert!(message.contains("timestamp"), "case {at}: {message}");
}
Err(Error::ChecksumMismatch { expected, actual })
if flags == PullFlags::UNTRUSTED =>
{
assert_eq!((expected, actual), (one, two), "case {at}");
}
other => panic!("case {at}: {other:?}"),
}
assert_nothing_written(&dst, &scratch.root.join(&name)).await;
}
});
}
#[test]
fn each_ref_that_names_one_tip_gets_the_listed_check() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let names = ["os/a", "os/b"];
let tip = local_commit(&src, &names, None, 1_700_000_001, b"one").await;
let unverified = Verification::from_trust(PullTrust::unverified());
let listed = probe_local(&src, &unverified, LOCAL_ID, &names)
.await
.unwrap()
.listed;
let run = PullOptions {
refs: names.map(str::to_owned).to_vec(),
..PullOptions::default()
};
for (at, wrong) in names.into_iter().enumerate() {
let dir = format!("wrong{at}");
let dst = scratch.create(&dir).await;
let mut pinned = pinned_of(&dst, &listed);
pinned.listed.insert(wrong.to_owned(), 1_700_000_002);
let related = RelatedRule::of(dst.config()).unwrap();
let pulled = dst
.pull_local_candidate(
&src,
PullTrust::unverified(),
related,
run.clone(),
&pinned,
)
.await;
match pulled {
Err(Error::Pull(message)) => {
assert!(message.contains(&format!("'{wrong}'")), "{message}");
}
other => panic!("{wrong}: {other:?}"),
}
assert_nothing_written(&dst, &scratch.root.join(&dir)).await;
}
let dst = scratch.create("dst").await;
let pinned = pinned_of(&dst, &listed);
let related = RelatedRule::of(dst.config()).unwrap();
dst.pull_local_candidate(&src, PullTrust::unverified(), related, run, &pinned)
.await
.unwrap();
for name in names {
let cref = crate::Ref::collection(LOCAL_ID, name);
assert_eq!(dst.resolve_ref_tip(&cref).await.unwrap(), Some(tip));
}
});
}
#[test]
fn a_commit_that_changes_after_its_signature_check_fails_the_pull() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let signed = local_commit(&src, &[], None, 1_700_000_001, b"one").await;
src.sign_commit(&signed, &ed25519_signer()).await.unwrap();
let unsigned = local_commit(&src, &["os/a"], None, 1_700_000_001, b"two").await;
let src_dir = scratch.root.join("src");
replace_object_file(&src_dir, ObjectType::CommitMeta, &unsigned, &signed);
let restore = restore_object_file(&src_dir, &unsigned, ObjectType::Commit);
replace_commit_file(&src_dir, &unsigned, &signed);
let dst = scratch.create("dst").await;
let dst_dir = scratch.root.join("dst");
import_seam::arm(&dst_dir, restore);
let pulled = probe_and_pull(
&dst,
&src,
PullTrust::commits(ed25519_keys()),
&["os/a"],
PullFlags::NONE,
0,
)
.await;
let armed = import_seam::disarm(&dst_dir);
match pulled {
Err(Error::ChecksumMismatch { expected, actual }) => {
assert_eq!((expected, actual), (unsigned, signed));
}
other => panic!("{other:?}"),
}
assert!(armed, "the pull got to the import");
assert_nothing_written(&dst, &dst_dir).await;
});
}
#[test]
fn a_dirtree_that_changes_after_the_walk_fails_an_untrusted_pull() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let tip = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
let other = local_commit(&src, &[], None, 1_700_000_001, b"two").await;
let root = src.load_commit(&tip).await.unwrap().0.root_dirtree;
let other_root = src.load_commit(&other).await.unwrap().0.root_dirtree;
let src_dir = scratch.root.join("src");
let restore = restore_object_file(&src_dir, &root, ObjectType::DirTree);
replace_object_file(&src_dir, ObjectType::DirTree, &root, &other_root);
let dst = scratch.create("dst").await;
let dst_dir = scratch.root.join("dst");
import_seam::arm(&dst_dir, restore);
let pulled = probe_and_pull(
&dst,
&src,
PullTrust::unverified(),
&["os/a"],
PullFlags::UNTRUSTED,
0,
)
.await;
let armed = import_seam::disarm(&dst_dir);
match pulled {
Err(Error::ChecksumMismatch { expected, actual }) => {
assert_eq!((expected, actual), (root, other_root));
}
other => panic!("{other:?}"),
}
assert!(armed, "the pull got to the import");
assert_nothing_written(&dst, &dst_dir).await;
});
}
#[test]
fn a_commitmeta_that_changes_after_the_signature_check_fails_the_pull() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let tip = local_commit(&src, &["os/a"], None, 1_700_000_001, b"one").await;
let other = local_commit(&src, &[], None, 1_700_000_001, b"two").await;
for commit in [&tip, &other] {
src.sign_commit(commit, &ed25519_signer()).await.unwrap();
}
let src_dir = scratch.root.join("src");
let dst = scratch.create("dst").await;
let dst_dir = scratch.root.join("dst");
import_seam::arm(&dst_dir, move || {
replace_object_file(&src_dir, ObjectType::CommitMeta, &tip, &other)
});
let pulled = probe_and_pull(
&dst,
&src,
PullTrust::commits(ed25519_keys()),
&["os/a"],
PullFlags::NONE,
0,
)
.await;
let armed = import_seam::disarm(&dst_dir);
assert!(!armed, "the pull did not get to the import");
match pulled {
Err(Error::Pull(message)) => {
assert!(message.contains(".commitmeta"), "{message}");
}
other => panic!("{other:?}"),
}
assert_nothing_written(&dst, &dst_dir).await;
});
}
#[test]
fn a_dependency_that_changes_after_the_walk_fails_an_untrusted_pull() {
ostrya_rt::block_on(async {
let scratch = Scratch::new();
let src = scratch.create("src").await;
let dependency = local_commit(&src, &[], None, 1_700_000_001, b"dep").await;
let other = local_commit(&src, &[], None, 1_700_000_001, b"other").await;
let options = crate::commit::CommitOptions {
timestamp: Some(1_700_000_001),
related: vec![("lib/b".to_owned(), dependency)],
..crate::commit::CommitOptions::default()
};
local_commit_with(&src, &["os/a"], options, b"one").await;
let src_dir = scratch.root.join("src");
let restore = restore_object_file(&src_dir, &dependency, ObjectType::Commit);
replace_commit_file(&src_dir, &dependency, &other);
let dst = scratch.create("dst").await;
let dst_dir = scratch.root.join("dst");
import_seam::arm(&dst_dir, restore);
let pulled = probe_and_pull(
&dst,
&src,
PullTrust::unverified(),
&["os/a"],
PullFlags::UNTRUSTED,
0,
)
.await;
let armed = import_seam::disarm(&dst_dir);
match pulled {
Err(Error::ChecksumMismatch { expected, actual }) => {
assert_eq!((expected, actual), (dependency, other));
}
other => panic!("{other:?}"),
}
assert!(armed, "the pull got to the import");
assert_nothing_written(&dst, &dst_dir).await;
});
}
}