use std::fmt;
use std::sync::Arc;
use ostrya_fetch::FetcherOptions;
use super::{Address, Credentials, Environment, Location, Settings, SigV4, resolve};
use crate::Result;
#[derive(Clone)]
#[non_exhaustive]
pub struct S3Endpoint {
pub location: Location,
pub credentials: Credentials,
pub http: ostrya_fetch::FetcherOptions,
}
impl S3Endpoint {
pub fn new(location: Location, credentials: Credentials) -> S3Endpoint {
S3Endpoint {
location,
credentials,
http: ostrya_fetch::FetcherOptions::default(),
}
}
pub async fn resolve(
address: &str,
settings: &Settings,
environment: &Environment,
) -> Result<S3Endpoint> {
let address = Address::parse(address)?;
let resolved = resolve(settings, environment).await?;
let location = Location::from_resolved(address, &resolved)?;
Ok(S3Endpoint::new(location, resolved.credentials))
}
pub fn pull_options(&self) -> Result<FetcherOptions> {
self.signed_options(self.location.repository_url())
}
pub(super) fn signed_options(&self, mirror: String) -> Result<FetcherOptions> {
let signer = SigV4::new(self.credentials.clone(), self.location.region())?;
Ok(FetcherOptions {
mirrors: vec![mirror],
signer: Some(Arc::new(signer)),
max_redirects: 0,
..self.http.clone()
})
}
}
impl fmt::Debug for S3Endpoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("S3Endpoint")
.field("location", &self.location)
.field("credentials", &self.credentials)
.field("http", &self.http)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::s3::Addressing;
fn endpoint(
address: &str,
endpoint: Option<&str>,
addressing: Option<Addressing>,
) -> S3Endpoint {
let location = Location::new(
Address::parse(address).unwrap(),
"eu-central-1",
endpoint,
addressing,
)
.unwrap();
let credentials =
Credentials::new("AKIDEXAMPLE".into(), "SECRETEXAMPLE".into(), None).unwrap();
S3Endpoint::new(location, credentials)
}
#[test]
fn the_pull_options_sign_each_request_to_the_repository_url() {
let mut s3 = endpoint("s3://builds/exampleos/x86_64", None, None);
s3.http.max_retries = 2;
s3.http.max_outstanding = 3;
s3.http.headers = vec![("X-A".into(), "b".into())];
s3.http.allow_cleartext_credentials = true;
let options = s3.pull_options().unwrap();
assert_eq!(
options.mirrors,
["https://builds.s3.eu-central-1.amazonaws.com/exampleos/x86_64"]
);
assert!(options.signer.is_some());
assert_eq!(options.max_redirects, 0);
assert_eq!(options.max_retries, 2);
assert_eq!(options.max_outstanding, 3);
assert_eq!(options.headers, [("X-A".to_owned(), "b".to_owned())]);
assert!(options.allow_cleartext_credentials);
assert!(!format!("{options:?}").contains("SECRETEXAMPLE"));
let s3 = endpoint("s3://builds", Some("http://127.0.0.1:9000"), None);
let options = s3.pull_options().unwrap();
assert_eq!(options.mirrors, ["http://127.0.0.1:9000/builds"]);
let s3 = endpoint(
"s3://builds/repo",
Some("https://s3.example.com"),
Some(Addressing::Path),
);
assert_eq!(
s3.pull_options().unwrap().mirrors,
["https://s3.example.com/builds/repo"]
);
}
}