memory-mcp 0.6.0

MCP server for semantic memory — pure-Rust embeddings, vector search, git-backed storage
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
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
829
use std::fmt;

use secrecy::{ExposeSecret, SecretString};
use tracing::{debug, info, warn};

use crate::error::MemoryError;

/// Token resolution order:
/// 1. `MEMORY_MCP_GITHUB_TOKEN` environment variable
/// 2. `~/.config/memory-mcp/token` file
/// 3. System keyring (GNOME Keyring / KWallet / macOS Keychain)
const ENV_VAR: &str = "MEMORY_MCP_GITHUB_TOKEN";
const TOKEN_FILE: &str = ".config/memory-mcp/token";

const GITHUB_CLIENT_ID: &str = "Ov23liWxHYkwXTxCrYHp";
const GITHUB_DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
const GITHUB_ACCESS_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";

// ---------------------------------------------------------------------------
// StoreBackend — where to persist a newly acquired token
// ---------------------------------------------------------------------------

/// Token storage backend selection for `memory-mcp auth login`.
#[derive(Clone, Debug, clap::ValueEnum)]
#[non_exhaustive]
pub enum StoreBackend {
    /// Store token in the system keyring.
    Keyring,
    /// Store token in `~/.config/memory-mcp/token`.
    File,
    /// Print token to stdout and do not persist it.
    Stdout,
    /// Store token as a Kubernetes Secret.
    #[cfg(feature = "k8s")]
    #[clap(name = "k8s-secret")]
    K8sSecret,
}

// ---------------------------------------------------------------------------
// K8sSecretConfig — configuration for Kubernetes Secret storage
// ---------------------------------------------------------------------------

/// Configuration for storing a token as a Kubernetes Secret.
#[cfg(feature = "k8s")]
#[derive(Debug)]
pub struct K8sSecretConfig {
    /// Kubernetes namespace in which to create or update the secret.
    pub namespace: String,
    /// Name of the Kubernetes Secret resource.
    pub secret_name: String,
}

// ---------------------------------------------------------------------------
// TokenSource — tracks which resolution step found the token
// ---------------------------------------------------------------------------

/// Indicates which source produced the resolved token.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TokenSource {
    /// Token was read from the `MEMORY_MCP_GITHUB_TOKEN` environment variable.
    EnvVar,
    /// Token was read from the `~/.config/memory-mcp/token` file.
    File,
    /// Token was read from the system keyring (GNOME Keyring / KWallet / macOS Keychain).
    Keyring,
    /// Token was provided directly via constructor.
    Explicit,
}

impl fmt::Display for TokenSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TokenSource::EnvVar => write!(f, "environment variable ({})", ENV_VAR),
            TokenSource::File => write!(f, "token file (~/.config/memory-mcp/token)"),
            TokenSource::Keyring => write!(f, "system keyring"),
            TokenSource::Explicit => write!(f, "explicit token"),
        }
    }
}

// ---------------------------------------------------------------------------
// Serde structs for OAuth responses
// ---------------------------------------------------------------------------

#[derive(serde::Deserialize)]
struct DeviceCodeResponse {
    device_code: String,
    user_code: String,
    verification_uri: String,
    expires_in: u64,
    interval: u64,
}

#[derive(serde::Deserialize)]
struct AccessTokenResponse {
    #[serde(default)]
    access_token: Option<String>,
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    error_description: Option<String>,
}

// ---------------------------------------------------------------------------
// AuthProvider
// ---------------------------------------------------------------------------

/// Resolves and caches a GitHub personal access token from multiple sources.
pub struct AuthProvider {
    /// Cached token and its source, if resolved at startup.
    token: Option<(SecretString, TokenSource)>,
}

impl AuthProvider {
    /// Create an `AuthProvider`, eagerly attempting token resolution.
    ///
    /// Does not fail if no token is available — some deployments may not
    /// need remote sync. Call [`Self::resolve_token`] when a token is required.
    pub fn new() -> Self {
        let token = Self::try_resolve_with_source().ok();
        if token.is_some() {
            debug!("AuthProvider: token resolved at startup");
        } else {
            debug!("AuthProvider: no token available at startup");
        }
        Self { token }
    }

    /// Resolve a GitHub personal access token, returning it wrapped in
    /// [`SecretString`] so it cannot accidentally appear in logs or error chains.
    ///
    /// Checks (in order):
    /// 1. `MEMORY_MCP_GITHUB_TOKEN` env var
    /// 2. `~/.config/memory-mcp/token` file
    /// 3. System keyring (GNOME Keyring / KWallet / macOS Keychain)
    pub fn resolve_token(&self) -> Result<SecretString, MemoryError> {
        self.resolve_with_source().map(|(tok, _)| tok)
    }

    /// Resolve the token and return which source provided it.
    ///
    /// Like [`resolve_token`](Self::resolve_token), returns the cached token if
    /// one was resolved at startup. Falls back to the resolution chain
    /// (env var → file → keyring) if no cached token exists.
    pub fn resolve_with_source(&self) -> Result<(SecretString, TokenSource), MemoryError> {
        if let Some((ref t, ref s)) = self.token {
            return Ok((t.clone(), s.clone()));
        }
        Self::try_resolve_with_source()
    }

    // -----------------------------------------------------------------------
    // Private helpers
    // -----------------------------------------------------------------------

    /// Resolve the token and return both the raw value and which source provided it.
    fn try_resolve_with_source() -> Result<(SecretString, TokenSource), MemoryError> {
        // 1. Environment variable.
        if let Ok(tok) = std::env::var(ENV_VAR) {
            if !tok.trim().is_empty() {
                return Ok((
                    SecretString::from(tok.trim().to_string()),
                    TokenSource::EnvVar,
                ));
            }
        }

        // 2. Token file.
        if let Some(home) = home_dir() {
            let path = home.join(TOKEN_FILE);
            if path.exists() {
                // Check permissions: warn if the file is world- or group-readable.
                check_token_file_permissions(&path);

                let raw = std::fs::read_to_string(&path)?;
                let tok = raw.trim().to_string();
                if !tok.is_empty() {
                    return Ok((SecretString::from(tok), TokenSource::File));
                }
            }
        }

        // 3. System keyring (GNOME Keyring / KWallet / macOS Keychain).
        match keyring::Entry::new("memory-mcp", "github-token") {
            Ok(entry) => match entry.get_password() {
                Ok(tok) if !tok.trim().is_empty() => {
                    info!("resolved GitHub token from system keyring");
                    return Ok((
                        SecretString::from(tok.trim().to_string()),
                        TokenSource::Keyring,
                    ));
                }
                Ok(_) => { /* empty password stored — fall through */ }
                Err(keyring::Error::NoEntry) => { /* no entry — fall through */ }
                Err(keyring::Error::NoStorageAccess(_)) => {
                    debug!("keyring: no storage backend available (headless?)");
                }
                Err(e) => {
                    warn!("keyring: unexpected error: {e}");
                }
            },
            Err(e) => {
                debug!("keyring: could not create entry: {e}");
            }
        }

        Err(MemoryError::Auth(
            "no token available; set MEMORY_MCP_GITHUB_TOKEN, add \
             ~/.config/memory-mcp/token, or store a token in the system keyring \
             under service 'memory-mcp', account 'github-token'."
                .to_string(),
        ))
    }
}

impl AuthProvider {
    /// Create an `AuthProvider` with a pre-set token.
    ///
    /// Use this when you already have a token from your own auth flow
    /// and want to skip the built-in resolution chain (env var → file → keyring).
    pub fn with_token(token: &str) -> Self {
        Self {
            token: Some((SecretString::from(token.to_string()), TokenSource::Explicit)),
        }
    }
}

impl Default for AuthProvider {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Device flow login
// ---------------------------------------------------------------------------

/// Authenticate with GitHub via the OAuth device flow and persist the token.
///
/// Prints user-facing prompts to stderr. Never logs the token value.
pub async fn device_flow_login(
    store: Option<StoreBackend>,
    #[cfg(feature = "k8s")] k8s_config: Option<K8sSecretConfig>,
) -> Result<(), MemoryError> {
    use std::time::{Duration, Instant};
    use tokio::time::sleep;

    let client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(10))
        .timeout(Duration::from_secs(30))
        .build()
        .map_err(|e| MemoryError::OAuth(format!("failed to build HTTP client: {e}")))?;

    // Step 1: Request a device code.
    let device_resp = client
        .post(GITHUB_DEVICE_CODE_URL)
        .header("Accept", "application/json")
        .form(&[("client_id", GITHUB_CLIENT_ID), ("scope", "repo")])
        .send()
        .await
        .map_err(|e| {
            MemoryError::OAuth(format!(
                "failed to contact GitHub device code endpoint: {e}"
            ))
        })?
        .error_for_status()
        .map_err(|e| MemoryError::OAuth(format!("GitHub device code request failed: {e}")))?
        .json::<DeviceCodeResponse>()
        .await
        .map_err(|e| MemoryError::OAuth(format!("failed to parse device code response: {e}")))?;

    // Compute overall deadline from expires_in, capped at 30 minutes to guard
    // against a compromised response setting an excessively long expiry.
    let expires_in = device_resp.expires_in.min(1800);
    let deadline = Instant::now() + Duration::from_secs(expires_in);

    // Step 2: Display instructions to the user.
    eprintln!();
    eprintln!("  Open this URL in your browser:");
    eprintln!("    {}", device_resp.verification_uri);
    eprintln!();
    eprintln!("  Enter this code when prompted:");
    eprintln!("    {}", device_resp.user_code);
    eprintln!();
    eprintln!("  Waiting for authorization...");

    // Step 3: Poll for the access token.
    let mut poll_interval = device_resp.interval.clamp(1, 30);
    let token = loop {
        if Instant::now() >= deadline {
            return Err(MemoryError::OAuth(format!(
                "Device code expired after {expires_in} seconds"
            )));
        }

        sleep(Duration::from_secs(poll_interval)).await;

        let resp = client
            .post(GITHUB_ACCESS_TOKEN_URL)
            .header("Accept", "application/json")
            .form(&[
                ("client_id", GITHUB_CLIENT_ID),
                ("device_code", &device_resp.device_code),
                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
            ])
            .send()
            .await
            .map_err(|e| MemoryError::OAuth(format!("polling GitHub token endpoint failed: {e}")))?
            .error_for_status()
            .map_err(|e| {
                MemoryError::OAuth(format!("GitHub token request returned error status: {e}"))
            })?
            .json::<AccessTokenResponse>()
            .await
            .map_err(|e| MemoryError::OAuth(format!("failed to parse token response: {e}")))?;

        if let Some(tok) = resp.access_token.filter(|t| !t.trim().is_empty()) {
            break SecretString::from(tok);
        }

        match resp.error.as_deref() {
            Some("authorization_pending") => {
                // Normal — user has not yet approved; keep polling.
                continue;
            }
            Some("slow_down") => {
                // GitHub asked us to back off; add 5 s to interval, capped at 60 s.
                poll_interval = (poll_interval + 5).min(60);
                continue;
            }
            Some("expired_token") => {
                return Err(MemoryError::OAuth(
                    "device code expired; please run `memory-mcp auth login` again".to_string(),
                ));
            }
            Some("access_denied") => {
                return Err(MemoryError::OAuth(
                    "authorization denied by user".to_string(),
                ));
            }
            Some(other) => {
                let desc = resp
                    .error_description
                    .as_deref()
                    .unwrap_or("no description");
                return Err(MemoryError::OAuth(format!(
                    "unexpected OAuth error '{other}': {desc}"
                )));
            }
            None => {
                return Err(MemoryError::OAuth(
                    "GitHub returned neither an access_token nor an error field; \
                     unexpected response"
                        .to_string(),
                ));
            }
        }
    };

    // Step 4: Store the token.
    store_token(
        &token,
        store,
        #[cfg(feature = "k8s")]
        k8s_config,
    )
    .await?;
    eprintln!("Authentication successful.");

    Ok(())
}

// ---------------------------------------------------------------------------
// Token storage
// ---------------------------------------------------------------------------

/// Persist a token via the specified backend.
///
/// Never logs the token value — only the chosen storage destination.
async fn store_token(
    token: &SecretString,
    backend: Option<StoreBackend>,
    #[cfg(feature = "k8s")] k8s_config: Option<K8sSecretConfig>,
) -> Result<(), MemoryError> {
    match backend {
        Some(StoreBackend::Stdout) => {
            println!("{}", token.expose_secret());
            debug!("token written to stdout");
        }
        Some(StoreBackend::Keyring) => {
            store_in_keyring(token.expose_secret())?;
        }
        Some(StoreBackend::File) => {
            store_in_file(token.expose_secret())?;
        }
        #[cfg(feature = "k8s")]
        Some(StoreBackend::K8sSecret) => {
            let config = k8s_config.ok_or_else(|| {
                MemoryError::TokenStorage(
                    "k8s-secret backend requires namespace and secret name".into(),
                )
            })?;
            store_in_k8s_secret(token.expose_secret(), &config).await?;
        }
        None => {
            // No --store flag: try keyring ONLY. Do NOT fall back to file.
            store_in_keyring(token.expose_secret()).map_err(|e| {
                MemoryError::TokenStorage(format!(
                    "Keyring unavailable: {e}. Use --store file to write to \
                     ~/.config/memory-mcp/token, --store stdout to print the token\
                     {k8s_hint}.",
                    k8s_hint = if cfg!(feature = "k8s") {
                        ", or --store k8s-secret to store in a Kubernetes Secret"
                    } else {
                        ""
                    }
                ))
            })?;
        }
    }
    Ok(())
}

fn store_in_keyring(token: &str) -> Result<(), MemoryError> {
    let entry = keyring::Entry::new("memory-mcp", "github-token")
        .map_err(|e| MemoryError::TokenStorage(format!("failed to create keyring entry: {e}")))?;
    entry
        .set_password(token)
        .map_err(|e| MemoryError::TokenStorage(format!("failed to store token in keyring: {e}")))?;
    info!("token stored in system keyring");
    Ok(())
}

fn store_in_file(token: &str) -> Result<(), MemoryError> {
    let home =
        home_dir().ok_or_else(|| MemoryError::TokenStorage("HOME directory is not set".into()))?;
    let token_path = home.join(TOKEN_FILE);

    if let Some(parent) = token_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            MemoryError::TokenStorage(format!(
                "failed to create config directory {}: {e}",
                parent.display()
            ))
        })?;

        // Set config directory to 0700 on Unix.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).map_err(
                |e| {
                    MemoryError::TokenStorage(format!(
                        "failed to set config directory permissions: {e}"
                    ))
                },
            )?;
        }
    }

    // Write to a temporary file in the same directory, then rename into place.
    // This ensures the token file is never left in a truncated state on crash,
    // and the 0600 mode is set before any content is written.
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let parent = token_path.parent().expect("token_path always has a parent");
        let tmp_path = parent.join(".token.tmp");
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&tmp_path)
            .map_err(|e| {
                MemoryError::TokenStorage(format!("failed to open temp token file: {e}"))
            })?;
        f.write_all(token.as_bytes()).map_err(|e| {
            MemoryError::TokenStorage(format!("failed to write temp token file: {e}"))
        })?;
        f.write_all(b"\n").map_err(|e| {
            MemoryError::TokenStorage(format!("failed to write temp token file: {e}"))
        })?;
        f.sync_all().map_err(|e| {
            MemoryError::TokenStorage(format!("failed to sync temp token file: {e}"))
        })?;
        drop(f);
        std::fs::rename(&tmp_path, &token_path).map_err(|e| {
            MemoryError::TokenStorage(format!("failed to rename token file into place: {e}"))
        })?;
    }
    #[cfg(not(unix))]
    {
        std::fs::write(&token_path, format!("{token}\n"))
            .map_err(|e| MemoryError::TokenStorage(format!("failed to write token file: {e}")))?;
    }

    info!("token stored in file ({})", token_path.display());
    Ok(())
}

// ---------------------------------------------------------------------------
// Kubernetes Secret storage (k8s feature)
// ---------------------------------------------------------------------------

#[cfg(feature = "k8s")]
async fn store_in_k8s_secret(token: &str, config: &K8sSecretConfig) -> Result<(), MemoryError> {
    use k8s_openapi::api::core::v1::Secret;
    use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
    use kube::{api::PostParams, Api, Client};
    use std::collections::BTreeMap;

    let client = Client::try_default().await.map_err(|e| {
        MemoryError::TokenStorage(format!(
            "Failed to initialize Kubernetes client. Ensure KUBECONFIG is set \
             or the pod has a service account: {e}"
        ))
    })?;

    let secrets: Api<Secret> = Api::namespaced(client, &config.namespace);
    let secret_name = &config.secret_name;

    let mut data = BTreeMap::new();
    data.insert(
        "token".to_string(),
        k8s_openapi::ByteString(token.as_bytes().to_vec()),
    );

    let mut labels = BTreeMap::new();
    labels.insert(
        "app.kubernetes.io/managed-by".to_string(),
        "memory-mcp".to_string(),
    );
    labels.insert(
        "app.kubernetes.io/component".to_string(),
        "auth".to_string(),
    );

    let mut secret = Secret {
        metadata: ObjectMeta {
            name: Some(secret_name.clone()),
            namespace: Some(config.namespace.clone()),
            labels: Some(labels),
            ..Default::default()
        },
        data: Some(data),
        type_: Some("Opaque".to_string()),
        ..Default::default()
    };

    // Create-first: attempt to create the secret; on 409 AlreadyExists, GET to
    // fetch the current resourceVersion and replace. This avoids the TOCTOU
    // race inherent in a GET-then-create/replace approach.
    match secrets.create(&PostParams::default(), &secret).await {
        Ok(_) => {
            debug!(
                "created Kubernetes Secret '{secret_name}' in namespace '{}'",
                config.namespace
            );
        }
        Err(kube::Error::Api(ref err_resp)) if err_resp.code == 409 => {
            // Secret already exists; fetch resourceVersion then replace.
            let existing = secrets
                .get(secret_name)
                .await
                .map_err(|e| map_kube_error(e, &config.namespace))?;
            secret.metadata.resource_version = existing.metadata.resource_version;
            secrets
                .replace(secret_name, &PostParams::default(), &secret)
                .await
                .map_err(|e| map_kube_error(e, &config.namespace))?;
            debug!(
                "updated Kubernetes Secret '{secret_name}' in namespace '{}'",
                config.namespace
            );
        }
        Err(e) => {
            return Err(map_kube_error(e, &config.namespace));
        }
    }

    eprintln!(
        "Token stored in Kubernetes Secret '{secret_name}' (namespace: {})",
        config.namespace
    );
    Ok(())
}

#[cfg(feature = "k8s")]
fn map_kube_error(e: kube::Error, namespace: &str) -> MemoryError {
    match &e {
        kube::Error::Api(err_resp) if err_resp.code == 403 => MemoryError::TokenStorage(format!(
            "Access denied. Ensure the service account has RBAC permission \
                 for secrets in namespace '{namespace}': {e}"
        )),
        kube::Error::Api(err_resp) if err_resp.code == 404 => {
            MemoryError::TokenStorage(format!("Namespace '{namespace}' does not exist: {e}"))
        }
        _ => MemoryError::TokenStorage(format!("Kubernetes API error: {e}")),
    }
}

// ---------------------------------------------------------------------------
// Auth status
// ---------------------------------------------------------------------------

/// Print the current authentication status to stdout.
///
/// Shows the source of the resolved token and a redacted preview.
/// Never prints the full token value.
pub fn print_auth_status(provider: &AuthProvider) {
    match provider.resolve_with_source() {
        Ok((token, source)) => {
            let raw = token.expose_secret();
            let preview = if raw.len() >= 8 {
                format!("...{}", &raw[raw.len() - 4..])
            } else {
                "****".to_string()
            };
            println!("Authenticated via {source}");
            println!("Token: {preview}");
        }
        Err(_) => {
            println!("No token configured.");
            println!("Run `memory-mcp auth login` to authenticate with GitHub.");
        }
    }
}

// ---------------------------------------------------------------------------
// Permission check (Unix only)
// ---------------------------------------------------------------------------

/// Warn if the token file has permissions that are wider than 0o600.
fn check_token_file_permissions(path: &std::path::Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        match std::fs::metadata(path) {
            Ok(meta) => {
                let mode = meta.mode() & 0o777;
                if mode != 0o600 {
                    warn!(
                        "token file '{}' has permissions {:04o}; \
                         expected 0600 — consider running: chmod 600 {}",
                        path.display(),
                        mode,
                        path.display()
                    );
                }
            }
            Err(e) => {
                warn!("could not read permissions for '{}': {}", path.display(), e);
            }
        }
    }
    // On non-Unix platforms there are no POSIX permissions to check.
    #[cfg(not(unix))]
    let _ = path;
}

// ---------------------------------------------------------------------------
// Platform-portable home directory helper
// ---------------------------------------------------------------------------

/// Returns the user's home directory using the platform-native mechanism.
///
/// Delegates to [`dirs::home_dir`], which checks `HOME` on Unix and the
/// Windows profile directory on Windows — no deprecated `std::env::home_dir`.
pub fn home_dir() -> Option<std::path::PathBuf> {
    dirs::home_dir()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;

    // Serialise all tests that mutate environment variables so they don't race
    // under `cargo test` (which runs tests in parallel by default).
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn test_resolve_from_env_var() {
        let _guard = ENV_LOCK.lock().unwrap();
        let token_value = "ghp_test_env_token_abc123";
        std::env::set_var(ENV_VAR, token_value);
        let result = AuthProvider::try_resolve_with_source().map(|(tok, _)| tok);
        std::env::remove_var(ENV_VAR);

        assert!(result.is_ok(), "expected Ok but got: {result:?}");
        assert_eq!(result.unwrap().expose_secret(), token_value);
    }

    #[test]
    fn test_resolve_trims_env_var_whitespace() {
        let _guard = ENV_LOCK.lock().unwrap();
        let token_value = "  ghp_padded_token  ";
        std::env::set_var(ENV_VAR, token_value);
        let result = AuthProvider::try_resolve_with_source().map(|(tok, _)| tok);
        std::env::remove_var(ENV_VAR);

        assert!(result.is_ok());
        assert_eq!(result.unwrap().expose_secret(), token_value.trim());
    }

    #[test]
    fn test_resolve_prefers_env_over_file() {
        let _guard = ENV_LOCK.lock().unwrap();
        // Write a token file and simultaneously set the env var; env must win.
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("token");
        std::fs::write(&file_path, "ghp_file_token").unwrap();

        let env_token = "ghp_env_wins";
        std::env::set_var(ENV_VAR, env_token);

        // Override HOME so the file lookup would pick up our temp file if env
        // were not consulted first.  We rely on env taking precedence, so
        // this primarily tests ordering rather than actual file resolution.
        let result = AuthProvider::try_resolve_with_source().map(|(tok, _)| tok);
        std::env::remove_var(ENV_VAR);

        assert!(result.is_ok());
        assert_eq!(result.unwrap().expose_secret(), env_token);
    }

    #[test]
    fn test_try_resolve_with_source_returns_env_var_source() {
        let _guard = ENV_LOCK.lock().unwrap();
        let token_value = "ghp_source_test_abc";
        std::env::set_var(ENV_VAR, token_value);
        let result = AuthProvider::try_resolve_with_source();
        std::env::remove_var(ENV_VAR);

        assert!(result.is_ok(), "expected Ok but got: {result:?}");
        let (tok, source) = result.unwrap();
        assert_eq!(tok.expose_secret(), token_value);
        assert!(
            matches!(source, TokenSource::EnvVar),
            "expected TokenSource::EnvVar, got: {source:?}"
        );
    }

    #[test]
    fn test_store_token_file_backend() {
        let dir = tempfile::tempdir().unwrap();
        let token_dir = dir.path().join(".config").join("memory-mcp");
        let token_path = token_dir.join("token");

        // Temporarily override HOME.
        let _guard = ENV_LOCK.lock().unwrap();
        let original_home = std::env::var("HOME").ok();
        std::env::set_var("HOME", dir.path());

        let result = store_in_file("ghp_file_backend_test");

        // Restore HOME before asserting so other tests aren't affected.
        match original_home {
            Some(h) => std::env::set_var("HOME", h),
            None => std::env::remove_var("HOME"),
        }

        assert!(result.is_ok(), "store_in_file failed: {result:?}");
        assert!(token_path.exists(), "token file was not created");

        let content = std::fs::read_to_string(&token_path).unwrap();
        assert_eq!(content, "ghp_file_backend_test\n");

        // Verify 0o600 permissions on Unix.
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            let mode = std::fs::metadata(&token_path).unwrap().mode() & 0o777;
            assert_eq!(mode, 0o600, "expected 0600 permissions, got {:04o}", mode);
        }
    }

    /// This test exercises the keyring path and requires a live D-Bus /
    /// secret-service backend.  Mark it `#[ignore]` so it does not run in CI.
    #[test]
    #[ignore = "requires live system keyring (D-Bus/GNOME Keyring/KWallet)"]
    fn test_resolve_from_keyring_ignored_in_ci() {
        let _guard = ENV_LOCK.lock().unwrap();
        // Pre-condition: no env var, no token file (rely on absence).
        std::env::remove_var(ENV_VAR);

        // Attempt to store then retrieve; if the keyring is unavailable the
        // test is inconclusive rather than failing.
        let entry = keyring::Entry::new("memory-mcp", "github-token")
            .expect("keyring entry creation should succeed");
        let test_token = "ghp_keyring_test_token";
        entry
            .set_password(test_token)
            .expect("storing token should succeed");

        let result = AuthProvider::try_resolve_with_source().map(|(tok, _)| tok);
        let _ = entry.delete_credential(); // cleanup before assert
        assert!(result.is_ok(), "expected token from keyring: {result:?}");
        assert_eq!(result.unwrap().expose_secret(), test_token);
    }

    /// Device flow requires real GitHub interaction — skip in CI.
    #[tokio::test]
    #[ignore = "requires real GitHub OAuth interaction"]
    async fn test_device_flow_login_ignored_in_ci() {
        device_flow_login(
            Some(StoreBackend::Stdout),
            #[cfg(feature = "k8s")]
            None,
        )
        .await
        .expect("device flow should succeed");
    }

    #[cfg(feature = "k8s")]
    #[test]
    #[ignore] // Requires a real Kubernetes cluster
    fn test_store_in_k8s_secret_ignored_in_ci() {
        // Placeholder for manual/integration testing
    }
}