use crate::data::map::*;
use base64::Engine;
use melodium_core::common::descriptor::DataType;
use melodium_core::common::executive::{
Secret as ExecutiveSecret, SecretDerivation, SecretOrigin, SecretPolicy, SecretReveal,
SecretTransmission,
};
use melodium_core::*;
use melodium_macro::{mel_function, mel_treatment};
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use std::collections::HashMap;
use std::sync::Arc;
use zeroize::Zeroize;
pub mod block;
#[mel_function]
pub fn from_environment(variable: string, name: string) -> Secret<string> {
ExecutiveSecret::new(
name,
DataType::String,
SecretPolicy::default(),
SecretOrigin::Locator(format!("env:{variable}")),
)
.unwrap()
}
#[mel_function]
pub fn from_file(path: string, name: string) -> Secret<string> {
ExecutiveSecret::new(
name,
DataType::String,
SecretPolicy::default(),
SecretOrigin::Locator(format!("file:{path}")),
)
.unwrap()
}
#[mel_function]
pub fn from_file_bytes(path: string, name: string) -> Secret<Vec<byte>> {
ExecutiveSecret::new(
name,
DataType::Vec(Box::new(DataType::Byte)),
SecretPolicy::default(),
SecretOrigin::Locator(format!("file:{path}")),
)
.unwrap()
}
#[mel_function(
generic T ()
)]
pub fn locate(
locator: string,
name: string,
transmission: string,
plain_reveal: bool,
) -> Option<Secret<T>> {
transmission
.parse::<SecretTransmission>()
.and_then(|transmission| {
ExecutiveSecret::new(
name,
generics.get("T").unwrap().clone(),
SecretPolicy {
transmission,
reveal: SecretReveal::Any,
plain_reveal,
},
SecretOrigin::Locator(locator),
)
})
.ok()
}
#[mel_function(
generic T ()
)]
pub fn name(secret: Secret<T>) -> string {
secret.name().to_string()
}
#[mel_function(
generic T ()
)]
pub fn keep_local(secret: Secret<T>) -> Secret<T> {
secret.narrow(&keep_local_narrowing())
}
#[mel_function(
generic T ()
)]
pub fn limit_to_reference(secret: Secret<T>) -> Secret<T> {
secret.narrow(&limit_to_reference_narrowing())
}
#[mel_function(
generic T ()
)]
pub fn reveal_only_by(secret: Secret<T>, elements: Vec<string>) -> Secret<T> {
secret.narrow(&reveal_only_by_narrowing(elements))
}
#[mel_function(
generic T ()
)]
pub fn forbid_plain_reveal(secret: Secret<T>) -> Secret<T> {
secret.narrow(&forbid_plain_reveal_narrowing())
}
pub(crate) fn keep_local_narrowing() -> SecretPolicy {
SecretPolicy {
transmission: SecretTransmission::Local,
..SecretPolicy::unrestricted()
}
}
pub(crate) fn limit_to_reference_narrowing() -> SecretPolicy {
SecretPolicy {
transmission: SecretTransmission::Reference,
..SecretPolicy::unrestricted()
}
}
pub(crate) fn reveal_only_by_narrowing(elements: Vec<String>) -> SecretPolicy {
SecretPolicy {
reveal: SecretReveal::Only(elements),
..SecretPolicy::unrestricted()
}
}
pub(crate) fn forbid_plain_reveal_narrowing() -> SecretPolicy {
SecretPolicy {
plain_reveal: false,
..SecretPolicy::unrestricted()
}
}
fn value_bytes(value: &Value) -> Option<std::borrow::Cow<'_, [u8]>> {
match value {
Value::String(text) => Some(std::borrow::Cow::Borrowed(text.as_bytes())),
Value::Packed(PackedArray::Byte(bytes)) | Value::Packed(PackedArray::U8(bytes)) => {
Some(std::borrow::Cow::Borrowed(bytes.as_slice()))
}
Value::Vec(values) => values
.iter()
.map(|value| match value {
Value::Byte(byte) | Value::U8(byte) => Some(*byte),
_ => None,
})
.collect::<Option<Vec<u8>>>()
.map(std::borrow::Cow::Owned),
_ => None,
}
}
fn format_entries(
entries: HashMap<String, Value>,
) -> (
HashMap<String, String>,
Vec<String>,
Vec<String>,
Vec<ExecutiveSecret>,
) {
let mut plain_entries = HashMap::new();
let mut secret_entries = Vec::new();
let mut invalid_entries = Vec::new();
let mut inputs = Vec::new();
for (entry, value) in entries {
let value = match value {
Value::Option(Some(value)) => *value,
Value::Option(None) => continue,
value => value,
};
match value {
Value::String(text) => {
plain_entries.insert(entry, text);
}
Value::Secret(secret) if secret.datatype() == &DataType::String => {
secret_entries.push(entry);
inputs.push(secret);
}
_ => invalid_entries.push(entry),
}
}
(plain_entries, secret_entries, invalid_entries, inputs)
}
#[derive(Debug)]
struct FormatDerivation {
template: String,
plain_entries: HashMap<String, String>,
secret_entries: Vec<String>,
invalid_entries: Vec<String>,
}
impl SecretDerivation for FormatDerivation {
fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
if let Some(entry) = self.invalid_entries.first() {
return Err(format!(
"entry '{entry}' is neither a string nor a Secret<string>"
));
}
let mut entries = self.plain_entries.clone();
let mut invalid = None;
for (entry, value) in self.secret_entries.iter().zip(inputs) {
match value {
Value::String(text) => {
entries.insert(entry.clone(), text.clone());
}
_ => {
invalid = Some(format!("entry '{entry}' is not a string"));
break;
}
}
}
let formatted = match invalid {
Some(invalid) => Err(invalid),
None => Ok(strfmt::strfmt(&self.template, &entries)),
};
for (_, mut text) in entries.drain() {
text.zeroize();
}
formatted?.map(Value::String).map_err(|err| match err {
strfmt::FmtError::Invalid(_) => "the template is not valid".to_string(),
strfmt::FmtError::KeyError(_) => {
"the template uses an entry that is not given".to_string()
}
strfmt::FmtError::TypeError(_) => {
"the template has an invalid placeholder format".to_string()
}
})
}
}
#[derive(Debug)]
pub(crate) struct Base64Derivation;
impl SecretDerivation for Base64Derivation {
fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
let bytes = inputs
.first()
.and_then(value_bytes)
.ok_or_else(|| "base64 needs a string or bytes".to_string())?;
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
if let std::borrow::Cow::Owned(mut bytes) = bytes {
bytes.zeroize();
}
Ok(Value::String(encoded))
}
}
const URL_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
#[derive(Debug)]
pub(crate) struct UrlEncodeDerivation;
impl SecretDerivation for UrlEncodeDerivation {
fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
match inputs.first() {
Some(Value::String(text)) => Ok(Value::String(
utf8_percent_encode(text, URL_COMPONENT).to_string(),
)),
_ => Err("URL encoding needs a string".to_string()),
}
}
}
#[derive(Debug)]
pub(crate) struct BytesDerivation;
impl SecretDerivation for BytesDerivation {
fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
match inputs.first() {
Some(Value::String(text)) => Ok(Value::Packed(PackedArray::Byte(Arc::new(
text.as_bytes().to_vec(),
)))),
_ => Err("bytes conversion needs a string".to_string()),
}
}
}
#[mel_function]
pub fn format(template: string, entries: Map, name: string) -> Secret<string> {
formatted(template, entries.map, name)
}
pub(crate) fn formatted(
template: String,
entries: HashMap<String, Value>,
name: String,
) -> ExecutiveSecret {
let (plain_entries, secret_entries, invalid_entries, inputs) = format_entries(entries);
ExecutiveSecret::derive(
name,
DataType::String,
inputs,
Arc::new(FormatDerivation {
template,
plain_entries,
secret_entries,
invalid_entries,
}),
)
.unwrap()
}
#[mel_function]
pub fn base64(secret: Secret<string>, name: string) -> Secret<string> {
derived(name, DataType::String, secret, Arc::new(Base64Derivation))
}
#[mel_function]
pub fn base64_bytes(secret: Secret<Vec<byte>>, name: string) -> Secret<string> {
derived(name, DataType::String, secret, Arc::new(Base64Derivation))
}
#[mel_function]
pub fn url_encode(secret: Secret<string>, name: string) -> Secret<string> {
derived(
name,
DataType::String,
secret,
Arc::new(UrlEncodeDerivation),
)
}
#[mel_function]
pub fn to_bytes(secret: Secret<string>, name: string) -> Secret<Vec<byte>> {
derived(
name,
DataType::Vec(Box::new(DataType::Byte)),
secret,
Arc::new(BytesDerivation),
)
}
pub(crate) fn derived(
name: String,
datatype: DataType,
secret: ExecutiveSecret,
derivation: Arc<dyn SecretDerivation>,
) -> ExecutiveSecret {
ExecutiveSecret::derive(name, datatype, vec![secret], derivation).unwrap()
}
#[mel_treatment(
generic T ()
input value Block<T>
output secret Block<Secret<T>>
output failed Block<void>
output error Block<string>
default transmission "local"
default plain_reveal false
)]
pub async fn conceal(name: string, transmission: string, plain_reveal: bool) {
if let Ok(content) = value.recv_one().await {
let concealed = transmission
.parse::<SecretTransmission>()
.and_then(|transmission| {
ExecutiveSecret::new(
name,
T,
SecretPolicy {
transmission,
reveal: SecretReveal::Any,
plain_reveal,
},
SecretOrigin::Inline(content),
)
});
match concealed {
Ok(concealed) => {
let _ = secret.send_one(Value::Secret(concealed)).await;
}
Err(err) => {
let _ = failed.send_one(().into()).await;
let _ = error.send_one(err.to_string().into()).await;
}
}
}
}
#[mel_treatment(
generic T ()
input secret Block<Secret<T>>
output value Block<T>
output failed Block<void>
output error Block<string>
secrets_access
)]
pub async fn reveal() {
if let Ok(Value::Secret(concealed)) = secret.recv_one().await {
match secrets_access
.reveal_plainly(&concealed, |content| content.clone())
.await
{
Ok(content) => {
let _ = value.send_one(content).await;
}
Err(err) => {
let _ = failed.send_one(().into()).await;
let _ = error.send_one(err.to_string().into()).await;
}
}
}
}
#[mel_treatment(
input data Stream<byte>
output scanned Stream<byte>
output completed Block<void>
output failed Block<void>
output finished Block<void>
output error Block<string>
secrets_access
)]
pub async fn scan() {
let mut search = secrets_access.revealed_scan();
let mut held = Hold::default();
let mut found = None;
let mut given = true;
while let Ok(mut bytes) = data.recv_many_as::<u8>().await {
found = search.scan(&bytes);
if found.is_some() {
bytes.zeroize();
break;
}
let released = held.push(bytes, search.overlap());
if !released.is_empty()
&& scanned
.send_many(TransmissionValue::Byte(released))
.await
.is_err()
{
given = false;
break;
}
}
match found {
Some(name) => {
data.close();
scanned.close().await;
let _ = failed.send_one(().into()).await;
let _ = error
.send_one(format!("the data holds a value revealed from secret '{name}'").into())
.await;
}
None if given => {
let rest = held.take();
if rest.is_empty()
|| scanned
.send_many(TransmissionValue::Byte(rest))
.await
.is_ok()
{
scanned.close().await;
let _ = completed.send_one(().into()).await;
}
}
None => {
data.close();
}
}
let _ = finished.send_one(().into()).await;
}
#[derive(Default)]
struct Hold(VecDeque<u8>);
impl Hold {
fn push(&mut self, mut bytes: Vec<u8>, overlap: usize) -> VecDeque<u8> {
self.0.extend(bytes.iter());
bytes.zeroize();
let release = self.0.len().saturating_sub(overlap);
self.0.drain(..release).collect()
}
fn take(&mut self) -> VecDeque<u8> {
core::mem::take(&mut self.0)
}
}
impl Drop for Hold {
fn drop(&mut self) {
self.0.iter_mut().for_each(|byte| *byte = 0);
}
}
#[cfg(test)]
mod tests {
use super::*;
const SENTINEL: &str = "s3cr3t:value/@";
#[test]
fn hold_keeps_what_could_start_a_value() {
let mut hold = Hold::default();
assert!(hold.push(b"abc".to_vec(), 5).is_empty());
assert_eq!(
hold.push(b"defgh".to_vec(), 5),
VecDeque::from(b"abc".to_vec())
);
assert_eq!(
hold.push(b"ij".to_vec(), 0),
VecDeque::from(b"defghij".to_vec())
);
assert!(hold.take().is_empty());
assert_eq!(hold.push(b"klm".to_vec(), 2), VecDeque::from(b"k".to_vec()));
assert_eq!(hold.take(), VecDeque::from(b"lm".to_vec()));
}
#[test]
fn format_fills_plain_and_secret_entries() {
let derivation = FormatDerivation {
template: "{scheme}://{user}:{password}@host".to_string(),
plain_entries: HashMap::from([
("scheme".to_string(), "https".to_string()),
("user".to_string(), "ci".to_string()),
]),
secret_entries: vec!["password".to_string()],
invalid_entries: Vec::new(),
};
assert_eq!(
derivation.derive(&[Value::String(SENTINEL.to_string())]),
Ok(Value::String(format!("https://ci:{SENTINEL}@host")))
);
}
#[test]
fn format_takes_entries_in_options() {
let secret = ExecutiveSecret::from_locator("env:TOKEN", DataType::String).unwrap();
let entries = Map::new_with(HashMap::from([
(
"token".to_string(),
Value::Option(Some(Box::new(Value::Secret(secret.clone())))),
),
(
"user".to_string(),
Value::Option(Some(Box::new(Value::String("ci".to_string())))),
),
("none".to_string(), Value::Option(None)),
(
"count".to_string(),
Value::Option(Some(Box::new(Value::U64(3)))),
),
]));
let (plain, secret_entries, invalid, inputs) = format_entries(entries.map);
assert_eq!(
plain,
HashMap::from([("user".to_string(), "ci".to_string())])
);
assert_eq!(secret_entries, vec!["token".to_string()]);
assert_eq!(invalid, vec!["count".to_string()]);
assert_eq!(inputs, vec![secret]);
}
#[test]
fn format_takes_empty_options_as_no_entries() {
let (plain_entries, secret_entries, invalid_entries, _) = format_entries(HashMap::from([
("user".to_string(), Value::String("ci".to_string())),
("none".to_string(), Value::Option(None)),
]));
let derivation = |template: &str| FormatDerivation {
template: template.to_string(),
plain_entries: plain_entries.clone(),
secret_entries: secret_entries.clone(),
invalid_entries: invalid_entries.clone(),
};
assert_eq!(
derivation("{user}").derive(&[]),
Ok(Value::String("ci".to_string()))
);
assert_eq!(
derivation("{user}:{none}").derive(&[]),
Err("the template uses an entry that is not given".to_string())
);
}
#[test]
fn format_errors_never_show_values() {
let missing = FormatDerivation {
template: "{missing} {password}".to_string(),
plain_entries: HashMap::new(),
secret_entries: vec!["password".to_string()],
invalid_entries: Vec::new(),
};
let invalid_format = FormatDerivation {
template: "{password:>.3e}".to_string(),
plain_entries: HashMap::new(),
secret_entries: vec!["password".to_string()],
invalid_entries: Vec::new(),
};
let invalid_entry = FormatDerivation {
template: "{password}".to_string(),
plain_entries: HashMap::new(),
secret_entries: vec!["password".to_string()],
invalid_entries: vec!["count".to_string()],
};
for derivation in [missing, invalid_format, invalid_entry] {
let error = derivation
.derive(&[Value::String(SENTINEL.to_string())])
.unwrap_err();
assert!(!error.contains(SENTINEL), "leaked in {error}");
}
}
#[test]
fn encodings() {
let value = Value::String(SENTINEL.to_string());
assert_eq!(
UrlEncodeDerivation.derive(&[value.clone()]),
Ok(Value::String("s3cr3t%3Avalue%2F%40".to_string()))
);
assert_eq!(
UrlEncodeDerivation.derive(&[Value::String("aZ09-._~ é".to_string())]),
Ok(Value::String("aZ09-._~%20%C3%A9".to_string()))
);
assert_eq!(
Base64Derivation.derive(&[Value::String("ci:password".to_string())]),
Ok(Value::String("Y2k6cGFzc3dvcmQ=".to_string()))
);
let bytes = BytesDerivation.derive(&[value]).unwrap();
assert_eq!(
bytes,
Value::Packed(PackedArray::Byte(Arc::new(SENTINEL.as_bytes().to_vec())))
);
assert_eq!(bytes.datatype(), DataType::Vec(Box::new(DataType::Byte)));
assert_eq!(
Base64Derivation.derive(&[Value::Vec(vec![Value::Byte(0xff), Value::Byte(0)])]),
Ok(Value::String("/wA=".to_string()))
);
assert!(Base64Derivation.derive(&[Value::U64(1)]).is_err());
}
}