bamboo-server 2026.7.34

HTTP server and API layer for the Bamboo agent framework
Documentation
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Provider instance CRUD APIs.
//!
//! Endpoints:
//! - `GET    /bamboo/settings/provider-instances`         — list all instances
//! - `POST   /bamboo/settings/provider-instances`         — create a new instance
//! - `PUT    /bamboo/settings/provider-instances/{id}`    — update an instance
//! - `DELETE /bamboo/settings/provider-instances/{id}`    — delete an instance
//! - `POST   /bamboo/settings/provider-instances/default` — set default instance

use actix_web::{web, HttpResponse};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use uuid::Uuid;

use bamboo_config::{FeatureFlags, ProviderInstanceConfig};
use bamboo_llm::AVAILABLE_PROVIDERS;

use crate::app_state::{AppState, ConfigUpdateEffects};
use crate::config_manager;
use crate::error::AppError;

// ─── Types ──────────────────────────────────────────────────────────

/// Frontend-facing response body for `GET /provider-instances`.
#[derive(Serialize)]
pub struct ListInstancesResponse {
    pub instances: Vec<ProviderInstanceResponse>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_provider_instance_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defaults: Option<bamboo_config::DefaultsConfig>,
    pub features: FeatureFlags,
}

/// Frontend-facing provider instance shape.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ProviderInstanceResponse {
    pub id: String,
    #[serde(rename = "type")]
    pub r#type: String,
    pub label: String,
    pub enabled: bool,
    pub config: Map<String, Value>,
}

/// Request body for `POST /provider-instances` (create).
#[derive(Debug, Clone, Deserialize)]
pub struct CreateInstanceRequest {
    #[serde(rename = "type")]
    pub provider_type: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub enabled: Option<bool>,
    pub config: Value,
}

/// Request body for `PUT /provider-instances/{id}` (update).
#[derive(Debug, Clone, Deserialize)]
pub struct UpdateInstanceRequest {
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub config: Option<Value>,
}

/// Request body for `POST /provider-instances/default` (set default).
#[derive(Debug, Clone, Deserialize)]
pub struct SetDefaultInstanceRequest {
    #[serde(alias = "instance_id")]
    pub default_provider_instance_id: String,
}

// ─── Helpers ────────────────────────────────────────────────────────

fn default_label_for_provider_type(provider_type: &str) -> String {
    match provider_type {
        "openai" => "OpenAI".to_string(),
        "anthropic" => "Anthropic".to_string(),
        "gemini" => "Gemini".to_string(),
        "copilot" => "GitHub Copilot".to_string(),
        "bodhi" => "Bodhi".to_string(),
        other => other.to_string(),
    }
}

fn instance_config_to_api(instance: &ProviderInstanceConfig) -> Map<String, Value> {
    let mut config = Map::new();

    if !instance.api_key.trim().is_empty()
        || instance.api_key_encrypted.is_some()
        || instance.credential_ref.is_some()
    {
        config.insert(
            "api_key".to_string(),
            Value::String("****...****".to_string()),
        );
    }

    if let Some(base_url) = &instance.base_url {
        config.insert("base_url".to_string(), Value::String(base_url.clone()));
    }
    if let Some(model) = &instance.model {
        config.insert("model".to_string(), Value::String(model.clone()));
    }
    if let Some(fast_model) = &instance.fast_model {
        config.insert("fast_model".to_string(), Value::String(fast_model.clone()));
    }
    if let Some(vision_model) = &instance.vision_model {
        config.insert(
            "vision_model".to_string(),
            Value::String(vision_model.clone()),
        );
    }
    if let Some(reasoning_effort) = instance.reasoning_effort {
        config.insert(
            "reasoning_effort".to_string(),
            serde_json::to_value(reasoning_effort).expect("reasoning_effort should serialize"),
        );
    }
    if !instance.responses_only_models.is_empty() {
        config.insert(
            "responses_only_models".to_string(),
            serde_json::to_value(&instance.responses_only_models)
                .expect("responses_only_models should serialize"),
        );
    }
    if let Some(request_overrides) = &instance.request_overrides {
        config.insert(
            "request_overrides".to_string(),
            serde_json::to_value(request_overrides).expect("request_overrides should serialize"),
        );
    }

    for (key, value) in &instance.extra {
        if key == "api_key_encrypted" {
            continue;
        }
        config.insert(key.clone(), value.clone());
    }

    config
}

fn instance_to_api(id: &str, instance: &ProviderInstanceConfig) -> ProviderInstanceResponse {
    ProviderInstanceResponse {
        id: id.to_string(),
        r#type: instance.provider_type.clone(),
        label: instance
            .label
            .clone()
            .unwrap_or_else(|| default_label_for_provider_type(&instance.provider_type)),
        enabled: instance.enabled,
        config: instance_config_to_api(instance),
    }
}

fn validate_instance_id(id: &str) -> Result<(), AppError> {
    if id.trim().is_empty() {
        return Err(AppError::BadRequest(
            "instance_id must not be empty".to_string(),
        ));
    }
    if id.len() > 128 {
        return Err(AppError::BadRequest(
            "instance_id must be at most 128 characters".to_string(),
        ));
    }
    Ok(())
}

fn validate_provider_type(provider_type: &str) -> Result<(), AppError> {
    if !AVAILABLE_PROVIDERS.contains(&provider_type) {
        return Err(AppError::BadRequest(format!(
            "Unknown provider_type '{}'. Available: {}",
            provider_type,
            AVAILABLE_PROVIDERS.join(", ")
        )));
    }
    Ok(())
}

fn validate_instance_config(instance: &ProviderInstanceConfig) -> Result<(), AppError> {
    validate_provider_type(&instance.provider_type)?;

    if instance.provider_type != "copilot" && instance.api_key.trim().is_empty() {
        return Err(AppError::BadRequest(
            "api_key is required for non-copilot providers".to_string(),
        ));
    }

    Ok(())
}

fn config_value_as_object(value: Value) -> Result<Map<String, Value>, AppError> {
    config_manager::assert_json_object(value)
}

fn build_instance_from_create(
    payload: &CreateInstanceRequest,
) -> Result<ProviderInstanceConfig, AppError> {
    validate_provider_type(&payload.provider_type)?;

    let mut obj = config_value_as_object(payload.config.clone())?;
    obj.remove("api_key_encrypted");
    obj.remove("credential_ref");
    obj.insert(
        "provider_type".to_string(),
        Value::String(payload.provider_type.clone()),
    );
    if let Some(label) = payload.label.clone() {
        obj.insert("label".to_string(), Value::String(label));
    }
    if let Some(enabled) = payload.enabled {
        obj.insert("enabled".to_string(), Value::Bool(enabled));
    }

    let instance: ProviderInstanceConfig = serde_json::from_value(Value::Object(obj))
        .map_err(|e| AppError::BadRequest(format!("Invalid provider instance config: {e}")))?;
    // On CREATE there is no existing key a placeholder could refer to — storing
    // the literal `****...****` as the api_key would break the provider (#430).
    if config_manager::is_masked_api_key(&instance.api_key) {
        return Err(AppError::BadRequest(
            "api_key looks like a masked placeholder (`****...****`); enter the real key"
                .to_string(),
        ));
    }
    validate_instance_config(&instance)?;
    Ok(instance)
}

fn instance_to_patchable_value(instance: &ProviderInstanceConfig) -> Result<Value, AppError> {
    let mut value = serde_json::to_value(instance).map_err(|e| {
        AppError::InternalError(anyhow::anyhow!(
            "Failed to serialize provider instance for patching: {e}"
        ))
    })?;

    let Some(obj) = value.as_object_mut() else {
        return Err(AppError::InternalError(anyhow::anyhow!(
            "Serialized provider instance was not a JSON object"
        )));
    };

    if !instance.api_key.trim().is_empty() {
        obj.insert(
            "api_key".to_string(),
            Value::String(instance.api_key.clone()),
        );
    }

    Ok(value)
}

fn apply_instance_update(
    existing: &ProviderInstanceConfig,
    payload: &UpdateInstanceRequest,
) -> Result<ProviderInstanceConfig, AppError> {
    let mut merged = instance_to_patchable_value(existing)?;
    let Some(obj) = merged.as_object_mut() else {
        return Err(AppError::InternalError(anyhow::anyhow!(
            "Serialized provider instance was not a JSON object"
        )));
    };

    if let Some(label) = payload.label.clone() {
        obj.insert("label".to_string(), Value::String(label));
    }
    if let Some(enabled) = payload.enabled {
        obj.insert("enabled".to_string(), Value::Bool(enabled));
    }

    if let Some(config_patch) = payload.config.clone() {
        let mut patch_obj = config_value_as_object(config_patch)?;

        if let Some(api_key) = patch_obj.get("api_key").and_then(|v| v.as_str()) {
            if config_manager::is_masked_api_key(api_key) {
                if existing.api_key.trim().is_empty() {
                    patch_obj.remove("api_key");
                } else {
                    patch_obj.insert(
                        "api_key".to_string(),
                        Value::String(existing.api_key.clone()),
                    );
                }
            }
        }

        patch_obj.remove("provider_type");
        patch_obj.remove("label");
        patch_obj.remove("enabled");
        patch_obj.remove("api_key_encrypted");
        patch_obj.remove("credential_ref");

        for (key, value) in patch_obj {
            obj.insert(key, value);
        }
    }

    obj.insert(
        "provider_type".to_string(),
        Value::String(existing.provider_type.clone()),
    );

    let updated: ProviderInstanceConfig = serde_json::from_value(merged)
        .map_err(|e| AppError::BadRequest(format!("Invalid provider instance config: {e}")))?;
    validate_instance_config(&updated)?;
    Ok(updated)
}

// ─── Handlers ───────────────────────────────────────────────────────

/// GET /bamboo/settings/provider-instances
pub async fn list_provider_instances(
    app_state: web::Data<AppState>,
) -> Result<HttpResponse, AppError> {
    let config = app_state.config.read().await;
    let instances: Vec<ProviderInstanceResponse> = config
        .provider_instances
        .iter()
        .map(|(id, instance)| instance_to_api(id, instance))
        .collect();

    Ok(HttpResponse::Ok().json(ListInstancesResponse {
        instances,
        default_provider_instance_id: config.default_provider_instance.clone(),
        defaults: config.defaults.clone(),
        features: config.features.clone(),
    }))
}

/// POST /bamboo/settings/provider-instances
pub async fn create_provider_instance(
    app_state: web::Data<AppState>,
    payload: web::Json<CreateInstanceRequest>,
) -> Result<HttpResponse, AppError> {
    let instance_id = Uuid::new_v4().to_string();
    validate_instance_id(&instance_id)?;

    let instance_config = build_instance_from_create(&payload)?;
    let instance_id_for_response = instance_id.clone();
    let instance_id_for_intent = instance_id.clone();

    let new_config = app_state
        .update_config_with_provider_credentials(
            move |config| {
                if config.provider_instances.contains_key(&instance_id) {
                    return Err(AppError::BadRequest(format!(
                        "Provider instance '{}' already exists",
                        instance_id
                    )));
                }
                let should_set_default = config.default_provider_instance.is_none();
                config
                    .provider_instances
                    .insert(instance_id.clone(), instance_config.clone());
                if should_set_default {
                    config.default_provider_instance = Some(instance_id.clone());
                }
                // No explicit ciphertext refresh needed here: `update_config`
                // runs `Config::refresh_encrypted_secrets` on the live config
                // after this closure (#515/#516), so `api_key_encrypted` is
                // populated in memory before persist/response.
                Ok(())
            },
            std::collections::BTreeSet::new(),
            std::collections::BTreeSet::from([instance_id_for_intent]),
            ConfigUpdateEffects {
                reload_provider: true,
                reconcile_mcp: false,
            },
        )
        .await?;

    let created = new_config
        .provider_instances
        .get(&instance_id_for_response)
        .ok_or_else(|| {
            AppError::InternalError(anyhow::anyhow!(
                "Created provider instance '{}' missing from config snapshot",
                instance_id_for_response
            ))
        })?;

    Ok(HttpResponse::Created().json(instance_to_api(&instance_id_for_response, created)))
}

/// PUT /bamboo/settings/provider-instances/{instance_id}
pub async fn update_provider_instance(
    app_state: web::Data<AppState>,
    path: web::Path<String>,
    payload: web::Json<UpdateInstanceRequest>,
) -> Result<HttpResponse, AppError> {
    let instance_id = path.into_inner();
    validate_instance_id(&instance_id)?;
    let payload_inner = payload.into_inner();
    let instance_id_for_response = instance_id.clone();
    let has_api_key_intent = payload_inner
        .config
        .as_ref()
        .and_then(Value::as_object)
        .and_then(|config| config.get("api_key"))
        .is_some_and(|value| match value {
            Value::Null => true,
            Value::String(value) => !config_manager::is_masked_api_key(value),
            _ => false,
        });
    let provider_instance_intents = if has_api_key_intent {
        std::collections::BTreeSet::from([instance_id.clone()])
    } else {
        std::collections::BTreeSet::new()
    };

    let new_config = app_state
        .update_config_with_provider_credentials(
            move |config| {
                let existing = config
                    .provider_instances
                    .get(&instance_id)
                    .cloned()
                    .ok_or_else(|| {
                        AppError::BadRequest(format!(
                            "Provider instance '{}' not found",
                            instance_id
                        ))
                    })?;

                let updated = apply_instance_update(&existing, &payload_inner)?;
                config
                    .provider_instances
                    .insert(instance_id.clone(), updated);
                // Ciphertext sync happens centrally in `update_config` via
                // `Config::refresh_encrypted_secrets` (#515/#516).
                Ok(())
            },
            std::collections::BTreeSet::new(),
            provider_instance_intents,
            ConfigUpdateEffects {
                reload_provider: true,
                reconcile_mcp: false,
            },
        )
        .await?;

    let updated = new_config
        .provider_instances
        .get(&instance_id_for_response)
        .ok_or_else(|| {
            AppError::InternalError(anyhow::anyhow!(
                "Updated provider instance '{}' missing from config snapshot",
                instance_id_for_response
            ))
        })?;

    Ok(HttpResponse::Ok().json(instance_to_api(&instance_id_for_response, updated)))
}

/// DELETE /bamboo/settings/provider-instances/{instance_id}
pub async fn delete_provider_instance(
    app_state: web::Data<AppState>,
    path: web::Path<String>,
) -> Result<HttpResponse, AppError> {
    let instance_id = path.into_inner();
    validate_instance_id(&instance_id)?;
    let instance_id_for_closure = instance_id.clone();
    let provider_instance_intents = std::collections::BTreeSet::from([instance_id.clone()]);

    let new_config = app_state
        .update_config_with_provider_credentials(
            move |config| {
                if config
                    .provider_instances
                    .remove(&instance_id_for_closure)
                    .is_none()
                {
                    return Err(AppError::BadRequest(format!(
                        "Provider instance '{}' not found",
                        instance_id_for_closure
                    )));
                }
                if config.default_provider_instance.as_deref() == Some(&instance_id_for_closure) {
                    config.default_provider_instance = None;
                }
                Ok(())
            },
            std::collections::BTreeSet::new(),
            provider_instance_intents,
            ConfigUpdateEffects {
                reload_provider: true,
                reconcile_mcp: false,
            },
        )
        .await?;

    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "deleted": instance_id,
        "default_provider_instance_id": new_config.default_provider_instance,
    })))
}

/// POST /bamboo/settings/provider-instances/default
pub async fn set_default_provider_instance(
    app_state: web::Data<AppState>,
    payload: web::Json<SetDefaultInstanceRequest>,
) -> Result<HttpResponse, AppError> {
    let target_id = payload.default_provider_instance_id.clone();

    let new_config = app_state
        .update_config(
            move |config| {
                let is_instance = config.provider_instances.contains_key(&target_id);
                let is_legacy_type = AVAILABLE_PROVIDERS.contains(&target_id.as_str());
                if !is_instance && !is_legacy_type {
                    return Err(AppError::BadRequest(format!(
                        "Cannot set '{}' as default: not a known provider instance or type",
                        target_id
                    )));
                }
                config.default_provider_instance = Some(target_id.clone());
                Ok(())
            },
            ConfigUpdateEffects {
                reload_provider: true,
                reconcile_mcp: false,
            },
        )
        .await?;

    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "default_provider_instance_id": new_config.default_provider_instance,
    })))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_request(api_key: &str) -> CreateInstanceRequest {
        CreateInstanceRequest {
            provider_type: "openai".to_string(),
            label: None,
            enabled: None,
            config: serde_json::json!({ "api_key": api_key }),
        }
    }

    #[test]
    fn create_rejects_masked_placeholder_api_key() {
        let err = build_instance_from_create(&create_request("****...****"))
            .expect_err("placeholder api_key must be rejected on create");
        assert!(matches!(err, AppError::BadRequest(_)));
    }

    #[test]
    fn create_accepts_real_api_key_even_with_placeholder_residue() {
        // A paste that didn't fully clear the prefilled placeholder is a real
        // (if garbled) key — it must be stored as given, not silently dropped.
        let instance = build_instance_from_create(&create_request("****...****sk-new"))
            .expect("mixed value is not a placeholder");
        assert_eq!(instance.api_key, "****...****sk-new");
    }

    #[test]
    fn create_and_update_ignore_client_owned_credential_metadata() {
        let mut request = create_request("sk-real");
        request.config["api_key_encrypted"] = Value::String("client-cipher".to_string());
        request.config["credential_ref"] = Value::String("attacker.chosen.ref".to_string());
        let instance = build_instance_from_create(&request).unwrap();
        assert!(instance.api_key_encrypted.is_none());
        assert!(instance.credential_ref.is_none());

        let updated = apply_instance_update(
            &instance,
            &UpdateInstanceRequest {
                label: None,
                enabled: None,
                config: Some(serde_json::json!({
                    "api_key_encrypted": "replacement-cipher",
                    "credential_ref": "attacker.replacement.ref",
                    "model": "gpt-safe"
                })),
            },
        )
        .unwrap();
        assert!(updated.api_key_encrypted.is_none());
        assert!(updated.credential_ref.is_none());
        assert_eq!(updated.model.as_deref(), Some("gpt-safe"));
    }

    #[test]
    fn api_reports_ref_backed_instance_as_configured_without_exposing_ref() {
        let mut instance = build_instance_from_create(&create_request("sk-real")).unwrap();
        instance.api_key.clear();
        instance.credential_ref =
            Some(bamboo_config::credential_ref("provider_instance", "work", "api_key").unwrap());
        let api = instance_config_to_api(&instance);
        assert_eq!(api["api_key"], "****...****");
        assert!(!api.contains_key("credential_ref"));
        assert!(!api.contains_key("api_key_encrypted"));
    }

    // A provider-instance secret is committed to credentials.json before its
    // ref-backed metadata is published. Later generic saves must retain the ref
    // without reintroducing ciphertext into config.json.
    #[tokio::test]
    async fn settings_save_preserves_instance_credential_ref_same_session() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let state = AppState::new(temp_dir.path().to_path_buf())
            .await
            .expect("app state should initialize");
        let app_state = web::Data::new(state);

        let create_resp = create_provider_instance(
            app_state.clone(),
            web::Json(create_request("sk-instance-secret")),
        )
        .await
        .expect("create should succeed");
        assert_eq!(create_resp.status(), actix_web::http::StatusCode::CREATED);

        // A settings save that does not mention `provider_instances` at all.
        let save_payload: Value =
            serde_json::json!({ "http_proxy": "http://example.invalid:8080" });
        crate::handlers::settings::set_bamboo_config(app_state.clone(), web::Json(save_payload))
            .await
            .expect("unrelated settings save should succeed");

        let config_path = temp_dir.path().join("providers.json");
        let raw = std::fs::read_to_string(&config_path).expect("providers.json should exist");
        let on_disk: Value =
            serde_json::from_str(&raw).expect("providers.json should be valid JSON");
        let instances = on_disk
            .get("data")
            .and_then(|data| data.get("provider_instances"))
            .and_then(|v| v.as_object())
            .expect("provider_instances should be present on disk");
        assert_eq!(instances.len(), 1, "exactly one instance was created");
        let (_id, instance) = instances.iter().next().expect("instance present");
        assert!(instance.get("api_key_encrypted").is_none());
        let reference = bamboo_config::CredentialRef::parse(
            instance["credential_ref"].as_str().expect("credential ref"),
        )
        .unwrap();
        assert_eq!(
            bamboo_config::CredentialStore::open(temp_dir.path())
                .resolve(&reference)
                .unwrap()
                .unwrap()
                .expose(),
            "sk-instance-secret"
        );
    }

    // Same as above but through the update path: an update that never touches
    // `config` (so `api_key` isn't in the patch at all) must also keep the
    // live in-memory ciphertext in sync, so a later unrelated settings save
    // doesn't wipe it either.
    #[tokio::test]
    async fn settings_save_preserves_instance_credential_ref_after_update_same_session() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let state = AppState::new(temp_dir.path().to_path_buf())
            .await
            .expect("app state should initialize");
        let app_state = web::Data::new(state);

        create_provider_instance(
            app_state.clone(),
            web::Json(create_request("sk-instance-secret")),
        )
        .await
        .expect("create should succeed");

        let instance_id = {
            let config = app_state.config.read().await;
            config
                .provider_instances
                .keys()
                .next()
                .cloned()
                .expect("instance exists")
        };

        let update_payload = UpdateInstanceRequest {
            label: Some("Renamed".to_string()),
            enabled: None,
            config: None,
        };
        update_provider_instance(
            app_state.clone(),
            web::Path::from(instance_id.clone()),
            web::Json(update_payload),
        )
        .await
        .expect("update should succeed");

        let save_payload: Value =
            serde_json::json!({ "http_proxy": "http://example.invalid:9090" });
        crate::handlers::settings::set_bamboo_config(app_state.clone(), web::Json(save_payload))
            .await
            .expect("unrelated settings save should succeed");

        let config_path = temp_dir.path().join("providers.json");
        let raw = std::fs::read_to_string(&config_path).expect("providers.json should exist");
        let on_disk: Value =
            serde_json::from_str(&raw).expect("providers.json should be valid JSON");
        let instance = &on_disk["data"]["provider_instances"][&instance_id];
        assert!(instance.get("api_key_encrypted").is_none());
        let reference = bamboo_config::CredentialRef::parse(
            instance["credential_ref"].as_str().expect("credential ref"),
        )
        .unwrap();
        assert_eq!(
            bamboo_config::CredentialStore::open(temp_dir.path())
                .resolve(&reference)
                .unwrap()
                .unwrap()
                .expose(),
            "sk-instance-secret"
        );
        assert_eq!(
            instance.get("label").and_then(|v| v.as_str()),
            Some("Renamed"),
            "the update itself should still apply"
        );
    }
}