1use async_trait::async_trait;
4use esh_core::{
5 ConfigValue, Error, Provider, ProviderCapability, ProviderId, ProviderMeta, Result,
6};
7use std::collections::HashMap;
8use std::sync::Arc;
9
10#[async_trait]
12pub trait GcpSecretClient: Send + Sync {
13 async fn access_secret(&self, secret_id: &str) -> Result<String>;
15}
16
17#[derive(Default, Clone)]
19pub struct MapGcpClient {
20 secrets: HashMap<String, String>,
21 fault: Option<GcpFault>,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum GcpFault {
27 Auth,
29 Timeout,
31}
32
33impl MapGcpClient {
34 #[must_use]
36 pub fn new() -> Self {
37 Self::default()
38 }
39
40 #[must_use]
42 pub fn with_secret(mut self, id: impl Into<String>, value: impl Into<String>) -> Self {
43 self.secrets.insert(id.into(), value.into());
44 self
45 }
46
47 #[must_use]
49 pub fn with_fault(mut self, fault: GcpFault) -> Self {
50 self.fault = Some(fault);
51 self
52 }
53}
54
55#[async_trait]
56impl GcpSecretClient for MapGcpClient {
57 async fn access_secret(&self, secret_id: &str) -> Result<String> {
58 match self.fault {
59 Some(GcpFault::Auth) => {
60 return Err(Error::provider("gcp-secret-manager", "access denied"));
61 }
62 Some(GcpFault::Timeout) => {
63 return Err(Error::provider("gcp-secret-manager", "timeout"));
64 }
65 None => {}
66 }
67 self.secrets
68 .get(secret_id)
69 .cloned()
70 .ok_or_else(|| Error::not_found(secret_id))
71 }
72}
73
74pub struct GcpSecretManagerProvider {
76 meta: ProviderMeta,
77 client: Arc<dyn GcpSecretClient>,
78 project: String,
79 prefix: String,
80}
81
82impl GcpSecretManagerProvider {
83 #[must_use]
85 pub fn new(project: impl Into<String>, client: Arc<dyn GcpSecretClient>) -> Self {
86 Self {
87 meta: ProviderMeta {
88 id: ProviderId::new("gcp-secret-manager"),
89 name: "Google Secret Manager".into(),
90 capabilities: ProviderCapability {
91 bulk: false,
92 versioned: true,
93 local: false,
94 },
95 },
96 client,
97 project: project.into(),
98 prefix: String::new(),
99 }
100 }
101
102 #[must_use]
104 pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
105 self.prefix = prefix.into();
106 self
107 }
108
109 #[must_use]
111 pub fn project(&self) -> &str {
112 &self.project
113 }
114
115 fn secret_id(&self, key: &str) -> String {
116 let normalized = key.replace('_', "-");
118 format!("{}{normalized}", self.prefix)
119 }
120}
121
122#[async_trait]
123impl Provider for GcpSecretManagerProvider {
124 fn meta(&self) -> &ProviderMeta {
125 &self.meta
126 }
127
128 async fn get(&self, key: &str) -> Result<ConfigValue> {
129 let id = self.secret_id(key);
130 let body = self.client.access_secret(&id).await.map_err(|e| match e {
131 Error::NotFound { .. } => Error::not_found(key),
132 other => other,
133 })?;
134 Ok(ConfigValue::secret(body))
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141 use esh_test_support::{
142 run_provider_conformance, ProviderConformanceCfg, SAMPLE_SECRET,
143 };
144
145 #[tokio::test]
146 async fn reads_secret() {
147 let client = Arc::new(MapGcpClient::new().with_secret("db-url", "postgres://gcp"));
148 let p = GcpSecretManagerProvider::new("demo", client);
149 assert_eq!(p.get("db_url").await.unwrap().as_str(), Some("postgres://gcp"));
150 }
151
152 #[tokio::test]
153 async fn gcp_conformance() {
154 let client = Arc::new(MapGcpClient::new().with_secret("database-url", SAMPLE_SECRET));
155 let p = GcpSecretManagerProvider::new("demo", client);
156 run_provider_conformance(
157 &p,
158 &ProviderConformanceCfg {
159 expected_id: "gcp-secret-manager".into(),
160 expected_capabilities: ProviderCapability {
161 bulk: false,
162 versioned: true,
163 local: false,
164 },
165 present_key: "database_url".into(),
166 present_value: SAMPLE_SECRET.into(),
167 missing_key: "missing".into(),
168 fault_key: None,
169 health_ok: true,
170 test_get_many: true,
171 },
172 )
173 .await;
174 }
175
176 #[tokio::test]
177 async fn gcp_timeout_fault() {
178 let client = Arc::new(
179 MapGcpClient::new()
180 .with_secret("database-url", SAMPLE_SECRET)
181 .with_fault(GcpFault::Timeout),
182 );
183 let p = GcpSecretManagerProvider::new("demo", client);
184 let err = p.get("database_url").await.unwrap_err();
185 assert!(!err.to_string().contains(SAMPLE_SECRET));
186 }
187}