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
//! Keychain service for token/credential caching.
//!
//! The keychain is the per-execution cache of resolved secrets / minted tokens
//! (noetl/ai-meta#61). Cached values are envelope-encrypted with the same
//! wallet primitives as credentials (per-record DEK wrapped by the KEK) and
//! stored as the self-describing envelope JSON. Forward-only — no legacy path.
use chrono::{Duration, Utc};
use crate::crypto::EnvelopeCipher;
use crate::db::models::{
KeychainDeleteResponse, KeychainEntrySummary, KeychainGetResponse, KeychainListResponse,
KeychainSetRequest, KeychainSetResponse,
};
use crate::db::queries::keychain as queries;
use crate::db::DbPool;
use crate::error::AppResult;
/// Service for keychain operations.
#[derive(Clone)]
pub struct KeychainService {
pool: DbPool,
cipher: EnvelopeCipher,
}
impl KeychainService {
/// Create a new keychain service.
///
/// `cipher` is the wallet's [`EnvelopeCipher`] (shared with the credential
/// service), built once over the configured KEK provider.
pub fn new(pool: DbPool, cipher: EnvelopeCipher) -> Self {
Self { pool, cipher }
}
/// Get a keychain entry.
pub async fn get(
&self,
catalog_id: i64,
keychain_name: &str,
execution_id: Option<i64>,
scope_type: &str,
) -> AppResult<KeychainGetResponse> {
let cache_key =
queries::build_cache_key(keychain_name, catalog_id, scope_type, execution_id);
let entry = match queries::get_keychain_by_cache_key(&self.pool, &cache_key).await? {
Some(e) => e,
None => {
return Ok(KeychainGetResponse {
status: "not_found".to_string(),
data: None,
expires_at: None,
auto_renew: None,
access_count: None,
});
}
};
// Check if expired
if let Some(expires_at) = entry.expires_at {
if expires_at < Utc::now() {
return Ok(KeychainGetResponse {
status: "expired".to_string(),
data: None,
expires_at: Some(expires_at),
auto_renew: Some(entry.auto_renew),
access_count: Some(entry.access_count),
});
}
}
// Increment access count (keyed by cache_key — the table PK).
queries::increment_access_count(&self.pool, &entry.cache_key).await?;
// Decrypt data: `data_encrypted` (TEXT) holds the self-describing
// envelope JSON string (same storage form as `noetl.credential`).
let data = self.cipher.open_storage_json(&entry.data_encrypted).await?;
Ok(KeychainGetResponse {
status: "found".to_string(),
data: Some(data),
expires_at: entry.expires_at,
auto_renew: Some(entry.auto_renew),
access_count: Some(entry.access_count + 1),
})
}
/// Secrets Wallet Phase 7c.2 — should the cached row for
/// `(catalog_id, keychain_name, execution_id, scope_type)` be
/// refreshed in the background right now?
///
/// Reads the row's `expires_at`, hands it to
/// [`crate::secrets::dynamic::should_refresh_default`] (which
/// honours `KEYCHAIN_CACHE_REFRESH_WINDOW_SECS`), and returns the
/// pure-function answer.
///
/// Returns `false` when the row doesn't exist, the row has no
/// issuer-reported `expires_at`, the row is already expired
/// (eviction path), or the row's remaining lifetime is outside the
/// refresh window. Returns `true` only when the cached row is
/// still valid AND inside the window.
///
/// Bumps `noetl_secret_refresh_total{outcome="triggered"}` when
/// returning `true`. The actual background spawn + per-(catalog_id,
/// alias) `tokio::sync::Mutex` stampede collapse + provider re-
/// resolution lives in Phase 7c.3.
pub async fn should_refresh(
&self,
catalog_id: i64,
keychain_name: &str,
execution_id: Option<i64>,
scope_type: &str,
now: chrono::DateTime<Utc>,
) -> AppResult<bool> {
let cache_key =
queries::build_cache_key(keychain_name, catalog_id, scope_type, execution_id);
let Some(entry) = queries::get_keychain_by_cache_key(&self.pool, &cache_key).await? else {
return Ok(false);
};
let triggered = crate::secrets::dynamic::should_refresh_default(entry.expires_at, now);
if triggered {
crate::metrics::record_secret_refresh("triggered");
}
Ok(triggered)
}
/// Set a keychain entry.
pub async fn set(
&self,
catalog_id: i64,
keychain_name: &str,
request: KeychainSetRequest,
) -> AppResult<KeychainSetResponse> {
let cache_key = queries::build_cache_key(
keychain_name,
catalog_id,
&request.scope_type,
request.execution_id,
);
// Calculate expiry time
let expires_at = request.expires_at.or_else(|| {
request
.expires_in
.map(|seconds| Utc::now() + Duration::seconds(seconds))
});
// Envelope-seal data into the self-describing JSON string, stored in
// the `data_encrypted` TEXT column (same form as `noetl.credential`).
let encrypted_data = self.cipher.seal_json_to_storage(&request.data).await?;
// Upsert entry
queries::upsert_keychain_entry(
&self.pool,
&cache_key,
catalog_id,
keychain_name,
&request.scope_type,
request.execution_id,
&encrypted_data,
expires_at,
request.auto_renew,
request.renew_config.as_ref(),
)
.await?;
Ok(KeychainSetResponse {
status: "success".to_string(),
cache_key,
expires_at,
})
}
/// Delete a keychain entry.
pub async fn delete(
&self,
catalog_id: i64,
keychain_name: &str,
execution_id: Option<i64>,
scope_type: &str,
) -> AppResult<KeychainDeleteResponse> {
let cache_key =
queries::build_cache_key(keychain_name, catalog_id, scope_type, execution_id);
let deleted = queries::delete_keychain_by_cache_key(&self.pool, &cache_key).await?;
Ok(KeychainDeleteResponse {
status: if deleted { "deleted" } else { "not_found" }.to_string(),
cache_key: if deleted { Some(cache_key) } else { None },
})
}
/// List all keychain entries for a catalog.
pub async fn list_by_catalog(&self, catalog_id: i64) -> AppResult<KeychainListResponse> {
let entries = queries::list_keychain_by_catalog(&self.pool, catalog_id).await?;
let now = Utc::now();
let summaries: Vec<KeychainEntrySummary> = entries
.into_iter()
.map(|e| {
let expired = e.expires_at.map(|exp| exp < now).unwrap_or(false);
KeychainEntrySummary {
keychain_name: e.keychain_name,
scope_type: e.scope_type,
execution_id: e.execution_id.map(|id| id.to_string()),
expires_at: e.expires_at,
expired,
access_count: e.access_count,
accessed_at: e.accessed_at,
created_at: e.created_at,
}
})
.collect();
Ok(KeychainListResponse {
catalog_id: catalog_id.to_string(),
entries: summaries,
})
}
/// Delete all expired entries (maintenance task).
pub async fn cleanup_expired(&self) -> AppResult<u64> {
queries::delete_expired_entries(&self.pool).await
}
/// Delete all entries for an execution.
pub async fn cleanup_execution(&self, execution_id: i64) -> AppResult<u64> {
queries::delete_keychain_by_execution(&self.pool, execution_id).await
}
}