git.delta.rocks / jrsonnet / refs/commits / 94ece5cae749

difftreelog

source

crates/fleet-shared/src/encoding.rs4.4 KiBsourcehistory
1use std::{2	fmt::{self, Display},3	str::FromStr,4};56use base64::engine::{Engine, general_purpose::STANDARD_NO_PAD};7use serde::{Deserialize, Deserializer, Serialize, de::Error};8use unicode_categories::UnicodeCategories;910#[derive(Debug, PartialEq, Clone)]11pub struct SecretData {12	pub data: Vec<u8>,13	pub encrypted: bool,14}1516const BASE64_ENCODED_PREFIX: &str = "<BASE64-ENCODED>\n";17const Z85_ENCODED_PREFIX: &str = "<Z85-ENCODED>\n";18// Multiline text in Nix can only end with \n, which is not cool for actual single-line strings.19const PLAINTEXT_NEWLINE_PREFIX: &str = "<PLAINTEXT-NL>\n";20const PLAINTEXT_PREFIX: &str = "<PLAINTEXT>";2122const SECRET_PREFIX: &str = "<ENCRYPTED>";2324impl<'de> Deserialize<'de> for SecretData {25	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>26	where27		D: Deserializer<'de>,28	{29		let string = String::deserialize(deserializer)?;30		string.parse().map_err(D::Error::custom)31	}32}3334impl Serialize for SecretData {35	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>36	where37		S: serde::Serializer,38	{39		self.to_string().serialize(serializer)40	}41}4243impl FromStr for SecretData {44	type Err = String;4546	fn from_str(string: &str) -> Result<Self, Self::Err> {47		let (encrypted, string) = if let Some(unprefixed) = string.strip_prefix(SECRET_PREFIX) {48			(true, unprefixed)49		} else {50			(false, string)51		};52		let data = if let Some(unprefixed) = string.strip_prefix(BASE64_ENCODED_PREFIX) {53			STANDARD_NO_PAD54				.decode(unprefixed.replace(|v| matches!(v, '\n' | '\t' | ' '), ""))55				.map_err(|e| format!("base64-encoded failed: {e}"))?56		} else if let Some(unprefixed) = string.strip_prefix(Z85_ENCODED_PREFIX) {57			z85::decode(unprefixed.replace(|v| matches!(v, '\n' | '\t' | ' '), ""))58				.map_err(|e| format!("z85-encoded failed: {e}"))?59		} else if let Some(unprefixed) = string.strip_prefix(PLAINTEXT_NEWLINE_PREFIX) {60			unprefixed.as_bytes().to_owned()61		} else if let Some(unprefixed) = string.strip_prefix(PLAINTEXT_PREFIX) {62			unprefixed.as_bytes().to_owned()63		} else {64			let secret_prefix = format!("{SECRET_PREFIX}{Z85_ENCODED_PREFIX}");65			return Err(format!(66				"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}"67			));68		};69		Ok(Self { data, encrypted })70	}71}7273impl Display for SecretData {74	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {75		let mut readable = std::str::from_utf8(&self.data).ok();76		if self.encrypted {77			write!(f, "{SECRET_PREFIX}")?;78			// Always base64-encode encrypted fields.79			readable = None;80		}81		if Some(false) == readable.map(is_printable) {82			readable = None83		};84		// TODO: Check if text is readable, and has no unprintable characters?..85		if let Some(plaintext) = readable {86			if plaintext.ends_with('\n') {87				write!(f, "{PLAINTEXT_NEWLINE_PREFIX}")?;88			} else {89				write!(f, "{PLAINTEXT_PREFIX}")?;90			}91			write!(f, "{plaintext}")?;92		} else {93			write!(f, "{BASE64_ENCODED_PREFIX}")?;94			let encoded = STANDARD_NO_PAD.encode(&self.data);95			for ele in encoded.as_bytes().chunks(64) {96				let chunk = std::str::from_utf8(ele).expect(97					"any slice of base64-encoded text is utf-8 compatible, as it is ascii-based",98				);99				writeln!(f, "{chunk}")?;100			}101		};102		Ok(())103	}104}105106fn is_printable(text: &str) -> bool {107	text.chars().all(|c| {108		c.is_letter()109			|| c.is_mark()110			|| c.is_number()111			|| c.is_punctuation()112			|| c.is_separator()113			|| c == '\n' || c == '\t'114			// Complete base64 alphabet115			|| c == '/' || c == '+'116			|| c == '='117	})118}119120#[test]121fn test() {122	fn check_roundtrip(data: SecretData, expected: &str) {123		let string = data.to_string();124		assert_eq!(string, expected, "unexpected encoding");125		let roundtrip: SecretData = string.parse().expect("roundtrip parse");126		assert_eq!(data, roundtrip, "roundtrip didn't match");127	}128	check_roundtrip(129		SecretData {130			data: vec![1, 2, 3, 4, 5, 6],131			encrypted: false,132		},133		"<BASE64-ENCODED>\nAQIDBAUG\n",134	);135	check_roundtrip(136		SecretData {137			data: vec![1, 2, 3, 4, 5, 6],138			encrypted: true,139		},140		"<ENCRYPTED><BASE64-ENCODED>\nAQIDBAUG\n",141	);142	check_roundtrip(143		SecretData {144			data: "Привет, мир!\n".to_owned().into(),145			encrypted: false,146		},147		"<PLAINTEXT-NL>\nПривет, мир!\n",148	);149	check_roundtrip(150		SecretData {151			data: "Привет, мир!".to_owned().into(),152			encrypted: false,153		},154		"<PLAINTEXT>Привет, мир!",155	);156}