use std::fmt;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::time::Duration;
use ostrya_core::config::relative_with_parent;
use crate::config::{self, ConfigPath, Key, KeyPath, RepoConfig, Section, SectionExt as _, io_of};
use crate::error::{Error, Result};
#[cfg(feature = "push")]
use crate::fetch::{BasicAuth, BearerToken};
use crate::fetch::{ClientIdentity, FetcherOptions, LowSpeed, Proxy, TrustRoots};
use crate::remote::{self, Endpoint, SshAddress, SshOptions};
use crate::repo::Repo;
use crate::repo_fs::{FsError, Named, Reason, open_named};
const FILE_CAP: u64 = 1 << 20;
const PULL_RETRIES: u32 = 5;
const PULL_OUTSTANDING: usize = 8;
const DEFAULT_LOW_SPEED_LIMIT: u32 = 1000;
const DEFAULT_LOW_SPEED_TIME: Duration = Duration::from_secs(30);
#[derive(Clone, Default, PartialEq, Eq)]
pub struct EndpointOverrides {
pub url: Option<String>,
pub push_token_file: Option<PathBuf>,
pub push_user: Option<String>,
pub tls_ca_path: Option<PathBuf>,
pub tls_client_cert_path: Option<PathBuf>,
pub tls_client_key_path: Option<PathBuf>,
pub ssh_command: Option<Vec<String>>,
pub remote_command: Option<String>,
pub allow_cleartext_credentials: bool,
pub http_headers: Vec<(String, String)>,
pub max_retries: Option<u32>,
pub low_speed_limit_bytes: Option<u32>,
pub low_speed_time: Option<Duration>,
pub s3_region: Option<String>,
pub s3_endpoint: Option<String>,
pub s3_addressing: Option<String>,
pub s3_profile: Option<String>,
}
impl fmt::Debug for EndpointOverrides {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let EndpointOverrides {
url,
push_token_file,
push_user,
tls_ca_path,
tls_client_cert_path,
tls_client_key_path,
ssh_command,
remote_command,
allow_cleartext_credentials,
http_headers,
max_retries,
low_speed_limit_bytes,
low_speed_time,
s3_region,
s3_endpoint,
s3_addressing,
s3_profile,
} = self;
let headers: Vec<(&str, &str)> = http_headers
.iter()
.map(|(name, _)| (name.as_str(), "<redacted>"))
.collect();
f.debug_struct("EndpointOverrides")
.field("url", &url.as_deref().map(remote::without_userinfo))
.field("push_token_file", push_token_file)
.field("push_user", push_user)
.field("tls_ca_path", tls_ca_path)
.field("tls_client_cert_path", tls_client_cert_path)
.field("tls_client_key_path", tls_client_key_path)
.field("ssh_command", ssh_command)
.field("remote_command", remote_command)
.field("allow_cleartext_credentials", allow_cleartext_credentials)
.field("http_headers", &headers)
.field("max_retries", max_retries)
.field("low_speed_limit_bytes", low_speed_limit_bytes)
.field("low_speed_time", low_speed_time)
.field("s3_region", s3_region)
.field(
"s3_endpoint",
&s3_endpoint.as_deref().map(remote::without_userinfo),
)
.field("s3_addressing", s3_addressing)
.field("s3_profile", s3_profile)
.finish()
}
}
pub(crate) fn neither_ssh_nor_http(operation: &str) -> Error {
Error::Unsupported(format!(
"{operation} takes an ssh or an HTTP endpoint, and this endpoint is neither"
))
}
#[cfg(feature = "s3")]
pub(crate) type S3Environment = remote::s3::Environment;
#[cfg(not(feature = "s3"))]
pub(crate) type S3Environment = ();
pub async fn resolve_pull(
repo: Option<&Repo>,
remote: &str,
overrides: EndpointOverrides,
) -> Result<Endpoint> {
resolve_pull_in(repo, remote, overrides, &S3Environment::default()).await
}
#[cfg_attr(not(feature = "s3"), allow(unused_variables))]
pub(crate) async fn resolve_pull_in(
repo: Option<&Repo>,
remote: &str,
overrides: EndpointOverrides,
env: &S3Environment,
) -> Result<Endpoint> {
let mut o = overrides;
let section = repo.and_then(|repo| repo.config().section::<config::remote::Group>(remote));
if let Some(name) = push_field(&o) {
return Err(Error::InvalidInput(format!(
"{name} applies to a push, and this is a pull"
)));
}
let address = pull_address(section.as_ref(), remote, o.url.take())?;
check_s3_keys(remote, section.as_ref())?;
let endpoint = match address {
PullAddress::Endpoint(endpoint) => endpoint,
PullAddress::Local => {
return Err(Error::Pull(format!(
"the pull address of remote '{remote}' is a local repository, which has no \
endpoint; Repo::pull reads it"
)));
}
PullAddress::S3(address) => {
#[cfg(feature = "s3")]
return Box::pin(pull_s3(remote, section.as_ref(), &address, o, env, repo)).await;
#[cfg(not(feature = "s3"))]
return Err(Error::Unsupported(format!(
"the pull address '{}' is an s3:// address, and this build of ostrya has no S3 \
support: turn on the feature s3 of ostrya",
remote::without_userinfo(&address)
)));
}
};
match endpoint {
Endpoint::Http(http) => pull_http(remote, section.as_ref(), http, o, repo).await,
Endpoint::Ssh { address, .. } => {
if let Some(name) = s3_field(&o) {
return Err(Error::InvalidInput(format!(
"{name} applies to a pull from an s3:// address, and '{}' is an ssh address",
address.without_user()
)));
}
if let Some(name) = http_field(&o) {
return Err(Error::InvalidInput(format!(
"{name} applies to a pull over HTTP, and '{}' is an ssh address",
address.without_user()
)));
}
let (config_command, remote_command) = match §ion {
Some(section) => (
section.get::<config::remote::SshCommand>()?,
match o.remote_command {
Some(command) => Some(command),
None => section.get::<config::remote::SendCommand>()?,
},
),
None => (None, o.remote_command),
};
Ok(Endpoint::Ssh {
address,
options: SshOptions {
command: o.ssh_command,
config_command,
remote_command,
},
})
}
_ => Err(neither_ssh_nor_http("a pull")),
}
}
#[allow(clippy::large_enum_variant)]
enum PullAddress {
Endpoint(Endpoint),
Local,
S3(String),
}
fn pull_address(
section: Option<&Section<'_, config::remote::Group>>,
remote: &str,
url: Option<String>,
) -> Result<PullAddress> {
if let Some(url) = url {
return parse_pull_address(remote, &url, address_kind(&url));
}
let section =
section.ok_or_else(|| Error::Pull(format!("no remote '{remote}' is configured")))?;
if let Some(pull_url) = section.get::<config::remote::PullUrl>()? {
return parse_pull_address(remote, &pull_url, address_kind(&pull_url));
}
let Some(url) = section.get::<config::remote::Url>()? else {
return Err(Error::Pull(format!(
"remote '{remote}' has no pull-url and no url"
)));
};
match address_kind(&url) {
AddressKind::S3 => Err(Error::Pull(format!(
"remote '{remote}': url '{}' is an s3:// address; the port reads an s3:// \
address from pull-url alone",
remote::without_userinfo(&url)
))),
AddressKind::Ssh => Err(Error::Pull(format!(
"remote '{remote}': url '{}' is an ssh address; the port reads an ssh \
address from pull-url alone",
remote::without_userinfo(&url)
))),
kind => parse_pull_address(remote, &url, kind),
}
}
pub fn pull_address_kind(
config: Option<&RepoConfig>,
remote: &str,
url: Option<&str>,
) -> Option<AddressKind> {
let section = config.and_then(|config| config.section::<config::remote::Group>(remote));
match pull_address(section.as_ref(), remote, url.map(str::to_owned)) {
Ok(PullAddress::S3(_)) => Some(AddressKind::S3),
Ok(PullAddress::Local) => Some(AddressKind::Local),
Ok(PullAddress::Endpoint(Endpoint::Ssh { .. })) => Some(AddressKind::Ssh),
Ok(PullAddress::Endpoint(_)) => Some(AddressKind::Http),
Err(_) => None,
}
}
pub fn pull_address_is_s3(
config: Option<&RepoConfig>,
remote: &str,
url: Option<&str>,
) -> Option<bool> {
pull_address_kind(config, remote, url).map(|kind| kind == AddressKind::S3)
}
fn is_s3(value: &str) -> bool {
value.starts_with("s3://")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AddressKind {
Local,
S3,
Ssh,
Http,
}
pub fn address_kind(value: &str) -> AddressKind {
if value
.as_bytes()
.get(..5)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case(b"file:"))
{
AddressKind::Local
} else if is_s3(value) {
AddressKind::S3
} else if value.starts_with("ssh://") || !value.contains("://") {
AddressKind::Ssh
} else {
AddressKind::Http
}
}
fn parse_pull_address(remote: &str, value: &str, kind: AddressKind) -> Result<PullAddress> {
match kind {
AddressKind::Local => {
local_path(remote, value)?;
Ok(PullAddress::Local)
}
AddressKind::S3 => Ok(PullAddress::S3(value.to_owned())),
AddressKind::Http => Ok(PullAddress::Endpoint(Endpoint::Http(FetcherOptions::new(
value,
)))),
AddressKind::Ssh => {
let address = SshAddress::parse(value).map_err(|e| match e {
remote::Error::InvalidInput(msg) => Error::InvalidInput(msg),
other => Error::Remote(other),
})?;
Ok(PullAddress::Endpoint(Endpoint::Ssh {
address,
options: SshOptions::default(),
}))
}
}
}
pub(crate) fn local_pull_path(
config: &RepoConfig,
remote: &str,
o: &EndpointOverrides,
) -> Result<Option<PathBuf>> {
if let Some(name) = push_field(o) {
return Err(Error::InvalidInput(format!(
"{name} applies to a push, and this is a pull"
)));
}
let section = config.section::<config::remote::Group>(remote);
let address = match (&o.url, §ion) {
(Some(url), _) => Some(url.clone()),
(None, Some(section)) => match section.get::<config::remote::PullUrl>()? {
Some(pull_url) => Some(pull_url),
None => section.get::<config::remote::Url>()?,
},
(None, None) => None,
};
let Some(address) = address else {
return Ok(None);
};
if address_kind(&address) != AddressKind::Local {
return Ok(None);
}
let rest = local_path(remote, &address)?;
check_s3_keys(remote, section.as_ref())?;
let field = http_field(o)
.map(|name| (name, "a pull over HTTP"))
.or_else(|| s3_field(o).map(|name| (name, "a pull from an s3:// address")))
.or_else(|| ssh_field(o, "send-command").map(|name| (name, "a pull over ssh")));
if let Some((name, transport)) = field {
return Err(Error::InvalidInput(format!(
"{name} applies to {transport}, and the pull address of remote '{remote}' is a \
local repository"
)));
}
Ok(Some(PathBuf::from(rest)))
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub(crate) enum Origin {
Local(PathBuf),
Endpoint(Endpoint),
}
pub(crate) async fn resolve_origin(
repo: &Repo,
remote: &str,
overrides: EndpointOverrides,
) -> Result<Origin> {
match local_pull_path(repo.config(), remote, &overrides)? {
Some(path) => Ok(Origin::Local(path)),
None => resolve_pull(Some(repo), remote, overrides)
.await
.map(Origin::Endpoint),
}
}
fn local_path<'a>(remote: &str, address: &'a str) -> Result<&'a str> {
let refused = |reason: &str| {
Error::Pull(format!(
"remote '{remote}': the file address '{}' {reason}; a local repository is file:// \
followed by an absolute path",
remote::without_userinfo(address)
))
};
let Some(rest) = address[5..].strip_prefix("//") else {
return Err(refused("does not start with file://"));
};
if rest.is_empty() {
return Err(refused("has no path"));
}
if !rest.starts_with('/') {
return Err(refused("names a host"));
}
if rest.contains(['%', '?', '#']) {
return Err(refused("holds '%', '?', or '#'"));
}
Ok(rest)
}
fn push_field(o: &EndpointOverrides) -> Option<&'static str> {
let set = [
("push-token-file", o.push_token_file.is_some()),
("push-user", o.push_user.is_some()),
];
set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}
fn ssh_field(o: &EndpointOverrides, command_key: &'static str) -> Option<&'static str> {
let set = [
("ssh-command", o.ssh_command.is_some()),
(command_key, o.remote_command.is_some()),
];
set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}
fn check_s3_keys(remote: &str, section: Option<&Section<'_, config::remote::Group>>) -> Result<()> {
let Some(section) = section else {
return Ok(());
};
let keys = [
("s3-region", section.get::<config::remote::S3Region>()?),
("s3-endpoint", section.get::<config::remote::S3Endpoint>()?),
(
"s3-addressing",
section.get::<config::remote::S3Addressing>()?,
),
("s3-profile", section.get::<config::remote::S3Profile>()?),
];
let Some((name, _)) = keys.iter().find(|(_, value)| value.is_some()) else {
return Ok(());
};
let s3 = |value: Option<String>| value.is_some_and(|value| is_s3(&value));
if s3(section.get::<config::remote::PullUrl>()?)
|| s3(section.get::<config::remote::PushUrl>()?)
{
return Ok(());
}
Err(Error::Pull(format!(
"remote '{remote}': {name} applies to an s3:// address, and neither pull-url nor \
push-url holds one"
)))
}
fn s3_field(o: &EndpointOverrides) -> Option<&'static str> {
let set = [
("s3-region", o.s3_region.is_some()),
("s3-endpoint", o.s3_endpoint.is_some()),
("s3-addressing", o.s3_addressing.is_some()),
("s3-profile", o.s3_profile.is_some()),
];
set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}
async fn pull_http(
remote: &str,
section: Option<&Section<'_, config::remote::Group>>,
mut http: FetcherOptions,
o: EndpointOverrides,
repo: Option<&Repo>,
) -> Result<Endpoint> {
if let Some(name) = ssh_field(&o, "send-command") {
return Err(Error::InvalidInput(format!(
"{name} applies to a pull over ssh, and this pull runs over HTTP"
)));
}
if let Some(name) = s3_field(&o) {
return Err(Error::InvalidInput(format!(
"{name} applies to a pull from an s3:// address, and this pull runs over HTTP"
)));
}
PullHttp::read(remote, section, o)?
.apply(&mut http, repo)
.await?;
Ok(Endpoint::Http(http))
}
#[cfg(feature = "s3")]
async fn pull_s3(
remote: &str,
section: Option<&Section<'_, config::remote::Group>>,
address: &str,
o: EndpointOverrides,
env: &S3Environment,
repo: Option<&Repo>,
) -> Result<Endpoint> {
if let Some(name) = ssh_field(&o, "send-command") {
return Err(Error::InvalidInput(format!(
"{name} applies to a pull over ssh, and this pull reads an s3:// address"
)));
}
let refusals = S3Refusals {
invalid: Error::InvalidInput,
remote: Error::Pull,
};
let (settings, http) = s3_settings(remote, section, o, refusals)?;
s3_resolve(address, &settings, http, env, refusals, repo).await
}
#[cfg(feature = "s3")]
#[derive(Clone, Copy)]
struct S3Refusals {
invalid: fn(String) -> Error,
remote: fn(String) -> Error,
}
#[cfg(feature = "s3")]
impl S3Refusals {
fn resolve_error(self, e: remote::Error) -> Error {
match e {
remote::Error::InvalidInput(msg) => (self.invalid)(msg),
remote::Error::Io(e) => Error::Io(e),
other => Error::Remote(other),
}
}
}
#[cfg(feature = "s3")]
fn s3_settings(
remote: &str,
section: Option<&Section<'_, config::remote::Group>>,
mut o: EndpointOverrides,
refusals: S3Refusals,
) -> Result<(remote::s3::Settings, PullHttp)> {
use remote::s3::{Addressing, Settings};
let region = or_key(o.s3_region.take(), section, |s| {
Ok(s.get::<config::remote::S3Region>()?)
})?;
let endpoint = or_key(o.s3_endpoint.take(), section, |s| {
Ok(s.get::<config::remote::S3Endpoint>()?)
})?;
let addressing = or_key(o.s3_addressing.take(), section, |s| {
Ok(s.get::<config::remote::S3Addressing>()?)
})?;
let profile = or_key(o.s3_profile.take(), section, |s| {
Ok(s.get::<config::remote::S3Profile>()?)
})?;
let addressing = match addressing {
Some(name) => Some(Addressing::from_name(&name).ok_or_else(|| {
(refusals.invalid)(format!(
"s3-addressing '{name}' is neither path nor virtual"
))
})?),
None => None,
};
let settings = Settings {
region,
endpoint,
addressing,
profile,
};
let http = PullHttp::read(remote, section, o).map_err(|e| match e {
Error::Pull(msg) => (refusals.remote)(msg),
Error::InvalidInput(msg) => (refusals.invalid)(msg),
other => other,
})?;
Ok((settings, http))
}
#[cfg(feature = "s3")]
async fn s3_resolve(
address: &str,
settings: &remote::s3::Settings,
http: PullHttp,
env: &S3Environment,
refusals: S3Refusals,
repo: Option<&Repo>,
) -> Result<Endpoint> {
use remote::s3::S3Endpoint;
let mut endpoint = S3Endpoint::resolve(address, settings, env)
.await
.map_err(|e| refusals.resolve_error(e))?;
let url = endpoint.location.endpoint();
let cleartext = url
.get(..7)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("http://"));
if cleartext && !http.allow_cleartext_credentials {
return Err((refusals.invalid)(format!(
"the S3 endpoint '{url}' is http://, so the signature of each request would \
travel in cleartext: use https, or set allow-cleartext-credentials"
)));
}
http.apply(&mut endpoint.http, repo).await?;
Ok(Endpoint::S3(endpoint))
}
#[cfg(feature = "s3")]
fn or_key(
value: Option<String>,
section: Option<&Section<'_, config::remote::Group>>,
read: impl FnOnce(&Section<'_, config::remote::Group>) -> Result<Option<String>>,
) -> Result<Option<String>> {
match (value, section) {
(Some(value), _) => Ok(Some(value)),
(None, Some(section)) => read(section),
(None, None) => Ok(None),
}
}
struct PullHttp {
any_chain: bool,
ca_path: Option<KeyPath>,
client_files: Option<(KeyPath, KeyPath)>,
proxy: Proxy,
headers: Vec<(String, String)>,
allow_cleartext_credentials: bool,
max_retries: Option<u32>,
low_speed_limit_bytes: Option<u32>,
low_speed_time: Option<Duration>,
}
impl PullHttp {
fn read(
remote: &str,
section: Option<&Section<'_, config::remote::Group>>,
o: EndpointOverrides,
) -> Result<PullHttp> {
let mut any_chain = false;
let ca_path = match (
caller_path(config::remote::TlsCaPath::NAME, o.tls_ca_path)?,
section,
) {
(Some(path), _) => Some(path),
(None, Some(section)) if section.get::<config::remote::TlsPermissive>()? => {
any_chain = true;
None
}
(None, Some(section)) => section.key_path::<config::remote::TlsCaPath>()?,
(None, None) => None,
};
let cert =
path_or_key::<config::remote::TlsClientCertPath>(o.tls_client_cert_path, section)?;
let key = path_or_key::<config::remote::TlsClientKeyPath>(o.tls_client_key_path, section)?;
let client_files = match (cert, key) {
(Some(cert), Some(key)) => Some((cert, key)),
(None, None) => None,
_ => {
return Err(Error::Pull(format!(
"remote '{remote}': a client certificate needs both \
tls-client-cert-path and tls-client-key-path"
)));
}
};
let proxy = match section {
Some(section) => remote_proxy(remote, section)?,
None => Proxy::Environment,
};
Ok(PullHttp {
any_chain,
ca_path,
client_files,
proxy,
headers: o.http_headers,
allow_cleartext_credentials: o.allow_cleartext_credentials,
max_retries: o.max_retries,
low_speed_limit_bytes: o.low_speed_limit_bytes,
low_speed_time: o.low_speed_time,
})
}
async fn apply(self, http: &mut FetcherOptions, repo: Option<&Repo>) -> Result<()> {
if self.any_chain {
http.tls.roots = TrustRoots::DangerousAcceptAnyChain;
}
let files = EndpointFiles {
token: None,
ca: self.ca_path,
client: self.client_files,
}
.read(repo)
.await?;
if let Some(pem) = files.ca {
http.tls.roots = TrustRoots::Pem(pem);
}
http.tls.client_identity = files.client;
http.headers = self.headers;
http.allow_cleartext_credentials = self.allow_cleartext_credentials;
http.proxy = self.proxy;
http.max_retries = self.max_retries.unwrap_or(PULL_RETRIES);
http.max_outstanding = PULL_OUTSTANDING;
http.low_speed = low_speed(self.low_speed_limit_bytes, self.low_speed_time);
Ok(())
}
}
#[cfg(feature = "push")]
pub async fn resolve_push(
repo: Option<&Repo>,
remote_or_address: &str,
overrides: EndpointOverrides,
) -> Result<Endpoint> {
resolve_push_in(
repo,
remote_or_address,
overrides,
&S3Environment::default(),
)
.await
}
#[cfg(feature = "push")]
#[cfg_attr(not(feature = "s3"), allow(unused_variables))]
pub(crate) async fn resolve_push_in(
repo: Option<&Repo>,
remote_or_address: &str,
overrides: EndpointOverrides,
env: &S3Environment,
) -> Result<Endpoint> {
match checked_push(repo.map(Repo::config), remote_or_address, overrides)? {
CheckedPush::Ssh(address, options) => Ok(Endpoint::Ssh { address, options }),
CheckedPush::Http(push) => push.read_files(repo).await,
#[cfg(feature = "s3")]
CheckedPush::S3(push) => {
Box::pin(s3_resolve(
&push.address,
&push.settings,
push.http,
env,
push.refusals,
repo,
))
.await
}
}
}
#[cfg(feature = "push")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushKind {
Session,
Bucket,
}
#[cfg(feature = "push")]
pub fn check_push(
config: Option<&RepoConfig>,
remote_or_address: &str,
overrides: EndpointOverrides,
) -> Result<PushKind> {
match checked_push(config, remote_or_address, overrides)? {
CheckedPush::Ssh(address, options) => {
remote::PushSession::check(&Endpoint::Ssh { address, options })?;
Ok(PushKind::Session)
}
CheckedPush::Http(push) => {
remote::PushSession::check(&Endpoint::Http(push.http))?;
Ok(PushKind::Session)
}
#[cfg(feature = "s3")]
CheckedPush::S3(push) => {
remote::s3::Address::parse(&push.address)
.map_err(|e| push.refusals.resolve_error(e))?;
Ok(PushKind::Bucket)
}
}
}
#[cfg(feature = "push")]
#[allow(clippy::large_enum_variant)]
enum CheckedPush {
Ssh(SshAddress, SshOptions),
Http(HttpPush),
#[cfg(feature = "s3")]
S3(S3Push),
}
#[cfg(feature = "s3")]
struct S3Push {
address: String,
settings: remote::s3::Settings,
http: PullHttp,
refusals: S3Refusals,
}
#[cfg(feature = "push")]
fn checked_push(
config: Option<&RepoConfig>,
remote_or_address: &str,
overrides: EndpointOverrides,
) -> Result<CheckedPush> {
let remote = remote_or_address;
if overrides.url.is_some() {
return Err(push_invalid("url applies to a pull, and this is a push"));
}
let (section, address) = if crate::is_push_address(remote) {
(None, remote.to_owned())
} else {
let section = config
.and_then(|config| config.section::<config::remote::Group>(remote))
.ok_or_else(|| push_invalid(format!("no remote '{remote}' is configured")))?;
check_s3_keys(remote, Some(§ion)).map_err(|e| match e {
Error::Pull(msg) => push_invalid(msg),
other => other,
})?;
let address = match section.get::<config::remote::PushUrl>()? {
Some(push_url) => push_url,
None => match section.get::<config::remote::Url>()? {
Some(url) if url.starts_with("http://") || url.starts_with("https://") => url,
Some(url) if is_s3(&url) => {
return Err(push_invalid(format!(
"remote '{remote}' has no push-url, and its url '{}' is an s3:// \
address; the port reads an s3:// address from push-url alone",
remote::without_userinfo(&url)
)));
}
Some(url) => {
return Err(push_invalid(format!(
"remote '{remote}' has no push-url, and its url '{}' is no push address",
remote::without_userinfo(&url)
)));
}
None => {
return Err(push_invalid(format!(
"remote '{remote}' has no push-url and no url"
)));
}
},
};
(Some(section), address)
};
if is_s3(&address) {
#[cfg(feature = "s3")]
let name = match section {
Some(_) => std::borrow::Cow::Borrowed(remote),
None => remote::without_userinfo(remote),
};
#[cfg(feature = "s3")]
return check_push_s3(&name, section.as_ref(), address, overrides).map(CheckedPush::S3);
#[cfg(not(feature = "s3"))]
return Err(Error::Unsupported(format!(
"the push address '{}' is an s3:// address, and this build of ostrya has no S3 \
support: turn on the feature s3 of ostrya",
remote::without_userinfo(&address)
)));
}
match Endpoint::parse(&address)? {
Endpoint::Http(http) => {
if let Some(name) = s3_field(&overrides) {
return Err(push_invalid(format!(
"{name} applies to an s3:// address, and '{}' is an HTTP address",
remote::without_userinfo(&address)
)));
}
check_push_http(remote, section.as_ref(), &address, http, overrides)
.map(CheckedPush::Http)
}
Endpoint::Ssh { address, .. } => {
if let Some(name) = s3_field(&overrides) {
return Err(push_invalid(format!(
"{name} applies to an s3:// address, and '{}' is an ssh address",
address.without_user()
)));
}
let options = push_ssh(section.as_ref(), &address, overrides)?;
Ok(CheckedPush::Ssh(address, options))
}
_ => Err(neither_ssh_nor_http("a push")),
}
}
#[cfg(feature = "s3")]
fn check_push_s3(
remote: &str,
section: Option<&Section<'_, config::remote::Group>>,
address: String,
o: EndpointOverrides,
) -> Result<S3Push> {
let shown = remote::without_userinfo(&address);
let (token_key, user_key) = match section {
Some(section) => (
section.get::<config::remote::PushTokenFile>()?.is_some(),
section.get::<config::remote::PushUser>()?.is_some(),
),
None => (false, false),
};
let http_fields = [
("push-token-file", o.push_token_file.is_some() || token_key),
("push-user", o.push_user.is_some() || user_key),
];
if let Some((name, _)) = http_fields.iter().find(|(_, set)| *set) {
return Err(push_invalid(format!(
"{name} applies to an HTTP address, and '{shown}' is an s3:// address"
)));
}
if let Some(name) = ssh_field(&o, "receive-command") {
return Err(push_invalid(format!(
"{name} applies to an ssh address, and '{shown}' is an s3:// address"
)));
}
if let Some(section) = section
&& section.get::<config::remote::TlsPermissive>()?
{
return Err(push_invalid(format!(
"remote '{remote}' sets tls-permissive=true, which a writer of a bucket \
repository refuses: the writer verifies the certificate chain of the server"
)));
}
let refusals = S3Refusals {
invalid: |msg| push_invalid(msg),
remote: |msg| push_invalid(msg),
};
let (settings, http) = s3_settings(remote, section, o, refusals)?;
Ok(S3Push {
address,
settings,
http,
refusals,
})
}
#[cfg(feature = "s3")]
pub async fn resolve_bucket(
repo: Option<&Repo>,
name_or_address: &str,
overrides: EndpointOverrides,
) -> Result<remote::s3::S3Endpoint> {
resolve_bucket_in(repo, name_or_address, overrides, &S3Environment::default()).await
}
#[cfg(feature = "s3")]
pub(crate) async fn resolve_bucket_in(
repo: Option<&Repo>,
name_or_address: &str,
overrides: EndpointOverrides,
env: &S3Environment,
) -> Result<remote::s3::S3Endpoint> {
let value = name_or_address;
if overrides.url.is_some() {
return Err(push_invalid(
"url applies to a pull, and this is a write to a bucket repository",
));
}
let (section, address) = if is_s3(value) {
(None, value.to_owned())
} else if value.contains([':', '/']) {
return Err(push_invalid(format!(
"'{}' is no s3:// address",
remote::without_userinfo(value)
)));
} else {
let section = repo
.and_then(|repo| repo.config().section::<config::remote::Group>(value))
.ok_or_else(|| push_invalid(format!("no remote '{value}' is configured")))?;
let s3 = |address: Option<String>| address.filter(|address| is_s3(address));
let address = match s3(section.get::<config::remote::PushUrl>()?) {
Some(address) => address,
None => s3(section.get::<config::remote::PullUrl>()?).ok_or_else(|| {
push_invalid(format!(
"remote '{value}' holds no s3:// address in push-url or pull-url"
))
})?,
};
(Some(section), address)
};
let name = match section {
Some(_) => std::borrow::Cow::Borrowed(value),
None => remote::without_userinfo(value),
};
let push = check_push_s3(&name, section.as_ref(), address, overrides)?;
let endpoint = Box::pin(s3_resolve(
&push.address,
&push.settings,
push.http,
env,
push.refusals,
repo,
))
.await?;
let Endpoint::S3(endpoint) = endpoint else {
unreachable!("the endpoint of an s3:// address is an S3 endpoint");
};
Ok(endpoint)
}
#[cfg(feature = "push")]
struct HttpPush {
http: FetcherOptions,
token_file: Option<KeyPath>,
user: Option<String>,
ca_path: Option<KeyPath>,
client_files: Option<(KeyPath, KeyPath)>,
cleartext: bool,
}
#[cfg(feature = "push")]
fn check_push_http(
remote: &str,
section: Option<&Section<'_, config::remote::Group>>,
address: &str,
mut http: FetcherOptions,
o: EndpointOverrides,
) -> Result<HttpPush> {
if let Some(section) = section
&& address.starts_with("https://")
&& section.get::<config::remote::TlsPermissive>()?
{
return Err(push_invalid(format!(
"remote '{remote}' sets tls-permissive=true, which a push refuses: a \
push verifies the certificate chain of the server"
)));
}
if let Some(name) = ssh_field(&o, "receive-command") {
return Err(push_invalid(format!(
"{name} applies to an ssh address, and '{address}' is an HTTP address"
)));
}
fn pick<K: Key<config::remote::Group, Value = ConfigPath>>(
path: Option<PathBuf>,
section: Option<&Section<'_, config::remote::Group>>,
) -> Result<Option<KeyPath>> {
path_or_key::<K>(path, section).map_err(|e| match e {
Error::InvalidInput(msg) => push_invalid(msg),
other => other,
})
}
let token_file = pick::<config::remote::PushTokenFile>(o.push_token_file, section)?;
let push_user = match (o.push_user, section) {
(Some(user), _) => Some(user),
(None, Some(section)) => section.get::<config::remote::PushUser>()?,
(None, None) => None,
};
let ca_path = pick::<config::remote::TlsCaPath>(o.tls_ca_path, section)?;
let cert = pick::<config::remote::TlsClientCertPath>(o.tls_client_cert_path, section)?;
let key = pick::<config::remote::TlsClientKeyPath>(o.tls_client_key_path, section)?;
let client_files = match (cert, key) {
(Some(cert), Some(key)) => Some((cert, key)),
(None, None) => None,
_ => {
return Err(push_invalid(
"a client certificate needs both tls-client-cert-path and tls-client-key-path",
));
}
};
match (&push_user, &token_file) {
(Some(_), None) => {
return Err(push_invalid("push-user needs push-token-file"));
}
(Some(user), Some(_)) if user.is_empty() || user.contains(':') => {
return Err(push_invalid(
"push-user is empty or holds ':', which a Basic credential cannot carry",
));
}
_ => {}
}
let cleartext = address
.get(..7)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("http://"));
if token_file.is_some() && cleartext && !o.allow_cleartext_credentials {
return Err(push_invalid(format!(
"the push address '{address}' is http://, so the token would travel in cleartext: \
use https, or set allow-cleartext-credentials"
)));
}
http.proxy = match section {
Some(section) => remote_proxy(remote, section)?,
None => Proxy::Environment,
};
http.headers = o.http_headers;
http.allow_cleartext_credentials = o.allow_cleartext_credentials;
if let Some(retries) = o.max_retries {
http.max_retries = retries;
}
if o.low_speed_limit_bytes.is_some() || o.low_speed_time.is_some() {
http.low_speed = low_speed(o.low_speed_limit_bytes, o.low_speed_time);
}
Ok(HttpPush {
http,
token_file,
user: push_user,
ca_path,
client_files,
cleartext,
})
}
#[cfg(feature = "push")]
impl HttpPush {
async fn read_files(self, repo: Option<&Repo>) -> Result<Endpoint> {
let HttpPush {
mut http,
token_file,
user,
ca_path,
client_files,
cleartext,
} = self;
let files = EndpointFiles {
token: token_file,
ca: ca_path.filter(|_| !cleartext),
client: client_files.filter(|_| !cleartext),
}
.read(repo)
.await?;
if let Some(token) = files.token {
match user {
Some(user) => {
http.basic_auth = Some(BasicAuth {
user,
password: token,
})
}
None => http.bearer_token = Some(BearerToken { token }),
}
}
if let Some(pem) = files.ca {
http.tls.roots = TrustRoots::Pem(pem);
}
if files.client.is_some() {
http.tls.client_identity = files.client;
}
Ok(Endpoint::Http(http))
}
}
#[cfg(feature = "push")]
fn push_ssh(
section: Option<&Section<'_, config::remote::Group>>,
address: &SshAddress,
o: EndpointOverrides,
) -> Result<SshOptions> {
let name = push_field(&o).or_else(|| http_field(&o));
if let Some(name) = name {
return Err(push_invalid(format!(
"{name} applies to an HTTP address, and '{}' is an ssh address",
address.without_user()
)));
}
let (config_command, remote_command) = match section {
Some(section) => (
section.get::<config::remote::SshCommand>()?,
match o.remote_command {
Some(command) => Some(command),
None => section.get::<config::remote::ReceiveCommand>()?,
},
),
None => (None, o.remote_command),
};
Ok(SshOptions {
command: o.ssh_command,
config_command,
remote_command,
})
}
#[cfg(any(feature = "push", feature = "s3"))]
fn push_invalid(msg: impl Into<String>) -> Error {
Error::Remote(remote::Error::InvalidInput(msg.into()))
}
fn http_field(o: &EndpointOverrides) -> Option<&'static str> {
let set = [
("tls-ca-path", o.tls_ca_path.is_some()),
("tls-client-cert-path", o.tls_client_cert_path.is_some()),
("tls-client-key-path", o.tls_client_key_path.is_some()),
("allow-cleartext-credentials", o.allow_cleartext_credentials),
("http-header", !o.http_headers.is_empty()),
("network-retries", o.max_retries.is_some_and(|n| n > 0)),
("low-speed-limit-bytes", o.low_speed_limit_bytes.is_some()),
("low-speed-time-seconds", o.low_speed_time.is_some()),
];
set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}
fn low_speed(limit: Option<u32>, time: Option<Duration>) -> Option<LowSpeed> {
let limit = limit.unwrap_or(DEFAULT_LOW_SPEED_LIMIT);
let time = time.unwrap_or(DEFAULT_LOW_SPEED_TIME);
(limit != 0 && !time.is_zero()).then_some(LowSpeed { limit, time })
}
fn remote_proxy(remote: &str, section: &Section<'_, config::remote::Group>) -> Result<Proxy> {
Ok(match section.get::<config::remote::Proxy>()? {
Some(url) if url.trim() != url => {
return Err(Error::Unsupported(format!(
"remote '{remote}': the proxy key has white space at the start or \
the end of its value"
)));
}
Some(url) if !url.is_empty() => Proxy::Url(url),
_ => Proxy::Environment,
})
}
fn path_or_key<K: Key<config::remote::Group, Value = ConfigPath>>(
path: Option<PathBuf>,
section: Option<&Section<'_, config::remote::Group>>,
) -> Result<Option<KeyPath>> {
match (caller_path(K::NAME, path)?, section) {
(Some(path), _) => Ok(Some(path)),
(None, Some(section)) => section.key_path::<K>(),
(None, None) => Ok(None),
}
}
pub(crate) fn caller_path(key: &str, path: Option<PathBuf>) -> Result<Option<KeyPath>> {
match path {
Some(path) if relative_with_parent(&path) => Err(Error::InvalidInput(format!(
"{key} {} is a relative path with a `..` component",
path.display()
))),
path => Ok(path.map(KeyPath::caller)),
}
}
struct EndpointFiles {
token: Option<KeyPath>,
ca: Option<KeyPath>,
client: Option<(KeyPath, KeyPath)>,
}
struct ReadFiles {
#[cfg_attr(not(feature = "push"), allow(dead_code))]
token: Option<String>,
ca: Option<Vec<u8>>,
client: Option<ClientIdentity>,
}
impl EndpointFiles {
async fn read(self, repo: Option<&Repo>) -> Result<ReadFiles> {
if self.token.is_none() && self.ca.is_none() && self.client.is_none() {
return Ok(ReadFiles {
token: None,
ca: None,
client: None,
});
}
let repo = repo.cloned();
ostrya_rt::unblock(move || {
let repo = repo.as_ref();
let token = match &self.token {
Some(path) => Some(read_token_file(path, repo)?),
None => None,
};
let ca = match &self.ca {
Some(path) => Some(read_pem_file("tls-ca-path", path, repo)?),
None => None,
};
let client = match &self.client {
Some((cert, key)) => Some(ClientIdentity {
cert_chain_pem: read_pem_file("tls-client-cert-path", cert, repo)?,
key_pem: read_pem_file("tls-client-key-path", key, repo)?,
key_passphrase: None,
}),
None => None,
};
Ok(ReadFiles { token, ca, client })
})
.await
}
}
fn read_token_file(path: &KeyPath, repo: Option<&Repo>) -> Result<String> {
const KEY: &str = "push-token-file";
let (file, shown) = open_key_file(KEY, path, repo)?;
let mut bytes = Vec::new();
BufReader::new(file.take(FILE_CAP + 1))
.read_until(b'\n', &mut bytes)
.map_err(|e| io_error(KEY, &shown, e))?;
let line = match bytes.split_last() {
Some((b'\n', line)) => line,
_ if bytes.len() as u64 > FILE_CAP => {
return Err(Error::InvalidInput(format!(
"the first line of {KEY} '{}' is over 1 MiB",
shown.display()
)));
}
_ => &bytes[..],
};
token_of(line).map_err(|why| Error::InvalidInput(format!("{KEY} '{}': {why}", shown.display())))
}
pub(crate) fn read_pem_file(key: &str, path: &KeyPath, repo: Option<&Repo>) -> Result<Vec<u8>> {
let (file, shown) = open_key_file(key, path, repo)?;
let mut bytes = Vec::with_capacity(8 * 1024);
file.take(FILE_CAP + 1)
.read_to_end(&mut bytes)
.map_err(|e| io_error(key, &shown, e))?;
if bytes.len() as u64 > FILE_CAP {
return Err(Error::InvalidInput(format!(
"{key} '{}' is over 1 MiB",
shown.display()
)));
}
Ok(bytes)
}
fn open_key_file(
key: &str,
path: &KeyPath,
repo: Option<&Repo>,
) -> Result<(std::fs::File, PathBuf)> {
let (base, at, shown) = path.locate(repo);
match open_named(base, &at, Named::File) {
Ok(fd) => Ok((std::fs::File::from(fd), shown)),
Err(FsError::Invalid {
reason: Reason::NotRegular(_),
..
}) => Err(Error::InvalidInput(format!(
"{key} '{}' is not a regular file",
shown.display()
))),
Err(err) => Err(io_error(key, &shown, io_of(err))),
}
}
fn io_error(key: &str, path: &Path, e: std::io::Error) -> Error {
Error::Io(std::io::Error::new(
e.kind(),
format!("{key} '{}': {e}", path.display()),
))
}
fn token_of(line: &[u8]) -> std::result::Result<String, &'static str> {
if line.contains(&b'\r') {
return Err("the first line holds a carriage return");
}
if line.is_empty() {
return Err("the first line is empty");
}
let token = std::str::from_utf8(line).map_err(|_| "the first line is not UTF-8")?;
if !is_token68(token) {
return Err(
"the token is not token68: it holds letters, digits, -, ., _, ~, +, or /, \
then any number of =",
);
}
Ok(token.to_owned())
}
fn is_token68(token: &str) -> bool {
let body = token.trim_end_matches('=');
!body.is_empty()
&& body
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-._~+/".contains(&b))
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<EndpointOverrides>();
};
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU32, Ordering};
use super::*;
use crate::fetch::TlsOptions;
struct Dir(PathBuf);
impl Dir {
fn new() -> Dir {
static N: AtomicU32 = AtomicU32::new(0);
let path = std::env::temp_dir().join(format!(
"ostrya-endpoint-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Dir(path)
}
fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
let path = self.0.join(name);
std::fs::write(&path, bytes).unwrap();
path
}
fn absent(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
struct TestRepo {
repo: Repo,
_dir: Dir,
}
impl std::ops::Deref for TestRepo {
type Target = Repo;
fn deref(&self) -> &Repo {
&self.repo
}
}
fn config(sections: &str) -> TestRepo {
let dir = Dir::new();
let root = dir.0.join("repo");
let repo = ostrya_rt::block_on(async {
Repo::create(
&root,
crate::CreateOptions::new(ostrya_core::RepoMode::Archive),
)
.await
.unwrap();
std::fs::write(
root.join("config"),
format!("[core]\nrepo_version=1\nmode=archive-z2\n\n{sections}"),
)
.unwrap();
Repo::open(&root).await.unwrap()
});
TestRepo { repo, _dir: dir }
}
fn handle(repo: Option<&TestRepo>) -> Option<&Repo> {
repo.map(|repo| &repo.repo)
}
fn pull(repo: Option<&TestRepo>, remote: &str, o: EndpointOverrides) -> Result<Endpoint> {
ostrya_rt::block_on(resolve_pull(handle(repo), remote, o))
}
fn http_of(endpoint: Result<Endpoint>) -> FetcherOptions {
match endpoint {
Ok(Endpoint::Http(http)) => http,
other => panic!("{other:?}"),
}
}
fn ssh(endpoint: Result<Endpoint>) -> (SshAddress, SshOptions) {
match endpoint {
Ok(Endpoint::Ssh { address, options }) => (address, options),
other => panic!("{other:?}"),
}
}
fn invalid_input<T: fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::InvalidInput(msg)) => msg,
other => panic!("expected InvalidInput, got {other:?}"),
}
}
fn pull_error<T: fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::Pull(msg)) => msg,
other => panic!("expected Pull, got {other:?}"),
}
}
fn not_found<T: fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::Io(e)) => {
assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
e.to_string()
}
other => panic!("expected Io, got {other:?}"),
}
}
fn token(path: &Path) -> Result<String> {
read_token_file(&KeyPath::caller(path), None)
}
fn pem(key: &str, path: &Path) -> Result<Vec<u8>> {
read_pem_file(key, &KeyPath::caller(path), None)
}
#[test]
fn the_token_is_the_first_line_of_the_file() {
let dir = Dir::new();
let file = dir.file("token", b"s3cr3t-T0ken==\nsecond line\n");
assert_eq!(token(&file).unwrap(), "s3cr3t-T0ken==");
assert_eq!(token(&dir.file("bare", b"abc")).unwrap(), "abc");
assert_eq!(
token(&dir.file("all", b"aZ0-._~+/==")).unwrap(),
"aZ0-._~+/=="
);
}
#[test]
fn a_bad_token_is_refused_without_the_token() {
let dir = Dir::new();
for (bytes, part) in [
(&b"\nQXZ"[..], "is empty"),
(b"", "is empty"),
(b"QXZ\r\n", "carriage return"),
(b"QX\rZ", "carriage return"),
(b"QXZ\xff\n", "not UTF-8"),
(b"QX Z\n", "not token68"),
(b"QXZ:x\n", "not token68"),
(b"==\n", "not token68"),
(b"QX=Z\n", "not token68"),
] {
let path = dir.file("t", bytes);
let m = invalid_input(token(&path));
assert!(m.contains(part), "{bytes:?}: {m}");
assert!(!m.contains("QX"), "{m}");
assert!(
m.starts_with(&format!("push-token-file '{}': ", path.display())),
"{m}"
);
}
}
#[test]
fn a_file_over_the_cap_is_refused() {
let dir = Dir::new();
let long = vec![b'a'; FILE_CAP as usize + 1];
let path = dir.file("long", &long);
let m = invalid_input(token(&path));
assert_eq!(
m,
format!(
"the first line of push-token-file '{}' is over 1 MiB",
path.display()
)
);
let mut short = b"abc\n".to_vec();
short.extend_from_slice(&long);
assert_eq!(token(&dir.file("short", &short)).unwrap(), "abc");
let mut at_cap = vec![b'a'; FILE_CAP as usize];
at_cap.push(b'\n');
assert_eq!(token(&dir.file("at-cap", &at_cap)).unwrap().len(), 1 << 20);
let m = invalid_input(pem("tls-ca-path", &path));
assert_eq!(m, format!("tls-ca-path '{}' is over 1 MiB", path.display()));
let at_cap = dir.file("pem-at-cap", &vec![b'a'; FILE_CAP as usize]);
assert_eq!(pem("tls-ca-path", &at_cap).unwrap().len(), 1 << 20);
}
#[test]
fn an_absent_file_is_an_io_error_that_names_the_key_and_the_path() {
let dir = Dir::new();
let absent = dir.absent("absent");
let m = not_found(token(&absent));
assert!(
m.starts_with(&format!("push-token-file '{}': ", absent.display())),
"{m}"
);
for key in ["tls-ca-path", "tls-client-cert-path", "tls-client-key-path"] {
let m = not_found(pem(key, &absent));
assert!(
m.starts_with(&format!("{key} '{}': ", absent.display())),
"{m}"
);
}
}
#[test]
fn an_empty_key_path_of_a_remotes_file_is_absent_as_in_config() {
use crate::config::tests::repos_with_remotes_file;
type Read = fn(&Section<'_, config::remote::Group>) -> Result<Option<KeyPath>>;
let keys: [(&str, Read); 4] = [
("push-token-file", |s| {
s.key_path::<config::remote::PushTokenFile>()
}),
("tls-ca-path", |s| s.key_path::<config::remote::TlsCaPath>()),
("tls-client-cert-path", |s| {
s.key_path::<config::remote::TlsClientCertPath>()
}),
("tls-client-key-path", |s| {
s.key_path::<config::remote::TlsClientKeyPath>()
}),
];
let dir = Dir::new();
let section = |name: &str| {
let mut text = format!("[remote \"{name}\"]\nurl=https://h/\n");
for (key, _) in keys {
text.push_str(&format!("{key}=\n"));
}
text
};
let root = dir.0.join("repo");
for repo in repos_with_remotes_file(&root, §ion("c"), §ion("o")) {
for (key, read) in keys {
let messages: Vec<String> = ["c", "o"]
.into_iter()
.map(|name| {
let remote = repo
.config()
.section::<config::remote::Group>(name)
.unwrap();
let path = read(&remote).unwrap().unwrap();
let result = match key {
"push-token-file" => read_token_file(&path, Some(&repo)).map(|_| ()),
_ => read_pem_file(key, &path, Some(&repo)).map(|_| ()),
};
not_found(result)
})
.collect();
assert!(
messages[0].starts_with(&format!("{key} '': No such file or directory")),
"{messages:?}"
);
assert_eq!(messages[0], messages[1], "{:?}", repo.remotes_dir());
}
}
}
#[test]
fn the_debug_output_shows_no_secret() {
let o = EndpointOverrides {
url: Some("https://user-QXZ:pw-QXZ@ex.com/repo".into()),
push_token_file: Some("/etc/ostrya/token".into()),
tls_ca_path: Some("/etc/ostrya/ca.pem".into()),
http_headers: vec![
("Authorization".into(), "Bearer QXZ".into()),
("Cookie".into(), "id=QXZ".into()),
],
..EndpointOverrides::default()
};
let text = format!("{o:?}");
assert!(!text.contains("QXZ"), "{text}");
for part in [
"https://ex.com/repo",
"/etc/ostrya/token",
"/etc/ostrya/ca.pem",
"Authorization",
"Cookie",
"<redacted>",
] {
assert!(text.contains(part), "{part}: {text}");
}
}
const PULL_SECTIONS: &str = "[remote \"both\"]\nurl=https://ex.com/pull\n\
pull-url=ssh://puller@ex.com/srv/repo\n\
ssh-command=ssh -o BatchMode=yes\n\
send-command=/opt/bin/ostrya send\n\
tls-ca-path=/nonexistent/ca.pem\n\
tls-permissive=maybe\n\n\
[remote \"http-pull-url\"]\nurl=ssh://h/dead\n\
pull-url=http://pull.ex.com/repo\n\
ssh-command=ssh -q\n\
send-command=ostrya send\n\n\
[remote \"upper\"]\npull-url=HTTP://ex.com/repo\n\n\
[remote \"scp\"]\npull-url=h:srv/repo\n\n\
[remote \"bad-pull-url\"]\npull-url=ssh://h\n\n\
[remote \"local-path\"]\npull-url=/srv/repo\n\n\
[remote \"url\"]\nurl=https://ex.com/repo\n\
contenturl=https://content.ex.com/repo\n\
metalink=https://ex.com/metalink.xml\n\
ssh-command=ssh -q\n\n\
[remote \"ssh-url\"]\nurl=ssh://h/srv/repo\n\n\
[remote \"scp-url\"]\nurl=u@h:/srv/repo\n\n\
[remote \"path-url\"]\nurl=/srv/repo\n\n\
[remote \"empty-url\"]\nurl=\n\n\
[remote \"none\"]\ngpg-verify=false\n";
fn pull_url(name: &str, url: Option<&str>) -> Result<Endpoint> {
let o = EndpointOverrides {
url: url.map(str::to_owned),
..EndpointOverrides::default()
};
pull(Some(&config(PULL_SECTIONS)), name, o)
}
fn mirror(endpoint: Result<Endpoint>) -> String {
let http = http_of(endpoint);
assert_eq!(http.mirrors.len(), 1);
http.mirrors[0].clone()
}
#[test]
fn the_pull_takes_the_url_override_then_pull_url_then_url() {
assert_eq!(
mirror(pull_url("http-pull-url", Some("https://other.ex.com/"))),
"https://other.ex.com/"
);
assert_eq!(
ssh(pull_url("both", None)).0,
SshAddress::parse("ssh://puller@ex.com/srv/repo").unwrap()
);
assert_eq!(
ssh(pull_url("http-pull-url", Some("u@h:x"))).0,
SshAddress::parse("u@h:x").unwrap()
);
assert_eq!(
mirror(pull_url("http-pull-url", None)),
"http://pull.ex.com/repo"
);
assert_eq!(mirror(pull_url("url", None)), "https://ex.com/repo");
assert_eq!(
ssh(pull_url("scp", None)).0,
SshAddress::parse("h:srv/repo").unwrap()
);
}
#[test]
fn another_scheme_goes_to_the_fetcher() {
assert_eq!(mirror(pull_url("upper", None)), "HTTP://ex.com/repo");
assert_eq!(
mirror(pull_url("none", Some("ftp://ex.com/repo"))),
"ftp://ex.com/repo"
);
}
#[test]
fn a_local_address_is_refused_with_no_endpoint() {
let config = config(
"[remote \"pull-url\"]\npull-url=file:///srv/repo\nurl=https://ex.com/repo\n\n\
[remote \"url\"]\nurl=file:///srv/a-QXZ\n\n\
[remote \"upper\"]\nurl=FILE:///srv/repo\n\n\
[remote \"http\"]\nurl=https://ex.com/repo\n",
);
for (name, url) in [
("pull-url", None),
("url", None),
("upper", None),
("http", Some("file:///srv/repo")),
("absent", Some("file:///srv/repo")),
] {
let o = EndpointOverrides {
url: url.map(str::to_owned),
..EndpointOverrides::default()
};
assert_eq!(
pull_error(pull(Some(&config), name, o)),
format!(
"the pull address of remote '{name}' is a local repository, which has no \
endpoint; Repo::pull reads it"
)
);
}
}
#[test]
fn the_refusals_of_a_pull_come_before_the_local_refusal() {
let config = config(
"[remote \"url\"]\nurl=file:///srv/repo\n\n\
[remote \"s3-key\"]\nurl=file:///srv/repo\ns3-region=eu-west-1\n",
);
let o = EndpointOverrides {
push_user: Some("u".into()),
..EndpointOverrides::default()
};
assert_eq!(
invalid_input(pull(Some(&config), "url", o)),
"push-user applies to a push, and this is a pull"
);
assert_eq!(
pull_error(pull(Some(&config), "s3-key", EndpointOverrides::default())),
"remote 's3-key': s3-region applies to an s3:// address, and neither pull-url \
nor push-url holds one"
);
}
#[test]
fn resolve_origin_gives_a_local_path_or_an_endpoint() {
let repo = config(LOCAL_SECTIONS);
let origin = |remote, o| ostrya_rt::block_on(resolve_origin(&repo, remote, o));
let d = EndpointOverrides::default;
assert!(matches!(origin("url", d()), Ok(Origin::Local(p)) if p == Path::new("/srv/repo")),);
assert!(
matches!(origin("upper", d()), Ok(Origin::Local(p)) if p == Path::new("/srv/a@b c")),
);
match origin("http", d()) {
Ok(Origin::Endpoint(endpoint)) => {
assert_eq!(mirror(Ok(endpoint)), "https://ex.com/repo");
}
other => panic!("{other:?}"),
}
match origin("ssh", d()) {
Ok(Origin::Endpoint(endpoint)) => {
assert_eq!(
ssh(Ok(endpoint)).0,
SshAddress::parse("ssh://h/srv/repo").unwrap()
);
}
other => panic!("{other:?}"),
}
let o = EndpointOverrides {
url: Some("file:///x".into()),
..d()
};
assert!(matches!(origin("http", o), Ok(Origin::Local(p)) if p == Path::new("/x")));
let o = EndpointOverrides {
url: Some("file:/x".into()),
..d()
};
let msg = pull_error(origin("http", o));
assert!(msg.contains("does not start with file://"), "{msg}");
let o = EndpointOverrides {
http_headers: vec![("X-A".into(), "b".into())],
..d()
};
let msg = invalid_input(origin("url", o));
assert!(msg.starts_with("http-header applies to "), "{msg}");
let msg = pull_error(origin("absent", d()));
assert_eq!(msg, "no remote 'absent' is configured");
}
#[test]
fn a_malformed_ssh_address_is_invalid_input() {
for (name, url, value) in [
("bad-pull-url", None, "ssh://h"),
("local-path", None, "/srv/repo"),
("none", Some("ssh://h"), "ssh://h"),
("none", Some("/srv/repo"), "/srv/repo"),
] {
let msg = invalid_input(pull_url(name, url));
assert!(msg.starts_with(&format!("address '{value}': ")), "{msg}");
}
}
#[test]
fn an_ssh_address_in_url_is_refused() {
for (name, value) in [
("ssh-url", "ssh://h/srv/repo"),
("scp-url", "h:/srv/repo"),
("path-url", "/srv/repo"),
("empty-url", ""),
] {
assert_eq!(
pull_error(pull_url(name, None)),
format!(
"remote '{name}': url '{value}' is an ssh address; the port reads an ssh \
address from pull-url alone"
)
);
}
}
#[test]
fn address_kind_gives_each_kind() {
for (value, kind) in [
("file:///x", AddressKind::Local),
("FILE:///x", AddressKind::Local),
("file:/x", AddressKind::Local),
("file:", AddressKind::Local),
("s3://b", AddressKind::S3),
("ssh://h/x", AddressKind::Ssh),
("h:x", AddressKind::Ssh),
("/srv/repo", AddressKind::Ssh),
("", AddressKind::Ssh),
("file", AddressKind::Ssh),
("https://ex.com/repo", AddressKind::Http),
("HTTP://ex.com/repo", AddressKind::Http),
("S3://b", AddressKind::Http),
("SSH://h/x", AddressKind::Http),
("ftp://ex.com/repo", AddressKind::Http),
] {
assert_eq!(address_kind(value), kind, "{value}");
}
}
#[test]
fn a_malformed_file_address_is_refused_in_each_key() {
let config = config(
"[remote \"url\"]\nurl=file:/x\n\n\
[remote \"pull-url\"]\npull-url=FILE:/x\nurl=https://ex.com/repo\n\n\
[remote \"other\"]\nurl=https://ex.com/repo\n",
);
for (name, url, value) in [
("url", None, "file:/x"),
("pull-url", None, "FILE:/x"),
("other", Some("file:/x"), "file:/x"),
("absent", Some("file:/x"), "file:/x"),
] {
let o = EndpointOverrides {
url: url.map(str::to_owned),
..EndpointOverrides::default()
};
assert_eq!(
pull_error(pull(Some(&config), name, o)),
format!(
"remote '{name}': the file address '{value}' does not start with file://; \
a local repository is file:// followed by an absolute path"
)
);
}
}
#[test]
fn the_refusal_of_an_ssh_url_shows_no_userinfo() {
let config = config(
"[remote \"ssh-userinfo\"]\nurl=ssh://user-QXZ:pw-QXZ@ex.com/srv/repo\n\n\
[remote \"scp-user\"]\nurl=user-QXZ@ex.com:/srv/repo\n",
);
for (name, shown) in [
("ssh-userinfo", "ssh://ex.com/srv/repo"),
("scp-user", "ex.com:/srv/repo"),
] {
let msg = pull_error(pull(Some(&config), name, EndpointOverrides::default()));
assert!(!msg.contains("QXZ"), "{name}: {msg}");
assert_eq!(
msg,
format!(
"remote '{name}': url '{shown}' is an ssh address; the port reads an ssh \
address from pull-url alone"
)
);
}
}
#[test]
fn a_pull_remote_with_no_address_is_refused() {
assert_eq!(
pull_error(pull_url("absent", None)),
"no remote 'absent' is configured"
);
assert_eq!(
pull_error(pull(None, "absent", EndpointOverrides::default())),
"no remote 'absent' is configured"
);
assert_eq!(
pull_error(pull_url("none", None)),
"remote 'none' has no pull-url and no url"
);
assert_eq!(
ssh(pull_url("absent", Some("ssh://h/x"))).0,
SshAddress::parse("ssh://h/x").unwrap()
);
}
#[test]
fn an_http_pull_gets_the_defaults_of_a_pull() {
for http in [
http_of(pull_url("url", None)),
http_of(pull(
None,
"absent",
EndpointOverrides {
url: Some("https://ex.com/repo".into()),
..EndpointOverrides::default()
},
)),
] {
assert_eq!(http.mirrors, ["https://ex.com/repo"]);
assert_eq!(http.max_retries, 5);
assert_eq!(http.max_outstanding, 8);
assert_eq!(
http.low_speed,
Some(LowSpeed {
limit: 1000,
time: Duration::from_secs(30)
})
);
assert_eq!(http.tls, TlsOptions::default());
assert!(matches!(http.proxy, Proxy::Environment));
assert!(http.headers.is_empty());
assert!(http.basic_auth.is_none());
assert!(http.bearer_token.is_none());
assert!(!http.allow_cleartext_credentials);
let d = FetcherOptions::default();
assert_eq!(http.max_redirects, d.max_redirects);
assert_eq!(http.fetch_timeout, d.fetch_timeout);
}
}
#[test]
fn the_pull_applies_the_http_overrides() {
let secs = Duration::from_secs;
for (limit, time, expected) in [
(None, None, Some((1000, secs(30)))),
(Some(5), None, Some((5, secs(30)))),
(None, Some(secs(10)), Some((1000, secs(10)))),
(Some(5), Some(secs(10)), Some((5, secs(10)))),
(Some(0), None, None),
(None, Some(Duration::ZERO), None),
(Some(0), Some(secs(10)), None),
] {
let o = EndpointOverrides {
low_speed_limit_bytes: limit,
low_speed_time: time,
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config(PULL_SECTIONS)), "url", o));
let expected = expected.map(|(limit, time)| LowSpeed { limit, time });
assert_eq!(http.low_speed, expected, "{limit:?} {time:?}");
}
let o = EndpointOverrides {
http_headers: vec![("X-A".into(), "b".into())],
allow_cleartext_credentials: true,
max_retries: Some(0),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config(PULL_SECTIONS)), "url", o));
assert_eq!(http.headers, [("X-A".to_owned(), "b".to_owned())]);
assert!(http.allow_cleartext_credentials);
assert_eq!(http.max_retries, 0);
}
#[test]
fn the_pull_maps_tls_permissive_to_any_chain() {
let dir = Dir::new();
let ca = dir.file("ca.pem", b"CA");
let config = config(&format!(
"[remote \"permissive\"]\nurl=https://ex.com/repo\n\
tls-ca-path={}\ntls-permissive=true\n\n\
[remote \"bad\"]\nurl=http://ex.com/repo\ntls-permissive=maybe\n",
dir.absent("absent.pem").display()
));
let http = http_of(pull(
Some(&config),
"permissive",
EndpointOverrides::default(),
));
assert_eq!(http.tls.roots, TrustRoots::DangerousAcceptAnyChain);
let o = EndpointOverrides {
tls_ca_path: Some(ca),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config), "permissive", o));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"CA".to_vec()));
assert!(matches!(
pull(Some(&config), "bad", EndpointOverrides::default()),
Err(Error::Core(_))
));
}
fn tls_keys(dir: &Dir, url: &str) -> TestRepo {
let ca = dir.file("key-ca.pem", b"KEY-CA");
let cert = dir.file("key-cert.pem", b"KEY-CERT");
let key = dir.file("key-key.pem", b"KEY-KEY");
let token = dir.file("key-token", b"KEY-TOKEN\n");
config(&format!(
"[remote \"keys\"]\nurl={url}\n\
push-token-file={}\npush-user=alice\n\
tls-ca-path={}\ntls-client-cert-path={}\ntls-client-key-path={}\n\
proxy=http://proxy.ex.com:3128\n\
ssh-command=ssh -o BatchMode=yes\n\
receive-command=/opt/bin/ostrya receive\n\
send-command=/opt/bin/ostrya send\n",
token.display(),
ca.display(),
cert.display(),
key.display()
))
}
fn given(dir: &Dir) -> [PathBuf; 4] {
[
dir.file("given-ca.pem", b"GIVEN-CA"),
dir.file("given-cert.pem", b"GIVEN-CERT"),
dir.file("given-key.pem", b"GIVEN-KEY"),
dir.file("given-token", b"GIVEN-TOKEN\n"),
]
}
fn identity(http: &FetcherOptions) -> (Vec<u8>, Vec<u8>) {
let identity = http.tls.client_identity.as_ref().unwrap();
assert_eq!(identity.key_passphrase, None);
(identity.cert_chain_pem.clone(), identity.key_pem.clone())
}
#[test]
fn an_override_wins_over_each_tls_key_of_the_pull() {
let dir = Dir::new();
let config = tls_keys(&dir, "https://ex.com/repo");
let http = http_of(pull(Some(&config), "keys", EndpointOverrides::default()));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
assert!(matches!(&http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
let [ca, cert, key, _] = given(&dir);
let o = EndpointOverrides {
tls_ca_path: Some(ca.clone()),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config), "keys", o));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"GIVEN-CA".to_vec()));
assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
let o = EndpointOverrides {
tls_client_cert_path: Some(cert.clone()),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config), "keys", o));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
assert_eq!(
identity(&http),
(b"GIVEN-CERT".to_vec(), b"KEY-KEY".to_vec())
);
let o = EndpointOverrides {
tls_client_key_path: Some(key.clone()),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config), "keys", o));
assert_eq!(
identity(&http),
(b"KEY-CERT".to_vec(), b"GIVEN-KEY".to_vec())
);
let o = EndpointOverrides {
url: Some("https://ex.com/repo".into()),
tls_ca_path: Some(ca),
tls_client_cert_path: Some(cert),
tls_client_key_path: Some(key),
..EndpointOverrides::default()
};
let http = http_of(pull(None, "absent", o));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"GIVEN-CA".to_vec()));
assert_eq!(
identity(&http),
(b"GIVEN-CERT".to_vec(), b"GIVEN-KEY".to_vec())
);
assert!(matches!(http.proxy, Proxy::Environment));
}
#[test]
fn a_lone_certificate_or_key_is_refused_by_the_pull() {
let dir = Dir::new();
let pem = dir.file("pem", b"");
let config = config(&format!(
"[remote \"cert\"]\nurl=https://ex.com/repo\ntls-ca-path={}\n\
tls-client-cert-path={}\n",
dir.absent("absent.pem").display(),
pem.display()
));
let expected = "remote 'cert': a client certificate needs both tls-client-cert-path \
and tls-client-key-path";
assert_eq!(
pull_error(pull(Some(&config), "cert", EndpointOverrides::default())),
expected
);
let o = EndpointOverrides {
url: Some("https://ex.com/repo".into()),
tls_client_key_path: Some(pem),
..EndpointOverrides::default()
};
assert_eq!(pull_error(pull(None, "cert", o)), expected);
}
#[test]
fn the_pull_refuses_a_proxy_with_white_space() {
let dir = Dir::new();
let config = config(&format!(
"[remote \"proxy\"]\nurl=https://ex.com/repo\nproxy=http://user-QXZ:pw@p:1 \n\
tls-ca-path={}\n",
dir.absent("absent.pem").display()
));
match pull(Some(&config), "proxy", EndpointOverrides::default()) {
Err(Error::Unsupported(msg)) => {
assert!(msg.contains("white space") && !msg.contains("QXZ"), "{msg}")
}
other => panic!("{other:?}"),
}
}
#[test]
fn the_pull_passes_a_socks5h_proxy_unchanged() {
let config = config(
"[remote \"socks\"]\nurl=https://ex.com/repo\n\
proxy=socks5h://u:p@proxy.ex.com:1080\n",
);
let http = http_of(pull(Some(&config), "socks", EndpointOverrides::default()));
assert!(matches!(&http.proxy, Proxy::Url(url) if url == "socks5h://u:p@proxy.ex.com:1080"));
}
#[test]
fn a_tls_file_over_the_cap_fails_the_pull() {
let dir = Dir::new();
let long = dir.file("long", &vec![b'a'; FILE_CAP as usize + 1]);
let absent = dir.absent("absent");
let pem = dir.file("pem", b"");
for (key, path) in [
("tls-ca-path", &long),
("tls-client-cert-path", &long),
("tls-client-key-path", &long),
] {
let mut o = EndpointOverrides {
url: Some("https://ex.com/repo".into()),
tls_client_cert_path: Some(pem.clone()),
tls_client_key_path: Some(pem.clone()),
..EndpointOverrides::default()
};
match key {
"tls-ca-path" => o.tls_ca_path = Some(path.clone()),
"tls-client-cert-path" => o.tls_client_cert_path = Some(path.clone()),
_ => o.tls_client_key_path = Some(path.clone()),
}
assert_eq!(
invalid_input(pull(None, "r", o.clone())),
format!("{key} '{}' is over 1 MiB", path.display())
);
match key {
"tls-ca-path" => o.tls_ca_path = Some(absent.clone()),
"tls-client-cert-path" => o.tls_client_cert_path = Some(absent.clone()),
_ => o.tls_client_key_path = Some(absent.clone()),
}
let m = not_found(pull(None, "r", o));
assert!(
m.starts_with(&format!("{key} '{}': ", absent.display())),
"{m}"
);
}
}
#[test]
fn the_pull_refuses_the_fields_of_a_push() {
for (name, o) in [
(
"push-token-file",
EndpointOverrides {
push_token_file: Some("/t".into()),
push_user: Some("alice".into()),
..EndpointOverrides::default()
},
),
(
"push-user",
EndpointOverrides {
push_user: Some("alice".into()),
..EndpointOverrides::default()
},
),
] {
for url in ["https://ex.com/repo", "ssh://h/r"] {
let o = EndpointOverrides {
url: Some(url.into()),
..o.clone()
};
assert_eq!(
invalid_input(pull(None, "r", o)),
format!("{name} applies to a push, and this is a pull")
);
}
assert_eq!(
invalid_input(pull(None, "absent", o)),
format!("{name} applies to a push, and this is a pull")
);
}
}
#[test]
fn the_pull_refuses_the_ssh_fields_for_an_http_address() {
for (name, o) in [
(
"ssh-command",
EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
remote_command: Some("ostrya send".into()),
..EndpointOverrides::default()
},
),
(
"send-command",
EndpointOverrides {
remote_command: Some("ostrya send".into()),
..EndpointOverrides::default()
},
),
] {
assert_eq!(
invalid_input(pull(Some(&config(PULL_SECTIONS)), "url", o)),
format!("{name} applies to a pull over ssh, and this pull runs over HTTP")
);
}
}
#[test]
fn the_pull_fills_the_ssh_options_from_the_keys() {
let config = config(PULL_SECTIONS);
let (_, options) = ssh(pull(Some(&config), "both", EndpointOverrides::default()));
assert_eq!(
options,
SshOptions {
command: None,
config_command: Some("ssh -o BatchMode=yes".into()),
remote_command: Some("/opt/bin/ostrya send".into()),
}
);
let o = EndpointOverrides {
ssh_command: Some(vec!["my-ssh".into()]),
remote_command: Some("my send".into()),
..EndpointOverrides::default()
};
let (_, options) = ssh(pull(Some(&config), "both", o.clone()));
assert_eq!(
options,
SshOptions {
command: Some(vec!["my-ssh".into()]),
config_command: Some("ssh -o BatchMode=yes".into()),
remote_command: Some("my send".into()),
}
);
let o = EndpointOverrides {
url: Some("ssh://h/r".into()),
..o
};
let (_, options) = ssh(pull(None, "absent", o));
assert_eq!(options.config_command, None);
assert_eq!(options.remote_command.as_deref(), Some("my send"));
let (_, options) = ssh(pull_url("none", Some("ssh://h/r")));
assert_eq!(options, SshOptions::default());
}
fn http_fields() -> Vec<(&'static str, EndpointOverrides)> {
let d = EndpointOverrides::default;
vec![
(
"tls-ca-path",
EndpointOverrides {
tls_ca_path: Some("/c".into()),
..d()
},
),
(
"tls-client-cert-path",
EndpointOverrides {
tls_client_cert_path: Some("/c".into()),
..d()
},
),
(
"tls-client-key-path",
EndpointOverrides {
tls_client_key_path: Some("/k".into()),
..d()
},
),
(
"allow-cleartext-credentials",
EndpointOverrides {
allow_cleartext_credentials: true,
..d()
},
),
(
"http-header",
EndpointOverrides {
http_headers: vec![("A".into(), "B".into())],
..d()
},
),
(
"network-retries",
EndpointOverrides {
max_retries: Some(1),
..d()
},
),
(
"low-speed-limit-bytes",
EndpointOverrides {
low_speed_limit_bytes: Some(0),
..d()
},
),
(
"low-speed-time-seconds",
EndpointOverrides {
low_speed_time: Some(Duration::ZERO),
..d()
},
),
]
}
fn from_field(fields: &[(&str, EndpointOverrides)], first: usize) -> EndpointOverrides {
let mut o = EndpointOverrides::default();
for (_, f) in &fields[first..] {
o.tls_ca_path = o.tls_ca_path.or(f.tls_ca_path.clone());
o.tls_client_cert_path = o.tls_client_cert_path.or(f.tls_client_cert_path.clone());
o.tls_client_key_path = o.tls_client_key_path.or(f.tls_client_key_path.clone());
o.allow_cleartext_credentials |= f.allow_cleartext_credentials;
o.http_headers.extend(f.http_headers.iter().cloned());
o.max_retries = o.max_retries.or(f.max_retries);
o.low_speed_limit_bytes = o.low_speed_limit_bytes.or(f.low_speed_limit_bytes);
o.low_speed_time = o.low_speed_time.or(f.low_speed_time);
o.push_token_file = o.push_token_file.or(f.push_token_file.clone());
o.push_user = o.push_user.or(f.push_user.clone());
}
o
}
#[test]
fn the_pull_refuses_each_http_field_for_an_ssh_address() {
let fields = http_fields();
for (first, (name, _)) in fields.iter().enumerate() {
let o = EndpointOverrides {
url: Some("user-QXZ@h:x".into()),
..from_field(&fields, first)
};
assert_eq!(
invalid_input(pull(None, "r", o)),
format!("{name} applies to a pull over HTTP, and 'ssh://h/~/x' is an ssh address")
);
}
let o = EndpointOverrides {
url: Some("ssh://h/x".into()),
max_retries: Some(0),
..EndpointOverrides::default()
};
ssh(pull(None, "r", o));
}
#[test]
fn the_refusal_of_an_http_field_shows_no_user_name() {
for (written, shown) in [
("ssh://user-QXZ@ex.com/srv/repo", "ssh://ex.com/srv/repo"),
("user-QXZ@ex.com:srv/repo", "ssh://ex.com/~/srv/repo"),
("ssh://user-QXZ@ex.com/srv/a@b", "ssh://ex.com/srv/a@b"),
] {
let o = EndpointOverrides {
url: Some(written.into()),
http_headers: vec![("A".into(), "B".into())],
..EndpointOverrides::default()
};
let msg = invalid_input(pull(None, "r", o));
assert!(!msg.contains("QXZ"), "{written}: {msg}");
assert_eq!(
msg,
format!("http-header applies to a pull over HTTP, and '{shown}' is an ssh address")
);
}
}
#[test]
fn a_url_override_keeps_the_tls_and_proxy_keys_of_the_section() {
let dir = Dir::new();
let config = tls_keys(&dir, "https://ex.com/repo");
let o = EndpointOverrides {
url: Some("https://other.ex.com/".into()),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&config), "keys", o));
assert_eq!(http.mirrors, ["https://other.ex.com/"]);
assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
assert!(matches!(&http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
}
const LOCAL_SECTIONS: &str = "[remote \"url\"]\nurl=file:///srv/repo\n\n\
[remote \"upper\"]\npull-url=FILE:///srv/a@b c\n\
url=https://ex.com/repo\n\n\
[remote \"http-pull-url\"]\npull-url=https://ex.com/repo\n\
url=file:///srv/repo\n\n\
[remote \"http\"]\nurl=https://ex.com/repo\n\n\
[remote \"ssh\"]\npull-url=ssh://h/srv/repo\n\n\
[remote \"keys\"]\nurl=file:///srv/repo\n\
tls-ca-path=/nowhere/ca.pem\nproxy=http://proxy.ex.com\n\
ssh-command=ssh -q\nsend-command=ostrya send\n\n\
[remote \"s3-key\"]\nurl=file:///srv/repo\n\
s3-region=eu-west-1\n\n\
[remote \"none\"]\ngpg-verify=false\n";
fn local(remote: &str, o: &EndpointOverrides) -> Result<Option<PathBuf>> {
local_pull_path(config(LOCAL_SECTIONS).config(), remote, o)
}
#[test]
fn a_file_address_gives_the_path_of_a_local_repository() {
let d = EndpointOverrides::default();
assert_eq!(local("url", &d).unwrap(), Some("/srv/repo".into()));
assert_eq!(local("upper", &d).unwrap(), Some("/srv/a@b c".into()));
assert_eq!(local("keys", &d).unwrap(), Some("/srv/repo".into()));
for name in ["http-pull-url", "http", "ssh", "absent", "none"] {
assert_eq!(local(name, &d).unwrap(), None, "{name}");
}
let o = EndpointOverrides {
url: Some("file:////srv//x".into()),
..EndpointOverrides::default()
};
assert_eq!(local("http", &o).unwrap(), Some("//srv//x".into()));
let o = EndpointOverrides {
url: Some("https://ex.com/".into()),
..EndpointOverrides::default()
};
assert_eq!(local("url", &o).unwrap(), None);
}
#[test]
fn a_malformed_file_address_is_refused() {
for (address, reason) in [
("file://localhost/srv/repo", "names a host"),
("file://h/srv/repo", "names a host"),
("file://u-QXZ@h/srv/repo", "names a host"),
("file://", "has no path"),
("file:/srv/repo", "does not start with file://"),
("file:///srv/a%20b", "holds '%', '?', or '#'"),
("file:///srv/a?b", "holds '%', '?', or '#'"),
("file:///srv/a#b", "holds '%', '?', or '#'"),
] {
let config = config(&format!("[remote \"r\"]\nurl={address}\n"));
let msg = pull_error(local_pull_path(
config.config(),
"r",
&EndpointOverrides::default(),
));
assert!(!msg.contains("QXZ"), "{msg}");
assert!(
msg.starts_with("remote 'r': the file address '")
&& msg.contains(&format!("' {reason}; ")),
"{address}: {msg}"
);
}
}
#[test]
fn a_local_repository_refuses_the_fields_of_another_transport() {
let ssh = [
(
"ssh-command",
EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
..EndpointOverrides::default()
},
),
(
"send-command",
EndpointOverrides {
remote_command: Some("ostrya send".into()),
..EndpointOverrides::default()
},
),
];
let fields = http_fields().into_iter().chain(s3_fields()).chain(ssh);
for (name, o) in fields {
let msg = invalid_input(local("url", &o));
assert!(
msg.starts_with(&format!("{name} applies to "))
&& msg.ends_with("the pull address of remote 'url' is a local repository"),
"{msg}"
);
}
let o = EndpointOverrides {
push_user: Some("u".into()),
..EndpointOverrides::default()
};
assert_eq!(
invalid_input(local("url", &o)),
"push-user applies to a push, and this is a pull"
);
let o = EndpointOverrides {
max_retries: Some(0),
..EndpointOverrides::default()
};
assert_eq!(local("url", &o).unwrap(), Some("/srv/repo".into()));
let msg = pull_error(local("s3-key", &EndpointOverrides::default()));
assert!(
msg.contains("s3-region applies to an s3:// address"),
"{msg}"
);
}
fn in_time<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
let worker = std::thread::spawn(f);
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !worker.is_finished() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(worker.is_finished(), "the read does not end in 10 seconds");
worker.join().unwrap()
}
fn make_fifo(path: &Path) -> bool {
rustix::fs::mknodat(
rustix::fs::CWD,
path,
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o600),
0,
)
.is_ok()
}
#[test]
fn a_relative_tls_key_is_relative_to_the_repository_root() {
let repo = config(
"[remote \"rel\"]\nurl=https://ex.com/repo\ntls-ca-path=certs/ca.pem\n\
tls-client-cert-path=certs/link.pem\ntls-client-key-path=certs/key.pem\n\
[remote \"up\"]\nurl=https://ex.com/repo\ntls-ca-path=../ca.pem\n",
);
let certs = repo.path().join("certs");
std::fs::create_dir(&certs).unwrap();
let m = not_found(pull(Some(&repo), "rel", EndpointOverrides::default()));
assert!(m.starts_with("tls-ca-path 'certs/ca.pem': "), "{m}");
std::fs::write(certs.join("ca.pem"), b"ROOT-CA").unwrap();
std::fs::write(certs.join("cert.pem"), b"ROOT-CERT").unwrap();
std::fs::write(certs.join("key.pem"), b"ROOT-KEY").unwrap();
std::os::unix::fs::symlink(certs.join("cert.pem"), certs.join("link.pem")).unwrap();
let http = http_of(pull(Some(&repo), "rel", EndpointOverrides::default()));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"ROOT-CA".to_vec()));
assert_eq!(
identity(&http),
(b"ROOT-CERT".to_vec(), b"ROOT-KEY".to_vec())
);
let err = pull(Some(&repo), "up", EndpointOverrides::default()).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[remote \"up\"] tls-ca-path \
../ca.pem has a `..` component, which a relative path in a config cannot have"),
"{err:?}"
);
let o = EndpointOverrides {
tls_ca_path: Some("../ca.pem".into()),
..EndpointOverrides::default()
};
assert_eq!(
invalid_input(pull(Some(&repo), "rel", o)),
"tls-ca-path ../ca.pem is a relative path with a `..` component"
);
let o = EndpointOverrides {
tls_ca_path: Some(certs.join("../certs/ca.pem")),
..EndpointOverrides::default()
};
let http = http_of(pull(Some(&repo), "rel", o));
assert_eq!(http.tls.roots, TrustRoots::Pem(b"ROOT-CA".to_vec()));
}
#[test]
fn a_tls_path_that_is_not_a_regular_file_fails_the_pull() {
let dir = Dir::new();
let fifo = dir.absent("fifo.pem");
let mut paths = vec![dir.0.clone(), PathBuf::from("/dev/null")];
if make_fifo(&fifo) {
paths.push(fifo);
}
for path in paths {
let o = EndpointOverrides {
url: Some("https://ex.com/repo".into()),
tls_ca_path: Some(path.clone()),
..EndpointOverrides::default()
};
let result = in_time(move || pull(None, "r", o));
assert_eq!(
invalid_input(result),
format!("tls-ca-path '{}' is not a regular file", path.display())
);
}
}
#[cfg(feature = "push")]
mod push {
use super::*;
const CONFIG: &str = "[remote \"both\"]\nurl=https://ex.com/pull\n\
push-url=ssh://pusher@ex.com/srv/repo\n\
ssh-command=ssh -o BatchMode=yes\n\
receive-command=/opt/bin/ostrya receive\n\
push-token-file=/etc/ostrya/ssh-token\n\
push-user=ssh-user\n\
tls-ca-path=/etc/ostrya/ssh-ca.pem\n\
tls-client-cert-path=/etc/ostrya/ssh-client.pem\n\
tls-client-key-path=/etc/ostrya/ssh-client.key\n\
tls-permissive=true\n\n\
[remote \"https\"]\nurl=https://ex.com/repo\n\n\
[remote \"http-push-url\"]\nurl=https://pull.ex.com/repo\n\
push-url=http://push.ex.com/\n\n\
[remote \"permissive\"]\nurl=https://ex.com/repo\n\
tls-permissive=true\n\n\
[remote \"permissive-push-url\"]\nurl=https://ex.com/repo\n\
push-url=https://push.ex.com/\n\
tls-permissive=true\n\n\
[remote \"permissive-http\"]\nurl=https://ex.com/repo\n\
push-url=http://push.ex.com/\n\
tls-permissive=true\n\n\
[remote \"permissive-bad\"]\nurl=http://ex.com/repo\n\
tls-permissive=maybe\n\n\
[remote \"http\"]\nurl=http://ex.com/repo\n\n\
[remote \"file\"]\nurl=file:///srv/repo\n\n\
[remote \"metalink\"]\nurl=metalink=https://ex.com/metalink.xml\n\n\
[remote \"mirrorlist\"]\nurl=mirrorlist=https://ex.com/mirrors\n\n\
[remote \"none\"]\ngpg-verify=false\n\n\
[remote \"file-push\"]\nurl=file:///srv/repo\n\
push-url=host:srv/repo\n\n\
[remote \"bad-url\"]\nurl=a\\zb\n\
push-url=ssh://h/p\n";
fn push(repo: Option<&TestRepo>, remote: &str, o: EndpointOverrides) -> Result<Endpoint> {
ostrya_rt::block_on(resolve_push(handle(repo), remote, o))
}
fn push_named(name: &str) -> Result<Endpoint> {
push(Some(&config(CONFIG)), name, EndpointOverrides::default())
}
fn refused<T: fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::Remote(remote::Error::InvalidInput(msg))) => msg,
other => panic!("expected InvalidInput, got {other:?}"),
}
}
fn address(endpoint: Result<Endpoint>) -> String {
match endpoint {
Ok(Endpoint::Http(http)) => {
assert_eq!(http.mirrors.len(), 1);
http.mirrors[0].clone()
}
Ok(Endpoint::Ssh { address, .. }) => address.to_string(),
other => panic!("{other:?}"),
}
}
fn parsed(value: &str) -> String {
address(Endpoint::parse(value).map_err(Error::Remote))
}
#[test]
fn a_value_with_a_colon_or_a_slash_is_an_address() {
let cfg = config(CONFIG);
for value in [
"host:srv/repo",
"host:repo",
"ssh://host/srv/repo",
"https://ex.com/r",
] {
let endpoint = push(Some(&cfg), value, EndpointOverrides::default());
assert_eq!(address(endpoint), parsed(value));
}
let (address, options) = ssh(push(None, "host:srv/repo", EndpointOverrides::default()));
assert_eq!(address, SshAddress::parse("host:srv/repo").unwrap());
assert_eq!(options, SshOptions::default());
let http = http_of(push(None, "https://ex.com/r", EndpointOverrides::default()));
assert!(matches!(http.proxy, Proxy::Environment));
assert_eq!(http.tls, TlsOptions::default());
for value in ["ftp://host/r", "srv/repo"] {
let expected = match Endpoint::parse(value) {
Err(remote::Error::InvalidInput(msg)) => msg,
other => panic!("{value}: {other:?}"),
};
assert_eq!(
refused(push(Some(&cfg), value, EndpointOverrides::default())),
expected
);
}
}
#[test]
fn push_url_wins_over_url() {
assert_eq!(
address(push_named("both")),
parsed("ssh://pusher@ex.com/srv/repo")
);
assert_eq!(address(push_named("file-push")), parsed("host:srv/repo"));
assert!(
config(CONFIG)
.config()
.section::<config::remote::Group>("bad-url")
.unwrap()
.get::<config::remote::Url>()
.is_err()
);
assert_eq!(address(push_named("bad-url")), parsed("ssh://h/p"));
}
#[test]
fn an_http_url_is_the_address_when_push_url_is_absent() {
assert_eq!(address(push_named("https")), "https://ex.com/repo");
assert_eq!(address(push_named("http")), "http://ex.com/repo");
assert_eq!(address(push_named("http-push-url")), "http://push.ex.com/");
}
#[test]
fn a_url_of_another_form_is_no_push_address() {
for name in ["file", "metalink", "mirrorlist"] {
let msg = refused(push_named(name));
assert!(msg.contains("is no push address"), "{msg}");
}
assert_eq!(
refused(push_named("none")),
"remote 'none' has no push-url and no url"
);
let cfg = config(
"[remote \"upper\"]\nurl=HTTPS://user-QXZ:pw-QXZ@ex.com/repo\n\n\
[remote \"ftp\"]\nurl=ftp://user-QXZ:pw-QXZ@ex.com/repo\n",
);
for (name, shown) in [
("upper", "HTTPS://ex.com/repo"),
("ftp", "ftp://ex.com/repo"),
] {
let msg = refused(push(Some(&cfg), name, EndpointOverrides::default()));
assert!(!msg.contains("QXZ"), "{name}: {msg}");
assert_eq!(
msg,
format!(
"remote '{name}' has no push-url, and its url '{shown}' is no push \
address"
)
);
}
}
#[test]
fn an_unknown_remote_is_refused_by_the_push() {
assert_eq!(
refused(push_named("absent")),
"no remote 'absent' is configured"
);
assert_eq!(
refused(push(None, "both", EndpointOverrides::default())),
"no remote 'both' is configured"
);
}
#[test]
fn the_push_refuses_a_url_override() {
for remote in ["https", "host:srv/repo", "absent"] {
let o = EndpointOverrides {
url: Some("https://ex.com/repo".into()),
..EndpointOverrides::default()
};
assert_eq!(
refused(push(Some(&config(CONFIG)), remote, o)),
"url applies to a pull, and this is a push"
);
}
}
#[test]
fn the_push_refuses_tls_permissive_for_https() {
for name in ["permissive", "permissive-push-url"] {
assert_eq!(
refused(push_named(name)),
format!(
"remote '{name}' sets tls-permissive=true, which a push refuses: a \
push verifies the certificate chain of the server"
)
);
}
assert_eq!(
address(push_named("permissive-http")),
"http://push.ex.com/"
);
assert_eq!(address(push_named("permissive-bad")), "http://ex.com/repo");
push(
Some(&config(CONFIG)),
"https://ex.com/repo",
EndpointOverrides::default(),
)
.unwrap();
}
#[test]
fn the_push_reads_the_proxy_key() {
let dir = Dir::new();
let cfg = tls_keys(&dir, "https://ex.com/repo");
let http = http_of(push(Some(&cfg), "keys", EndpointOverrides::default()));
assert!(matches!(&http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
let http = http_of(push_named("https"));
assert!(matches!(http.proxy, Proxy::Environment));
let cfg = config(&format!(
"[remote \"p\"]\nurl=https://ex.com/repo\nproxy=\\s\npush-token-file={}\n",
dir.absent("absent").display()
));
match push(Some(&cfg), "p", EndpointOverrides::default()) {
Err(Error::Unsupported(msg)) => assert!(msg.contains("white space"), "{msg}"),
other => panic!("{other:?}"),
}
}
#[test]
fn the_push_passes_a_socks5h_proxy_unchanged() {
let cfg = config(
"[remote \"socks\"]\nurl=https://ex.com/repo\n\
proxy=socks5h://u:p@proxy.ex.com:1080\n",
);
let http = http_of(push(Some(&cfg), "socks", EndpointOverrides::default()));
assert!(
matches!(&http.proxy, Proxy::Url(url) if url == "socks5h://u:p@proxy.ex.com:1080")
);
}
#[test]
fn a_push_token_gives_a_bearer_token_or_a_basic_credential() {
let dir = Dir::new();
let cfg = tls_keys(&dir, "https://ex.com/repo");
let http = http_of(push(Some(&cfg), "keys", EndpointOverrides::default()));
assert_eq!(
http.basic_auth,
Some(BasicAuth {
user: "alice".into(),
password: "KEY-TOKEN".into()
})
);
assert_eq!(http.bearer_token, None);
assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
let token = dir.file("t", b"s3cr3t==\n");
let o = EndpointOverrides {
push_token_file: Some(token),
..EndpointOverrides::default()
};
let http = http_of(push(None, "https://ex.com/r", o));
assert_eq!(
http.bearer_token,
Some(BearerToken {
token: "s3cr3t==".into()
})
);
assert_eq!(http.basic_auth, None);
let http = http_of(push_named("https"));
assert_eq!(http.bearer_token, None);
assert_eq!(http.basic_auth, None);
}
#[test]
fn a_relative_push_token_file_is_relative_to_the_repository_root() {
let cfg = config(
"[remote \"rel\"]\npush-url=https://ex.com/r\npush-token-file=t/token\n\
[remote \"up\"]\npush-url=https://ex.com/r\npush-token-file=../token\n\
[remote \"fifo\"]\npush-url=https://ex.com/r\npush-token-file=t/fifo\n",
);
std::fs::create_dir(cfg.path().join("t")).unwrap();
let m = not_found(push(Some(&cfg), "rel", EndpointOverrides::default()));
assert!(m.starts_with("push-token-file 't/token': "), "{m}");
std::fs::write(cfg.path().join("t/token"), b"r00t==\n").unwrap();
let http = http_of(push(Some(&cfg), "rel", EndpointOverrides::default()));
assert_eq!(
http.bearer_token,
Some(BearerToken {
token: "r00t==".into()
})
);
let err = push(Some(&cfg), "up", EndpointOverrides::default()).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m.starts_with("[remote \"up\"] push-token-file ../token has a `..`")),
"{err:?}"
);
let o = EndpointOverrides {
push_token_file: Some("../token".into()),
..EndpointOverrides::default()
};
assert_eq!(
refused(push(Some(&cfg), "rel", o)),
"push-token-file ../token is a relative path with a `..` component"
);
if make_fifo(&cfg.path().join("t/fifo")) {
let root = cfg.path().to_owned();
let result = in_time(move || {
let repo = ostrya_rt::block_on(Repo::open(&root)).unwrap();
ostrya_rt::block_on(resolve_push(
Some(&repo),
"fifo",
EndpointOverrides::default(),
))
});
assert_eq!(
invalid_input(result),
"push-token-file 't/fifo' is not a regular file"
);
}
}
#[test]
fn an_override_wins_over_each_key_of_the_push() {
let dir = Dir::new();
let cfg = tls_keys(&dir, "https://ex.com/repo");
let [ca, cert, key, token] = given(&dir);
let resolve = |o: EndpointOverrides| http_of(push(Some(&cfg), "keys", o));
let d = EndpointOverrides::default;
let http = resolve(EndpointOverrides {
push_token_file: Some(token),
..d()
});
assert_eq!(http.basic_auth.unwrap().password, "GIVEN-TOKEN");
let http = resolve(EndpointOverrides {
push_user: Some("bob".into()),
..d()
});
let auth = http.basic_auth.unwrap();
assert_eq!(
(auth.user.as_str(), auth.password.as_str()),
("bob", "KEY-TOKEN")
);
let http = resolve(EndpointOverrides {
tls_ca_path: Some(ca),
..d()
});
assert_eq!(http.tls.roots, TrustRoots::Pem(b"GIVEN-CA".to_vec()));
assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
let http = resolve(EndpointOverrides {
tls_client_cert_path: Some(cert),
..d()
});
assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
assert_eq!(
identity(&http),
(b"GIVEN-CERT".to_vec(), b"KEY-KEY".to_vec())
);
let http = resolve(EndpointOverrides {
tls_client_key_path: Some(key),
..d()
});
assert_eq!(
identity(&http),
(b"KEY-CERT".to_vec(), b"GIVEN-KEY".to_vec())
);
}
#[test]
fn the_push_applies_the_http_overrides() {
let defaults = FetcherOptions::default();
let http = http_of(push_named("https"));
assert_eq!(http.max_retries, defaults.max_retries);
assert_eq!(http.max_outstanding, defaults.max_outstanding);
assert_eq!(http.low_speed, None);
assert!(http.headers.is_empty());
assert!(!http.allow_cleartext_credentials);
let o = EndpointOverrides {
http_headers: vec![("X-A".into(), "b".into())],
allow_cleartext_credentials: true,
max_retries: Some(0),
..EndpointOverrides::default()
};
let http = http_of(push(Some(&config(CONFIG)), "https", o));
assert_eq!(http.headers, [("X-A".to_owned(), "b".to_owned())]);
assert!(http.allow_cleartext_credentials);
assert_eq!(http.max_retries, 0);
let secs = Duration::from_secs;
for (limit, time, expected) in [
(Some(5), None, Some((5, secs(30)))),
(None, Some(secs(10)), Some((1000, secs(10)))),
(Some(5), Some(secs(10)), Some((5, secs(10)))),
(Some(0), None, None),
(None, Some(Duration::ZERO), None),
] {
let o = EndpointOverrides {
low_speed_limit_bytes: limit,
low_speed_time: time,
..EndpointOverrides::default()
};
let http = http_of(push(Some(&config(CONFIG)), "https", o));
let expected = expected.map(|(limit, time)| LowSpeed { limit, time });
assert_eq!(http.low_speed, expected, "{limit:?} {time:?}");
}
}
#[test]
fn push_user_needs_a_token_file() {
let dir = Dir::new();
let o = EndpointOverrides {
push_user: Some("alice".into()),
..EndpointOverrides::default()
};
assert_eq!(
refused(push(None, "https://h/", o)),
"push-user needs push-token-file"
);
for user in ["", "a:b"] {
let o = EndpointOverrides {
push_user: Some(user.into()),
push_token_file: Some(dir.absent("absent")),
..EndpointOverrides::default()
};
assert_eq!(
refused(push(None, "https://h/", o)),
"push-user is empty or holds ':', which a Basic credential cannot carry"
);
}
}
#[test]
fn the_push_refuses_a_cleartext_token_before_it_reads_a_file() {
let dir = Dir::new();
let absent = dir.absent("absent");
let expected = |address: &str| {
format!(
"the push address '{address}' is http://, so the token would travel in \
cleartext: use https, or set allow-cleartext-credentials"
)
};
let o = EndpointOverrides {
push_token_file: Some(absent.clone()),
tls_ca_path: Some(absent.clone()),
..EndpointOverrides::default()
};
assert_eq!(refused(push(None, "http://h/", o)), expected("http://h/"));
let cfg = config(&format!(
"[remote \"keys\"]\nurl=http://ex.com/repo\n\
push-token-file={0}\ntls-ca-path={0}\n",
absent.display()
));
assert_eq!(
refused(push(Some(&cfg), "keys", EndpointOverrides::default())),
expected("http://ex.com/repo")
);
}
#[test]
fn the_cleartext_permission_lets_a_token_go_to_an_http_address() {
let dir = Dir::new();
let cfg = tls_keys(&dir, "http://ex.com/repo");
let o = EndpointOverrides {
allow_cleartext_credentials: true,
..EndpointOverrides::default()
};
let http = http_of(push(Some(&cfg), "keys", o));
assert!(http.allow_cleartext_credentials);
assert_eq!(
http.basic_auth,
Some(BasicAuth {
user: "alice".into(),
password: "KEY-TOKEN".into()
})
);
assert_eq!(http.tls, TlsOptions::default());
let o = EndpointOverrides {
push_token_file: Some(dir.file("t", b"s3cr3t==\n")),
allow_cleartext_credentials: true,
..EndpointOverrides::default()
};
let http = http_of(push(None, "http://h/", o));
assert_eq!(
http.bearer_token,
Some(BearerToken {
token: "s3cr3t==".into()
})
);
}
#[test]
fn a_cleartext_push_reads_no_tls_file() {
let dir = Dir::new();
let absent = dir.absent("absent");
let o = EndpointOverrides {
tls_ca_path: Some(absent.clone()),
tls_client_cert_path: Some(absent.clone()),
tls_client_key_path: Some(absent.clone()),
..EndpointOverrides::default()
};
let http = http_of(push(None, "http://h/", o));
assert_eq!(http.tls, TlsOptions::default());
let cfg = config(&format!(
"[remote \"keys\"]\nurl=http://ex.com/repo\n\
tls-ca-path={0}\ntls-client-cert-path={0}\ntls-client-key-path={0}\n",
absent.display()
));
let http = http_of(push(Some(&cfg), "keys", EndpointOverrides::default()));
assert_eq!(http.tls, TlsOptions::default());
}
#[test]
fn the_push_session_refuses_an_authorization_header_beside_a_token() {
let dir = Dir::new();
let token = dir.file("t", b"s3cr3t==\n");
for (user, part) in [
(None, "a bearer token and an authorization header"),
(
Some("alice"),
"basic-auth credentials and an authorization header",
),
] {
let o = EndpointOverrides {
push_token_file: Some(token.clone()),
push_user: user.map(str::to_owned),
http_headers: vec![("Authorization".into(), "Bearer other".into())],
..EndpointOverrides::default()
};
let endpoint = push(None, "https://h/", o).unwrap();
match ostrya_rt::block_on(remote::PushSession::prepare(endpoint)) {
Err(remote::Error::Fetch(e)) => {
let msg = e.to_string();
assert!(msg.contains(part), "{msg}");
assert!(!msg.contains("s3cr3t"), "{msg}");
}
other => panic!("{user:?}: {other:?}"),
}
}
}
#[test]
fn a_lone_certificate_or_key_is_refused_by_the_push() {
let dir = Dir::new();
let absent = dir.absent("absent");
for (cert, key) in [(Some(absent.clone()), None), (None, Some(absent.clone()))] {
for address in ["https://h/", "http://h/"] {
let o = EndpointOverrides {
push_token_file: Some(absent.clone()),
tls_ca_path: Some(absent.clone()),
tls_client_cert_path: cert.clone(),
tls_client_key_path: key.clone(),
..EndpointOverrides::default()
};
assert_eq!(
refused(push(None, address, o)),
"a client certificate needs both tls-client-cert-path and \
tls-client-key-path"
);
}
}
}
#[test]
fn a_file_over_the_cap_fails_the_push() {
let dir = Dir::new();
let long = dir.file("long", &vec![b'a'; FILE_CAP as usize + 1]);
let absent = dir.absent("absent");
let pem = dir.file("pem", b"");
type Field = fn(&mut EndpointOverrides) -> &mut Option<PathBuf>;
let cases: [(&str, Field); 4] = [
("push-token-file", |o| &mut o.push_token_file),
("tls-ca-path", |o| &mut o.tls_ca_path),
("tls-client-cert-path", |o| &mut o.tls_client_cert_path),
("tls-client-key-path", |o| &mut o.tls_client_key_path),
];
for (key, field) in cases {
let mut o = EndpointOverrides {
tls_client_cert_path: Some(pem.clone()),
tls_client_key_path: Some(pem.clone()),
..EndpointOverrides::default()
};
*field(&mut o) = Some(long.clone());
let msg = invalid_input(push(None, "https://h/", o.clone()));
assert!(
msg.contains(&format!("{key} '{}'", long.display())),
"{msg}"
);
assert!(msg.ends_with("over 1 MiB"), "{msg}");
*field(&mut o) = Some(absent.clone());
let m = not_found(push(None, "https://h/", o));
assert!(
m.starts_with(&format!("{key} '{}': ", absent.display())),
"{m}"
);
}
}
#[test]
fn the_push_refuses_the_ssh_fields_for_an_http_address() {
for (name, o) in [
(
"ssh-command",
EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
remote_command: Some("ostrya receive".into()),
..EndpointOverrides::default()
},
),
(
"receive-command",
EndpointOverrides {
remote_command: Some("ostrya receive".into()),
..EndpointOverrides::default()
},
),
] {
assert_eq!(
refused(push(None, "https://h/", o)),
format!(
"{name} applies to an ssh address, and 'https://h/' is an HTTP address"
)
);
}
let cfg = config(
"[remote \"bad-ssh\"]\nurl=https://ex.com/repo\n\
ssh-command=a\\zb\nreceive-command=a\\zb\n",
);
let section = cfg
.config()
.section::<config::remote::Group>("bad-ssh")
.unwrap();
assert!(section.get::<config::remote::SshCommand>().is_err());
assert!(section.get::<config::remote::ReceiveCommand>().is_err());
assert_eq!(
address(push(Some(&cfg), "bad-ssh", EndpointOverrides::default())),
"https://ex.com/repo"
);
}
#[test]
fn the_push_fills_the_ssh_options_from_the_keys() {
let (_, options) = ssh(push_named("both"));
assert_eq!(
options,
SshOptions {
command: None,
config_command: Some("ssh -o BatchMode=yes".into()),
remote_command: Some("/opt/bin/ostrya receive".into()),
}
);
let o = EndpointOverrides {
ssh_command: Some(vec!["my-ssh".into()]),
remote_command: Some("receiver".into()),
..EndpointOverrides::default()
};
let (_, options) = ssh(push(Some(&config(CONFIG)), "both", o.clone()));
assert_eq!(
options,
SshOptions {
command: Some(vec!["my-ssh".into()]),
config_command: Some("ssh -o BatchMode=yes".into()),
remote_command: Some("receiver".into()),
}
);
let (_, options) = ssh(push(None, "h:r", o));
assert_eq!(options.config_command, None);
assert_eq!(options.remote_command.as_deref(), Some("receiver"));
}
#[test]
fn the_push_refuses_each_http_field_for_an_ssh_address() {
let d = EndpointOverrides::default;
let mut fields = vec![
(
"push-token-file",
EndpointOverrides {
push_token_file: Some("/t".into()),
..d()
},
),
(
"push-user",
EndpointOverrides {
push_user: Some("u".into()),
..d()
},
),
];
fields.extend(http_fields());
for (first, (name, _)) in fields.iter().enumerate() {
let o = from_field(&fields, first);
assert_eq!(
refused(push(None, "user-QXZ@h:x", o)),
format!(
"{name} applies to an HTTP address, and 'ssh://h/~/x' is an ssh address"
)
);
}
for (value, shown) in [
("ssh://user-QXZ@ex.com/srv/repo", "ssh://ex.com/srv/repo"),
("user-QXZ@ex.com:srv/a@b", "ssh://ex.com/~/srv/a@b"),
] {
let o = EndpointOverrides {
push_user: Some("u".into()),
..d()
};
assert_eq!(
refused(push(None, value, o)),
format!(
"push-user applies to an HTTP address, and '{shown}' is an ssh address"
)
);
}
let o = EndpointOverrides {
max_retries: Some(0),
..d()
};
ssh(push(None, "h:x", o));
}
#[test]
fn the_push_refuses_the_s3_fields_for_another_address() {
for (name, o) in s3_fields() {
for (remote, shown) in [
("https", "'https://ex.com/repo' is an HTTP address"),
("https://ex.com/r", "'https://ex.com/r' is an HTTP address"),
("ssh://u-QXZ@h/r", "'ssh://h/r' is an ssh address"),
] {
assert_eq!(
refused(push(Some(&config(CONFIG)), remote, o.clone())),
format!("{name} applies to an s3:// address, and {shown}")
);
}
}
}
#[test]
fn an_s3_address_in_url_is_no_push_address() {
let config = config(S3_SECTIONS);
for name in ["s3-url", "s3-url-user"] {
assert_eq!(
refused(push(Some(&config), name, EndpointOverrides::default())),
format!(
"remote '{name}' has no push-url, and its url 's3://bkt/repo' is an \
s3:// address; the port reads an s3:// address from push-url alone"
)
);
}
}
#[test]
fn an_s3_key_with_no_s3_address_is_refused_by_the_push() {
let config = config(S3_SECTIONS);
assert_eq!(
refused(push(
Some(&config),
"stray-key",
EndpointOverrides::default()
)),
"remote 'stray-key': s3-profile applies to an s3:// address, and neither \
pull-url nor push-url holds one"
);
}
#[cfg(not(feature = "s3"))]
#[test]
fn a_build_without_s3_refuses_an_s3_push_address() {
let config = config(S3_SECTIONS);
for result in [
push(Some(&config), "push", EndpointOverrides::default()),
push(
None,
"s3://AKID-QXZ:s@bkt/repo",
EndpointOverrides::default(),
),
] {
match result {
Err(Error::Unsupported(msg)) => {
assert!(msg.contains("the feature s3 of ostrya"), "{msg}");
assert!(msg.contains("'s3://bkt/repo'"), "{msg}");
assert!(!msg.contains("QXZ"), "{msg}");
}
other => panic!("{other:?}"),
}
}
}
#[test]
fn check_push_gives_the_refusals_of_resolve_push_that_need_no_file() {
let dir = Dir::new();
let config = config(CONFIG);
let d = EndpointOverrides::default;
let cases = [
(
"https",
EndpointOverrides {
url: Some("https://ex.com/".into()),
..d()
},
),
("absent", d()),
("none", d()),
("permissive", d()),
("file", d()),
(
"https",
EndpointOverrides {
s3_region: Some("eu-west-1".into()),
..d()
},
),
(
"https",
EndpointOverrides {
remote_command: Some("receive".into()),
..d()
},
),
(
"https",
EndpointOverrides {
push_user: Some(String::new()),
push_token_file: Some(dir.absent("token")),
..d()
},
),
(
"http",
EndpointOverrides {
push_token_file: Some(dir.absent("token")),
..d()
},
),
(
"both",
EndpointOverrides {
push_user: Some("u".into()),
..d()
},
),
];
for (name, o) in cases {
let checked = check_push(Some(config.config()), name, o.clone());
let resolved = push(Some(&config), name, o);
assert!(checked.is_err(), "{name}: {checked:?}");
assert_eq!(
format!("{checked:?}"),
format!("{:?}", resolved.map(drop)),
"{name}"
);
}
}
#[test]
fn check_push_reads_no_file_and_checks_the_ssh_command() {
let dir = Dir::new();
let o = EndpointOverrides {
push_token_file: Some(dir.absent("token")),
push_user: Some("alice".into()),
tls_ca_path: Some(dir.absent("ca.pem")),
..EndpointOverrides::default()
};
assert_eq!(
check_push(None, "https://h/", o.clone()).unwrap(),
PushKind::Session
);
assert!(matches!(push(None, "https://h/", o), Err(Error::Io(_))));
let ssh = |command: Vec<String>| EndpointOverrides {
ssh_command: Some(command),
..EndpointOverrides::default()
};
assert_eq!(
check_push(None, "ssh://h/srv/repo", ssh(vec!["ssh".into()])).unwrap(),
PushKind::Session
);
push(None, "ssh://h/srv/repo", ssh(Vec::new())).unwrap();
match check_push(None, "ssh://h/srv/repo", ssh(Vec::new())) {
Err(Error::Remote(remote::Error::InvalidInput(msg))) => {
assert_eq!(msg, "the ssh command of the options is empty")
}
other => panic!("{other:?}"),
}
let o = EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
remote_command: Some(" ".into()),
..EndpointOverrides::default()
};
assert!(matches!(
check_push(None, "ssh://h/srv/repo", o),
Err(Error::Remote(remote::Error::InvalidInput(_)))
));
}
#[test]
fn check_push_makes_the_refusals_of_the_push_session_that_need_no_file() {
let dir = Dir::new();
let config = config(
"[remote \"proxied\"]\nurl=https://h/repo\nproxy=ftp://proxy:3128\n\n\
[remote \"plain\"]\nurl=https://h/repo\nproxy=http://proxy:3128\n\n\
[remote \"cleartext\"]\nurl=http://h/repo\nproxy=http://proxy:3128\n",
);
let d = EndpointOverrides::default;
let headers = |pairs: &[(&str, &str)]| EndpointOverrides {
http_headers: pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect(),
..d()
};
for (name, o) in [
("proxied", d()),
("plain", headers(&[("Host", "other")])),
("plain", headers(&[("Connection", "close")])),
("cleartext", headers(&[("Cookie", "id=1")])),
("proxied", headers(&[("Host", "other")])),
] {
let endpoint = push(Some(&config), name, o.clone()).unwrap();
let prepared = ostrya_rt::block_on(remote::PushSession::prepare(endpoint))
.map(drop)
.map_err(Error::Remote);
let checked = check_push(Some(config.config()), name, o);
assert!(
matches!(checked, Err(Error::Remote(remote::Error::Fetch(_)))),
"{checked:?}"
);
assert_eq!(format!("{checked:?}"), format!("{prepared:?}"), "{name}");
}
assert_eq!(
check_push(Some(config.config()), "plain", d()).unwrap(),
PushKind::Session
);
let o = EndpointOverrides {
push_token_file: Some(dir.absent("token")),
..d()
};
assert!(matches!(
check_push(Some(config.config()), "proxied", o),
Err(Error::Remote(remote::Error::Fetch(_)))
));
}
}
fn s3_fields() -> Vec<(&'static str, EndpointOverrides)> {
let d = EndpointOverrides::default;
vec![
(
"s3-region",
EndpointOverrides {
s3_region: Some("eu-west-1".into()),
..d()
},
),
(
"s3-endpoint",
EndpointOverrides {
s3_endpoint: Some("https://s3.ex.com".into()),
..d()
},
),
(
"s3-addressing",
EndpointOverrides {
s3_addressing: Some("path".into()),
..d()
},
),
(
"s3-profile",
EndpointOverrides {
s3_profile: Some("p".into()),
..d()
},
),
]
}
const S3_SECTIONS: &str = "[remote \"s3-url\"]\nurl=s3://bkt/repo\n\n\
[remote \"s3-url-user\"]\nurl=s3://u-QXZ:p-QXZ@bkt/repo\n\n\
[remote \"pull\"]\npull-url=s3://bkt/repo\n\n\
[remote \"push\"]\nurl=https://ex.com/repo\n\
push-url=s3://bkt/repo\ns3-region=eu-west-1\n\n\
[remote \"stray-key\"]\nurl=https://ex.com/repo\n\
push-url=ssh://h/srv/repo\ns3-profile=p\n\n\
[remote \"stray-region\"]\npull-url=https://ex.com/repo\n\
s3-region=eu-west-1\ns3-endpoint=https://s3.ex.com\n";
#[test]
fn an_s3_address_in_url_is_refused() {
let config = config(S3_SECTIONS);
for name in ["s3-url", "s3-url-user"] {
let msg = pull_error(pull(Some(&config), name, EndpointOverrides::default()));
assert_eq!(
msg,
format!(
"remote '{name}': url 's3://bkt/repo' is an s3:// address; the port reads \
an s3:// address from pull-url alone"
)
);
}
}
#[test]
fn the_s3_test_of_a_pull_address_follows_the_order_of_the_pull() {
let local = config(
"[remote \"file-url\"]\nurl=file:///x\n\n\
[remote \"bad-file-url\"]\nurl=file:/x\n\n\
[remote \"path-url\"]\nurl=/srv/repo\n",
);
let config = config(S3_SECTIONS);
let is_s3 = |remote, url| pull_address_is_s3(Some(config.config()), remote, url);
assert_eq!(is_s3("pull", None), Some(true));
assert_eq!(is_s3("push", None), Some(false));
assert_eq!(is_s3("s3-url", None), None);
assert_eq!(is_s3("absent", None), None);
assert_eq!(is_s3("push", Some("s3://b/x")), Some(true));
assert_eq!(is_s3("pull", Some("https://ex.com/r")), Some(false));
assert_eq!(is_s3("pull", Some("h:/srv/r")), Some(false));
assert_eq!(is_s3("pull", Some("file:///x")), Some(false));
assert_eq!(is_s3("pull", Some("FILE:///x")), Some(false));
assert_eq!(is_s3("pull", Some("file:/x")), None);
assert_eq!(pull_address_is_s3(None, "r", Some("s3://b/x")), Some(true));
assert_eq!(pull_address_is_s3(None, "r", None), None);
let is_s3 = |remote| pull_address_is_s3(Some(local.config()), remote, None);
assert_eq!(is_s3("file-url"), Some(false));
assert_eq!(is_s3("bad-file-url"), None);
assert_eq!(is_s3("path-url"), None);
}
#[test]
fn the_kind_of_a_pull_address_follows_the_order_of_the_pull() {
let local = config(
"[remote \"file-url\"]\nurl=file:///x\n\n\
[remote \"file-pull-url\"]\npull-url=FILE:///x\nurl=https://ex.com/r\n\n\
[remote \"bad-file-url\"]\nurl=file:/x\n\n\
[remote \"path-url\"]\nurl=/srv/repo\n",
);
let config = config(S3_SECTIONS);
let kind = |remote, url| pull_address_kind(Some(config.config()), remote, url);
assert_eq!(kind("pull", None), Some(AddressKind::S3));
assert_eq!(kind("s3-url", None), None);
assert_eq!(kind("absent", None), None);
assert_eq!(
kind("pull", Some("https://ex.com/r")),
Some(AddressKind::Http)
);
assert_eq!(kind("pull", Some("h:/srv/r")), Some(AddressKind::Ssh));
assert_eq!(kind("pull", Some("file:///x")), Some(AddressKind::Local));
assert_eq!(kind("pull", Some("file:/x")), None);
assert_eq!(kind("pull", Some("ssh://")), None);
let kind = |remote| pull_address_kind(Some(local.config()), remote, None);
assert_eq!(kind("file-url"), Some(AddressKind::Local));
assert_eq!(kind("file-pull-url"), Some(AddressKind::Local));
assert_eq!(kind("bad-file-url"), None);
assert_eq!(kind("path-url"), None);
}
#[test]
fn an_s3_key_with_no_s3_address_is_refused() {
let config = config(S3_SECTIONS);
for (name, key, url) in [
("stray-key", "s3-profile", None),
("stray-region", "s3-region", None),
("stray-region", "s3-region", Some("s3://bkt/repo")),
] {
let o = EndpointOverrides {
url: url.map(str::to_owned),
..EndpointOverrides::default()
};
assert_eq!(
pull_error(pull(Some(&config), name, o)),
format!(
"remote '{name}': {key} applies to an s3:// address, and neither \
pull-url nor push-url holds one"
)
);
}
assert_eq!(
mirror(pull(Some(&config), "push", EndpointOverrides::default())),
"https://ex.com/repo"
);
}
#[test]
fn the_pull_refuses_the_s3_fields_for_another_address() {
for (name, o) in s3_fields() {
let http = EndpointOverrides {
url: Some("https://ex.com/repo".into()),
..o.clone()
};
assert_eq!(
invalid_input(pull(None, "r", http)),
format!(
"{name} applies to a pull from an s3:// address, and this pull runs over \
HTTP"
)
);
let ssh = EndpointOverrides {
url: Some("user-QXZ@h:x".into()),
..o
};
assert_eq!(
invalid_input(pull(None, "r", ssh)),
format!(
"{name} applies to a pull from an s3:// address, and 'ssh://h/~/x' is an \
ssh address"
)
);
}
}
#[test]
fn the_pull_refuses_the_fields_of_a_push_for_an_s3_address() {
for (name, o) in [
(
"push-token-file",
EndpointOverrides {
push_token_file: Some("/t".into()),
..EndpointOverrides::default()
},
),
(
"push-user",
EndpointOverrides {
push_user: Some("alice".into()),
..EndpointOverrides::default()
},
),
] {
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
..o
};
assert_eq!(
invalid_input(pull(None, "r", o)),
format!("{name} applies to a push, and this is a pull")
);
}
}
#[test]
fn the_debug_output_shows_no_userinfo_of_the_s3_endpoint() {
let o = EndpointOverrides {
s3_endpoint: Some("https://user-QXZ:pw-QXZ@s3.ex.com".into()),
s3_profile: Some("prod".into()),
..EndpointOverrides::default()
};
let text = format!("{o:?}");
assert!(!text.contains("QXZ"), "{text}");
assert!(text.contains("https://s3.ex.com"), "{text}");
assert!(text.contains("prod"), "{text}");
}
#[cfg(not(feature = "s3"))]
#[test]
fn a_build_without_s3_refuses_an_s3_address() {
let config = config(S3_SECTIONS);
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
..EndpointOverrides::default()
};
for result in [
pull(Some(&config), "pull", EndpointOverrides::default()),
pull(None, "r", o),
] {
match result {
Err(Error::Unsupported(msg)) => {
assert!(msg.contains("the feature s3 of ostrya"), "{msg}")
}
other => panic!("{other:?}"),
}
}
}
#[cfg(not(feature = "s3"))]
#[test]
fn the_refusal_of_an_s3_address_shows_no_userinfo() {
let config = config("[remote \"keyed\"]\npull-url=s3://AKID-QXZ:secret-QXZ@bkt/repo\n");
let o = EndpointOverrides {
url: Some("s3://AKID-QXZ:secret-QXZ@bkt/repo".into()),
..EndpointOverrides::default()
};
for result in [
pull(Some(&config), "keyed", EndpointOverrides::default()),
pull(None, "r", o),
] {
match result {
Err(Error::Unsupported(msg)) => {
assert!(!msg.contains("QXZ"), "{msg}");
assert!(msg.contains("'s3://bkt/repo'"), "{msg}");
}
other => panic!("{other:?}"),
}
}
}
#[cfg(feature = "s3")]
mod s3 {
use super::*;
use crate::remote::s3::{Addressing, Environment, S3Endpoint};
fn env(dir: &Dir, extra: &[(&str, &str)]) -> Environment {
let mut variables = vec![
("AWS_ACCESS_KEY_ID".to_owned(), "AKIDEXAMPLE".to_owned()),
("AWS_SECRET_ACCESS_KEY".to_owned(), "SECRET-QXZ".to_owned()),
(
"AWS_CONFIG_FILE".to_owned(),
dir.absent("aws-config").display().to_string(),
),
(
"AWS_SHARED_CREDENTIALS_FILE".to_owned(),
dir.absent("aws-credentials").display().to_string(),
),
];
variables.extend(
extra
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned())),
);
Environment::Variables(variables)
}
fn pull_in(
repo: Option<&TestRepo>,
remote: &str,
o: EndpointOverrides,
env: &Environment,
) -> Result<Endpoint> {
ostrya_rt::block_on(resolve_pull_in(handle(repo), remote, o, env))
}
fn s3_of(endpoint: Result<Endpoint>) -> S3Endpoint {
match endpoint {
Ok(Endpoint::S3(s3)) => s3,
other => panic!("{other:?}"),
}
}
#[test]
fn an_s3_address_gives_an_s3_endpoint() {
let dir = Dir::new();
let config = config(S3_SECTIONS);
let other = EndpointOverrides {
url: Some("s3://other/x".into()),
..EndpointOverrides::default()
};
for (name, o, repository) in [
(
"pull",
EndpointOverrides::default(),
"https://bkt.s3.us-east-1.amazonaws.com/repo",
),
(
"absent",
other,
"https://other.s3.us-east-1.amazonaws.com/x",
),
] {
let s3 = s3_of(pull_in(Some(&config), name, o, &env(&dir, &[])));
assert_eq!(s3.location.repository_url(), repository);
assert_eq!(s3.location.region(), "us-east-1");
assert_eq!(s3.credentials.access_key_id(), "AKIDEXAMPLE");
assert_eq!(s3.http.max_retries, 5);
assert_eq!(s3.http.max_outstanding, 8);
assert_eq!(
s3.http.low_speed,
Some(LowSpeed {
limit: 1000,
time: Duration::from_secs(30)
})
);
assert_eq!(s3.http.tls, TlsOptions::default());
assert!(matches!(s3.http.proxy, Proxy::Environment));
assert!(!s3.http.allow_cleartext_credentials);
assert!(s3.http.mirrors.is_empty());
assert!(s3.http.signer.is_none());
}
}
#[test]
fn an_override_wins_over_the_key_and_the_key_over_the_environment() {
let dir = Dir::new();
let config = config(
"[remote \"keys\"]\npull-url=s3://bkt/repo\ns3-region=eu-west-1\n\
s3-endpoint=https://keys.ex.com\ns3-addressing=virtual\n\n\
[remote \"bare\"]\npull-url=s3://bkt/repo\n",
);
let env = env(
&dir,
&[
("AWS_REGION", "us-west-2"),
("AWS_ENDPOINT_URL_S3", "https://env.ex.com"),
],
);
let s3 = s3_of(pull_in(
Some(&config),
"keys",
EndpointOverrides::default(),
&env,
));
assert_eq!(s3.location.region(), "eu-west-1");
assert_eq!(s3.location.endpoint(), "https://keys.ex.com");
assert_eq!(s3.location.addressing(), Addressing::Virtual);
assert_eq!(s3.location.repository_url(), "https://bkt.keys.ex.com/repo");
let o = EndpointOverrides {
s3_region: Some("ap-south-1".into()),
s3_endpoint: Some("https://given.ex.com".into()),
s3_addressing: Some("path".into()),
..EndpointOverrides::default()
};
let s3 = s3_of(pull_in(Some(&config), "keys", o, &env));
assert_eq!(s3.location.region(), "ap-south-1");
assert_eq!(s3.location.endpoint(), "https://given.ex.com");
assert_eq!(
s3.location.repository_url(),
"https://given.ex.com/bkt/repo"
);
let s3 = s3_of(pull_in(
Some(&config),
"bare",
EndpointOverrides::default(),
&env,
));
assert_eq!(s3.location.region(), "us-west-2");
assert_eq!(s3.location.endpoint(), "https://env.ex.com");
}
#[test]
fn a_profile_of_the_key_turns_off_the_keys_of_the_environment() {
let dir = Dir::new();
let credentials = dir.file(
"credentials",
b"[keyed]\naws_access_key_id = AKIDPROFILE\naws_secret_access_key = S\n",
);
let config = config("[remote \"p\"]\npull-url=s3://bkt/repo\ns3-profile=keyed\n");
let env = Environment::Variables(vec![
("AWS_ACCESS_KEY_ID".into(), "AKIDEXAMPLE".into()),
("AWS_SECRET_ACCESS_KEY".into(), "SECRET-QXZ".into()),
(
"AWS_CONFIG_FILE".into(),
dir.absent("config").display().to_string(),
),
(
"AWS_SHARED_CREDENTIALS_FILE".into(),
credentials.display().to_string(),
),
]);
let s3 = s3_of(pull_in(
Some(&config),
"p",
EndpointOverrides::default(),
&env,
));
assert_eq!(s3.credentials.access_key_id(), "AKIDPROFILE");
}
#[test]
fn a_bad_addressing_style_is_refused() {
let dir = Dir::new();
let config = config("[remote \"auto\"]\npull-url=s3://bkt/repo\ns3-addressing=auto\n");
assert_eq!(
invalid_input(pull_in(
Some(&config),
"auto",
EndpointOverrides::default(),
&env(&dir, &[])
)),
"s3-addressing 'auto' is neither path nor virtual"
);
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
s3_addressing: Some("Path".into()),
..EndpointOverrides::default()
};
assert_eq!(
invalid_input(pull_in(None, "r", o, &env(&dir, &[]))),
"s3-addressing 'Path' is neither path nor virtual"
);
}
#[test]
fn the_pull_refuses_the_ssh_fields_for_an_s3_address() {
let dir = Dir::new();
for (name, o) in [
(
"ssh-command",
EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
..EndpointOverrides::default()
},
),
(
"send-command",
EndpointOverrides {
remote_command: Some("ostrya send".into()),
..EndpointOverrides::default()
},
),
] {
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
..o
};
assert_eq!(
invalid_input(pull_in(None, "r", o, &env(&dir, &[]))),
format!(
"{name} applies to a pull over ssh, and this pull reads an s3:// \
address"
)
);
}
}
#[test]
fn an_http_endpoint_needs_the_cleartext_permission() {
let dir = Dir::new();
let config = config(S3_SECTIONS);
let env = env(&dir, &[("AWS_ENDPOINT_URL", "http://127.0.0.1:9000")]);
assert_eq!(
invalid_input(pull_in(
Some(&config),
"pull",
EndpointOverrides::default(),
&env,
)),
"the S3 endpoint 'http://127.0.0.1:9000' is http://, so the signature of each \
request would travel in cleartext: use https, or set \
allow-cleartext-credentials"
);
let o = EndpointOverrides {
allow_cleartext_credentials: true,
..EndpointOverrides::default()
};
let s3 = s3_of(pull_in(Some(&config), "pull", o, &env));
assert!(s3.http.allow_cleartext_credentials);
assert_eq!(
s3.location.repository_url(),
"http://127.0.0.1:9000/bkt/repo"
);
}
#[test]
fn the_http_options_go_into_the_s3_endpoint() {
let dir = Dir::new();
let config = tls_keys(&dir, "https://ex.com/repo");
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
http_headers: vec![("X-A".into(), "b".into())],
max_retries: Some(2),
low_speed_limit_bytes: Some(0),
..EndpointOverrides::default()
};
let s3 = s3_of(pull_in(Some(&config), "keys", o, &env(&dir, &[])));
assert_eq!(s3.http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
assert_eq!(
identity(&s3.http),
(b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec())
);
assert!(matches!(&s3.http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
assert_eq!(s3.http.headers, [("X-A".to_owned(), "b".to_owned())]);
assert_eq!(s3.http.max_retries, 2);
assert_eq!(s3.http.low_speed, None);
let config = super::config(
"[remote \"permissive\"]\npull-url=s3://bkt/repo\ntls-permissive=true\n\
tls-ca-path=/nonexistent/ca.pem\n",
);
let s3 = s3_of(pull_in(
Some(&config),
"permissive",
EndpointOverrides::default(),
&env(&dir, &[]),
));
assert_eq!(s3.http.tls.roots, TrustRoots::DangerousAcceptAnyChain);
}
#[test]
fn a_refusal_comes_before_the_read_of_the_shared_files() {
let dir = Dir::new();
let credentials = dir.absent("aws-credentials");
std::fs::create_dir(&credentials).unwrap();
let env = Environment::Variables(vec![(
"AWS_SHARED_CREDENTIALS_FILE".into(),
credentials.display().to_string(),
)]);
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
tls_client_cert_path: Some("/c".into()),
..EndpointOverrides::default()
};
assert_eq!(
pull_error(pull_in(None, "r", o, &env)),
"remote 'r': a client certificate needs both tls-client-cert-path and \
tls-client-key-path"
);
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
..EndpointOverrides::default()
};
assert!(matches!(pull_in(None, "r", o, &env), Err(Error::Io(_))));
}
#[cfg(feature = "push")]
fn push_in(
repo: Option<&TestRepo>,
remote: &str,
o: EndpointOverrides,
env: &Environment,
) -> Result<Endpoint> {
ostrya_rt::block_on(resolve_push_in(handle(repo), remote, o, env))
}
#[cfg(feature = "push")]
fn push_refused<T: fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::Remote(remote::Error::InvalidInput(msg))) => msg,
other => panic!("expected InvalidInput, got {other:?}"),
}
}
#[cfg(feature = "push")]
#[test]
fn check_push_reads_no_aws_file() {
let dir = Dir::new();
let no_keys = Environment::Variables(vec![
(
"AWS_CONFIG_FILE".to_owned(),
dir.absent("aws-config").display().to_string(),
),
(
"AWS_SHARED_CREDENTIALS_FILE".to_owned(),
dir.absent("aws-credentials").display().to_string(),
),
]);
let config = config(S3_SECTIONS);
let d = EndpointOverrides::default;
assert!(push_in(Some(&config), "push", d(), &no_keys).is_err());
assert_eq!(
check_push(Some(config.config()), "push", d()).unwrap(),
PushKind::Bucket
);
assert_eq!(
check_push(None, "s3://bkt/x", d()).unwrap(),
PushKind::Bucket
);
for o in [
EndpointOverrides {
push_user: Some("u".into()),
..d()
},
EndpointOverrides {
remote_command: Some("x".into()),
..d()
},
EndpointOverrides {
s3_addressing: Some("other".into()),
..d()
},
EndpointOverrides {
tls_client_cert_path: Some(dir.absent("cert.pem")),
..d()
},
] {
let checked = check_push(Some(config.config()), "push", o.clone());
let resolved = push_in(Some(&config), "push", o, &env(&dir, &[]));
assert_eq!(push_refused(checked), push_refused(resolved));
}
for address in ["s3://Bad_Bucket/x", "s3://bkt/a//b"] {
let checked = push_refused(check_push(None, address, d()));
let resolved = push_refused(push_in(None, address, d(), &no_keys));
assert!(checked.starts_with("S3 address: "), "{checked}");
assert_eq!(checked, resolved);
}
}
#[cfg(feature = "push")]
#[test]
fn an_s3_push_address_gives_an_s3_endpoint() {
let dir = Dir::new();
let config = config(S3_SECTIONS);
let s3 = s3_of(push_in(
Some(&config),
"push",
EndpointOverrides::default(),
&env(&dir, &[]),
));
assert_eq!(
s3.location.repository_url(),
"https://bkt.s3.eu-west-1.amazonaws.com/repo"
);
assert_eq!(s3.credentials.access_key_id(), "AKIDEXAMPLE");
assert_eq!(s3.http.max_retries, 5);
assert_eq!(s3.http.max_outstanding, 8);
let o = EndpointOverrides {
s3_endpoint: Some("http://127.0.0.1:9000".into()),
allow_cleartext_credentials: true,
..EndpointOverrides::default()
};
let s3 = s3_of(push_in(None, "s3://bkt/x", o, &env(&dir, &[])));
assert_eq!(s3.location.repository_url(), "http://127.0.0.1:9000/bkt/x");
assert!(s3.http.allow_cleartext_credentials);
}
#[cfg(feature = "push")]
#[test]
fn an_s3_push_refuses_the_fields_of_another_transport() {
let dir = Dir::new();
let d = EndpointOverrides::default;
for (name, o) in [
(
"push-token-file",
EndpointOverrides {
push_token_file: Some("/t".into()),
..d()
},
),
(
"push-user",
EndpointOverrides {
push_user: Some("u".into()),
..d()
},
),
] {
assert_eq!(
push_refused(push_in(None, "s3://u-QXZ@bkt/r", o, &env(&dir, &[]))),
format!(
"{name} applies to an HTTP address, and 's3://bkt/r' is an s3:// \
address"
)
);
}
for (key, name) in [
("push-token-file=/t", "push-token-file"),
("push-user=u", "push-user"),
] {
let config = config(&format!("[remote \"r\"]\npush-url=s3://bkt/r\n{key}\n"));
assert_eq!(
push_refused(push_in(Some(&config), "r", d(), &env(&dir, &[]))),
format!(
"{name} applies to an HTTP address, and 's3://bkt/r' is an s3:// \
address"
)
);
}
for (name, o) in [
(
"ssh-command",
EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
..d()
},
),
(
"receive-command",
EndpointOverrides {
remote_command: Some("ostrya receive".into()),
..d()
},
),
] {
assert_eq!(
push_refused(push_in(None, "s3://bkt/r", o, &env(&dir, &[]))),
format!(
"{name} applies to an ssh address, and 's3://bkt/r' is an s3:// address"
)
);
}
let config = config(
"[remote \"r\"]\npush-url=s3://bkt/r\nssh-command=ssh\n\
receive-command=x\nsend-command=y\n",
);
s3_of(push_in(Some(&config), "r", d(), &env(&dir, &[])));
}
#[cfg(feature = "push")]
#[test]
fn an_s3_push_verifies_the_chain_and_refuses_cleartext() {
let dir = Dir::new();
let config =
config("[remote \"permissive\"]\npush-url=s3://bkt/repo\ntls-permissive=true\n");
assert_eq!(
push_refused(push_in(
Some(&config),
"permissive",
EndpointOverrides::default(),
&env(&dir, &[])
)),
"remote 'permissive' sets tls-permissive=true, which a writer of a bucket \
repository refuses: the writer verifies the certificate chain of the server"
);
let env = env(&dir, &[("AWS_ENDPOINT_URL", "http://127.0.0.1:9000")]);
assert!(
push_refused(push_in(
None,
"s3://bkt/r",
EndpointOverrides::default(),
&env
))
.contains("is http://, so the signature of each request would travel")
);
let o = EndpointOverrides {
url: None,
tls_client_cert_path: Some("/c".into()),
..EndpointOverrides::default()
};
assert_eq!(
push_refused(push_in(None, "s3://bkt/r", o, &env)),
"remote 's3://bkt/r': a client certificate needs both tls-client-cert-path \
and tls-client-key-path"
);
}
#[cfg(feature = "push")]
#[test]
fn a_refusal_of_an_s3_push_address_shows_no_userinfo() {
let dir = Dir::new();
let env = env(&dir, &[("AWS_ENDPOINT_URL", "http://127.0.0.1:9000")]);
let o = EndpointOverrides {
url: None,
tls_client_cert_path: Some("/c".into()),
..EndpointOverrides::default()
};
let message = push_refused(push_in(None, "s3://AKID:SECRET@bkt/r", o, &env));
assert!(!message.contains("AKID"), "{message}");
assert!(!message.contains("SECRET"), "{message}");
assert_eq!(
message,
"remote 's3://bkt/r': a client certificate needs both tls-client-cert-path \
and tls-client-key-path"
);
}
fn bucket_in(
repo: Option<&TestRepo>,
value: &str,
o: EndpointOverrides,
env: &Environment,
) -> Result<S3Endpoint> {
ostrya_rt::block_on(resolve_bucket_in(handle(repo), value, o, env))
}
fn bucket_refused(result: Result<S3Endpoint>) -> String {
match result {
Err(Error::Remote(remote::Error::InvalidInput(msg))) => msg,
other => panic!("expected InvalidInput, got {other:?}"),
}
}
#[test]
fn a_bucket_writer_takes_push_url_then_pull_url() {
let dir = Dir::new();
let config = config(
"[remote \"both\"]\npull-url=s3://pull/a\npush-url=s3://push/b\n\n\
[remote \"pull\"]\nurl=https://ex.com/r\npull-url=s3://pull/a\n\
push-url=https://ex.com/p\ns3-region=eu-west-1\n\n\
[remote \"url\"]\nurl=s3://bkt/repo\n\n\
[remote \"http\"]\npull-url=https://ex.com/r\npush-url=ssh://h/r\n",
);
let d = EndpointOverrides::default;
let url_of = |value: &str| {
bucket_in(Some(&config), value, d(), &env(&dir, &[]))
.unwrap()
.location
.repository_url()
.to_owned()
};
assert_eq!(url_of("both"), "https://push.s3.us-east-1.amazonaws.com/b");
assert_eq!(url_of("pull"), "https://pull.s3.eu-west-1.amazonaws.com/a");
assert_eq!(
url_of("s3://bkt/x"),
"https://bkt.s3.us-east-1.amazonaws.com/x"
);
for (value, message) in [
(
"url",
"remote 'url' holds no s3:// address in push-url or pull-url",
),
(
"http",
"remote 'http' holds no s3:// address in push-url or pull-url",
),
("absent", "no remote 'absent' is configured"),
(
"https://u:p@ex.com/r",
"'https://ex.com/r' is no s3:// address",
),
("h:/srv/r", "'h:/srv/r' is no s3:// address"),
] {
assert_eq!(
bucket_refused(bucket_in(Some(&config), value, d(), &env(&dir, &[]))),
message
);
}
let o = EndpointOverrides {
url: Some("s3://bkt/x".into()),
..d()
};
assert_eq!(
bucket_refused(bucket_in(None, "s3://bkt/x", o, &env(&dir, &[]))),
"url applies to a pull, and this is a write to a bucket repository"
);
}
#[test]
fn a_bucket_writer_makes_the_refusals_of_a_push() {
let dir = Dir::new();
let d = EndpointOverrides::default;
let config = config(
"[remote \"token\"]\npush-url=s3://bkt/r\npush-token-file=/t\n\n\
[remote \"permissive\"]\npull-url=s3://bkt/r\ntls-permissive=true\n",
);
assert_eq!(
bucket_refused(bucket_in(Some(&config), "token", d(), &env(&dir, &[]))),
"push-token-file applies to an HTTP address, and 's3://bkt/r' is an s3:// \
address"
);
assert_eq!(
bucket_refused(bucket_in(Some(&config), "permissive", d(), &env(&dir, &[]))),
"remote 'permissive' sets tls-permissive=true, which a writer of a bucket \
repository refuses: the writer verifies the certificate chain of the server"
);
let o = EndpointOverrides {
push_user: Some("u".into()),
..d()
};
assert_eq!(
bucket_refused(bucket_in(None, "s3://bkt/r", o, &env(&dir, &[]))),
"push-user applies to an HTTP address, and 's3://bkt/r' is an s3:// address"
);
let o = EndpointOverrides {
ssh_command: Some(vec!["ssh".into()]),
..d()
};
assert_eq!(
bucket_refused(bucket_in(None, "s3://bkt/r", o, &env(&dir, &[]))),
"ssh-command applies to an ssh address, and 's3://bkt/r' is an s3:// address"
);
let o = EndpointOverrides {
s3_endpoint: Some("http://127.0.0.1:9000".into()),
..d()
};
assert!(
bucket_refused(bucket_in(None, "s3://bkt/r", o.clone(), &env(&dir, &[])))
.contains("is http://, so the signature of each request would travel")
);
let o = EndpointOverrides {
allow_cleartext_credentials: true,
s3_region: Some("eu-north-1".into()),
..o
};
let s3 = bucket_in(None, "s3://bkt/r", o, &env(&dir, &[])).unwrap();
assert_eq!(s3.location.repository_url(), "http://127.0.0.1:9000/bkt/r");
assert_eq!(s3.location.region(), "eu-north-1");
assert!(s3.http.allow_cleartext_credentials);
}
#[test]
fn the_s3_endpoint_shows_no_secret() {
let dir = Dir::new();
let o = EndpointOverrides {
url: Some("s3://bkt/repo".into()),
..EndpointOverrides::default()
};
let endpoint = pull_in(None, "r", o, &env(&dir, &[])).unwrap();
let text = format!("{endpoint:?}");
assert!(!text.contains("QXZ"), "{text}");
assert!(text.contains("AKIDEXAMPLE"), "{text}");
}
}
}