use std::marker::PhantomData;
use std::path::PathBuf;
use ostrya_core::KeyFile;
use super::typed::{OutputOf, ValueOf, lists, str_eq};
use super::value::{
ConfigPath, Value, ValueError, decode_string, encode_string, encode_string_list, value_error,
};
use super::{
Group, Key, KeyOrigin, KeyPath, Overrides, RemoteFile, RemoteSource, RepoConfig, SingleKey,
TextInEffect, client, key, remote, trust,
};
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Lookup<V> {
Forced(V),
File(V),
Fallback(V),
Default(V),
}
impl<V> Lookup<V> {
pub fn value(&self) -> &V {
match self {
Lookup::Forced(v) | Lookup::File(v) | Lookup::Fallback(v) | Lookup::Default(v) => v,
}
}
pub fn into_value(self) -> V {
match self {
Lookup::Forced(v) | Lookup::File(v) | Lookup::Fallback(v) | Lookup::Default(v) => v,
}
}
}
pub struct GroupRef<G: Group> {
name: String,
group: PhantomData<fn() -> G>,
}
impl<G: Group> GroupRef<G> {
pub fn new(name: impl Into<String>) -> std::result::Result<GroupRef<G>, ValueError> {
let name = name.into();
if name.is_empty() {
return Err(ValueError::new("is empty"));
}
Ok(GroupRef {
name,
group: PhantomData,
})
}
pub fn name(&self) -> &str {
&self.name
}
}
impl<G: Group> Clone for GroupRef<G> {
fn clone(&self) -> GroupRef<G> {
GroupRef {
name: self.name.clone(),
group: PhantomData,
}
}
}
impl<G: Group> std::fmt::Debug for GroupRef<G> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GroupRef")
.field("group", &G::NAME)
.field("name", &self.name)
.finish()
}
}
impl<G: Group> PartialEq for GroupRef<G> {
fn eq(&self, other: &GroupRef<G>) -> bool {
self.name == other.name
}
}
impl<G: Group> Eq for GroupRef<G> {}
impl<G: Group> std::hash::Hash for GroupRef<G> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl<G: Group> Value for GroupRef<G> {
fn parse(raw: &str) -> std::result::Result<GroupRef<G>, ValueError> {
GroupRef::new(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(&self.name)
}
}
pub struct Section<'a, G: Group> {
keyfile: &'a KeyFile,
header: &'a str,
file: Option<&'a str>,
group: PhantomData<fn() -> G>,
}
impl<G: Group> Clone for Section<'_, G> {
fn clone(&self) -> Self {
Section {
keyfile: self.keyfile,
header: self.header,
file: self.file,
group: PhantomData,
}
}
}
impl<G: Group> std::fmt::Debug for Section<'_, G> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Section")
.field("header", &self.header)
.field("file", &self.file)
.finish()
}
}
impl<'a, G: Group> Section<'a, G> {
pub fn name(&self) -> &'a str {
let header: &'a str = self.header;
header
.split_once('"')
.and_then(|(_, rest)| rest.strip_suffix('"'))
.unwrap_or_default()
}
pub fn get<K: Key<G>>(&self) -> Result<K::Output> {
read_in_effect::<G, K>(self.keyfile, self.header, None)
}
pub fn file_value<K: Key<G>>(&self) -> Result<Option<K::Value>> {
read_file::<G, K>(self.keyfile, self.header)
}
pub fn lookup<K: Key<G>>(&self) -> Result<Option<Lookup<K::Value>>> {
lookup::<G, K>(self.keyfile, self.header, None)
}
pub fn refuse_unknown_keys(&self) -> Result<()> {
refuse_unknown_keys::<G>(self.keyfile, self.header)
}
pub(crate) fn at(keyfile: &'a KeyFile, header: &'a str) -> Section<'a, G> {
Section {
keyfile,
header,
file: None,
group: PhantomData,
}
}
pub(crate) fn raw_value<K: Key<G>>(&self) -> Option<&'a str> {
const {
assert!(
lists(G::KEYS, K::NAME),
"the key is not in the key list of its group"
)
};
let keyfile: &'a KeyFile = self.keyfile;
keyfile.get_value(self.header, K::NAME)
}
pub(crate) fn contains<K: Key<G>>(&self) -> bool {
self.raw_value::<K>().is_some()
}
pub(crate) fn header(&self) -> &'a str {
self.header
}
pub(crate) fn key_names(&self) -> impl Iterator<Item = &'a str> + use<'a, G> {
let keyfile: &'a KeyFile = self.keyfile;
keyfile.keys(self.header)
}
pub(crate) fn key_path<K>(&self) -> Result<Option<KeyPath>>
where
K: Key<G, Value = ConfigPath>,
{
Ok(self
.file_value::<K>()?
.map(|path| self.key_path_of(path.into_string())))
}
fn key_path_of(&self, value: String) -> KeyPath {
KeyPath {
value: PathBuf::from(value),
origin: match self.file {
None => KeyOrigin::Config,
Some(_) => KeyOrigin::RemotesFile,
},
}
}
#[cfg(feature = "verify-gpg")]
pub(crate) fn gpgkeypath_paths(&self) -> Result<Vec<KeyPath>>
where
remote::GpgKeyPath: Key<G, Value = super::KeyringPaths, Output = super::KeyringPaths>,
{
Ok(self
.get::<remote::GpgKeyPath>()?
.into_entries()
.into_iter()
.map(|entry| self.key_path_of(entry))
.collect())
}
pub(crate) fn verification_key(&self, engine: &str) -> Result<Option<String>>
where
remote::VerificationEd25519Key: Key<G, Output = Option<String>>,
remote::VerificationSpkiKey: Key<G, Output = Option<String>>,
{
match engine {
"ed25519" => self.get::<remote::VerificationEd25519Key>(),
"spki" => self.get::<remote::VerificationSpkiKey>(),
_ => Ok(None),
}
}
pub(crate) fn verification_file(&self, engine: &str) -> Result<Option<KeyPath>>
where
remote::VerificationEd25519File: Key<G, Value = ConfigPath>,
remote::VerificationSpkiFile: Key<G, Value = ConfigPath>,
{
match engine {
"ed25519" => self.key_path::<remote::VerificationEd25519File>(),
"spki" => self.key_path::<remote::VerificationSpkiFile>(),
_ => Ok(None),
}
}
}
impl<'a> Section<'a, remote::Group> {
pub fn source(&self) -> RemoteSource<'a> {
match self.file {
None => RemoteSource::Config,
Some(file) => RemoteSource::File(file),
}
}
pub fn mirrored_collection_ids(&self) -> Result<Vec<String>> {
let Some(ids) = self.file_value::<remote::MirroredCollectionIds>()? else {
return Ok(Vec::new());
};
let ids = ids.into_ids();
if let Some(own) = self.get::<remote::CollectionId>()?
&& let Some(id) = ids.iter().find(|id| **id == own)
{
return Err(Error::InvalidFormat(format!(
"[{}] {} holds '{id}', the collection-id of the remote",
self.header,
<remote::MirroredCollectionIds as Key<remote::Group>>::NAME
)));
}
Ok(ids)
}
pub(crate) fn check(&self) -> Result<()> {
remote::check_file(self.keyfile, self.header)?;
self.mirrored_collection_ids().map(drop)
}
pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
let text = if key == <remote::MirroredCollectionIds as Key<remote::Group>>::NAME {
if !self.contains::<remote::MirroredCollectionIds>() {
return Ok(TextInEffect::NoKey);
}
Some(encode_string_list(&self.mirrored_collection_ids()?))
} else {
match remote::text_in_effect(self.keyfile, self.header, None, key) {
Some(text) => text?,
None => self.keyfile.get_value(self.header, key).map(str::to_owned),
}
};
Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
}
}
impl Section<'_, client::Group> {
pub fn allow_unsigned(&self) -> Result<bool> {
match self.get::<client::AllowUnsigned>()? {
Some(value) => Ok(value),
None => Ok(self.get::<client::Verify>()?.is_none()),
}
}
pub(crate) fn refuse_removed_keys(&self) -> Result<()> {
if self.keyfile.get_value(self.header, "collection").is_some() {
return Err(Error::InvalidFormat(format!(
"[{}] holds the removed key 'collection'; an allow item or a deny item \
names the refs of a collection as @ID:PATTERN",
self.header
)));
}
Ok(())
}
pub(crate) fn check(&self) -> Result<()> {
self.refuse_removed_keys()?;
client::check_file(self.keyfile, self.header)
}
pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
let text = if key == <client::AllowUnsigned as Key<client::Group>>::NAME {
Some(self.allow_unsigned()?.format())
} else {
match client::text_in_effect(self.keyfile, self.header, None, key) {
Some(text) => text?,
None => self.keyfile.get_value(self.header, key).map(str::to_owned),
}
};
Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
}
}
pub(crate) const TRUST_ENGINES: &[&str] = &["ed25519", "spki"];
pub(crate) fn verification_engine(key: &str) -> Option<&str> {
let rest = key.strip_prefix("verification-")?;
rest.strip_suffix("-key")
.or_else(|| rest.strip_suffix("-file"))
}
impl Section<'_, trust::Group> {
pub(crate) fn refuse_foreign_keys(&self) -> Result<()> {
let header = self.header;
for key in self.key_names() {
if <trust::Group as Group>::KEYS.contains(&key) {
continue;
}
let reason = match key {
"gpg-verify-summary" | "sign-verify-summary" => {
"a trust group sets a commit policy alone".to_owned()
}
_ => match verification_engine(key) {
Some(engine) if !TRUST_ENGINES.contains(&engine) => {
format!("'{engine}' is not ed25519 or spki")
}
_ => {
return Err(Error::InvalidFormat(format!(
"[{header}] holds the unknown key '{key}'"
)));
}
},
};
return Err(Error::InvalidFormat(format!(
"[{header}] holds '{key}', and {reason}"
)));
}
Ok(())
}
pub(crate) fn check(&self) -> Result<()> {
self.refuse_foreign_keys()?;
trust::check_file(self.keyfile, self.header)
}
pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
let text = match trust::text_in_effect(self.keyfile, self.header, None, key) {
Some(text) => text?,
None => self.keyfile.get_value(self.header, key).map(str::to_owned),
};
Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
}
}
impl Section<'_, key::Group> {
pub(crate) fn check(&self) -> Result<()> {
key::check_file(self.keyfile, self.header)
}
pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
let text = match key::text_in_effect(self.keyfile, self.header, None, key) {
Some(text) => text?,
None => self.keyfile.get_value(self.header, key).map(str::to_owned),
};
Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
}
}
impl RepoConfig {
pub fn get<K>(&self) -> Result<OutputOf<K>>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
read_in_effect::<K::Group, K>(
&self.keyfile,
<K as SingleKey>::Group::NAME,
Some(&self.overrides),
)
}
pub fn file_value<K>(&self) -> Result<Option<ValueOf<K>>>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
read_file::<K::Group, K>(&self.keyfile, <K as SingleKey>::Group::NAME)
}
pub fn lookup<K>(&self) -> Result<Option<Lookup<ValueOf<K>>>>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
lookup::<K::Group, K>(
&self.keyfile,
<K as SingleKey>::Group::NAME,
Some(&self.overrides),
)
}
pub fn section<G: Group>(&self, name: &str) -> Option<Section<'_, G>> {
const { assert!(G::NAMED, "a single group has no section") };
if !is_section_name(name) {
return None;
}
let header = section_header::<G>(name);
self.sources::<G>().find_map(|(keyfile, file)| {
let header = keyfile.group_name(&header)?;
Some(Section {
keyfile,
header,
file,
group: PhantomData,
})
})
}
pub fn sections<G: Group>(&self) -> impl Iterator<Item = Section<'_, G>> {
const { assert!(G::NAMED, "a single group has no section") };
self.sources::<G>().flat_map(|(keyfile, file)| {
keyfile.groups().filter_map(move |header| {
section_name::<G>(header)?;
Some(Section {
keyfile,
header,
file,
group: PhantomData,
})
})
})
}
pub fn resolve<G: Group>(&self, reference: &GroupRef<G>) -> Result<Section<'_, G>> {
self.section::<G>(reference.name()).ok_or_else(|| {
Error::InvalidFormat(format!(
"the config has no [{}] group",
section_header::<G>(reference.name())
))
})
}
pub fn refuse_unknown_keys<G: Group>(&self) -> Result<()> {
if !G::CLOSED {
return Ok(());
}
if !G::NAMED {
return refuse_unknown_keys::<G>(&self.keyfile, G::NAME);
}
self.keyfile
.groups()
.filter(|header| section_name::<G>(header).is_some())
.try_for_each(|header| refuse_unknown_keys::<G>(&self.keyfile, header))
}
fn sources<G: Group>(&self) -> impl Iterator<Item = (&KeyFile, Option<&str>)> {
let is_remote = const { str_eq(G::NAME, <remote::Group as Group>::NAME) };
let files: &[RemoteFile] = if is_remote { &self.remote_files } else { &[] };
std::iter::once((&self.keyfile, None)).chain(
files
.iter()
.map(|file| (&file.keyfile, Some(file.name.as_str()))),
)
}
}
pub(crate) fn section_header<G: Group>(name: &str) -> String {
format!("{} \"{name}\"", G::NAME)
}
pub(crate) fn section_name<G: Group>(header: &str) -> Option<&str> {
let name = header
.strip_prefix(G::NAME)?
.strip_prefix(" \"")?
.strip_suffix('"')?;
is_section_name(name).then_some(name)
}
fn is_section_name(name: &str) -> bool {
!name.is_empty() && !name.contains('"')
}
pub(crate) fn refuse_unknown_keys<G: Group>(keyfile: &KeyFile, header: &str) -> Result<()> {
if !G::CLOSED {
return Ok(());
}
match keyfile.keys(header).find(|key| !G::KEYS.contains(key)) {
Some(key) => Err(Error::InvalidFormat(format!(
"[{header}] holds the unknown key '{key}'"
))),
None => Ok(()),
}
}
pub(crate) fn read_file<G: Group, K: Key<G>>(
keyfile: &KeyFile,
header: &str,
) -> Result<Option<K::Value>> {
const {
assert!(
lists(G::KEYS, K::NAME),
"the key is not in the key list of its group"
)
};
let Some(raw) = keyfile.get_value(header, K::NAME) else {
return Ok(None);
};
K::Value::parse(raw)
.map(Some)
.map_err(|err| value_error(header, K::NAME, raw, err))
}
fn lookup<G: Group, K: Key<G>>(
keyfile: &KeyFile,
header: &str,
overrides: Option<&Overrides>,
) -> Result<Option<Lookup<K::Value>>> {
if let Some(raw) = overrides.and_then(|o| o.forced(header, K::NAME)) {
return parse_text::<G, K>(header, raw).map(|v| Some(Lookup::Forced(v)));
}
if let Some(value) = read_file::<G, K>(keyfile, header)? {
return Ok(Some(Lookup::File(value)));
}
if let Some(raw) = overrides.and_then(|o| o.fallback_of(header, K::NAME)) {
return parse_text::<G, K>(header, raw).map(|v| Some(Lookup::Fallback(v)));
}
Ok(K::default_value().map(Lookup::Default))
}
pub(crate) fn lookup_text<G: Group, K: Key<G>>(
keyfile: &KeyFile,
header: &str,
overrides: Option<&Overrides>,
) -> Result<Option<String>> {
Ok(lookup::<G, K>(keyfile, header, overrides)?.map(|found| found.into_value().format()))
}
fn parse_text<G: Group, K: Key<G>>(header: &str, raw: &str) -> Result<K::Value> {
K::Value::parse(raw).map_err(|err| value_error(header, K::NAME, raw, err))
}
fn read_in_effect<G: Group, K: Key<G>>(
keyfile: &KeyFile,
header: &str,
overrides: Option<&Overrides>,
) -> Result<K::Output> {
let value = lookup::<G, K>(keyfile, header, overrides)?.map(Lookup::into_value);
K::output(value).ok_or_else(|| Error::InvalidFormat(format!("[{header}] has no {}", K::NAME)))
}