Skip to main content

adk_session/
encrypted_approval.rs

1//! [`EncryptedApprovalStore`]: an [`ApprovalStore`](adk_core::ApprovalStore) whose payloads reach the inner store
2//! sealed in the [`envelope`](crate::envelope) (spec 3.1 §7.12, §9.2 I57, §10 S5).
3//!
4//! | Data | Stored as |
5//! |------|-----------|
6//! | A held call's arguments and fingerprint (`ToolConfirmationRequest::args`) | One envelope in `args`, bound to (app, user, session, row key) |
7//! | A decision's edited arguments, message and fingerprint | One envelope in `message`, bound to (app, user, session, row key) |
8//! | An [`ApprovalRequest`](adk_core::ApprovalRequest)'s `fingerprint`, `args_redacted`, `summary`, `note` and each decision's `edited_args` and `reason` | Envelopes bound to (app, user, session, request id) |
9//! | Row keys, request ids, tool names, agents, subjects, states, timestamps, delegations | Plaintext, so the inner store can key, order and filter |
10//!
11//! A call's fingerprint spells out its canonical arguments, so it cannot be the row key.
12//! Rows are keyed by `adk-fp:v1:` and the HMAC-SHA256, under the store key, of the scope and
13//! the fingerprint; the real fingerprint travels inside the sealed payload and comes back
14//! from [`pending`](adk_core::ApprovalStore::pending). The inner store derives a pending row's key
15//! from the request it is given, so the wrapper records through
16//! [`ApprovalStore::record_pending_keyed`](adk_core::ApprovalStore::record_pending_keyed), which the stores in `adk-core` and this crate's
17//! SQL stores implement.
18//!
19//! Reads try the current key, then each previous key; a value no key opens, or one stored
20//! in plaintext, is an error, never a fallback (I57).
21//!
22//! # Example
23//!
24//! ```rust
25//! use adk_core::InMemoryApprovalStore;
26//! use adk_session::{EncryptedApprovalStore, EncryptionKey};
27//!
28//! let store = EncryptedApprovalStore::new(InMemoryApprovalStore::new(), EncryptionKey::generate(), vec![]);
29//! # let _ = store;
30//! ```
31
32use adk_core::principal::SubjectRef;
33use adk_core::{
34    AdkError, ApprovalDelegation, ApprovalRequest, ApprovalRequestQuery, ApprovalScope,
35    ApprovalStore, ErrorCategory, ErrorComponent, PendingApproval, Result, ToolApproval,
36    ToolConfirmationDecision, ToolConfirmationRequest,
37};
38use async_trait::async_trait;
39use hmac::{Hmac, Mac};
40use serde::{Deserialize, Serialize};
41use serde_json::Value;
42use sha2::Sha256;
43
44use crate::encryption_key::EncryptionKey;
45use crate::envelope::{self, ENVELOPE_PREFIX};
46
47/// Domain separator of every envelope this store writes.
48const AAD_DOMAIN: &[u8] = b"adk-session/encrypted-approval-store/v1";
49/// Domain separator of the row-key MAC.
50const ROW_KEY_DOMAIN: &[u8] = b"adk-session/encrypted-approval-store/row-key/v1";
51/// Prefix of every row key this store writes.
52pub const ROW_KEY_PREFIX: &str = "adk-fp:v1:";
53
54/// The sealed payload of a pending row: the call's fingerprint and arguments.
55#[derive(Serialize, Deserialize)]
56struct SealedCall {
57    fingerprint: String,
58    args: Value,
59}
60
61/// The sealed payload of a decision row: the call's fingerprint and what the approver
62/// attached.
63#[derive(Serialize, Deserialize)]
64struct SealedDecision {
65    fingerprint: String,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    edited_args: Option<Value>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    message: Option<String>,
70}
71
72/// An [`ApprovalStore`] that seals arguments and decisions before they reach `S`.
73///
74/// See the [module documentation](self) for what is sealed and what stays plaintext.
75///
76/// # Example
77///
78/// ```rust
79/// use adk_core::InMemoryApprovalStore;
80/// use adk_session::{EncryptedApprovalStore, EncryptionKey};
81///
82/// let current = EncryptionKey::generate();
83/// let retired = EncryptionKey::generate();
84/// let store = EncryptedApprovalStore::new(InMemoryApprovalStore::new(), current, vec![retired]);
85/// # let _ = store;
86/// ```
87pub struct EncryptedApprovalStore<S: ApprovalStore> {
88    inner: S,
89    current_key: EncryptionKey,
90    previous_keys: Vec<EncryptionKey>,
91    legacy_migration: bool,
92}
93
94impl<S: ApprovalStore> std::fmt::Debug for EncryptedApprovalStore<S> {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("EncryptedApprovalStore")
97            .field("inner", &self.inner)
98            .field("key_id", &self.current_key.id())
99            .field("previous_keys", &self.previous_keys.len())
100            .finish()
101    }
102}
103
104fn error(code: &'static str, message: impl Into<String>) -> AdkError {
105    AdkError::new(ErrorComponent::Session, ErrorCategory::Internal, code, message)
106}
107
108fn decrypt_error(what: &str) -> AdkError {
109    error(
110        "session.encryption.decrypt_failed",
111        format!(
112            "failed to decrypt the approval store's {what}: no configured key authenticates it; \
113             it was written with an unknown key or moved from another session or request"
114        ),
115    )
116}
117
118fn unencrypted_error(what: &str) -> AdkError {
119    error(
120        "session.encryption.unencrypted_data",
121        format!(
122            "the approval store's {what} is not encrypted; rows written before the store key \
123             was configured must be sealed first (`adk-rust store rotate-key`)"
124        ),
125    )
126}
127
128fn serialization_error(error_: serde_json::Error) -> AdkError {
129    error(
130        "session.encryption.serialization_failed",
131        format!("failed to (de)serialize sealed approval data: {error_}"),
132    )
133}
134
135/// The key a pending or decision row is stored under: a MAC of the scope and the
136/// fingerprint, so equal calls in different sessions never share a row key and no row key
137/// reveals the arguments.
138fn row_key(key: &EncryptionKey, scope: &ApprovalScope, fingerprint: &str) -> String {
139    let mut mac =
140        Hmac::<Sha256>::new_from_slice(key.as_bytes()).expect("HMAC-SHA256 accepts a 32-byte key");
141    mac.update(&envelope::associated_data(
142        ROW_KEY_DOMAIN,
143        &[&scope.app_name, &scope.user_id, &scope.session_id, fingerprint],
144    ));
145    let digest = mac.finalize().into_bytes();
146    let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
147    format!("{ROW_KEY_PREFIX}{hex}")
148}
149
150fn pending_aad(scope: &ApprovalScope, row_key: &str) -> Vec<u8> {
151    envelope::associated_data(
152        AAD_DOMAIN,
153        &["pending", &scope.app_name, &scope.user_id, &scope.session_id, row_key],
154    )
155}
156
157fn decision_aad(scope: &ApprovalScope, row_key: &str) -> Vec<u8> {
158    envelope::associated_data(
159        AAD_DOMAIN,
160        &["decision", &scope.app_name, &scope.user_id, &scope.session_id, row_key],
161    )
162}
163
164fn request_aad(scope: &ApprovalScope, id: &str) -> Vec<u8> {
165    envelope::associated_data(
166        AAD_DOMAIN,
167        &["request", &scope.app_name, &scope.user_id, &scope.session_id, id],
168    )
169}
170
171impl<S: ApprovalStore> EncryptedApprovalStore<S> {
172    /// Wraps `inner`: writes seal with `current_key`; reads open with it, then with each
173    /// of `previous_keys`.
174    pub fn new(inner: S, current_key: EncryptionKey, previous_keys: Vec<EncryptionKey>) -> Self {
175        Self { inner, current_key, previous_keys, legacy_migration: false }
176    }
177
178    /// Lets `rewrap_sqlite` seal rows written in plaintext before a key was configured,
179    /// so a store can be encrypted in place. Reads stay strict: a plaintext row is an error.
180    #[must_use]
181    pub fn with_legacy_migration(mut self, enabled: bool) -> Self {
182        self.legacy_migration = enabled;
183        self
184    }
185
186    /// The wrapped store. Reads through it return envelopes; writes bypass sealing.
187    pub fn inner(&self) -> &S {
188        &self.inner
189    }
190
191    /// Consumes the wrapper and returns the wrapped store.
192    pub fn into_inner(self) -> S {
193        self.inner
194    }
195
196    fn keys(&self) -> impl Iterator<Item = &EncryptionKey> {
197        std::iter::once(&self.current_key).chain(&self.previous_keys)
198    }
199
200    /// The row keys `fingerprint` may be stored under: the current key's first, then each
201    /// previous key's (rows not yet re-sealed after a rotation).
202    fn row_keys(&self, scope: &ApprovalScope, fingerprint: &str) -> Vec<String> {
203        self.keys().map(|key| row_key(key, scope, fingerprint)).collect()
204    }
205
206    fn seal_text(&self, text: &str, aad: &[u8]) -> Result<String> {
207        envelope::seal(&self.current_key, text.as_bytes(), aad)
208    }
209
210    fn open_text(&self, text: &str, what: &str, aad: &[u8]) -> Result<String> {
211        if !text.starts_with(ENVELOPE_PREFIX) {
212            return Err(unencrypted_error(what));
213        }
214        let (plaintext, _) =
215            envelope::open(self.keys(), text, aad).ok_or_else(|| decrypt_error(what))?;
216        String::from_utf8(plaintext).map_err(|e| {
217            error("session.encryption.serialization_failed", format!("{what} is not UTF-8: {e}"))
218        })
219    }
220
221    fn seal_json<T: Serialize>(&self, value: &T, aad: &[u8]) -> Result<Value> {
222        let text = serde_json::to_string(value).map_err(serialization_error)?;
223        Ok(Value::String(self.seal_text(&text, aad)?))
224    }
225
226    fn open_json<T: for<'de> Deserialize<'de>>(
227        &self,
228        value: &Value,
229        what: &str,
230        aad: &[u8],
231    ) -> Result<T> {
232        let Some(text) = value.as_str() else {
233            return Err(unencrypted_error(what));
234        };
235        serde_json::from_str(&self.open_text(text, what, aad)?).map_err(serialization_error)
236    }
237
238    /// `request` with its fingerprint and arguments sealed under `row_key`.
239    fn seal_call(
240        &self,
241        request: &ToolConfirmationRequest,
242        fingerprint: &str,
243        scope: &ApprovalScope,
244        row_key: &str,
245    ) -> Result<ToolConfirmationRequest> {
246        let payload =
247            SealedCall { fingerprint: fingerprint.to_string(), args: request.args.clone() };
248        let mut sealed = request.clone();
249        sealed.args = self.seal_json(&payload, &pending_aad(scope, row_key))?;
250        Ok(sealed)
251    }
252
253    /// The call and its fingerprint from a pending row stored under `row_key`.
254    fn open_call(
255        &self,
256        request: &ToolConfirmationRequest,
257        scope: &ApprovalScope,
258        row_key: &str,
259    ) -> Result<(ToolConfirmationRequest, String)> {
260        let payload: SealedCall =
261            self.open_json(&request.args, "held call arguments", &pending_aad(scope, row_key))?;
262        let mut opened = request.clone();
263        opened.args = payload.args;
264        Ok((opened, payload.fingerprint))
265    }
266
267    fn seal_approval(
268        &self,
269        approval: ToolApproval,
270        fingerprint: &str,
271        scope: &ApprovalScope,
272        row_key: &str,
273    ) -> Result<ToolApproval> {
274        let payload = SealedDecision {
275            fingerprint: fingerprint.to_string(),
276            edited_args: approval.edited_args,
277            message: approval.message,
278        };
279        let sealed = self.seal_json(&payload, &decision_aad(scope, row_key))?;
280        Ok(ToolApproval {
281            decision: approval.decision,
282            expires_at: approval.expires_at,
283            edited_args: None,
284            message: sealed.as_str().map(str::to_string),
285        })
286    }
287
288    fn open_approval(
289        &self,
290        approval: ToolApproval,
291        scope: &ApprovalScope,
292        row_key: &str,
293    ) -> Result<(ToolApproval, String)> {
294        let Some(blob) = &approval.message else {
295            return Err(unencrypted_error("decision"));
296        };
297        let payload: SealedDecision = serde_json::from_str(&self.open_text(
298            blob,
299            "decision",
300            &decision_aad(scope, row_key),
301        )?)
302        .map_err(serialization_error)?;
303        Ok((
304            ToolApproval {
305                decision: approval.decision,
306                expires_at: approval.expires_at,
307                edited_args: payload.edited_args,
308                message: payload.message,
309            },
310            payload.fingerprint,
311        ))
312    }
313
314    fn seal_approval_request(&self, request: &ApprovalRequest) -> Result<ApprovalRequest> {
315        let aad = request_aad(&request.scope, &request.id);
316        let mut sealed = request.clone();
317        sealed.fingerprint = self.seal_text(&request.fingerprint, &aad)?;
318        sealed.args_redacted = self.seal_json(&request.args_redacted, &aad)?;
319        sealed.summary = self.seal_text(&request.summary, &aad)?;
320        if let Some(note) = &request.note {
321            sealed.note = Some(self.seal_text(note, &aad)?);
322        }
323        for decision in &mut sealed.decisions {
324            if let Some(args) = &decision.edited_args {
325                decision.edited_args = Some(self.seal_json(args, &aad)?);
326            }
327            if let Some(reason) = &decision.reason {
328                decision.reason = Some(self.seal_text(reason, &aad)?);
329            }
330        }
331        Ok(sealed)
332    }
333
334    fn open_approval_request(&self, request: &ApprovalRequest) -> Result<ApprovalRequest> {
335        let aad = request_aad(&request.scope, &request.id);
336        let mut opened = request.clone();
337        opened.fingerprint = self.open_text(&request.fingerprint, "request fingerprint", &aad)?;
338        opened.args_redacted = self.open_json(&request.args_redacted, "request arguments", &aad)?;
339        opened.summary = self.open_text(&request.summary, "request summary", &aad)?;
340        if let Some(note) = &request.note {
341            opened.note = Some(self.open_text(note, "request note", &aad)?);
342        }
343        for decision in &mut opened.decisions {
344            if let Some(args) = &decision.edited_args {
345                decision.edited_args = Some(self.open_json(args, "edited arguments", &aad)?);
346            }
347            if let Some(reason) = &decision.reason {
348                decision.reason = Some(self.open_text(reason, "decision reason", &aad)?);
349            }
350        }
351        Ok(opened)
352    }
353
354    /// The decrypted pending rows of `scope` with their row keys.
355    async fn opened_pending(
356        &self,
357        scope: &ApprovalScope,
358    ) -> Result<Vec<(String, PendingApproval)>> {
359        self.inner
360            .pending(scope)
361            .await?
362            .into_iter()
363            .map(|entry| {
364                let (request, fingerprint) =
365                    self.open_call(&entry.request, scope, &entry.fingerprint)?;
366                Ok((
367                    entry.fingerprint,
368                    PendingApproval { fingerprint, request, requested_at: entry.requested_at },
369                ))
370            })
371            .collect()
372    }
373
374    /// The row key of the pending row for `fingerprint`, if one exists under any key.
375    async fn pending_row_key(
376        &self,
377        scope: &ApprovalScope,
378        fingerprint: &str,
379    ) -> Result<Option<String>> {
380        Ok(self
381            .opened_pending(scope)
382            .await?
383            .into_iter()
384            .find(|(_, entry)| entry.fingerprint == fingerprint)
385            .map(|(row_key, _)| row_key))
386    }
387}
388
389#[async_trait]
390impl<S: ApprovalStore> ApprovalStore for EncryptedApprovalStore<S> {
391    async fn record_pending(
392        &self,
393        scope: &ApprovalScope,
394        request: &ToolConfirmationRequest,
395    ) -> Result<()> {
396        self.record_pending_keyed(scope, &request.fingerprint(), request).await
397    }
398
399    async fn record_pending_keyed(
400        &self,
401        scope: &ApprovalScope,
402        fingerprint: &str,
403        request: &ToolConfirmationRequest,
404    ) -> Result<()> {
405        // A call already pending under a previous key's row keeps that row, so recording
406        // it again keeps its request time as the trait requires.
407        let row_key = match self.pending_row_key(scope, fingerprint).await? {
408            Some(existing) => existing,
409            None => row_key(&self.current_key, scope, fingerprint),
410        };
411        let sealed = self.seal_call(request, fingerprint, scope, &row_key)?;
412        self.inner.record_pending_keyed(scope, &row_key, &sealed).await
413    }
414
415    async fn pending(&self, scope: &ApprovalScope) -> Result<Vec<PendingApproval>> {
416        Ok(self.opened_pending(scope).await?.into_iter().map(|(_, entry)| entry).collect())
417    }
418
419    async fn decide(
420        &self,
421        scope: &ApprovalScope,
422        fingerprint: &str,
423        approval: ToolApproval,
424    ) -> Result<()> {
425        // The decision clears the pending row, so it goes under the pending row's key.
426        let row_key = match self.pending_row_key(scope, fingerprint).await? {
427            Some(existing) => existing,
428            None => row_key(&self.current_key, scope, fingerprint),
429        };
430        let sealed = self.seal_approval(approval, fingerprint, scope, &row_key)?;
431        self.inner.decide(scope, &row_key, sealed).await
432    }
433
434    async fn take_decision(
435        &self,
436        scope: &ApprovalScope,
437        fingerprint: &str,
438    ) -> Result<Option<ToolConfirmationDecision>> {
439        for row_key in self.row_keys(scope, fingerprint) {
440            if let Some(decision) = self.inner.take_decision(scope, &row_key).await? {
441                return Ok(Some(decision));
442            }
443        }
444        Ok(None)
445    }
446
447    async fn has_decision(&self, scope: &ApprovalScope, fingerprint: &str) -> Result<bool> {
448        // The trait's default on real fingerprints: a call no longer pending may have a
449        // decision; `take_approval` then finds it under whichever key sealed it.
450        Ok(!self.pending(scope).await?.iter().any(|entry| entry.fingerprint == fingerprint))
451    }
452
453    async fn take_approval(
454        &self,
455        scope: &ApprovalScope,
456        fingerprint: &str,
457    ) -> Result<Option<ToolApproval>> {
458        for row_key in self.row_keys(scope, fingerprint) {
459            if let Some(approval) = self.inner.take_approval(scope, &row_key).await? {
460                let (approval, _) = self.open_approval(approval, scope, &row_key)?;
461                return Ok(Some(approval));
462            }
463        }
464        Ok(None)
465    }
466
467    async fn create_request(&self, request: &ApprovalRequest) -> Result<ApprovalRequest> {
468        let stored = self.inner.create_request(&self.seal_approval_request(request)?).await?;
469        self.open_approval_request(&stored)
470    }
471
472    async fn get_request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
473        match self.inner.get_request(id).await? {
474            Some(request) => Ok(Some(self.open_approval_request(&request)?)),
475            None => Ok(None),
476        }
477    }
478
479    async fn replace_request(
480        &self,
481        request: &ApprovalRequest,
482        expected_version: u64,
483    ) -> Result<bool> {
484        self.inner.replace_request(&self.seal_approval_request(request)?, expected_version).await
485    }
486
487    async fn list_requests(&self, query: &ApprovalRequestQuery) -> Result<Vec<ApprovalRequest>> {
488        self.inner
489            .list_requests(query)
490            .await?
491            .iter()
492            .map(|request| self.open_approval_request(request))
493            .collect()
494    }
495
496    async fn put_delegation(&self, delegation: &ApprovalDelegation) -> Result<()> {
497        self.inner.put_delegation(delegation).await
498    }
499
500    async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>> {
501        self.inner.delegations_to(to).await
502    }
503
504    async fn delete_delegation(&self, id: &str) -> Result<bool> {
505        self.inner.delete_delegation(id).await
506    }
507}
508
509/// Key rotation over the SQLite store (spec 3.1 §7.12).
510#[cfg(feature = "sqlite")]
511impl EncryptedApprovalStore<crate::SqliteApprovalStore> {
512    /// Re-keys and re-seals every held call, decision and request a previous key sealed
513    /// with the current key, and returns how many rows changed.
514    ///
515    /// # Errors
516    ///
517    /// Returns `session.encryption.decrypt_failed` when a value opens under none of the
518    /// keys, `session.encryption.unencrypted_data` when a row holds plaintext, or the
519    /// database error.
520    pub async fn rewrap_sqlite(&self) -> Result<u64> {
521        use sqlx::Row;
522        let pool = self.inner.pool().clone();
523        let db = |e: sqlx::Error| {
524            error(
525                "session.approval_store.storage",
526                format!("re-sealing the approval store failed: {e}"),
527            )
528        };
529        let under_current = |text: &str, aad: &[u8]| {
530            envelope::open(std::iter::once(&self.current_key), text, aad).is_some()
531        };
532        let mut rewritten = 0u64;
533
534        let rows = sqlx::query(
535            "SELECT app_name, user_id, session_id, fingerprint, request FROM adk_approval_pending",
536        )
537        .fetch_all(&pool)
538        .await
539        .map_err(db)?;
540        for row in rows {
541            let scope = ApprovalScope::new(
542                row.get::<String, _>("app_name"),
543                row.get::<String, _>("user_id"),
544                row.get::<String, _>("session_id"),
545            );
546            let old_row_key: String = row.get("fingerprint");
547            let stored: ToolConfirmationRequest =
548                serde_json::from_str(&row.get::<String, _>("request"))
549                    .map_err(serialization_error)?;
550            let sealed_args = stored.args.as_str().filter(|text| text.starts_with(ENVELOPE_PREFIX));
551            let (opened, fingerprint) = match sealed_args {
552                Some(text) if under_current(text, &pending_aad(&scope, &old_row_key)) => continue,
553                Some(_) => self.open_call(&stored, &scope, &old_row_key)?,
554                // A plaintext row written before the key: its row key is the fingerprint.
555                None if self.legacy_migration => (stored.clone(), old_row_key.clone()),
556                None => return Err(unencrypted_error("held call arguments")),
557            };
558            let new_row_key = row_key(&self.current_key, &scope, &fingerprint);
559            let sealed = self.seal_call(&opened, &fingerprint, &scope, &new_row_key)?;
560            sqlx::query(
561                "UPDATE adk_approval_pending SET fingerprint = ?, request = ? \
562                 WHERE app_name = ? AND user_id = ? AND session_id = ? AND fingerprint = ?",
563            )
564            .bind(&new_row_key)
565            .bind(serde_json::to_string(&sealed).map_err(serialization_error)?)
566            .bind(&scope.app_name)
567            .bind(&scope.user_id)
568            .bind(&scope.session_id)
569            .bind(&old_row_key)
570            .execute(&pool)
571            .await
572            .map_err(db)?;
573            rewritten += 1;
574        }
575
576        let rows = sqlx::query(
577            "SELECT app_name, user_id, session_id, fingerprint, approval FROM adk_approval_decisions",
578        )
579        .fetch_all(&pool)
580        .await
581        .map_err(db)?;
582        for row in rows {
583            let scope = ApprovalScope::new(
584                row.get::<String, _>("app_name"),
585                row.get::<String, _>("user_id"),
586                row.get::<String, _>("session_id"),
587            );
588            let old_row_key: String = row.get("fingerprint");
589            let stored: ToolApproval = serde_json::from_str(&row.get::<String, _>("approval"))
590                .map_err(serialization_error)?;
591            let sealed_blob =
592                stored.message.as_deref().filter(|text| text.starts_with(ENVELOPE_PREFIX));
593            let (opened, fingerprint) = match sealed_blob {
594                Some(blob) if under_current(blob, &decision_aad(&scope, &old_row_key)) => continue,
595                Some(_) => self.open_approval(stored, &scope, &old_row_key)?,
596                None if self.legacy_migration => (stored, old_row_key.clone()),
597                None => return Err(unencrypted_error("decision")),
598            };
599            let new_row_key = row_key(&self.current_key, &scope, &fingerprint);
600            let sealed = self.seal_approval(opened, &fingerprint, &scope, &new_row_key)?;
601            sqlx::query(
602                "UPDATE adk_approval_decisions SET fingerprint = ?, approval = ? \
603                 WHERE app_name = ? AND user_id = ? AND session_id = ? AND fingerprint = ?",
604            )
605            .bind(&new_row_key)
606            .bind(serde_json::to_string(&sealed).map_err(serialization_error)?)
607            .bind(&scope.app_name)
608            .bind(&scope.user_id)
609            .bind(&scope.session_id)
610            .bind(&old_row_key)
611            .execute(&pool)
612            .await
613            .map_err(db)?;
614            rewritten += 1;
615        }
616
617        let rows = sqlx::query("SELECT id, record FROM adk_approval_requests")
618            .fetch_all(&pool)
619            .await
620            .map_err(db)?;
621        for row in rows {
622            let id: String = row.get("id");
623            let stored: ApprovalRequest = serde_json::from_str(&row.get::<String, _>("record"))
624                .map_err(serialization_error)?;
625            let opened = if stored.summary.starts_with(ENVELOPE_PREFIX) {
626                if under_current(&stored.summary, &request_aad(&stored.scope, &stored.id)) {
627                    continue;
628                }
629                self.open_approval_request(&stored)?
630            } else if self.legacy_migration {
631                stored
632            } else {
633                return Err(unencrypted_error("request summary"));
634            };
635            let resealed = self.seal_approval_request(&opened)?;
636            sqlx::query("UPDATE adk_approval_requests SET record = ? WHERE id = ?")
637                .bind(serde_json::to_string(&resealed).map_err(serialization_error)?)
638                .bind(&id)
639                .execute(&pool)
640                .await
641                .map_err(db)?;
642            rewritten += 1;
643        }
644        Ok(rewritten)
645    }
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651    use adk_core::InMemoryApprovalStore;
652    use serde_json::json;
653
654    fn scope() -> ApprovalScope {
655        ApprovalScope::new("app", "alice", "s1")
656    }
657
658    #[tokio::test]
659    async fn arguments_and_decisions_reach_the_inner_store_sealed_under_a_keyed_row_key() {
660        let key = EncryptionKey::generate();
661        let store = EncryptedApprovalStore::new(InMemoryApprovalStore::new(), key, vec![]);
662        let request = ToolConfirmationRequest::new("bash", json!({ "command": "rm -rf build" }))
663            .with_function_call_id("call-1");
664        let fingerprint = request.fingerprint();
665        store.record_pending(&scope(), &request).await.unwrap();
666
667        let raw = store.inner().pending(&scope()).await.unwrap();
668        assert!(raw[0].fingerprint.starts_with(ROW_KEY_PREFIX), "{}", raw[0].fingerprint);
669        assert!(!raw[0].fingerprint.contains("rm -rf"), "the row key spells no arguments");
670        assert!(raw[0].request.args.as_str().unwrap().starts_with(ENVELOPE_PREFIX));
671        assert!(!serde_json::to_string(&raw[0].request).unwrap().contains("rm -rf"));
672
673        let opened = store.pending(&scope()).await.unwrap();
674        assert_eq!(opened[0].request, request);
675        assert_eq!(opened[0].fingerprint, fingerprint, "the real fingerprint comes back");
676        assert!(!store.has_decision(&scope(), &fingerprint).await.unwrap());
677
678        let approval = ToolApproval {
679            edited_args: Some(json!({ "command": "rm -rf target" })),
680            message: Some("only the build dir".into()),
681            ..ToolApproval::approve()
682        };
683        store.decide(&scope(), &fingerprint, approval.clone()).await.unwrap();
684        assert!(store.pending(&scope()).await.unwrap().is_empty(), "deciding clears the row");
685        assert!(store.has_decision(&scope(), &fingerprint).await.unwrap());
686        let raw_row = row_key(&store.current_key, &scope(), &fingerprint);
687        let raw = store.inner().take_approval(&scope(), &raw_row).await.unwrap().unwrap();
688        assert!(raw.edited_args.is_none() && raw.message.unwrap().starts_with(ENVELOPE_PREFIX));
689        store.decide(&scope(), &fingerprint, approval.clone()).await.unwrap();
690        assert_eq!(store.take_approval(&scope(), &fingerprint).await.unwrap(), Some(approval));
691        assert_eq!(store.take_approval(&scope(), &fingerprint).await.unwrap(), None, "consumed");
692    }
693
694    #[tokio::test]
695    async fn equal_calls_in_different_sessions_get_different_row_keys() {
696        let key = EncryptionKey::generate();
697        let request = ToolConfirmationRequest::new("bash", json!({ "command": "ls" }));
698        let a = row_key(&key, &ApprovalScope::new("app", "alice", "s1"), &request.fingerprint());
699        let b = row_key(&key, &ApprovalScope::new("app", "alice", "s2"), &request.fingerprint());
700        assert_ne!(a, b);
701        assert_eq!(
702            a,
703            row_key(&key, &ApprovalScope::new("app", "alice", "s1"), &request.fingerprint())
704        );
705    }
706
707    #[tokio::test]
708    async fn a_wrong_key_fails_the_read_instead_of_falling_back() {
709        let store = EncryptedApprovalStore::new(
710            InMemoryApprovalStore::new(),
711            EncryptionKey::generate(),
712            vec![],
713        );
714        let request = ToolConfirmationRequest::new("bash", json!({ "command": "ls" }));
715        store.record_pending(&scope(), &request).await.unwrap();
716        let other =
717            EncryptedApprovalStore::new(store.into_inner(), EncryptionKey::generate(), vec![]);
718        let error = other.pending(&scope()).await.unwrap_err();
719        assert_eq!(error.code, "session.encryption.decrypt_failed");
720
721        let plain = InMemoryApprovalStore::new();
722        plain.record_pending(&scope(), &request).await.unwrap();
723        let wrapped = EncryptedApprovalStore::new(plain, EncryptionKey::generate(), vec![]);
724        assert_eq!(
725            wrapped.pending(&scope()).await.unwrap_err().code,
726            "session.encryption.unencrypted_data"
727        );
728    }
729
730    #[tokio::test]
731    async fn a_previous_key_still_opens_and_decides_what_it_sealed() {
732        let old = EncryptionKey::generate();
733        let new = EncryptionKey::generate();
734        let store = EncryptedApprovalStore::new(InMemoryApprovalStore::new(), old, vec![]);
735        let request = ToolConfirmationRequest::new("bash", json!({ "command": "ls" }));
736        store.record_pending(&scope(), &request).await.unwrap();
737        let old = EncryptionKey::from_bytes(store.current_key.as_bytes()).unwrap();
738        let rotated = EncryptedApprovalStore::new(store.into_inner(), new, vec![old]);
739        let pending = rotated.pending(&scope()).await.unwrap();
740        assert_eq!(pending[0].request, request);
741        // The decision clears the row the previous key wrote and is found afterwards.
742        rotated.decide(&scope(), &request.fingerprint(), ToolApproval::approve()).await.unwrap();
743        assert!(rotated.pending(&scope()).await.unwrap().is_empty());
744        assert_eq!(
745            rotated.take_approval(&scope(), &request.fingerprint()).await.unwrap(),
746            Some(ToolApproval::approve())
747        );
748    }
749}