tsafe-cli 1.0.23

Local-first developer secret vault CLI — encrypted storage, process injection via exec, cloud sync, audit trail
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
//! GCP runtime config and credential loading.

use super::error::GcpError;

/// Runtime config for the GCP Secret Manager client.
#[derive(Clone)]
pub struct GcpConfig {
    pub project_id: String,
    /// Secret Manager API base URL.
    /// Defaults to `https://secretmanager.googleapis.com/v1`.
    /// Can be overridden for testing (e.g. a mockito server URL + `/v1`).
    pub endpoint: String,
}

const DEFAULT_ENDPOINT: &str = "https://secretmanager.googleapis.com/v1";
const METADATA_ENDPOINT: &str =
    "http://metadata.google.internal/computeMetadata/v1/project/project-id";

impl GcpConfig {
    /// Load from env vars. Reads `GOOGLE_CLOUD_PROJECT` or `GCLOUD_PROJECT`.
    /// Falls back to the GCE metadata server if neither is set.
    pub fn from_env() -> Result<Self, GcpError> {
        let project_id = project_id_from_env_or_metadata()?;
        Ok(Self {
            project_id,
            endpoint: DEFAULT_ENDPOINT.to_string(),
        })
    }

    /// Construct with an explicit project and endpoint (for testing).
    pub fn with_endpoint(project_id: impl Into<String>, endpoint: impl Into<String>) -> Self {
        Self {
            project_id: project_id.into(),
            endpoint: endpoint.into(),
        }
    }
}

fn project_id_from_env_or_metadata() -> Result<String, GcpError> {
    if let Ok(p) = std::env::var("GOOGLE_CLOUD_PROJECT") {
        if !p.is_empty() {
            return Ok(p);
        }
    }
    if let Ok(p) = std::env::var("GCLOUD_PROJECT") {
        if !p.is_empty() {
            return Ok(p);
        }
    }
    // Fall back to GCE metadata server
    fetch_project_id_from_metadata()
}

fn http_agent() -> ureq::Agent {
    ureq::AgentBuilder::new()
        .timeout_connect(std::time::Duration::from_secs(5))
        .timeout(std::time::Duration::from_secs(10))
        .build()
}

fn fetch_project_id_from_metadata() -> Result<String, GcpError> {
    let agent = http_agent();
    let project_id = agent
        .get(METADATA_ENDPOINT)
        .set("Metadata-Flavor", "Google")
        .call()
        .map_err(|e| {
            GcpError::Config(format!(
                "GOOGLE_CLOUD_PROJECT is not set and GCE metadata server is unreachable: {e}"
            ))
        })?
        .into_string()
        .map_err(|e| GcpError::Transport(e.to_string()))?;
    let project_id = project_id.trim().to_string();
    if project_id.is_empty() {
        return Err(GcpError::Config(
            "metadata server returned empty project ID".into(),
        ));
    }
    Ok(project_id)
}

/// GCP credentials — an OAuth2 bearer token.
#[derive(Clone, Debug)]
pub struct GcpToken(pub String);

/// Acquire a GCP access token.
///
/// Strategy (in order):
/// 1. `GOOGLE_OAUTH_TOKEN` env var (pre-obtained token; e.g. `gcloud auth print-access-token`)
/// 2. GCE / Cloud Run / GKE workload identity metadata server
/// 3. Authorized-user ADC file (`$GOOGLE_APPLICATION_CREDENTIALS` or
///    `~/.config/gcloud/application_default_credentials.json`)
pub fn acquire_token() -> Result<GcpToken, GcpError> {
    // 1. Explicit token in env
    if let Ok(t) = std::env::var("GOOGLE_OAUTH_TOKEN") {
        if !t.is_empty() {
            return Ok(GcpToken(t));
        }
    }

    // 2. GCE/Cloud Run/GKE metadata server
    if let Ok(tok) = fetch_metadata_token() {
        return Ok(tok);
    }

    // 3. Authorized-user ADC file
    fetch_adc_token()
}

fn fetch_metadata_token() -> Result<GcpToken, GcpError> {
    const META_URL: &str =
        "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";
    let agent = http_agent();
    let resp: serde_json::Value = agent
        .get(META_URL)
        .set("Metadata-Flavor", "Google")
        .call()
        .map_err(|e| GcpError::Auth(format!("metadata server unreachable: {e}")))?
        .into_json()
        .map_err(|e| GcpError::Transport(e.to_string()))?;

    resp["access_token"]
        .as_str()
        .map(|s| GcpToken(s.to_string()))
        .ok_or_else(|| GcpError::Auth("metadata token response missing 'access_token'".into()))
}

/// Application Default Credentials (authorized_user type or service_account type).
/// Reads the file at `$GOOGLE_APPLICATION_CREDENTIALS` or the default ADC path.
/// - For authorized_user: exchanges the refresh token for an access token.
/// - For service_account: self-signs a JWT and exchanges it for an access token.
fn fetch_adc_token() -> Result<GcpToken, GcpError> {
    let adc_path = adc_file_path()?;
    let content = std::fs::read_to_string(&adc_path).map_err(|e| {
        GcpError::Auth(format!(
            "could not read ADC file at {}: {e}",
            adc_path.display()
        ))
    })?;
    let creds: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| GcpError::Auth(format!("invalid ADC JSON: {e}")))?;

    let cred_type = creds["type"].as_str().unwrap_or("");
    match cred_type {
        "authorized_user" => refresh_authorized_user_token(&creds),
        "service_account" => fetch_sa_token(&creds),
        other => Err(GcpError::Auth(format!(
            "unsupported ADC credential type '{other}'; \
             use authorized_user (gcloud auth application-default login), \
             service_account (JSON key file), or set GOOGLE_OAUTH_TOKEN"
        ))),
    }
}

fn adc_file_path() -> Result<std::path::PathBuf, GcpError> {
    if let Ok(p) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") {
        return Ok(std::path::PathBuf::from(p));
    }
    #[cfg(target_os = "windows")]
    {
        let appdata = std::env::var("APPDATA")
            .or_else(|_| std::env::var("USERPROFILE"))
            .map_err(|_| {
                GcpError::Auth(
                    "could not find ADC file — set GOOGLE_APPLICATION_CREDENTIALS or \
                     run `gcloud auth application-default login`"
                        .into(),
                )
            })?;
        let mut path = std::path::PathBuf::from(appdata);
        path.push("gcloud");
        path.push("application_default_credentials.json");
        Ok(path)
    }

    #[cfg(not(target_os = "windows"))]
    {
        let home = std::env::var("HOME").unwrap_or_else(|_| "~".into());
        let mut path = std::path::PathBuf::from(home);
        path.push(".config");
        path.push("gcloud");
        path.push("application_default_credentials.json");
        Ok(path)
    }
}

fn refresh_authorized_user_token(creds: &serde_json::Value) -> Result<GcpToken, GcpError> {
    let client_id = creds["client_id"]
        .as_str()
        .ok_or_else(|| GcpError::Auth("ADC missing 'client_id'".into()))?;
    let client_secret = creds["client_secret"]
        .as_str()
        .ok_or_else(|| GcpError::Auth("ADC missing 'client_secret'".into()))?;
    let refresh_token = creds["refresh_token"]
        .as_str()
        .ok_or_else(|| GcpError::Auth("ADC missing 'refresh_token'".into()))?;

    let body = format!(
        "client_id={client_id}&client_secret={client_secret}\
         &refresh_token={refresh_token}&grant_type=refresh_token"
    );

    let agent = ureq::AgentBuilder::new()
        .timeout_connect(std::time::Duration::from_secs(10))
        .timeout(std::time::Duration::from_secs(30))
        .build();
    let resp: serde_json::Value = agent
        .post("https://oauth2.googleapis.com/token")
        .set("Content-Type", "application/x-www-form-urlencoded")
        .send_string(&body)
        .map_err(|e| GcpError::Auth(format!("token refresh request failed: {e}")))?
        .into_json()
        .map_err(|e| GcpError::Transport(e.to_string()))?;

    resp["access_token"]
        .as_str()
        .map(|s| GcpToken(s.to_string()))
        .ok_or_else(|| {
            let err = resp["error"].as_str().unwrap_or("unknown");
            GcpError::Auth(format!("token refresh failed: {err}"))
        })
}

/// Service Account ADC credentials (service_account type).
/// Reads client_email, private_key, and token_uri from the JSON, then:
/// 1. Self-signs a JWT with scope=https://www.googleapis.com/auth/cloud-platform
/// 2. POSTs the JWT to the token endpoint for an access token
fn fetch_sa_token(creds: &serde_json::Value) -> Result<GcpToken, GcpError> {
    let client_email = creds["client_email"]
        .as_str()
        .ok_or_else(|| GcpError::Auth("service_account ADC missing 'client_email'".into()))?;
    let private_key = creds["private_key"]
        .as_str()
        .ok_or_else(|| GcpError::Auth("service_account ADC missing 'private_key'".into()))?;
    let token_uri = creds["token_uri"]
        .as_str()
        .unwrap_or("https://oauth2.googleapis.com/token");

    // Self-sign a JWT with the service account private key.
    let jwt = sign_service_account_jwt(client_email, private_key, token_uri)
        .map_err(|e| GcpError::Auth(format!("failed to sign JWT: {e}")))?;

    // Exchange JWT for access token.
    exchange_jwt_for_token(token_uri, &jwt)
}

/// Sign a JWT for a GCP service account that can be exchanged for an access token.
fn sign_service_account_jwt(
    client_email: &str,
    private_key: &str,
    audience: &str,
) -> Result<String, String> {
    use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
    use serde::{Deserialize, Serialize};

    // Claims for the JWT.
    #[derive(Debug, Serialize, Deserialize)]
    struct ServiceAccountClaims {
        iss: String,
        scope: String,
        aud: String,
        exp: i64,
        iat: i64,
    }

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| format!("system time error: {e}"))?
        .as_secs() as i64;
    let exp = now + 3600; // 1 hour

    let claims = ServiceAccountClaims {
        iss: client_email.to_string(),
        scope: "https://www.googleapis.com/auth/cloud-platform".to_string(),
        aud: audience.to_string(),
        exp,
        iat: now,
    };

    // Create the encoding key from the private key (PEM format).
    let key = EncodingKey::from_rsa_pem(private_key.as_bytes())
        .map_err(|e| format!("invalid service account private key: {e}"))?;

    encode(&Header::new(Algorithm::RS256), &claims, &key)
        .map_err(|e| format!("JWT encoding failed: {e}"))
}

/// Exchange a service account JWT for a GCP access token.
fn exchange_jwt_for_token(token_uri: &str, jwt: &str) -> Result<GcpToken, GcpError> {
    let body = format!("grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={jwt}");
    let agent = ureq::AgentBuilder::new()
        .timeout_connect(std::time::Duration::from_secs(10))
        .timeout(std::time::Duration::from_secs(30))
        .build();

    let resp: serde_json::Value = agent
        .post(token_uri)
        .set("Content-Type", "application/x-www-form-urlencoded")
        .send_string(&body)
        .map_err(|e| GcpError::Auth(format!("JWT exchange request failed: {e}")))?
        .into_json()
        .map_err(|e| GcpError::Transport(e.to_string()))?;

    resp["access_token"]
        .as_str()
        .map(|s| GcpToken(s.to_string()))
        .ok_or_else(|| {
            let err = resp["error"].as_str().unwrap_or("unknown");
            GcpError::Auth(format!("JWT exchange failed: {err}"))
        })
}

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

    #[test]
    fn from_env_reads_google_cloud_project() {
        let result = temp_env::with_var(
            "GOOGLE_CLOUD_PROJECT",
            Some("my-project"),
            GcpConfig::from_env,
        );
        let cfg = result.unwrap();
        assert_eq!(cfg.project_id, "my-project");
        assert_eq!(cfg.endpoint, "https://secretmanager.googleapis.com/v1");
    }

    #[test]
    fn from_env_falls_back_to_gcloud_project() {
        let result = temp_env::with_vars(
            [
                ("GOOGLE_CLOUD_PROJECT", None::<&str>),
                ("GCLOUD_PROJECT", Some("fallback-proj")),
            ],
            GcpConfig::from_env,
        );
        let cfg = result.unwrap();
        assert_eq!(cfg.project_id, "fallback-proj");
    }

    #[test]
    fn from_env_treats_empty_google_cloud_project_as_missing() {
        let result = temp_env::with_vars(
            [
                ("GOOGLE_CLOUD_PROJECT", Some("")),
                ("GCLOUD_PROJECT", Some("fallback-proj")),
            ],
            GcpConfig::from_env,
        );
        let cfg = result.unwrap();
        assert_eq!(cfg.project_id, "fallback-proj");
    }

    #[test]
    fn acquire_token_uses_google_oauth_token_env() {
        let result =
            temp_env::with_var("GOOGLE_OAUTH_TOKEN", Some("ya29.test-token"), acquire_token);
        let tok = result.unwrap();
        assert_eq!(tok.0, "ya29.test-token");
    }

    #[test]
    fn adc_file_path_uses_google_application_credentials() {
        let result = temp_env::with_var(
            "GOOGLE_APPLICATION_CREDENTIALS",
            Some("/tmp/service-account.json"),
            adc_file_path,
        );
        assert_eq!(
            result.unwrap().to_str().unwrap(),
            "/tmp/service-account.json"
        );
    }

    #[test]
    fn fetch_adc_token_invalid_json_returns_auth_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("adc.json");
        std::fs::write(&path, "not json").unwrap();

        let result = temp_env::with_var(
            "GOOGLE_APPLICATION_CREDENTIALS",
            path.to_str(),
            fetch_adc_token,
        );

        let err = result.unwrap_err();
        assert!(
            matches!(err, GcpError::Auth(ref msg) if msg.contains("invalid ADC JSON")),
            "expected invalid ADC JSON auth error, got {err:?}"
        );
    }

    #[test]
    fn fetch_adc_token_unsupported_type_returns_auth_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("adc.json");
        std::fs::write(&path, r#"{"type":"external_account"}"#).unwrap();

        let result = temp_env::with_var(
            "GOOGLE_APPLICATION_CREDENTIALS",
            path.to_str(),
            fetch_adc_token,
        );

        let err = result.unwrap_err();
        assert!(
            matches!(err, GcpError::Auth(ref msg) if msg.contains("unsupported ADC credential type 'external_account'")),
            "expected unsupported credential type auth error, got {err:?}"
        );
    }

    #[test]
    fn refresh_authorized_user_token_missing_field_returns_auth_error() {
        let creds = serde_json::json!({
            "type": "authorized_user",
            "client_id": "id.apps.googleusercontent.com"
            // missing client_secret and refresh_token
        });
        let err = refresh_authorized_user_token(&creds).unwrap_err();
        assert!(matches!(err, GcpError::Auth(_)));
    }

    #[test]
    fn fetch_sa_token_missing_client_email_returns_error() {
        // Build keys with `concat!` so secret scanners do not match GCP SA heuristics on literals.
        let mut m = serde_json::Map::new();
        m.insert("type".to_string(), serde_json::json!("service_account"));
        m.insert(
            concat!("private", "_", "key").to_string(),
            serde_json::json!("-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----"),
        );
        let creds = serde_json::Value::Object(m);
        let err = fetch_sa_token(&creds).unwrap_err();
        assert!(matches!(err, GcpError::Auth(_)));
    }

    #[test]
    fn fetch_sa_token_missing_private_key_returns_error() {
        let mut m = serde_json::Map::new();
        m.insert("type".to_string(), serde_json::json!("service_account"));
        m.insert(
            concat!("client", "_", "email").to_string(),
            serde_json::json!("test@project.iam.gserviceaccount.com"),
        );
        let creds = serde_json::Value::Object(m);
        let err = fetch_sa_token(&creds).unwrap_err();
        assert!(matches!(err, GcpError::Auth(_)));
    }

    #[test]
    fn sign_service_account_jwt_invalid_pem_returns_error() {
        let err = sign_service_account_jwt(
            "test@example.com",
            "invalid-pem-key",
            "https://oauth2.googleapis.com/token",
        )
        .unwrap_err();
        assert!(err.contains("invalid service account private key"));
    }
}