tsafe-cli 1.0.21

tsafe CLI — local secret and credential manager (replaces .env files)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Integration tests for the KeePass `.kdbx` cloud-pull provider.
//!
//! Tests use the `keepass` crate (with `save_kdbx4` feature) to create
//! temporary `.kdbx` databases programmatically — no pre-committed fixture
//! files are required.
//!
//! All tests run only when the `cloud-pull-keepass` feature is active.

#[cfg(feature = "cloud-pull-keepass")]
mod inner {
    use keepass::{
        db::{fields, GroupMut},
        Database, DatabaseKey,
    };
    use tempfile::tempdir;
    use tsafe_cli::tsafe_keepass::{pull_entries, KeePassConfig, KeePassError};
    use tsafe_core::pullconfig::PullSource;

    const PASSWORD: &str = "test-master-password";

    /// Create a minimal KDBX4 database in a temporary directory, returning the
    /// path to the file and the directory (so the tempdir is not dropped early).
    fn make_kdbx(
        password: &str,
        setup: impl FnOnce(&mut Database),
    ) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.kdbx");

        let mut db = Database::new();
        setup(&mut db);

        let key = DatabaseKey::new().with_password(password);
        let mut file = std::fs::File::create(&path).unwrap();
        db.save(&mut file, key).unwrap();

        (dir, path)
    }

    /// Add an entry with standard fields to `group`.
    fn add_entry(
        group: &mut GroupMut<'_>,
        title: &str,
        username: &str,
        password: &str,
        url: Option<&str>,
    ) {
        let mut entry = group.add_entry();
        entry.set_unprotected(fields::TITLE, title);
        entry.set_unprotected(fields::USERNAME, username);
        entry.set_protected(fields::PASSWORD, password);
        if let Some(u) = url {
            entry.set_unprotected(fields::URL, u);
        }
    }

    // ── helper ────────────────────────────────────────────────────────────────

    fn cfg_from_path(path: &std::path::Path) -> KeePassConfig {
        KeePassConfig::from_pull_source(&PullSource::Keepass {
            name: None,
            ns: None,
            path: path.to_string_lossy().into_owned(),
            password_env: Some("TSAFE_TEST_KP_PASSWORD".to_string()),
            keyfile_path: None,
            group: None,
            recursive: None,
            overwrite: false,
        })
        .expect("config should be valid when env var is set")
    }

    fn cfg_from_path_with_group(path: &std::path::Path, group: &str) -> KeePassConfig {
        KeePassConfig::from_pull_source(&PullSource::Keepass {
            name: None,
            ns: None,
            path: path.to_string_lossy().into_owned(),
            password_env: Some("TSAFE_TEST_KP_PASSWORD".to_string()),
            keyfile_path: None,
            group: Some(group.to_string()),
            recursive: None,
            overwrite: false,
        })
        .expect("config should be valid when env var is set")
    }

    // ── tests ─────────────────────────────────────────────────────────────────

    /// Pulling from a database with a single entry extracts USERNAME and PASSWORD.
    #[test]
    fn keepass_pull_reads_username_and_password() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            add_entry(&mut root, "Database Creds", "admin", "s3cr3t", None);
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            let cfg = cfg_from_path(&path);
            let entries = pull_entries(&cfg).expect("pull_entries should succeed");

            let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
            let values: std::collections::HashMap<&str, &str> = entries
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect();

            assert!(
                keys.contains(&"DATABASE_CREDS_USERNAME"),
                "expected DATABASE_CREDS_USERNAME in keys, got {keys:?}"
            );
            assert!(
                keys.contains(&"DATABASE_CREDS_PASSWORD"),
                "expected DATABASE_CREDS_PASSWORD in keys, got {keys:?}"
            );
            assert_eq!(
                values.get("DATABASE_CREDS_USERNAME").copied(),
                Some("admin")
            );
            assert_eq!(
                values.get("DATABASE_CREDS_PASSWORD").copied(),
                Some("s3cr3t")
            );
        });
    }

    /// URL field is extracted as TITLE_URL when non-empty.
    #[test]
    fn keepass_pull_reads_url_field() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            add_entry(
                &mut root,
                "My Service",
                "user",
                "pass",
                Some("https://example.com"),
            );
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            let cfg = cfg_from_path(&path);
            let entries = pull_entries(&cfg).expect("pull_entries should succeed");
            let values: std::collections::HashMap<&str, &str> = entries
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect();

            assert_eq!(
                values.get("MY_SERVICE_URL").copied(),
                Some("https://example.com")
            );
        });
    }

    /// Key normalisation: spaces → underscores, uppercase.
    #[test]
    fn keepass_pull_normalises_title_with_spaces() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            add_entry(&mut root, "db prod server", "dbadmin", "dbpass", None);
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            let cfg = cfg_from_path(&path);
            let entries = pull_entries(&cfg).expect("pull_entries should succeed");
            let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();

            assert!(
                keys.iter().any(|k| k.starts_with("DB_PROD_SERVER_")),
                "expected normalised key prefix DB_PROD_SERVER_, got {keys:?}"
            );
        });
    }

    /// Group filter: only entries in the named group are returned.
    #[test]
    fn keepass_pull_group_filter_returns_only_group_entries() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();

            // Entry directly in root (should be excluded when group filter is active).
            add_entry(&mut root, "Root Entry", "root-user", "root-pass", None);

            // Child group "Infrastructure"
            let mut infra = root.add_group();
            infra.name = "Infrastructure".to_string();
            add_entry(&mut infra, "Infra Entry", "infra-user", "infra-pass", None);
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            let cfg = cfg_from_path_with_group(&path, "Infrastructure");
            let entries = pull_entries(&cfg).expect("pull_entries should succeed");
            let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();

            // Only the Infrastructure group entry should be present.
            assert!(
                keys.contains(&"INFRA_ENTRY_USERNAME"),
                "expected INFRA_ENTRY_USERNAME in keys, got {keys:?}"
            );
            assert!(
                !keys.contains(&"ROOT_ENTRY_USERNAME"),
                "expected ROOT_ENTRY_USERNAME to be absent from keys, got {keys:?}"
            );
        });
    }

    /// Group filter: group name matching is case-insensitive.
    #[test]
    fn keepass_pull_group_filter_is_case_insensitive() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            let mut grp = root.add_group();
            grp.name = "MyGroup".to_string();
            add_entry(&mut grp, "Group Entry", "g-user", "g-pass", None);
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            // Filter with lowercase name — should still match "MyGroup".
            let cfg = cfg_from_path_with_group(&path, "mygroup");
            let entries = pull_entries(&cfg).expect("pull_entries should succeed");
            let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();

            assert!(
                keys.contains(&"GROUP_ENTRY_USERNAME"),
                "expected GROUP_ENTRY_USERNAME in keys with case-insensitive match, got {keys:?}"
            );
        });
    }

    /// Wrong password returns KeePassError::Auth.
    #[test]
    fn keepass_pull_wrong_password_errors() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            add_entry(&mut root, "Entry", "user", "pass", None);
        });

        temp_env::with_var(
            "TSAFE_TEST_KP_PASSWORD",
            Some("definitely-wrong-password"),
            || {
                let cfg = cfg_from_path(&path);
                let result = pull_entries(&cfg);
                assert!(
                    matches!(result, Err(KeePassError::Auth)),
                    "expected KeePassError::Auth for wrong password, got {result:?}"
                );
            },
        );
    }

    /// Missing file returns KeePassError::Open.
    #[test]
    fn keepass_pull_missing_file_errors() {
        let dir = tempdir().unwrap();
        let nonexistent_path = dir.path().join("does_not_exist.kdbx");

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            let cfg = KeePassConfig::from_pull_source(&PullSource::Keepass {
                name: None,
                ns: None,
                path: nonexistent_path.to_string_lossy().into_owned(),
                password_env: Some("TSAFE_TEST_KP_PASSWORD".to_string()),
                keyfile_path: None,
                group: None,
                recursive: None,
                overwrite: false,
            })
            .expect("config is valid");

            let result = pull_entries(&cfg);
            assert!(
                matches!(result, Err(KeePassError::Open(_))),
                "expected KeePassError::Open for missing file, got {result:?}"
            );
        });
    }

    /// Non-existent group name returns KeePassError::GroupNotFound.
    #[test]
    fn keepass_pull_nonexistent_group_errors() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            add_entry(&mut root, "Entry", "user", "pass", None);
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            let cfg = cfg_from_path_with_group(&path, "NoSuchGroup");
            let result = pull_entries(&cfg);
            assert!(
                matches!(result, Err(KeePassError::GroupNotFound(_))),
                "expected KeePassError::GroupNotFound, got {result:?}"
            );
        });
    }

    /// Missing password_env returns KeePassError::PasswordRequired.
    #[test]
    fn keepass_config_missing_password_env_errors() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.kdbx");

        // Don't actually create the file — config building should fail before opening.
        let result = temp_env::with_var("TSAFE_TEST_KP_PASSWORD_ABSENT", None::<&str>, || {
            KeePassConfig::from_pull_source(&PullSource::Keepass {
                name: None,
                ns: None,
                path: path.to_string_lossy().into_owned(),
                password_env: Some("TSAFE_TEST_KP_PASSWORD_ABSENT".to_string()),
                keyfile_path: None,
                group: None,
                recursive: None,
                overwrite: false,
            })
        });

        assert!(
            matches!(result, Err(KeePassError::PasswordRequired(_))),
            "expected KeePassError::PasswordRequired when env var is unset, got {result:?}"
        );
    }

    /// No password_env AND no keyfile_path returns KeePassError::PasswordRequired.
    #[test]
    fn keepass_config_no_credentials_errors() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.kdbx");

        let result = KeePassConfig::from_pull_source(&PullSource::Keepass {
            name: None,
            ns: None,
            path: path.to_string_lossy().into_owned(),
            password_env: None,
            keyfile_path: None,
            group: None,
            recursive: None,
            overwrite: false,
        });

        assert!(
            matches!(result, Err(KeePassError::PasswordRequired(_))),
            "expected PasswordRequired when neither password_env nor keyfile_path is set, got {result:?}"
        );
    }

    /// Recursive traversal includes entries in descendant groups.
    #[test]
    fn keepass_pull_recursive_traversal_includes_descendant_groups() {
        let (_dir, path) = make_kdbx(PASSWORD, |db| {
            let mut root = db.root_mut();
            let mut parent = root.add_group();
            parent.name = "ParentGroup".to_string();

            let mut child = parent.add_group();
            child.name = "ChildGroup".to_string();
            add_entry(&mut child, "Child Entry", "child-user", "child-pass", None);
        });

        temp_env::with_var("TSAFE_TEST_KP_PASSWORD", Some(PASSWORD), || {
            // With recursive = true, the child group entry should be found.
            let cfg = KeePassConfig::from_pull_source(&PullSource::Keepass {
                name: None,
                ns: None,
                path: path.to_string_lossy().into_owned(),
                password_env: Some("TSAFE_TEST_KP_PASSWORD".to_string()),
                keyfile_path: None,
                group: Some("ParentGroup".to_string()),
                recursive: Some(true),
                overwrite: false,
            })
            .expect("config should be valid");

            let entries = pull_entries(&cfg).expect("pull_entries should succeed");
            let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();

            assert!(
                keys.contains(&"CHILD_ENTRY_USERNAME"),
                "expected CHILD_ENTRY_USERNAME with recursive=true, got {keys:?}"
            );
        });
    }

    /// YAML config with `source: kp` parses correctly into PullSource::Keepass.
    #[test]
    fn keepass_pull_source_yaml_parses() {
        let yaml = r#"
pulls:
  - source: kp
    path: /tmp/test.kdbx
    password_env: TSAFE_KP_PASSWORD
    group: Infrastructure
    recursive: false
    ns: infra
"#;
        let cfg: tsafe_core::pullconfig::PullConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(cfg.pulls.len(), 1);
        match &cfg.pulls[0] {
            PullSource::Keepass {
                path,
                password_env,
                group,
                recursive,
                ns,
                ..
            } => {
                assert_eq!(path, "/tmp/test.kdbx");
                assert_eq!(password_env.as_deref(), Some("TSAFE_KP_PASSWORD"));
                assert_eq!(group.as_deref(), Some("Infrastructure"));
                assert_eq!(recursive, &Some(false));
                assert_eq!(ns.as_deref(), Some("infra"));
            }
            other => panic!("expected Keepass variant, got {other:?}"),
        }
    }

    /// `name()`, `ns()`, and `provider_type()` accessors work for Keepass.
    #[test]
    fn keepass_pull_source_accessors() {
        use tsafe_core::pullconfig::PullSource;

        let src = PullSource::Keepass {
            name: Some("dev-kp".into()),
            ns: Some("dev".into()),
            path: "/tmp/dev.kdbx".into(),
            password_env: Some("KP_PW".into()),
            keyfile_path: None,
            group: None,
            recursive: None,
            overwrite: false,
        };

        assert_eq!(src.name(), Some("dev-kp"));
        assert_eq!(src.ns(), Some("dev"));
        assert_eq!(src.provider_type(), "kp");
    }
}