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