1#![forbid(unsafe_code)]
27#![warn(missing_docs)]
28
29mod realisation;
30
31pub use realisation::{
32 realisation_cache_path, Realisation, RealisationParseError, UnkeyedRealisation,
33 MAX_REALISATION_SIZE, REALISATIONS_PREFIX,
34};
35
36use std::collections::BTreeSet;
37use std::fmt;
38use std::io;
39use std::str::FromStr;
40
41use base64::Engine as _;
42use ed25519_dalek::{Signature, VerifyingKey};
43use nix_derivation::{CAHash, NixHash, StoreDir, StorePath};
44use thiserror::Error;
45
46pub const MAX_NARINFO_SIZE: usize = 1024 * 1024;
48
49#[derive(Clone, Debug, Eq, PartialEq)]
51pub struct NarInfo {
52 store_dir: StoreDir,
53 store_path: StorePath,
54 url: String,
55 compression: Compression,
56 nar_hash: NixHash,
57 nar_size: u64,
58 references: BTreeSet<StorePath>,
59 deriver: Option<StorePath>,
60 signatures: Vec<NarInfoSignature>,
61 content_address: Option<CAHash>,
62 file_hash: Option<NixHash>,
63 file_size: Option<u64>,
64 extensions: Vec<Field>,
65}
66
67#[derive(Clone, Debug, Eq, PartialEq)]
69pub enum Compression {
70 None,
72 Bzip2,
74 Gzip,
76 Xz,
78 Zstd,
80 Other(String),
82}
83
84impl Compression {
85 #[must_use]
87 pub fn parse(input: &str) -> Self {
88 match input {
89 "" | "bzip2" => Self::Bzip2,
90 "none" => Self::None,
91 "gzip" => Self::Gzip,
92 "xz" => Self::Xz,
93 "zstd" => Self::Zstd,
94 other => Self::Other(other.to_owned()),
95 }
96 }
97
98 #[must_use]
100 pub fn as_str(&self) -> &str {
101 match self {
102 Self::None => "none",
103 Self::Bzip2 => "bzip2",
104 Self::Gzip => "gzip",
105 Self::Xz => "xz",
106 Self::Zstd => "zstd",
107 Self::Other(name) => name,
108 }
109 }
110}
111
112impl fmt::Display for Compression {
113 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
114 formatter.write_str(self.as_str())
115 }
116}
117
118#[derive(Clone, Debug, Eq, PartialEq)]
123pub struct NixSignature {
124 pub key_name: String,
126 pub encoded: String,
128}
129
130pub type NarInfoSignature = NixSignature;
132
133#[derive(Clone, Debug, Eq, PartialEq)]
135pub struct Field {
136 pub name: String,
138 pub value: String,
140}
141
142#[derive(Clone, Debug, Eq, PartialEq)]
144pub struct TrustedPublicKey {
145 pub name: String,
147 pub key: VerifyingKey,
149}
150
151#[derive(Clone, Debug)]
153pub struct NarInfoBuilder {
154 store_dir: StoreDir,
155 store_path: StorePath,
156 url: String,
157 compression: Compression,
158 nar_hash: NixHash,
159 nar_size: u64,
160 references: BTreeSet<StorePath>,
161 deriver: Option<StorePath>,
162 signatures: Vec<NarInfoSignature>,
163 content_address: Option<CAHash>,
164 file_hash: Option<NixHash>,
165 file_size: Option<u64>,
166 extensions: Vec<Field>,
167}
168
169impl NarInfoBuilder {
170 #[must_use]
172 pub fn new(
173 store_path: StorePath,
174 url: impl Into<String>,
175 nar_hash: NixHash,
176 nar_size: u64,
177 ) -> Self {
178 Self::new_in(StoreDir::default(), store_path, url, nar_hash, nar_size)
179 }
180
181 #[must_use]
183 pub fn new_in(
184 store_dir: StoreDir,
185 store_path: StorePath,
186 url: impl Into<String>,
187 nar_hash: NixHash,
188 nar_size: u64,
189 ) -> Self {
190 Self {
191 store_dir,
192 store_path,
193 url: url.into(),
194 compression: Compression::Bzip2,
195 nar_hash,
196 nar_size,
197 references: BTreeSet::new(),
198 deriver: None,
199 signatures: Vec::new(),
200 content_address: None,
201 file_hash: None,
202 file_size: None,
203 extensions: Vec::new(),
204 }
205 }
206
207 #[must_use]
209 pub fn compression(mut self, compression: Compression) -> Self {
210 self.compression = compression;
211 self
212 }
213
214 #[must_use]
216 pub fn references(mut self, references: impl IntoIterator<Item = StorePath>) -> Self {
217 self.references = references.into_iter().collect();
218 self
219 }
220
221 #[must_use]
223 pub fn deriver(mut self, deriver: Option<StorePath>) -> Self {
224 self.deriver = deriver;
225 self
226 }
227
228 #[must_use]
230 pub fn signatures(mut self, signatures: impl IntoIterator<Item = NarInfoSignature>) -> Self {
231 self.signatures = signatures.into_iter().collect();
232 self
233 }
234
235 #[must_use]
237 pub fn signature(mut self, signature: NarInfoSignature) -> Self {
238 self.signatures.push(signature);
239 self
240 }
241
242 #[must_use]
244 pub fn content_address(mut self, content_address: Option<CAHash>) -> Self {
245 self.content_address = content_address;
246 self
247 }
248
249 #[must_use]
251 pub fn file_hash(mut self, file_hash: Option<NixHash>) -> Self {
252 self.file_hash = file_hash;
253 self
254 }
255
256 #[must_use]
258 pub fn file_size(mut self, file_size: Option<u64>) -> Self {
259 self.file_size = file_size;
260 self
261 }
262
263 #[must_use]
265 pub fn extensions(mut self, extensions: impl IntoIterator<Item = Field>) -> Self {
266 self.extensions = extensions.into_iter().collect();
267 self
268 }
269
270 #[must_use]
272 pub fn extension(mut self, extension: Field) -> Self {
273 self.extensions.push(extension);
274 self
275 }
276
277 pub fn build(self) -> Result<NarInfo, BuildError> {
279 if self.nar_size == 0 {
280 return Err(BuildError::ZeroNarSize);
281 }
282 validate_line_value("StoreDir", self.store_dir.as_str())?;
283 validate_canonical_value("URL", &self.url)?;
284 if self.url.is_empty() {
285 return Err(BuildError::InvalidField {
286 field: "URL".to_owned(),
287 message: "must not be empty".to_owned(),
288 });
289 }
290 if let Compression::Other(name) = &self.compression {
291 validate_canonical_value("Compression", name)?;
292 if matches!(
293 name.as_str(),
294 "" | "none" | "bzip2" | "gzip" | "xz" | "zstd"
295 ) {
296 return Err(BuildError::InvalidField {
297 field: "Compression".to_owned(),
298 message: "known names must use their typed compression variant".to_owned(),
299 });
300 }
301 }
302 for signature in &self.signatures {
303 validate_canonical_value("Sig key name", &signature.key_name)?;
304 validate_line_value("Sig encoding", &signature.encoded)?;
305 if signature.key_name.contains(':') {
306 return Err(BuildError::InvalidField {
307 field: "Sig key name".to_owned(),
308 message: "must not contain ':'".to_owned(),
309 });
310 }
311 }
312 for extension in &self.extensions {
313 validate_line_value("extension name", &extension.name)?;
314 validate_canonical_value("extension value", &extension.value)?;
315 if extension.name.is_empty() || extension.name.contains(':') {
316 return Err(BuildError::InvalidField {
317 field: "extension name".to_owned(),
318 message: "must be nonempty and must not contain ':'".to_owned(),
319 });
320 }
321 if is_known_field(&extension.name) {
322 return Err(BuildError::InvalidField {
323 field: extension.name.clone(),
324 message: "recognized fields must use their typed builder method".to_owned(),
325 });
326 }
327 }
328
329 Ok(NarInfo {
330 store_dir: self.store_dir,
331 store_path: self.store_path,
332 url: self.url,
333 compression: self.compression,
334 nar_hash: self.nar_hash,
335 nar_size: self.nar_size,
336 references: self.references,
337 deriver: self.deriver,
338 signatures: self.signatures,
339 content_address: self.content_address,
340 file_hash: self.file_hash,
341 file_size: self.file_size,
342 extensions: self.extensions,
343 })
344 }
345}
346
347impl TrustedPublicKey {
348 pub fn parse(input: &str) -> Result<Self, KeyError> {
350 let (name, encoded) = input.split_once(':').ok_or(KeyError::MissingName)?;
351 if name.is_empty() {
352 return Err(KeyError::EmptyName);
353 }
354 let bytes = base64::engine::general_purpose::STANDARD
355 .decode(encoded)
356 .map_err(|_| KeyError::InvalidBase64)?;
357 let bytes: [u8; 32] = bytes
358 .try_into()
359 .map_err(|bytes: Vec<u8>| KeyError::InvalidLength { got: bytes.len() })?;
360 let key = VerifyingKey::from_bytes(&bytes).map_err(|_| KeyError::InvalidKey)?;
361 Ok(Self {
362 name: name.to_owned(),
363 key,
364 })
365 }
366}
367
368impl FromStr for TrustedPublicKey {
369 type Err = KeyError;
370
371 fn from_str(input: &str) -> Result<Self, Self::Err> {
372 Self::parse(input)
373 }
374}
375
376impl NixSignature {
377 pub fn parse(input: &str) -> Result<Self, SignatureError> {
383 let (key_name, encoded) = input
384 .split_once(':')
385 .ok_or(SignatureError::MissingSeparator)?;
386 if key_name.is_empty() {
387 return Err(SignatureError::EmptyKeyName);
388 }
389 let bytes = base64::engine::general_purpose::STANDARD
390 .decode(encoded)
391 .map_err(|_| SignatureError::InvalidBase64)?;
392 if bytes.is_empty() {
393 return Err(SignatureError::EmptySignature);
394 }
395 Ok(Self {
396 key_name: key_name.to_owned(),
397 encoded: base64::engine::general_purpose::STANDARD.encode(bytes),
398 })
399 }
400
401 pub fn from_bytes(key_name: impl Into<String>, bytes: &[u8]) -> Result<Self, SignatureError> {
403 let key_name = key_name.into();
404 if key_name.is_empty() {
405 return Err(SignatureError::EmptyKeyName);
406 }
407 if key_name.contains(':') {
408 return Err(SignatureError::InvalidKeyName);
409 }
410 if bytes.is_empty() {
411 return Err(SignatureError::EmptySignature);
412 }
413 Ok(Self {
414 key_name,
415 encoded: base64::engine::general_purpose::STANDARD.encode(bytes),
416 })
417 }
418
419 pub fn to_nix_string(&self) -> String {
424 format!("{}:{}", self.key_name, self.encoded)
425 }
426
427 pub fn canonicalized(&self) -> Result<Self, SignatureError> {
429 if self.key_name.is_empty() {
430 return Err(SignatureError::EmptyKeyName);
431 }
432 if self.key_name.contains(':') {
433 return Err(SignatureError::InvalidKeyName);
434 }
435 let bytes = base64::engine::general_purpose::STANDARD
436 .decode(&self.encoded)
437 .map_err(|_| SignatureError::InvalidBase64)?;
438 Self::from_bytes(self.key_name.clone(), &bytes)
439 }
440
441 pub fn verify(
447 &self,
448 fingerprint: &[u8],
449 keys: &[TrustedPublicKey],
450 ) -> Result<bool, SignatureError> {
451 if self.key_name.is_empty() {
452 return Err(SignatureError::EmptyKeyName);
453 }
454 let bytes = base64::engine::general_purpose::STANDARD
455 .decode(&self.encoded)
456 .map_err(|_| SignatureError::InvalidBase64)?;
457 let signature = Signature::from_slice(&bytes)
458 .map_err(|_| SignatureError::InvalidLength { got: bytes.len() })?;
459
460 Ok(keys
461 .iter()
462 .filter(|key| key.name == self.key_name)
463 .any(|key| key.key.verify_strict(fingerprint, &signature).is_ok()))
464 }
465}
466
467impl fmt::Display for NixSignature {
468 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
469 formatter.write_str(&self.to_nix_string())
470 }
471}
472
473impl FromStr for NixSignature {
474 type Err = SignatureError;
475
476 fn from_str(input: &str) -> Result<Self, Self::Err> {
477 Self::parse(input)
478 }
479}
480
481impl PartialOrd for NixSignature {
482 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
483 Some(self.cmp(other))
484 }
485}
486
487impl Ord for NixSignature {
488 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
489 self.key_name.cmp(&other.key_name).then_with(|| {
490 let engine = base64::engine::general_purpose::STANDARD;
491 match (engine.decode(&self.encoded), engine.decode(&other.encoded)) {
492 (Ok(left), Ok(right)) => left
493 .cmp(&right)
494 .then_with(|| self.encoded.cmp(&other.encoded)),
495 _ => self.encoded.cmp(&other.encoded),
496 }
497 })
498 }
499}
500
501impl NarInfo {
502 #[must_use]
504 pub fn builder(
505 store_path: StorePath,
506 url: impl Into<String>,
507 nar_hash: NixHash,
508 nar_size: u64,
509 ) -> NarInfoBuilder {
510 NarInfoBuilder::new(store_path, url, nar_hash, nar_size)
511 }
512
513 #[must_use]
515 pub fn builder_in(
516 store_dir: StoreDir,
517 store_path: StorePath,
518 url: impl Into<String>,
519 nar_hash: NixHash,
520 nar_size: u64,
521 ) -> NarInfoBuilder {
522 NarInfoBuilder::new_in(store_dir, store_path, url, nar_hash, nar_size)
523 }
524
525 pub fn parse_in(store_dir: &StoreDir, input: &[u8]) -> Result<Self, ParseError> {
527 if input.len() > MAX_NARINFO_SIZE {
528 return Err(ParseError::TooLarge {
529 size: input.len(),
530 limit: MAX_NARINFO_SIZE,
531 });
532 }
533 let text = std::str::from_utf8(input).map_err(|_| ParseError::InvalidUtf8)?;
534 let mut fields = Vec::new();
535 for (index, line) in text.lines().enumerate() {
536 if line.is_empty() {
537 continue;
538 }
539 let (name, value) = line
540 .split_once(':')
541 .ok_or(ParseError::MalformedLine { line: index + 1 })?;
542 fields.push(ParsedField {
543 name,
544 value: value.trim_start(),
545 line: index + 1,
546 });
547 }
548
549 let store_path_field = required(&fields, "StorePath")?;
550 let url_field = required(&fields, "URL")?;
551 let nar_hash_field = required(&fields, "NarHash")?;
552 let nar_size_field = required(&fields, "NarSize")?;
553 let compression_field = optional(&fields, "Compression")?;
554 let references_field = optional(&fields, "References")?;
555 let deriver_field = optional(&fields, "Deriver")?;
556 let content_address_field = optional(&fields, "CA")?;
557 let file_hash_field = optional(&fields, "FileHash")?;
558 let file_size_field = optional(&fields, "FileSize")?;
559
560 if url_field.value.is_empty() {
561 return Err(ParseError::InvalidField {
562 field: "URL",
563 message: format!("at line {}: must not be empty", url_field.line),
564 });
565 }
566 let url = url_field.value.to_owned();
567
568 let signatures = fields
569 .iter()
570 .filter(|field| field.name == "Sig")
571 .map(|field| parse_signature(field))
572 .collect();
573 let extensions = fields
574 .iter()
575 .filter(|field| !is_known_field(field.name))
576 .map(|field| Field {
577 name: field.name.to_owned(),
578 value: field.value.to_owned(),
579 })
580 .collect();
581
582 let nar_size = parse_size(nar_size_field, "NarSize")?;
583 if nar_size == 0 {
584 return Err(ParseError::InvalidField {
585 field: "NarSize",
586 message: format!("at line {}: must be greater than zero", nar_size_field.line),
587 });
588 }
589
590 let store_path = parse_absolute_path(store_dir, store_path_field, "StorePath")?;
591 let nar_hash = NixHash::parse(nar_hash_field.value)
592 .map_err(|error| invalid_field("NarHash", nar_hash_field.line, error))?;
593 let compression =
594 compression_field.map_or(Compression::Bzip2, |field| Compression::parse(field.value));
595
596 let references = references_field
597 .map(|field| {
598 field
599 .value
600 .split_ascii_whitespace()
601 .map(|value| parse_path(store_dir, value, "References", field.line))
602 .collect()
603 })
604 .transpose()?
605 .unwrap_or_default();
606
607 let deriver = deriver_field
608 .filter(|field| field.value != "unknown-deriver")
609 .map(|field| parse_path(store_dir, field.value, "Deriver", field.line))
610 .transpose()?;
611
612 let content_address = content_address_field
613 .map(|field| {
614 CAHash::parse(field.value).map_err(|error| invalid_field("CA", field.line, error))
615 })
616 .transpose()?;
617 let file_hash = file_hash_field
618 .map(|field| {
619 NixHash::parse(field.value)
620 .map_err(|error| invalid_field("FileHash", field.line, error))
621 })
622 .transpose()?;
623 let file_size = file_size_field
624 .map(|field| parse_size(field, "FileSize"))
625 .transpose()?;
626
627 Ok(Self {
628 store_dir: store_dir.clone(),
629 store_path,
630 url,
631 compression,
632 nar_hash,
633 nar_size,
634 references,
635 deriver,
636 signatures,
637 content_address,
638 file_hash,
639 file_size,
640 extensions,
641 })
642 }
643
644 pub fn write_canonical(&self, writer: &mut impl io::Write) -> Result<(), io::Error> {
646 writeln!(
647 writer,
648 "StorePath: {}",
649 self.store_dir.render_path(&self.store_path)
650 )?;
651 writeln!(writer, "URL: {}", self.url)?;
652 writeln!(writer, "Compression: {}", self.compression)?;
653 if let Some(hash) = &self.file_hash {
654 writeln!(writer, "FileHash: {}", hash.to_nix_nixbase32_string())?;
655 }
656 if let Some(size) = self.file_size {
657 writeln!(writer, "FileSize: {size}")?;
658 }
659 writeln!(
660 writer,
661 "NarHash: {}",
662 self.nar_hash.to_nix_nixbase32_string()
663 )?;
664 writeln!(writer, "NarSize: {}", self.nar_size)?;
665 let references = self
666 .references
667 .iter()
668 .map(StorePath::to_basename)
669 .collect::<Vec<_>>()
670 .join(" ");
671 writeln!(writer, "References: {references}")?;
672 if let Some(deriver) = &self.deriver {
673 writeln!(writer, "Deriver: {}", deriver.to_basename())?;
674 }
675 for signature in &self.signatures {
676 writeln!(writer, "Sig: {}:{}", signature.key_name, signature.encoded)?;
677 }
678 if let Some(content_address) = &self.content_address {
679 writeln!(writer, "CA: {}", content_address.to_nix_string())?;
680 }
681 for field in &self.extensions {
682 writeln!(writer, "{}: {}", field.name, field.value)?;
683 }
684 Ok(())
685 }
686
687 #[must_use]
689 pub fn to_canonical_bytes(&self) -> Vec<u8> {
690 let mut bytes = Vec::new();
691 self.write_canonical(&mut bytes)
692 .expect("writing to a Vec cannot fail");
693 bytes
694 }
695
696 #[must_use]
698 pub fn fingerprint(&self, store_dir: &StoreDir) -> String {
699 let references = self
700 .references
701 .iter()
702 .map(|path| store_dir.render_path(path))
703 .collect::<Vec<_>>()
704 .join(",");
705 format!(
706 "1;{};{};{};{}",
707 store_dir.render_path(&self.store_path),
708 self.nar_hash.to_nix_nixbase32_string(),
709 self.nar_size,
710 references,
711 )
712 }
713
714 #[must_use]
719 pub fn has_valid_signature(&self, store_dir: &StoreDir, keys: &[TrustedPublicKey]) -> bool {
720 let fingerprint = self.fingerprint(store_dir);
721 self.signatures.iter().any(|signature| {
722 signature
723 .verify(fingerprint.as_bytes(), keys)
724 .unwrap_or(false)
725 })
726 }
727
728 #[must_use]
730 pub fn is_content_addressed(&self, store_dir: &StoreDir) -> bool {
731 let Some(content_address) = &self.content_address else {
732 return false;
733 };
734 let self_reference = self.references.contains(&self.store_path);
735 let other_references = self
736 .references
737 .iter()
738 .filter(|path| *path != &self.store_path);
739 store_dir
740 .build_ca_path(
741 self.store_path.name(),
742 content_address,
743 other_references,
744 self_reference,
745 )
746 .is_ok_and(|expected| expected == self.store_path)
747 }
748
749 #[must_use]
751 pub const fn store_path(&self) -> &StorePath {
752 &self.store_path
753 }
754
755 #[must_use]
757 pub const fn store_dir(&self) -> &StoreDir {
758 &self.store_dir
759 }
760
761 #[must_use]
763 pub fn url(&self) -> &str {
764 &self.url
765 }
766
767 #[must_use]
769 pub const fn compression(&self) -> &Compression {
770 &self.compression
771 }
772
773 #[must_use]
775 pub const fn nar_hash(&self) -> &NixHash {
776 &self.nar_hash
777 }
778
779 #[must_use]
781 pub const fn nar_size(&self) -> u64 {
782 self.nar_size
783 }
784
785 #[must_use]
787 pub const fn references(&self) -> &BTreeSet<StorePath> {
788 &self.references
789 }
790
791 #[must_use]
793 pub const fn deriver(&self) -> Option<&StorePath> {
794 self.deriver.as_ref()
795 }
796
797 #[must_use]
799 pub fn signatures(&self) -> &[NarInfoSignature] {
800 &self.signatures
801 }
802
803 #[must_use]
805 pub const fn content_address(&self) -> Option<&CAHash> {
806 self.content_address.as_ref()
807 }
808
809 #[must_use]
811 pub const fn file_hash(&self) -> Option<&NixHash> {
812 self.file_hash.as_ref()
813 }
814
815 #[must_use]
817 pub const fn file_size(&self) -> Option<u64> {
818 self.file_size
819 }
820
821 #[must_use]
823 pub fn extensions(&self) -> &[Field] {
824 &self.extensions
825 }
826}
827
828impl FromStr for NarInfo {
829 type Err = ParseError;
830
831 fn from_str(input: &str) -> Result<Self, Self::Err> {
833 Self::parse_in(&StoreDir::default(), input.as_bytes())
834 }
835}
836
837#[derive(Clone, Copy)]
838struct ParsedField<'a> {
839 name: &'a str,
840 value: &'a str,
841 line: usize,
842}
843
844fn required<'a>(
845 fields: &'a [ParsedField<'a>],
846 name: &'static str,
847) -> Result<ParsedField<'a>, ParseError> {
848 optional(fields, name)?.ok_or(ParseError::MissingField { field: name })
849}
850
851fn optional<'a>(
852 fields: &'a [ParsedField<'a>],
853 name: &'static str,
854) -> Result<Option<ParsedField<'a>>, ParseError> {
855 let mut matching = fields.iter().copied().filter(|field| field.name == name);
856 let first = matching.next();
857 if matching.next().is_some() {
858 return Err(ParseError::DuplicateField {
859 field: name.to_owned(),
860 });
861 }
862 Ok(first)
863}
864
865fn parse_absolute_path(
866 store_dir: &StoreDir,
867 field: ParsedField<'_>,
868 name: &'static str,
869) -> Result<StorePath, ParseError> {
870 if !field.value.starts_with('/') {
871 return Err(ParseError::InvalidField {
872 field: name,
873 message: format!("at line {}: expected an absolute store path", field.line),
874 });
875 }
876 store_dir
877 .parse_path(field.value.as_bytes())
878 .map_err(|error| invalid_field(name, field.line, error))
879}
880
881fn parse_path(
882 store_dir: &StoreDir,
883 value: &str,
884 field: &'static str,
885 line: usize,
886) -> Result<StorePath, ParseError> {
887 let result = if value.starts_with('/') {
888 store_dir.parse_path(value.as_bytes())
889 } else {
890 StorePath::from_basename(value.as_bytes())
891 };
892 result.map_err(|error| invalid_field(field, line, error))
893}
894
895fn parse_size(field: ParsedField<'_>, name: &'static str) -> Result<u64, ParseError> {
896 field
897 .value
898 .parse()
899 .map_err(|error| invalid_field(name, field.line, error))
900}
901
902fn parse_signature(field: &ParsedField<'_>) -> NarInfoSignature {
903 let (key_name, encoded) = field.value.split_once(':').unwrap_or((field.value, ""));
904 NarInfoSignature {
905 key_name: key_name.to_owned(),
906 encoded: encoded.to_owned(),
907 }
908}
909
910fn invalid_field(field: &'static str, line: usize, error: impl fmt::Display) -> ParseError {
911 ParseError::InvalidField {
912 field,
913 message: format!("at line {line}: {error}"),
914 }
915}
916
917fn is_known_field(name: &str) -> bool {
918 matches!(
919 name,
920 "StorePath"
921 | "URL"
922 | "Compression"
923 | "NarHash"
924 | "NarSize"
925 | "References"
926 | "Deriver"
927 | "Sig"
928 | "CA"
929 | "FileHash"
930 | "FileSize"
931 )
932}
933
934fn validate_line_value(field: &str, value: &str) -> Result<(), BuildError> {
935 if value.contains(['\r', '\n']) {
936 Err(BuildError::InvalidField {
937 field: field.to_owned(),
938 message: "must not contain a line break".to_owned(),
939 })
940 } else {
941 Ok(())
942 }
943}
944
945fn validate_canonical_value(field: &str, value: &str) -> Result<(), BuildError> {
946 validate_line_value(field, value)?;
947 if value.chars().next().is_some_and(char::is_whitespace) {
948 Err(BuildError::InvalidField {
949 field: field.to_owned(),
950 message: "must not begin with whitespace".to_owned(),
951 })
952 } else {
953 Ok(())
954 }
955}
956
957#[derive(Debug, Error, Eq, PartialEq)]
959#[non_exhaustive]
960pub enum BuildError {
961 #[error("NarSize must be greater than zero")]
963 ZeroNarSize,
964 #[error("invalid {field}: {message}")]
966 InvalidField {
967 field: String,
969 message: String,
971 },
972}
973
974#[derive(Debug, Error, Eq, PartialEq)]
976#[non_exhaustive]
977pub enum ParseError {
978 #[error("narinfo is {size} bytes, exceeding the {limit}-byte limit")]
980 TooLarge {
981 size: usize,
983 limit: usize,
985 },
986 #[error("narinfo is not UTF-8")]
988 InvalidUtf8,
989 #[error("invalid narinfo line {line}: expected NAME: VALUE")]
991 MalformedLine {
992 line: usize,
994 },
995 #[error("narinfo is missing {field}")]
997 MissingField {
998 field: &'static str,
1000 },
1001 #[error("narinfo contains duplicate {field}")]
1003 DuplicateField {
1004 field: String,
1006 },
1007 #[error("invalid {field}: {message}")]
1009 InvalidField {
1010 field: &'static str,
1012 message: String,
1014 },
1015}
1016
1017#[derive(Debug, Error, Eq, PartialEq)]
1019#[non_exhaustive]
1020pub enum KeyError {
1021 #[error("public key has no name separator")]
1023 MissingName,
1024 #[error("public key has an empty name")]
1026 EmptyName,
1027 #[error("public key is not valid base64")]
1029 InvalidBase64,
1030 #[error("public key is {got} bytes, expected 32")]
1032 InvalidLength {
1033 got: usize,
1035 },
1036 #[error("invalid Ed25519 public key")]
1038 InvalidKey,
1039}
1040
1041#[derive(Debug, Error, Eq, PartialEq)]
1043#[non_exhaustive]
1044pub enum SignatureError {
1045 #[error("signature has no name separator")]
1047 MissingSeparator,
1048 #[error("signature has an empty key name")]
1050 EmptyKeyName,
1051 #[error("signature is not valid base64")]
1053 InvalidBase64,
1054 #[error("signature is empty")]
1056 EmptySignature,
1057 #[error("signature key name contains ':'")]
1059 InvalidKeyName,
1060 #[error("signature is {got} bytes, expected 64")]
1062 InvalidLength {
1063 got: usize,
1065 },
1066}