omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! Atlassian credential management.
//!
//! Loads and saves Atlassian Basic and Bearer credentials from/to the
//! `~/.omni-dev/settings.json` file — the active profile's `env` map when a
//! profile is selected, the base `env` map otherwise (issue #1116).

use anyhow::Result;
use serde::Serialize;

use crate::atlassian::error::AtlassianError;
use crate::utils::env::{EnvSource, SystemEnv};
use crate::utils::secret::Secret;
use crate::utils::secret_env::{secret_var, secret_var_is_set};
use crate::utils::settings::{active_profile_from, Settings};

/// Environment variable / settings key for the Atlassian instance URL.
pub const ATLASSIAN_INSTANCE_URL: &str = "ATLASSIAN_INSTANCE_URL";

/// Environment variable / settings key for the Atlassian user email.
pub const ATLASSIAN_EMAIL: &str = "ATLASSIAN_EMAIL";

/// Environment variable / settings key for the Atlassian API token.
pub const ATLASSIAN_API_TOKEN: &str = "ATLASSIAN_API_TOKEN";

/// Environment variable that overrides the Atlassian instance URL.
///
/// Applies to **every** JIRA/Confluence command. Set by the `--instance` flag
/// via [`crate::cli::atlassian::InstanceArg::apply`]; takes precedence
/// over `ATLASSIAN_INSTANCE_URL` / settings.json. A caller-supplied override
/// (e.g. via [`load_credentials_with_instance`]) still wins over it.
pub const ATLASSIAN_INSTANCE_OVERRIDE_ENV: &str = "OMNI_DEV_ATLASSIAN_INSTANCE";

/// Environment variable / settings key for a Server/Data Center PAT.
pub const ATLASSIAN_PAT: &str = "ATLASSIAN_PAT";

/// Authentication credentials; secret values are redacted in Debug output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AtlassianAuth {
    /// Cloud Basic authentication.
    Basic {
        /// Account email.
        email: String,
        /// Cloud API token.
        api_token: Secret,
    },
    /// Server/Data Center Personal Access Token authentication.
    Bearer {
        /// Personal Access Token.
        token: Secret,
    },
}

/// Non-secret authentication mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, clap::ValueEnum, Default)]
#[serde(rename_all = "snake_case")]
pub enum AuthMode {
    /// Email and API token.
    #[default]
    Basic,
    /// Personal Access Token without email.
    Bearer,
}

impl AtlassianAuth {
    /// Returns the authentication mode without exposing credentials.
    #[must_use]
    pub const fn mode(&self) -> AuthMode {
        match self {
            Self::Basic { .. } => AuthMode::Basic,
            Self::Bearer { .. } => AuthMode::Bearer,
        }
    }

    /// Validates required fields without printing their contents.
    pub(crate) fn validate(&self) -> Result<()> {
        let token = match self {
            Self::Basic { email, api_token } => {
                if email.trim().is_empty() {
                    anyhow::bail!("ATLASSIAN_EMAIL is required for Basic authentication");
                }
                api_token.expose_secret()
            }
            Self::Bearer { token } => token.expose_secret(),
        };
        if token.trim().is_empty() {
            anyhow::bail!("Atlassian token must not be blank");
        }
        if token.chars().any(char::is_control) {
            anyhow::bail!("Atlassian token contains invalid control characters");
        }
        Ok(())
    }
}

/// Atlassian credentials for one instance.
#[derive(Debug, Clone)]
pub struct AtlassianCredentials {
    /// Base URL, including any self-hosted context path.
    pub instance_url: String,
    /// Selected authentication credentials.
    pub auth: AtlassianAuth,
}

/// Loads Atlassian credentials from environment variables or settings.json.
///
/// Checks environment variables first, then falls back to the settings file.
/// The `--instance` flag (propagated to [`ATLASSIAN_INSTANCE_OVERRIDE_ENV`])
/// overrides the configured instance URL for every command; a blank value is
/// ignored. Callers that carry their own explicit override should call
/// [`load_credentials_with_instance`] directly.
pub fn load_credentials() -> Result<AtlassianCredentials> {
    let env_override = std::env::var(ATLASSIAN_INSTANCE_OVERRIDE_ENV)
        .ok()
        .filter(|s| !s.trim().is_empty());
    load_credentials_with_instance(env_override.as_deref())
}

/// Loads Atlassian credentials, optionally overriding the instance URL.
///
/// When `instance_override` is `Some`, that URL is used verbatim (after
/// trailing-slash normalization) and the `ATLASSIAN_INSTANCE_URL` env /
/// settings lookup is skipped — so a caller-supplied instance (e.g.
/// `jira create --instance`) works even when no instance is configured in the
/// environment. Authentication requires either email/API token or a PAT.
/// When `None`, behaves exactly like [`load_credentials`].
pub fn load_credentials_with_instance(
    instance_override: Option<&str>,
) -> Result<AtlassianCredentials> {
    let settings = Settings::load_or_warn_default();

    load_credentials_from(&settings.env_source(), instance_override)
}

/// Resolves credentials through an injected layered environment source.
pub(crate) fn load_credentials_from(
    env: &impl EnvSource,
    instance_override: Option<&str>,
) -> Result<AtlassianCredentials> {
    let scope = scope_status_from(env);
    if scope.configuration_state == ConfigurationState::Conflict {
        anyhow::bail!(
            "ATLASSIAN_PAT and ATLASSIAN_API_TOKEN conflict; configure only one token source"
        );
    }
    let instance_url = instance_override
        .map(str::to_owned)
        .or(scope.instance_url)
        .filter(|v| !v.trim().is_empty())
        .ok_or(AtlassianError::CredentialsNotFound)?;
    let auth = if scope.has_pat {
        AtlassianAuth::Bearer {
            token: secret_var(env, ATLASSIAN_PAT)?.ok_or(AtlassianError::CredentialsNotFound)?,
        }
    } else {
        AtlassianAuth::Basic {
            email: env
                .var(ATLASSIAN_EMAIL)
                .filter(|v| !v.trim().is_empty())
                .ok_or(AtlassianError::CredentialsNotFound)?,
            api_token: secret_var(env, ATLASSIAN_API_TOKEN)?
                .ok_or(AtlassianError::CredentialsNotFound)?,
        }
    };
    auth.validate()?;
    Ok(AtlassianCredentials {
        instance_url: instance_url.trim_end_matches('/').to_string(),
        auth,
    })
}

/// Configuration presence, without resolving or authenticating secrets.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ConfigurationState {
    /// No authentication keys are present.
    Missing,
    /// Required configuration is absent.
    Incomplete,
    /// Required configuration is present; not remotely validated.
    Configured,
    /// Both authentication token sources are configured.
    Conflict,
}

/// Summary of a single Atlassian credential scope.
///
/// Reports which credential keys are present without exposing their values.
/// Safe to serialize and return over the MCP surface.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct AtlassianScopeStatus {
    /// Scope name (currently always `"default"`; forward-compatible for
    /// per-instance scopes).
    pub name: String,
    /// Whether [`ATLASSIAN_EMAIL`] is present.
    pub has_email: bool,
    /// Whether [`ATLASSIAN_API_TOKEN`] is present. Token value is never exposed.
    pub has_token: bool,
    /// Whether a PAT source is present, without resolving it.
    pub has_pat: bool,
    /// Unambiguous selected authentication mode, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_mode: Option<AuthMode>,
    /// Presence classification; never a claim of authentication success.
    pub configuration_state: ConfigurationState,
    /// Value of [`ATLASSIAN_INSTANCE_URL`] when set. The URL is considered
    /// non-secret; returning it helps the assistant surface which instance
    /// a scope targets without exposing credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance_url: Option<String>,
}

/// Aggregate credential status across every known Atlassian scope.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct AuthStatus {
    /// One entry per scope. Currently a single default scope; kept as a list
    /// so future multi-instance support does not require a schema change.
    pub scopes: Vec<AtlassianScopeStatus>,
}

/// Builds an [`AuthStatus`] from the current settings / environment.
///
/// Reports credential presence without leaking any secret values.
/// [`AtlassianScopeStatus::instance_url`] is returned verbatim when set —
/// URLs are explicitly non-secret; tokens and emails are flagged as booleans
/// only. Safe to call with no credentials configured (returns a scope with
/// every flag `false`).
pub fn status() -> AuthStatus {
    let settings = Settings::load_or_warn_default();

    status_from(&settings.env_source())
}

/// Reports presence through an injected source, without resolving secrets.
pub(crate) fn status_from(env: &impl EnvSource) -> AuthStatus {
    AuthStatus {
        scopes: vec![scope_status_from(env)],
    }
}

/// Classifies credential presence without reading files or executing helpers.
fn scope_status_from(env: &impl EnvSource) -> AtlassianScopeStatus {
    let instance_url = env
        .var(ATLASSIAN_INSTANCE_URL)
        .filter(|v| !v.trim().is_empty())
        .map(|v| v.trim_end_matches('/').to_string());
    let has_email = env
        .var(ATLASSIAN_EMAIL)
        .is_some_and(|v| !v.trim().is_empty());
    let has_token = secret_var_is_set(env, ATLASSIAN_API_TOKEN);
    let has_pat = secret_var_is_set(env, ATLASSIAN_PAT);
    let auth_mode = match (has_token, has_pat) {
        (true, false) => Some(AuthMode::Basic),
        (false, true) => Some(AuthMode::Bearer),
        _ => None,
    };
    let configuration_state = if has_token && has_pat {
        ConfigurationState::Conflict
    } else if (has_pat || (has_token && has_email)) && instance_url.is_some() {
        ConfigurationState::Configured
    } else if !has_email && !has_token && !has_pat && instance_url.is_none() {
        ConfigurationState::Missing
    } else {
        ConfigurationState::Incomplete
    };
    AtlassianScopeStatus {
        name: "default".to_string(),
        has_email,
        has_token,
        has_pat,
        auth_mode,
        configuration_state,
        instance_url,
    }
}

/// Saves Atlassian credentials to `~/.omni-dev/settings.json`.
///
/// Reads the existing settings file, merges the new credential keys into
/// the active profile's `env` map (the base `env` when no profile is active
/// — issue #1116), and writes back. Preserves all other settings.
pub fn save_credentials(credentials: &AtlassianCredentials) -> Result<()> {
    save_credentials_to(
        &Settings::get_settings_path()?,
        active_profile_from(&SystemEnv).as_deref(),
        credentials,
    )
}

/// [`save_credentials`], writing to an explicit settings-file path and env
/// map (`profiles.<name>.env` when `profile` is `Some`, base `env` otherwise).
///
/// Tests inject a tempdir path and an explicit profile instead of mutating
/// `HOME` / `OMNI_DEV_PROFILE` (issue #1030).
pub(crate) fn save_credentials_to(
    settings_path: &std::path::Path,
    profile: Option<&str>,
    credentials: &AtlassianCredentials,
) -> Result<()> {
    credentials.auth.validate()?;
    if credentials.instance_url.trim().is_empty() {
        anyhow::bail!("Instance URL is required");
    }
    let mut vars = vec![(ATLASSIAN_INSTANCE_URL, credentials.instance_url.as_str())];
    let remove = match &credentials.auth {
        AtlassianAuth::Basic { email, api_token } => {
            vars.extend([
                (ATLASSIAN_EMAIL, email.as_str()),
                (ATLASSIAN_API_TOKEN, api_token.expose_secret()),
            ]);
            vec![ATLASSIAN_PAT]
        }
        AtlassianAuth::Bearer { token } => {
            vars.push((ATLASSIAN_PAT, token.expose_secret()));
            vec![ATLASSIAN_EMAIL, ATLASSIAN_API_TOKEN]
        }
    };
    Settings::replace_env_vars_in(settings_path, profile, &vars, &remove)
}

/// Removes Atlassian credential keys from `~/.omni-dev/settings.json` — from
/// the active profile's `env` map when a profile is active, the base `env`
/// otherwise (issue #1116).
///
/// Leaves all other settings intact. Returns `true` if any Atlassian key was
/// present and removed, `false` when the targeted map was already free of
/// them (or the file did not exist).
pub fn remove_credentials() -> Result<bool> {
    remove_credentials_at(
        &Settings::get_settings_path()?,
        active_profile_from(&SystemEnv).as_deref(),
    )
}

/// [`remove_credentials`], operating on an explicit settings-file path and
/// env map (`profiles.<name>.env` when `profile` is `Some`, base `env`
/// otherwise).
///
/// Tests inject a tempdir path and an explicit profile instead of mutating
/// `HOME` / `OMNI_DEV_PROFILE` (issue #1030).
pub(crate) fn remove_credentials_at(
    settings_path: &std::path::Path,
    profile: Option<&str>,
) -> Result<bool> {
    Settings::remove_env_vars_in(
        settings_path,
        profile,
        &[
            ATLASSIAN_INSTANCE_URL,
            ATLASSIAN_EMAIL,
            ATLASSIAN_API_TOKEN,
            ATLASSIAN_PAT,
        ],
    )
}

/// Crate-internal test utilities for code that calls [`load_credentials`] /
/// [`crate::cli::atlassian::helpers::create_client`]. Lives here because it
/// needs the credential constants and shares process-wide env state with
/// auth.rs's own tests — every consumer must serialise on
/// [`AUTH_ENV_MUTEX`] to avoid racing.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
pub(crate) mod test_util {
    use super::{
        ATLASSIAN_API_TOKEN, ATLASSIAN_EMAIL, ATLASSIAN_INSTANCE_OVERRIDE_ENV,
        ATLASSIAN_INSTANCE_URL, ATLASSIAN_PAT,
    };
    use crate::utils::settings::PROFILE_ENV_VAR;

    /// Mutex shared by every test that mutates `HOME`, `OMNI_DEV_PROFILE`, or
    /// the Atlassian credential env vars. Serialises those tests against each
    /// other so parallel execution doesn't race on process-wide env state.
    ///
    /// Aliases the crate-wide [`crate::test_support::HOME_ENV_MUTEX`] rather
    /// than declaring its own `Mutex<()>`, so Atlassian's HOME mutation also
    /// serialises against every other domain's (Datadog, Gmail, …) — see
    /// that static's doc comment for why an independent mutex here provides
    /// no real exclusion.
    pub(crate) static AUTH_ENV_MUTEX: &std::sync::Mutex<()> = &crate::test_support::HOME_ENV_MUTEX;

    /// RAII guard: snapshots `HOME`, `OMNI_DEV_PROFILE`, and every Atlassian
    /// credential env var on construction and restores them on drop.
    /// Concentrating the save/restore branches into one place (here) instead
    /// of inlining them in each test keeps coverage high — every test
    /// exercises the same guard drop path.
    pub(crate) struct EnvGuard {
        _lock: std::sync::MutexGuard<'static, ()>,
        snapshot: Vec<(&'static str, Option<String>)>,
    }

    impl EnvGuard {
        pub(crate) fn take() -> Self {
            let lock = AUTH_ENV_MUTEX
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let keys = [
                "HOME",
                PROFILE_ENV_VAR,
                ATLASSIAN_INSTANCE_URL,
                ATLASSIAN_INSTANCE_OVERRIDE_ENV,
                ATLASSIAN_EMAIL,
                ATLASSIAN_API_TOKEN,
                ATLASSIAN_PAT,
            ];
            let snapshot = keys
                .into_iter()
                .map(|k| (k, std::env::var(k).ok()))
                .collect();
            Self {
                _lock: lock,
                snapshot,
            }
        }

        /// Clears the three Atlassian credential env vars plus
        /// `OMNI_DEV_PROFILE` and points `HOME` at a fresh empty tempdir so
        /// `load_credentials()` returns `CredentialsNotFound` and settings
        /// writes target the base `env` map. Useful for testing the Err
        /// propagation path of code that calls `create_client()` and the
        /// `HOME`-resolving credential-write wrappers.
        pub(crate) fn clear_credentials(&self) -> tempfile::TempDir {
            let dir = {
                std::fs::create_dir_all("tmp").ok();
                tempfile::TempDir::new_in("tmp").unwrap()
            };
            std::env::set_var("HOME", dir.path());
            std::env::remove_var(PROFILE_ENV_VAR);
            std::env::remove_var(ATLASSIAN_INSTANCE_URL);
            std::env::remove_var(ATLASSIAN_INSTANCE_OVERRIDE_ENV);
            std::env::remove_var(ATLASSIAN_EMAIL);
            std::env::remove_var(ATLASSIAN_API_TOKEN);
            std::env::remove_var(ATLASSIAN_PAT);
            dir
        }

        /// Sets the three Atlassian credential env vars to point at a wiremock
        /// (or any HTTP) endpoint. The matching `HOME` is replaced with a
        /// fresh tempdir so any `~/.omni-dev/settings.json` on the developer's
        /// machine does not bleed in.
        pub(crate) fn set_credentials(&self, instance_url: &str) -> tempfile::TempDir {
            let dir = {
                std::fs::create_dir_all("tmp").ok();
                tempfile::TempDir::new_in("tmp").unwrap()
            };
            std::env::set_var("HOME", dir.path());
            std::env::set_var(ATLASSIAN_INSTANCE_URL, instance_url);
            std::env::set_var(ATLASSIAN_EMAIL, "test@example.com");
            std::env::set_var(ATLASSIAN_API_TOKEN, "test-token");
            std::env::remove_var(ATLASSIAN_PAT);
            dir
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (k, v) in &self.snapshot {
                match v {
                    Some(val) => std::env::set_var(k, val),
                    None => std::env::remove_var(k),
                }
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use std::fs;

    use super::*;

    #[test]
    fn save_and_read_credentials() {
        let temp_dir = {
            std::fs::create_dir_all("tmp").ok();
            tempfile::TempDir::new_in("tmp").unwrap()
        };
        let settings_path = temp_dir.path().join("settings.json");

        // Start with existing settings
        let existing = r#"{"env": {"SOME_KEY": "value"}}"#;
        fs::write(&settings_path, existing).unwrap();

        // Read it back as a value, add credentials, write
        let content = fs::read_to_string(&settings_path).unwrap();
        let mut val: serde_json::Value = serde_json::from_str(&content).unwrap();
        val["env"]["ATLASSIAN_INSTANCE_URL"] =
            serde_json::Value::String("https://test.atlassian.net".to_string());
        val["env"]["ATLASSIAN_EMAIL"] = serde_json::Value::String("user@example.com".to_string());
        val["env"]["ATLASSIAN_API_TOKEN"] = serde_json::Value::String("secret-token".to_string());
        let formatted = serde_json::to_string_pretty(&val).unwrap();
        fs::write(&settings_path, formatted).unwrap();

        // Verify existing keys are preserved
        let content = fs::read_to_string(&settings_path).unwrap();
        let val: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(val["env"]["SOME_KEY"], "value");
        assert_eq!(
            val["env"]["ATLASSIAN_INSTANCE_URL"],
            "https://test.atlassian.net"
        );
        assert_eq!(val["env"]["ATLASSIAN_EMAIL"], "user@example.com");
        assert_eq!(val["env"]["ATLASSIAN_API_TOKEN"], "secret-token");
    }

    #[test]
    fn load_credentials_normalizes_trailing_slash() {
        // Test the trailing-slash normalization logic directly
        let url = "https://env.atlassian.net/";
        let normalized = url.trim_end_matches('/').to_string();
        assert_eq!(normalized, "https://env.atlassian.net");
    }

    #[test]
    fn constant_key_names() {
        assert_eq!(ATLASSIAN_INSTANCE_URL, "ATLASSIAN_INSTANCE_URL");
        assert_eq!(ATLASSIAN_EMAIL, "ATLASSIAN_EMAIL");
        assert_eq!(ATLASSIAN_API_TOKEN, "ATLASSIAN_API_TOKEN");
    }

    #[test]
    fn credentials_struct_clone_and_debug() {
        let creds = AtlassianCredentials {
            instance_url: "https://org.atlassian.net".to_string(),
            auth: crate::atlassian::auth::AtlassianAuth::Basic {
                email: "user@test.com".to_string(),
                api_token: "super-sekret-api-token-value".into(),
            },
        };
        let cloned = creds.clone();
        assert_eq!(cloned.instance_url, creds.instance_url);
        assert_eq!(cloned.auth, creds.auth);
        // Debug must never print the token value (#1131).
        let debug = format!("{creds:?}");
        assert!(debug.contains("AtlassianCredentials"));
        assert!(
            !debug.contains("super-sekret-api-token-value"),
            "leaked token: {debug}"
        );
        assert!(debug.contains("api_token: <redacted>"));
    }

    use super::test_util::EnvGuard;

    fn with_empty_home(_guard: &EnvGuard) -> tempfile::TempDir {
        let dir = {
            std::fs::create_dir_all("tmp").ok();
            tempfile::TempDir::new_in("tmp").unwrap()
        };
        std::env::set_var("HOME", dir.path());
        std::env::remove_var(crate::utils::settings::PROFILE_ENV_VAR);
        std::env::remove_var(ATLASSIAN_INSTANCE_URL);
        std::env::remove_var(ATLASSIAN_EMAIL);
        std::env::remove_var(ATLASSIAN_API_TOKEN);
        std::env::remove_var(ATLASSIAN_PAT);
        dir
    }

    #[test]
    fn status_reports_all_false_when_nothing_configured() {
        let guard = EnvGuard::take();
        let _dir = with_empty_home(&guard);

        let status = status();
        assert_eq!(status.scopes.len(), 1);
        let scope = &status.scopes[0];
        assert_eq!(scope.name, "default");
        assert!(!scope.has_email);
        assert!(!scope.has_token);
        assert_eq!(scope.instance_url, None);
    }

    #[test]
    fn status_reports_presence_flags_from_settings_without_leaking_secrets() {
        let guard = EnvGuard::take();
        let dir = with_empty_home(&guard);
        let omni_dir = dir.path().join(".omni-dev");
        fs::create_dir_all(&omni_dir).unwrap();
        fs::write(
            omni_dir.join("settings.json"),
            r#"{"env":{
                "ATLASSIAN_INSTANCE_URL":"https://status.atlassian.net/",
                "ATLASSIAN_EMAIL":"person@example.com",
                "ATLASSIAN_API_TOKEN":"sekret-do-not-leak"
            }}"#,
        )
        .unwrap();

        let status = status();
        assert_eq!(status.scopes.len(), 1);
        let scope = &status.scopes[0];
        assert!(scope.has_email);
        assert!(scope.has_token);
        assert_eq!(
            scope.instance_url.as_deref(),
            Some("https://status.atlassian.net")
        );

        let yaml = serde_yaml::to_string(&status).unwrap();
        assert!(!yaml.contains("sekret-do-not-leak"), "leaked token: {yaml}");
        assert!(!yaml.contains("person@example.com"), "leaked email: {yaml}");
    }

    #[test]
    fn status_returns_instance_url_from_env_without_trailing_slash() {
        let guard = EnvGuard::take();
        let _dir = with_empty_home(&guard);
        std::env::set_var(ATLASSIAN_INSTANCE_URL, "https://env.atlassian.net/");

        let status = status();
        let scope = &status.scopes[0];
        assert_eq!(
            scope.instance_url.as_deref(),
            Some("https://env.atlassian.net")
        );
        assert!(!scope.has_email);
        assert!(!scope.has_token);
    }

    /// The production wrapper resolves `~/.omni-dev/settings.json` from
    /// `HOME`, which `dirs::home_dir()` reads internally — so this one test
    /// must redirect `HOME` (under the shared [`EnvGuard`]). Every other save
    /// test injects a path into `save_credentials_to` instead (issue #1030).
    #[test]
    fn save_credentials_resolves_default_settings_path() {
        let guard = EnvGuard::take();
        let dir = with_empty_home(&guard);

        let creds = AtlassianCredentials {
            instance_url: "https://wrapper.atlassian.net".to_string(),
            auth: crate::atlassian::auth::AtlassianAuth::Basic {
                email: "wrapper@example.com".to_string(),
                api_token: "wrapper-token".into(),
            },
        };
        save_credentials(&creds).unwrap();

        let settings_path = dir.path().join(".omni-dev").join("settings.json");
        let val: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        assert_eq!(val["env"]["ATLASSIAN_EMAIL"], "wrapper@example.com");
    }

    /// The `remove_credentials()` wrapper resolves the settings path from
    /// `HOME` and the profile from the environment; every other removal test
    /// injects both into `remove_credentials_at` (issue #1030).
    #[test]
    fn remove_credentials_resolves_default_settings_path() {
        let guard = EnvGuard::take();
        let dir = with_empty_home(&guard);

        let creds = AtlassianCredentials {
            instance_url: "https://wrapper.atlassian.net".to_string(),
            auth: crate::atlassian::auth::AtlassianAuth::Basic {
                email: "wrapper@example.com".to_string(),
                api_token: "wrapper-token".into(),
            },
        };
        save_credentials(&creds).unwrap();

        // Present → removed.
        assert!(remove_credentials().unwrap());

        let settings_path = dir.path().join(".omni-dev").join("settings.json");
        let val: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        assert!(val["env"].get(ATLASSIAN_EMAIL).is_none());
        assert!(val["env"].get(ATLASSIAN_API_TOKEN).is_none());

        // Idempotent: nothing left to remove.
        assert!(!remove_credentials().unwrap());
    }

    /// Save against injected settings-file paths — no `HOME` mutation, so the
    /// test needs no lock (issue #1030). Covers fresh-file creation and
    /// merge-with-existing.
    #[test]
    fn save_credentials_creates_and_preserves() {
        // ── Part 1: creates file from scratch ──────────────────────
        {
            let temp_dir = {
                std::fs::create_dir_all("tmp").ok();
                tempfile::TempDir::new_in("tmp").unwrap()
            };
            let settings_path = temp_dir.path().join(".omni-dev").join("settings.json");

            let creds = AtlassianCredentials {
                instance_url: "https://save.atlassian.net".to_string(),
                auth: crate::atlassian::auth::AtlassianAuth::Basic {
                    email: "save@example.com".to_string(),
                    api_token: "save-token".into(),
                },
            };
            save_credentials_to(&settings_path, None, &creds).unwrap();

            assert!(settings_path.exists());
            let content = fs::read_to_string(&settings_path).unwrap();
            let val: serde_json::Value = serde_json::from_str(&content).unwrap();
            assert_eq!(
                val["env"]["ATLASSIAN_INSTANCE_URL"],
                "https://save.atlassian.net"
            );
            assert_eq!(val["env"]["ATLASSIAN_EMAIL"], "save@example.com");
            assert_eq!(val["env"]["ATLASSIAN_API_TOKEN"], "save-token");

            // The credential store is created owner-only (issue #1128).
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = fs::metadata(&settings_path).unwrap().permissions().mode();
                assert_eq!(mode & 0o777, 0o600);
            }
        }

        // ── Part 2: preserves existing keys ────────────────────────
        {
            let temp_dir = {
                std::fs::create_dir_all("tmp").ok();
                tempfile::TempDir::new_in("tmp").unwrap()
            };
            let omni_dir = temp_dir.path().join(".omni-dev");
            fs::create_dir_all(&omni_dir).unwrap();
            let settings_path = omni_dir.join("settings.json");
            fs::write(
                &settings_path,
                r#"{"env": {"OTHER_KEY": "keep_me"}, "extra": true}"#,
            )
            .unwrap();

            let creds = AtlassianCredentials {
                instance_url: "https://org.atlassian.net".to_string(),
                auth: crate::atlassian::auth::AtlassianAuth::Basic {
                    email: "user@test.com".to_string(),
                    api_token: "token".into(),
                },
            };
            save_credentials_to(&settings_path, None, &creds).unwrap();

            let content = fs::read_to_string(&settings_path).unwrap();
            let val: serde_json::Value = serde_json::from_str(&content).unwrap();
            assert_eq!(val["env"]["OTHER_KEY"], "keep_me");
            assert_eq!(val["extra"], true);
            assert_eq!(
                val["env"]["ATLASSIAN_INSTANCE_URL"],
                "https://org.atlassian.net"
            );
        }
    }

    /// A profile-targeted save lands under `profiles.<name>.env` — where the
    /// profile-aware read side will find it — and leaves the base `env`
    /// untouched (issue #1116).
    #[test]
    fn save_credentials_to_profile_writes_into_profile_env() {
        let temp_dir = {
            std::fs::create_dir_all("tmp").ok();
            tempfile::TempDir::new_in("tmp").unwrap()
        };
        let omni_dir = temp_dir.path().join(".omni-dev");
        fs::create_dir_all(&omni_dir).unwrap();
        let settings_path = omni_dir.join("settings.json");
        fs::write(&settings_path, r#"{"env": {"OTHER_KEY": "keep_me"}}"#).unwrap();

        let creds = AtlassianCredentials {
            instance_url: "https://work.atlassian.net".to_string(),
            auth: crate::atlassian::auth::AtlassianAuth::Basic {
                email: "work@example.com".to_string(),
                api_token: "work-token".into(),
            },
        };
        save_credentials_to(&settings_path, Some("work"), &creds).unwrap();

        let val: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        assert_eq!(
            val["profiles"]["work"]["env"]["ATLASSIAN_EMAIL"],
            "work@example.com"
        );
        assert_eq!(
            val["profiles"]["work"]["env"]["ATLASSIAN_INSTANCE_URL"],
            "https://work.atlassian.net"
        );
        assert!(val["env"].get("ATLASSIAN_EMAIL").is_none());
        assert_eq!(val["env"]["OTHER_KEY"], "keep_me");
    }

    #[test]
    fn load_credentials_with_instance_override_supplies_instance_url() {
        // The override lets a caller (e.g. `jira create --instance`) target an
        // instance even when ATLASSIAN_INSTANCE_URL is unset, as long as email
        // and token are present. The trailing slash is normalized.
        let guard = EnvGuard::take();
        let _dir = with_empty_home(&guard);
        std::env::set_var(ATLASSIAN_EMAIL, "person@example.com");
        std::env::set_var(ATLASSIAN_API_TOKEN, "token");

        let creds =
            load_credentials_with_instance(Some("https://override.atlassian.net/")).unwrap();
        assert_eq!(creds.instance_url, "https://override.atlassian.net");
        assert!(
            matches!(&creds.auth, AtlassianAuth::Basic { email, .. } if email == "person@example.com")
        );
        assert!(
            matches!(&creds.auth, AtlassianAuth::Basic { api_token, .. } if api_token.expose_secret() == "token")
        );
    }

    #[test]
    fn load_credentials_with_instance_none_requires_env_instance() {
        // Without an override and without ATLASSIAN_INSTANCE_URL configured,
        // resolution fails just like load_credentials() does today.
        let guard = EnvGuard::take();
        let _dir = with_empty_home(&guard);
        std::env::set_var(ATLASSIAN_EMAIL, "person@example.com");
        std::env::set_var(ATLASSIAN_API_TOKEN, "token");

        assert!(load_credentials_with_instance(None).is_err());
    }

    #[test]
    fn load_credentials_honours_instance_override_env() {
        // The global `--instance` flag (exported as OMNI_DEV_ATLASSIAN_INSTANCE)
        // overrides the instance for every command, even with no configured
        // ATLASSIAN_INSTANCE_URL (#1117). A blank value is ignored.
        let guard = EnvGuard::take();
        let _dir = with_empty_home(&guard);
        std::env::set_var(ATLASSIAN_EMAIL, "person@example.com");
        std::env::set_var(ATLASSIAN_API_TOKEN, "token");

        // Blank → ignored → falls back to the (absent) configured instance.
        std::env::set_var(ATLASSIAN_INSTANCE_OVERRIDE_ENV, "  ");
        assert!(load_credentials().is_err());

        // Set → used verbatim (trailing slash normalized).
        std::env::set_var(
            ATLASSIAN_INSTANCE_OVERRIDE_ENV,
            "https://flag.atlassian.net/",
        );
        let creds = load_credentials().unwrap();
        assert_eq!(creds.instance_url, "https://flag.atlassian.net");
        assert!(
            matches!(&creds.auth, AtlassianAuth::Basic { email, .. } if email == "person@example.com")
        );
    }
    use crate::test_support::env::{secret_file, MapEnv};

    fn pat_env() -> MapEnv {
        MapEnv::new()
            .with(ATLASSIAN_INSTANCE_URL, "https://self.example/jira/")
            .with(ATLASSIAN_PAT, "private-pat")
    }

    #[test]
    fn pat_loads_without_email_and_is_redacted() {
        let creds = load_credentials_from(&pat_env(), None).unwrap();
        assert_eq!(creds.instance_url, "https://self.example/jira");
        assert_eq!(creds.auth.mode(), AuthMode::Bearer);
        assert!(!format!("{creds:?}").contains("private-pat"));
        let scope = scope_status_from(&pat_env().with(ATLASSIAN_EMAIL, "leftover@example.com"));
        assert_eq!(scope.configuration_state, ConfigurationState::Configured);
        assert_eq!(scope.auth_mode, Some(AuthMode::Bearer));
        let yaml = serde_yaml::to_string(&scope).unwrap();
        assert!(yaml.contains("has_pat: true"));
        assert!(!yaml.contains("private-pat"));
        assert!(!yaml.contains("leftover@example.com"));
    }

    #[test]
    fn token_conflict_precedes_secret_resolution() {
        let env = MapEnv::new()
            .with(ATLASSIAN_INSTANCE_URL, "https://self.example")
            .with("ATLASSIAN_PAT_COMMAND", "/does/not/exist")
            .with("ATLASSIAN_API_TOKEN_FILE", "/does/not/exist");
        let scope = scope_status_from(&env);
        assert_eq!(scope.configuration_state, ConfigurationState::Conflict);
        assert_eq!(scope.auth_mode, None);
        let err = load_credentials_from(&env, None).unwrap_err().to_string();
        assert!(err.contains("conflict"));
        assert!(!err.contains("/does/not/exist"));
    }

    #[test]
    fn presence_status_does_not_resolve_sources() {
        for key in ["ATLASSIAN_PAT_FILE", "ATLASSIAN_PAT_COMMAND"] {
            let env = MapEnv::new()
                .with(ATLASSIAN_INSTANCE_URL, "https://self.example")
                .with(key, "/does/not/exist");
            assert_eq!(
                scope_status_from(&env).configuration_state,
                ConfigurationState::Configured
            );
        }
        assert_eq!(
            scope_status_from(&MapEnv::new()).configuration_state,
            ConfigurationState::Missing
        );
        assert_eq!(
            scope_status_from(&MapEnv::new().with(ATLASSIAN_PAT, "pat")).configuration_state,
            ConfigurationState::Incomplete
        );
    }

    #[test]
    fn pat_file_and_helper_use_secret_resolver() {
        let (_dir, path) = secret_file("file-pat\n");
        let env = MapEnv::new().with("ATLASSIAN_PAT_FILE", &path);
        let creds = load_credentials_from(&env, Some("https://self.example/confluence/")).unwrap();
        assert!(
            matches!(creds.auth, AtlassianAuth::Bearer { token } if token.expose_secret() == "file-pat")
        );
        // The printf helper is Unix-specific; the file-source case above is portable.
        #[cfg(unix)]
        {
            let env = MapEnv::new().with("ATLASSIAN_PAT_COMMAND", "/usr/bin/printf helper-pat");
            let creds = load_credentials_from(&env, Some("https://self.example")).unwrap();
            assert!(
                matches!(creds.auth, AtlassianAuth::Bearer { token } if token.expose_secret() == "helper-pat")
            );
        }
    }

    #[test]
    fn invalid_and_missing_credentials_do_not_fall_back() {
        for token in [" ", "pat\r\nInjected: yes"] {
            let env = MapEnv::new().with(ATLASSIAN_PAT, token);
            let err = load_credentials_from(&env, Some("https://self.example")).unwrap_err();
            if !token.trim().is_empty() {
                assert!(!err.to_string().contains(token));
            }
        }
        let env = MapEnv::new().with(ATLASSIAN_API_TOKEN, "cloud-token");
        assert!(load_credentials_from(&env, Some("https://self.example")).is_err());
        assert!(load_credentials_from(&MapEnv::new(), Some("https://self.example")).is_err());
        assert!(load_credentials_from(&pat_env(), Some(" ")).is_err());
        let env = MapEnv::new()
            .with(ATLASSIAN_PAT, "pat")
            .with("ATLASSIAN_PAT_FILE", "/missing");
        assert!(load_credentials_from(&env, Some("https://self.example")).is_err());
    }

    struct Layered<'a> {
        settings: &'a Settings,
        raw: MapEnv,
        profile: Option<&'a str>,
    }
    impl EnvSource for Layered<'_> {
        fn var(&self, key: &str) -> Option<String> {
            self.settings.resolve_with(&self.raw, self.profile, key)
        }
        fn var_triple(
            &self,
            key: &str,
            file: &str,
            command: &str,
        ) -> crate::utils::env::SecretTriple {
            self.settings
                .resolve_triple_with(&self.raw, self.profile, key, file, command)
        }
    }

    #[test]
    fn pat_profiles_are_isolated_and_process_source_wins() {
        let settings: Settings = serde_json::from_value(serde_json::json!({
            "env": {"ATLASSIAN_EMAIL": "base@example.com", "ATLASSIAN_API_TOKEN": "base-token"},
            "profiles": {"work": {"env": {"ATLASSIAN_PAT": "profile-pat"}}}
        }))
        .unwrap();
        let source = Layered {
            settings: &settings,
            raw: MapEnv::new(),
            profile: Some("work"),
        };
        let creds = load_credentials_from(&source, Some("https://self.example")).unwrap();
        assert!(
            matches!(creds.auth, AtlassianAuth::Bearer { token } if token.expose_secret() == "profile-pat")
        );
        let source = Layered {
            raw: MapEnv::new().with(ATLASSIAN_PAT, "process-pat"),
            ..source
        };
        let creds = load_credentials_from(&source, Some("https://self.example")).unwrap();
        assert!(
            matches!(creds.auth, AtlassianAuth::Bearer { token } if token.expose_secret() == "process-pat")
        );
    }

    #[test]
    fn mode_switch_and_logout_remove_obsolete_sources_atomically() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let initial = serde_json::json!({"unknown": true, "env": {"KEEP": "base"}, "profiles": {
            "work": {"env": {"KEEP": "work", "ATLASSIAN_EMAIL": "old@example.com",
                "ATLASSIAN_API_TOKEN_FILE": "/old-file", "ATLASSIAN_API_TOKEN_COMMAND": "old-helper"}},
            "other": {"env": {"ATLASSIAN_PAT": "other-pat"}}
        }});
        fs::write(&path, initial.to_string()).unwrap();
        let creds = AtlassianCredentials {
            instance_url: "https://self.example".into(),
            auth: AtlassianAuth::Bearer {
                token: "new-pat".into(),
            },
        };
        save_credentials_to(&path, Some("work"), &creds).unwrap();
        let saved: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        let env = &saved["profiles"]["work"]["env"];
        assert_eq!(env[ATLASSIAN_PAT], "new-pat");
        for key in [
            ATLASSIAN_EMAIL,
            ATLASSIAN_API_TOKEN,
            "ATLASSIAN_API_TOKEN_FILE",
            "ATLASSIAN_API_TOKEN_COMMAND",
        ] {
            assert!(env.get(key).is_none());
        }
        assert_eq!(saved["env"], initial["env"]);
        assert_eq!(saved["profiles"]["other"], initial["profiles"]["other"]);
        assert_eq!(saved["unknown"], true);
        let creds = AtlassianCredentials {
            instance_url: "https://cloud.example".into(),
            auth: AtlassianAuth::Basic {
                email: "me@example.com".into(),
                api_token: "cloud-token".into(),
            },
        };
        save_credentials_to(&path, Some("work"), &creds).unwrap();
        let saved: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert!(saved["profiles"]["work"]["env"]
            .get(ATLASSIAN_PAT)
            .is_none());
        assert!(remove_credentials_at(&path, Some("work")).unwrap());
        assert!(!remove_credentials_at(&path, Some("work")).unwrap());
    }

    #[test]
    fn selected_helper_refusal_leaves_file_unchanged() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let initial = r#"{"env":{"ATLASSIAN_PAT_COMMAND":"helper","ATLASSIAN_API_TOKEN":"old"}}"#;
        fs::write(&path, initial).unwrap();
        let creds = AtlassianCredentials {
            instance_url: "https://self.example".into(),
            auth: AtlassianAuth::Bearer {
                token: "new-pat".into(),
            },
        };
        assert!(save_credentials_to(&path, None, &creds).is_err());
        assert_eq!(fs::read_to_string(&path).unwrap(), initial);
    }
}