chio-http-core 0.1.0

Protocol-agnostic HTTP security types for the Chio kernel
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
//! Phase 3.4-3.6 HITL approval HTTP surface.
//!
//! Substrate-agnostic handlers for the four approval endpoints:
//!
//! | Method | Path                            | Handler |
//! |--------|---------------------------------|---------|
//! | GET    | `/approvals/pending`            | [`handle_list_pending`] |
//! | GET    | `/approvals/{id}`               | [`handle_get_approval`] |
//! | POST   | `/approvals/{id}/respond`       | [`handle_respond`] |
//! | POST   | `/approvals/batch/respond`      | [`handle_batch_respond`] |
//!
//! Each handler accepts parsed inputs and returns a typed response so
//! `chio-tower`, `chio-api-protect`, and hosted sidecars can serve them
//! without agreeing on a framework. Errors carry HTTP status codes via
//! [`ApprovalHandlerError::status`] for predictable mapping.

use std::sync::Arc;

use chio_core_types::capability::GovernedApprovalToken;
use chio_core_types::crypto::PublicKey;
use chio_kernel::{
    resume_with_decision, ApprovalDecision, ApprovalFilter, ApprovalOutcome, ApprovalRequest,
    ApprovalStore, ApprovalStoreError, ApprovalToken, KernelError, ResolvedApproval,
};
use serde::{Deserialize, Serialize};

/// Errors returned by the approval handlers. Each variant maps onto a
/// stable HTTP status so substrate adapters can relay the code without
/// re-interpreting the semantics.
#[derive(Debug, Clone)]
pub enum ApprovalHandlerError {
    /// Request body could not be parsed into the expected JSON shape.
    BadRequest(String),
    /// Target approval id does not exist in the store.
    NotFound(String),
    /// Approval was already resolved (single-response rule).
    Conflict(String),
    /// Replay detected: the signed token has already been consumed.
    ReplayDetected(String),
    /// Approval token failed binding / signature / time checks.
    Rejected(String),
    /// Backend store surfaced an internal error.
    Internal(String),
}

impl ApprovalHandlerError {
    #[must_use]
    pub fn status(&self) -> u16 {
        match self {
            Self::BadRequest(_) => 400,
            Self::NotFound(_) => 404,
            Self::Conflict(_) => 409,
            Self::ReplayDetected(_) => 409,
            Self::Rejected(_) => 403,
            Self::Internal(_) => 500,
        }
    }

    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Self::BadRequest(_) => "bad_request",
            Self::NotFound(_) => "not_found",
            Self::Conflict(_) => "conflict",
            Self::ReplayDetected(_) => "replay_detected",
            Self::Rejected(_) => "approval_rejected",
            Self::Internal(_) => "internal_error",
        }
    }

    #[must_use]
    pub fn message(&self) -> String {
        match self {
            Self::BadRequest(m)
            | Self::NotFound(m)
            | Self::Conflict(m)
            | Self::ReplayDetected(m)
            | Self::Rejected(m)
            | Self::Internal(m) => m.clone(),
        }
    }

    #[must_use]
    pub fn body(&self) -> serde_json::Value {
        serde_json::json!({
            "error": self.code(),
            "message": self.message(),
        })
    }
}

impl std::fmt::Display for ApprovalHandlerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code(), self.message())
    }
}

impl std::error::Error for ApprovalHandlerError {}

impl From<ApprovalStoreError> for ApprovalHandlerError {
    fn from(e: ApprovalStoreError) -> Self {
        match e {
            ApprovalStoreError::NotFound(m) => Self::NotFound(m),
            ApprovalStoreError::AlreadyResolved(m) => {
                Self::Conflict(format!("already resolved: {m}"))
            }
            ApprovalStoreError::Replay(m) => Self::ReplayDetected(m),
            ApprovalStoreError::Backend(m) => Self::Internal(m),
            ApprovalStoreError::Serialization(m) => Self::Internal(m),
        }
    }
}

impl From<KernelError> for ApprovalHandlerError {
    fn from(e: KernelError) -> Self {
        match e {
            KernelError::ApprovalRejected(m) => {
                if m.contains("replay") {
                    Self::ReplayDetected(m)
                } else {
                    Self::Rejected(m)
                }
            }
            other => Self::Internal(other.to_string()),
        }
    }
}

/// Admin handle bound to the kernel's approval store.
#[derive(Clone)]
pub struct ApprovalAdmin {
    store: Arc<dyn ApprovalStore>,
}

impl std::fmt::Debug for ApprovalAdmin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ApprovalAdmin").finish_non_exhaustive()
    }
}

impl ApprovalAdmin {
    #[must_use]
    pub fn new(store: Arc<dyn ApprovalStore>) -> Self {
        Self { store }
    }

    #[must_use]
    pub fn store(&self) -> &Arc<dyn ApprovalStore> {
        &self.store
    }
}

// ----- Wire shapes --------------------------------------------------

/// Query parameters for `GET /approvals/pending`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PendingQuery {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_server: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_expired_at: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

impl From<PendingQuery> for ApprovalFilter {
    fn from(q: PendingQuery) -> Self {
        Self {
            subject_id: q.subject_id,
            tool_server: q.tool_server,
            tool_name: q.tool_name,
            not_expired_at: q.not_expired_at,
            limit: q.limit,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingListResponse {
    pub approvals: Vec<ApprovalRequest>,
    pub count: usize,
}

/// Body for `POST /approvals/{id}/respond`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RespondRequest {
    pub outcome: ApprovalOutcome,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub approver: PublicKey,
    pub token: GovernedApprovalToken,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RespondResponse {
    pub approval_id: String,
    pub outcome: ApprovalOutcome,
    pub resolved_at: u64,
}

/// Body for `POST /approvals/batch/respond`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRespondRequest {
    pub decisions: Vec<BatchDecisionEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchDecisionEntry {
    pub approval_id: String,
    pub outcome: ApprovalOutcome,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub approver: PublicKey,
    pub token: GovernedApprovalToken,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRespondResponse {
    pub results: Vec<BatchRespondResult>,
    pub summary: BatchRespondSummary,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRespondResult {
    pub approval_id: String,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<ApprovalOutcome>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRespondSummary {
    pub total: usize,
    pub approved: usize,
    pub denied: usize,
    pub rejected: usize,
}

// ----- Handlers -----------------------------------------------------

/// `GET /approvals/pending` -- list pending approvals matching the
/// filter. Returns a stable JSON shape.
pub fn handle_list_pending(
    admin: &ApprovalAdmin,
    query: PendingQuery,
) -> Result<PendingListResponse, ApprovalHandlerError> {
    let filter: ApprovalFilter = query.into();
    let approvals = admin.store.list_pending(&filter)?;
    let count = approvals.len();
    Ok(PendingListResponse { approvals, count })
}

/// `GET /approvals/{id}`.
///
/// Returns the pending record if still outstanding; otherwise returns
/// the resolved record. Adapters may encode "resolved" via the
/// `resolution` field so callers can tell the two states apart without
/// extra round trips.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetApprovalResponse {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending: Option<ApprovalRequest>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution: Option<ResolvedApproval>,
}

pub fn handle_get_approval(
    admin: &ApprovalAdmin,
    approval_id: &str,
) -> Result<GetApprovalResponse, ApprovalHandlerError> {
    let pending = admin.store.get_pending(approval_id)?;
    let resolution = admin.store.get_resolution(approval_id)?;
    if pending.is_none() && resolution.is_none() {
        return Err(ApprovalHandlerError::NotFound(approval_id.to_string()));
    }
    Ok(GetApprovalResponse {
        pending,
        resolution,
    })
}

/// `POST /approvals/{id}/respond` -- submit an approval decision.
pub fn handle_respond(
    admin: &ApprovalAdmin,
    approval_id: &str,
    body: RespondRequest,
    now: u64,
) -> Result<RespondResponse, ApprovalHandlerError> {
    // The approval_id in the URL must agree with the token the human
    // signed, otherwise the signed binding is wrong and we cannot
    // authorize resume.
    if body.token.request_id != approval_id {
        return Err(ApprovalHandlerError::BadRequest(format!(
            "approval_id {approval_id} does not match signed token request_id {}",
            body.token.request_id
        )));
    }

    let decision = ApprovalDecision {
        approval_id: approval_id.to_string(),
        outcome: body.outcome.clone(),
        reason: body.reason,
        approver: body.approver.clone(),
        token: body.token,
        received_at: now,
    };

    let outcome = resume_with_decision(admin.store.as_ref(), &decision, now)?;

    // Defense-in-depth: the ApprovalToken is now consumed; exercise
    // the replay guard immediately so operators can trust the store
    // wrote the record.
    let approval_token = ApprovalToken::from_decision(&decision);
    let _ = approval_token; // consumed; flagged via resume_with_decision.

    Ok(RespondResponse {
        approval_id: approval_id.to_string(),
        outcome,
        resolved_at: now,
    })
}

/// `POST /approvals/batch/respond` -- apply decisions to multiple
/// approvals in one call.
pub fn handle_batch_respond(
    admin: &ApprovalAdmin,
    body: BatchRespondRequest,
    now: u64,
) -> Result<BatchRespondResponse, ApprovalHandlerError> {
    if body.decisions.is_empty() {
        return Err(ApprovalHandlerError::BadRequest(
            "batch respond requires at least one decision".into(),
        ));
    }

    let mut results = Vec::with_capacity(body.decisions.len());
    let mut approved = 0usize;
    let mut denied = 0usize;
    let mut rejected = 0usize;

    for entry in body.decisions {
        let approval_id = entry.approval_id.clone();
        if entry.token.request_id != approval_id {
            rejected += 1;
            results.push(BatchRespondResult {
                approval_id,
                status: "rejected".into(),
                outcome: None,
                error: Some(format!(
                    "token request_id {} mismatches approval_id",
                    entry.token.request_id
                )),
            });
            continue;
        }

        let decision = ApprovalDecision {
            approval_id: approval_id.clone(),
            outcome: entry.outcome.clone(),
            reason: entry.reason,
            approver: entry.approver,
            token: entry.token,
            received_at: now,
        };

        match resume_with_decision(admin.store.as_ref(), &decision, now) {
            Ok(outcome) => {
                match outcome {
                    ApprovalOutcome::Approved => approved += 1,
                    ApprovalOutcome::Denied => denied += 1,
                }
                results.push(BatchRespondResult {
                    approval_id,
                    status: "resolved".into(),
                    outcome: Some(outcome),
                    error: None,
                });
            }
            Err(e) => {
                rejected += 1;
                let handler_err: ApprovalHandlerError = e.into();
                results.push(BatchRespondResult {
                    approval_id,
                    status: "rejected".into(),
                    outcome: None,
                    error: Some(handler_err.message()),
                });
            }
        }
    }

    let total = results.len();
    Ok(BatchRespondResponse {
        results,
        summary: BatchRespondSummary {
            total,
            approved,
            denied,
            rejected,
        },
    })
}