qos_core 0.9.0

Core components and logic for QuorumOS applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Pivot environment variable manifest types.

use std::{borrow::Borrow, collections::BTreeMap, fmt, ops::Deref};

use borsh::{BorshDeserialize, BorshSerialize};

use crate::protocol::ProtocolError;

/// Maximum number of env vars in a pivot manifest.
pub const MAX_PIVOT_ENV_VARS: usize = 512;
/// Maximum pivot env var name length in bytes.
pub const MAX_PIVOT_ENV_NAME_LEN: usize = 1024;
/// Maximum pivot env var value length in bytes.
pub const MAX_PIVOT_ENV_VALUE_LEN: usize = 64 * 1024;

/// Environment variable name to inject into the pivot process.
#[derive(
	PartialEq,
	Eq,
	PartialOrd,
	Ord,
	Clone,
	Hash,
	Debug,
	BorshSerialize,
	serde::Serialize,
	serde::Deserialize,
)]
#[serde(try_from = "String")]
pub struct PivotEnvVarName(String);

impl PivotEnvVarName {
	/// Parse and validate an environment variable name.
	///
	/// # Errors
	///
	/// Returns [`ProtocolError::InvalidPivotEnv`] if the name is empty,
	/// too long, or contains invalid characters.
	pub fn new(name: String) -> Result<Self, ProtocolError> {
		if name.len() > MAX_PIVOT_ENV_NAME_LEN {
			return Err(ProtocolError::InvalidPivotEnv(format!(
				"env var `{name}` name too long: {} > {}",
				name.len(),
				MAX_PIVOT_ENV_NAME_LEN
			)));
		}

		let mut chars = name.chars();
		let Some(first) = chars.next() else {
			return Err(ProtocolError::InvalidPivotEnv(
				"env var name cannot be empty".to_string(),
			));
		};

		if !(first.is_ascii_alphabetic() || first == '_') {
			return Err(ProtocolError::InvalidPivotEnv(format!(
				"env var name `{name}` must start with [A-Za-z_]"
			)));
		}

		if chars.any(|c| !(c.is_ascii_alphanumeric() || c == '_')) {
			return Err(ProtocolError::InvalidPivotEnv(format!(
				"env var name `{name}` must match [A-Za-z_][A-Za-z0-9_]*"
			)));
		}

		Ok(Self(name))
	}
}

impl fmt::Display for PivotEnvVarName {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl Borrow<str> for PivotEnvVarName {
	fn borrow(&self) -> &str {
		&self.0
	}
}

impl Deref for PivotEnvVarName {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl TryFrom<String> for PivotEnvVarName {
	type Error = ProtocolError;

	fn try_from(name: String) -> Result<Self, Self::Error> {
		Self::new(name)
	}
}

impl BorshDeserialize for PivotEnvVarName {
	fn deserialize_reader<R: borsh::io::Read>(
		reader: &mut R,
	) -> borsh::io::Result<Self> {
		let name = String::deserialize_reader(reader)?;
		Self::new(name).map_err(|e| {
			borsh::io::Error::new(borsh::io::ErrorKind::InvalidData, e)
		})
	}
}

/// Validated plain-text environment variable value.
#[derive(
	PartialEq,
	Eq,
	PartialOrd,
	Ord,
	Clone,
	Hash,
	BorshSerialize,
	serde::Serialize,
	serde::Deserialize,
)]
#[serde(try_from = "String")]
pub struct PivotEnvPlainValue(String);

impl PivotEnvPlainValue {
	/// Parse and validate a plain environment variable value.
	///
	/// # Errors
	///
	/// Returns [`ProtocolError::InvalidPivotEnv`] if the value contains
	/// NUL bytes or exceeds the maximum length.
	pub fn new(value: String) -> Result<Self, ProtocolError> {
		if value.contains('\0') {
			return Err(ProtocolError::InvalidPivotEnv(
				"env var value cannot contain NUL".to_string(),
			));
		}
		if value.len() > MAX_PIVOT_ENV_VALUE_LEN {
			return Err(ProtocolError::InvalidPivotEnv(format!(
				"env var value too long: {} > {}",
				value.len(),
				MAX_PIVOT_ENV_VALUE_LEN
			)));
		}

		Ok(Self(value))
	}
}

impl Deref for PivotEnvPlainValue {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl AsRef<str> for PivotEnvPlainValue {
	fn as_ref(&self) -> &str {
		&self.0
	}
}

impl fmt::Display for PivotEnvPlainValue {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl fmt::Debug for PivotEnvPlainValue {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl TryFrom<String> for PivotEnvPlainValue {
	type Error = ProtocolError;

	fn try_from(value: String) -> Result<Self, Self::Error> {
		Self::new(value)
	}
}

impl From<PivotEnvPlainValue> for String {
	fn from(value: PivotEnvPlainValue) -> Self {
		value.0
	}
}

impl BorshDeserialize for PivotEnvPlainValue {
	fn deserialize_reader<R: borsh::io::Read>(
		reader: &mut R,
	) -> borsh::io::Result<Self> {
		let value = String::deserialize_reader(reader)?;
		Self::new(value).map_err(|e| {
			borsh::io::Error::new(borsh::io::ErrorKind::InvalidData, e)
		})
	}
}

/// Environment variable value to inject into the pivot process.
#[derive(
	PartialEq,
	Eq,
	Clone,
	Debug,
	BorshSerialize,
	serde::Serialize,
	serde::Deserialize,
)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum PivotEnvValue {
	/// A plain, non-secret environment variable value.
	Plain {
		/// Value to set for the environment variable.
		value: PivotEnvPlainValue,
	},
}

impl PivotEnvValue {
	/// Parse and validate a plain environment variable value.
	///
	/// # Errors
	///
	/// Returns [`ProtocolError::InvalidPivotEnv`] if the value is
	/// invalid.
	pub fn plain(value: String) -> Result<Self, ProtocolError> {
		Ok(Self::Plain { value: PivotEnvPlainValue::try_from(value)? })
	}

	/// Return the string value to inject into the pivot process.
	#[must_use]
	#[allow(unreachable_patterns)]
	pub fn as_plain_value(&self) -> Option<&str> {
		match self {
			Self::Plain { value } => Some(value.as_ref()),
			_ => None,
		}
	}
}

impl BorshDeserialize for PivotEnvValue {
	fn deserialize_reader<R: borsh::io::Read>(
		reader: &mut R,
	) -> borsh::io::Result<Self> {
		let variant = u8::deserialize_reader(reader)?;
		match variant {
			0 => {
				let value = String::deserialize_reader(reader)?;
				Self::plain(value).map_err(|e| {
					borsh::io::Error::new(borsh::io::ErrorKind::InvalidData, e)
				})
			}
			_ => Err(borsh::io::Error::new(
				borsh::io::ErrorKind::InvalidData,
				format!("invalid pivot env value variant: {variant}"),
			)),
		}
	}
}

/// Environment variables to inject into the pivot process.
#[derive(
	PartialEq,
	Eq,
	Clone,
	Default,
	BorshSerialize,
	serde::Serialize,
	serde::Deserialize,
)]
#[serde(try_from = "BTreeMap<PivotEnvVarName, PivotEnvValue>")]
#[repr(transparent)]
pub struct PivotEnv(BTreeMap<PivotEnvVarName, PivotEnvValue>);

impl PivotEnv {
	/// Create an empty pivot environment.
	#[must_use]
	pub fn new() -> Self {
		Self(BTreeMap::new())
	}

	/// Return the number of environment variables.
	#[must_use]
	pub fn len(&self) -> usize {
		self.0.len()
	}

	/// Return true if there are no environment variables.
	#[must_use]
	pub fn is_empty(&self) -> bool {
		self.0.is_empty()
	}

	/// Insert an environment variable.
	///
	/// # Errors
	///
	/// Returns [`ProtocolError::InvalidPivotEnv`] if inserting the
	/// variable would exceed the collection limits.
	pub fn insert(
		&mut self,
		name: PivotEnvVarName,
		value: PivotEnvValue,
	) -> Result<Option<PivotEnvValue>, ProtocolError> {
		let previous = self.0.insert(name.clone(), value);
		if let Err(err) = self.check_limits() {
			if let Some(previous) = previous {
				self.0.insert(name, previous);
			} else {
				self.0.remove(&name);
			}
			return Err(err);
		}

		Ok(previous)
	}

	/// Get an environment variable by name.
	#[must_use]
	pub fn get(&self, name: &str) -> Option<&PivotEnvValue> {
		self.0.get(name)
	}

	fn check_limits(&self) -> Result<(), ProtocolError> {
		if self.len() > MAX_PIVOT_ENV_VARS {
			return Err(ProtocolError::InvalidPivotEnv(format!(
				"too many env vars: {} > {}",
				self.len(),
				MAX_PIVOT_ENV_VARS
			)));
		}
		Ok(())
	}
}

impl TryFrom<BTreeMap<PivotEnvVarName, PivotEnvValue>> for PivotEnv {
	type Error = ProtocolError;

	fn try_from(
		value: BTreeMap<PivotEnvVarName, PivotEnvValue>,
	) -> Result<Self, Self::Error> {
		let env = Self(value);
		env.check_limits()?;
		Ok(env)
	}
}

impl BorshDeserialize for PivotEnv {
	fn deserialize_reader<R: borsh::io::Read>(
		reader: &mut R,
	) -> borsh::io::Result<Self> {
		let env =
			BTreeMap::<PivotEnvVarName, PivotEnvValue>::deserialize_reader(
				reader,
			)?;
		Self::try_from(env).map_err(|e| {
			borsh::io::Error::new(borsh::io::ErrorKind::InvalidData, e)
		})
	}
}

impl fmt::Debug for PivotEnv {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl Deref for PivotEnv {
	type Target = BTreeMap<PivotEnvVarName, PivotEnvValue>;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

#[cfg(test)]
mod test {
	use borsh::{BorshDeserialize, BorshSerialize};

	use super::*;

	#[test]
	fn parses_valid_pivot_env() {
		let mut env = BTreeMap::new();
		env.insert(
			PivotEnvVarName::new("FOO".to_string()).unwrap(),
			PivotEnvValue::plain("bar".to_string()).unwrap(),
		);
		env.insert(
			PivotEnvVarName::new("_EMPTY".to_string()).unwrap(),
			PivotEnvValue::plain(String::new()).unwrap(),
		);

		assert!(PivotEnv::try_from(env).is_ok());
	}

	#[test]
	fn accepts_valid_pivot_env_var_names() {
		assert!(PivotEnvVarName::new("A".to_string()).is_ok());
		assert!(PivotEnvVarName::new("_".to_string()).is_ok());
		assert!(PivotEnvVarName::new("_WITH_NUMBERS_123".to_string()).is_ok());
		assert!(
			PivotEnvVarName::new("A".repeat(MAX_PIVOT_ENV_NAME_LEN)).is_ok()
		);
	}

	#[test]
	fn rejects_invalid_pivot_env_as_it_parses() {
		assert!(PivotEnvVarName::new(String::new()).is_err());
		assert!(PivotEnvVarName::new("BAD=NAME".to_string()).is_err());
		assert!(PivotEnvVarName::new("1BAD".to_string()).is_err());
		assert!(PivotEnvVarName::new("BAD-NAME".to_string()).is_err());
		assert!(PivotEnvVarName::new("BAD.NAME".to_string()).is_err());
		assert!(PivotEnvVarName::new("BAD NAME".to_string()).is_err());
		assert!(PivotEnvVarName::new("BAD/NAME".to_string()).is_err());
		assert!(PivotEnvVarName::new("BAD+NAME".to_string()).is_err());
		assert!(
			PivotEnvVarName::new("A".repeat(MAX_PIVOT_ENV_NAME_LEN + 1))
				.is_err()
		);
		assert!(PivotEnvValue::plain("bad\0value".to_string()).is_err());
		assert!(
			PivotEnvValue::plain("A".repeat(MAX_PIVOT_ENV_VALUE_LEN + 1))
				.is_err()
		);

		let mut env = BTreeMap::new();
		for i in 0..=MAX_PIVOT_ENV_VARS {
			env.insert(
				PivotEnvVarName::new(format!("KEY_{i}")).unwrap(),
				PivotEnvValue::plain("value".to_string()).unwrap(),
			);
		}
		assert!(PivotEnv::try_from(env).is_err());
	}

	#[test]
	fn pivot_env_serializes_to_sorted_externally_tagged_json() {
		let mut env = PivotEnv::new();
		env.insert(
			PivotEnvVarName::new("ZETA".to_string()).unwrap(),
			PivotEnvValue::plain("last".to_string()).unwrap(),
		)
		.unwrap();
		env.insert(
			PivotEnvVarName::new("ALPHA".to_string()).unwrap(),
			PivotEnvValue::plain("first".to_string()).unwrap(),
		)
		.unwrap();

		let serialized = serde_json::to_string(&env).unwrap();
		assert_eq!(
			serialized,
			r#"{"ALPHA":{"plain":{"value":"first"}},"ZETA":{"plain":{"value":"last"}}}"#
		);
	}

	#[test]
	fn pivot_env_insert_rejects_values_that_exceed_count_limit() {
		let mut env = PivotEnv::new();
		for i in 0..MAX_PIVOT_ENV_VARS {
			env.insert(
				PivotEnvVarName::new(format!("KEY_{i}")).unwrap(),
				PivotEnvValue::plain("value".to_string()).unwrap(),
			)
			.unwrap();
		}

		let err = env
			.insert(
				PivotEnvVarName::new("ONE_TOO_MANY".to_string()).unwrap(),
				PivotEnvValue::plain("value".to_string()).unwrap(),
			)
			.unwrap_err();

		assert!(matches!(err, ProtocolError::InvalidPivotEnv(_)));
		assert_eq!(env.len(), MAX_PIVOT_ENV_VARS);
		assert!(env.get("ONE_TOO_MANY").is_none());
	}

	#[test]
	fn rejects_invalid_pivot_env_during_serde_deserialize() {
		let invalid = PivotEnv(BTreeMap::from([(
			PivotEnvVarName("1BAD".to_string()),
			PivotEnvValue::Plain {
				value: PivotEnvPlainValue("bar".to_string()),
			},
		)]));

		let serialized = serde_json::to_value(&invalid).unwrap();
		let err = serde_json::from_value::<PivotEnv>(serialized).unwrap_err();
		assert!(
			err.to_string()
				.contains("env var name `1BAD` must start with [A-Za-z_]"),
			"unexpected serde error: {err}"
		);
	}

	#[test]
	fn rejects_invalid_pivot_env_during_borsh_deserialize() {
		let mut bytes = Vec::new();
		1u32.serialize(&mut bytes).unwrap();
		"1BAD".to_string().serialize(&mut bytes).unwrap();
		0u8.serialize(&mut bytes).unwrap();
		"bar".to_string().serialize(&mut bytes).unwrap();

		let err = PivotEnv::try_from_slice(&bytes).unwrap_err();
		assert_eq!(err.kind(), borsh::io::ErrorKind::InvalidData);
		assert!(
			err.to_string()
				.contains("env var name `1BAD` must start with [A-Za-z_]"),
			"unexpected borsh error: {err}"
		);
	}
}