hakanai 2.20.1

CLI client for Hakanai, a secure secret sharing service.
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
// SPDX-License-Identifier: Apache-2.0

use std::env::current_dir;
use std::fs::OpenOptions;
use std::io;
use std::io::{Cursor, Read, Write};
use std::path::{Path, PathBuf};

use anyhow::{Result, anyhow};
use colored::Colorize;
use zeroize::Zeroizing;
use zip::ZipArchive;

use hakanai_lib::client::Client;
use hakanai_lib::models::Payload;
use hakanai_lib::options::SecretReceiveOptions;
use hakanai_lib::utils::timestamp;

use crate::args::GetArgs;
use crate::factory::Factory;
use crate::helper;

pub async fn get<T: Factory>(factory: T, args: GetArgs) -> Result<()> {
    args.validate()?;

    let user_agent = helper::get_user_agent_name();
    let observer = factory.new_observer("Receiving secret...")?;
    let mut opts = SecretReceiveOptions::default()
        .with_user_agent(user_agent)
        .with_observer(observer);

    if let Some(ref passphrase) = args.passphrase {
        let bytes = Zeroizing::new(passphrase.bytes().collect::<Vec<u8>>());
        opts = opts.with_passphrase(bytes.as_ref());
    }

    if args.ask_passphrase {
        let passphrase = rpassword::prompt_password("Passphrase: ")?;
        let bytes = Zeroizing::new(passphrase.bytes().collect::<Vec<u8>>());
        opts = opts.with_passphrase(bytes.as_ref());
    }

    let url = args.secret_url()?.clone();
    let payload = factory.new_client().receive_secret(url, Some(opts)).await?;

    output_secret(payload, args.clone())?;

    Ok(())
}

fn output_secret(payload: Payload, args: GetArgs) -> Result<()> {
    let bytes = Zeroizing::new(payload.decode_bytes()?);
    let filename = args.filename.or_else(|| payload.filename.clone());
    let output_directory = match args.output_dir {
        Some(dir) => dir,
        None => current_dir()?,
    };

    if args.to_stdout {
        print_to_stdout(&bytes)?;
    } else if let Some(name) = payload.filename.clone()
        && args.extract
        && is_archive(&name)
    {
        extract_archive(name, &bytes, &output_directory)?;
    } else if let Some(file) = filename {
        write_to_file(
            file,
            Cursor::<&[u8]>::new(bytes.as_ref()),
            &output_directory,
        )?;
    } else {
        print_to_stdout(&bytes)?;
    }

    Ok(())
}

fn is_archive(filename: &str) -> bool {
    filename.to_lowercase().ends_with(".zip")
}

fn print_to_stdout(bytes: &[u8]) -> Result<()> {
    std::io::stdout().write_all(bytes)?;
    Ok(())
}

fn extract_archive(filename: String, bytes: &[u8], target_dir: &Path) -> Result<()> {
    let mut archive = ZipArchive::new(Cursor::new(bytes))?;

    println!("Extracting archive: {}", filename.cyan());
    for i in 0..archive.len() {
        let file = archive.by_index(i)?;
        if file.is_dir() {
            continue; // skip directories
        }

        let name = file.name().to_string();

        // extract flat, just use the filename
        let flat_name = PathBuf::from(&name)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&name)
            .to_string();
        write_to_file(flat_name, file, target_dir)?;
    }

    Ok(())
}

fn write_to_file<T: Read>(filename: String, mut r: T, target_dir: &Path) -> Result<()> {
    if filename.is_empty() {
        return Err(anyhow!("Filename cannot be empty"));
    }

    let path = PathBuf::from(&target_dir).join(filename.clone());
    let file_res = OpenOptions::new()
        .write(true)
        .create_new(true) // fail if file exists
        .open(&path);

    match file_res {
        Ok(mut f) => io::copy(&mut r, &mut f)?,
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            return write_to_timestamped_file(filename, r, target_dir);
        }
        Err(e) => return Err(e)?,
    };

    let success_message = format!("Saved to: {}", filename.cyan());
    println!("{success_message}");

    Ok(())
}

fn write_to_timestamped_file<T: Read>(filename: String, r: T, target_dir: &Path) -> Result<()> {
    let timestamp = timestamp::now_string()?;
    let filename_with_timestamp = format!("{filename}.{timestamp}");

    let warn_message = format!(
        "File {filename} already exists. To prevent overriding we use {filename_with_timestamp} instead."
    );
    eprintln!("{}", warn_message.yellow());

    write_to_file(filename_with_timestamp, r, target_dir)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    use anyhow::Result;
    use tempfile::TempDir;

    use hakanai_lib::client_mock::MockClient;
    use hakanai_lib::models::Payload;

    use crate::factory_mock::test_utils::MockFactory;

    #[tokio::test]
    async fn test_get_successful_to_stdout() -> Result<()> {
        let payload = Payload::from_bytes(b"secret text content");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key").with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_successful_to_file_with_payload_filename() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let payload = Payload::from_bytes(b"file content").with_filename("document.txt");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        // Use temp directory path to avoid writing to current directory
        let filename = temp_dir
            .path()
            .join("document.txt")
            .to_string_lossy()
            .to_string();
        let args = GetArgs::builder("https://example.com/s/test123#key").with_filename(&filename);
        get(factory, args).await?;

        // Check that file was created with payload filename
        let file_path = temp_dir.path().join("document.txt");
        let content = fs::read(&file_path)?;
        assert_eq!(content, b"file content");
        Ok(())
    }

    #[tokio::test]
    async fn test_get_successful_to_file_with_custom_filename() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let payload = Payload::from_bytes(b"binary content").with_filename("original.bin");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let custom_filename = temp_dir
            .path()
            .join("custom.bin")
            .to_string_lossy()
            .to_string();
        let args =
            GetArgs::builder("https://example.com/s/test123#key").with_filename(&custom_filename);
        get(factory, args).await?;

        // Check that file was created with custom filename
        let file_path = temp_dir.path().join("custom.bin");
        let content = fs::read(&file_path)?;
        assert_eq!(content, b"binary content");
        Ok(())
    }

    #[tokio::test]
    async fn test_get_successful_binary_content() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let binary_data = vec![0x00, 0x01, 0xFF, 0xFE, 0x42, 0x43];
        let payload = Payload::from_bytes(&binary_data).with_filename("binary.dat");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let filename = temp_dir
            .path()
            .join("output.dat")
            .to_string_lossy()
            .to_string();
        let args = GetArgs::builder("https://example.com/s/test123#key").with_filename(&filename);
        get(factory, args).await?;

        let file_path = temp_dir.path().join("output.dat");
        let content = fs::read(&file_path)?;
        assert_eq!(content, binary_data);
        Ok(())
    }

    #[tokio::test]
    async fn test_get_client_error() -> Result<()> {
        let client = MockClient::new().with_receive_failure("Network timeout".to_string());
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key").with_to_stdout();
        let result = get(factory, args).await;

        assert!(result.is_err(), "Expected network error, got: {:?}", result);
        assert!(result.unwrap_err().to_string().contains("Network timeout"));
        Ok(())
    }

    #[tokio::test]
    async fn test_get_empty_payload() -> Result<()> {
        let payload = Payload::from_bytes(b"");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key").with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_file_overwrite_prevention() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let file_path = temp_dir.path().join("existing.txt");

        // Create existing file
        fs::write(&file_path, "existing content")?;

        let payload = Payload::from_bytes(b"new content");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_filename(file_path.to_string_lossy().as_ref());
        get(factory, args).await?;

        // Original file should be unchanged
        let original_content = fs::read_to_string(&file_path)?;
        assert_eq!(original_content, "existing content");

        // New timestamped file should exist
        let files: Vec<_> = fs::read_dir(temp_dir.path())?
            .filter_map(|entry| entry.ok())
            .filter(|entry| {
                entry
                    .file_name()
                    .to_string_lossy()
                    .starts_with("existing.txt.")
            })
            .collect();

        assert_eq!(files.len(), 1);
        let timestamped_content = fs::read_to_string(files[0].path())?;
        assert_eq!(timestamped_content, "new content");
        Ok(())
    }

    // Tests for archive extraction
    #[test]
    fn test_is_archive() {
        assert!(is_archive("test.zip"));
        assert!(is_archive("archive.ZIP"));
        assert!(is_archive("my-files.zip"));
        assert!(!is_archive("test.tar"));
        assert!(!is_archive("test.gz"));
        assert!(!is_archive("test.txt"));
        assert!(!is_archive("test"));
    }

    #[test]
    fn test_extract_archive_with_multiple_files() -> Result<()> {
        use std::io::Write;
        use zip::ZipWriter;
        use zip::write::FileOptions;

        let temp_dir = TempDir::new()?;

        // Create a ZIP archive in memory
        let mut zip_data = Vec::new();
        {
            let mut zip = ZipWriter::new(std::io::Cursor::new(&mut zip_data));

            // Add files to the archive
            let options = FileOptions::<()>::default();
            zip.start_file("file1.txt", options)?;
            zip.write_all(b"Content of file 1")?;

            zip.start_file("file2.txt", options)?;
            zip.write_all(b"Content of file 2")?;

            zip.add_directory("subdir/", options)?;

            zip.start_file("subdir/file3.txt", options)?;
            zip.write_all(b"Content of file 3 in subdir")?;

            zip.finish()?;
        }

        // Extract to the temp directory
        extract_archive("test.zip".to_string(), &zip_data, temp_dir.path())?;

        // Verify extracted files - all files are extracted flat (no subdirectories)
        assert!(temp_dir.path().join("file1.txt").exists());
        assert!(temp_dir.path().join("file2.txt").exists());
        // subdir/file3.txt is extracted as just file3.txt
        assert!(temp_dir.path().join("file3.txt").exists());

        let content1 = fs::read_to_string(temp_dir.path().join("file1.txt"))?;
        assert_eq!(content1, "Content of file 1");

        let content2 = fs::read_to_string(temp_dir.path().join("file2.txt"))?;
        assert_eq!(content2, "Content of file 2");

        let content3 = fs::read_to_string(temp_dir.path().join("file3.txt"))?;
        assert_eq!(content3, "Content of file 3 in subdir");

        Ok(())
    }

    #[tokio::test]
    async fn test_extract_only_for_zip_files() -> Result<()> {
        let temp_dir = TempDir::new()?;

        // Test that non-zip files are saved normally even with --extract
        let payload = Payload::from_bytes(b"Not a zip file").with_filename("document.pdf");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_extract()
            .with_output_dir(temp_dir.path().to_string_lossy().as_ref());
        get(factory, args).await?;

        // Should save as regular file, not attempt extraction
        assert!(temp_dir.path().join("document.pdf").exists());
        let content = fs::read(temp_dir.path().join("document.pdf"))?;
        assert_eq!(content, b"Not a zip file");

        Ok(())
    }

    #[tokio::test]
    async fn test_extract_with_existing_files() -> Result<()> {
        use std::io::Write;
        use zip::ZipWriter;
        use zip::write::FileOptions;

        let temp_dir = TempDir::new()?;

        // Create existing file
        fs::write(temp_dir.path().join("file1.txt"), "existing content")?;

        // Create ZIP archive
        let mut zip_data = Vec::new();
        {
            let mut zip = ZipWriter::new(std::io::Cursor::new(&mut zip_data));

            let options = FileOptions::<()>::default();
            zip.start_file("file1.txt", options)?;
            zip.write_all(b"New content from ZIP")?;

            zip.start_file("file2.txt", options)?;
            zip.write_all(b"Another file")?;

            zip.finish()?;
        }

        let payload = Payload::from_bytes(&zip_data).with_filename("archive.zip");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_extract()
            .with_output_dir(temp_dir.path().to_string_lossy().as_ref());
        get(factory, args).await?;

        // Original file should be unchanged
        let content1 = fs::read_to_string(temp_dir.path().join("file1.txt"))?;
        assert_eq!(content1, "existing content");

        // Should have created timestamped version
        let files: Vec<_> = fs::read_dir(temp_dir.path())?
            .filter_map(|entry| entry.ok())
            .filter(|entry| {
                entry
                    .file_name()
                    .to_string_lossy()
                    .starts_with("file1.txt.")
            })
            .collect();

        assert_eq!(files.len(), 1);
        let timestamped_content = fs::read_to_string(files[0].path())?;
        assert_eq!(timestamped_content, "New content from ZIP");

        // New file should be created normally
        let content2 = fs::read_to_string(temp_dir.path().join("file2.txt"))?;
        assert_eq!(content2, "Another file");

        Ok(())
    }

    #[tokio::test]
    async fn test_extract_empty_archive() -> Result<()> {
        use zip::ZipWriter;

        let temp_dir = TempDir::new()?;

        // Create empty ZIP archive
        let mut zip_data = Vec::new();
        {
            let zip = ZipWriter::new(std::io::Cursor::new(&mut zip_data));
            zip.finish()?;
        }

        let payload = Payload::from_bytes(&zip_data).with_filename("empty.zip");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_extract()
            .with_output_dir(temp_dir.path().to_string_lossy().as_ref());
        get(factory, args).await?;

        // No files should be created (empty archive extracts nothing)
        let entries: Vec<_> = fs::read_dir(temp_dir.path())?
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(
            entries.len(),
            0,
            "Expected no files after extracting empty archive"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_get_with_passphrase() -> Result<()> {
        let payload = Payload::from_bytes(b"protected secret");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_passphrase("mypassword")
            .with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_with_empty_passphrase() -> Result<()> {
        let payload = Payload::from_bytes(b"protected secret");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_passphrase("")
            .with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_with_unicode_passphrase() -> Result<()> {
        let payload = Payload::from_bytes(b"unicode protected secret");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_passphrase("パスワード123🔒")
            .with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_without_passphrase() -> Result<()> {
        let payload = Payload::from_bytes(b"unprotected secret");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let args = GetArgs::builder("https://example.com/s/test123#key").with_to_stdout();
        // Should work fine without passphrase when secret doesn't require one
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_passphrase_with_file_output() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let payload = Payload::from_bytes(b"protected file content").with_filename("protected.txt");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let filename = temp_dir
            .path()
            .join("output.txt")
            .to_string_lossy()
            .to_string();
        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_passphrase("filepassword")
            .with_filename(&filename);
        get(factory, args).await?;

        // Verify file was created with correct content
        let content = fs::read(temp_dir.path().join("output.txt"))?;
        assert_eq!(content, b"protected file content");
        Ok(())
    }

    #[tokio::test]
    async fn test_get_long_passphrase() -> Result<()> {
        let payload = Payload::from_bytes(b"secret with very long passphrase");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        // Test with a very long passphrase (512 characters)
        let long_passphrase = "a".repeat(512);
        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_passphrase(&long_passphrase)
            .with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_passphrase_with_special_characters() -> Result<()> {
        let payload = Payload::from_bytes(b"secret with special chars in passphrase");
        let client = MockClient::new().with_receive_success(payload);
        let factory = MockFactory::new().with_client(client);

        let special_passphrase = "!@#$%^&*()_+-=[]{}|;':\",./<>?`~";
        let args = GetArgs::builder("https://example.com/s/test123#key")
            .with_passphrase(special_passphrase)
            .with_to_stdout();
        get(factory, args).await?;
        Ok(())
    }
}