1use crate::master::{self, Master};
53use chacha20::{
54 ChaCha20Legacy,
55 cipher::{KeyIvInit, StreamCipher},
56};
57use serde::Deserialize;
58use std::{num::NonZeroU64, str::FromStr};
59
60pub trait RandomStream {
65 fn read(&mut self, dest: &mut [u8]);
67
68 fn u64(&mut self) -> u64 {
70 let mut data = [0; 8];
71 self.read(&mut data);
72 u64::from_le_bytes(data)
73 }
74
75 fn bool(&mut self) -> bool {
77 let mut data = [0; 1];
78 self.read(&mut data);
79 data[0] & 128 == 0
80 }
81
82 fn below(&mut self, max: u64) -> u64 {
93 assert!(max > 0, "cannot choose from nothing");
94 let mask = match max - 1 {
96 0 => 0,
97 largest => u64::MAX >> largest.leading_zeros(),
98 };
99 loop {
100 let number = self.u64() & mask;
101 if number < max {
102 return number;
103 }
104 }
105 }
106}
107
108impl<T: RandomStream + ?Sized> RandomStream for &mut T {
109 fn read(&mut self, dest: &mut [u8]) {
110 (**self).read(dest)
111 }
112}
113
114impl<T: RandomStream + ?Sized> RandomStream for Box<T> {
115 fn read(&mut self, dest: &mut [u8]) {
116 (**self).read(dest)
117 }
118}
119
120#[derive(Debug, Clone)]
122struct Blocks<const N: usize> {
123 block: [u8; N],
124 position: usize,
126}
127
128impl<const N: usize> Blocks<N> {
129 fn new() -> Self {
130 Self {
131 block: [0; N],
132 position: N,
133 }
134 }
135
136 fn read(&mut self, mut dest: &mut [u8], mut next: impl FnMut(&mut [u8; N])) {
137 while !dest.is_empty() {
138 if self.position == N {
139 next(&mut self.block);
140 self.position = 0;
141 }
142 let length = dest.len().min(N - self.position);
143 let (head, tail) = dest.split_at_mut(length);
144 head.copy_from_slice(&self.block[self.position..self.position + length]);
145 self.position += length;
146 dest = tail;
147 }
148 }
149}
150
151#[derive(Debug, Clone, PartialEq)]
156pub enum Random {
157 System(System),
159 Zero(Zero),
161 Xorshift(Xorshift),
163 ChaCha20(ChaCha20),
165}
166
167impl Default for Random {
168 fn default() -> Self {
169 Self::System(System)
170 }
171}
172
173impl Random {
174 pub fn is_deterministic(&self) -> bool {
177 !matches!(self, Self::System(_))
178 }
179}
180
181#[derive(Clone, PartialEq, Default, Deserialize)]
211pub enum RandomDesc {
212 #[default]
214 #[serde(rename = "system")]
215 System,
216 #[serde(rename = "zero")]
218 Zero,
219 #[serde(rename = "xorshift")]
221 Xorshift {
222 seed: NonZeroU64,
224 },
225 #[serde(rename = "chacha20")]
227 ChaCha20 {
228 key: [u8; 32],
230 #[serde(default = "default_iv")]
232 iv: [u8; 8],
233 },
234 #[serde(rename = "master")]
236 Master {
237 version: u32,
239 level: u32,
241 passphrase: String,
243 #[serde(default)]
245 seed: Vec<u8>,
246 #[serde(default)]
248 domain: String,
249 #[serde(default)]
251 user: String,
252 },
253}
254
255fn default_iv() -> [u8; 8] {
256 ChaCha20::DEFAULT_IV
257}
258
259impl std::fmt::Debug for RandomDesc {
260 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261 match self {
263 Self::System => f.write_str("System"),
264 Self::Zero => f.write_str("Zero"),
265 Self::Xorshift { seed } => f.debug_struct("Xorshift").field("seed", seed).finish(),
266 Self::ChaCha20 { .. } => f.debug_struct("ChaCha20").finish_non_exhaustive(),
267 Self::Master {
268 version,
269 level,
270 domain,
271 user,
272 ..
273 } => f
274 .debug_struct("Master")
275 .field("version", version)
276 .field("level", level)
277 .field("domain", domain)
278 .field("user", user)
279 .finish_non_exhaustive(),
280 }
281 }
282}
283
284impl RandomDesc {
285 pub fn is_secret(input: &str) -> bool {
289 input.starts_with("chacha20:") || input.starts_with("master:")
290 }
291
292 pub fn open(&self) -> Result<Random, master::Error> {
296 Ok(match self {
297 Self::System => Random::System(System),
298 Self::Zero => Random::Zero(Zero),
299 Self::Xorshift { seed } => Random::Xorshift(Xorshift(seed.get())),
300 Self::ChaCha20 { key, iv } => Random::ChaCha20(ChaCha20::new(*key, *iv)),
301 Self::Master {
302 version,
303 level,
304 passphrase,
305 seed,
306 domain,
307 user,
308 } => {
309 let master = Master::derive(*version, *level, passphrase, seed)?;
310 Random::ChaCha20(master.random(domain, user))
311 }
312 })
313 }
314}
315
316#[derive(thiserror::Error, Debug, Clone, PartialEq)]
318pub enum ParseError {
319 #[error("unknown randomness source '{0:}'")]
321 Unknown(String),
322 #[error("invalid seed '{0:}', must be a number between 1 and 18446744073709551615")]
324 Seed(String),
325 #[error("key must be 64 hex digits")]
327 Key,
328 #[error("IV must be 16 hex digits")]
330 Iv,
331 #[error(
334 "expected master:VERSION:LEVEL:PASSPHRASE:SEED:DOMAIN:USER, with a seed in hex, and \\: \
335 for colons"
336 )]
337 Master,
338 #[error(transparent)]
340 MasterLevel(#[from] master::Error),
341 #[error("master passphrase, domain and user can have at most {DESCRIPTION_MAX} bytes each")]
343 TooLong,
344}
345
346fn hex<const N: usize>(input: &str) -> Option<[u8; N]> {
348 hex_bytes(input)?.try_into().ok()
349}
350
351const DESCRIPTION_MAX: usize = 128;
354
355fn master_fields(input: &str) -> Option<Vec<String>> {
358 let mut fields = vec![String::new()];
359 let mut chars = input.chars();
360 while let Some(character) = chars.next() {
361 match character {
362 ':' => fields.push(String::new()),
363 '\\' => match chars.next()? {
364 escaped @ (':' | '\\') => fields.last_mut()?.push(escaped),
365 _ => return None,
366 },
367 character => fields.last_mut()?.push(character),
368 }
369 }
370 Some(fields)
371}
372
373fn master_number(input: &str) -> Option<u32> {
375 let valid = (1..=3).contains(&input.len())
376 && input.bytes().all(|byte| byte.is_ascii_digit())
377 && (input.len() == 1 || !input.starts_with('0'));
378 valid.then(|| input.parse().ok()).flatten()
379}
380
381fn hex_bytes(input: &str) -> Option<Vec<u8>> {
383 if !input.len().is_multiple_of(2) {
384 return None;
385 }
386 input
387 .as_bytes()
388 .chunks(2)
389 .map(|pair| {
390 let high = (pair[0] as char).to_digit(16)?;
391 let low = (pair[1] as char).to_digit(16)?;
392 Some((high << 4 | low) as u8)
393 })
394 .collect()
395}
396
397fn master_desc(params: &str) -> Result<RandomDesc, ParseError> {
399 let fields: [String; 6] = master_fields(params)
400 .and_then(|fields| fields.try_into().ok())
401 .ok_or(ParseError::Master)?;
402 let [version, level, passphrase, seed, domain, user] = fields;
403
404 let version = master_number(&version).ok_or(ParseError::Master)?;
406 let level = master_number(&level).ok_or(ParseError::Master)?;
407 master::Cost::level(version, level)?;
408
409 if [&passphrase, &domain, &user]
410 .iter()
411 .any(|part| part.len() > DESCRIPTION_MAX)
412 {
413 return Err(ParseError::TooLong);
414 }
415
416 let seed = hex_bytes(&seed).ok_or(ParseError::Master)?;
417 if seed.len() > master::SEED_MAX {
418 return Err(master::Error::SeedTooLong.into());
419 }
420
421 Ok(RandomDesc::Master {
422 version,
423 level,
424 passphrase,
425 seed,
426 domain,
427 user,
428 })
429}
430
431impl FromStr for RandomDesc {
432 type Err = ParseError;
433
434 fn from_str(input: &str) -> Result<Self, Self::Err> {
435 let (name, params) = match input.split_once(':') {
436 Some((name, params)) => (name, Some(params)),
437 None => (input, None),
438 };
439
440 match (name, params) {
441 ("system", None) => Ok(Self::System),
442 ("zero", None) => Ok(Self::Zero),
443 ("xorshift", Some(seed)) => seed
444 .parse()
445 .ok()
446 .filter(|_| seed.bytes().all(|byte| byte.is_ascii_digit()))
448 .map(|seed| Self::Xorshift { seed })
449 .ok_or_else(|| ParseError::Seed(seed.to_string())),
450 ("chacha20", Some(params)) => {
451 let (key, iv) = match params.split_once(':') {
454 Some((key, iv)) => (key, Some(iv)),
455 None => (params, None),
456 };
457
458 Ok(Self::ChaCha20 {
459 key: hex(key).ok_or(ParseError::Key)?,
460 iv: match iv {
461 None => ChaCha20::DEFAULT_IV,
462 Some(iv) => hex(iv).ok_or(ParseError::Iv)?,
463 },
464 })
465 }
466 ("master", Some(params)) => master_desc(params),
467 _ => Err(ParseError::Unknown(input.to_string())),
468 }
469 }
470}
471
472pub trait RandomSource {
478 type Stream: RandomStream + 'static;
480
481 fn stream(&self, index: u64) -> Self::Stream;
483
484 fn stream_boxed(&self, index: u64) -> Box<dyn RandomStream> {
486 Box::new(self.stream(index))
487 }
488}
489
490impl RandomSource for Random {
491 type Stream = Box<dyn RandomStream>;
492
493 fn stream(&self, index: u64) -> Box<dyn RandomStream> {
494 match self {
495 Self::System(random) => random.stream_boxed(index),
496 Self::Zero(random) => random.stream_boxed(index),
497 Self::Xorshift(random) => random.stream_boxed(index),
498 Self::ChaCha20(random) => random.stream_boxed(index),
499 }
500 }
501
502 fn stream_boxed(&self, index: u64) -> Box<dyn RandomStream> {
503 self.stream(index)
504 }
505}
506
507#[derive(Debug, Clone, Copy, PartialEq, Default)]
509pub struct System;
510
511#[derive(Debug, Clone)]
513pub struct SystemStream(Blocks<1024>);
514
515impl RandomSource for System {
516 type Stream = SystemStream;
517
518 fn stream(&self, _index: u64) -> Self::Stream {
519 SystemStream(Blocks::new())
520 }
521}
522
523impl RandomStream for SystemStream {
524 fn read(&mut self, dest: &mut [u8]) {
528 self.0.read(dest, |block| {
529 getrandom::fill(block).expect("system randomness is not available")
530 })
531 }
532}
533
534#[derive(Debug, Clone, Copy, PartialEq, Default)]
536pub struct Zero;
537
538impl RandomSource for Zero {
539 type Stream = Zero;
540
541 fn stream(&self, _index: u64) -> Self::Stream {
542 Zero
543 }
544}
545
546impl RandomStream for Zero {
547 fn read(&mut self, dest: &mut [u8]) {
548 dest.fill(0);
549 }
550}
551
552#[derive(Debug, Clone, Copy, PartialEq)]
554pub struct Xorshift(u64);
555
556impl Xorshift {
557 pub fn new(seed: u64) -> Option<Self> {
559 (seed != 0).then_some(Xorshift(seed))
560 }
561}
562
563#[derive(Debug, Clone)]
565pub struct XorshiftStream {
566 state: u64,
567 blocks: Blocks<8>,
568}
569
570impl RandomSource for Xorshift {
571 type Stream = XorshiftStream;
572
573 fn stream(&self, index: u64) -> Self::Stream {
574 let mut mix = index.wrapping_mul(0x9e3779b97f4a7c15);
578 mix = (mix ^ (mix >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
579 mix = (mix ^ (mix >> 27)).wrapping_mul(0x94d049bb133111eb);
580 mix ^= mix >> 31;
581
582 let state = match self.0 ^ mix {
584 0 => u64::MAX,
585 state => state,
586 };
587
588 XorshiftStream {
589 state,
590 blocks: Blocks::new(),
591 }
592 }
593}
594
595impl RandomStream for XorshiftStream {
596 fn read(&mut self, dest: &mut [u8]) {
597 let state = &mut self.state;
598 self.blocks.read(dest, |block| {
599 *state ^= *state << 13;
600 *state ^= *state >> 7;
601 *state ^= *state << 17;
602 *block = state.to_le_bytes();
603 })
604 }
605}
606
607#[derive(Clone, Copy, PartialEq)]
612pub struct ChaCha20 {
613 key: [u8; 32],
614 iv: [u8; 8],
615}
616
617impl std::fmt::Debug for ChaCha20 {
618 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619 f.debug_struct("ChaCha20").finish_non_exhaustive()
621 }
622}
623
624impl ChaCha20 {
625 pub const DEFAULT_IV: [u8; 8] = *b"passgen\0";
627
628 pub fn new(key: [u8; 32], iv: [u8; 8]) -> Self {
630 Self { key, iv }
631 }
632}
633
634pub struct ChaCha20Stream(ChaCha20Legacy);
636
637impl RandomSource for ChaCha20 {
638 type Stream = ChaCha20Stream;
639
640 fn stream(&self, index: u64) -> Self::Stream {
641 let iv = u64::from_le_bytes(self.iv) ^ index;
645 ChaCha20Stream(ChaCha20Legacy::new(
646 &self.key.into(),
647 &iv.to_le_bytes().into(),
648 ))
649 }
650}
651
652impl RandomStream for ChaCha20Stream {
653 fn read(&mut self, dest: &mut [u8]) {
654 dest.fill(0);
656 self.0.apply_keystream(dest);
657 }
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663 use test_strategy::*;
664
665 struct Bytes<'a>(&'a [u8], usize);
667
668 impl RandomStream for Bytes<'_> {
669 fn read(&mut self, dest: &mut [u8]) {
670 dest.copy_from_slice(&self.0[self.1..self.1 + dest.len()]);
671 self.1 += dest.len();
672 }
673 }
674
675 #[test]
676 fn stream_u64_little_endian() {
677 let mut stream = Bytes(&[1, 2, 3, 4, 5, 6, 7, 8], 0);
678 assert_eq!(stream.u64(), 0x0807060504030201);
679 }
680
681 #[test]
682 fn stream_bool_highest_bit() {
683 let mut stream = Bytes(&[0, 127, 128, 255], 0);
684 assert_eq!(
685 [stream.bool(), stream.bool(), stream.bool(), stream.bool()],
686 [true, true, false, false]
687 );
688 assert_eq!(stream.1, 4);
689 }
690
691 #[test]
692 fn stream_below_masks_and_rejects() {
693 let numbers: Vec<u8> = [0xffu64, 0x106, 0x105, 0x1234]
694 .into_iter()
695 .flat_map(u64::to_le_bytes)
696 .collect();
697
698 let mut stream = Bytes(&numbers, 0);
700 assert_eq!(stream.below(6), 5);
701 assert_eq!(stream.1, 24);
702
703 let mut stream = Bytes(&numbers, 0);
705 assert_eq!(stream.below(8), 7);
706 assert_eq!(stream.below(256), 6);
707 assert_eq!(stream.1, 16);
708
709 let mut stream = Bytes(&numbers, 0);
711 assert_eq!(stream.below(1), 0);
712 assert_eq!(stream.1, 8);
713
714 let numbers: Vec<u8> = [u64::MAX, u64::MAX - 1]
716 .into_iter()
717 .flat_map(u64::to_le_bytes)
718 .collect();
719 let mut stream = Bytes(&numbers, 0);
720 assert_eq!(stream.below(u64::MAX), u64::MAX - 1);
721 assert_eq!(stream.1, 16);
722 }
723
724 #[test]
725 #[should_panic]
726 fn stream_below_zero() {
727 Zero.below(0);
728 }
729
730 #[proptest]
731 fn stream_below_in_range(#[strategy(1u64..)] seed: u64, #[strategy(1u64..)] max: u64) {
732 let mut stream = Xorshift::new(seed).unwrap().stream(0);
733 for _ in 0..16 {
734 assert!(stream.below(max) < max);
735 }
736 }
737
738 #[proptest]
740 fn streams_are_bytes(index: u64, #[strategy(1u64..)] seed: u64, sizes: Vec<u8>) {
741 let sources = [
742 Random::Xorshift(Xorshift::new(seed).unwrap()),
743 Random::ChaCha20(ChaCha20::new([seed as u8; 32], seed.to_le_bytes())),
744 ];
745 for source in sources {
746 let total = sizes.iter().map(|size| *size as usize).sum();
747 let mut whole = vec![0; total];
748 source.stream(index).read(&mut whole);
749
750 let mut stream = source.stream(index);
751 let mut parts = vec![0; total];
752 let mut rest = &mut parts[..];
753 for size in &sizes {
754 let (part, tail) = rest.split_at_mut(*size as usize);
755 stream.read(part);
756 rest = tail;
757 }
758
759 assert_eq!(whole, parts);
760 }
761 }
762
763 #[test]
764 fn xorshift_stream() {
765 let mut stream = Xorshift::new(1).unwrap().stream(0);
767 assert_eq!(stream.u64(), 0x40822041);
768 assert_eq!(stream.u64(), 0x100041060c011441);
769 assert_eq!(Xorshift::new(0), None);
770 }
771
772 #[test]
773 fn parse_random() {
774 let parse = |input: &str| input.parse::<RandomDesc>();
775 assert_eq!(parse("system"), Ok(RandomDesc::System));
776 assert_eq!(parse("zero"), Ok(RandomDesc::Zero));
777 assert_eq!(
778 parse("xorshift:18446744073709551615"),
779 Ok(RandomDesc::Xorshift {
780 seed: NonZeroU64::MAX
781 })
782 );
783 for seed in ["", "0", "+1", "-1", "abc", "1 ", "18446744073709551616"] {
784 assert_eq!(
785 parse(&format!("xorshift:{seed}")),
786 Err(ParseError::Seed(seed.into()))
787 );
788 }
789 for random in ["", "null", "xorshift", "zero:1", "xoshiro:1", "chacha20"] {
790 assert_eq!(parse(random), Err(ParseError::Unknown(random.into())));
791 }
792 }
793
794 #[test]
795 fn open_random() {
796 let open = |input: &str| input.parse::<RandomDesc>().unwrap().open().unwrap();
797 assert_eq!(RandomDesc::default().open(), Ok(Random::default()));
798 assert_eq!(open("system"), Random::System(System));
799 assert_eq!(open("zero"), Random::Zero(Zero));
800 assert_eq!(open("xorshift:5"), Random::Xorshift(Xorshift(5)));
801 assert_eq!(
802 open(&format!("chacha20:{}:{}", "6b".repeat(32), "69".repeat(8))),
803 Random::ChaCha20(ChaCha20::new([b'k'; 32], [b'i'; 8]))
804 );
805 assert_eq!(
806 open("master:1:1:a:00:b:c"),
807 Random::ChaCha20(Master::derive(1, 1, "a", &[0]).unwrap().random("b", "c"))
808 );
809 }
810
811 #[test]
812 fn debug_hides_secrets() {
813 let key = format!("{}{}", "736563726574".repeat(4), "00".repeat(8));
815 for random in [
816 format!("chacha20:{key}"),
817 "master:1:1:secret:736563726574:domain:user".to_string(),
818 ] {
819 let desc: RandomDesc = random.parse().unwrap();
820 for debug in [format!("{desc:?}"), format!("{:?}", desc.open().unwrap())] {
821 assert!(!debug.contains("secret"));
822 assert!(!debug.contains("736563"));
823 assert!(!debug.contains("115, 101, 99"));
825 }
826 }
827 }
828
829 #[test]
830 fn deserialize_random() {
831 let parse = |input: &str| serde_json::from_str::<RandomDesc>(input).unwrap();
832 assert_eq!(parse(r#""system""#), RandomDesc::System);
833 assert_eq!(parse(r#""zero""#), RandomDesc::Zero);
834 assert_eq!(
835 parse(r#"{"xorshift": {"seed": 1234}}"#),
836 "xorshift:1234".parse().unwrap()
837 );
838 assert_eq!(
839 parse(r#"{"master": {"version": 1, "level": 2, "passphrase": "a", "domain": "b"}}"#),
840 "master:1:2:a::b:".parse().unwrap()
841 );
842 assert_eq!(
843 parse(&format!(r#"{{"chacha20": {{"key": {:?}}}}}"#, [97; 32])),
844 format!("chacha20:{}", "61".repeat(32)).parse().unwrap()
845 );
846 assert!(serde_json::from_str::<RandomDesc>(r#"{"xorshift": {"seed": 0}}"#).is_err());
848 }
849
850 #[test]
851 fn chacha20_stream() {
852 let mut stream = ChaCha20::new([0; 32], [0; 8]).stream(0);
854 let mut data = [0; 16];
855 stream.read(&mut data);
856 assert_eq!(
857 data,
858 [
859 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86,
860 0xbd, 0x28
861 ]
862 );
863 }
864
865 #[test]
866 fn chacha20_streams_differ() {
867 let random = ChaCha20::new([1; 32], ChaCha20::DEFAULT_IV);
868 let numbers = |index| {
869 let mut stream = random.stream(index);
870 [stream.u64(), stream.u64()]
871 };
872 assert_eq!(numbers(0), numbers(0));
873 assert_ne!(numbers(0), numbers(1));
874 assert_ne!(numbers(1), numbers(2));
875 }
876
877 #[test]
878 fn parse_chacha20() {
879 let parse = |input: &str| match input.parse::<RandomDesc>() {
880 Ok(RandomDesc::ChaCha20 { key, iv }) => Ok((key, iv)),
881 Ok(other) => panic!("not chacha20: {other:?}"),
882 Err(error) => Err(error),
883 };
884
885 let mut key = [0; 32];
886 key[..3].copy_from_slice(b"key");
887 let hex_key = format!("6b6579{}", "0".repeat(58));
888 assert_eq!(
889 parse(&format!("chacha20:{hex_key}")),
890 Ok((key, *b"passgen\0"))
891 );
892 assert_eq!(
893 parse(&format!("chacha20:{hex_key}:6976000000000000")),
894 Ok((key, *b"iv\0\0\0\0\0\0"))
895 );
896
897 assert_eq!(
899 parse(&format!("chacha20:{}:{}", "fF".repeat(32), "Ab".repeat(8))),
900 Ok(([0xff; 32], [0xab; 8]))
901 );
902
903 for key in [
905 "",
906 "key",
907 &hex_key[1..],
908 &format!("{hex_key}00"),
909 &hex_key.replace('6', "g"),
910 ] {
911 assert_eq!(
912 parse(&format!("chacha20:{key}")),
913 Err(ParseError::Key),
914 "{key}"
915 );
916 }
917 for iv in [
918 "",
919 "iv",
920 "69760000000000",
921 "697600000000000000",
922 "+976000000000000",
923 ] {
924 assert_eq!(
925 parse(&format!("chacha20:{hex_key}:{iv}")),
926 Err(ParseError::Iv),
927 "{iv}"
928 );
929 }
930 assert_eq!(
931 parse(&format!("chacha20:{hex_key}:6976000000000000:")),
932 Err(ParseError::Iv)
933 );
934 }
935
936 #[test]
937 fn parse_master() {
938 let parse = |input: &str| input.parse::<RandomDesc>();
939 let master = |passphrase: &str, seed: &[u8], domain: &str, user: &str| {
940 Ok(RandomDesc::Master {
941 version: 1,
942 level: 1,
943 passphrase: passphrase.into(),
944 seed: seed.into(),
945 domain: domain.into(),
946 user: user.into(),
947 })
948 };
949 assert_eq!(parse("master:1:1:master:::"), master("master", &[], "", ""));
950 assert_eq!(parse("master:1:1:a::b:c"), master("a", &[], "b", "c"));
951 assert_eq!(parse("master:1:1:a:::c"), master("a", &[], "", "c"));
952 assert_eq!(parse("master:1:1::::"), master("", &[], "", ""));
953 assert_eq!(
954 parse("master:1:1:a:00fFa1:b:c"),
955 master("a", &[0, 255, 161], "b", "c")
956 );
957 assert!(matches!(
958 parse("master:1:3:a::b:c"),
959 Ok(RandomDesc::Master { level: 3, .. })
960 ));
961
962 assert_eq!(
964 parse(r"master:1:1:pass\:word\\::example.com\:8443:us\\er"),
965 master(r"pass:word\", &[], "example.com:8443", r"us\er")
966 );
967
968 for random in [
970 "master:",
971 "master:1:1:a",
972 "master:1:1:a::b",
973 "master:1:1:a::b:c:",
974 "master:1:1:a::b:c:d",
975 r"master:1:1:pa\ss::b:c",
977 r"master:1:1:a::b:c\",
978 "master::1:a::b:c",
980 "master:1::a::b:c",
981 "master:01:1:a::b:c",
982 "master:1:+1:a::b:c",
983 "master:1:1000:a::b:c",
984 "master:x:1:a::b:c",
985 "master:1:1:a:0:b:c",
987 "master:1:1:a:0g:b:c",
988 "master:1:1:a:seed:b:c",
989 ] {
990 assert_eq!(parse(random), Err(ParseError::Master), "{random}");
991 }
992
993 assert_eq!(
995 parse("master:2:1:a::b:c"),
996 Err(ParseError::MasterLevel(master::Error::Version(2)))
997 );
998 assert_eq!(
999 parse("master:1:4:a::b:c"),
1000 Err(ParseError::MasterLevel(master::Error::Level(4)))
1001 );
1002 assert_eq!(
1003 parse("master:1:0:a::b:c"),
1004 Err(ParseError::MasterLevel(master::Error::Level(0)))
1005 );
1006 }
1007
1008 #[test]
1009 fn parse_master_limits() {
1010 let parse = |input: &str| input.parse::<RandomDesc>();
1011 let fits = "a".repeat(DESCRIPTION_MAX);
1012 assert!(parse(&format!("master:1:1:{fits}::{fits}:{fits}")).is_ok());
1013
1014 let long = format!("{fits}a");
1015 for random in [
1016 format!("master:1:1:{long}::b:c"),
1017 format!("master:1:1:a::{long}:c"),
1018 format!("master:1:1:a::b:{long}"),
1019 ] {
1020 assert_eq!(parse(&random), Err(ParseError::TooLong));
1021 }
1022
1023 let seed = "00".repeat(master::SEED_MAX);
1024 assert!(parse(&format!("master:1:1:a:{seed}:b:c")).is_ok());
1025 assert_eq!(
1026 parse(&format!("master:1:1:a:{seed}00:b:c")),
1027 Err(ParseError::MasterLevel(master::Error::SeedTooLong))
1028 );
1029 }
1030
1031 #[test]
1032 fn secret_descriptions() {
1033 for random in ["system", "zero", "xorshift:1", "chacha20", "unknown:x"] {
1034 assert!(!RandomDesc::is_secret(random), "{random}");
1035 }
1036 for random in ["chacha20:", "chacha20:key", "master:", "master:1:1:a"] {
1037 assert!(RandomDesc::is_secret(random), "{random}");
1038 }
1039 }
1040}