secretspec 0.14.0

Declarative secrets, every environment, any provider
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
//! Google Cloud Secret Manager provider
//!
//! This provider integrates with Google Cloud Secret Manager to store and retrieve secrets.
//!
//! # Authentication
//!
//! Uses Application Default Credentials (ADC). Set up via:
//! - `gcloud auth application-default login` for local development
//! - Service account with `GOOGLE_APPLICATION_CREDENTIALS` environment variable
//! - Workload Identity for GKE environments
//!
//! # URI Format
//!
//! `gcsm://project-id`
//!
//! # Secret Naming
//!
//! Secrets are stored with the naming pattern: `secretspec-{project}-{profile}-{key}`
//!
//! # Example
//!
//! ```bash
//! # Set up authentication
//! gcloud auth application-default login
//!
//! # Set a secret
//! secretspec set DATABASE_URL --provider gcsm://my-gcp-project
//!
//! # Check secrets from GCP
//! secretspec check --provider gcsm://my-gcp-project
//! ```

use super::{Address, Provider, ProviderUrl};
use crate::{Result, SecretSpecError};
use google_cloud_secretmanager_v1::client::SecretManagerService;
use google_cloud_secretmanager_v1::model::{Replication, Secret, SecretPayload, replication};
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};

/// Configuration for the Google Cloud Secret Manager provider.
///
/// Contains the GCP project ID where secrets are stored.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GcsmConfig {
    /// The GCP project ID (e.g., "my-gcp-project")
    pub project_id: String,
}

/// Validates a GCP project ID format.
///
/// GCP project IDs must:
/// - Be 6-30 characters long
/// - Start with a lowercase letter
/// - Contain only lowercase letters, digits, and hyphens
/// - Not end with a hyphen
fn validate_gcp_project_id(project_id: &str) -> std::result::Result<(), SecretSpecError> {
    let len = project_id.len();
    if len < 6 || len > 30 {
        return Err(SecretSpecError::ProviderOperationFailed(format!(
            "GCP project ID must be 6-30 characters, got {}",
            len
        )));
    }

    let mut chars = project_id.chars().peekable();

    // First character must be a lowercase letter
    match chars.next() {
        Some(c) if c.is_ascii_lowercase() => {}
        _ => {
            return Err(SecretSpecError::ProviderOperationFailed(
                "GCP project ID must start with a lowercase letter".to_string(),
            ));
        }
    }

    // Check remaining characters
    for c in chars {
        if !c.is_ascii_lowercase() && !c.is_ascii_digit() && c != '-' {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "GCP project ID contains invalid character '{}'. \
                Only lowercase letters, digits, and hyphens are allowed",
                c
            )));
        }
    }

    // Cannot end with a hyphen
    if project_id.ends_with('-') {
        return Err(SecretSpecError::ProviderOperationFailed(
            "GCP project ID cannot end with a hyphen".to_string(),
        ));
    }

    Ok(())
}

impl TryFrom<&ProviderUrl> for GcsmConfig {
    type Error = SecretSpecError;

    fn try_from(url: &ProviderUrl) -> std::result::Result<Self, Self::Error> {
        if url.scheme() != "gcsm" {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "Invalid scheme '{}' for gcsm provider. Expected 'gcsm'.",
                url.scheme()
            )));
        }

        // Extract project ID from host portion: gcsm://project-id
        let project_id = url.host().filter(|s| !s.is_empty()).ok_or_else(|| {
            SecretSpecError::ProviderOperationFailed(
                "GCP project ID is required. Use format: gcsm://project-id".to_string(),
            )
        })?;

        // Validate project ID format
        validate_gcp_project_id(&project_id)?;

        // The path reference form from earlier iterations is rejected with a
        // pointer at the `ref` table, instead of being silently ignored and
        // reading the conventional layout.
        let path = url.path();
        let trimmed = path.trim_start_matches('/');
        if !trimmed.is_empty() {
            let id = trimmed
                .strip_prefix("secrets/")
                .unwrap_or(trimmed)
                .split('/')
                .next()
                .unwrap_or(trimmed);
            let hint = crate::config::ref_table_hint(None, id, None, None);
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "gcsm URIs take no path: address the secret with \
                 {hint} on the secret instead \
                 (add version = \"<n>\" to pin a version)"
            )));
        }

        Ok(Self { project_id })
    }
}

/// Google Cloud Secret Manager provider.
///
/// This provider stores and retrieves secrets from Google Cloud Secret Manager using
/// Application Default Credentials for authentication.
pub struct GcsmProvider {
    config: GcsmConfig,
}

crate::register_provider! {
    struct: GcsmProvider,
    config: GcsmConfig,
    name: "gcsm",
    description: "Google Cloud Secret Manager",
    schemes: ["gcsm"],
    examples: ["gcsm://my-gcp-project"],
}

impl GcsmProvider {
    /// Creates a new GcsmProvider with the given configuration.
    pub fn new(config: GcsmConfig) -> Self {
        Self { config }
    }

    /// Validates a secret name component for GCP Secret Manager.
    ///
    /// Components must contain only alphanumeric characters, underscores, and hyphens.
    fn validate_name_component(name: &str, component: &str) -> Result<()> {
        if component.is_empty() {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "{} cannot be empty",
                name
            )));
        }

        for c in component.chars() {
            if !c.is_ascii_alphanumeric() && c != '_' && c != '-' {
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "{} contains invalid character '{}'. \
                    Only alphanumeric characters, underscores, and hyphens are allowed",
                    name, c
                )));
            }
        }

        Ok(())
    }

    /// Formats and validates the secret name for GCP Secret Manager.
    ///
    /// Converts the SecretSpec path format to GCP-compatible name:
    /// `secretspec-{project}-{profile}-{key}`
    ///
    /// GCP Secret Manager secret IDs must:
    /// - Be 1-255 characters long
    /// - Contain only alphanumeric characters, hyphens, and underscores
    fn format_secret_name(&self, project: &str, profile: &str, key: &str) -> Result<String> {
        // Validate each component
        Self::validate_name_component("project", project)?;
        Self::validate_name_component("profile", profile)?;
        Self::validate_name_component("key", key)?;

        let secret_name = format!("secretspec-{}-{}-{}", project, profile, key);

        // GCP secret IDs must be 1-255 characters
        if secret_name.len() > 255 {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "Secret name too long: {} characters (max 255)",
                secret_name.len()
            )));
        }

        Ok(secret_name)
    }

    /// Checks if an error indicates the resource was not found.
    fn is_not_found_error(e: &impl std::error::Error) -> bool {
        let s = e.to_string();
        s.contains("NOT_FOUND") || s.contains("notFound")
    }

    /// Checks if an error indicates the resource already exists.
    fn is_already_exists_error(e: &impl std::error::Error) -> bool {
        let s = e.to_string();
        s.contains("ALREADY_EXISTS") || s.contains("alreadyExists")
    }

    /// Creates a SecretManagerService client.
    async fn create_client(&self) -> Result<SecretManagerService> {
        SecretManagerService::builder().build().await.map_err(|e| {
            SecretSpecError::ProviderOperationFailed(format!(
                "Failed to create GCP Secret Manager client: {}\n\n\
                Ensure Application Default Credentials are configured:\n  \
                - Local development: Run 'gcloud auth application-default login'\n  \
                - Service account: Set GOOGLE_APPLICATION_CREDENTIALS environment variable\n  \
                - GKE: Configure Workload Identity",
                e
            ))
        })
    }

    /// Resolves coordinates to a version resource and reads it, mapping "not
    /// found" to `None`: `item` is the secret id, `version` the version to read
    /// (defaulting to the latest).
    async fn get_coords_async(
        &self,
        coords: &crate::config::NativeAddress,
    ) -> Result<Option<SecretString>> {
        let version = coords.version.as_deref().unwrap_or("latest");
        let secret_version_path = format!(
            "projects/{}/secrets/{}/versions/{}",
            self.config.project_id, coords.item, version
        );
        let client = self.create_client().await?;

        match client
            .access_secret_version()
            .set_name(&secret_version_path)
            .send()
            .await
        {
            Ok(response) => {
                if let Some(payload) = response.payload {
                    let data = String::from_utf8(payload.data.to_vec()).map_err(|e| {
                        SecretSpecError::ProviderOperationFailed(format!(
                            "Secret data is not valid UTF-8: {}",
                            e
                        ))
                    })?;
                    Ok(Some(SecretString::new(data.into())))
                } else {
                    Ok(None)
                }
            }
            Err(e) => {
                // Check if the error is "not found" (secret doesn't exist)
                if Self::is_not_found_error(&e) {
                    Ok(None)
                } else {
                    Err(SecretSpecError::ProviderOperationFailed(format!(
                        "Failed to access secret '{}': {}",
                        coords.item, e
                    )))
                }
            }
        }
    }

    /// Creates or updates a secret in GCP Secret Manager.
    ///
    /// Always attempts to create the secret first (idempotent operation), then adds a new version.
    /// This avoids TOCTOU race conditions by not checking existence before creation.
    async fn set_secret_async(&self, secret_name: &str, value: &SecretString) -> Result<()> {
        let client = self.create_client().await?;

        // Always try to create the secret first (idempotent - ALREADY_EXISTS is expected for existing secrets)
        let create_result = client
            .create_secret()
            .set_parent(format!("projects/{}", self.config.project_id))
            .set_secret_id(secret_name)
            .set_secret(Secret::default().set_replication(
                Replication::default().set_automatic(replication::Automatic::default()),
            ))
            .send()
            .await;

        // Only fail on errors OTHER than ALREADY_EXISTS
        if let Err(e) = create_result {
            if !Self::is_already_exists_error(&e) {
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "Failed to create secret '{}': {}",
                    secret_name, e
                )));
            }
            // ALREADY_EXISTS is expected for existing secrets, continue to add version
        }

        // Add a new version with the secret data
        client
            .add_secret_version()
            .set_parent(format!(
                "projects/{}/secrets/{}",
                self.config.project_id, secret_name
            ))
            .set_payload(
                SecretPayload::default().set_data(value.expose_secret().as_bytes().to_vec()),
            )
            .send()
            .await
            .map_err(|e| {
                SecretSpecError::ProviderOperationFailed(format!(
                    "Failed to add secret version for '{}': {}",
                    secret_name, e
                ))
            })?;

        Ok(())
    }
}

impl Provider for GcsmProvider {
    /// Convention secrets are ids of the form
    /// `secretspec-{project}-{profile}-{key}` (GCP secret ids cannot contain
    /// slashes), read at their latest version.
    fn convention_address(
        &self,
        project: &str,
        profile: &str,
        key: &str,
    ) -> Result<crate::config::NativeAddress> {
        Ok(crate::config::NativeAddress {
            item: self.format_secret_name(project, profile, key)?,
            ..Default::default()
        })
    }

    fn name(&self) -> &'static str {
        Self::PROVIDER_NAME
    }

    fn uri(&self) -> String {
        format!("gcsm://{}", self.config.project_id)
    }

    /// An optional `version` pins the secret version to read.
    fn supported_coords(&self) -> &'static [&'static str] {
        &["version"]
    }

    fn get(&self, addr: Address<'_>) -> Result<Option<SecretString>> {
        let coords = self.resolve_coords(addr)?;
        super::block_on(self.get_coords_async(&coords))
    }

    fn set(&self, addr: Address<'_>, value: &SecretString) -> Result<()> {
        self.check_writable(addr)?;
        let coords = self.resolve_coords(addr)?;
        super::block_on(self.set_secret_async(&coords.item, value))
    }

    /// Native addresses are read-only: they name an existing (often
    /// version-pinned) secret, and writing would mean minting a new version of
    /// someone else's secret.
    fn check_writable(&self, addr: Address<'_>) -> Result<()> {
        match addr {
            Address::Convention { .. } => Ok(()),
            Address::Native(_) => Err(SecretSpecError::ProviderOperationFailed(
                "gcsm secret references are read-only and cannot be written".to_string(),
            )),
        }
    }
}

#[cfg(test)]
mod reference_tests {
    use super::*;
    use url::Url;

    /// A path that is not a `secrets/...` resource is rejected.
    #[test]
    fn path_is_rejected_with_ref_hint() {
        let err = GcsmConfig::try_from(&ProviderUrl::new(
            Url::parse("gcsm://my-project/secrets/db-url/versions/3").unwrap(),
        ))
        .unwrap_err();
        assert!(
            err.to_string().contains("ref = { item = \"db-url\" }"),
            "{err}"
        );
    }

    /// Native addresses are read-only: writing would mint a new version of a
    /// secret managed outside SecretSpec.
    #[test]
    fn native_address_is_read_only() {
        let c = GcsmConfig::try_from(&ProviderUrl::new(Url::parse("gcsm://my-project").unwrap()))
            .unwrap();
        let p = GcsmProvider::new(c);
        let addr = crate::config::NativeAddress {
            item: "db-url".into(),
            ..Default::default()
        };
        let refusal = p.check_writable(Address::Native(&addr)).unwrap_err();
        assert!(refusal.to_string().contains("read-only"), "{refusal}");
        // `set` refuses with the same reason, so the pre-check cannot drift.
        let err = p
            .set(
                Address::Native(&addr),
                &secrecy::SecretString::new("v".into()),
            )
            .unwrap_err();
        assert_eq!(err.to_string(), refusal.to_string());
    }

    /// GCSM secrets have no fields; the coordinate is rejected before any
    /// network I/O.
    #[test]
    fn native_address_rejects_field() {
        let c = GcsmConfig::try_from(&ProviderUrl::new(Url::parse("gcsm://my-project").unwrap()))
            .unwrap();
        let p = GcsmProvider::new(c);
        let addr = crate::config::NativeAddress {
            item: "db-url".into(),
            field: Some("x".into()),
            ..Default::default()
        };
        let err = p.get(Address::Native(&addr)).unwrap_err();
        assert!(err.to_string().contains("`field`"), "{err}");
    }
}