use std::time::Duration;
use anyhow::{Context as _, Result, bail, ensure};
use openmoat_core::mint::MintSource;
use zeroize::Zeroizing;
use super::command::Answer;
use crate::remote::https::{Client, Request, Response};
mod aws;
pub mod encode;
mod gcp;
mod github;
mod rsa;
mod sigv4;
const TIMEOUT: Duration = Duration::from_secs(30);
const MIN_ANSWER_MS: i64 = 10_000;
pub trait Transport: Send + Sync {
fn send(&self, host: &str, request: &Request) -> Result<Response>;
}
struct Https;
impl Transport for Https {
fn send(&self, host: &str, request: &Request) -> Result<Response> {
Client::new(host)?.send(request, TIMEOUT)
}
}
pub struct Minted {
pub value: Zeroizing<String>,
pub expires_ms: i64,
pub masked: Vec<Zeroizing<String>>,
}
pub struct Minter {
id: String,
source: MintSource,
home: String,
transport: Box<dyn Transport>,
now_ms: fn() -> i64,
}
impl Minter {
pub fn prepare(id: &str, source: &MintSource, home: &str) -> Self {
Self {
id: id.to_owned(),
source: source.clone(),
home: home.trim_end_matches('/').to_owned(),
transport: Box::new(Https),
now_ms: crate::time::now_ms,
}
}
#[cfg(test)]
pub fn with(self, transport: Box<dyn Transport>, now_ms: fn() -> i64) -> Self {
Self {
transport,
now_ms,
..self
}
}
fn read(&self, path: &str) -> Result<Zeroizing<String>> {
let full = match path.strip_prefix("~/") {
Some(rest) => format!("{}/{rest}", self.home),
None => path.to_owned(),
};
Ok(Zeroizing::new(
std::fs::read_to_string(&full).with_context(|| format!("reading {path}"))?,
))
}
}
impl super::Fetch for Minter {
fn id(&self) -> &str {
&self.id
}
fn refresh_before(&self) -> Duration {
Duration::from_secs(self.source.refresh_before_secs())
}
fn time_limit(&self) -> Duration {
TIMEOUT
}
fn fetch(&self) -> Result<Answer> {
let now = (self.now_ms)();
let send = |host: &str, request: &Request| self.transport.send(host, request);
let read = |path: &str| self.read(path);
let lifetime = self.source.lifetime_secs();
let minted = match &self.source {
MintSource::GithubApp(app) => github::mint(app, now, &read, &send),
MintSource::AwsSts(sts) => aws::mint((&self.id, sts), (now, lifetime), &read, &send),
MintSource::Gcp(gcp) => gcp::mint(gcp, (now, lifetime), &read, &send),
}
.with_context(|| format!("minting with {}", self.source.provider()))?;
answer(minted, now, lifetime)
}
}
pub fn answer(minted: Minted, now: i64, asked_secs: u64) -> Result<Answer> {
let left = minted.expires_ms - now;
ensure!(
left >= MIN_ANSWER_MS,
"the provider answered with a credential that expires in {}s",
left.max(0) / 1000
);
let left = Duration::from_millis(u64::try_from(left).unwrap_or(0));
Ok(Answer {
value: minted.value,
lifetime: left.min(Duration::from_secs(asked_secs)),
masked: minted.masked,
})
}
pub fn refused(provider: &str, response: &Response, code: Option<String>) -> anyhow::Error {
let code = code
.map(|c| {
c.chars()
.filter(|c| !c.is_control())
.take(200)
.collect::<String>()
})
.map_or_else(String::new, |c| format!(": {c}"));
anyhow::Error::msg(format!(
"{provider} refused the minting request with HTTP {}{code}",
response.status
))
}
pub fn json(body: &[u8]) -> Result<serde_json::Value> {
let value: serde_json::Value =
serde_json::from_slice(body).context("the answer is not JSON")?;
if !value.is_object() {
bail!("the answer is not a JSON object");
}
Ok(value)
}
pub fn field(value: &serde_json::Value, name: &str) -> Result<Zeroizing<String>> {
value
.get(name)
.and_then(serde_json::Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| Zeroizing::new(s.to_owned()))
.with_context(|| format!("the answer has no `{name}`"))
}
pub fn expiry(value: &serde_json::Value, name: &str) -> Result<i64> {
let text = field(value, name)?;
encode::expiry_ms(&text).with_context(|| format!("the answer's `{name}` is not a UTC time"))
}
#[cfg(test)]
mod tests;