Skip to main content

agent_service/
google_calendar_access.rs

1//! Resolves per-invocation read access to owner- or family-shared calendars.
2
3use std::{str::FromStr, sync::Arc};
4
5use agent_storage::{
6    CalendarAccessMode, CalendarFamilyAccess, ConnectedCalendarId, ConnectedCalendarStore,
7    ExternalConnectionStatus, ExternalConnectionStore, FamilyId, UserId,
8};
9
10use crate::{FamilyService, FamilyServiceError};
11
12use super::{AuthorizedGoogleCalendar, GoogleCalendarAccessError};
13
14/// Checks current EME permissions and resolves the owner's credential for a read.
15pub struct GoogleCalendarAccessService {
16    calendars: Arc<dyn ConnectedCalendarStore>,
17    connections: Arc<dyn ExternalConnectionStore>,
18    families: Arc<FamilyService>,
19}
20
21impl GoogleCalendarAccessService {
22    pub fn new(
23        calendars: Arc<dyn ConnectedCalendarStore>,
24        connections: Arc<dyn ExternalConnectionStore>,
25        families: Arc<FamilyService>,
26    ) -> Self {
27        Self {
28            calendars,
29            connections,
30            families,
31        }
32    }
33
34    /// List calendars visible to the caller without decrypting any credentials.
35    ///
36    /// The optional family ID must come from trusted ToolContext. Family roster
37    /// membership is resolved live, so stale shares for departed owners vanish.
38    pub async fn list_readable_calendars(
39        &self,
40        user_id: &str,
41        family_id: Option<&str>,
42    ) -> Result<Vec<agent_storage::ConnectedCalendar>, GoogleCalendarAccessError> {
43        Ok(self
44            .list_readable_calendars_with_permissions(user_id, family_id)
45            .await?
46            .into_iter()
47            .map(|(calendar, _)| calendar)
48            .collect())
49    }
50
51    /// List calendars visible to the caller together with their effective write
52    /// permission, combining EME settings, family sharing and Google OAuth scopes.
53    pub async fn list_readable_calendars_with_permissions(
54        &self,
55        user_id: &str,
56        family_id: Option<&str>,
57    ) -> Result<Vec<(agent_storage::ConnectedCalendar, bool)>, GoogleCalendarAccessError> {
58        let user =
59            UserId::from_str(user_id).map_err(|_| GoogleCalendarAccessError::InvalidIdentity)?;
60        let (family, owners) = match family_id {
61            Some(value) => {
62                let family = FamilyId::from_str(value)
63                    .map_err(|_| GoogleCalendarAccessError::NotAuthorized)?;
64                let context = self
65                    .families
66                    .context_for_member(user, family)
67                    .await
68                    .map_err(map_family_error)?;
69                let owners = context
70                    .members
71                    .iter()
72                    .map(|member| UserId::from_str(&member.user_id))
73                    .collect::<Result<Vec<_>, _>>()
74                    .map_err(|_| GoogleCalendarAccessError::FamilyUnavailable)?;
75                (Some(family), owners)
76            }
77            None => (None, vec![user]),
78        };
79
80        let mut calendars = Vec::new();
81        for owner in owners {
82            let connections = self
83                .connections
84                .list_connections(owner)
85                .await
86                .map_err(|error| GoogleCalendarAccessError::Storage(error.to_string()))?;
87            for connection in connections.into_iter().filter(|connection| {
88                connection.provider == "google"
89                    && connection.status == ExternalConnectionStatus::Active
90            }) {
91                if !has_calendar_read_scope(&connection.granted_scopes) {
92                    continue;
93                }
94                let connected = self
95                    .calendars
96                    .list_for_connection(owner, connection.id)
97                    .await
98                    .map_err(|error| GoogleCalendarAccessError::Storage(error.to_string()))?;
99                calendars.extend(
100                    connected
101                        .into_iter()
102                        .filter(|calendar| {
103                            calendar.selected
104                                && (calendar.owner_id == user
105                                    || (family.is_some()
106                                        && calendar.family_id == family
107                                        && calendar.family_access.is_some()))
108                        })
109                        .map(|calendar| {
110                            let can_write = calendar.access_mode == CalendarAccessMode::ReadWrite
111                                && (calendar.owner_id == user
112                                    || calendar.family_access
113                                        == Some(CalendarFamilyAccess::Contributor))
114                                && has_calendar_write_scope(&connection.granted_scopes);
115                            (calendar, can_write)
116                        }),
117                );
118            }
119        }
120        calendars.sort_by(|(left, _), (right, _)| {
121            left.display_name
122                .as_deref()
123                .unwrap_or("")
124                .cmp(right.display_name.as_deref().unwrap_or(""))
125                .then_with(|| left.id.to_string().cmp(&right.id.to_string()))
126        });
127        Ok(calendars)
128    }
129
130    /// Authorize a read using trusted caller and selected-family context.
131    pub async fn authorize_read(
132        &self,
133        user_id: &str,
134        calendar_id: &str,
135        family_id: Option<&str>,
136    ) -> Result<AuthorizedGoogleCalendar, GoogleCalendarAccessError> {
137        self.authorize(user_id, calendar_id, family_id, false).await
138    }
139
140    /// Authorize a write. EME permissions and Google's granted write scope are
141    /// checked before the owner's refresh token is decrypted.
142    pub async fn authorize_write(
143        &self,
144        user_id: &str,
145        calendar_id: &str,
146        family_id: Option<&str>,
147    ) -> Result<AuthorizedGoogleCalendar, GoogleCalendarAccessError> {
148        self.authorize(user_id, calendar_id, family_id, true).await
149    }
150
151    async fn authorize(
152        &self,
153        user_id: &str,
154        calendar_id: &str,
155        family_id: Option<&str>,
156        write: bool,
157    ) -> Result<AuthorizedGoogleCalendar, GoogleCalendarAccessError> {
158        let user =
159            UserId::from_str(user_id).map_err(|_| GoogleCalendarAccessError::InvalidIdentity)?;
160        let calendar_id = ConnectedCalendarId::from_str(calendar_id)
161            .map_err(|_| GoogleCalendarAccessError::NotFound)?;
162        let calendar = self
163            .calendars
164            .get_selected(calendar_id)
165            .await
166            .map_err(|error| GoogleCalendarAccessError::Storage(error.to_string()))?
167            .ok_or(GoogleCalendarAccessError::NotFound)?;
168
169        if calendar.owner_id != user {
170            let family_id = family_id
171                .and_then(|value| FamilyId::from_str(value).ok())
172                .ok_or(GoogleCalendarAccessError::NotAuthorized)?;
173            if calendar.family_id != Some(family_id)
174                || !matches!(
175                    calendar.family_access,
176                    Some(CalendarFamilyAccess::Viewer | CalendarFamilyAccess::Contributor)
177                )
178            {
179                return Err(GoogleCalendarAccessError::NotAuthorized);
180            }
181            self.families
182                .context_for_member(user, family_id)
183                .await
184                .map_err(map_family_error)?;
185            self.families
186                .context_for_member(calendar.owner_id, family_id)
187                .await
188                .map_err(map_family_error)?;
189            if write && calendar.family_access != Some(CalendarFamilyAccess::Contributor) {
190                return Err(GoogleCalendarAccessError::WriteNotAuthorized);
191            }
192        }
193        if write && calendar.access_mode != CalendarAccessMode::ReadWrite {
194            return Err(GoogleCalendarAccessError::WriteNotAuthorized);
195        }
196
197        let connection = self
198            .connections
199            .get_connection(calendar.owner_id, calendar.connection_id)
200            .await
201            .map_err(|error| GoogleCalendarAccessError::Storage(error.to_string()))?
202            .filter(|connection| {
203                connection.provider == "google"
204                    && connection.status == ExternalConnectionStatus::Active
205            })
206            .ok_or(GoogleCalendarAccessError::NotFound)?;
207        let scope_granted = if write {
208            has_calendar_write_scope(&connection.granted_scopes)
209        } else {
210            has_calendar_read_scope(&connection.granted_scopes)
211        };
212        if !scope_granted {
213            return Err(if write {
214                GoogleCalendarAccessError::InsufficientWriteScopes
215            } else {
216                GoogleCalendarAccessError::InsufficientScopes
217            });
218        }
219
220        let refresh_token = self
221            .connections
222            .refresh_token(calendar.owner_id, calendar.connection_id)
223            .await
224            .map_err(|error| GoogleCalendarAccessError::Storage(error.to_string()))?;
225        Ok(AuthorizedGoogleCalendar {
226            calendar,
227            refresh_token,
228        })
229    }
230}
231
232fn has_calendar_read_scope(scopes: &[String]) -> bool {
233    scopes.iter().any(|scope| {
234        matches!(
235            scope.as_str(),
236            "https://www.googleapis.com/auth/calendar.events.readonly"
237                | "https://www.googleapis.com/auth/calendar.events"
238                | "https://www.googleapis.com/auth/calendar"
239        )
240    })
241}
242
243fn has_calendar_write_scope(scopes: &[String]) -> bool {
244    scopes.iter().any(|scope| {
245        matches!(
246            scope.as_str(),
247            "https://www.googleapis.com/auth/calendar.events"
248                | "https://www.googleapis.com/auth/calendar"
249        )
250    })
251}
252
253fn map_family_error(error: FamilyServiceError) -> GoogleCalendarAccessError {
254    match error {
255        FamilyServiceError::NotFound | FamilyServiceError::NotMember => {
256            GoogleCalendarAccessError::NotAuthorized
257        }
258        _ => GoogleCalendarAccessError::FamilyUnavailable,
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use agent_storage::{
266        CalendarAccessMode, CalendarFamilyAccess, ConnectedCalendarStore, DiscoveredCalendar,
267        ExternalConnectionStore, FamilyInvitationStore, FamilyRelationship,
268        InMemoryFamilyInvitationStore, InMemoryFamilyStore, NewExternalConnection,
269        SqliteConnectedCalendarStore, SqliteExternalConnectionStore,
270    };
271
272    #[tokio::test]
273    async fn owner_and_current_family_members_can_read_but_removed_members_cannot() {
274        assert!(!has_calendar_write_scope(&[
275            "https://www.googleapis.com/auth/calendar.events.readonly".into()
276        ]));
277        assert!(has_calendar_write_scope(&[
278            "https://www.googleapis.com/auth/calendar.events".into()
279        ]));
280
281        let path =
282            std::env::temp_dir().join(format!("eme-google-access-{}.sqlite", uuid::Uuid::new_v4()));
283        let owner = UserId::new();
284        let member = UserId::new();
285        let connections = Arc::new(SqliteExternalConnectionStore::open(&path, [0x42; 32]).unwrap());
286        let calendars = Arc::new(SqliteConnectedCalendarStore::open(&path).unwrap());
287        let connection = connections
288            .create_connection(NewExternalConnection {
289                owner_id: owner,
290                provider: "google".into(),
291                provider_subject: "google-subject".into(),
292                display_email: None,
293                refresh_token: "owner-refresh-token".into(),
294                granted_scopes: vec!["https://www.googleapis.com/auth/calendar.events".into()],
295            })
296            .await
297            .unwrap();
298        let discovered = calendars
299            .sync_discovered(
300                owner,
301                connection.id,
302                vec![DiscoveredCalendar {
303                    provider_calendar_id: "private-calendar@example.com".into(),
304                    display_name: Some("Private".into()),
305                    time_zone: Some("Europe/Madrid".into()),
306                    provider_access_role: Some("owner".into()),
307                }],
308            )
309            .await
310            .unwrap()
311            .remove(0);
312        calendars
313            .update(
314                owner,
315                discovered.id,
316                Some(true),
317                Some(CalendarAccessMode::ReadOnly),
318            )
319            .await
320            .unwrap();
321
322        let family_store = Arc::new(InMemoryFamilyStore::default());
323        let invitations = Arc::new(InMemoryFamilyInvitationStore::new(family_store.clone()));
324        let family_service = Arc::new(FamilyService::new(
325            family_store,
326            invitations as Arc<dyn FamilyInvitationStore>,
327        ));
328        let family = family_service
329            .create_family(owner, "Home", FamilyRelationship::Other)
330            .await
331            .unwrap();
332        family_service
333            .add_managed_member(owner, family.id, member, FamilyRelationship::Other)
334            .await
335            .unwrap();
336        calendars
337            .share_with_family(
338                owner,
339                discovered.id,
340                family.id,
341                CalendarFamilyAccess::Viewer,
342            )
343            .await
344            .unwrap();
345
346        let service = GoogleCalendarAccessService::new(
347            calendars.clone(),
348            connections.clone(),
349            family_service.clone(),
350        );
351        let calendar_id = discovered.id.to_string();
352        let family_id = family.id.to_string();
353        assert!(matches!(
354            service
355                .authorize_write(&owner.to_string(), &calendar_id, None)
356                .await,
357            Err(GoogleCalendarAccessError::WriteNotAuthorized)
358        ));
359        let owner_access = service
360            .authorize_read(&owner.to_string(), &calendar_id, None)
361            .await
362            .unwrap();
363        assert_eq!(owner_access.refresh_token, "owner-refresh-token");
364        let owner_permissions = service
365            .list_readable_calendars_with_permissions(&owner.to_string(), None)
366            .await
367            .unwrap();
368        assert_eq!(owner_permissions.len(), 1);
369        assert!(!owner_permissions[0].1); // EME calendar setting is read-only.
370        let family_access = service
371            .authorize_read(&member.to_string(), &calendar_id, Some(&family_id))
372            .await
373            .unwrap();
374        assert_eq!(
375            family_access.calendar.family_access,
376            Some(CalendarFamilyAccess::Viewer)
377        );
378        assert!(matches!(
379            service
380                .authorize_write(&member.to_string(), &calendar_id, Some(&family_id))
381                .await,
382            Err(GoogleCalendarAccessError::WriteNotAuthorized)
383        ));
384        calendars
385            .update(
386                owner,
387                discovered.id,
388                None,
389                Some(CalendarAccessMode::ReadWrite),
390            )
391            .await
392            .unwrap();
393        assert!(
394            service
395                .authorize_write(&owner.to_string(), &calendar_id, None)
396                .await
397                .is_ok()
398        );
399        let owner_permissions = service
400            .list_readable_calendars_with_permissions(&owner.to_string(), None)
401            .await
402            .unwrap();
403        assert!(owner_permissions[0].1); // EME and Google both grant writes.
404        assert!(matches!(
405            service
406                .authorize_write(&member.to_string(), &calendar_id, Some(&family_id))
407                .await,
408            Err(GoogleCalendarAccessError::WriteNotAuthorized)
409        ));
410        let viewer_permissions = service
411            .list_readable_calendars_with_permissions(&member.to_string(), Some(&family_id))
412            .await
413            .unwrap();
414        assert!(!viewer_permissions[0].1); // Viewer sharing never grants writes.
415        calendars
416            .share_with_family(
417                owner,
418                discovered.id,
419                family.id,
420                CalendarFamilyAccess::Contributor,
421            )
422            .await
423            .unwrap();
424        assert!(
425            service
426                .authorize_write(&member.to_string(), &calendar_id, Some(&family_id))
427                .await
428                .is_ok()
429        );
430        let visible_to_member = service
431            .list_readable_calendars(&member.to_string(), Some(&family_id))
432            .await
433            .unwrap();
434        assert_eq!(visible_to_member.len(), 1);
435        assert_eq!(visible_to_member[0].id, discovered.id);
436        let member_permissions = service
437            .list_readable_calendars_with_permissions(&member.to_string(), Some(&family_id))
438            .await
439            .unwrap();
440        assert!(member_permissions[0].1); // Contributor + owner setting + Google scope.
441        assert!(
442            service
443                .list_readable_calendars(&member.to_string(), None)
444                .await
445                .unwrap()
446                .is_empty()
447        );
448        assert!(matches!(
449            service
450                .authorize_read(&member.to_string(), &calendar_id, None)
451                .await,
452            Err(GoogleCalendarAccessError::NotAuthorized)
453        ));
454
455        family_service
456            .remove_member(owner, family.id, member)
457            .await
458            .unwrap();
459        assert!(matches!(
460            service
461                .authorize_read(&member.to_string(), &calendar_id, Some(&family_id))
462                .await,
463            Err(GoogleCalendarAccessError::NotAuthorized)
464        ));
465        assert!(matches!(
466            service
467                .list_readable_calendars(&member.to_string(), Some(&family_id))
468                .await,
469            Err(GoogleCalendarAccessError::NotAuthorized)
470        ));
471
472        drop(service);
473        drop(calendars);
474        drop(connections);
475        let _ = std::fs::remove_file(path);
476    }
477}