alpaca-trader-rs 0.6.0

Alpaca Markets trading toolkit — async REST client library and interactive TUI trading terminal
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
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
//! Tiered credential resolution for Alpaca API keys.
//!
//! Resolution order (highest → lowest priority):
//!
//! 1. **`ALPACA_API_KEY` + `ALPACA_API_SECRET`** — unified pair; ideal for CI,
//!    Docker, and systemd where a single key pair is configured.
//! 2. **`{ENV}_ALPACA_KEY` + `{ENV}_ALPACA_SECRET`** — per-environment vars
//!    (`LIVE_*` or `PAPER_*`); developer `.env` files and multi-environment setups.
//! 3. **OS-native keychain** (macOS Keychain Access, Windows Credential Store,
//!    Linux kernel keyutils) — no C-library dependency on any platform.
//! 4. **Interactive TTY prompt** via `rpassword` — runs once on first launch
//!    and offers to persist credentials in the OS keychain.
//!
//! Call [`resolve`] **before** `enable_raw_mode()` — it may print to stderr
//! and read from stdin.

use std::io::{self, BufRead as _, IsTerminal as _};

use anyhow::{bail, Result};

use crate::config::{AlpacaEnv, ResolvedCredentials};

const SERVICE: &str = "alpaca-trader-rs";

const DEFAULT_LIVE_ENDPOINT: &str = "https://api.alpaca.markets";
const DEFAULT_PAPER_ENDPOINT: &str = "https://paper-api.alpaca.markets/v2";

/// Resolve credentials for `env` using the tiered lookup strategy.
///
/// Must be called **before** `enable_raw_mode()`.
pub fn resolve(env: AlpacaEnv) -> Result<ResolvedCredentials> {
    let (prefix, kr_prefix, default_ep) = match env {
        AlpacaEnv::Live => ("LIVE_ALPACA", "live", DEFAULT_LIVE_ENDPOINT),
        AlpacaEnv::Paper => ("PAPER_ALPACA", "paper", DEFAULT_PAPER_ENDPOINT),
    };
    let env_label = match env {
        AlpacaEnv::Live => "live",
        AlpacaEnv::Paper => "paper",
    };

    let endpoint =
        std::env::var(format!("{prefix}_ENDPOINT")).unwrap_or_else(|_| default_ep.to_string());

    // ── Step 1a: unified env vars (ALPACA_API_KEY / ALPACA_API_SECRET) ─────────
    // These take priority and work regardless of live/paper mode — ideal for CI,
    // Docker, and systemd where a single key pair is configured.
    let unified_key = std::env::var("ALPACA_API_KEY")
        .ok()
        .filter(|s| !s.is_empty());
    let unified_secret = std::env::var("ALPACA_API_SECRET")
        .ok()
        .filter(|s| !s.is_empty());

    if let (Some(key), Some(secret)) = (unified_key, unified_secret) {
        tracing::debug!(
            env = env_label,
            "credentials loaded from ALPACA_API_KEY / ALPACA_API_SECRET"
        );
        return Ok(ResolvedCredentials {
            endpoint,
            key,
            secret,
            env,
        });
    }

    // ── Step 1b: per-environment env vars ({ENV}_ALPACA_KEY / _SECRET) ─────────
    let env_key = std::env::var(format!("{prefix}_KEY"))
        .ok()
        .filter(|s| !s.is_empty());
    let env_secret = std::env::var(format!("{prefix}_SECRET"))
        .ok()
        .filter(|s| !s.is_empty());

    if let (Some(key), Some(secret)) = (env_key, env_secret) {
        tracing::debug!(
            env = env_label,
            "credentials loaded from environment variables"
        );
        return Ok(ResolvedCredentials {
            endpoint,
            key,
            secret,
            env,
        });
    }

    // ── Step 2: OS keychain ────────────────────────────────────────────────────
    // keychain_usable is true when the keychain backend is present and healthy.
    // On unsupported platforms the entire block is compiled away.
    let mut keychain_usable = false;

    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    match try_keychain_load(kr_prefix) {
        Ok(Some((key, secret))) => {
            tracing::debug!(env = env_label, "credentials loaded from OS keychain");
            return Ok(ResolvedCredentials {
                endpoint,
                key,
                secret,
                env,
            });
        }
        Ok(None) => {
            // Not stored yet — fall through to interactive prompt.
            keychain_usable = true;
        }
        Err(KeychainStatus::Unavailable(msg)) => {
            eprintln!(
                "Warning: OS keychain unavailable ({msg}) — \
                 credentials will not be persisted."
            );
            // keychain_usable remains false
        }
        Err(KeychainStatus::Hard(e)) => return Err(e),
    }

    // Suppress unused-variable warning on platforms without keychain support.
    let _ = keychain_usable;

    // ── Step 3: interactive TTY prompt ─────────────────────────────────────────
    if !io::stdin().is_terminal() {
        bail!(
            "No {env_label} Alpaca credentials found and no interactive terminal is available.\n\
             Set {prefix}_KEY and {prefix}_SECRET in your environment or .env file."
        );
    }

    eprintln!();
    eprintln!("No {env_label} Alpaca credentials found.");
    if matches!(env, AlpacaEnv::Live) {
        eprintln!("⚠️  Live trading uses real money. Proceed with care.");
    }
    eprintln!("Visit https://app.alpaca.markets to generate API credentials.");
    eprintln!();

    let key_prompt = format!("{} API Key   (APCA-API-KEY-ID): ", env_label.to_uppercase());
    let secret_prompt = format!("{} API Secret:                  ", env_label.to_uppercase());

    let key = rpassword::prompt_password(key_prompt)?;
    let secret = rpassword::prompt_password(secret_prompt)?;

    if key.trim().is_empty() || secret.trim().is_empty() {
        bail!("API key and secret must not be empty.");
    }

    // ── Step 4: offer to save to keychain ─────────────────────────────────────
    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    if keychain_usable {
        offer_keychain_save(kr_prefix, &key, &secret);
    }

    eprintln!();
    Ok(ResolvedCredentials {
        endpoint,
        key,
        secret,
        env,
    })
}

/// Delete stored keychain credentials for `env` and exit.
///
/// Prints a status message to stderr. On platforms without keychain support,
/// prints an informational message and returns without error.
pub fn reset(env: AlpacaEnv) {
    let (kr_prefix, env_label, env_prefix) = match env {
        AlpacaEnv::Live => ("live", "live", "LIVE_ALPACA"),
        AlpacaEnv::Paper => ("paper", "paper", "PAPER_ALPACA"),
    };

    // ── Report env var sources ────────────────────────────────────────────────
    // dotenvy::dotenv() is called before reset() in main, so vars from .env
    // files are already in the environment at this point.
    let has_unified = std::env::var("ALPACA_API_KEY")
        .ok()
        .filter(|s| !s.is_empty())
        .is_some()
        && std::env::var("ALPACA_API_SECRET")
            .ok()
            .filter(|s| !s.is_empty())
            .is_some();
    let has_prefixed = std::env::var(format!("{env_prefix}_KEY"))
        .ok()
        .filter(|s| !s.is_empty())
        .is_some()
        && std::env::var(format!("{env_prefix}_SECRET"))
            .ok()
            .filter(|s| !s.is_empty())
            .is_some();

    if has_unified {
        eprintln!(
            "Note: ALPACA_API_KEY / ALPACA_API_SECRET are set in your environment or a .env file."
        );
        eprintln!("      To stop using them, remove or unset those variables.");
    }
    if has_prefixed {
        eprintln!(
            "Note: {env_prefix}_KEY / {env_prefix}_SECRET are set in your environment or a .env file."
        );
        eprintln!(
            "      To stop using them, remove or unset those variables (check ~/.env or .env)."
        );
    }

    // ── Remove keychain entries ───────────────────────────────────────────────
    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    {
        let key_user = format!("{kr_prefix}-api-key");
        let secret_user = format!("{kr_prefix}-api-secret");
        let mut removed = 0u8;
        let mut any_error = false;

        for user in [&key_user, &secret_user] {
            match keyring::Entry::new(SERVICE, user) {
                Ok(entry) => match entry.delete_credential() {
                    Ok(()) => removed += 1,
                    Err(keyring::Error::NoEntry) => {}
                    Err(e) => {
                        eprintln!("Warning: could not remove {user} from keychain: {e}");
                        any_error = true;
                    }
                },
                Err(e) => {
                    eprintln!("Warning: keychain init error for {user}: {e}");
                    any_error = true;
                }
            }
        }

        if any_error {
            eprintln!("Some entries could not be removed. You may need to remove them manually.");
        } else if removed == 0 {
            if !has_unified && !has_prefixed {
                eprintln!("No {env_label} credentials found in keychain or environment (nothing to remove).");
            } else {
                eprintln!("No {env_label} credentials found in keychain (see env var note above).");
            }
        } else {
            eprintln!("{env_label} credentials removed from keychain.");
        }
    }

    #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
    {
        let _ = kr_prefix;
        if !has_unified && !has_prefixed {
            eprintln!("Keychain storage is not supported on this platform — nothing to reset.");
            eprintln!(
                "To clear credentials, unset the {env_prefix}_KEY / {env_prefix}_SECRET \
                 environment variables."
            );
        }
    }
}

// ── Keychain helpers (compiled only on supported platforms) ───────────────────

/// Distinguishes between "entry not found" and a hard backend error.
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
enum KeychainStatus {
    /// The keychain is locked or the backend is unavailable.
    Unavailable(String),
    /// An unexpected hard error occurred.
    Hard(anyhow::Error),
}

/// Try to read a key+secret pair from the OS keychain.
///
/// Returns:
/// - `Ok(Some(_))` — credentials found
/// - `Ok(None)` — entry absent (`NoEntry`); first-run, safe to prompt
/// - `Err(KeychainStatus::Unavailable)` — keychain locked/inaccessible; warn and prompt without saving
/// - `Err(KeychainStatus::Hard)` — unexpected error; propagate to caller
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
fn try_keychain_load(prefix: &str) -> Result<Option<(String, String)>, KeychainStatus> {
    let key = load_one_entry(&format!("{prefix}-api-key"))?;
    let secret = load_one_entry(&format!("{prefix}-api-secret"))?;
    match (key, secret) {
        (Some(k), Some(s)) => Ok(Some((k, s))),
        _ => Ok(None), // one or both absent — first run
    }
}

#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
fn load_one_entry(user: &str) -> Result<Option<String>, KeychainStatus> {
    let entry = keyring::Entry::new(SERVICE, user)
        .map_err(|e| KeychainStatus::Hard(anyhow::anyhow!("keyring init error: {e}")))?;

    match entry.get_password() {
        Ok(v) => Ok(Some(v)),
        Err(keyring::Error::NoEntry) => Ok(None),
        Err(keyring::Error::NoStorageAccess(e) | keyring::Error::PlatformFailure(e)) => {
            Err(KeychainStatus::Unavailable(e.to_string()))
        }
        Err(e) => Err(KeychainStatus::Hard(anyhow::anyhow!(
            "keychain read error: {e}"
        ))),
    }
}

/// Prompt the user to save credentials to the OS keychain.
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
fn offer_keychain_save(prefix: &str, key: &str, secret: &str) {
    eprint!("Store credentials in OS keychain for future logins? [Y/n]: ");
    let mut answer = String::new();
    if io::stdin().lock().read_line(&mut answer).is_err() {
        return;
    }
    if !(answer.trim().is_empty() || answer.trim().eq_ignore_ascii_case("y")) {
        return;
    }
    match save_keychain_pair(prefix, key, secret) {
        Ok(()) => eprintln!("✓ Credentials saved to keychain."),
        Err(e) => eprintln!("Warning: could not save to keychain: {e}"),
    }
}

#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
fn save_keychain_pair(prefix: &str, key: &str, secret: &str) -> Result<()> {
    keyring::Entry::new(SERVICE, &format!("{prefix}-api-key"))
        .and_then(|e| e.set_password(key))
        .map_err(|e| anyhow::anyhow!("keychain write error (key): {e}"))?;
    keyring::Entry::new(SERVICE, &format!("{prefix}-api-secret"))
        .and_then(|e| e.set_password(secret))
        .map_err(|e| anyhow::anyhow!("keychain write error (secret): {e}"))?;
    Ok(())
}

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

    // Helper: clear all credential env vars around a test closure.
    fn with_no_env_creds<F: FnOnce()>(f: F) {
        temp_env::with_vars(
            [
                ("ALPACA_API_KEY", None::<&str>),
                ("ALPACA_API_SECRET", None::<&str>),
                ("LIVE_ALPACA_KEY", None::<&str>),
                ("LIVE_ALPACA_SECRET", None::<&str>),
                ("PAPER_ALPACA_KEY", None::<&str>),
                ("PAPER_ALPACA_SECRET", None::<&str>),
                ("LIVE_ALPACA_ENDPOINT", None::<&str>),
                ("PAPER_ALPACA_ENDPOINT", None::<&str>),
            ],
            f,
        );
    }

    // ── Unified env var tests ─────────────────────────────────────────────────

    #[test]
    fn unified_vars_resolve_for_live() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("unified-key")),
                    ("ALPACA_API_SECRET", Some("unified-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.key, "unified-key");
                    assert_eq!(creds.secret, "unified-secret");
                    assert!(matches!(creds.env, AlpacaEnv::Live));
                },
            );
        });
    }

    #[test]
    fn unified_vars_resolve_for_paper() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("unified-key")),
                    ("ALPACA_API_SECRET", Some("unified-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Paper).unwrap();
                    assert_eq!(creds.key, "unified-key");
                    assert_eq!(creds.secret, "unified-secret");
                    assert!(matches!(creds.env, AlpacaEnv::Paper));
                },
            );
        });
    }

    #[test]
    fn unified_vars_use_default_live_endpoint() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("k")),
                    ("ALPACA_API_SECRET", Some("s")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.endpoint, DEFAULT_LIVE_ENDPOINT);
                },
            );
        });
    }

    #[test]
    fn unified_vars_use_default_paper_endpoint() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("k")),
                    ("ALPACA_API_SECRET", Some("s")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Paper).unwrap();
                    assert_eq!(creds.endpoint, DEFAULT_PAPER_ENDPOINT);
                },
            );
        });
    }

    // ── Per-environment env var tests ─────────────────────────────────────────

    #[test]
    fn live_prefixed_vars_resolve() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("LIVE_ALPACA_KEY", Some("live-key")),
                    ("LIVE_ALPACA_SECRET", Some("live-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.key, "live-key");
                    assert_eq!(creds.secret, "live-secret");
                    assert!(matches!(creds.env, AlpacaEnv::Live));
                },
            );
        });
    }

    #[test]
    fn paper_prefixed_vars_resolve() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("PAPER_ALPACA_KEY", Some("paper-key")),
                    ("PAPER_ALPACA_SECRET", Some("paper-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Paper).unwrap();
                    assert_eq!(creds.key, "paper-key");
                    assert_eq!(creds.secret, "paper-secret");
                    assert!(matches!(creds.env, AlpacaEnv::Paper));
                },
            );
        });
    }

    #[test]
    fn unified_vars_take_priority_over_prefixed() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("unified-key")),
                    ("ALPACA_API_SECRET", Some("unified-secret")),
                    ("LIVE_ALPACA_KEY", Some("live-key")),
                    ("LIVE_ALPACA_SECRET", Some("live-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.key, "unified-key");
                    assert_eq!(creds.secret, "unified-secret");
                },
            );
        });
    }

    #[test]
    fn custom_endpoint_from_env_is_used() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("k")),
                    ("ALPACA_API_SECRET", Some("s")),
                    ("LIVE_ALPACA_ENDPOINT", Some("https://custom.example.com")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.endpoint, "https://custom.example.com");
                },
            );
        });
    }

    // ── Empty value filtering ─────────────────────────────────────────────────

    #[test]
    fn empty_unified_key_falls_through_to_prefixed() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("")),
                    ("ALPACA_API_SECRET", Some("secret")),
                    ("LIVE_ALPACA_KEY", Some("live-key")),
                    ("LIVE_ALPACA_SECRET", Some("live-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.key, "live-key");
                },
            );
        });
    }

    #[test]
    fn empty_unified_secret_falls_through_to_prefixed() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("ALPACA_API_KEY", Some("some-key")),
                    ("ALPACA_API_SECRET", Some("")),
                    ("LIVE_ALPACA_KEY", Some("live-key")),
                    ("LIVE_ALPACA_SECRET", Some("live-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Live).unwrap();
                    assert_eq!(creds.key, "live-key");
                },
            );
        });
    }

    #[test]
    fn live_prefixed_vars_not_used_for_paper() {
        with_no_env_creds(|| {
            temp_env::with_vars(
                [
                    ("LIVE_ALPACA_KEY", Some("live-key")),
                    ("LIVE_ALPACA_SECRET", Some("live-secret")),
                    ("PAPER_ALPACA_KEY", Some("paper-key")),
                    ("PAPER_ALPACA_SECRET", Some("paper-secret")),
                ],
                || {
                    let creds = resolve(AlpacaEnv::Paper).unwrap();
                    assert_eq!(creds.key, "paper-key");
                    assert_eq!(creds.secret, "paper-secret");
                },
            );
        });
    }
}