1use std::{2 collections::BTreeMap, fmt::{self, Display}, str::FromStr3};45use base64::engine::{Engine, general_purpose::STANDARD_NO_PAD};6use serde::{Deserialize, Deserializer, Serialize, de::Error};7use unicode_categories::UnicodeCategories;89#[derive(Debug, PartialEq, Clone)]10pub struct SecretData {11 pub data: Vec<u8>,12 pub encrypted: bool,13}1415const BASE64_ENCODED_PREFIX: &str = "<BASE64-ENCODED>\n";16const Z85_ENCODED_PREFIX: &str = "<Z85-ENCODED>\n";1718const PLAINTEXT_NEWLINE_PREFIX: &str = "<PLAINTEXT-NL>\n";19const PLAINTEXT_PREFIX: &str = "<PLAINTEXT>";2021const SECRET_PREFIX: &str = "<ENCRYPTED>";2223impl<'de> Deserialize<'de> for SecretData {24 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>25 where26 D: Deserializer<'de>,27 {28 let string = String::deserialize(deserializer)?;29 string.parse().map_err(D::Error::custom)30 }31}3233impl Serialize for SecretData {34 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>35 where36 S: serde::Serializer,37 {38 self.to_string().serialize(serializer)39 }40}4142impl FromStr for SecretData {43 type Err = String;4445 fn from_str(string: &str) -> Result<Self, Self::Err> {46 let (encrypted, string) = if let Some(unprefixed) = string.strip_prefix(SECRET_PREFIX) {47 (true, unprefixed)48 } else {49 (false, string)50 };51 let data = if let Some(unprefixed) = string.strip_prefix(BASE64_ENCODED_PREFIX) {52 STANDARD_NO_PAD53 .decode(unprefixed.replace(['\n', '\t', ' '], ""))54 .map_err(|e| format!("base64-encoded failed: {e}"))?55 } else if let Some(unprefixed) = string.strip_prefix(Z85_ENCODED_PREFIX) {56 z85::decode(unprefixed.replace(['\n', '\t', ' '], ""))57 .map_err(|e| format!("z85-encoded failed: {e}"))?58 } else if let Some(unprefixed) = string.strip_prefix(PLAINTEXT_NEWLINE_PREFIX) {59 unprefixed.as_bytes().to_owned()60 } else if let Some(unprefixed) = string.strip_prefix(PLAINTEXT_PREFIX) {61 unprefixed.as_bytes().to_owned()62 } else {63 let secret_prefix = format!("{SECRET_PREFIX}{Z85_ENCODED_PREFIX}");64 return Err(format!(65 "unknown secret encoding. If you're migrating from old version of fleet, prefix public secret fields with {PLAINTEXT_PREFIX:?}, and encrypted data with {secret_prefix:?}: {string}"66 ));67 };68 Ok(Self { data, encrypted })69 }70}7172impl Display for SecretData {73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {74 let mut readable = std::str::from_utf8(&self.data).ok();75 if self.encrypted {76 write!(f, "{SECRET_PREFIX}")?;77 78 readable = None;79 }80 if Some(false) == readable.map(is_printable) {81 readable = None82 };83 84 if let Some(plaintext) = readable {85 if plaintext.ends_with('\n') {86 write!(f, "{PLAINTEXT_NEWLINE_PREFIX}")?;87 } else {88 write!(f, "{PLAINTEXT_PREFIX}")?;89 }90 write!(f, "{plaintext}")?;91 } else {92 write!(f, "{BASE64_ENCODED_PREFIX}")?;93 let encoded = STANDARD_NO_PAD.encode(&self.data);94 for ele in encoded.as_bytes().chunks(64) {95 let chunk = std::str::from_utf8(ele).expect(96 "any slice of base64-encoded text is utf-8 compatible, as it is ascii-based",97 );98 writeln!(f, "{chunk}")?;99 }100 };101 Ok(())102 }103}104105fn is_printable(text: &str) -> bool {106 text.chars().all(|c| {107 c.is_letter()108 || c.is_mark()109 || c.is_number()110 || c.is_punctuation()111 || c.is_separator()112 || c == '\n' || c == '\t'113 114 || c == '/' || c == '+'115 || c == '='116 })117}118119#[test]120fn test() {121 fn check_roundtrip(data: SecretData, expected: &str) {122 let string = data.to_string();123 assert_eq!(string, expected, "unexpected encoding");124 let roundtrip: SecretData = string.parse().expect("roundtrip parse");125 assert_eq!(data, roundtrip, "roundtrip didn't match");126 }127 check_roundtrip(128 SecretData {129 data: vec![1, 2, 3, 4, 5, 6],130 encrypted: false,131 },132 "<BASE64-ENCODED>\nAQIDBAUG\n",133 );134 check_roundtrip(135 SecretData {136 data: vec![1, 2, 3, 4, 5, 6],137 encrypted: true,138 },139 "<ENCRYPTED><BASE64-ENCODED>\nAQIDBAUG\n",140 );141 check_roundtrip(142 SecretData {143 data: "Привет, мир!\n".to_owned().into(),144 encrypted: false,145 },146 "<PLAINTEXT-NL>\nПривет, мир!\n",147 );148 check_roundtrip(149 SecretData {150 data: "Привет, мир!".to_owned().into(),151 encrypted: false,152 },153 "<PLAINTEXT>Привет, мир!",154 );155}