apcore-cli 0.7.0

Command-line interface for apcore modules
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
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
// apcore-cli — Encrypted config storage.
// Protocol spec: SEC-03 (ConfigEncryptor, ConfigDecryptionError)

use aes_gcm::{
    aead::{rand_core::RngCore, Aead, AeadCore, KeyInit, OsRng},
    Aes256Gcm, Nonce,
};
use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
use gethostname::gethostname;
use pbkdf2::pbkdf2_hmac;
use sha2::Sha256;
use thiserror::Error;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const SERVICE_NAME: &str = "apcore-cli";
/// Legacy static salt used by `enc:` (v1) tokens — kept for decryption
/// backward compatibility only.  New encryptions use `enc:v2:` with a
/// per-encryption random salt embedded in the wire bytes.
const PBKDF2_SALT_V1: &[u8] = b"apcore-cli-config-v1";
/// OWASP 2026 minimum for PBKDF2-HMAC-SHA256.
const PBKDF2_ITERATIONS: u32 = 600_000;
/// Minimum v1 wire-format length: 12-byte nonce + 16-byte tag.
const MIN_WIRE_LEN_V1: usize = 28;
/// Random salt length prepended to v2 wire bytes.
const PBKDF2_SALT_LEN_V2: usize = 16;
/// Minimum v2 wire-format length: 16-byte salt + 12-byte nonce + 16-byte tag.
const MIN_WIRE_LEN_V2: usize = PBKDF2_SALT_LEN_V2 + 28;

// ---------------------------------------------------------------------------
// ConfigDecryptionError
// ---------------------------------------------------------------------------

/// Errors produced by decryption or key-derivation operations.
#[derive(Debug, Error)]
pub enum ConfigDecryptionError {
    /// The ciphertext is malformed or has been tampered with.
    #[error("decryption failed: authentication tag mismatch or corrupt data")]
    AuthTagMismatch,

    /// The stored data was not valid UTF-8 after decryption.
    #[error("decrypted data is not valid UTF-8")]
    InvalidUtf8,

    /// Keyring access failed.
    #[error("keyring error: {0}")]
    KeyringError(String),

    /// Key-derivation failed.
    #[error("key derivation error: {0}")]
    KdfError(String),
}

// ---------------------------------------------------------------------------
// ConfigEncryptor
// ---------------------------------------------------------------------------

/// AES-GCM encrypted config store backed by the system keyring.
///
/// Uses PBKDF2-HMAC-SHA256 for key derivation from a machine-specific
/// `hostname:username` material, and AES-256-GCM for authenticated encryption.
///
/// Wire format for AES-encrypted values:
///   `enc:<base64(nonce[12] || tag[16] || ciphertext)>`
///
/// Keyring-stored values are referenced as:
///   `keyring:<key>`
#[derive(Default)]
pub struct ConfigEncryptor {
    /// When `true`, skip the OS keyring probe and always use AES encryption.
    /// Intended for unit tests running in headless/CI environments.
    _force_aes: bool,
}

impl ConfigEncryptor {
    /// Create a new `ConfigEncryptor` using the OS keyring when available.
    pub fn new() -> Result<Self, ConfigDecryptionError> {
        Ok(Self::default())
    }

    /// Create a `ConfigEncryptor` that always uses AES encryption, bypassing
    /// the OS keyring. Intended for use in tests running in headless/CI environments.
    /// Gated behind the `test-support` feature so it is excluded from production builds.
    #[cfg(any(test, feature = "test-support"))]
    pub fn new_forced_aes() -> Self {
        Self { _force_aes: true }
    }

    /// Wrapper for `_keyring_available()` for use in integration tests.
    #[allow(dead_code)]
    pub(crate) fn keyring_available(&self) -> bool {
        self._keyring_available()
    }

    // -----------------------------------------------------------------------
    // Public API
    // -----------------------------------------------------------------------

    /// Persist `value` for `key`.
    ///
    /// Tries the OS keyring first. On failure (headless / CI) falls back to
    /// AES-256-GCM file encryption.
    ///
    /// Returns a config-file token:
    /// - `"keyring:<key>"` when stored in the OS keyring.
    /// - `"enc:<base64>"` when stored as an encrypted blob.
    ///
    /// # Security note
    ///
    /// The `enc:` fallback path derives its encryption key from the machine's
    /// hostname and the current username. This protects against casual file
    /// browsing but **not** against targeted attacks by co-tenants on shared
    /// systems who know both values. For sensitive credentials (API keys,
    /// tokens), prefer the `keyring:` path (OS keyring) when available, or
    /// use environment variables instead of config file storage.
    pub fn store(&self, key: &str, value: &str) -> Result<String, ConfigDecryptionError> {
        if self._keyring_available() {
            let entry = keyring::Entry::new(SERVICE_NAME, key)
                .map_err(|e| ConfigDecryptionError::KeyringError(e.to_string()))?;
            entry
                .set_password(value)
                .map_err(|e| ConfigDecryptionError::KeyringError(e.to_string()))?;
            Ok(format!("keyring:{key}"))
        } else {
            tracing::warn!("OS keyring unavailable. Using file-based encryption.");
            let ciphertext = self._aes_encrypt_v2(value)?;
            Ok(format!("enc:v2:{}", B64.encode(&ciphertext)))
        }
    }

    /// Retrieve the plaintext for a config value token.
    ///
    /// Handles four formats:
    /// - `"keyring:<ref>"` — fetch from OS keyring.
    /// - `"enc:v2:<base64>"` — v2: per-encryption random salt (PBKDF2 600k rounds).
    /// - `"enc:<base64>"` — v1 legacy: static PBKDF2 salt (100k rounds, read-only).
    /// - anything else — return as-is (plain passthrough).
    pub fn retrieve(&self, config_value: &str, key: &str) -> Result<String, ConfigDecryptionError> {
        if let Some(ref_key) = config_value.strip_prefix("keyring:") {
            let entry = keyring::Entry::new(SERVICE_NAME, ref_key)
                .map_err(|e| ConfigDecryptionError::KeyringError(e.to_string()))?;
            entry.get_password().map_err(|e| match e {
                keyring::Error::NoEntry => ConfigDecryptionError::KeyringError(format!(
                    "Keyring entry not found for '{ref_key}'."
                )),
                other => ConfigDecryptionError::KeyringError(other.to_string()),
            })
        } else if let Some(b64_data) = config_value.strip_prefix("enc:v2:") {
            let data = B64
                .decode(b64_data)
                .map_err(|_| ConfigDecryptionError::AuthTagMismatch)?;
            self._aes_decrypt_v2(&data).map_err(|e| match e {
                ConfigDecryptionError::AuthTagMismatch => ConfigDecryptionError::AuthTagMismatch,
                other => ConfigDecryptionError::KeyringError(format!(
                    "Failed to decrypt configuration value '{key}'. \
                     Re-configure with 'apcore-cli config set {key}'. Cause: {other}"
                )),
            })
        } else if let Some(b64_data) = config_value.strip_prefix("enc:") {
            let data = B64
                .decode(b64_data)
                .map_err(|_| ConfigDecryptionError::AuthTagMismatch)?;
            self._aes_decrypt_v1(&data).map_err(|e| match e {
                ConfigDecryptionError::AuthTagMismatch => ConfigDecryptionError::AuthTagMismatch,
                other => ConfigDecryptionError::KeyringError(format!(
                    "Failed to decrypt configuration value '{key}'. \
                     Re-configure with 'apcore-cli config set {key}'. Cause: {other}"
                )),
            })
        } else {
            Ok(config_value.to_string())
        }
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    /// Returns `true` when the OS keyring is accessible.
    fn _keyring_available(&self) -> bool {
        if self._force_aes {
            return false;
        }
        let entry = match keyring::Entry::new(SERVICE_NAME, "__apcore_probe__") {
            Ok(e) => e,
            Err(_) => return false,
        };
        matches!(entry.get_password(), Ok(_) | Err(keyring::Error::NoEntry))
    }

    /// Derive a 32-byte AES key via PBKDF2-HMAC-SHA256.
    ///
    /// Key material precedence (matching Python/TS parity):
    /// 1. `APCORE_CLI_CONFIG_PASSPHRASE` env var if set and non-empty.
    /// 2. `hostname:username` fallback.
    fn _derive_key_with_salt(&self, salt: &[u8]) -> Result<[u8; 32], ConfigDecryptionError> {
        self._derive_key_with_salt_iter(salt, PBKDF2_ITERATIONS)
    }

    /// Like [`_derive_key_with_salt`] but with a configurable iteration count.
    /// Used by [`_aes_decrypt_v1`] to support the 600k → 100k retry that
    /// Python and TypeScript SDKs perform for early-version v1 ciphertexts
    /// (D10-001).
    fn _derive_key_with_salt_iter(
        &self,
        salt: &[u8],
        iterations: u32,
    ) -> Result<[u8; 32], ConfigDecryptionError> {
        let material = if let Ok(passphrase) = std::env::var("APCORE_CLI_CONFIG_PASSPHRASE") {
            if !passphrase.is_empty() {
                passphrase
            } else {
                let hostname = gethostname()
                    .into_string()
                    .unwrap_or_else(|_| "unknown".to_string());
                let username = std::env::var("USER")
                    .or_else(|_| std::env::var("LOGNAME"))
                    .unwrap_or_else(|_| "unknown".to_string());
                format!("{hostname}:{username}")
            }
        } else {
            let hostname = gethostname()
                .into_string()
                .unwrap_or_else(|_| "unknown".to_string());
            let username = std::env::var("USER")
                .or_else(|_| std::env::var("LOGNAME"))
                .unwrap_or_else(|_| "unknown".to_string());
            format!("{hostname}:{username}")
        };
        let mut key = [0u8; 32];
        pbkdf2_hmac::<Sha256>(material.as_bytes(), salt, iterations, &mut key);
        Ok(key)
    }

    /// Encrypt `plaintext` and return v2 wire bytes.
    ///
    /// Wire format: `salt[16] || nonce[12] || tag[16] || ciphertext`.
    /// A 16-byte random salt is generated per encryption; it is embedded in
    /// the output so no external state is required for decryption.
    pub(crate) fn _aes_encrypt_v2(
        &self,
        plaintext: &str,
    ) -> Result<Vec<u8>, ConfigDecryptionError> {
        let mut salt_bytes = [0u8; PBKDF2_SALT_LEN_V2];
        OsRng.fill_bytes(&mut salt_bytes);
        let raw_key = self._derive_key_with_salt(&salt_bytes)?;
        let cipher = Aes256Gcm::new_from_slice(&raw_key)
            .map_err(|e| ConfigDecryptionError::KdfError(e.to_string()))?;
        let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
        let encrypted = cipher
            .encrypt(&nonce, plaintext.as_bytes())
            .map_err(|_| ConfigDecryptionError::AuthTagMismatch)?;
        let ct_len = encrypted.len() - 16;
        let ciphertext = &encrypted[..ct_len];
        let tag = &encrypted[ct_len..];
        let mut out = Vec::with_capacity(PBKDF2_SALT_LEN_V2 + 12 + 16 + ct_len);
        out.extend_from_slice(&salt_bytes);
        out.extend_from_slice(nonce.as_slice());
        out.extend_from_slice(tag);
        out.extend_from_slice(ciphertext);
        Ok(out)
    }

    /// Decrypt v2 wire bytes back to a UTF-8 string.
    ///
    /// Expected wire format: `salt[16] || nonce[12] || tag[16] || ciphertext`.
    pub(crate) fn _aes_decrypt_v2(&self, data: &[u8]) -> Result<String, ConfigDecryptionError> {
        if data.len() < MIN_WIRE_LEN_V2 {
            return Err(ConfigDecryptionError::AuthTagMismatch);
        }
        let salt = &data[..PBKDF2_SALT_LEN_V2];
        let rest = &data[PBKDF2_SALT_LEN_V2..];
        let raw_key = self._derive_key_with_salt(salt)?;
        let cipher = Aes256Gcm::new_from_slice(&raw_key)
            .map_err(|e| ConfigDecryptionError::KdfError(e.to_string()))?;
        let nonce = Nonce::from_slice(&rest[..12]);
        let tag = &rest[12..28];
        let ciphertext = &rest[28..];
        let mut ct_with_tag = Vec::with_capacity(ciphertext.len() + 16);
        ct_with_tag.extend_from_slice(ciphertext);
        ct_with_tag.extend_from_slice(tag);
        let plaintext = cipher
            .decrypt(nonce, ct_with_tag.as_slice())
            .map_err(|_| ConfigDecryptionError::AuthTagMismatch)?;
        String::from_utf8(plaintext).map_err(|_| ConfigDecryptionError::InvalidUtf8)
    }

    /// Decrypt v1 (legacy) wire bytes back to a UTF-8 string.
    ///
    /// Expected wire format: `nonce[12] || tag[16] || ciphertext` with the
    /// static `PBKDF2_SALT_V1` salt. Read-only — new encryptions use
    /// `_aes_encrypt_v2` / `enc:v2:` tokens instead.
    ///
    /// Iteration retry per the cross-SDK contract (D10-001): tries 600k
    /// (current Rust-written v1) first, then 100k (early Python/TS-written
    /// v1). Mirrors apcore-cli-python/src/apcore_cli/security/config_encryptor.py:139
    /// and apcore-cli-typescript/src/security/config-encryptor.ts:197.
    pub(crate) fn _aes_decrypt_v1(&self, data: &[u8]) -> Result<String, ConfigDecryptionError> {
        if data.len() < MIN_WIRE_LEN_V1 {
            return Err(ConfigDecryptionError::AuthTagMismatch);
        }
        let nonce = Nonce::from_slice(&data[..12]);
        let tag = &data[12..28];
        let ciphertext = &data[28..];

        let mut last_err: Option<ConfigDecryptionError> = None;
        for iterations in [PBKDF2_ITERATIONS, 100_000_u32] {
            let raw_key = match self._derive_key_with_salt_iter(PBKDF2_SALT_V1, iterations) {
                Ok(k) => k,
                Err(e) => {
                    last_err = Some(e);
                    continue;
                }
            };
            let cipher = match Aes256Gcm::new_from_slice(&raw_key) {
                Ok(c) => c,
                Err(e) => {
                    last_err = Some(ConfigDecryptionError::KdfError(e.to_string()));
                    continue;
                }
            };
            let mut ct_with_tag = Vec::with_capacity(ciphertext.len() + 16);
            ct_with_tag.extend_from_slice(ciphertext);
            ct_with_tag.extend_from_slice(tag);
            match cipher.decrypt(nonce, ct_with_tag.as_slice()) {
                Ok(plaintext) => {
                    return String::from_utf8(plaintext)
                        .map_err(|_| ConfigDecryptionError::InvalidUtf8);
                }
                Err(_) => {
                    last_err = Some(ConfigDecryptionError::AuthTagMismatch);
                    continue;
                }
            }
        }
        Err(last_err.unwrap_or(ConfigDecryptionError::AuthTagMismatch))
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    /// Build an encryptor that always uses the AES path (keyring skipped).
    fn aes_encryptor() -> ConfigEncryptor {
        ConfigEncryptor { _force_aes: true }
    }

    #[test]
    fn test_aes_v2_roundtrip() {
        let enc = aes_encryptor();
        let ciphertext = enc._aes_encrypt_v2("hello-secret").expect("encrypt");
        let plaintext = enc._aes_decrypt_v2(&ciphertext).expect("decrypt");
        assert_eq!(plaintext, "hello-secret");
    }

    /// Helper: encrypt v1 wire bytes with an explicit iteration count so we
    /// can test the 600k → 100k decrypt fallback (D10-001) without exposing
    /// the legacy 100k path as a public encryption API.
    fn _v1_encrypt_with_iterations(
        enc: &ConfigEncryptor,
        plaintext: &str,
        iterations: u32,
    ) -> Vec<u8> {
        use aes_gcm::aead::{Aead, AeadCore, KeyInit, OsRng};
        let raw_key = enc
            ._derive_key_with_salt_iter(PBKDF2_SALT_V1, iterations)
            .expect("derive");
        let cipher = Aes256Gcm::new_from_slice(&raw_key).expect("cipher");
        let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
        let ct_with_tag = cipher
            .encrypt(&nonce, plaintext.as_bytes())
            .expect("encrypt");
        // Wire format: nonce[12] || tag[16] || ciphertext.
        // aes-gcm appends the 16-byte tag to the end of the ciphertext, so we
        // need to splice it into the middle slot.
        assert!(ct_with_tag.len() >= 16);
        let split = ct_with_tag.len() - 16;
        let (ct, tag) = ct_with_tag.split_at(split);
        let mut wire = Vec::with_capacity(12 + 16 + ct.len());
        wire.extend_from_slice(&nonce);
        wire.extend_from_slice(tag);
        wire.extend_from_slice(ct);
        wire
    }

    #[test]
    fn test_aes_v1_decrypts_600k_ciphertext() {
        // Sanity: the current iteration count round-trips.
        let enc = aes_encryptor();
        let wire = _v1_encrypt_with_iterations(&enc, "current-secret", PBKDF2_ITERATIONS);
        let plaintext = enc._aes_decrypt_v1(&wire).expect("decrypt");
        assert_eq!(plaintext, "current-secret");
    }

    #[test]
    fn test_aes_v1_decrypts_100k_legacy_ciphertext() {
        // D10-001: very early SDK builds wrote v1 ciphertexts with 100k
        // PBKDF2 iterations. Python and TS retry with 100k after 600k fails;
        // Rust must do the same so legacy values remain readable.
        let enc = aes_encryptor();
        let wire = _v1_encrypt_with_iterations(&enc, "legacy-secret", 100_000);
        let plaintext = enc
            ._aes_decrypt_v1(&wire)
            .expect("v1 decrypt must retry at 100k iterations");
        assert_eq!(plaintext, "legacy-secret");
    }

    #[test]
    fn test_aes_v1_rejects_wrong_iterations() {
        // Ciphertext encrypted with 200k (neither 600k nor 100k) must fail
        // — proves the retry list is bounded, not "try anything".
        let enc = aes_encryptor();
        let wire = _v1_encrypt_with_iterations(&enc, "weird", 200_000);
        let result = enc._aes_decrypt_v1(&wire);
        assert!(result.is_err(), "200k ciphertext must not decrypt");
    }

    #[test]
    fn test_store_without_keyring_returns_enc_v2_prefix() {
        let enc = aes_encryptor();
        let token = enc.store("auth.api_key", "secret123").expect("store");
        assert!(
            token.starts_with("enc:v2:"),
            "expected enc:v2: prefix, got {token}"
        );
    }

    #[test]
    fn test_retrieve_enc_v2_value() {
        let enc = aes_encryptor();
        let token = enc.store("auth.api_key", "secret123").expect("store");
        let result = enc.retrieve(&token, "auth.api_key").expect("retrieve");
        assert_eq!(result, "secret123");
    }

    #[test]
    fn test_retrieve_plaintext_passthrough() {
        let enc = aes_encryptor();
        let result = enc.retrieve("plain-value", "some.key").expect("retrieve");
        assert_eq!(result, "plain-value");
    }

    #[test]
    fn test_retrieve_corrupted_v1_ciphertext_returns_error() {
        let enc = aes_encryptor();
        let mut bad = vec![0u8; 40];
        bad[12] ^= 0xFF;
        let config_value = format!("enc:{}", B64.encode(&bad));
        let result = enc.retrieve(&config_value, "some.key");
        assert!(matches!(
            result,
            Err(ConfigDecryptionError::AuthTagMismatch)
        ));
    }

    #[test]
    fn test_retrieve_corrupted_v2_ciphertext_returns_error() {
        let enc = aes_encryptor();
        // v2 wire: 16 salt + 40 (12 nonce + 16 tag + 12 ct), corrupt tag.
        let mut bad = vec![0u8; 56];
        bad[16 + 12] ^= 0xFF;
        let config_value = format!("enc:v2:{}", B64.encode(&bad));
        let result = enc.retrieve(&config_value, "some.key");
        assert!(matches!(
            result,
            Err(ConfigDecryptionError::AuthTagMismatch)
        ));
    }

    #[test]
    fn test_retrieve_short_v1_ciphertext_returns_error() {
        let enc = aes_encryptor();
        let config_value = format!("enc:{}", B64.encode([0u8; 10]));
        let result = enc.retrieve(&config_value, "some.key");
        assert!(matches!(
            result,
            Err(ConfigDecryptionError::AuthTagMismatch)
        ));
    }

    #[test]
    fn test_retrieve_short_v2_ciphertext_returns_error() {
        let enc = aes_encryptor();
        let config_value = format!("enc:v2:{}", B64.encode([0u8; 10]));
        let result = enc.retrieve(&config_value, "some.key");
        assert!(matches!(
            result,
            Err(ConfigDecryptionError::AuthTagMismatch)
        ));
    }

    #[test]
    fn test_derive_key_is_32_bytes() {
        let enc = aes_encryptor();
        let key = enc._derive_key_with_salt(PBKDF2_SALT_V1).expect("derive");
        assert_eq!(key.len(), 32);
    }

    #[test]
    fn test_v2_ciphertexts_differ_for_same_plaintext() {
        // Random per-encryption salt means same plaintext produces different tokens.
        let enc = aes_encryptor();
        let ct1 = enc._aes_encrypt_v2("same").expect("e1");
        let ct2 = enc._aes_encrypt_v2("same").expect("e2");
        assert_ne!(ct1, ct2, "v2 ciphertexts must differ (random salt)");
    }
}