ironflow_api/routes/secrets/
update.rs1use axum::Json;
4use axum::extract::{Path, State};
5use axum::response::IntoResponse;
6use serde::Deserialize;
7use validator::Validate;
8
9use ironflow_auth::extractor::Authenticated;
10
11use crate::entities::SecretResponse;
12use crate::error::ApiError;
13use crate::response::ok;
14use crate::routes::secrets::reject_provider_account_key;
15use crate::state::AppState;
16
17#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
19#[derive(Debug, Deserialize, Validate)]
20pub struct UpdateSecretRequest {
21 #[validate(length(min = 1, max = 65536))]
23 pub value: String,
24}
25
26#[cfg_attr(
37 feature = "openapi",
38 utoipa::path(
39 put,
40 path = "/api/v1/secrets/{key}",
41 tags = ["secrets"],
42 params(("key" = String, Path, description = "Secret key")),
43 request_body(content = UpdateSecretRequest, description = "New secret value"),
44 responses(
45 (status = 200, description = "Secret updated", body = SecretResponse),
46 (status = 400, description = "Invalid input"),
47 (status = 401, description = "Unauthorized"),
48 (status = 403, description = "Forbidden"),
49 (status = 404, description = "Secret not found")
50 ),
51 security(("Bearer" = []))
52 )
53)]
54pub async fn update_secret(
55 auth: Authenticated,
56 State(state): State<AppState>,
57 Path(key): Path<String>,
58 Json(req): Json<UpdateSecretRequest>,
59) -> Result<impl IntoResponse, ApiError> {
60 if !auth.is_admin() {
61 return Err(ApiError::Forbidden);
62 }
63 reject_provider_account_key(&key)?;
64
65 req.validate()
66 .map_err(|e| ApiError::BadRequest(e.to_string()))?;
67
68 let existing = state.store.get_secret(&key).await?;
69 if existing.is_none() {
70 return Err(ApiError::SecretNotFound(key));
71 }
72
73 let secret = state.store.set_secret(&key, &req.value).await?;
74
75 Ok(ok(SecretResponse::from(secret)))
76}
77
78#[cfg(test)]
79mod tests {
80 use axum::Router;
81 use axum::body::Body;
82 use axum::http::{Request, StatusCode};
83 use axum::routing::put;
84 use http_body_util::BodyExt;
85 use ironflow_auth::jwt::JwtConfig;
86 use ironflow_core::providers::claude::ClaudeCodeProvider;
87 use ironflow_engine::context::WorkflowContext;
88 use ironflow_engine::engine::Engine;
89 use ironflow_engine::handler::{HandlerFuture, WorkflowHandler};
90 use ironflow_engine::notify::Event;
91 use ironflow_store::crypto::MasterKey;
92 use ironflow_store::memory::InMemoryStore;
93 use ironflow_store::store::Store;
94 use serde_json::{Value as JsonValue, json};
95 use std::sync::Arc;
96 use tokio::sync::broadcast;
97 use tower::ServiceExt;
98
99 use super::*;
100 use crate::routes::test_helpers::create_user_auth_header;
101
102 struct TestWorkflow;
103
104 impl WorkflowHandler for TestWorkflow {
105 fn name(&self) -> &str {
106 "test-workflow"
107 }
108
109 fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
110 Box::pin(async move { Ok(()) })
111 }
112 }
113
114 fn test_jwt_config() -> Arc<JwtConfig> {
115 Arc::new(JwtConfig {
116 secret: "test-secret".to_string(),
117 access_token_ttl_secs: 900,
118 refresh_token_ttl_secs: 604800,
119 cookie_domain: None,
120 cookie_secure: false,
121 })
122 }
123
124 fn test_state() -> AppState {
125 let mut in_mem_store = InMemoryStore::new();
126 let master_key = MasterKey::from_bytes(&[42u8; 32]).unwrap();
127 in_mem_store.set_master_key(master_key);
128 let store: Arc<dyn Store> = Arc::new(in_mem_store);
129 let provider = Arc::new(ClaudeCodeProvider::new());
130 let mut engine = Engine::new(store.clone(), provider);
131 engine.register(TestWorkflow).unwrap();
132 let (event_sender, _) = broadcast::channel::<Event>(1);
133 AppState::new(
134 store,
135 Arc::new(engine),
136 test_jwt_config(),
137 "test-worker-token".to_string(),
138 event_sender,
139 )
140 }
141
142 #[tokio::test]
143 async fn update_secret_admin_only() {
144 let state = test_state();
145 state
146 .store
147 .set_secret("api-key", "old-value")
148 .await
149 .unwrap();
150
151 let auth_header = create_user_auth_header(&state, "user", false).await;
152
153 let app = Router::new()
154 .route("/{key}", put(update_secret))
155 .with_state(state);
156
157 let body = json!({ "value": "new-value" });
158 let req = Request::builder()
159 .uri("/api-key")
160 .method("PUT")
161 .header("authorization", auth_header)
162 .header("content-type", "application/json")
163 .body(Body::from(serde_json::to_string(&body).unwrap()))
164 .unwrap();
165
166 let resp = app.oneshot(req).await.unwrap();
167 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
168 }
169
170 #[tokio::test]
171 async fn update_secret_success() {
172 let state = test_state();
173 state
174 .store
175 .set_secret("api-key", "old-value")
176 .await
177 .unwrap();
178
179 let auth_header = create_user_auth_header(&state, "admin", true).await;
180
181 let app = Router::new()
182 .route("/{key}", put(update_secret))
183 .with_state(state);
184
185 let body = json!({ "value": "new-value" });
186 let req = Request::builder()
187 .uri("/api-key")
188 .method("PUT")
189 .header("authorization", auth_header)
190 .header("content-type", "application/json")
191 .body(Body::from(serde_json::to_string(&body).unwrap()))
192 .unwrap();
193
194 let resp = app.oneshot(req).await.unwrap();
195 assert_eq!(resp.status(), StatusCode::OK);
196
197 let resp_body = resp.into_body().collect().await.unwrap().to_bytes();
198 let json_val: JsonValue = serde_json::from_slice(&resp_body).unwrap();
199 assert_eq!(json_val["data"]["key"], "api-key");
200 }
201
202 #[tokio::test]
203 async fn update_secret_not_found() {
204 let state = test_state();
205 let auth_header = create_user_auth_header(&state, "admin", true).await;
206
207 let app = Router::new()
208 .route("/{key}", put(update_secret))
209 .with_state(state);
210
211 let body = json!({ "value": "new-value" });
212 let req = Request::builder()
213 .uri("/nonexistent-secret")
214 .method("PUT")
215 .header("authorization", auth_header)
216 .header("content-type", "application/json")
217 .body(Body::from(serde_json::to_string(&body).unwrap()))
218 .unwrap();
219
220 let resp = app.oneshot(req).await.unwrap();
221 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
222 }
223
224 #[tokio::test]
225 async fn update_secret_empty_value_validation() {
226 let state = test_state();
227 state.store.set_secret("api-key", "value").await.ok();
228
229 let auth_header = create_user_auth_header(&state, "admin", true).await;
230
231 let app = Router::new()
232 .route("/{key}", put(update_secret))
233 .with_state(state);
234
235 let body = json!({ "value": "" });
236 let req = Request::builder()
237 .uri("/api-key")
238 .method("PUT")
239 .header("authorization", auth_header)
240 .header("content-type", "application/json")
241 .body(Body::from(serde_json::to_string(&body).unwrap()))
242 .unwrap();
243
244 let resp = app.oneshot(req).await.unwrap();
245 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
246 }
247}