Skip to main content

ironflow_api/routes/secrets/
update.rs

1//! `PUT /api/v1/secrets/:key` -- Update a secret value (admin only).
2
3use 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/// Request body for updating a secret value.
18#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
19#[derive(Debug, Deserialize, Validate)]
20pub struct UpdateSecretRequest {
21    /// New secret value (plaintext, will be encrypted at rest).
22    #[validate(length(min = 1, max = 65536))]
23    pub value: String,
24}
25
26/// Update a secret's value. Admin only.
27///
28/// The key is taken from the URL path. The response never includes
29/// the secret value.
30///
31/// # Errors
32///
33/// - 403 if the caller is not an admin
34/// - 404 if the secret key does not exist
35/// - 400 if the value is invalid
36#[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::{AccessToken, 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    use uuid::Uuid;
99
100    use super::*;
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    fn make_admin_token(state: &AppState) -> String {
143        let user_id = Uuid::now_v7();
144        let token = AccessToken::for_user(user_id, "admin", true, &state.jwt_config).unwrap();
145        format!("Bearer {}", token.0)
146    }
147
148    fn make_regular_token(state: &AppState) -> String {
149        let user_id = Uuid::now_v7();
150        let token = AccessToken::for_user(user_id, "user", false, &state.jwt_config).unwrap();
151        format!("Bearer {}", token.0)
152    }
153
154    #[tokio::test]
155    async fn update_secret_admin_only() {
156        let state = test_state();
157        state
158            .store
159            .set_secret("api-key", "old-value")
160            .await
161            .unwrap();
162
163        let auth_header = make_regular_token(&state);
164
165        let app = Router::new()
166            .route("/{key}", put(update_secret))
167            .with_state(state);
168
169        let body = json!({ "value": "new-value" });
170        let req = Request::builder()
171            .uri("/api-key")
172            .method("PUT")
173            .header("authorization", auth_header)
174            .header("content-type", "application/json")
175            .body(Body::from(serde_json::to_string(&body).unwrap()))
176            .unwrap();
177
178        let resp = app.oneshot(req).await.unwrap();
179        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
180    }
181
182    #[tokio::test]
183    async fn update_secret_success() {
184        let state = test_state();
185        state
186            .store
187            .set_secret("api-key", "old-value")
188            .await
189            .unwrap();
190
191        let auth_header = make_admin_token(&state);
192
193        let app = Router::new()
194            .route("/{key}", put(update_secret))
195            .with_state(state);
196
197        let body = json!({ "value": "new-value" });
198        let req = Request::builder()
199            .uri("/api-key")
200            .method("PUT")
201            .header("authorization", auth_header)
202            .header("content-type", "application/json")
203            .body(Body::from(serde_json::to_string(&body).unwrap()))
204            .unwrap();
205
206        let resp = app.oneshot(req).await.unwrap();
207        assert_eq!(resp.status(), StatusCode::OK);
208
209        let resp_body = resp.into_body().collect().await.unwrap().to_bytes();
210        let json_val: JsonValue = serde_json::from_slice(&resp_body).unwrap();
211        assert_eq!(json_val["data"]["key"], "api-key");
212    }
213
214    #[tokio::test]
215    async fn update_secret_not_found() {
216        let state = test_state();
217        let auth_header = make_admin_token(&state);
218
219        let app = Router::new()
220            .route("/{key}", put(update_secret))
221            .with_state(state);
222
223        let body = json!({ "value": "new-value" });
224        let req = Request::builder()
225            .uri("/nonexistent-secret")
226            .method("PUT")
227            .header("authorization", auth_header)
228            .header("content-type", "application/json")
229            .body(Body::from(serde_json::to_string(&body).unwrap()))
230            .unwrap();
231
232        let resp = app.oneshot(req).await.unwrap();
233        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
234    }
235
236    #[tokio::test]
237    async fn update_secret_empty_value_validation() {
238        let state = test_state();
239        state.store.set_secret("api-key", "value").await.ok();
240
241        let auth_header = make_admin_token(&state);
242
243        let app = Router::new()
244            .route("/{key}", put(update_secret))
245            .with_state(state);
246
247        let body = json!({ "value": "" });
248        let req = Request::builder()
249            .uri("/api-key")
250            .method("PUT")
251            .header("authorization", auth_header)
252            .header("content-type", "application/json")
253            .body(Body::from(serde_json::to_string(&body).unwrap()))
254            .unwrap();
255
256        let resp = app.oneshot(req).await.unwrap();
257        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
258    }
259}