use std::any::Any;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::os::fd::AsFd;
use std::sync::Arc;
use ostrya_core::{
Checksum, Commit, ObjectName, ObjectType, Ref, Type, Value, loose_path, to_bytes, validate,
};
use super::ancestry::{Parents, Walks};
use super::hooks::{self, HookRefusal, HostEntry, ReceiveHooks, ReceiveRefUpdate, UpdatePlan};
use super::merge::{
SIGNATURE_KEYS, check_stored, merge_detached, replace_entries, signature_keys_in,
};
use super::policy::{SessionPolicy, UpdateRule};
use super::session::{
Failure, ReceiveCommit, ReceiveRefOutcome, ReceiveReport, ReceiveStep, ReceiveWarning,
};
use super::walk::{self, Missing};
use super::{ReceiveVerify, ServerSigner, TrustedKeys};
use crate::MAX_METADATA_SIZE;
use crate::access::ClientAccess;
use crate::composefs::RecordedBuildError;
use crate::error::{Error, Result};
use crate::lock::UpdateLockHeld;
use crate::object::read_meta_object;
use crate::read::CommitState;
use crate::refs::RefFileState;
use crate::related::{self, HeldDependency, RelatedRule};
use crate::remote::proto::{CommitRequest, MAX_FRAME, Message};
use crate::remote::{self, Expected, RefOutcome, RefUpdate};
use crate::repo::Repo;
use crate::sign::{Signer, append_signature};
use crate::summary::{
OSTREE_METADATA_REF, SummaryOptions, SummaryStep, parse_signature_dict,
serialize_signature_dict,
};
use crate::transaction::{Transaction, TransactionStats};
use crate::verify::Payload;
use crate::write::flat_name;
const GPG_KEY: &str = "ostree.gpgsigs";
pub(super) type Checked<T> = std::result::Result<T, Failure>;
type Bytes = Arc<Vec<u8>>;
pub(super) fn protocol(message: String) -> Failure {
Failure::Wire(remote::Error::Protocol(message))
}
pub(super) fn ref_denied(message: String) -> Failure {
Failure::Wire(remote::Error::RefDenied(message))
}
pub(super) struct Named<'a> {
pub(super) names: &'a [String],
pub(super) refs: &'a [Ref],
pub(super) paths: &'a [String],
pub(super) one_way: bool,
}
impl Named<'_> {
pub(super) fn by_name(&self) -> HashMap<&str, usize> {
self.names
.iter()
.enumerate()
.map(|(i, name)| (name.as_str(), i))
.collect()
}
pub(super) fn indices<'n>(
index: &HashMap<&str, usize>,
wanted: impl Iterator<Item = &'n str>,
what: &str,
) -> Checked<Vec<usize>> {
let mut seen = HashSet::new();
let mut found = Vec::new();
for name in wanted {
let Some(&i) = index.get(name) else {
return Err(protocol(format!("ref '{name}' was not named in Hello")));
};
if !seen.insert(i) {
return Err(protocol(format!("ref '{name}' is {what} more than once")));
}
found.push(i);
}
Ok(found)
}
}
pub(super) fn commit_ref(own: Option<&str>, name: &str, writes: bool) -> Checked<Ref> {
let r = name
.parse::<Ref>()
.map_err(|_| invalid_ref(name))?
.canonical(own);
check_shape(&r, name, writes)?;
Ok(r)
}
fn check_shape(r: &Ref, name: &str, writes: bool) -> Checked<()> {
match r {
Ref::Local { name: local } if writes && ostrya_core::is_checksum_shaped(local) => {
Err(invalid_ref(name))
}
_ => Ok(()),
}
}
fn invalid_ref(name: &str) -> Failure {
Failure::Wire(remote::Error::InvalidRef(format!(
"invalid ref name '{name}'"
)))
}
struct Target {
checksum: Checksum,
bytes: Arc<Vec<u8>>,
commit: Commit,
updates: Vec<usize>,
}
struct Prepared<'a> {
signer: &'a ServerSigner,
signature: Vec<u8>,
}
struct Edit<'a> {
commit: Checksum,
payload: Payload<'a>,
stored: Option<Bytes>,
incoming: Option<Bytes>,
keep: Arc<Vec<String>>,
signers: Vec<&'a Arc<ServerSigner>>,
signatures: Vec<Prepared<'a>>,
oversize: Option<u64>,
}
pub(super) async fn finish(
repo: &Repo,
policy: &dyn SessionPolicy,
hooks: Option<&dyn ReceiveHooks>,
txn: Transaction,
named: Named<'_>,
mut commit_meta: HashMap<Checksum, Vec<u8>>,
request: CommitRequest,
) -> Checked<ReceiveCommit> {
if request.server_commit.is_some() {
return Box::pin(super::server_commit::finish(
repo,
policy,
hooks,
txn,
named,
commit_meta,
request,
))
.await;
}
let CommitRequest { updates, force, .. } = request;
let own = repo.config().collection_id();
let indices = check_names(own, &named, &updates)?;
let paths: Arc<[String]> = indices.iter().map(|&i| named.paths[i].clone()).collect();
let names: Vec<&Ref> = indices.iter().map(|&i| &named.refs[i]).collect();
drop(indices);
check_reply_fits(&updates)?;
let (
rules,
Loaded {
targets,
session_commits,
roots,
parents,
staged,
fields,
},
) = Box::pin(async {
let outside = check_commit_meta_commits(&txn, &updates, &commit_meta).await?;
let rules = select_rules(repo, policy, &names, &updates)?;
let loaded = load_commits(&txn, &updates).await?;
drop_dependency_meta(outside, &loaded.fields, &mut commit_meta)?;
Ok::<_, Failure>((rules, loaded))
})
.await?;
let missing = walk::completeness(&txn, roots).await?;
if missing.total > 0 {
return Err(missing_objects(missing, "the trees of the commits reach"));
}
check_dependencies(&txn, &targets, &staged, &fields).await?;
check_bindings(
repo,
policy.verifies_ref_bindings(),
named.one_way,
&names,
&targets,
)?;
drop((staged, fields));
let commit_meta: HashMap<Checksum, Bytes> = commit_meta
.into_iter()
.map(|(commit, bytes)| (commit, Arc::new(bytes)))
.collect();
let mut stored = read_stored_for(repo, &rules, &targets, &commit_meta).await?;
check_signatures(&rules, &commit_meta, &targets, &stored).await?;
let incoming = filter_detached(repo, commit_meta).await?;
let edits = plan(&rules, &targets, &mut stored, incoming);
let leftover = match hooks {
Some(_) => stored,
None => {
drop(stored);
HashMap::new()
}
};
Box::pin(build_images(&txn, &session_commits)).await?;
let (synced, edits) = futures_lite::future::zip(
txn.sync_staged(),
prepare_signatures(edits, hooks.is_none()),
)
.await;
synced.map_err(Failure::Internal)?;
let edits = edits?;
let tips = repo
.resolve_relpath_tips(Arc::clone(&paths))
.await
.map_err(Failure::Internal)?;
let mut walks = Walks::new(parents);
let mut chains = Vec::with_capacity(updates.len());
for ((update, tip), rule) in updates.iter().zip(&tips).zip(&rules) {
chains.push(match (update.new, tip) {
_ if force && rule.allow_non_fast_forward => None,
_ if rule.create_only => None,
(Some(new), Some(tip)) if new != *tip => Some(walks.chain(&txn, new, *tip).await?),
_ => None,
});
}
let mut carried: Option<Box<dyn Any + Send>> = None;
let edits = match hooks {
None => edits,
Some(hooks) => {
let UpdatePlan {
metadata,
carried: value,
} = hooks
.before_update(&hook_updates(&names, &updates))
.await
.map_err(HookRefusal::into_failure)?;
carried = Some(value);
add_host_entries(repo, &targets, edits, leftover, metadata).await?
}
};
let held = repo.lock_update().await.map_err(Failure::Internal)?;
let anchor = policy.regenerates_summary() && repo.config().collection_id().is_some();
let (states, anchor_parent) = repo
.read_ref_states(Arc::clone(&paths), anchor.then_some(OSTREE_METADATA_REF))
.await
.map_err(Failure::Internal)?;
let refs: Vec<(&str, &str, bool)> = updates
.iter()
.zip(paths.iter())
.map(|(update, path)| (update.name.as_str(), path.as_str(), update.new.is_some()))
.collect();
let current = check_ref_paths(&refs, &states)?;
drop(refs);
let mut changes = Vec::with_capacity(updates.len());
for (i, update) in updates.iter().enumerate() {
let changed = check_ref(
&txn, update, &rules[i], force, current[i], chains[i], &mut walks,
)
.await?;
changes.push(changed);
}
queue_detached(repo, &txn, edits).await?;
for ((update, name), changed) in updates.iter().zip(&names).zip(&changes) {
if !*changed {
continue;
}
txn.set_ref(name, update.new.as_ref());
}
let changed = changes.contains(&true);
let (stats, warnings) = Box::pin(publish(
repo,
policy,
txn,
held,
changed,
anchor_parent,
session_commits,
))
.await?;
drop((walks, targets, chains, tips, paths, rules, states, changes));
let refs = names
.iter()
.zip(&updates)
.zip(¤t)
.map(|((&name, update), &old)| ReceiveRefOutcome {
name: name.clone(),
old,
new: update.new,
})
.collect();
let reply = updates
.into_iter()
.zip(current)
.map(|(update, old)| RefOutcome {
name: update.name,
old,
new: update.new,
})
.collect();
let report = report(policy, refs, stats, warnings);
if let (Some(hooks), Some(carried)) = (hooks, carried)
&& let Err(mut message) = hooks.after_update(&report, carried).await
{
hooks::cut(&mut message);
return Err(Failure::Wire(remote::Error::Internal(message)));
}
Ok(ReceiveCommit { report, reply })
}
fn hook_updates(names: &[&Ref], updates: &[RefUpdate]) -> Vec<ReceiveRefUpdate> {
names
.iter()
.zip(updates)
.map(|(&name, update)| ReceiveRefUpdate {
name: name.clone(),
expected: update.expected,
new: update.new,
})
.collect()
}
pub(super) async fn publish(
repo: &Repo,
policy: &dyn SessionPolicy,
txn: Transaction,
held: UpdateLockHeld,
changed: bool,
anchor_parent: Option<Result<Option<Checksum>>>,
session_commits: Vec<Checksum>,
) -> Checked<(TransactionStats, Vec<ReceiveWarning>)> {
let summary = policy.regenerates_summary() && changed;
if summary && let Some(collection_id) = repo.config().collection_id().map(str::to_owned) {
let parent = anchor_parent
.transpose()
.map_err(Failure::Internal)?
.flatten();
repo.stage_anchor_commit(&txn, &collection_id, parent, None)
.await
.map_err(Failure::Internal)?;
}
let stats = txn.commit_under(&held).await.map_err(Failure::Internal)?;
let mut warnings: Vec<ReceiveWarning> = repo
.remove_partial_markers(session_commits)
.await
.into_iter()
.map(|(commit, e)| ReceiveWarning {
step: ReceiveStep::PartialMarker,
message: format!("the partial marker of commit {commit}: {e}"),
})
.collect();
if summary && let Err(warning) = write_summary(repo, policy.summary_keys()).await {
warnings.push(warning);
}
drop(held);
Ok((stats, warnings))
}
pub(super) fn report(
policy: &dyn SessionPolicy,
refs: Vec<ReceiveRefOutcome>,
stats: TransactionStats,
warnings: Vec<ReceiveWarning>,
) -> ReceiveReport {
ReceiveReport {
refs,
stats,
warnings,
group: policy.group().map(str::to_owned),
}
}
fn check_names(own: Option<&str>, named: &Named<'_>, updates: &[RefUpdate]) -> Checked<Vec<usize>> {
let index = named.by_name();
for update in updates {
let writes = update.new.is_some();
match index.get(update.name.as_str()) {
Some(&i) => check_shape(&named.refs[i], &update.name, writes)?,
None => {
commit_ref(own, &update.name, writes)?;
}
}
}
if updates.is_empty() {
return Err(protocol("the Commit message holds no ref update".into()));
}
Named::indices(&index, updates.iter().map(|u| u.name.as_str()), "updated")
}
fn check_reply_fits(updates: &[RefUpdate]) -> Checked<()> {
let any_commit = Checksum::from_bytes([0; 32]);
let longest = Message::CommitReply(
updates
.iter()
.map(|u| RefOutcome {
name: u.name.clone(),
old: Some(any_commit),
new: u.new,
})
.collect(),
);
let body = longest.encode_body().map_err(Failure::Wire)?;
let len = body.len() as u64 + 1;
if len > u64::from(MAX_FRAME) {
return Err(Failure::Wire(remote::Error::LimitExceeded(format!(
"the reply to the {} ref updates of Commit can need a frame of {len} bytes, over the \
limit {MAX_FRAME}",
updates.len()
))));
}
Ok(())
}
fn outside_commits(
txn: &Transaction,
updates: &[RefUpdate],
commit_meta: &HashMap<Checksum, Vec<u8>>,
) -> Vec<Checksum> {
let new: HashSet<&Checksum> = updates.iter().filter_map(|u| u.new.as_ref()).collect();
let mut outside: Vec<Checksum> = commit_meta
.keys()
.filter(|commit| !(new.contains(commit) || txn.is_staged(commit, ObjectType::Commit)))
.copied()
.collect();
outside.sort_unstable();
outside
}
async fn check_commit_meta_commits(
txn: &Transaction,
updates: &[RefUpdate],
commit_meta: &HashMap<Checksum, Vec<u8>>,
) -> Checked<Vec<Checksum>> {
let outside = outside_commits(txn, updates, commit_meta);
if outside.is_empty() {
return Ok(outside);
}
let repo = txn.repo().clone();
let held: Vec<(Checksum, bool)> = ostrya_rt::unblock(move || {
outside
.into_iter()
.map(|commit| {
repo.has_object_blocking(ObjectType::Commit, &commit)
.map(|held| (commit, held))
})
.collect::<Result<_>>()
})
.await
.map_err(Failure::Internal)?;
if let Some((commit, _)) = held.iter().find(|(_, held)| !held) {
return Err(protocol(format!(
"detached metadata for commit {commit}, which the session did not stage, no ref \
update names, and the repository does not hold"
)));
}
Ok(held.into_iter().map(|(commit, _)| commit).collect())
}
fn drop_dependency_meta(
outside: Vec<Checksum>,
fields: &HashMap<Checksum, Vec<(String, Vec<u8>)>>,
commit_meta: &mut HashMap<Checksum, Vec<u8>>,
) -> Checked<()> {
if outside.is_empty() {
return Ok(());
}
let named: HashSet<&[u8]> = fields
.values()
.flatten()
.filter(|(name, _)| !name.is_empty())
.map(|(_, bytes)| bytes.as_slice())
.collect();
for commit in outside {
if !named.contains(&commit.as_bytes()[..]) {
return Err(protocol(format!(
"detached metadata for commit {commit}, which the session did not stage, no ref \
update names, and no commit of the session names as a dependency"
)));
}
commit_meta.remove(&commit);
}
Ok(())
}
fn select_rules<'a>(
repo: &Repo,
policy: &'a dyn SessionPolicy,
names: &[&Ref],
updates: &[RefUpdate],
) -> Checked<Vec<UpdateRule<'a>>> {
let own = repo.config().collection_id();
names
.iter()
.zip(updates)
.map(|(&name, update)| {
check_anchor(own.is_some(), name)?;
policy.rule(name, update, own)
})
.collect()
}
pub(super) fn check_anchor(collection: bool, name: &Ref) -> Checked<()> {
match name {
Ref::Local { name } if collection && name == OSTREE_METADATA_REF => Err(ref_denied(
format!("ref '{name}' holds the collection anchor commit, which the server writes"),
)),
_ => Ok(()),
}
}
async fn build_images(txn: &Transaction, session_commits: &[Checksum]) -> Checked<()> {
for commit in session_commits {
txn.mark_complete(commit);
}
txn.build_recorded_images_classified()
.await
.map_err(|e| match e {
RecordedBuildError::Key(e) => protocol(e.to_string()),
RecordedBuildError::Mismatch(e) => {
Failure::Wire(remote::Error::ChecksumMismatch(e.to_string()))
}
RecordedBuildError::Other(e) => Failure::Internal(e),
})
}
struct Loaded {
targets: Vec<Target>,
session_commits: Vec<Checksum>,
roots: Vec<(Checksum, Checksum)>,
parents: Parents,
staged: HashSet<Checksum>,
fields: HashMap<Checksum, Vec<(String, Vec<u8>)>>,
}
enum ReadCommit {
Absent,
Unparsable(ostrya_core::Error),
Target(Vec<u8>, Commit),
Other(
(Checksum, Checksum),
Option<Checksum>,
Vec<(String, Vec<u8>)>,
),
}
async fn load_commits(txn: &Transaction, updates: &[RefUpdate]) -> Checked<Loaded> {
let mut news: Vec<(Checksum, Vec<usize>)> = Vec::new();
let mut index: HashMap<Checksum, usize> = HashMap::new();
for (i, update) in updates.iter().enumerate() {
let Some(new) = update.new else {
continue;
};
match index.entry(new) {
Entry::Occupied(at) => news[*at.get()].1.push(i),
Entry::Vacant(at) => {
at.insert(news.len());
news.push((new, vec![i]));
}
}
}
let mut reads: Vec<(Checksum, bool)> = news
.iter()
.map(|(new, _)| (*new, txn.is_staged(new, ObjectType::Commit)))
.collect();
reads.extend(
txn.staged_of_type(ObjectType::Commit)
.into_iter()
.filter(|commit| !index.contains_key(commit))
.map(|commit| (commit, true)),
);
let count = news.len();
let mut read = read_commits(txn, reads.clone(), count)
.await
.map_err(Failure::Internal)?;
let others = read.split_off(count);
let parse_failure = |checksum: &Checksum, staged: bool, e: ostrya_core::Error| {
let message = format!("commit {checksum} does not parse: {e}");
if staged {
protocol(message)
} else {
Failure::Internal(Error::InvalidFormat(message))
}
};
let mut loaded = Loaded {
targets: Vec::with_capacity(count),
session_commits: Vec::with_capacity(reads.len()),
roots: Vec::with_capacity(reads.len()),
parents: Parents::with_capacity(reads.len()),
staged: HashSet::new(),
fields: HashMap::new(),
};
let mut absent = Missing::default();
for (((checksum, staged), read), (_, updates)) in reads.iter().zip(read).zip(news) {
match read {
ReadCommit::Absent => absent.add(ObjectName::new(*checksum, ObjectType::Commit)),
ReadCommit::Unparsable(e) => return Err(parse_failure(checksum, *staged, e)),
ReadCommit::Target(bytes, mut commit) => {
loaded.session_commits.push(*checksum);
loaded
.roots
.push((commit.root_dirtree, commit.root_dirmeta));
loaded.parents.insert(*checksum, commit.parent);
let related = std::mem::take(&mut commit.related);
if !related.is_empty() {
loaded.fields.insert(*checksum, related);
}
loaded.targets.push(Target {
checksum: *checksum,
bytes: Arc::new(bytes),
commit,
updates,
});
}
ReadCommit::Other(..) => unreachable!("a new commit is read with its bytes"),
}
}
if absent.total > 0 {
return Err(missing_objects(absent, "the ref updates name"));
}
for ((checksum, staged), read) in reads[count..].iter().zip(others) {
match read {
ReadCommit::Other(root, parent, related) => {
loaded.session_commits.push(*checksum);
loaded.roots.push(root);
loaded.parents.insert(*checksum, parent);
if !related.is_empty() {
loaded.fields.insert(*checksum, related);
}
}
ReadCommit::Unparsable(e) => return Err(parse_failure(checksum, *staged, e)),
ReadCommit::Absent | ReadCommit::Target(..) => {
unreachable!("a staged commit is read without its bytes")
}
}
}
if !loaded.fields.is_empty() {
loaded.staged = reads
.iter()
.filter(|(_, staged)| *staged)
.map(|(checksum, _)| *checksum)
.collect();
}
Ok(loaded)
}
async fn read_commits(
txn: &Transaction,
reads: Vec<(Checksum, bool)>,
targets: usize,
) -> Result<Vec<ReadCommit>> {
let mode = txn.repo().mode();
let objects = txn.repo().objects_fd().try_clone_to_owned()?;
let staging = txn.staging_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || {
reads
.into_iter()
.enumerate()
.map(|(i, (checksum, staged))| {
let bytes = if staged {
let name = flat_name(&checksum, ObjectType::Commit, mode);
read_meta_object(staging.as_fd(), &name, MAX_METADATA_SIZE)?
} else {
let path = loose_path(&checksum, ObjectType::Commit, mode);
match read_meta_object(objects.as_fd(), &path, MAX_METADATA_SIZE) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(ReadCommit::Absent);
}
Err(e) => return Err(Error::Io(e)),
}
};
Ok(match Commit::parse(&bytes) {
Err(e) => ReadCommit::Unparsable(e),
Ok(commit) if i < targets => ReadCommit::Target(bytes, commit),
Ok(commit) => ReadCommit::Other(
(commit.root_dirtree, commit.root_dirmeta),
commit.parent,
commit.related,
),
})
})
.collect()
})
.await
}
pub(super) fn missing_objects(missing: Missing, what: &str) -> Failure {
let mut message = format!(
"{} objects that {what} are neither staged nor present",
missing.total
);
if missing.listed.len() < missing.total {
message.push_str(&format!(", the first {} listed", missing.listed.len()));
}
Failure::Wire(remote::Error::MissingObjects {
message,
missing: missing.listed,
})
}
async fn check_dependencies(
txn: &Transaction,
targets: &[Target],
staged: &HashSet<Checksum>,
fields: &HashMap<Checksum, Vec<(String, Vec<u8>)>>,
) -> Checked<()> {
if fields.is_empty() {
return Ok(());
}
let held: Vec<Checksum> = targets
.iter()
.map(|t| t.checksum)
.filter(|c| !staged.contains(c) && fields.contains_key(c))
.collect();
let partial: HashSet<Checksum> = if held.is_empty() {
HashSet::new()
} else {
let repo = txn.repo().clone();
ostrya_rt::unblock(move || {
held.into_iter()
.filter_map(|commit| match repo.commit_state_blocking(&commit) {
Ok(CommitState::Partial) => Some(Ok(commit)),
Ok(CommitState::Normal) => None,
Err(e) => Some(Err(e)),
})
.collect::<Result<_>>()
})
.await
.map_err(Failure::Internal)?
};
let news: HashSet<&Checksum> = targets.iter().map(|t| &t.checksum).collect();
let mut others: Vec<&Checksum> = fields.keys().filter(|c| !news.contains(c)).collect();
others.sort_unstable();
let naming = targets
.iter()
.map(|t| &t.checksum)
.filter(|c| staged.contains(c) || partial.contains(c))
.chain(others);
let mut known = HashSet::new();
let mut named: Vec<(Checksum, Checksum, &str)> = Vec::new();
for commit in naming {
let Some(field) = fields.get(commit) else {
continue;
};
let entries =
related::borrowed_dependencies(commit, field).map_err(|e| protocol(e.to_string()))?;
for (name, dependency) in entries {
if known.insert(dependency) {
named.push((dependency, *commit, name));
}
}
}
let held: Vec<Checksum> = named
.iter()
.map(|(dependency, ..)| *dependency)
.filter(|dependency| !staged.contains(dependency) && !news.contains(dependency))
.collect();
let states: HashMap<Checksum, HeldDependency> = if held.is_empty() {
HashMap::new()
} else {
let repo = txn.repo().clone();
ostrya_rt::unblock(move || {
held.into_iter()
.map(|dependency| {
related::held_dependency_blocking(&repo, None, &dependency, |_| Ok(()))
.map(|state| (dependency, state))
})
.collect::<Result<_>>()
})
.await
.map_err(Failure::Internal)?
};
let mut absent = Missing::default();
for (dependency, ..) in &named {
if states.get(dependency) == Some(&HeldDependency::Absent) {
absent.add(ObjectName::new(*dependency, ObjectType::Commit));
}
}
if absent.total > 0 {
return Err(missing_objects(
absent,
"the staged commits name as dependencies",
));
}
for (dependency, naming, name) in named {
let nested = match states.get(&dependency) {
None => fields.contains_key(&dependency),
Some(HeldDependency::Complete { nested, .. }) => *nested,
Some(HeldDependency::Partial) => {
return Err(Failure::Wire(remote::Error::MissingObjects {
message: related::partial_dependency(naming, name, &dependency).to_string(),
missing: Vec::new(),
}));
}
Some(HeldDependency::Absent) => unreachable!("an absent dependency was refused"),
};
if nested {
return Err(protocol(
related::nested_dependency(naming, name, &dependency).to_string(),
));
}
}
Ok(())
}
fn check_bindings(
repo: &Repo,
ref_bindings: bool,
one_way: bool,
names: &[&Ref],
targets: &[Target],
) -> Checked<()> {
let own = repo.config().collection_id();
let mismatch = |message: String| Failure::Wire(remote::Error::BindingMismatch(message));
for target in targets {
let commit = &target.checksum;
let listed = target.commit.metadata_value("ostree.ref-binding").is_some();
let bindings = target.commit.ref_bindings();
let bound = target.commit.collection_binding();
for &i in &target.updates {
let name = names[i];
if ref_bindings && listed && !bindings.contains(&name.name()) {
return Err(mismatch(format!(
"commit {commit} is bound to the refs {bindings:?}, which do not hold '{}'",
name.name()
)));
}
let wanted = match name {
Ref::Collection { id, .. } => Some(id.as_str()),
Ref::Local { .. } if one_way && own.is_none() => continue,
Ref::Local { .. } => own,
Ref::Remote { .. } if own.is_some() => own,
Ref::Remote { .. } => continue,
};
match (bound, wanted) {
(Some(bound), Some(id)) if id == bound => {}
(Some(bound), Some(id)) => {
return Err(mismatch(format!(
"commit {commit} is bound to the collection '{bound}', not '{id}' of \
ref '{name}'"
)));
}
(Some(bound), None) => {
return Err(mismatch(format!(
"commit {commit} is bound to the collection '{bound}', and ref '{name}' \
is a local ref of a repository with no collection id"
)));
}
(None, _) if matches!(name, Ref::Collection { .. }) => {
return Err(mismatch(format!(
"commit {commit} has no collection binding, which a ref of the \
collection of ref '{name}' needs"
)));
}
(None, _) => {}
}
}
}
Ok(())
}
fn target_keys<'a>(
rules: &[UpdateRule<'a>],
indices: &[usize],
) -> Vec<(&'a Arc<TrustedKeys>, bool)> {
let mut keys: Vec<(&Arc<TrustedKeys>, bool)> = Vec::new();
for &i in indices {
let rule = &rules[i];
if let ReceiveVerify::Keys(held) = rule.verify {
match keys.iter_mut().find(|(k, _)| Arc::ptr_eq(k, held)) {
Some((_, unsigned)) => *unsigned &= rule.allow_unsigned,
None => keys.push((held, rule.allow_unsigned)),
}
}
}
keys
}
fn target_signers<'a>(rules: &[UpdateRule<'a>], indices: &[usize]) -> Vec<&'a Arc<ServerSigner>> {
let mut signers: Vec<&Arc<ServerSigner>> = Vec::new();
for &i in indices {
for signer in rules[i].signers {
if !signers.iter().any(|s| Arc::ptr_eq(s, signer)) {
signers.push(signer);
}
}
}
signers
}
async fn read_stored_for(
repo: &Repo,
rules: &[UpdateRule<'_>],
targets: &[Target],
commit_meta: &HashMap<Checksum, Bytes>,
) -> Checked<HashMap<Checksum, Option<Bytes>>> {
let mut commits: Vec<Checksum> = targets
.iter()
.filter(|t| {
!target_keys(rules, &t.updates).is_empty()
|| !target_signers(rules, &t.updates).is_empty()
|| commit_meta.contains_key(&t.checksum)
})
.map(|t| t.checksum)
.collect();
let listed: HashSet<Checksum> = commits.iter().copied().collect();
commits.extend(commit_meta.keys().filter(|c| !listed.contains(c)).copied());
let stored = read_stored(repo, commits.clone()).await?;
Ok(commits.into_iter().zip(stored).collect())
}
pub(super) async fn sign_server_commit(
repo: &Repo,
txn: &Transaction,
commit: Checksum,
payload: &Arc<Vec<u8>>,
signers: &[Arc<ServerSigner>],
) -> Checked<()> {
let mut unique: Vec<&Arc<ServerSigner>> = Vec::with_capacity(signers.len());
for signer in signers {
if !unique.iter().any(|s| Arc::ptr_eq(s, signer)) {
unique.push(signer);
}
}
if unique.is_empty() {
return Ok(());
}
let stored = read_stored(repo, vec![commit]).await?.pop().flatten();
let edit = Edit {
commit,
payload: payload.into(),
stored,
incoming: None,
keep: Arc::default(),
signers: unique,
signatures: Vec::new(),
oversize: None,
};
let edits = prepare_signatures(vec![edit], true).await?;
queue_edits(txn, edits)
}
async fn read_stored(repo: &Repo, commits: Vec<Checksum>) -> Checked<Vec<Option<Bytes>>> {
let mode = repo.mode();
let objects = repo
.objects_fd()
.try_clone_to_owned()
.map_err(|e| Failure::Internal(e.into()))?;
ostrya_rt::unblock(move || {
commits
.iter()
.map(|commit| {
let path = loose_path(commit, ObjectType::CommitMeta, mode);
match read_meta_object(objects.as_fd(), &path, MAX_METADATA_SIZE) {
Ok(bytes) if bytes.is_empty() => Ok(None),
Ok(bytes) => Ok(Some(Arc::new(bytes))),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(Error::Io(e)),
}
})
.collect::<Result<Vec<_>>>()
})
.await
.map_err(Failure::Internal)
}
fn merged_dict(
stored: Option<&[u8]>,
incoming: Option<&[u8]>,
keep: &[String],
) -> Result<Option<Value>> {
let stored = stored.map(parse_signature_dict).transpose()?.flatten();
match incoming.map(parse_signature_dict).transpose()?.flatten() {
Some(incoming) => merge_detached(stored, incoming, keep).map(Some),
None => Ok(stored),
}
}
fn empty_dict() -> Value {
Value::Array(Vec::new())
}
async fn check_signatures(
rules: &[UpdateRule<'_>],
commit_meta: &HashMap<Checksum, Bytes>,
targets: &[Target],
stored: &HashMap<Checksum, Option<Bytes>>,
) -> Checked<()> {
for target in targets {
let checksum = target.checksum;
let keys = target_keys(rules, &target.updates);
if keys.is_empty() {
continue;
}
let stored = stored.get(&checksum).cloned().flatten();
let incoming = commit_meta.get(&checksum).cloned();
let dict = ostrya_rt::unblock(move || {
merged_dict(
stored.as_deref().map(Vec::as_slice),
incoming.as_deref().map(Vec::as_slice),
&[],
)
})
.await
.map_err(Failure::Internal)?;
let subject = format!("commit {checksum}");
let signed = keys.iter().any(|(_, allow_unsigned)| *allow_unsigned)
&& dict.as_ref().is_some_and(has_signature);
for (held, allow_unsigned) in keys {
if allow_unsigned && !signed {
continue;
}
held.check(&subject, &target.bytes, dict.as_ref())
.await
.map_err(|e| match e {
Error::Signature(message) => {
Failure::Wire(remote::Error::SignatureRequired(message))
}
other => Failure::Internal(other),
})?;
}
}
Ok(())
}
fn has_signature(dict: &Value) -> bool {
SIGNATURE_KEYS.iter().any(|key| {
let Some(value) = dict.dict_get(key) else {
return false;
};
let array = match value.as_variant() {
Some((_, inner)) => inner,
None => value,
};
array
.as_array()
.is_some_and(|blobs| blobs.iter().any(|blob| blob.as_bytes().is_some()))
})
}
pub(super) fn check_ref_paths(
refs: &[(&str, &str, bool)],
states: &[RefFileState],
) -> Checked<Vec<Option<Checksum>>> {
let mut current = Vec::with_capacity(refs.len());
for (&(name, _, _), state) in refs.iter().zip(states) {
current.push(match state {
RefFileState::Absent => None,
RefFileState::Commit(commit) => Some(*commit),
RefFileState::Alias => {
return Err(ref_denied(format!(
"ref '{name}' is an alias of another ref"
)));
}
RefFileState::NotARef => {
return Err(ref_denied(format!(
"ref '{name}' names a directory or a path below a ref file, \
which a ref write cannot replace"
)));
}
});
}
let writes = || refs.iter().filter(|(_, _, writes)| *writes);
let mut written: HashMap<&str, &str> = HashMap::new();
for &(name, relpath, _) in writes() {
written.insert(relpath, name);
}
for &(name, relpath, _) in writes() {
let mut path = relpath;
while let Some((parent, _)) = path.rsplit_once('/') {
if let Some(other) = written.get(parent) {
return Err(ref_denied(format!(
"ref '{name}' names a path below ref '{other}' of the same message"
)));
}
path = parent;
}
}
Ok(current)
}
async fn check_ref(
txn: &Transaction,
update: &RefUpdate,
rule: &UpdateRule<'_>,
force: bool,
current: Option<Checksum>,
chain: Option<usize>,
walks: &mut Walks,
) -> Checked<bool> {
let name = &update.name;
let expected = match update.expected {
Expected::Absent => current.is_none(),
Expected::Commit(commit) => current == Some(commit),
Expected::Any => true,
};
if !expected {
let state = match current {
Some(commit) => format!("at {commit}"),
None => "absent".into(),
};
return Err(Failure::Wire(remote::Error::RefMismatch {
message: format!("ref '{name}' is {state}"),
name: name.clone(),
current,
}));
}
if let (Some(commit), Some(_)) = (current, update.new)
&& rule.create_only
{
return Err(Failure::Wire(remote::Error::RefMismatch {
message: format!(
"ref '{name}' is at {commit}, and the policy lets an update create the ref \
and not write to it"
),
name: name.clone(),
current,
}));
}
match (current, update.new) {
(None, None) => Ok(false),
(Some(_), None) if !rule.allow_delete => Err(Failure::Wire(remote::Error::DeleteDenied(
format!("the policy does not allow a delete of ref '{name}'"),
))),
(Some(_), None) | (None, Some(_)) => Ok(true),
(Some(current), Some(new)) if current == new => Ok(false),
(Some(_), Some(_)) if force && rule.allow_non_fast_forward => Ok(true),
(Some(current), Some(new)) => {
let chain = match chain {
Some(chain) => chain,
None => walks.chain(txn, new, current).await?,
};
if !walks.reaches(txn, chain, current).await? {
return Err(Failure::Wire(remote::Error::NonFastForward(format!(
"commit {new} does not descend from {current}, the commit of ref '{name}'"
))));
}
Ok(true)
}
}
}
async fn filter_detached(
repo: &Repo,
mut commit_meta: HashMap<Checksum, Bytes>,
) -> Checked<HashMap<Checksum, Bytes>> {
let rule = RelatedRule::of(repo.config()).map_err(Failure::Internal)?;
if !rule.drop_related {
commit_meta.retain(|_, bytes| !bytes.is_empty());
return Ok(commit_meta);
}
ostrya_rt::unblock(move || -> Result<_> {
let mut incoming = HashMap::with_capacity(commit_meta.len());
for (commit, bytes) in commit_meta {
let bytes = Arc::unwrap_or_clone(bytes);
if let Some(bytes) = rule.apply(&commit, bytes)?
&& !bytes.is_empty()
{
incoming.insert(commit, Arc::new(bytes));
}
}
Ok(incoming)
})
.await
.map_err(Failure::Internal)
}
fn plan<'a>(
rules: &[UpdateRule<'a>],
targets: &'a [Target],
stored: &mut HashMap<Checksum, Option<Bytes>>,
mut incoming: HashMap<Checksum, Bytes>,
) -> Vec<Edit<'a>> {
let mut edit = |commit: Checksum, payload, incoming, signers| Edit {
commit,
payload,
stored: stored.remove(&commit).flatten(),
incoming,
keep: Arc::default(),
signers,
signatures: Vec::new(),
oversize: None,
};
let mut edits = Vec::new();
for target in targets {
let signers = target_signers(rules, &target.updates);
let dict = incoming.remove(&target.checksum);
if dict.is_some() || !signers.is_empty() {
edits.push(edit(target.checksum, (&target.bytes).into(), dict, signers));
}
}
for (commit, dict) in incoming {
edits.push(edit(commit, Payload::Borrowed(&[]), Some(dict), Vec::new()));
}
edits
}
fn flagged<'k>(keys: impl IntoIterator<Item = &'k str>) -> [bool; SIGNATURE_KEYS.len()] {
let mut flags = [false; SIGNATURE_KEYS.len()];
for key in keys {
if let Some(i) = SIGNATURE_KEYS.iter().position(|k| *k == key) {
flags[i] = true;
}
}
flags
}
async fn check_edit(
stored: Option<Bytes>,
incoming: Option<Bytes>,
keys: [bool; SIGNATURE_KEYS.len()],
build: bool,
keep: Arc<Vec<String>>,
) -> Checked<Option<Value>> {
if stored.is_none() && incoming.is_none() {
return Ok(build.then(empty_dict));
}
ostrya_rt::unblock(move || -> Result<Option<Value>> {
let incoming = incoming.as_deref().map(Vec::as_slice);
let stored = stored.as_deref().map(Vec::as_slice);
if let Some(stored) = stored {
let mut touched = match incoming {
Some(incoming) => signature_keys_in(incoming)?,
None => [false; SIGNATURE_KEYS.len()],
};
for (touched, key) in touched.iter_mut().zip(keys) {
*touched |= key;
}
check_stored(stored, touched)?;
}
if !build {
return Ok(None);
}
Ok(Some(
merged_dict(stored, incoming, &keep)?.unwrap_or_else(empty_dict),
))
})
.await
.map_err(Failure::Internal)
}
fn size_over(
limit: u64,
stored: Option<&[u8]>,
incoming: Option<&[u8]>,
signatures: &[(&str, &[u8])],
written: Option<Value>,
keep: &[String],
) -> Result<Option<u64>> {
let sources = (stored.map_or(0, <[u8]>::len) + incoming.map_or(0, <[u8]>::len)) as u64;
let bound = 16 * sources
+ signatures
.iter()
.map(|(_, signature)| signature.len() as u64 + 8)
.sum::<u64>()
+ 64 * SIGNATURE_KEYS.len() as u64;
if bound <= limit {
return Ok(None);
}
let dict = match written {
Some(dict) => dict,
None => {
let mut dict = merged_dict(stored, incoming, keep)?.unwrap_or_else(empty_dict);
for (key, signature) in signatures {
append_signature(&mut dict, key, signature.to_vec())?;
}
dict
}
};
let size = serialize_signature_dict(&dict)?.len() as u64;
Ok((size > limit).then_some(size))
}
async fn oversize(edit: &Edit<'_>, written: Option<Value>) -> Checked<Option<u64>> {
let stored = edit.stored.clone();
let incoming = edit.incoming.clone();
let keep = edit.keep.clone();
let signatures: Vec<(String, Vec<u8>)> = edit
.signatures
.iter()
.map(|p| {
(
p.signer.signer().metadata_key().to_owned(),
p.signature.clone(),
)
})
.collect();
ostrya_rt::unblock(move || {
let signatures: Vec<(&str, &[u8])> = signatures
.iter()
.map(|(key, signature)| (key.as_str(), signature.as_slice()))
.collect();
size_over(
MAX_METADATA_SIZE,
stored.as_deref().map(Vec::as_slice),
incoming.as_deref().map(Vec::as_slice),
&signatures,
written,
&keep,
)
})
.await
.map_err(Failure::Internal)
}
fn oversize_failure(commit: &Checksum, size: u64) -> Failure {
Failure::Wire(remote::Error::LimitExceeded(format!(
"the merged detached metadata of commit {commit} is {size} bytes, larger than \
{MAX_METADATA_SIZE} bytes"
)))
}
async fn prepare_signatures(mut edits: Vec<Edit<'_>>, size: bool) -> Checked<Vec<Edit<'_>>> {
for edit in &mut edits {
let signers = std::mem::take(&mut edit.signers);
let keys = flagged(signers.iter().map(|s| s.signer().metadata_key()));
let mut written = check_edit(
edit.stored.clone(),
edit.incoming.clone(),
keys,
!signers.is_empty(),
edit.keep.clone(),
)
.await?;
if let Some(dict) = written.as_mut() {
for signer in signers {
if signer.has_signed(edit.payload, Some(dict)).await {
continue;
}
let key = signer.signer().metadata_key();
let signature = signer
.signer()
.sign(edit.payload.bytes())
.await
.map_err(|e| Failure::Internal(e.into()))?;
append_signature(dict, key, signature.clone())
.map_err(|e| Failure::Internal(e.into()))?;
edit.signatures.push(Prepared {
signer: signer.as_ref(),
signature,
});
}
}
if size {
edit.oversize = oversize(edit, written).await?;
}
}
Ok(edits)
}
fn invalid_plan(mut message: String) -> Failure {
hooks::cut(&mut message);
Failure::Internal(Error::InvalidInput(message))
}
fn quoted(key: &str) -> String {
let mut key = key.to_owned();
hooks::cut(&mut key);
key
}
fn check_plan(
targets: &[Checksum],
metadata: Vec<(Checksum, Vec<HostEntry>)>,
) -> Checked<Vec<(usize, Vec<HostEntry>)>> {
let index: HashMap<Checksum, usize> = targets
.iter()
.enumerate()
.map(|(i, target)| (*target, i))
.collect();
let mut seen = HashSet::with_capacity(metadata.len());
let mut plan = Vec::with_capacity(metadata.len());
for (commit, entries) in metadata {
let Some(&target) = index.get(&commit) else {
return Err(invalid_plan(format!(
"the host gives detached metadata for commit {commit}, which no ref update \
names as its new commit"
)));
};
if !seen.insert(commit) {
return Err(invalid_plan(format!(
"the host gives the detached metadata of commit {commit} in two tuples"
)));
}
let mut keys = HashSet::with_capacity(entries.len());
for entry in &entries {
let key = entry.key.as_str();
if SIGNATURE_KEYS.contains(&key) {
return Err(invalid_plan(format!(
"the host gives the signature key '{}' for commit {commit}",
quoted(key)
)));
}
if !keys.insert(key) {
return Err(invalid_plan(format!(
"the host gives the key '{}' two times for commit {commit}",
quoted(key)
)));
}
if !matches!(entry.value, Value::Variant(_)) {
return Err(invalid_plan(format!(
"the host gives the key '{}' for commit {commit} a value that is not a \
variant",
quoted(key)
)));
}
}
if !entries.is_empty() {
plan.push((target, entries));
}
}
Ok(plan)
}
fn into_key(dict: Value) -> String {
if let Value::Array(entries) = dict
&& let Some(Value::Tuple(fields)) = entries.into_iter().next()
&& let Some(Value::Str(key)) = fields.into_iter().next()
{
return key;
}
String::new()
}
type HostMerge = (usize, Vec<u8>, Arc<Vec<String>>);
async fn add_host_entries<'a>(
repo: &Repo,
targets: &'a [Target],
mut edits: Vec<Edit<'a>>,
leftover: HashMap<Checksum, Option<Bytes>>,
metadata: Vec<(Checksum, Vec<HostEntry>)>,
) -> Checked<Vec<Edit<'a>>> {
let commits: Vec<Checksum> = targets.iter().map(|target| target.checksum).collect();
let at: HashMap<Checksum, usize> = edits
.iter()
.enumerate()
.map(|(i, edit)| (edit.commit, i))
.collect();
let mut incoming: HashMap<Checksum, Bytes> = metadata
.iter()
.filter(|(_, entries)| !entries.is_empty())
.filter_map(|(commit, _)| {
let &i = at.get(commit)?;
Some((*commit, edits[i].incoming.take()?))
})
.collect();
let (merged, mut leftover) = ostrya_rt::unblock(move || {
let plan = check_plan(&commits, metadata)?;
let named: HashSet<Checksum> = plan.iter().map(|(target, _)| commits[*target]).collect();
let mut leftover = leftover;
leftover.retain(|commit, _| named.contains(commit));
let ty = Type::parse("a{sv}")
.map_err(|e| Failure::Internal(ostrya_core::Error::from(e).into()))?;
let mut encoded = Vec::with_capacity(plan.len());
for (target, entries) in plan {
let commit = commits[target];
let mut host = Vec::with_capacity(entries.len());
let mut keep = Vec::new();
for HostEntry {
key,
value,
keep_existing,
} in entries
{
let dict = Value::Array(vec![Value::Tuple(vec![Value::Str(key), value])]);
let bytes = match to_bytes(&ty, &dict)
.and_then(|bytes| validate(&ty, &bytes).map(|()| bytes))
{
Ok(bytes) => bytes,
Err(e) => {
return Err(invalid_plan(format!(
"the host entry '{}' for commit {commit} does not encode: {e}",
quoted(&into_key(dict))
)));
}
};
if keep_existing {
keep.push(into_key(dict));
}
host.push(bytes);
}
encoded.push((target, host, keep));
}
let merged = encoded
.into_iter()
.map(|(target, host, keep)| {
let incoming = incoming.remove(&commits[target]);
let merged = replace_entries(incoming.as_deref().map(Vec::as_slice), &host)
.map_err(Failure::Internal)?;
Ok((target, merged, Arc::new(keep)))
})
.collect::<Checked<Vec<HostMerge>>>()?;
Ok((merged, leftover))
})
.await?;
let reads: Vec<Checksum> = merged
.iter()
.map(|(target, ..)| targets[*target].checksum)
.filter(|commit| !at.contains_key(commit) && !leftover.contains_key(commit))
.collect();
if !reads.is_empty() {
let read = read_stored(repo, reads.clone()).await?;
leftover.extend(reads.into_iter().zip(read));
}
let mut host = vec![false; edits.len()];
let mut fresh = Vec::new();
for (target, bytes, keep) in merged {
let target = &targets[target];
let incoming = Some(Arc::new(bytes));
match at.get(&target.checksum) {
Some(&i) => {
edits[i].incoming = incoming;
edits[i].keep = keep;
host[i] = true;
}
None => {
let stored = leftover.remove(&target.checksum).flatten();
if let Some(stored) = &stored {
fresh.push(stored.clone());
}
host.push(true);
edits.push(Edit {
commit: target.checksum,
payload: (&target.bytes).into(),
stored,
incoming,
keep,
signers: Vec::new(),
signatures: Vec::new(),
oversize: None,
});
}
}
}
drop(leftover);
if !fresh.is_empty() {
ostrya_rt::unblock(move || {
fresh
.iter()
.try_for_each(|stored| check_stored(stored, [false; SIGNATURE_KEYS.len()]))
})
.await
.map_err(Failure::Internal)?;
}
for (edit, host) in edits.iter_mut().zip(host) {
edit.oversize = match &edit.incoming {
Some(merged)
if host
&& edit.stored.is_none()
&& edit.signatures.is_empty()
&& merged.len() as u64 <= MAX_METADATA_SIZE =>
{
None
}
_ => oversize(edit, None).await?,
};
if host && let Some(size) = edit.oversize {
return Err(oversize_failure(&edit.commit, size));
}
}
Ok(edits)
}
async fn queue_detached(repo: &Repo, txn: &Transaction, edits: Vec<Edit<'_>>) -> Checked<()> {
let stored = read_stored(repo, edits.iter().map(|e| e.commit).collect()).await?;
for (mut edit, stored) in edits.into_iter().zip(stored) {
if stored != edit.stored {
edit.stored = stored;
let prepared = std::mem::take(&mut edit.signatures);
let keys = flagged(prepared.iter().map(|p| p.signer.signer().metadata_key()));
let mut written = check_edit(
edit.stored.clone(),
edit.incoming.clone(),
keys,
!prepared.is_empty(),
edit.keep.clone(),
)
.await?;
if let Some(dict) = written.as_mut() {
for prepared in prepared {
if prepared.signer.has_signed(edit.payload, Some(dict)).await {
continue;
}
let key = prepared.signer.signer().metadata_key();
append_signature(dict, key, prepared.signature.clone())
.map_err(|e| Failure::Internal(e.into()))?;
edit.signatures.push(prepared);
}
}
edit.oversize = oversize(&edit, written).await?;
}
queue_edit(txn, edit)?;
}
Ok(())
}
fn queue_edits(txn: &Transaction, edits: Vec<Edit<'_>>) -> Checked<()> {
for edit in edits {
queue_edit(txn, edit)?;
}
Ok(())
}
fn queue_edit(txn: &Transaction, edit: Edit<'_>) -> Checked<()> {
if let Some(size) = edit.oversize {
return Err(oversize_failure(&edit.commit, size));
}
if let Some(incoming) = edit.incoming {
txn.merge_commit_detached(
&edit.commit,
Arc::unwrap_or_clone(incoming),
Arc::unwrap_or_clone(edit.keep),
);
}
for prepared in edit.signatures {
txn.append_signature(
&edit.commit,
prepared.signer.signer().metadata_key(),
prepared.signature,
);
}
Ok(())
}
async fn write_summary(
repo: &Repo,
signers: &[Arc<ServerSigner>],
) -> std::result::Result<(), ReceiveWarning> {
let warning = |step, what: &str, e: Error| ReceiveWarning {
step,
message: format!("{what}: {e}"),
};
let access = ClientAccess::from_config(repo.config(), repo.path())
.map_err(|e| warning(ReceiveStep::SummaryBuild, "the summary build", e))?;
let is_gpg = |s: &&Arc<ServerSigner>| s.signer().metadata_key() == GPG_KEY;
let ordered: Vec<&dyn Signer> = signers
.iter()
.filter(is_gpg)
.chain(signers.iter().filter(|s| !is_gpg(s)))
.map(|s| s.signer())
.collect();
repo.write_summaries(Arc::new(access), &SummaryOptions::default(), &ordered)
.await
.map(drop)
.map_err(|failure| match failure.step {
SummaryStep::Build => warning(
ReceiveStep::SummaryBuild,
"the summary build",
failure.error,
),
SummaryStep::Sign => {
let what = match &failure.key {
Some(key) => format!("the summary signature with the {key} key"),
None => "the summary signature".to_owned(),
};
warning(ReceiveStep::SummarySign, &what, failure.error)
}
SummaryStep::Write => warning(
ReceiveStep::SummaryWrite,
"the summary write",
failure.error,
),
})
}
#[cfg(test)]
mod tests {
use super::*;
const KEY: &str = "ostree.sign.ed25519";
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Scratch {
let dir = std::env::temp_dir().join(format!(
"ostrya-finish-{tag}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn absent_updates(count: usize) -> Vec<RefUpdate> {
(0..count)
.map(|i| RefUpdate {
name: format!("refs-{i:015}"),
expected: Expected::Absent,
new: Some(Checksum::from_bytes([1; 32])),
})
.collect()
}
#[test]
fn a_commit_whose_reply_cannot_fit_is_refused() {
let updates = absent_updates(15_000);
let request = Message::Commit(CommitRequest {
updates: updates.clone(),
force: false,
server_commit: None,
});
let request_len = request.encode_body().unwrap().len() + 1;
assert!(request_len <= MAX_FRAME as usize, "{request_len}");
match check_reply_fits(&updates) {
Err(Failure::Wire(remote::Error::LimitExceeded(m))) => {
assert!(m.contains("15000 ref updates"), "{m}")
}
Err(Failure::Wire(e)) => panic!("expected limit-exceeded, got {e}"),
Err(_) => panic!("expected limit-exceeded, got another failure"),
Ok(()) => panic!("a reply over the limit passed"),
}
assert!(check_reply_fits(&absent_updates(100)).is_ok());
let (mut low, mut high) = (100, 15_000);
while high - low > 1 {
let mid = (low + high) / 2;
if check_reply_fits(&absent_updates(mid)).is_ok() {
low = mid;
} else {
high = mid;
}
}
let longest = |count| {
Message::CommitReply(
absent_updates(count)
.into_iter()
.map(|u| RefOutcome {
name: u.name,
old: Some(Checksum::from_bytes([2; 32])),
new: u.new,
})
.collect(),
)
.encode_body()
.unwrap()
.len()
+ 1
};
assert!(longest(low) <= MAX_FRAME as usize);
assert!(longest(high) > MAX_FRAME as usize);
}
fn serialized(dict: &Value) -> Vec<u8> {
serialize_signature_dict(dict).unwrap()
}
fn signed(blobs: &[&[u8]]) -> Value {
let mut dict = Value::Array(Vec::new());
for blob in blobs {
append_signature(&mut dict, KEY, blob.to_vec()).unwrap();
}
dict
}
#[test]
fn the_size_check_is_exact_at_the_limit() {
let stored = serialized(&signed(&[b"one"]));
let incoming = serialized(&signed(&[b"one", b"two"]));
let signatures: [(&str, &[u8]); 1] = [(KEY, b"three")];
let written = serialized(&signed(&[b"one", b"two", b"three"]));
let n = written.len() as u64;
let over = |limit| {
size_over(
limit,
Some(&stored),
Some(&incoming),
&signatures,
None,
&[],
)
.unwrap()
};
assert_eq!(over(n - 1), Some(n));
assert_eq!(over(n), None);
assert_eq!(over(0), Some(n));
assert_eq!(over(u64::MAX), None);
assert_eq!(
size_over(
n - 1,
None,
None,
&[],
Some(signed(&[b"one", b"two", b"three"])),
&[],
)
.unwrap(),
Some(n)
);
}
#[test]
fn the_size_check_keeps_the_stored_value() {
let blob = |len| Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![7; len]));
let dict = |len| {
let mut dict = empty_dict();
crate::commit::append_dict_entry(&mut dict, "k", blob(len)).unwrap();
dict
};
let stored = serialized(&dict(100));
let incoming = serialized(&dict(10));
let keep = ["k".to_owned()];
let over = |keep: &[String]| {
size_over(0, Some(&stored), Some(&incoming), &[], None, keep).unwrap()
};
assert_eq!(over(&keep), Some(stored.len() as u64));
assert_eq!(over(&[]), Some(incoming.len() as u64));
}
fn entry(key: &str, value: Value) -> HostEntry {
HostEntry {
key: key.into(),
value,
keep_existing: false,
}
}
fn text(value: &str) -> Value {
Value::variant(Type::Str, Value::Str(value.into()))
}
#[test]
fn the_plan_checks_run_in_order() {
let (a, b, c) = (
Checksum::from_bytes([1; 32]),
Checksum::from_bytes([2; 32]),
Checksum::from_bytes([3; 32]),
);
let targets = [a, b];
let sig = || entry("ostree.gpgsigs", text("x"));
let bare = |key: &str| entry(key, Value::U32(1));
let refused = |metadata: Vec<(Checksum, Vec<HostEntry>)>, needle: &str| match check_plan(
&targets, metadata,
) {
Err(Failure::Internal(Error::InvalidInput(m))) => {
assert!(m.contains(needle), "{needle}: {m}")
}
Err(_) => panic!("{needle}: another failure"),
Ok(_) => panic!("{needle}: the plan passed"),
};
let passed = |metadata| match check_plan(&targets, metadata) {
Ok(plan) => plan,
Err(_) => panic!("the plan was refused"),
};
let plan = passed(vec![
(b, Vec::new()),
(a, vec![entry("", text("empty key"))]),
]);
assert_eq!(plan.len(), 1);
assert_eq!(plan[0].0, 0);
assert_eq!(plan[0].1, [entry("", text("empty key"))]);
assert!(passed(Vec::new()).is_empty());
refused(vec![(c, vec![sig()])], "no ref update names");
refused(vec![(c, Vec::new())], "no ref update names");
refused(vec![(a, Vec::new()), (a, Vec::new())], "in two tuples");
refused(vec![(a, Vec::new()), (a, vec![sig()])], "in two tuples");
refused(vec![(a, vec![sig()]), (c, Vec::new())], "signature key");
refused(
vec![(c, Vec::new()), (a, vec![sig()])],
"no ref update names",
);
refused(vec![(a, vec![bare("k"), sig()])], "not a variant");
refused(vec![(a, vec![sig(), bare("k")])], "signature key");
refused(
vec![(a, vec![entry("k", text("x")), bare("k")])],
"two times",
);
refused(vec![(a, vec![bare("ostree.sign.dummy")])], "signature key");
for key in SIGNATURE_KEYS {
refused(vec![(b, vec![entry(key, text("x"))])], "signature key");
}
}
#[test]
fn the_size_bound_holds_when_the_offsets_grow() {
let blobs: Vec<Vec<u8>> = (0..200u32).map(|i| i.to_le_bytes().to_vec()).collect();
let half = blobs.len() / 2;
let refs: Vec<&[u8]> = blobs.iter().map(Vec::as_slice).collect();
let stored = serialized(&signed(&refs[..half]));
let incoming = serialized(&signed(&refs[half..]));
let signature = vec![7u8; 300];
let signatures: [(&str, &[u8]); 1] = [(KEY, &signature)];
let mut all = refs.clone();
all.push(&signature);
let written = serialized(&signed(&all)).len() as u64;
let bound = 16 * (stored.len() + incoming.len()) as u64
+ signature.len() as u64
+ 8
+ 64 * SIGNATURE_KEYS.len() as u64;
assert!(bound >= written, "bound {bound} < written {written}");
assert_eq!(
size_over(
written - 1,
Some(&stored),
Some(&incoming),
&signatures,
None,
&[],
)
.unwrap(),
Some(written)
);
}
#[test]
fn the_server_commit_search_gets_the_bytes_with_no_copy() {
use crate::sign::DummySigner;
use crate::verify::trust::tests::ThreadRecorder;
let scratch = Scratch::new("server-commit");
let recorder = ThreadRecorder::new("ostree.sign.dummy");
let server = || {
Arc::new(
ServerSigner::new(
Box::new(DummySigner::new(b"k".to_vec())),
Box::new(recorder.clone()),
)
.unwrap(),
)
};
let signers = [server(), server()];
let payload = Arc::new(b"commit".to_vec());
ostrya_rt::block_on(async {
let repo = Repo::create(
&scratch.0.join("repo"),
crate::CreateOptions::new(crate::RepoMode::Archive),
)
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let commit = Checksum::from_bytes([1; 32]);
assert!(
sign_server_commit(&repo, &txn, commit, &payload, &signers)
.await
.is_ok()
);
txn.abort().await.unwrap();
});
drop(scratch);
recorder.assert_one_foreign_call();
recorder.assert_no_copy_of(&payload);
}
#[test]
fn a_build_error_of_the_server_is_internal() {
let scratch = Scratch::new("build-error");
let path = scratch.0.join("repo");
ostrya_rt::block_on(async {
Repo::create(&path, crate::CreateOptions::new(crate::RepoMode::BareUser))
.await
.unwrap();
let mut config = std::fs::read_to_string(path.join("config")).unwrap();
config.push_str("[ex-ostrya]\ngenerate-composefs=true\n");
std::fs::write(path.join("config"), config).unwrap();
let repo = Repo::open(&path).await.unwrap();
let txn = repo.transaction().await.unwrap();
let digest = Value::variant(Type::array(Type::Byte), Value::Bytes(vec![0x5a; 32]));
let commit = Commit {
metadata: Value::Array(vec![Value::Tuple(vec![
Value::Str("ostree.composefs.digest.v0".into()),
digest,
])]),
parent: None,
related: Vec::new(),
subject: "absent tree".into(),
body: String::new(),
timestamp: 0,
root_dirtree: Checksum::from_bytes([2; 32]),
root_dirmeta: Checksum::from_bytes([3; 32]),
};
let checksum = txn
.write_metadata(ObjectType::Commit, None, &commit.serialize().unwrap())
.await
.unwrap();
assert!(matches!(
build_images(&txn, &[checksum]).await,
Err(Failure::Internal(_))
));
txn.abort().await.unwrap();
});
}
}