-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathwallet_import.rs
More file actions
828 lines (745 loc) · 29.2 KB
/
Copy pathwallet_import.rs
File metadata and controls
828 lines (745 loc) · 29.2 KB
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! Pure parsers for wallet import and backup payloads.
//!
//! `starforge wallet import --file` and `starforge backup restore` both accept
//! files that arrive from outside the tool: an exported wallet backup, possibly
//! wrapped in an encrypted bundle. That makes them a trust boundary, so the
//! parsing lives here — separated from prompting, disk access, and the config
//! store — where it can be unit-tested, property-tested, and fuzzed.
//!
//! The harnesses under `fuzz/fuzz_targets/` drive these functions directly:
//!
//! ```text
//! cargo fuzz run fuzz_wallet_backup_parse
//! cargo fuzz run fuzz_wallet_import_envelope
//! ```
//!
//! ## Guarantees
//!
//! Every function here is total: for **any** input — malformed JSON, truncated
//! ciphertext, invalid StrKeys, multi-megabyte blobs, or hostile Unicode — it
//! returns a [`WalletImportError`] rather than panicking, and never allocates
//! proportionally to an attacker-chosen length before the size check runs.
//!
//! ## Security
//!
//! - Size limits are enforced *before* parsing, so an oversized file cannot
//! drive the JSON parser into a large allocation.
//! - Error messages never echo secret key material; only the wallet name and
//! the failure reason are reported.
//! - Wallet names containing bidirectional or zero-width control characters are
//! rejected: they can make one wallet's name render identically to another's.
//! Non-ASCII names are accepted but reported as a warning for the same
//! reason — rejecting them outright would break backups made by earlier
//! releases, which allow any Unicode alphanumeric.
use serde::{Deserialize, Serialize};
use crate::utils::config;
/// Backup schema version this build writes and accepts.
pub const WALLET_BACKUP_VERSION: &str = "1";
/// Largest backup document accepted, in bytes.
pub const MAX_BACKUP_BYTES: usize = 4 * 1024 * 1024;
/// Largest number of wallets accepted in one backup.
pub const MAX_WALLETS_PER_BACKUP: usize = 1_000;
/// Longest wallet name accepted from a backup file.
pub const MAX_WALLET_NAME_LEN: usize = 64;
/// Largest encrypted bundle accepted, in bytes.
pub const MAX_ENVELOPE_BYTES: usize = MAX_BACKUP_BYTES * 2;
/// Salt length written by [`crate::utils::crypto::encrypt_secret`].
pub const SALT_LEN: usize = 16;
/// AES-GCM nonce length.
pub const NONCE_LEN: usize = 12;
/// AES-GCM authentication tag length: a ciphertext shorter than this cannot
/// even carry a tag and is therefore truncated.
pub const GCM_TAG_LEN: usize = 16;
// ─────────────────────────────────────────────────────────────────────────────
// Errors
// ─────────────────────────────────────────────────────────────────────────────
/// Why an import payload was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WalletImportError {
/// Input exceeded a size limit.
TooLarge { bytes: usize, limit: usize },
/// Input was empty or whitespace only.
Empty,
/// The document was not valid JSON.
MalformedJson(String),
/// The backup declares a version this build cannot read.
UnsupportedVersion { found: String, expected: String },
/// The backup contained no wallets.
NoWallets,
/// The backup contained more wallets than [`MAX_WALLETS_PER_BACKUP`].
TooManyWallets { count: usize, limit: usize },
/// Two entries share a name.
DuplicateWallet(String),
/// A wallet entry failed validation.
InvalidEntry { wallet: String, reason: String },
/// A wallet name carried invisible or direction-changing characters.
DeceptiveWalletName { wallet: String, reason: String },
/// The encrypted bundle did not have 3, 5, or 6 colon-separated parts.
MalformedEnvelope { parts: usize },
/// A base64 field of the bundle did not decode.
InvalidBase64 { field: &'static str },
/// A bundle field had the wrong decoded length.
InvalidFieldLength {
field: &'static str,
len: usize,
expected: usize,
},
/// The ciphertext is too short to carry an authentication tag.
TruncatedCiphertext { len: usize, minimum: usize },
/// A KDF parameter was absent, non-numeric, or zero.
InvalidKdfParameter { field: &'static str, reason: String },
}
impl std::fmt::Display for WalletImportError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TooLarge { bytes, limit } => write!(
f,
"input is {} bytes, above the {} byte limit for an import payload",
bytes, limit
),
Self::Empty => write!(f, "input is empty"),
Self::MalformedJson(msg) => write!(f, "invalid backup JSON: {}", msg),
Self::UnsupportedVersion { found, expected } => write!(
f,
"unsupported backup version '{}'; this build reads version '{}'",
found, expected
),
Self::NoWallets => write!(f, "backup contains no wallets"),
Self::TooManyWallets { count, limit } => write!(
f,
"backup contains {} wallets, above the limit of {}",
count, limit
),
Self::DuplicateWallet(name) => {
write!(f, "duplicate wallet '{}' in backup file", name)
}
Self::InvalidEntry { wallet, reason } => {
write!(f, "wallet '{}' is invalid: {}", wallet, reason)
}
Self::DeceptiveWalletName { wallet, reason } => write!(
f,
"wallet name {:?} is rejected: {}",
wallet.escape_debug().to_string(),
reason
),
Self::MalformedEnvelope { parts } => write!(
f,
"encrypted bundle has {} colon-separated parts; expected 3, 5, or 6",
parts
),
Self::InvalidBase64 { field } => {
write!(f, "encrypted bundle field `{}` is not valid base64", field)
}
Self::InvalidFieldLength {
field,
len,
expected,
} => write!(
f,
"encrypted bundle field `{}` decoded to {} bytes; expected {}",
field, len, expected
),
Self::TruncatedCiphertext { len, minimum } => write!(
f,
"ciphertext is {} bytes; at least {} are needed for the authentication tag",
len, minimum
),
Self::InvalidKdfParameter { field, reason } => {
write!(f, "KDF parameter `{}` is invalid: {}", field, reason)
}
}
}
}
impl std::error::Error for WalletImportError {}
type Result<T> = std::result::Result<T, WalletImportError>;
// ─────────────────────────────────────────────────────────────────────────────
// Backup documents
// ─────────────────────────────────────────────────────────────────────────────
/// A wallet backup document, as written by `starforge wallet export`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WalletBackup {
pub version: String,
pub exported_at: String,
pub wallets: Vec<WalletBackupEntry>,
}
/// One wallet inside a backup document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WalletBackupEntry {
pub name: String,
pub public_key: String,
pub secret_key: Option<String>,
pub network: String,
pub created_at: String,
pub funded: bool,
}
/// A parsed backup plus any non-fatal observations about it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedBackup {
pub backup: WalletBackup,
/// Notes worth showing the user, e.g. a wallet name that could be
/// confused with another one.
pub warnings: Vec<String>,
}
/// Whether an import payload is an encrypted bundle or a plaintext document.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PayloadKind {
/// `salt:nonce:ciphertext[:mem:iters[:parallelism]]`
Encrypted,
/// A bare JSON document.
Plaintext,
}
/// Classify an import payload.
///
/// Earlier releases detected encryption with `raw.matches(':').count() == 2`,
/// which misclassified the 5- and 6-part bundles written when custom Argon2
/// parameters are configured — those were handed to the JSON parser and failed
/// with a confusing "Invalid backup JSON format". Classification now mirrors
/// the bundle grammar, and a JSON document (which always starts with `{` or
/// `[`) is never treated as a bundle regardless of how many colons it holds.
pub fn classify_payload(raw: &str) -> PayloadKind {
let trimmed = raw.trim();
if trimmed.starts_with('{') || trimmed.starts_with('[') {
return PayloadKind::Plaintext;
}
let parts: Vec<&str> = trimmed.split(':').collect();
if matches!(parts.len(), 3 | 5 | 6)
&& parts
.iter()
.take(3)
.all(|part| !part.is_empty() && part.bytes().all(is_base64_byte))
{
return PayloadKind::Encrypted;
}
PayloadKind::Plaintext
}
fn is_base64_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'='
}
// ─────────────────────────────────────────────────────────────────────────────
// Encrypted envelope
// ─────────────────────────────────────────────────────────────────────────────
/// A structurally valid encrypted bundle.
///
/// Structural validity says nothing about whether the passphrase is correct —
/// that is decided by AES-GCM during decryption. The point of parsing first is
/// to reject garbage before spending an Argon2 key derivation on it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedEnvelope {
pub salt: Vec<u8>,
pub nonce: Vec<u8>,
pub ciphertext: Vec<u8>,
pub mem_cost: Option<u32>,
pub iterations: Option<u32>,
pub parallelism: Option<u32>,
}
/// Parse and structurally validate an encrypted bundle.
pub fn parse_encrypted_envelope(raw: &str) -> Result<EncryptedEnvelope> {
if raw.len() > MAX_ENVELOPE_BYTES {
return Err(WalletImportError::TooLarge {
bytes: raw.len(),
limit: MAX_ENVELOPE_BYTES,
});
}
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(WalletImportError::Empty);
}
let parts: Vec<&str> = trimmed.split(':').collect();
if !matches!(parts.len(), 3 | 5 | 6) {
return Err(WalletImportError::MalformedEnvelope { parts: parts.len() });
}
let salt = decode_field(parts[0], "salt")?;
let nonce = decode_field(parts[1], "nonce")?;
let ciphertext = decode_field(parts[2], "ciphertext")?;
if salt.len() != SALT_LEN {
return Err(WalletImportError::InvalidFieldLength {
field: "salt",
len: salt.len(),
expected: SALT_LEN,
});
}
if nonce.len() != NONCE_LEN {
return Err(WalletImportError::InvalidFieldLength {
field: "nonce",
len: nonce.len(),
expected: NONCE_LEN,
});
}
if ciphertext.len() < GCM_TAG_LEN {
return Err(WalletImportError::TruncatedCiphertext {
len: ciphertext.len(),
minimum: GCM_TAG_LEN,
});
}
let (mem_cost, iterations) = if parts.len() >= 5 {
(
Some(parse_kdf_param(parts[3], "mem")?),
Some(parse_kdf_param(parts[4], "iterations")?),
)
} else {
(None, None)
};
let parallelism = if parts.len() == 6 {
Some(parse_kdf_param(parts[5], "parallelism")?)
} else {
None
};
Ok(EncryptedEnvelope {
salt,
nonce,
ciphertext,
mem_cost,
iterations,
parallelism,
})
}
fn decode_field(value: &str, field: &'static str) -> Result<Vec<u8>> {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
BASE64
.decode(value)
.map_err(|_| WalletImportError::InvalidBase64 { field })
}
fn parse_kdf_param(value: &str, field: &'static str) -> Result<u32> {
let parsed = value
.parse::<u32>()
.map_err(|_| WalletImportError::InvalidKdfParameter {
field,
reason: "must be a decimal u32".to_string(),
})?;
if parsed == 0 {
return Err(WalletImportError::InvalidKdfParameter {
field,
reason: "must be greater than zero".to_string(),
});
}
Ok(parsed)
}
// ─────────────────────────────────────────────────────────────────────────────
// Backup parsing
// ─────────────────────────────────────────────────────────────────────────────
/// Parse and validate a plaintext wallet backup document.
pub fn parse_wallet_backup(contents: &str) -> Result<ParsedBackup> {
if contents.len() > MAX_BACKUP_BYTES {
return Err(WalletImportError::TooLarge {
bytes: contents.len(),
limit: MAX_BACKUP_BYTES,
});
}
if contents.trim().is_empty() {
return Err(WalletImportError::Empty);
}
let backup: WalletBackup = serde_json::from_str(contents)
.map_err(|e| WalletImportError::MalformedJson(e.to_string()))?;
if backup.version != WALLET_BACKUP_VERSION {
return Err(WalletImportError::UnsupportedVersion {
found: backup.version.clone(),
expected: WALLET_BACKUP_VERSION.to_string(),
});
}
if backup.wallets.is_empty() {
return Err(WalletImportError::NoWallets);
}
if backup.wallets.len() > MAX_WALLETS_PER_BACKUP {
return Err(WalletImportError::TooManyWallets {
count: backup.wallets.len(),
limit: MAX_WALLETS_PER_BACKUP,
});
}
let mut warnings = Vec::new();
let mut seen = std::collections::HashSet::new();
for entry in &backup.wallets {
check_wallet_name(&entry.name)?;
if !seen.insert(entry.name.as_str()) {
return Err(WalletImportError::DuplicateWallet(entry.name.clone()));
}
if !entry.name.is_ascii() {
warnings.push(format!(
"wallet '{}' has a non-ASCII name, which can render identically to another name",
entry.name
));
}
validate_entry(entry)?;
}
Ok(ParsedBackup { backup, warnings })
}
/// Reject wallet names that are invisible, direction-changing, or overlong.
///
/// Length is checked in `char`s: a name of 64 astral characters is 256 bytes,
/// and the limit is about what a human can read, not about storage.
fn check_wallet_name(name: &str) -> Result<()> {
if name.is_empty() {
return Err(WalletImportError::DeceptiveWalletName {
wallet: name.to_string(),
reason: "name is empty".to_string(),
});
}
if name.chars().count() > MAX_WALLET_NAME_LEN {
return Err(WalletImportError::DeceptiveWalletName {
wallet: name.chars().take(16).collect(),
reason: format!(
"name is {} characters; at most {} are allowed",
name.chars().count(),
MAX_WALLET_NAME_LEN
),
});
}
if let Some(bad) = name.chars().find(|c| is_deceptive_char(*c)) {
return Err(WalletImportError::DeceptiveWalletName {
wallet: name.to_string(),
reason: format!(
"contains U+{:04X}, an invisible or direction-changing character",
bad as u32
),
});
}
Ok(())
}
/// Characters that are invisible or that reorder the rendering of a name.
fn is_deceptive_char(c: char) -> bool {
c.is_control()
|| matches!(c,
'\u{200B}'..='\u{200F}' // zero width space … RTL mark
| '\u{202A}'..='\u{202E}' // bidi embedding / override
| '\u{2066}'..='\u{2069}' // bidi isolates
| '\u{FEFF}' // zero width no-break space
| '\u{00AD}' // soft hyphen
)
}
/// Validate a single backup entry against the wallet rules.
///
/// Errors quote the wallet name and the reason, never the key material.
pub fn validate_entry(entry: &WalletBackupEntry) -> Result<()> {
config::validate_wallet_name(&entry.name).map_err(|e| WalletImportError::InvalidEntry {
wallet: entry.name.clone(),
reason: e.to_string(),
})?;
config::validate_public_key(&entry.public_key).map_err(|e| {
WalletImportError::InvalidEntry {
wallet: entry.name.clone(),
reason: e.to_string(),
}
})?;
if let Some(secret) = &entry.secret_key {
config::validate_secret_key(secret).map_err(|e| WalletImportError::InvalidEntry {
wallet: entry.name.clone(),
reason: e.to_string(),
})?;
}
if entry.network.trim().is_empty() {
return Err(WalletImportError::InvalidEntry {
wallet: entry.name.clone(),
reason: "network is empty".to_string(),
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn valid_public_key() -> String {
format!("G{}", "A".repeat(55))
}
fn valid_secret_key() -> String {
format!("S{}", "B".repeat(55))
}
fn backup_json(wallets: &str) -> String {
format!(
r#"{{"version":"1","exported_at":"2026-07-29T00:00:00Z","wallets":[{}]}}"#,
wallets
)
}
fn wallet_json(name: &str) -> String {
format!(
r#"{{"name":"{}","public_key":"{}","secret_key":"{}","network":"testnet","created_at":"2026-07-29T00:00:00Z","funded":true}}"#,
name,
valid_public_key(),
valid_secret_key()
)
}
fn envelope(salt: usize, nonce: usize, ct: usize) -> String {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
format!(
"{}:{}:{}",
BASE64.encode(vec![1u8; salt]),
BASE64.encode(vec![2u8; nonce]),
BASE64.encode(vec![3u8; ct])
)
}
// ── Primary flow ────────────────────────────────────────────────────────
#[test]
fn parses_a_well_formed_backup() {
let parsed = parse_wallet_backup(&backup_json(&wallet_json("alice"))).unwrap();
assert_eq!(parsed.backup.version, "1");
assert_eq!(parsed.backup.wallets.len(), 1);
assert_eq!(parsed.backup.wallets[0].name, "alice");
assert!(parsed.warnings.is_empty());
}
#[test]
fn parses_a_well_formed_envelope() {
let env = parse_encrypted_envelope(&envelope(SALT_LEN, NONCE_LEN, 64)).unwrap();
assert_eq!(env.salt.len(), SALT_LEN);
assert_eq!(env.nonce.len(), NONCE_LEN);
assert_eq!(env.ciphertext.len(), 64);
assert_eq!(env.mem_cost, None);
}
#[test]
fn parses_a_six_part_envelope_with_kdf_parameters() {
let raw = format!("{}:65536:3:4", envelope(SALT_LEN, NONCE_LEN, 32));
let env = parse_encrypted_envelope(&raw).unwrap();
assert_eq!(env.mem_cost, Some(65_536));
assert_eq!(env.iterations, Some(3));
assert_eq!(env.parallelism, Some(4));
}
#[test]
fn classifies_bundles_and_documents() {
assert_eq!(
classify_payload(&envelope(SALT_LEN, NONCE_LEN, 32)),
PayloadKind::Encrypted
);
// 5- and 6-part bundles were misclassified as plaintext before #697.
assert_eq!(
classify_payload(&format!("{}:65536:3", envelope(SALT_LEN, NONCE_LEN, 32))),
PayloadKind::Encrypted
);
assert_eq!(
classify_payload(&format!("{}:65536:3:4", envelope(SALT_LEN, NONCE_LEN, 32))),
PayloadKind::Encrypted
);
assert_eq!(
classify_payload(&backup_json(&wallet_json("alice"))),
PayloadKind::Plaintext
);
// A JSON document with colons in its values is still a document.
assert_eq!(classify_payload(r#"{"a":"b:c:d"}"#), PayloadKind::Plaintext);
}
// ── Boundary cases ──────────────────────────────────────────────────────
#[test]
fn ciphertext_of_exactly_one_tag_is_accepted_and_one_byte_less_is_not() {
assert!(parse_encrypted_envelope(&envelope(SALT_LEN, NONCE_LEN, GCM_TAG_LEN)).is_ok());
assert_eq!(
parse_encrypted_envelope(&envelope(SALT_LEN, NONCE_LEN, GCM_TAG_LEN - 1)).unwrap_err(),
WalletImportError::TruncatedCiphertext {
len: GCM_TAG_LEN - 1,
minimum: GCM_TAG_LEN,
}
);
}
#[test]
fn a_backup_at_the_wallet_limit_is_accepted_and_one_over_is_not() {
let at_limit = (0..MAX_WALLETS_PER_BACKUP)
.map(|i| wallet_json(&format!("w{}", i)))
.collect::<Vec<_>>()
.join(",");
assert!(parse_wallet_backup(&backup_json(&at_limit)).is_ok());
let over = (0..=MAX_WALLETS_PER_BACKUP)
.map(|i| wallet_json(&format!("w{}", i)))
.collect::<Vec<_>>()
.join(",");
assert!(matches!(
parse_wallet_backup(&backup_json(&over)).unwrap_err(),
WalletImportError::TooManyWallets { .. }
));
}
#[test]
fn a_name_at_the_length_limit_is_accepted_and_one_over_is_not() {
let at_limit = "a".repeat(MAX_WALLET_NAME_LEN);
assert!(parse_wallet_backup(&backup_json(&wallet_json(&at_limit))).is_ok());
let over = "a".repeat(MAX_WALLET_NAME_LEN + 1);
assert!(matches!(
parse_wallet_backup(&backup_json(&wallet_json(&over))).unwrap_err(),
WalletImportError::DeceptiveWalletName { .. }
));
}
#[test]
fn an_oversized_document_is_rejected_before_parsing() {
let big = "x".repeat(MAX_BACKUP_BYTES + 1);
assert_eq!(
parse_wallet_backup(&big).unwrap_err(),
WalletImportError::TooLarge {
bytes: MAX_BACKUP_BYTES + 1,
limit: MAX_BACKUP_BYTES,
}
);
}
// ── Failure cases ───────────────────────────────────────────────────────
#[test]
fn malformed_json_is_rejected() {
for bad in [
"{",
"{\"version\":}",
"[]",
"null",
"\"just a string\"",
"{\"version\":\"1\"}",
] {
assert!(
matches!(
parse_wallet_backup(bad),
Err(WalletImportError::MalformedJson(_))
),
"accepted malformed JSON {:?}",
bad
);
}
}
#[test]
fn empty_input_is_rejected() {
assert_eq!(
parse_wallet_backup(" ").unwrap_err(),
WalletImportError::Empty
);
assert_eq!(
parse_encrypted_envelope(" ").unwrap_err(),
WalletImportError::Empty
);
}
#[test]
fn an_unsupported_version_is_rejected() {
let doc =
backup_json(&wallet_json("alice")).replace("\"version\":\"1\"", "\"version\":\"9\"");
assert_eq!(
parse_wallet_backup(&doc).unwrap_err(),
WalletImportError::UnsupportedVersion {
found: "9".to_string(),
expected: "1".to_string(),
}
);
}
#[test]
fn an_empty_wallet_list_is_rejected() {
assert_eq!(
parse_wallet_backup(&backup_json("")).unwrap_err(),
WalletImportError::NoWallets
);
}
#[test]
fn duplicate_wallet_names_are_rejected() {
let doc = backup_json(&format!(
"{},{}",
wallet_json("alice"),
wallet_json("alice")
));
assert_eq!(
parse_wallet_backup(&doc).unwrap_err(),
WalletImportError::DuplicateWallet("alice".to_string())
);
}
#[test]
fn invalid_strkeys_are_rejected() {
let doc = backup_json(&wallet_json("alice").replace(&valid_public_key(), "GNOTAKEY"));
assert!(matches!(
parse_wallet_backup(&doc).unwrap_err(),
WalletImportError::InvalidEntry { .. }
));
let doc = backup_json(&wallet_json("alice").replace(&valid_secret_key(), "S123"));
assert!(matches!(
parse_wallet_backup(&doc).unwrap_err(),
WalletImportError::InvalidEntry { .. }
));
}
#[test]
fn an_error_never_echoes_the_secret_key() {
let secret = valid_secret_key();
let doc = backup_json(&wallet_json("alice").replace(&valid_public_key(), "GBAD"));
let err = parse_wallet_backup(&doc).unwrap_err().to_string();
assert!(
!err.contains(&secret),
"secret key leaked into the error: {}",
err
);
}
#[test]
fn bidi_and_zero_width_names_are_rejected() {
for name in [
"al\u{202E}ice", // right-to-left override
"al\u{200B}ice", // zero width space
"al\u{FEFF}ice", // BOM
"al\u{00AD}ice", // soft hyphen
"al\u{2066}ice", // bidi isolate
] {
let doc = backup_json(&wallet_json(name));
assert!(
matches!(
parse_wallet_backup(&doc),
Err(WalletImportError::DeceptiveWalletName { .. })
),
"accepted deceptive name {:?}",
name
);
}
}
#[test]
fn a_non_ascii_name_is_accepted_but_warned_about() {
// Cyrillic 'а' renders like Latin 'a'.
let doc = backup_json(&wallet_json("\u{0430}lice"));
let parsed = parse_wallet_backup(&doc).unwrap();
assert_eq!(parsed.warnings.len(), 1);
assert!(parsed.warnings[0].contains("non-ASCII"));
}
#[test]
fn truncated_and_corrupt_envelopes_are_rejected() {
// Wrong number of parts.
assert!(matches!(
parse_encrypted_envelope("onlyonepart"),
Err(WalletImportError::MalformedEnvelope { parts: 1 })
));
assert!(matches!(
parse_encrypted_envelope("a:b:c:d"),
Err(WalletImportError::MalformedEnvelope { parts: 4 })
));
// Not base64.
assert_eq!(
parse_encrypted_envelope("!!!:@@@:###").unwrap_err(),
WalletImportError::InvalidBase64 { field: "salt" }
);
// Wrong salt / nonce length.
assert!(matches!(
parse_encrypted_envelope(&envelope(8, NONCE_LEN, 32)),
Err(WalletImportError::InvalidFieldLength { field: "salt", .. })
));
assert!(matches!(
parse_encrypted_envelope(&envelope(SALT_LEN, 4, 32)),
Err(WalletImportError::InvalidFieldLength { field: "nonce", .. })
));
}
#[test]
fn invalid_kdf_parameters_are_rejected() {
let base = envelope(SALT_LEN, NONCE_LEN, 32);
assert!(matches!(
parse_encrypted_envelope(&format!("{}:notanumber:3", base)),
Err(WalletImportError::InvalidKdfParameter { field: "mem", .. })
));
assert!(matches!(
parse_encrypted_envelope(&format!("{}:65536:0", base)),
Err(WalletImportError::InvalidKdfParameter {
field: "iterations",
..
})
));
assert!(matches!(
parse_encrypted_envelope(&format!("{}:65536:3:99999999999", base)),
Err(WalletImportError::InvalidKdfParameter {
field: "parallelism",
..
})
));
}
#[test]
fn parsers_are_total_over_hostile_input() {
// Everything here must return an error, never panic.
let inputs = [
String::new(),
"\u{0}\u{1}\u{2}".to_string(),
"\u{FFFD}".repeat(100),
":".repeat(1000),
"{".repeat(5000),
"\u{1F600}".repeat(500),
format!("{}\u{0}", envelope(SALT_LEN, NONCE_LEN, 32)),
];
for input in &inputs {
let _ = parse_wallet_backup(input);
let _ = parse_encrypted_envelope(input);
let _ = classify_payload(input);
}
}
}