shipper-core 0.4.0

Core library behind the `shipper` CLI: engine, planning, state, registry, and remediation primitives for `cargo publish` workspaces.
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
//! Cargo registry token resolution and authentication detection.
//!
//! This module is the single source of truth for Shipper's authentication
//! handling. It was previously split across:
//!   - a `shipper-auth` microcrate (token resolution from env/credentials),
//!   - an in-crate `auth` shim (added whitespace trimming, legacy credentials
//!     filename fallback, and OIDC-based `detect_auth_type`).
//!
//! Both were absorbed into `crate::ops::auth` and split into focused
//! submodules:
//!
//! - [`credentials`] — `$CARGO_HOME/credentials.toml` (and legacy `credentials`)
//!   file parsing, plus crates.io alias handling.
//! - [`resolver`] — token discovery across env vars and credentials files,
//!   along with the `AuthInfo`/`TokenSource` diagnostic types.
//! - [`oidc`] — GitHub Actions trusted-publishing detection.
//!
//! # Resolution order
//!
//! 1. `CARGO_REGISTRY_TOKEN` env var (only for `crates-io` / empty name)
//! 2. `CARGO_REGISTRIES_<NAME>_TOKEN` env var
//! 3. `$CARGO_HOME/credentials.toml` (with crates.io aliases: `crates-io`,
//!    `crates.io`, `crates_io`, and the nested `[registries.crates.io]` form)
//! 4. Legacy `$CARGO_HOME/credentials` file
//!
//! # Invariants
//!
//! - Tokens are opaque strings; NEVER log them.
//! - Empty and whitespace-trimmed-empty tokens are treated as absent.
//! - OIDC detection requires BOTH `ACTIONS_ID_TOKEN_REQUEST_URL` and
//!   `ACTIONS_ID_TOKEN_REQUEST_TOKEN`.

use std::env;
use std::path::PathBuf;

use anyhow::{Context, Result};

use crate::types::{AuthEvidence, AuthEvidenceMode, AuthType};

pub(crate) mod credentials;
pub(crate) mod oidc;
pub(crate) mod resolver;

// Re-exports forming the public-to-crate API. Exposed further as
// `shipper::auth::*` by the facade module in `lib.rs`.
pub use credentials::{CREDENTIALS_FILE, list_configured_registries};
pub use oidc::is_trusted_publishing_available;
pub use resolver::{
    AuthInfo, CARGO_HOME_ENV, CARGO_REGISTRIES_TOKEN_PREFIX, CARGO_REGISTRY_TOKEN_ENV,
    CRATES_IO_REGISTRY, TokenSource, cargo_home_path, has_token, mask_token,
    resolve_token as resolve_auth_info,
};

/// Resolve the authentication token for a registry.
///
/// Wraps the lower-level resolver (which returns an [`AuthInfo`] diagnostic
/// record) and adds:
///
/// - Whitespace trimming; empty/whitespace-only tokens are treated as absent.
/// - Fallback to the legacy `$CARGO_HOME/credentials` filename (in addition
///   to `credentials.toml`) with crates.io alias handling.
///
/// This is the canonical public-crate API used by `engine.rs` and the CLI.
pub fn resolve_token(registry_name: &str) -> Result<Option<String>> {
    let micro_token = resolver::resolve_token(registry_name, None)
        .token
        .and_then(|token| {
            let trimmed = token.trim().to_string();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed)
            }
        });

    if micro_token.is_some() {
        return Ok(micro_token);
    }

    let cargo_home = cargo_home_dir()?;
    for filename in [CREDENTIALS_FILE, "credentials"] {
        let path = cargo_home.join(filename);
        if path.exists()
            && let Some(token) =
                credentials::token_from_credentials_file_extended(&path, registry_name)?
        {
            let token = token.trim().to_string();
            if !token.is_empty() {
                return Ok(Some(token));
            }
        }
    }

    Ok(None)
}

/// Detect the best-known authentication mode for publish/preflight diagnostics.
///
/// Resolution order:
/// 1) Explicit Cargo token configuration ([`AuthType::Token`])
/// 2) Trusted publishing OIDC environment ([`AuthType::TrustedPublishing`])
/// 3) Partial trusted-publishing environment ([`AuthType::Unknown`])
/// 4) No known auth configured (`None`)
pub fn detect_auth_type(registry_name: &str) -> Result<Option<AuthType>> {
    let token = resolve_token(registry_name)?;
    Ok(detect_auth_type_from_token(token.as_deref()))
}

pub(crate) fn detect_auth_type_from_token(token: Option<&str>) -> Option<AuthType> {
    if token.map(str::trim).map(|s| !s.is_empty()).unwrap_or(false) {
        return Some(AuthType::Token);
    }

    let has_oidc_url = env::var_os("ACTIONS_ID_TOKEN_REQUEST_URL").is_some();
    let has_oidc_token = env::var_os("ACTIONS_ID_TOKEN_REQUEST_TOKEN").is_some();

    match (has_oidc_url, has_oidc_token) {
        (true, true) => Some(AuthType::TrustedPublishing),
        (true, false) | (false, true) => Some(AuthType::Unknown),
        (false, false) => None,
    }
}

/// Collect non-secret authentication evidence for release artifacts.
///
/// This is best-effort evidence: it must not make publish fail merely because
/// diagnostic token lookup could not read a local Cargo credentials file.
pub fn collect_auth_evidence(registry_name: &str) -> AuthEvidence {
    let token_result = resolve_token(registry_name);
    let token_resolution_failed = token_result.is_err();
    let token_detected = token_result
        .as_ref()
        .ok()
        .and_then(|token| token.as_deref())
        .map(str::trim)
        .map(|token| !token.is_empty())
        .unwrap_or(false);

    let oidc_request_url_present = env::var_os("ACTIONS_ID_TOKEN_REQUEST_URL").is_some();
    let oidc_request_token_present = env::var_os("ACTIONS_ID_TOKEN_REQUEST_TOKEN").is_some();

    let auth_mode = if token_resolution_failed {
        AuthEvidenceMode::Unknown
    } else {
        match (
            token_detected,
            oidc_request_url_present,
            oidc_request_token_present,
        ) {
            (true, true, true) => AuthEvidenceMode::CargoTokenWithOidcContext,
            (true, _, _) => AuthEvidenceMode::CargoToken,
            (false, true, true) => AuthEvidenceMode::TrustedPublishingContext,
            (false, true, false) | (false, false, true) => AuthEvidenceMode::PartialOidcContext,
            (false, false, false) => AuthEvidenceMode::Missing,
        }
    };

    AuthEvidence {
        schema_version: "shipper.auth_evidence.v1".to_string(),
        registry: registry_name.to_string(),
        auth_mode,
        token_detected,
        oidc_request_url_present,
        oidc_request_token_present,
    }
}

/// Resolve the `CARGO_HOME` directory via env-only lookup (uses `HOME` as
/// fallback). Distinct from [`resolver::cargo_home_path`] which also falls
/// back to `dirs::home_dir()` and the current directory.
///
/// The env-only form preserves the original shim behavior that expects a
/// clean error when neither `CARGO_HOME` nor `HOME` is set.
fn cargo_home_dir() -> Result<PathBuf> {
    if let Ok(ch) = env::var("CARGO_HOME") {
        return Ok(PathBuf::from(ch));
    }

    let home = env::var("HOME").context("HOME env var not set; set CARGO_HOME or HOME")?;
    Ok(PathBuf::from(home).join(".cargo"))
}

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

    use serial_test::serial;
    use tempfile::tempdir;

    fn normalize_registry_for_env(name: &str) -> String {
        name.chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() {
                    c.to_ascii_uppercase()
                } else {
                    '_'
                }
            })
            .collect()
    }

    #[test]
    fn normalize_registry_name_for_env() {
        assert_eq!(normalize_registry_for_env("my-registry"), "MY_REGISTRY");
        assert_eq!(normalize_registry_for_env("crates.io"), "CRATES_IO");
        assert_eq!(normalize_registry_for_env("A1_b"), "A1_B");
    }

    #[test]
    #[serial]
    fn resolve_token_prefers_crates_io_default_var() {
        temp_env::with_vars(
            [
                ("CARGO_REGISTRY_TOKEN", Some("token-a")),
                ("CARGO_REGISTRIES_CRATES_IO_TOKEN", Some("token-b")),
            ],
            || {
                let tok = resolve_token("crates-io").expect("resolve");
                assert_eq!(tok.as_deref(), Some("token-a"));
            },
        );
    }

    #[test]
    #[serial]
    fn resolve_token_uses_env_registry_var() {
        temp_env::with_vars(
            [
                ("CARGO_REGISTRY_TOKEN", None::<&str>),
                ("CARGO_REGISTRIES_PRIVATE_REG_TOKEN", Some("abc123")),
            ],
            || {
                let tok = resolve_token("private-reg").expect("resolve");
                assert_eq!(tok.as_deref(), Some("abc123"));
            },
        );
    }

    #[test]
    #[serial]
    fn resolve_token_prefers_env_over_credentials() {
        let td = tempdir().expect("tempdir");
        fs::write(
            td.path().join("credentials.toml"),
            r#"[registry]
token = "file-token"
"#,
        )
        .expect("write");

        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", Some("env-token")),
            ],
            || {
                let tok = resolve_token("crates-io").expect("resolve");
                assert_eq!(tok.as_deref(), Some("env-token"));
            },
        );
    }

    #[test]
    #[serial]
    fn resolve_token_reads_legacy_credentials_file() {
        let td = tempdir().expect("tempdir");
        fs::write(
            td.path().join("credentials"),
            r#"[registries.private-reg]
token = "legacy-token"
"#,
        )
        .expect("write");

        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", None::<&str>),
            ],
            || {
                let tok = resolve_token("private-reg").expect("resolve");
                assert_eq!(tok.as_deref(), Some("legacy-token"));
            },
        );
    }

    #[test]
    #[serial]
    fn resolve_token_supports_crates_io_aliases_in_credentials() {
        let td = tempdir().expect("tempdir");
        fs::write(
            td.path().join("credentials.toml"),
            r#"[registries.crates.io]
token = "token-dot"
"#,
        )
        .expect("write");

        temp_env::with_vars(
            [("CARGO_HOME", Some(td.path().to_str().expect("utf8")))],
            || {
                let tok = resolve_token("crates-io").expect("resolve");
                assert_eq!(tok.as_deref(), Some("token-dot"));
            },
        );
    }

    #[test]
    #[serial]
    fn detect_auth_type_prefers_token_when_present() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", Some("env-token")),
                (
                    "ACTIONS_ID_TOKEN_REQUEST_URL",
                    Some("https://example.invalid/oidc"),
                ),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", Some("oidc-token")),
            ],
            || {
                let auth = detect_auth_type("crates-io").expect("detect");
                assert_eq!(auth, Some(AuthType::Token));
            },
        );
    }

    #[test]
    #[serial]
    fn detect_auth_type_detects_trusted_publishing_from_oidc_env() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                (
                    "ACTIONS_ID_TOKEN_REQUEST_URL",
                    Some("https://example.invalid/oidc"),
                ),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", Some("oidc-token")),
                ("CARGO_REGISTRY_TOKEN", None::<&str>),
            ],
            || {
                let auth = detect_auth_type("crates-io").expect("detect");
                assert_eq!(auth, Some(AuthType::TrustedPublishing));
            },
        );
    }

    #[test]
    #[serial]
    fn detect_auth_type_returns_unknown_for_partial_oidc_env() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                (
                    "ACTIONS_ID_TOKEN_REQUEST_URL",
                    Some("https://example.invalid/oidc"),
                ),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", None::<&str>),
                ("CARGO_REGISTRY_TOKEN", None::<&str>),
            ],
            || {
                let auth = detect_auth_type("crates-io").expect("detect");
                assert_eq!(auth, Some(AuthType::Unknown));
            },
        );
    }

    #[test]
    #[serial]
    fn collect_auth_evidence_reports_token_only_mode() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", Some("env-token")),
                ("ACTIONS_ID_TOKEN_REQUEST_URL", None::<&str>),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", None::<&str>),
            ],
            || {
                let evidence = collect_auth_evidence("crates-io");
                assert_eq!(evidence.schema_version, "shipper.auth_evidence.v1");
                assert_eq!(evidence.registry, "crates-io");
                assert_eq!(evidence.auth_mode, AuthEvidenceMode::CargoToken);
                assert!(evidence.token_detected);
                assert!(!evidence.oidc_request_url_present);
                assert!(!evidence.oidc_request_token_present);
            },
        );
    }

    #[test]
    #[serial]
    fn collect_auth_evidence_reports_oidc_only_context() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", None::<&str>),
                (
                    "ACTIONS_ID_TOKEN_REQUEST_URL",
                    Some("https://example.invalid/oidc"),
                ),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", Some("oidc-token")),
            ],
            || {
                let evidence = collect_auth_evidence("crates-io");
                assert_eq!(
                    evidence.auth_mode,
                    AuthEvidenceMode::TrustedPublishingContext
                );
                assert!(!evidence.token_detected);
                assert!(evidence.oidc_request_url_present);
                assert!(evidence.oidc_request_token_present);
            },
        );
    }

    #[test]
    #[serial]
    fn collect_auth_evidence_reports_token_with_oidc_context_without_claiming_provenance() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", Some("env-token")),
                (
                    "ACTIONS_ID_TOKEN_REQUEST_URL",
                    Some("https://example.invalid/oidc"),
                ),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", Some("oidc-token")),
            ],
            || {
                let evidence = collect_auth_evidence("crates-io");
                assert_eq!(
                    evidence.auth_mode,
                    AuthEvidenceMode::CargoTokenWithOidcContext
                );
                assert!(evidence.token_detected);
                assert!(evidence.oidc_request_url_present);
                assert!(evidence.oidc_request_token_present);
            },
        );
    }

    #[test]
    #[serial]
    fn collect_auth_evidence_reports_partial_oidc_context() {
        let td = tempdir().expect("tempdir");
        temp_env::with_vars(
            [
                ("CARGO_HOME", Some(td.path().to_str().expect("utf8"))),
                ("CARGO_REGISTRY_TOKEN", None::<&str>),
                (
                    "ACTIONS_ID_TOKEN_REQUEST_URL",
                    Some("https://example.invalid/oidc"),
                ),
                ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", None::<&str>),
            ],
            || {
                let evidence = collect_auth_evidence("crates-io");
                assert_eq!(evidence.auth_mode, AuthEvidenceMode::PartialOidcContext);
                assert!(!evidence.token_detected);
                assert!(evidence.oidc_request_url_present);
                assert!(!evidence.oidc_request_token_present);
            },
        );
    }
}