Skip to main content

adk_session/
encrypted.rs

1//! Transparent encryption wrapper for any [`SessionService`] implementation.
2//!
3//! [`EncryptedSession`] encrypts session state and event payloads with AES-256-GCM before
4//! they reach the inner [`SessionService`], and decrypts them on every read path (`create`,
5//! `get`, `list`).
6//!
7//! # What Reaches the Inner Service
8//!
9//! | Data | Stored as |
10//! |------|-----------|
11//! | Each state value, from `create` state and from event `state_delta` | An envelope string; the key name stays in plaintext |
12//! | Event payload: content, LLM response metadata, actions, long-running tool IDs | One envelope in the single text part of the event `content` |
13//! | Event ID, timestamp, invocation ID, branch, author | Plaintext, so the inner service can order and filter events |
14//! | `llm_request` and event `provider_metadata` | Not persisted, matching the database backends |
15//!
16//! State keys stay in plaintext so the inner service keeps its tier semantics. `app:` and
17//! `user:` values are stored encrypted in the shared app and user tiers and stay visible to
18//! every session of that app or user. `temp:` keys are dropped before encryption.
19//!
20//! # Envelope Format
21//!
22//! An envelope is `adk-enc:v1:` followed by base64 of `[12-byte nonce][ciphertext + tag]`.
23//! The associated data binds every ciphertext to where it is stored, so a value or event
24//! copied to another session, user, app, state key, or event ID fails authentication:
25//!
26//! | Data | Bound to |
27//! |------|----------|
28//! | Session-scoped state value | app name, user ID, session ID, state key |
29//! | `user:` state value | app name, user ID, state key |
30//! | `app:` state value | app name, state key |
31//! | Event payload | app name, user ID, session ID, event ID |
32//!
33//! Nonces are random, so rotate the key well before it has encrypted 2^32 values.
34//!
35//! # Key Rotation
36//!
37//! Writes always use the current key; reads try the current key, then each previous key.
38//! When `get` finds state values under a previous key, it re-encrypts them with the current
39//! key by appending a state-only rotation event through
40//! [`append_event_for_identity`](SessionService::append_event_for_identity) and returns any
41//! failure. Rotation events are not included in the events returned to callers.
42//!
43//! `SessionService` has no way to rewrite stored events, so events written under a previous
44//! key stay readable only while that key remains in `previous_keys`. Keep a retired key until
45//! the sessions that used it are deleted or expire. A concurrent write to a key between the
46//! read and the rotation append can be overwritten with the re-encrypted older value.
47//!
48//! # Addressing
49//!
50//! Ciphertext is bound to the full `(app_name, user_id, session_id)` identity, which a bare
51//! session ID does not determine, so [`append_event`](SessionService::append_event) returns a
52//! `session.encryption.identity_required` error. Use
53//! [`append_event_for_identity`](SessionService::append_event_for_identity), which the
54//! runner uses. `create` without a `session_id` generates a UUID v4 in the wrapper so the
55//! initial state can be bound to the session.
56//!
57//! History operations check the decrypted history, then forward to the inner service, which
58//! must implement them. A rewrite applies only while the stored history is still the one that
59//! was checked, `rewind_steps` counts only the events callers see, so key-rotation events are
60//! not steps, and a fork re-seals the copied state and events under the fork's identity.
61//!
62//! # Data Written by Earlier Releases
63//!
64//! Earlier releases stored `create` state as one `__encrypted_state` blob without associated
65//! data and passed event content and state deltas through in plaintext. Reads reject such
66//! data by default with `session.encryption.unencrypted_data`.
67//! [`with_legacy_migration`](EncryptedSession::with_legacy_migration) accepts it: the blob is
68//! decrypted, plaintext values and events are returned as stored, and `get` re-encrypts the
69//! state into the current format. Plaintext events stay plaintext in the inner service, so a
70//! session that holds them stays readable only with legacy migration enabled.
71//!
72//! # Example
73//!
74//! ```rust,no_run
75//! use adk_session::{EncryptedSession, EncryptionKey, InMemorySessionService};
76//!
77//! let inner = InMemorySessionService::new();
78//! let key = EncryptionKey::generate();
79//! let service = EncryptedSession::new(inner, key, vec![]);
80//! ```
81
82use crate::encryption_key::EncryptionKey;
83use crate::history::{
84    HistoryEdit, HistoryOutcome, HistoryRewrite, ImportSessionRequest, RewriteHistoryRequest,
85    SessionHistory,
86};
87use crate::service::{
88    AppendEventRequest, CreateRequest, DeleteRequest, GetRequest, ListRequest, SessionService,
89    validate_scope, validate_session_id,
90};
91use crate::session::{KEY_PREFIX_APP, KEY_PREFIX_TEMP, KEY_PREFIX_USER, Session};
92use crate::state::State;
93use crate::{Event, Events};
94
95use crate::envelope::{self, ENVELOPE_PREFIX};
96use adk_core::identity::{AdkIdentity, AppName, SessionId, UserId};
97use adk_core::{AdkError, Content, ErrorCategory, ErrorComponent, Part, Result};
98use async_trait::async_trait;
99use chrono::{DateTime, Utc};
100use serde_json::Value;
101use std::collections::HashMap;
102use uuid::Uuid;
103
104/// State key that held the whole encrypted state in earlier releases.
105const LEGACY_STATE_KEY: &str = "__encrypted_state";
106/// Author of the state-only events that carry re-encrypted values.
107const ROTATION_AUTHOR: &str = "__adk_session_key_rotation__";
108/// Domain separator prepended to all associated data.
109const AAD_DOMAIN: &[u8] = b"adk-session/encrypted-session/v1";
110
111/// Transparent encryption wrapper for any [`SessionService`].
112///
113/// Encrypts state values and event payloads with AES-256-GCM before writing to the inner
114/// service and decrypts them on read. See the [module documentation](self) for the storage
115/// format, what stays in plaintext, and how key rotation behaves.
116///
117/// # Example
118///
119/// ```rust,no_run
120/// use adk_session::{EncryptedSession, EncryptionKey, InMemorySessionService};
121///
122/// # fn main() -> adk_core::Result<()> {
123/// let current = EncryptionKey::from_env("SESSION_KEY")?;
124/// let retired = EncryptionKey::from_env("SESSION_KEY_PREVIOUS")?;
125/// let service = EncryptedSession::new(InMemorySessionService::new(), current, vec![retired]);
126/// # Ok(())
127/// # }
128/// ```
129pub struct EncryptedSession<S: SessionService> {
130    inner: S,
131    current_key: EncryptionKey,
132    previous_keys: Vec<EncryptionKey>,
133    legacy_migration: bool,
134}
135
136/// Borrowed `(app_name, user_id, session_id)` triple that ciphertext is bound to.
137#[derive(Clone, Copy)]
138struct SessionIdentity<'a> {
139    app_name: &'a str,
140    user_id: &'a str,
141    session_id: &'a str,
142}
143
144impl<'a> From<&'a AdkIdentity> for SessionIdentity<'a> {
145    fn from(identity: &'a AdkIdentity) -> Self {
146        Self {
147            app_name: identity.app_name.as_ref(),
148            user_id: identity.user_id.as_ref(),
149            session_id: identity.session_id.as_ref(),
150        }
151    }
152}
153
154/// Which key opened an envelope.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156enum KeyUsed {
157    Current,
158    Previous,
159}
160
161/// Decrypted state plus what `get` must re-encrypt with the current key.
162#[derive(Default)]
163struct OpenedState {
164    state: HashMap<String, Value>,
165    /// Values read under a previous key or from legacy data.
166    stale: HashMap<String, Value>,
167    /// Whether a legacy `__encrypted_state` blob is still stored.
168    legacy_blob: bool,
169}
170
171/// Builds length-prefixed associated data so distinct component lists never collide.
172fn associated_data(parts: &[&str]) -> Vec<u8> {
173    envelope::associated_data(AAD_DOMAIN, parts)
174}
175
176/// Associated data for a state value, scoped by the tier its key prefix selects.
177fn state_aad(id: &SessionIdentity<'_>, key: &str) -> Vec<u8> {
178    if key.starts_with(KEY_PREFIX_APP) {
179        associated_data(&["state", "app", id.app_name, key])
180    } else if key.starts_with(KEY_PREFIX_USER) {
181        associated_data(&["state", "user", id.app_name, id.user_id, key])
182    } else {
183        associated_data(&["state", "session", id.app_name, id.user_id, id.session_id, key])
184    }
185}
186
187fn event_aad(id: &SessionIdentity<'_>, event_id: &str) -> Vec<u8> {
188    associated_data(&["event", id.app_name, id.user_id, id.session_id, event_id])
189}
190
191fn encryption_error(code: &'static str, message: impl Into<String>) -> AdkError {
192    AdkError::new(ErrorComponent::Session, ErrorCategory::Internal, code, message)
193}
194
195fn decrypt_error(what: &str) -> AdkError {
196    encryption_error(
197        "session.encryption.decrypt_failed",
198        format!(
199            "failed to decrypt {what}: no configured key authenticates it; the data was written \
200             with an unknown key or was moved from another session, key, or event"
201        ),
202    )
203}
204
205fn unencrypted_error(what: &str) -> AdkError {
206    encryption_error(
207        "session.encryption.unencrypted_data",
208        format!(
209            "{what} is not encrypted by EncryptedSession; data written by an earlier \
210             adk-session release is read only with EncryptedSession::with_legacy_migration(true)"
211        ),
212    )
213}
214
215fn serialization_error(error: serde_json::Error) -> AdkError {
216    encryption_error(
217        "session.encryption.serialization_failed",
218        format!("failed to (de)serialize encrypted session data: {error}"),
219    )
220}
221
222/// Returns the envelope body of an event stored by this wrapper, if it has one.
223fn event_envelope(stored: &Event) -> Option<&str> {
224    match stored.llm_response.content.as_ref()?.parts.as_slice() {
225        [Part::Text { text }] => text.strip_prefix(ENVELOPE_PREFIX),
226        _ => None,
227    }
228}
229
230impl<S: SessionService> EncryptedSession<S> {
231    /// Create a new encrypted session wrapper.
232    ///
233    /// # Arguments
234    ///
235    /// * `inner` โ€” the underlying session service to delegate to
236    /// * `current_key` โ€” the active encryption key for new writes
237    /// * `previous_keys` โ€” older keys to try during decryption (for rotation)
238    ///
239    /// # Example
240    ///
241    /// ```rust
242    /// use adk_session::{EncryptedSession, EncryptionKey, InMemorySessionService};
243    ///
244    /// let service = EncryptedSession::new(
245    ///     InMemorySessionService::new(),
246    ///     EncryptionKey::generate(),
247    ///     vec![],
248    /// );
249    /// ```
250    pub fn new(inner: S, current_key: EncryptionKey, previous_keys: Vec<EncryptionKey>) -> Self {
251        Self { inner, current_key, previous_keys, legacy_migration: false }
252    }
253
254    /// Accepts data written by adk-session releases before the envelope format.
255    ///
256    /// When enabled, reads decrypt the legacy `__encrypted_state` blob and return plaintext
257    /// state values and events as stored; `get` then re-encrypts the state into the current
258    /// format. Plaintext from the inner service is not authenticated, so enable this only
259    /// while migrating existing sessions.
260    ///
261    /// # Example
262    ///
263    /// ```rust
264    /// use adk_session::{EncryptedSession, EncryptionKey, InMemorySessionService};
265    ///
266    /// let service = EncryptedSession::new(
267    ///     InMemorySessionService::new(),
268    ///     EncryptionKey::generate(),
269    ///     vec![],
270    /// )
271    /// .with_legacy_migration(true);
272    /// ```
273    pub fn with_legacy_migration(mut self, enabled: bool) -> Self {
274        self.legacy_migration = enabled;
275        self
276    }
277
278    /// Returns the wrapped session service.
279    ///
280    /// Reads through it return ciphertext; writes through it bypass encryption.
281    ///
282    /// # Example
283    ///
284    /// ```rust
285    /// use adk_session::{EncryptedSession, EncryptionKey, InMemorySessionService};
286    ///
287    /// let service =
288    ///     EncryptedSession::new(InMemorySessionService::new(), EncryptionKey::generate(), vec![]);
289    /// let _raw: &InMemorySessionService = service.inner();
290    /// ```
291    pub fn inner(&self) -> &S {
292        &self.inner
293    }
294
295    /// Consumes the wrapper and returns the wrapped session service.
296    ///
297    /// # Example
298    ///
299    /// ```rust
300    /// use adk_session::{EncryptedSession, EncryptionKey, InMemorySessionService};
301    ///
302    /// let old = EncryptionKey::from_bytes(&[1; 32]).unwrap();
303    /// let service = EncryptedSession::new(InMemorySessionService::new(), old, vec![]);
304    ///
305    /// // Re-wrap the same store with a new current key and the old key for reads.
306    /// let rotated = EncryptedSession::new(
307    ///     service.into_inner(),
308    ///     EncryptionKey::generate(),
309    ///     vec![EncryptionKey::from_bytes(&[1; 32]).unwrap()],
310    /// );
311    /// ```
312    pub fn into_inner(self) -> S {
313        self.inner
314    }
315
316    /// Encrypts `plaintext` with the current key and returns the envelope string.
317    fn seal(&self, plaintext: &[u8], aad: &[u8]) -> Result<String> {
318        envelope::seal(&self.current_key, plaintext, aad)
319    }
320
321    /// Decrypts the envelope body `encoded` (without its prefix) with the first configured
322    /// key that authenticates it.
323    fn open(&self, encoded: &str, aad: &[u8]) -> Option<(Vec<u8>, KeyUsed)> {
324        let keys = std::iter::once(&self.current_key).chain(&self.previous_keys);
325        envelope::open(keys, &format!("{ENVELOPE_PREFIX}{encoded}"), aad).map(
326            |(plaintext, index)| {
327                (plaintext, if index == 0 { KeyUsed::Current } else { KeyUsed::Previous })
328            },
329        )
330    }
331
332    /// Encrypts every non-`temp:` value of `state`, keeping the key names.
333    fn seal_state(
334        &self,
335        id: &SessionIdentity<'_>,
336        state: &HashMap<String, Value>,
337    ) -> Result<HashMap<String, Value>> {
338        state
339            .iter()
340            .filter(|(key, _)| !key.starts_with(KEY_PREFIX_TEMP))
341            .map(|(key, value)| {
342                if key == LEGACY_STATE_KEY {
343                    return Err(AdkError::new(
344                        ErrorComponent::Session,
345                        ErrorCategory::InvalidInput,
346                        "session.encryption.reserved_key",
347                        format!("state key '{LEGACY_STATE_KEY}' is reserved by EncryptedSession"),
348                    ));
349                }
350                let plaintext = serde_json::to_vec(value).map_err(serialization_error)?;
351                Ok((key.clone(), Value::String(self.seal(&plaintext, &state_aad(id, key))?)))
352            })
353            .collect()
354    }
355
356    /// Decrypts every state value returned by the inner service.
357    fn open_state(
358        &self,
359        id: &SessionIdentity<'_>,
360        raw: &HashMap<String, Value>,
361    ) -> Result<OpenedState> {
362        let mut opened = OpenedState::default();
363        let mut legacy_state: HashMap<String, Value> = HashMap::new();
364
365        for (key, value) in raw {
366            if key == LEGACY_STATE_KEY {
367                match (value, self.legacy_migration) {
368                    // Tombstone written once the blob has been migrated.
369                    (Value::Null, _) => {}
370                    (Value::String(blob), true) => {
371                        let (plaintext, _) = self
372                            .open(blob, b"")
373                            .ok_or_else(|| decrypt_error("the legacy encrypted state blob"))?;
374                        legacy_state =
375                            serde_json::from_slice(&plaintext).map_err(serialization_error)?;
376                        opened.legacy_blob = true;
377                    }
378                    (_, _) => {
379                        return Err(unencrypted_error(&format!(
380                            "the legacy '{LEGACY_STATE_KEY}' state blob"
381                        )));
382                    }
383                }
384                continue;
385            }
386
387            match value.as_str().and_then(|s| s.strip_prefix(ENVELOPE_PREFIX)) {
388                Some(encoded) => {
389                    let (plaintext, key_used) = self
390                        .open(encoded, &state_aad(id, key))
391                        .ok_or_else(|| decrypt_error(&format!("state key '{key}'")))?;
392                    let value: Value =
393                        serde_json::from_slice(&plaintext).map_err(serialization_error)?;
394                    if key_used == KeyUsed::Previous {
395                        opened.stale.insert(key.clone(), value.clone());
396                    }
397                    opened.state.insert(key.clone(), value);
398                }
399                None if self.legacy_migration => {
400                    opened.stale.insert(key.clone(), value.clone());
401                    opened.state.insert(key.clone(), value.clone());
402                }
403                None => return Err(unencrypted_error(&format!("state key '{key}'"))),
404            }
405        }
406
407        // Per-key values were written after the legacy blob, so they take precedence.
408        for (key, value) in legacy_state {
409            if key.starts_with(KEY_PREFIX_TEMP) || opened.state.contains_key(&key) {
410                continue;
411            }
412            opened.stale.insert(key.clone(), value.clone());
413            opened.state.insert(key, value);
414        }
415
416        Ok(opened)
417    }
418
419    /// Returns the form of `event` stored in the inner service.
420    fn seal_event(&self, id: &SessionIdentity<'_>, event: &Event) -> Result<Event> {
421        let mut payload = event.clone();
422        payload.actions.state_delta.retain(|key, _| !key.starts_with(KEY_PREFIX_TEMP));
423        payload.llm_request = None;
424        payload.provider_metadata.clear();
425        let plaintext = serde_json::to_vec(&payload).map_err(serialization_error)?;
426
427        let mut stored = Event::with_id(event.id.clone(), event.invocation_id.clone());
428        stored.timestamp = event.timestamp;
429        stored.branch = event.branch.clone();
430        stored.author = event.author.clone();
431        stored.llm_response.content = Some(Content {
432            role: "model".to_string(),
433            parts: vec![Part::Text { text: self.seal(&plaintext, &event_aad(id, &event.id))? }],
434        });
435        stored.actions.state_delta = self.seal_state(id, &payload.actions.state_delta)?;
436        Ok(stored)
437    }
438
439    /// Recovers the original event from its stored form.
440    fn open_event(&self, id: &SessionIdentity<'_>, stored: &Event) -> Result<Event> {
441        let Some(encoded) = event_envelope(stored) else {
442            if self.legacy_migration {
443                return Ok(stored.clone());
444            }
445            return Err(unencrypted_error(&format!("event '{}'", stored.id)));
446        };
447        let (plaintext, _) = self
448            .open(encoded, &event_aad(id, &stored.id))
449            .ok_or_else(|| decrypt_error(&format!("event '{}'", stored.id)))?;
450        serde_json::from_slice(&plaintext).map_err(serialization_error)
451    }
452
453    /// Decrypts a session returned by the inner service for identity `id`.
454    fn open_session(
455        &self,
456        id: &SessionIdentity<'_>,
457        session: &dyn Session,
458    ) -> Result<(DecryptedSession, OpenedState)> {
459        let mut opened = self.open_state(id, &session.state().all())?;
460        let stored_events = session.events();
461        let mut events = Vec::with_capacity(stored_events.len());
462        // Read in place: each event is decrypted into a new one, so a copy would be dropped.
463        for stored in (0..stored_events.len()).filter_map(|index| stored_events.at(index)) {
464            let event = self.open_event(id, stored)?;
465            if event.author != ROTATION_AUTHOR {
466                events.push(event);
467            }
468        }
469
470        let decrypted = DecryptedSession {
471            app_name: id.app_name.to_string(),
472            user_id: id.user_id.to_string(),
473            session_id: id.session_id.to_string(),
474            state: std::mem::take(&mut opened.state),
475            events,
476            updated_at: session.last_update_time(),
477        };
478        Ok((decrypted, opened))
479    }
480
481    /// Decrypts a stored history, leaving out key-rotation events.
482    fn open_history(
483        &self,
484        identity: &AdkIdentity,
485        stored: &SessionHistory,
486    ) -> Result<SessionHistory> {
487        let id = SessionIdentity::from(identity);
488        let mut events = Vec::with_capacity(stored.events.len());
489        for event in &stored.events {
490            let event = self.open_event(&id, event)?;
491            if event.author != ROTATION_AUTHOR {
492                events.push(event);
493            }
494        }
495        let state = self.open_state(&id, &stored.state)?.state;
496        let initial_state = match &stored.initial_state {
497            Some(initial) => Some(self.open_state(&id, initial)?.state),
498            None => None,
499        };
500        let mut history = SessionHistory::new(events, state, initial_state);
501        history.shared_tiers = stored.shared_tiers;
502        Ok(history)
503    }
504
505    /// Re-encrypts `opened.stale` with the current key through a state-only event.
506    async fn reencrypt(&self, id: &SessionIdentity<'_>, opened: &OpenedState) -> Result<()> {
507        let mut rotation = Event::new("");
508        rotation.author = ROTATION_AUTHOR.to_string();
509        rotation.actions.state_delta = opened.stale.clone();
510        let mut stored = self.seal_event(id, &rotation)?;
511        if opened.legacy_blob {
512            stored.actions.state_delta.insert(LEGACY_STATE_KEY.to_string(), Value::Null);
513        }
514
515        let identity = AdkIdentity::new(
516            AppName::try_from(id.app_name)?,
517            UserId::try_from(id.user_id)?,
518            SessionId::try_from(id.session_id)?,
519        );
520        self.inner
521            .append_event_for_identity(AppendEventRequest { identity, event: stored })
522            .await?;
523        tracing::info!(
524            session.id = %id.session_id,
525            state.keys = opened.stale.len(),
526            "re-encrypted session state with the current key"
527        );
528        Ok(())
529    }
530}
531
532/// Key rotation over the SQLite backend (spec 3.1 ยง7.12): the trait cannot rewrite stored
533/// events, so the rows are re-sealed in place.
534#[cfg(feature = "sqlite")]
535impl EncryptedSession<crate::sqlite::SqliteSessionService> {
536    /// Re-seals every state value and event a previous key sealed with the current key, in
537    /// every session, app and user tier of the database, and returns how many rows changed.
538    ///
539    /// Build the wrapper with the new key as `current_key` and the retired keys as
540    /// `previous_keys`; after this returns, the previous keys open nothing in the database
541    /// and can be dropped. With [`with_legacy_migration`](Self::with_legacy_migration), a
542    /// row written in plaintext before a key was configured is sealed too, so a store can
543    /// be encrypted in place.
544    ///
545    /// # Errors
546    ///
547    /// Returns `session.encryption.decrypt_failed` when a value opens under none of the
548    /// keys, `session.encryption.unencrypted_data` when a row holds plaintext and legacy
549    /// migration is off, or the database error.
550    pub async fn rewrap_sqlite(&self) -> Result<u64> {
551        use sqlx::Row;
552        let pool = self.inner.pool().clone();
553        let db = |e: sqlx::Error| {
554            encryption_error(
555                "session.encryption.storage",
556                format!("re-sealing the session store failed: {e}"),
557            )
558        };
559        let mut rewritten = 0u64;
560
561        let rows =
562            sqlx::query("SELECT app_name, user_id, session_id, state, initial_state FROM sessions")
563                .fetch_all(&pool)
564                .await
565                .map_err(db)?;
566        for row in rows {
567            let (app, user, session): (String, String, String) =
568                (row.get("app_name"), row.get("user_id"), row.get("session_id"));
569            let id = SessionIdentity { app_name: &app, user_id: &user, session_id: &session };
570            let state: String = row.get("state");
571            let initial: Option<String> = row.get("initial_state");
572            let (state, changed_state) = self.rewrap_state_json(&id, &state, "")?;
573            let (initial, changed_initial) = match initial {
574                Some(initial) => {
575                    let (text, changed) = self.rewrap_state_json(&id, &initial, "")?;
576                    (Some(text), changed)
577                }
578                None => (None, false),
579            };
580            if changed_state || changed_initial {
581                sqlx::query(
582                    "UPDATE sessions SET state = ?, initial_state = ? \
583                     WHERE app_name = ? AND user_id = ? AND session_id = ?",
584                )
585                .bind(state)
586                .bind(initial)
587                .bind(&app)
588                .bind(&user)
589                .bind(&session)
590                .execute(&pool)
591                .await
592                .map_err(db)?;
593                rewritten += 1;
594            }
595        }
596
597        let rows = sqlx::query(
598            "SELECT id, app_name, user_id, session_id, invocation_id, branch, author, timestamp, \
599             llm_response, actions, long_running_tool_ids FROM events",
600        )
601        .fetch_all(&pool)
602        .await
603        .map_err(db)?;
604        for row in rows {
605            let (event_id, app, user, session): (String, String, String, String) =
606                (row.get("id"), row.get("app_name"), row.get("user_id"), row.get("session_id"));
607            let id = SessionIdentity { app_name: &app, user_id: &user, session_id: &session };
608            let response: String = row.get("llm_response");
609            let actions: String = row.get("actions");
610            let mut response: Value =
611                serde_json::from_str(&response).map_err(serialization_error)?;
612            let mut actions: Value = serde_json::from_str(&actions).map_err(serialization_error)?;
613            let mut changed = false;
614            let text = response
615                .pointer_mut("/content/parts/0/text")
616                .and_then(|text| text.as_str().map(str::to_string).map(|t| (text, t)));
617            match text {
618                Some((slot, text)) if text.starts_with(ENVELOPE_PREFIX) => {
619                    let aad = event_aad(&id, &event_id);
620                    if let Some(resealed) =
621                        self.reseal(&text, &aad, &format!("event '{event_id}'"))?
622                    {
623                        *slot = Value::String(resealed);
624                        changed = true;
625                    }
626                }
627                _ if self.legacy_migration => {
628                    // A plaintext event written before the key: stored as `seal_event`
629                    // stores one, with its payload in the envelope.
630                    let timestamp: String = row.get("timestamp");
631                    let tool_ids: String = row.get("long_running_tool_ids");
632                    let event = Event {
633                        id: event_id.clone(),
634                        timestamp: DateTime::parse_from_rfc3339(&timestamp)
635                            .map(|t| t.with_timezone(&Utc))
636                            .unwrap_or_else(|_| Utc::now()),
637                        invocation_id: row.get("invocation_id"),
638                        branch: row.get("branch"),
639                        author: row.get("author"),
640                        llm_request: None,
641                        llm_response: serde_json::from_value(response.clone())
642                            .map_err(serialization_error)?,
643                        actions: serde_json::from_value(actions.clone())
644                            .map_err(serialization_error)?,
645                        long_running_tool_ids: serde_json::from_str(&tool_ids)
646                            .map_err(serialization_error)?,
647                        provider_metadata: HashMap::new(),
648                    };
649                    let sealed = self.seal_event(&id, &event)?;
650                    response =
651                        serde_json::to_value(&sealed.llm_response).map_err(serialization_error)?;
652                    actions = serde_json::to_value(&sealed.actions).map_err(serialization_error)?;
653                    changed = true;
654                }
655                _ => return Err(unencrypted_error(&format!("event '{event_id}'"))),
656            }
657            if let Some(delta) = actions.get_mut("state_delta").and_then(Value::as_object_mut)
658                && self.rewrap_state_map(&id, delta, "")?
659            {
660                changed = true;
661            }
662            if changed {
663                sqlx::query(
664                    "UPDATE events SET llm_response = ?, actions = ? \
665                     WHERE id = ? AND app_name = ? AND user_id = ? AND session_id = ?",
666                )
667                .bind(serde_json::to_string(&response).map_err(serialization_error)?)
668                .bind(serde_json::to_string(&actions).map_err(serialization_error)?)
669                .bind(&event_id)
670                .bind(&app)
671                .bind(&user)
672                .bind(&session)
673                .execute(&pool)
674                .await
675                .map_err(db)?;
676                rewritten += 1;
677            }
678        }
679
680        let rows = sqlx::query("SELECT app_name, state FROM app_states")
681            .fetch_all(&pool)
682            .await
683            .map_err(db)?;
684        for row in rows {
685            let app: String = row.get("app_name");
686            let id = SessionIdentity { app_name: &app, user_id: "", session_id: "" };
687            let state: String = row.get("state");
688            let (state, changed) = self.rewrap_state_json(&id, &state, KEY_PREFIX_APP)?;
689            if changed {
690                sqlx::query("UPDATE app_states SET state = ? WHERE app_name = ?")
691                    .bind(state)
692                    .bind(&app)
693                    .execute(&pool)
694                    .await
695                    .map_err(db)?;
696                rewritten += 1;
697            }
698        }
699
700        let rows = sqlx::query("SELECT app_name, user_id, state FROM user_states")
701            .fetch_all(&pool)
702            .await
703            .map_err(db)?;
704        for row in rows {
705            let (app, user): (String, String) = (row.get("app_name"), row.get("user_id"));
706            let id = SessionIdentity { app_name: &app, user_id: &user, session_id: "" };
707            let state: String = row.get("state");
708            let (state, changed) = self.rewrap_state_json(&id, &state, KEY_PREFIX_USER)?;
709            if changed {
710                sqlx::query("UPDATE user_states SET state = ? WHERE app_name = ? AND user_id = ?")
711                    .bind(state)
712                    .bind(&app)
713                    .bind(&user)
714                    .execute(&pool)
715                    .await
716                    .map_err(db)?;
717                rewritten += 1;
718            }
719        }
720        Ok(rewritten)
721    }
722
723    /// Re-seals the envelopes of a stored JSON state map whose keys the backend stored
724    /// without `prefix` (the app and user tiers); returns the text and whether any value
725    /// changed.
726    fn rewrap_state_json(
727        &self,
728        id: &SessionIdentity<'_>,
729        json: &str,
730        prefix: &str,
731    ) -> Result<(String, bool)> {
732        let mut state: Value = serde_json::from_str(json).map_err(serialization_error)?;
733        let changed = match state.as_object_mut() {
734            Some(map) => self.rewrap_state_map(id, map, prefix)?,
735            None => false,
736        };
737        Ok((serde_json::to_string(&state).map_err(serialization_error)?, changed))
738    }
739
740    fn rewrap_state_map(
741        &self,
742        id: &SessionIdentity<'_>,
743        map: &mut serde_json::Map<String, Value>,
744        prefix: &str,
745    ) -> Result<bool> {
746        let mut changed = false;
747        for (key, value) in map.iter_mut() {
748            if key == LEGACY_STATE_KEY || value.is_null() {
749                continue;
750            }
751            match value.as_str() {
752                Some(text) if text.starts_with(ENVELOPE_PREFIX) => {
753                    let aad = state_aad(id, &format!("{prefix}{key}"));
754                    if let Some(resealed) =
755                        self.reseal(text, &aad, &format!("state value '{key}'"))?
756                    {
757                        *value = Value::String(resealed);
758                        changed = true;
759                    }
760                }
761                _ if self.legacy_migration => {
762                    // A plaintext value written before the key, sealed as `seal_state` would.
763                    let plaintext = serde_json::to_vec(value).map_err(serialization_error)?;
764                    let aad = state_aad(id, &format!("{prefix}{key}"));
765                    *value = Value::String(self.seal(&plaintext, &aad)?);
766                    changed = true;
767                }
768                _ => return Err(unencrypted_error(&format!("state value '{key}'"))),
769            }
770        }
771        Ok(changed)
772    }
773
774    /// The envelope `text` sealed again with the current key when a previous key sealed it;
775    /// `None` when the current key already did.
776    fn reseal(&self, text: &str, aad: &[u8], what: &str) -> Result<Option<String>> {
777        let encoded = text.strip_prefix(ENVELOPE_PREFIX).unwrap_or(text);
778        let (plaintext, used) = self.open(encoded, aad).ok_or_else(|| decrypt_error(what))?;
779        match used {
780            KeyUsed::Current => Ok(None),
781            KeyUsed::Previous => Ok(Some(self.seal(&plaintext, aad)?)),
782        }
783    }
784}
785
786#[async_trait]
787impl<S: SessionService> SessionService for EncryptedSession<S> {
788    async fn create(&self, mut req: CreateRequest) -> Result<Box<dyn Session>> {
789        let session_id = req.session_id.get_or_insert_with(|| Uuid::new_v4().to_string()).clone();
790        req.try_identity()?;
791        let app_name = req.app_name.clone();
792        let user_id = req.user_id.clone();
793        let id =
794            SessionIdentity { app_name: &app_name, user_id: &user_id, session_id: &session_id };
795
796        req.state = self.seal_state(&id, &req.state)?;
797        let session = self.inner.create(req).await?;
798        let (decrypted, _) = self.open_session(&id, session.as_ref())?;
799        Ok(Box::new(decrypted))
800    }
801
802    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
803        req.try_identity()?;
804        let app_name = req.app_name.clone();
805        let user_id = req.user_id.clone();
806        let session_id = req.session_id.clone();
807        let id =
808            SessionIdentity { app_name: &app_name, user_id: &user_id, session_id: &session_id };
809
810        let session = self.inner.get(req).await?;
811        let (decrypted, opened) = self.open_session(&id, session.as_ref())?;
812        if !opened.stale.is_empty() || opened.legacy_blob {
813            self.reencrypt(&id, &opened).await?;
814        }
815        Ok(Box::new(decrypted))
816    }
817
818    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
819        validate_scope(&req.app_name, &req.user_id)?;
820        let app_name = req.app_name.clone();
821        let user_id = req.user_id.clone();
822        let sessions = self.inner.list(req).await?;
823
824        sessions
825            .iter()
826            .map(|session| {
827                let id = SessionIdentity {
828                    app_name: &app_name,
829                    user_id: &user_id,
830                    session_id: session.id(),
831                };
832                let (decrypted, _) = self.open_session(&id, session.as_ref())?;
833                Ok(Box::new(decrypted) as Box<dyn Session>)
834            })
835            .collect()
836    }
837
838    async fn delete(&self, req: DeleteRequest) -> Result<()> {
839        req.try_identity()?;
840        self.inner.delete(req).await
841    }
842
843    /// Always fails, with an invalid-input error for an invalid session ID: ciphertext is bound
844    /// to the full session identity, which a bare session ID does not determine. Use
845    /// [`append_event_for_identity`](SessionService::append_event_for_identity).
846    async fn append_event(&self, session_id: &str, _event: Event) -> Result<()> {
847        validate_session_id(session_id)?;
848        Err(AdkError::new(
849            ErrorComponent::Session,
850            ErrorCategory::Unsupported,
851            "session.encryption.identity_required",
852            format!(
853                "EncryptedSession cannot append to session '{session_id}' by ID alone because \
854                 ciphertext is bound to (app_name, user_id, session_id); call \
855                 append_event_for_identity instead"
856            ),
857        ))
858    }
859
860    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
861        let stored = self.seal_event(&SessionIdentity::from(&req.identity), &req.event)?;
862        self.inner
863            .append_event_for_identity(AppendEventRequest { identity: req.identity, event: stored })
864            .await
865    }
866
867    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
868        validate_scope(app_name, user_id)?;
869        self.inner.delete_all_sessions(app_name, user_id).await
870    }
871
872    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
873        Ok(self.open_history(identity, &self.inner.history(identity).await?)?)
874    }
875
876    /// Checks the rewrite against the decrypted history, then forwards it to the inner
877    /// service with the stored history's version, so the inner write applies only to the
878    /// history that was checked. `RewindSteps` counts only the events callers see.
879    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
880        let identity = &req.identity;
881        let stored = self.inner.history(identity).await?;
882        let plain = self.open_history(identity, &stored)?;
883        let checked = plain.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
884
885        let id = SessionIdentity::from(identity);
886        let rewrite = match &req.rewrite {
887            HistoryRewrite::RewindSteps { .. } => match checked.events.last() {
888                Some(last) => HistoryRewrite::RewindTo { event_id: last.id.clone() },
889                None => HistoryRewrite::RewindSteps { steps: stored.events.len() },
890            },
891            HistoryRewrite::Edit { edits } => HistoryRewrite::Edit {
892                edits: edits
893                    .iter()
894                    .map(|edit| match edit {
895                        HistoryEdit::Replace { event } => Ok(HistoryEdit::Replace {
896                            event: Box::new(self.seal_event(&id, event)?),
897                        }),
898                        other => Ok(other.clone()),
899                    })
900                    .collect::<Result<_>>()?,
901            },
902            other => other.clone(),
903        };
904        let outcome = self
905            .inner
906            .rewrite_history(
907                RewriteHistoryRequest::new(identity.clone(), rewrite)
908                    .expect_version(stored.version()),
909            )
910            .await?;
911        let (decrypted, _) = self.open_session(&id, outcome.session.as_ref())?;
912        Ok(HistoryOutcome::new(Box::new(decrypted), checked.change))
913    }
914
915    /// Seals the state, creation state, and events under the new session's identity.
916    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
917        let id = SessionIdentity::from(&req.identity);
918        let sealed = ImportSessionRequest {
919            identity: req.identity.clone(),
920            initial_state: self.seal_state(&id, &req.initial_state)?,
921            state: self.seal_state(&id, &req.state)?,
922            events: req
923                .events
924                .iter()
925                .map(|event| self.seal_event(&id, event))
926                .collect::<Result<_>>()?,
927        };
928        let session = self.inner.import_session(sealed).await?;
929        let (decrypted, _) = self.open_session(&id, session.as_ref())?;
930        Ok(Box::new(decrypted))
931    }
932
933    async fn health_check(&self) -> Result<()> {
934        self.inner.health_check().await
935    }
936}
937
938/// A session presenting decrypted state and events.
939struct DecryptedSession {
940    app_name: String,
941    user_id: String,
942    session_id: String,
943    state: HashMap<String, Value>,
944    events: Vec<Event>,
945    updated_at: DateTime<Utc>,
946}
947
948impl Session for DecryptedSession {
949    fn id(&self) -> &str {
950        &self.session_id
951    }
952
953    fn app_name(&self) -> &str {
954        &self.app_name
955    }
956
957    fn user_id(&self) -> &str {
958        &self.user_id
959    }
960
961    fn state(&self) -> &dyn State {
962        self
963    }
964
965    fn events(&self) -> &dyn Events {
966        self
967    }
968
969    fn last_update_time(&self) -> DateTime<Utc> {
970        self.updated_at
971    }
972
973    fn take_events(&mut self) -> Vec<Event> {
974        std::mem::take(&mut self.events)
975    }
976}
977
978impl State for DecryptedSession {
979    fn get(&self, key: &str) -> Option<Value> {
980        self.state.get(key).cloned()
981    }
982
983    fn set(&mut self, key: String, value: Value) {
984        if let Err(msg) = adk_core::validate_state_key(&key) {
985            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
986            return;
987        }
988        self.state.insert(key, value);
989    }
990
991    fn all(&self) -> HashMap<String, Value> {
992        self.state.clone()
993    }
994}
995
996impl Events for DecryptedSession {
997    fn all(&self) -> Vec<Event> {
998        self.events.clone()
999    }
1000
1001    fn len(&self) -> usize {
1002        self.events.len()
1003    }
1004
1005    fn at(&self, index: usize) -> Option<&Event> {
1006        self.events.get(index)
1007    }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013
1014    #[test]
1015    fn associated_data_is_unambiguous() {
1016        // Without length prefixes these would concatenate to the same bytes.
1017        assert_ne!(associated_data(&["ab", "c"]), associated_data(&["a", "bc"]));
1018    }
1019
1020    #[test]
1021    fn state_values_are_bound_to_their_tier() {
1022        let alice = SessionIdentity { app_name: "app", user_id: "alice", session_id: "s1" };
1023        let alice_other_session = SessionIdentity { session_id: "s2", ..alice };
1024        let bob = SessionIdentity { user_id: "bob", ..alice };
1025
1026        assert_eq!(state_aad(&alice, "app:x"), state_aad(&bob, "app:x"));
1027        assert_eq!(state_aad(&alice, "user:x"), state_aad(&alice_other_session, "user:x"));
1028        assert_ne!(state_aad(&alice, "user:x"), state_aad(&bob, "user:x"));
1029        assert_ne!(state_aad(&alice, "x"), state_aad(&alice_other_session, "x"));
1030        assert_ne!(state_aad(&alice, "x"), state_aad(&alice, "y"));
1031    }
1032}