bamboo-server 2026.7.24

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
//! Permission rule settings backed by the independent permission section.

use std::path::PathBuf;
use std::sync::Arc;

use actix_web::{web, HttpResponse};
use bamboo_config::{ConfigStoreError, SectionSnapshot, SectionSourceKind, SectionStatus};
use bamboo_tools::permission::{
    DurablePermissionRule, PermissionDecisionKind, PermissionEvaluation, PermissionOutcome,
    PermissionType, SerializablePermissionConfig,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

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

#[derive(Debug, Serialize)]
pub struct AskRulesResponse {
    pub rules: Vec<String>,
    pub revision: u64,
    pub loaded_at: DateTime<Utc>,
    pub source_path: PathBuf,
    pub source_kind: SectionSourceKind,
    pub status: SectionStatus,
    pub last_error: Option<String>,
}

impl AskRulesResponse {
    fn from_snapshot(snapshot: &SectionSnapshot<SerializablePermissionConfig>) -> Self {
        Self {
            rules: snapshot.data.ask_rules.clone(),
            revision: snapshot.revision,
            loaded_at: snapshot.loaded_at,
            source_path: snapshot.source_path.clone(),
            source_kind: snapshot.source_kind,
            status: snapshot.status,
            last_error: snapshot.last_error.clone(),
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct UpdateAskRulesRequest {
    /// Clients should send the revision returned by GET. Optional only for
    /// compatibility with pre-revision clients; those use the current process
    /// snapshot and still perform a store-level CAS.
    #[serde(default)]
    pub expected_revision: Option<u64>,
    #[serde(default)]
    pub rules: Vec<String>,
}

pub async fn get_permission_ask_rules(
    app_state: web::Data<AppState>,
) -> Result<HttpResponse, AppError> {
    let snapshot = app_state.permission_section.snapshot();
    Ok(HttpResponse::Ok().json(AskRulesResponse::from_snapshot(&snapshot)))
}

/// Replaces always-ask rules with durable-before-live, cancellation-safe ordering.
pub async fn update_permission_ask_rules(
    app_state: web::Data<AppState>,
    payload: web::Json<UpdateAskRulesRequest>,
) -> Result<HttpResponse, AppError> {
    let req = payload.into_inner();
    let mut rules: Vec<String> = req
        .rules
        .into_iter()
        .map(|rule| rule.trim().to_string())
        .filter(|rule| !rule.is_empty())
        .collect();
    let mut seen = std::collections::HashSet::new();
    rules.retain(|rule| seen.insert(rule.clone()));

    let Some(config) = app_state.permission_checker.permission_config() else {
        return Err(AppError::InternalError(anyhow::anyhow!(
            "permission checker does not support configurable rules"
        )));
    };

    let section = Arc::clone(&app_state.permission_section);
    let io_lock = Arc::clone(&app_state.permission_io_lock);
    let expected_revision = req
        .expected_revision
        .unwrap_or_else(|| app_state.permission_section.snapshot().revision);
    // This task is deliberately detached from request cancellation. Once a
    // mutation starts, it completes the durable commit and live publication as
    // one serialized operation even if the client disconnects.
    let mutation = tokio::spawn(async move {
        let _guard = io_lock.lock().await;
        let mut candidate = section.snapshot().data.as_ref().clone();
        candidate.ask_rules = rules;
        let writer = Arc::clone(&section);
        tokio::task::spawn_blocking(move || writer.commit(expected_revision, candidate))
            .await
            .map_err(|error| {
                AppError::InternalError(anyhow::anyhow!("permission commit task failed: {error}"))
            })?
            .map_err(map_store_error)?;

        let snapshot = section.snapshot();
        config.publish_persistent_policy(snapshot.revision, snapshot.data.as_ref());
        Ok::<_, AppError>(snapshot)
    });

    let snapshot = mutation.await.map_err(|error| {
        AppError::InternalError(anyhow::anyhow!("permission mutation task failed: {error}"))
    })??;
    Ok(HttpResponse::Ok().json(AskRulesResponse::from_snapshot(&snapshot)))
}

fn map_store_error(error: ConfigStoreError) -> AppError {
    match error {
        ConfigStoreError::Conflict { expected, actual } => {
            AppError::ConfigConflict { expected, actual }
        }
        other => AppError::InternalError(anyhow::anyhow!(
            "failed to persist permission rules: {other}"
        )),
    }
}

#[derive(Debug, Serialize)]
pub struct PermissionPolicyResponse {
    pub revision: u64,
    pub loaded_at: DateTime<Utc>,
    pub source_path: PathBuf,
    pub source_kind: SectionSourceKind,
    pub status: SectionStatus,
    pub last_error: Option<String>,
    pub policy: SerializablePermissionConfig,
}

impl PermissionPolicyResponse {
    fn from_snapshot(snapshot: &SectionSnapshot<SerializablePermissionConfig>) -> Self {
        Self {
            revision: snapshot.revision,
            loaded_at: snapshot.loaded_at,
            source_path: snapshot.source_path.clone(),
            source_kind: snapshot.source_kind,
            status: snapshot.status,
            last_error: snapshot.last_error.clone(),
            policy: snapshot.data.as_ref().clone(),
        }
    }
}

pub async fn get_permission_policy(
    app_state: web::Data<AppState>,
) -> Result<HttpResponse, AppError> {
    let snapshot = app_state.permission_section.snapshot();
    Ok(HttpResponse::Ok().json(PermissionPolicyResponse::from_snapshot(&snapshot)))
}

#[derive(Debug, Deserialize)]
pub struct PutPermissionRuleRequest {
    pub expected_revision: u64,
    pub rule: DurablePermissionRule,
}

#[derive(Debug, Deserialize)]
pub struct DeletePermissionRuleRequest {
    pub expected_revision: u64,
}

async fn commit_permission_candidate(
    app_state: &web::Data<AppState>,
    expected_revision: u64,
    candidate: SerializablePermissionConfig,
) -> Result<Arc<SectionSnapshot<SerializablePermissionConfig>>, AppError> {
    let Some(config) = app_state.permission_checker.permission_config() else {
        return Err(AppError::InternalError(anyhow::anyhow!(
            "permission checker does not support configurable rules"
        )));
    };
    let section = Arc::clone(&app_state.permission_section);
    let io_lock = Arc::clone(&app_state.permission_io_lock);
    tokio::spawn(async move {
        let _guard = io_lock.lock().await;
        let writer = Arc::clone(&section);
        tokio::task::spawn_blocking(move || writer.commit(expected_revision, candidate))
            .await
            .map_err(|error| {
                AppError::InternalError(anyhow::anyhow!("permission commit task failed: {error}"))
            })?
            .map_err(map_store_error)?;
        let snapshot = section.snapshot();
        config.publish_persistent_policy(snapshot.revision, snapshot.data.as_ref());
        Ok::<_, AppError>(snapshot)
    })
    .await
    .map_err(|error| {
        AppError::InternalError(anyhow::anyhow!("permission mutation task failed: {error}"))
    })?
}

pub async fn create_permission_rule(
    app_state: web::Data<AppState>,
    payload: web::Json<PutPermissionRuleRequest>,
) -> Result<HttpResponse, AppError> {
    let request = payload.into_inner();
    request.rule.validate().map_err(AppError::BadRequest)?;
    let snapshot = app_state.permission_section.snapshot();
    if snapshot
        .data
        .durable_rules
        .iter()
        .any(|rule| rule.id == request.rule.id)
    {
        return Err(AppError::BadRequest(format!(
            "permission rule '{}' already exists",
            request.rule.id
        )));
    }
    let mut candidate = snapshot.data.as_ref().clone();
    candidate.durable_rules.push(request.rule);
    let snapshot =
        commit_permission_candidate(&app_state, request.expected_revision, candidate).await?;
    Ok(HttpResponse::Created().json(PermissionPolicyResponse::from_snapshot(&snapshot)))
}

pub async fn update_permission_rule(
    app_state: web::Data<AppState>,
    rule_id: web::Path<String>,
    payload: web::Json<PutPermissionRuleRequest>,
) -> Result<HttpResponse, AppError> {
    let rule_id = rule_id.into_inner();
    let request = payload.into_inner();
    if request.rule.id != rule_id {
        return Err(AppError::BadRequest(
            "rule id in path and body must match".to_string(),
        ));
    }
    request.rule.validate().map_err(AppError::BadRequest)?;
    let snapshot = app_state.permission_section.snapshot();
    let mut candidate = snapshot.data.as_ref().clone();
    let Some(existing) = candidate
        .durable_rules
        .iter_mut()
        .find(|rule| rule.id == rule_id)
    else {
        return Err(AppError::NotFound(format!("permission rule '{rule_id}'")));
    };
    *existing = request.rule;
    let snapshot =
        commit_permission_candidate(&app_state, request.expected_revision, candidate).await?;
    Ok(HttpResponse::Ok().json(PermissionPolicyResponse::from_snapshot(&snapshot)))
}

pub async fn delete_permission_rule(
    app_state: web::Data<AppState>,
    rule_id: web::Path<String>,
    query: web::Query<DeletePermissionRuleRequest>,
) -> Result<HttpResponse, AppError> {
    let rule_id = rule_id.into_inner();
    let snapshot = app_state.permission_section.snapshot();
    let mut candidate = snapshot.data.as_ref().clone();
    let before = candidate.durable_rules.len();
    candidate.durable_rules.retain(|rule| rule.id != rule_id);
    if candidate.durable_rules.len() == before {
        return Err(AppError::NotFound(format!("permission rule '{rule_id}'")));
    }
    let snapshot =
        commit_permission_candidate(&app_state, query.expected_revision, candidate).await?;
    Ok(HttpResponse::Ok().json(PermissionPolicyResponse::from_snapshot(&snapshot)))
}

#[derive(Debug, Deserialize)]
pub struct DiagnosePermissionRequest {
    #[serde(default)]
    pub request_id: String,
    #[serde(default)]
    pub session_id: String,
    #[serde(default)]
    pub workspace_path: Option<String>,
    pub tool_name: String,
    #[serde(default)]
    pub tool_args: serde_json::Value,
    pub permission_type: PermissionType,
    pub resource: String,
    #[serde(default)]
    pub operation_summary: String,
    #[serde(default)]
    pub bypass_requested: bool,
    #[serde(default)]
    pub platform_hard_deny: Option<String>,
}

pub async fn diagnose_permission(
    app_state: web::Data<AppState>,
    payload: web::Json<DiagnosePermissionRequest>,
) -> Result<HttpResponse, AppError> {
    let request = payload.into_inner();
    let Some(config) = app_state.permission_checker.permission_config() else {
        return Err(AppError::InternalError(anyhow::anyhow!(
            "permission checker does not expose typed policy"
        )));
    };
    let outcome: PermissionOutcome = config.evaluate(PermissionEvaluation {
        request_id: request.request_id,
        session_id: request.session_id,
        workspace_path: request.workspace_path,
        tool_name: request.tool_name,
        tool_args: request.tool_args,
        permission_type: request.permission_type,
        resource: request.resource,
        operation_summary: request.operation_summary,
        risk_level: request.permission_type.risk_level(),
        bypass_requested: request.bypass_requested,
        platform_hard_deny: request.platform_hard_deny,
        consume_once: false,
        supported_decisions: PermissionDecisionKind::all_supported(),
    });
    Ok(HttpResponse::Ok().json(outcome))
}

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

    fn global_rule(
        effect: bamboo_tools::permission::PermissionRuleEffect,
    ) -> DurablePermissionRule {
        DurablePermissionRule {
            id: "rule-1".to_string(),
            permission_type: PermissionType::ExecuteCommand,
            effect,
            scope: bamboo_tools::permission::PermissionRuleScope::Global,
            workspace_path: None,
            matcher: bamboo_tools::permission::PermissionMatcher {
                id: "git-status".to_string(),
                kind: bamboo_tools::permission::PermissionMatcherKind::CommandPrefix,
                value: "git status".to_string(),
            },
            source: bamboo_tools::permission::PermissionRuleSource::User,
            expires_at: None,
        }
    }

    #[tokio::test]
    async fn conflict_leaves_live_policy_and_disk_unchanged_then_valid_cas_publishes() {
        let temp = tempfile::tempdir().unwrap();
        let state = web::Data::new(
            AppState::new(temp.path().to_path_buf())
                .await
                .expect("app state should initialize"),
        );

        let conflict = update_permission_ask_rules(
            state.clone(),
            web::Json(UpdateAskRulesRequest {
                expected_revision: Some(99),
                rules: vec!["Bash(git push *)".to_string()],
            }),
        )
        .await
        .unwrap_err();

        assert!(matches!(
            conflict,
            AppError::ConfigConflict {
                expected: 99,
                actual: 0
            }
        ));
        assert!(state
            .permission_checker
            .permission_config()
            .unwrap()
            .ask_rule_patterns()
            .is_empty());
        assert!(!temp.path().join("permissions.json").exists());

        let response = update_permission_ask_rules(
            state.clone(),
            web::Json(UpdateAskRulesRequest {
                expected_revision: Some(0),
                rules: vec![" Bash(git push *) ".to_string()],
            }),
        )
        .await
        .unwrap();

        assert_eq!(response.status(), actix_web::http::StatusCode::OK);
        assert_eq!(
            state
                .permission_checker
                .permission_config()
                .unwrap()
                .ask_rule_patterns(),
            vec!["Bash(git push *)"]
        );
        let reopened = bamboo_tools::permission::PermissionSection::open(temp.path()).unwrap();
        assert_eq!(reopened.snapshot().revision, 1);
        assert_eq!(reopened.snapshot().data.ask_rules, vec!["Bash(git push *)"]);
    }

    #[tokio::test]
    async fn durable_rule_crud_is_cas_guarded_and_published_after_commit() {
        let temp = tempfile::tempdir().unwrap();
        let state = web::Data::new(
            AppState::new(temp.path().to_path_buf())
                .await
                .expect("app state should initialize"),
        );

        let created = create_permission_rule(
            state.clone(),
            web::Json(PutPermissionRuleRequest {
                expected_revision: 0,
                rule: global_rule(bamboo_tools::permission::PermissionRuleEffect::Allow),
            }),
        )
        .await
        .unwrap();
        assert_eq!(created.status(), actix_web::http::StatusCode::CREATED);
        assert_eq!(
            state
                .permission_checker
                .permission_config()
                .unwrap()
                .durable_rules()[0]
                .effect,
            bamboo_tools::permission::PermissionRuleEffect::Allow
        );

        update_permission_rule(
            state.clone(),
            web::Path::from("rule-1".to_string()),
            web::Json(PutPermissionRuleRequest {
                expected_revision: 1,
                rule: global_rule(bamboo_tools::permission::PermissionRuleEffect::Deny),
            }),
        )
        .await
        .unwrap();

        let stale = delete_permission_rule(
            state.clone(),
            web::Path::from("rule-1".to_string()),
            web::Query(DeletePermissionRuleRequest {
                expected_revision: 1,
            }),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            stale,
            AppError::ConfigConflict {
                expected: 1,
                actual: 2
            }
        ));
        assert_eq!(
            state
                .permission_checker
                .permission_config()
                .unwrap()
                .durable_rules()[0]
                .effect,
            bamboo_tools::permission::PermissionRuleEffect::Deny
        );

        delete_permission_rule(
            state.clone(),
            web::Path::from("rule-1".to_string()),
            web::Query(DeletePermissionRuleRequest {
                expected_revision: 2,
            }),
        )
        .await
        .unwrap();
        assert!(state
            .permission_checker
            .permission_config()
            .unwrap()
            .durable_rules()
            .is_empty());
        let reopened = bamboo_tools::permission::PermissionSection::open(temp.path()).unwrap();
        assert_eq!(reopened.snapshot().revision, 3);
        assert!(reopened.snapshot().data.durable_rules.is_empty());
    }
}