use super::rules::Stop;
use super::state::Reason;
use crate::profile::files::Endpoint;
use crate::remote::selection::Selection;
pub const SCALARS: usize = 512;
pub const REMOVED: &str = "[credential]";
pub const UNKNOWN: &str = "unknown";
pub fn credentials(selection: &Selection) -> Vec<String> {
let mut found = Vec::new();
match selection {
Selection::File(_) => {}
Selection::Postgres { dsn, .. } => {
found.push(dsn.clone());
found.extend(parts(dsn));
}
Selection::Remote { url, token } => {
found.push(token.clone());
found.extend(parts(url));
}
Selection::Profile(resolved) => {
for (source, binding) in &resolved.bindings {
found.extend(resolved.credential(source).ok().flatten());
if let Endpoint::Http { url, .. } = &binding.endpoint {
found.extend(parts(url));
}
}
}
}
found.retain(|secret| !secret.is_empty());
found.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
found.dedup();
found
}
fn parts(url: &str) -> Vec<String> {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority = &rest[..rest.find(['/', '?', '#']).unwrap_or(rest.len())];
let userinfo = authority.rsplit_once('@').map(|(userinfo, _)| userinfo);
let query = rest
.split_once('?')
.map(|(_, query)| &query[..query.find('#').unwrap_or(query.len())]);
[userinfo, query]
.into_iter()
.flatten()
.map(str::to_string)
.collect()
}
pub fn kept(message: &str, credentials: &[String]) -> String {
let mut cleaned = message.to_string();
for secret in credentials {
if cleaned.contains(secret.as_str()) {
cleaned = cleaned.replace(secret.as_str(), REMOVED);
}
}
cut(&cleaned)
}
pub fn cut(message: &str) -> String {
message.chars().take(SCALARS).collect()
}
pub fn stop(stop: Stop, credentials: &[String]) -> Stop {
let clean = |message: String| kept(&message, credentials);
match stop {
Stop::Conversation(message) => Stop::Conversation(clean(message)),
Stop::Retry { seconds, message } => Stop::Retry {
seconds,
message: clean(message),
},
Stop::Wait {
seconds,
failing,
message,
} => Stop::Wait {
seconds,
failing,
message: clean(message),
},
Stop::Block {
block,
message,
status,
code,
} => Stop::Block {
block,
message: clean(message),
status,
code,
},
}
}
pub fn reason(mut reason: Reason, credentials: &[String]) -> Reason {
reason.message = reason.message.map(|message| kept(&message, credentials));
if let Some(answered) = reason.answered.as_mut() {
answered.code = answered.code.take().map(|said| code(&said, credentials));
}
reason
}
pub fn code(code: &str, credentials: &[String]) -> String {
let grammar = code.len() <= 64
&& code.starts_with(|first: char| first.is_ascii_lowercase())
&& code
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
let secret = credentials
.iter()
.any(|credential| code.contains(credential.as_str()));
match grammar && !secret {
true => code.to_string(),
false => UNKNOWN.to_string(),
}
}