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
//! Key Storage Abstraction Layer
//!
//! This module defines the [`KeyStore`] trait for future integration with
//! external key management systems.
//!
//! # Current Implementation
//!
//! Currently, keys are stored as plaintext JSON in `~/.tap/keys.json`.
//! This is suitable for development and testing but **NOT recommended for production**
//! deployments with high-value keys.
//!
//! The current storage flow:
//! 1. Keys are generated or imported into [`AgentKeyManager`](crate::AgentKeyManager)
//! 2. Keys are serialized to [`StoredKey`](crate::StoredKey) format (base64-encoded key material)
//! 3. [`KeyStorage`](crate::KeyStorage) writes JSON to disk at the configured path
//!
//! # Security Considerations
//!
//! The plaintext storage has the following security properties:
//! - **No encryption at rest**: Key material is base64-encoded but not encrypted
//! - **File permissions**: Relies on OS file permissions for access control
//! - **Portable**: Keys can be easily backed up or transferred
//!
//! For production deployments, consider implementing a [`KeyStore`] backend that provides:
//! - Encryption at rest (e.g., envelope encryption with master key)
//! - Hardware security module (HSM) integration
//! - Cloud key management service (KMS) integration
//! - Platform keychain integration
//!
//! # Future External Key Management
//!
//! The [`KeyStore`] trait provides an abstraction that can be implemented for various backends:
//!
//! ## Hardware Security Modules (HSMs)
//! - AWS CloudHSM
//! - Azure Dedicated HSM
//! - Thales Luna HSM
//!
//! ## Cloud Key Management Services
//! - AWS KMS
//! - Google Cloud KMS
//! - Azure Key Vault
//! - HashiCorp Vault
//!
//! ## Platform Keychains
//! - macOS Keychain (Security.framework)
//! - Windows DPAPI / Credential Manager
//! - Linux Secret Service (libsecret)
//!
//! # Implementation Guide
//!
//! To implement a custom key store backend:
//!
//! 1. Implement the [`KeyStore`] trait for your backend
//! 2. Handle key material serialization appropriate for your backend
//! 3. Implement proper error handling for network/hardware failures
//! 4. Consider caching strategies for performance
//!
//! ## Example: HashiCorp Vault Integration
//!
//! ```rust,ignore
//! use tap_agent::key_store::{KeyStore, KeyStoreError};
//! use async_trait::async_trait;
//!
//! pub struct VaultKeyStore {
//! client: vault::Client,
//! mount_path: String,
//! }
//!
//! impl VaultKeyStore {
//! pub fn new(addr: &str, token: &str) -> Result<Self, Box<dyn std::error::Error>> {
//! let client = vault::Client::new(addr, token)?;
//! Ok(Self {
//! client,
//! mount_path: "secret/tap-keys".to_string(),
//! })
//! }
//! }
//!
//! #[async_trait]
//! impl KeyStore for VaultKeyStore {
//! async fn store_key(&self, id: &str, material: &[u8]) -> Result<(), KeyStoreError> {
//! let path = format!("{}/{}", self.mount_path, id);
//! let data = base64::encode(material);
//! self.client.secrets().kv2().set(&path, &[("key", &data)]).await
//! .map_err(|e| KeyStoreError::Storage(e.to_string()))?;
//! Ok(())
//! }
//!
//! async fn load_key(&self, id: &str) -> Result<Vec<u8>, KeyStoreError> {
//! let path = format!("{}/{}", self.mount_path, id);
//! let secret = self.client.secrets().kv2().get(&path).await
//! .map_err(|e| KeyStoreError::NotFound(id.to_string()))?;
//! let data = secret.data.get("key")
//! .ok_or_else(|| KeyStoreError::InvalidFormat("Missing key field".to_string()))?;
//! base64::decode(data)
//! .map_err(|e| KeyStoreError::InvalidFormat(e.to_string()))
//! }
//!
//! async fn delete_key(&self, id: &str) -> Result<(), KeyStoreError> {
//! let path = format!("{}/{}", self.mount_path, id);
//! self.client.secrets().kv2().delete(&path).await
//! .map_err(|e| KeyStoreError::Storage(e.to_string()))?;
//! Ok(())
//! }
//!
//! async fn key_exists(&self, id: &str) -> Result<bool, KeyStoreError> {
//! let path = format!("{}/{}", self.mount_path, id);
//! match self.client.secrets().kv2().get(&path).await {
//! Ok(_) => Ok(true),
//! Err(_) => Ok(false),
//! }
//! }
//!
//! async fn list_keys(&self) -> Result<Vec<String>, KeyStoreError> {
//! self.client.secrets().kv2().list(&self.mount_path).await
//! .map_err(|e| KeyStoreError::Storage(e.to_string()))
//! }
//! }
//! ```
//!
//! ## Integration with AgentKeyManager
//!
//! Future versions will support passing a custom [`KeyStore`] to the
//! [`AgentKeyManagerBuilder`](crate::AgentKeyManagerBuilder):
//!
//! ```rust,ignore
//! let vault_store = VaultKeyStore::new("https://vault.example.com", token)?;
//!
//! let key_manager = AgentKeyManagerBuilder::new()
//! .with_key_store(Box::new(vault_store))
//! .build()?;
//! ```
use async_trait;
/// Error types for key storage operations
/// Trait for key storage backends
///
/// Implement this trait to integrate with external key management systems.
/// All operations are async to support network-based backends (HSMs, cloud KMS, etc.).
///
/// # Thread Safety
///
/// Implementations must be `Send + Sync` to allow use across async tasks.
///
/// # Error Handling
///
/// Implementations should:
/// - Return `KeyStoreError::NotFound` for missing keys (not a general error)
/// - Return `KeyStoreError::AccessDenied` for permission issues
/// - Return `KeyStoreError::Unavailable` for transient failures (enable retry logic)
/// - Return `KeyStoreError::Storage` for other backend errors
/// Plaintext file-based key store
///
/// **WARNING**: This implementation stores keys as plaintext JSON.
/// It wraps the existing [`KeyStorage`](crate::KeyStorage) implementation
/// for backwards compatibility.
///
/// Use only for development and testing. For production deployments,
/// implement a secure [`KeyStore`] backend with encryption at rest.