Skip to main content

agent_server/api/
google_oauth.rs

1//! Authenticated Google account connection and OAuth callback endpoints.
2
3use std::{path::Path, str::FromStr, sync::Arc};
4
5use actix_web::{
6    HttpRequest, HttpResponse, Responder, Scope, delete, get, post,
7    web::{self, Data, Json, Path as PathParam, Query},
8};
9use agent_service::{FamilyService, FamilyServiceError, GoogleCalendarAccessService};
10use agent_storage::{
11    CalendarAccessMode, CalendarFamilyAccess, ConnectedCalendarId, ConnectedCalendarStorageError,
12    ConnectedCalendarStore, DiscoveredCalendar, ExternalConnectionId, ExternalConnectionStatus,
13    ExternalConnectionStore, FamilyId, FileUserIdentityStore, NewExternalAuthorization,
14    NewExternalConnection, SqliteConnectedCalendarStore, SqliteExternalConnectionStore, UserId,
15    UserIdentityStore,
16};
17use chrono::{Duration, Utc};
18use google_tool::{
19    CalendarScope, GoogleCalendarRuntimeConfig, GoogleOAuthConfig, GoogleOAuthTokenManager,
20    authorization_request, exchange_code, fetch_user_info, list_calendars_with_access_token,
21};
22use serde::{Deserialize, Serialize};
23
24const AUTHORIZATION_TTL_MINUTES: i64 = 10;
25
26#[derive(Clone)]
27pub struct GoogleOAuthState {
28    config: Option<GoogleOAuthConfig>,
29    store: Option<SqliteExternalConnectionStore>,
30    calendar_store: Option<SqliteConnectedCalendarStore>,
31    token_manager: Arc<GoogleOAuthTokenManager>,
32}
33
34impl GoogleOAuthState {
35    pub fn from_env(data_dir: &Path) -> Result<Self, String> {
36        let client_id = std::env::var("GOOGLE_OAUTH_CLIENT_ID").ok();
37        let client_secret = std::env::var("GOOGLE_OAUTH_CLIENT_SECRET").ok();
38        let redirect_uri = std::env::var("GOOGLE_OAUTH_REDIRECT_URI").ok();
39        let encryption_key = std::env::var("EME_CREDENTIAL_ENCRYPTION_KEY").ok();
40        let configured = [
41            client_id.is_some(),
42            client_secret.is_some(),
43            redirect_uri.is_some(),
44            encryption_key.is_some(),
45        ];
46        if configured.iter().all(|value| !*value) {
47            return Ok(Self {
48                config: None,
49                store: None,
50                calendar_store: None,
51                token_manager: Arc::new(GoogleOAuthTokenManager::new()),
52            });
53        }
54        if configured.iter().any(|value| !*value) {
55            return Err("Google OAuth requires GOOGLE_OAUTH_CLIENT_ID, GOOGLE_OAUTH_CLIENT_SECRET, GOOGLE_OAUTH_REDIRECT_URI, and EME_CREDENTIAL_ENCRYPTION_KEY".to_owned());
56        }
57        let key = parse_encryption_key(encryption_key.as_deref().unwrap_or_default())?;
58        let database_path = data_dir.join("external_connections.sqlite");
59        let store = SqliteExternalConnectionStore::open(&database_path, key)
60            .map_err(|error| format!("opening external connection storage: {error}"))?;
61        let calendar_store = SqliteConnectedCalendarStore::open(&database_path)
62            .map_err(|error| format!("opening connected calendar storage: {error}"))?;
63        Ok(Self {
64            config: Some(GoogleOAuthConfig {
65                client_id: client_id.unwrap_or_default(),
66                client_secret: client_secret.unwrap_or_default(),
67                redirect_uri: redirect_uri.unwrap_or_default(),
68            }),
69            store: Some(store),
70            calendar_store: Some(calendar_store),
71            token_manager: Arc::new(GoogleOAuthTokenManager::new()),
72        })
73    }
74
75    fn enabled(&self) -> bool {
76        self.config.is_some() && self.store.is_some() && self.calendar_store.is_some()
77    }
78
79    /// Compose the trusted Google Calendar tool runtime from the same stores
80    /// used by the authenticated OAuth and calendar-management endpoints.
81    pub fn calendar_runtime(
82        &self,
83        families: Arc<FamilyService>,
84    ) -> Option<GoogleCalendarRuntimeConfig> {
85        let oauth = self.config.clone()?;
86        let connections = self.store.clone()?;
87        let calendars = self.calendar_store.clone()?;
88        let access = Arc::new(GoogleCalendarAccessService::new(
89            Arc::new(calendars),
90            Arc::new(connections),
91            families,
92        ));
93        Some(GoogleCalendarRuntimeConfig::new(
94            oauth,
95            access,
96            self.token_manager.clone(),
97        ))
98    }
99}
100
101fn parse_encryption_key(value: &str) -> Result<[u8; 32], String> {
102    if value.len() != 64 || !value.is_ascii() {
103        return Err(
104            "EME_CREDENTIAL_ENCRYPTION_KEY must contain exactly 64 hexadecimal characters"
105                .to_owned(),
106        );
107    }
108    let mut key = [0_u8; 32];
109    for (index, byte) in key.iter_mut().enumerate() {
110        let start = index * 2;
111        *byte = u8::from_str_radix(&value[start..start + 2], 16)
112            .map_err(|_| "EME_CREDENTIAL_ENCRYPTION_KEY must be hexadecimal".to_owned())?;
113    }
114    Ok(key)
115}
116
117fn current_user_id(
118    request: &HttpRequest,
119    auth: &crate::auth::TelegramAuth,
120    identities: &FileUserIdentityStore,
121) -> Result<UserId, HttpResponse> {
122    let owner = auth
123        .owner_for_request(request)
124        .ok_or_else(|| HttpResponse::Unauthorized().finish())?;
125    let subject = owner
126        .strip_prefix("telegram:")
127        .filter(|value| !value.is_empty())
128        .ok_or_else(|| HttpResponse::Unauthorized().finish())?;
129    let identity = identities
130        .find_identity("telegram", subject)
131        .map_err(|_| HttpResponse::InternalServerError().finish())?
132        .ok_or_else(|| HttpResponse::Unauthorized().finish())?;
133    Ok(identity.user_id)
134}
135
136#[derive(Clone, Copy, Deserialize)]
137#[serde(rename_all = "snake_case")]
138enum RequestedAccess {
139    ReadOnly,
140    ReadWrite,
141}
142
143impl From<RequestedAccess> for CalendarScope {
144    fn from(value: RequestedAccess) -> Self {
145        match value {
146            RequestedAccess::ReadOnly => Self::ReadOnly,
147            RequestedAccess::ReadWrite => Self::ReadWrite,
148        }
149    }
150}
151
152#[derive(Deserialize)]
153struct StartGoogleOAuthRequest {
154    access: RequestedAccess,
155}
156
157#[derive(Serialize)]
158struct StartGoogleOAuthResponse {
159    authorization_url: String,
160    expires_in_seconds: u64,
161}
162
163#[post("/oauth/start")]
164async fn start_oauth(
165    request: HttpRequest,
166    auth: Data<crate::auth::TelegramAuth>,
167    identities: Data<Arc<FileUserIdentityStore>>,
168    state: Data<GoogleOAuthState>,
169    body: Json<StartGoogleOAuthRequest>,
170) -> impl Responder {
171    if !state.enabled() {
172        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
173    }
174    let user_id = match current_user_id(&request, &auth, &identities) {
175        Ok(id) => id,
176        Err(response) => return response,
177    };
178    let config = state
179        .config
180        .as_ref()
181        .expect("enabled state has OAuth config");
182    let store = state.store.as_ref().expect("enabled state has storage");
183    let access: CalendarScope = body.access.into();
184    let requested_scopes = match access {
185        CalendarScope::ReadOnly => vec![
186            "https://www.googleapis.com/auth/calendar.calendarlist.readonly".to_owned(),
187            "https://www.googleapis.com/auth/calendar.events.readonly".to_owned(),
188            "openid".to_owned(),
189            "email".to_owned(),
190        ],
191        CalendarScope::ReadWrite => vec![
192            "https://www.googleapis.com/auth/calendar.calendarlist.readonly".to_owned(),
193            "https://www.googleapis.com/auth/calendar.events".to_owned(),
194            "openid".to_owned(),
195            "email".to_owned(),
196        ],
197    };
198    let pending = match authorization_request(config, access) {
199        Ok(value) => value,
200        Err(error) => {
201            tracing::error!(%error, "could not create Google OAuth request");
202            return HttpResponse::BadGateway().finish();
203        }
204    };
205    let expires_at = Utc::now() + Duration::minutes(AUTHORIZATION_TTL_MINUTES);
206    if let Err(error) = store
207        .begin_authorization(NewExternalAuthorization {
208            user_id,
209            provider: "google".to_owned(),
210            state: pending.state,
211            pkce_verifier: pending.pkce_verifier,
212            requested_scopes,
213            expires_at,
214        })
215        .await
216    {
217        tracing::error!(%error, "could not persist Google OAuth state");
218        return HttpResponse::InternalServerError().finish();
219    }
220    HttpResponse::Created().json(StartGoogleOAuthResponse {
221        authorization_url: pending.authorization_url.to_string(),
222        expires_in_seconds: (AUTHORIZATION_TTL_MINUTES * 60) as u64,
223    })
224}
225
226#[derive(Deserialize)]
227struct GoogleOAuthCallback {
228    code: Option<String>,
229    state: String,
230    error: Option<String>,
231}
232
233#[derive(Serialize)]
234struct ConnectedGoogleAccount {
235    id: ExternalConnectionId,
236    email: Option<String>,
237    scopes: Vec<String>,
238    status: ExternalConnectionStatus,
239    updated_at: chrono::DateTime<Utc>,
240}
241
242#[get("/oauth/callback")]
243async fn oauth_callback(
244    request: HttpRequest,
245    auth: Data<crate::auth::TelegramAuth>,
246    identities: Data<Arc<FileUserIdentityStore>>,
247    state: Data<GoogleOAuthState>,
248    query: Query<GoogleOAuthCallback>,
249) -> impl Responder {
250    if !state.enabled() {
251        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
252    }
253    let user_id = match current_user_id(&request, &auth, &identities) {
254        Ok(id) => id,
255        Err(response) => return response,
256    };
257    let store = state.store.as_ref().expect("enabled state has storage");
258    let consumed = match store
259        .consume_authorization("google", &query.state, Utc::now())
260        .await
261    {
262        Ok(value) => value,
263        Err(error) => {
264            tracing::warn!(%error, "rejected Google OAuth callback state");
265            return HttpResponse::BadRequest().body("Invalid or expired OAuth state");
266        }
267    };
268    if consumed.user_id != user_id {
269        return HttpResponse::Forbidden().body("OAuth authorization belongs to another user");
270    }
271    if query.error.is_some() {
272        return HttpResponse::BadRequest().body("Google authorization was not completed");
273    }
274    let Some(code) = query.code.as_ref().filter(|value| !value.is_empty()) else {
275        return HttpResponse::BadRequest().body("Google did not return an authorization code");
276    };
277    let config = state
278        .config
279        .as_ref()
280        .expect("enabled state has OAuth config");
281    let tokens = match exchange_code(config, code.clone(), consumed.pkce_verifier).await {
282        Ok(tokens) => tokens,
283        Err(error) => {
284            tracing::warn!(%error, "Google OAuth code exchange failed");
285            return HttpResponse::BadGateway().body("Google token exchange failed");
286        }
287    };
288    let identity = match fetch_user_info(&tokens.access_token).await {
289        Ok(identity) if identity.email_verified && !identity.sub.is_empty() => identity,
290        Ok(_) => return HttpResponse::BadRequest().body("Google account identity is not verified"),
291        Err(error) => {
292            tracing::warn!(%error, "Google account identity verification failed");
293            return HttpResponse::BadGateway().body("Could not verify Google account identity");
294        }
295    };
296    let existing = match store.list_connections(user_id).await {
297        Ok(connections) => connections.into_iter().find(|connection| {
298            connection.provider == "google" && connection.provider_subject == identity.sub
299        }),
300        Err(error) => {
301            tracing::error!(%error, "could not look up existing Google connection");
302            return HttpResponse::InternalServerError().finish();
303        }
304    };
305    // Google may omit a refresh token on subsequent consent grants. Reuse the
306    // encrypted token only for this same verified provider subject.
307    let refresh_token = match tokens.refresh_token.clone() {
308        Some(token) => token,
309        None => {
310            let Some(existing) = existing
311                .as_ref()
312                .filter(|connection| connection.status == ExternalConnectionStatus::Active)
313            else {
314                return HttpResponse::Conflict()
315                    .body("Google did not issue a refresh token for this new account");
316            };
317            match store.refresh_token(user_id, existing.id).await {
318                Ok(token) => token,
319                Err(error) => {
320                    tracing::error!(%error, "could not recover existing Google refresh token");
321                    return HttpResponse::InternalServerError().finish();
322                }
323            }
324        }
325    };
326    let audit_action = if existing.is_some() {
327        "reauthorize"
328    } else {
329        "connect"
330    };
331    let granted_scope_count = tokens.scopes.len();
332    let connection = match store
333        .create_connection(NewExternalConnection {
334            owner_id: user_id,
335            provider: "google".to_owned(),
336            provider_subject: identity.sub.clone(),
337            display_email: Some(identity.email.clone()),
338            refresh_token,
339            granted_scopes: tokens.scopes.clone(),
340        })
341        .await
342    {
343        Ok(connection) => connection,
344        Err(agent_storage::ExternalConnectionStorageError::AlreadyExists) => {
345            let Some(existing) = existing else {
346                return HttpResponse::Conflict().body("This Google account is already connected");
347            };
348            match store
349                .update_credentials(user_id, existing.id, tokens.refresh_token, tokens.scopes)
350                .await
351            {
352                Ok(connection) => connection,
353                Err(error) => {
354                    tracing::error!(%error, "could not update existing Google connection");
355                    return HttpResponse::InternalServerError().finish();
356                }
357            }
358        }
359        Err(error) => {
360            tracing::error!(%error, "could not persist Google account connection");
361            return HttpResponse::InternalServerError().finish();
362        }
363    };
364    state.token_manager.invalidate(connection.id).await;
365    tracing::info!(audit_event = "google_connection_authorized", action = audit_action, user_id = %user_id, connection_id = %connection.id, granted_scope_count, "Google account connection authorized");
366    HttpResponse::Ok()
367        .content_type("text/html; charset=utf-8")
368        .body(
369            r#"<!doctype html>
370<html lang="en">
371<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Google Calendar connected</title></head>
372<body>
373<p>Google Calendar connected. This window should close automatically.</p>
374<script>
375if (window.opener) {
376  window.opener.postMessage({ type: "eme-google-oauth", status: "success" }, window.location.origin);
377  window.close();
378}
379</script>
380</body>
381</html>"#,
382        )
383}
384
385#[get("/connections")]
386async fn list_connections(
387    request: HttpRequest,
388    auth: Data<crate::auth::TelegramAuth>,
389    identities: Data<Arc<FileUserIdentityStore>>,
390    state: Data<GoogleOAuthState>,
391) -> impl Responder {
392    if !state.enabled() {
393        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
394    }
395    let user_id = match current_user_id(&request, &auth, &identities) {
396        Ok(id) => id,
397        Err(response) => return response,
398    };
399    match state
400        .store
401        .as_ref()
402        .expect("enabled state has storage")
403        .list_connections(user_id)
404        .await
405    {
406        Ok(connections) => HttpResponse::Ok().json(
407            connections
408                .into_iter()
409                .map(|connection| ConnectedGoogleAccount {
410                    id: connection.id,
411                    email: connection.display_email,
412                    scopes: connection.granted_scopes,
413                    status: connection.status,
414                    updated_at: connection.updated_at,
415                })
416                .collect::<Vec<_>>(),
417        ),
418        Err(error) => {
419            tracing::error!(%error, "could not list Google account connections");
420            HttpResponse::InternalServerError().finish()
421        }
422    }
423}
424
425#[delete("/connections/{connection_id}")]
426async fn disconnect(
427    request: HttpRequest,
428    auth: Data<crate::auth::TelegramAuth>,
429    identities: Data<Arc<FileUserIdentityStore>>,
430    state: Data<GoogleOAuthState>,
431    connection_id: PathParam<String>,
432) -> impl Responder {
433    if !state.enabled() {
434        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
435    }
436    let user_id = match current_user_id(&request, &auth, &identities) {
437        Ok(id) => id,
438        Err(response) => return response,
439    };
440    let id = match ExternalConnectionId::from_str(&connection_id) {
441        Ok(id) => id,
442        Err(_) => return HttpResponse::BadRequest().body("Invalid connection ID"),
443    };
444    let store = state.store.as_ref().expect("enabled state has storage");
445    match store.get_connection(user_id, id).await {
446        Ok(Some(connection)) if connection.status == ExternalConnectionStatus::Active => {}
447        Ok(_) => return HttpResponse::NotFound().finish(),
448        Err(error) => {
449            tracing::error!(%error, "could not inspect Google connection before disconnect");
450            return HttpResponse::InternalServerError().finish();
451        }
452    }
453    let refresh_token = match store.refresh_token(user_id, id).await {
454        Ok(token) => token,
455        Err(agent_storage::ExternalConnectionStorageError::NotFound) => {
456            return HttpResponse::NotFound().finish();
457        }
458        Err(error) => {
459            tracing::error!(%error, "could not load Google credential for revocation");
460            return HttpResponse::InternalServerError().finish();
461        }
462    };
463    if let Err(error) = store.revoke_connection(user_id, id).await {
464        tracing::error!(%error, "could not revoke local Google connection");
465        return HttpResponse::InternalServerError().finish();
466    }
467    state.token_manager.invalidate(id).await;
468    tracing::info!(audit_event = "google_connection_disconnected", user_id = %user_id, connection_id = %id, "Google account connection disconnected");
469    // Local access is disabled first and remains disabled even if Google's
470    // revocation endpoint is temporarily unavailable.
471    if let Err(error) = google_tool::revoke_token(&refresh_token).await {
472        tracing::warn!(%error, "local Google connection revoked, but provider token revocation failed");
473    }
474    HttpResponse::NoContent().finish()
475}
476
477#[derive(Serialize)]
478struct ConnectedCalendarResponse {
479    id: ConnectedCalendarId,
480    display_name: Option<String>,
481    time_zone: Option<String>,
482    provider_access_role: Option<String>,
483    selected: bool,
484    access_mode: CalendarAccessMode,
485    family_id: Option<FamilyId>,
486    family_access: Option<CalendarFamilyAccess>,
487}
488
489impl From<agent_storage::ConnectedCalendar> for ConnectedCalendarResponse {
490    fn from(calendar: agent_storage::ConnectedCalendar) -> Self {
491        Self {
492            id: calendar.id,
493            display_name: calendar.display_name,
494            time_zone: calendar.time_zone,
495            provider_access_role: calendar.provider_access_role,
496            selected: calendar.selected,
497            access_mode: calendar.access_mode,
498            family_id: calendar.family_id,
499            family_access: calendar.family_access,
500        }
501    }
502}
503
504fn calendar_storage_error(error: ConnectedCalendarStorageError) -> HttpResponse {
505    match error {
506        ConnectedCalendarStorageError::ConnectionNotFound
507        | ConnectedCalendarStorageError::CalendarNotFound => HttpResponse::NotFound().finish(),
508        ConnectedCalendarStorageError::InsufficientScopes => HttpResponse::Conflict()
509            .body("The connected Google account has not granted calendar write access"),
510        ConnectedCalendarStorageError::EmptyProviderCalendarId => {
511            HttpResponse::BadRequest().finish()
512        }
513        ConnectedCalendarStorageError::FamilyShareRequiresSelected => {
514            HttpResponse::Conflict().body("Select the calendar before sharing it")
515        }
516        ConnectedCalendarStorageError::FamilyWriteRequiresOwnerWrite => {
517            HttpResponse::Conflict().body("Contributor sharing requires owner read/write access")
518        }
519        ConnectedCalendarStorageError::Backend(error) => {
520            tracing::error!(%error, "connected calendar storage failed");
521            HttpResponse::InternalServerError().finish()
522        }
523    }
524}
525
526#[get("/connections/{connection_id}/calendars")]
527async fn list_connected_calendars(
528    request: HttpRequest,
529    auth: Data<crate::auth::TelegramAuth>,
530    identities: Data<Arc<FileUserIdentityStore>>,
531    state: Data<GoogleOAuthState>,
532    connection_id: PathParam<String>,
533) -> impl Responder {
534    if !state.enabled() {
535        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
536    }
537    let owner = match current_user_id(&request, &auth, &identities) {
538        Ok(id) => id,
539        Err(response) => return response,
540    };
541    let connection_id = match ExternalConnectionId::from_str(&connection_id) {
542        Ok(id) => id,
543        Err(_) => return HttpResponse::BadRequest().body("Invalid connection ID"),
544    };
545    let calendars = state
546        .calendar_store
547        .as_ref()
548        .expect("enabled state has calendar storage")
549        .list_for_connection(owner, connection_id)
550        .await;
551    match calendars {
552        Ok(calendars) => HttpResponse::Ok().json(
553            calendars
554                .into_iter()
555                .map(ConnectedCalendarResponse::from)
556                .collect::<Vec<_>>(),
557        ),
558        Err(error) => calendar_storage_error(error),
559    }
560}
561
562#[post("/connections/{connection_id}/calendars/sync")]
563async fn sync_connected_calendars(
564    request: HttpRequest,
565    auth: Data<crate::auth::TelegramAuth>,
566    identities: Data<Arc<FileUserIdentityStore>>,
567    state: Data<GoogleOAuthState>,
568    connection_id: PathParam<String>,
569) -> impl Responder {
570    if !state.enabled() {
571        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
572    }
573    let owner = match current_user_id(&request, &auth, &identities) {
574        Ok(id) => id,
575        Err(response) => return response,
576    };
577    let connection_id = match ExternalConnectionId::from_str(&connection_id) {
578        Ok(id) => id,
579        Err(_) => return HttpResponse::BadRequest().body("Invalid connection ID"),
580    };
581    let store = state
582        .store
583        .as_ref()
584        .expect("enabled state has connection storage");
585    let connection = match store.get_connection(owner, connection_id).await {
586        Ok(Some(connection))
587            if connection.provider == "google"
588                && connection.status == ExternalConnectionStatus::Active =>
589        {
590            connection
591        }
592        Ok(_) => return HttpResponse::NotFound().finish(),
593        Err(error) => {
594            tracing::error!(%error, "could not inspect Google connection for calendar sync");
595            return HttpResponse::InternalServerError().finish();
596        }
597    };
598    let refresh_token = match store.refresh_token(owner, connection_id).await {
599        Ok(token) => token,
600        Err(error) => {
601            tracing::error!(%error, "could not load Google credential for calendar sync");
602            return HttpResponse::InternalServerError().finish();
603        }
604    };
605    let config = state
606        .config
607        .as_ref()
608        .expect("enabled state has OAuth config");
609    let token = match state
610        .token_manager
611        .refresh_access_token(connection_id, config, &refresh_token)
612        .await
613    {
614        Ok(token) => token,
615        Err(error) => {
616            tracing::warn!(%error, connection_id = %connection.id, "Google Calendar token refresh failed during discovery");
617            return HttpResponse::BadGateway().body("Google Calendar token refresh failed");
618        }
619    };
620    let discovered = match list_calendars_with_access_token(&token).await {
621        Ok(calendars) => calendars
622            .into_iter()
623            .map(|calendar| DiscoveredCalendar {
624                provider_calendar_id: calendar.id,
625                display_name: calendar.summary,
626                time_zone: calendar.time_zone,
627                provider_access_role: calendar.access_role,
628            })
629            .collect(),
630        Err(error) => {
631            tracing::warn!(%error, connection_id = %connection.id, "Google Calendar discovery failed");
632            return HttpResponse::BadGateway().body("Google Calendar discovery failed");
633        }
634    };
635    let calendars = state
636        .calendar_store
637        .as_ref()
638        .expect("enabled state has calendar storage")
639        .sync_discovered(owner, connection_id, discovered)
640        .await;
641    match calendars {
642        Ok(calendars) => {
643            tracing::info!(audit_event = "google_calendars_synchronized", user_id = %owner, connection_id = %connection_id, calendar_count = calendars.len(), "Google calendars synchronized");
644            HttpResponse::Ok().json(
645                calendars
646                    .into_iter()
647                    .map(ConnectedCalendarResponse::from)
648                    .collect::<Vec<_>>(),
649            )
650        }
651        Err(error) => calendar_storage_error(error),
652    }
653}
654
655#[derive(Deserialize)]
656struct UpdateConnectedCalendarRequest {
657    selected: Option<bool>,
658    access_mode: Option<CalendarAccessMode>,
659}
660
661#[actix_web::patch("/calendars/{calendar_id}")]
662async fn update_connected_calendar(
663    request: HttpRequest,
664    auth: Data<crate::auth::TelegramAuth>,
665    identities: Data<Arc<FileUserIdentityStore>>,
666    state: Data<GoogleOAuthState>,
667    calendar_id: PathParam<String>,
668    body: Json<UpdateConnectedCalendarRequest>,
669) -> impl Responder {
670    if !state.enabled() {
671        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
672    }
673    if body.selected.is_none() && body.access_mode.is_none() {
674        return HttpResponse::BadRequest().body("At least one calendar setting must be supplied");
675    }
676    let owner = match current_user_id(&request, &auth, &identities) {
677        Ok(id) => id,
678        Err(response) => return response,
679    };
680    let calendar_id = match ConnectedCalendarId::from_str(&calendar_id) {
681        Ok(id) => id,
682        Err(_) => return HttpResponse::BadRequest().body("Invalid calendar ID"),
683    };
684    let calendar = state
685        .calendar_store
686        .as_ref()
687        .expect("enabled state has calendar storage")
688        .update(owner, calendar_id, body.selected, body.access_mode)
689        .await;
690    match calendar {
691        Ok(calendar) => {
692            tracing::info!(audit_event = "google_calendar_permissions_updated", user_id = %owner, calendar_id = %calendar.id, selected = calendar.selected, access_mode = ?calendar.access_mode, "Google Calendar permissions updated");
693            HttpResponse::Ok().json(ConnectedCalendarResponse::from(calendar))
694        }
695        Err(error) => calendar_storage_error(error),
696    }
697}
698
699#[derive(Deserialize)]
700struct ShareCalendarWithFamilyRequest {
701    family_id: String,
702    access: CalendarFamilyAccess,
703}
704
705fn family_sharing_error(error: FamilyServiceError) -> HttpResponse {
706    match error {
707        FamilyServiceError::NotFound | FamilyServiceError::NotMember => {
708            HttpResponse::NotFound().finish()
709        }
710        FamilyServiceError::Forbidden => HttpResponse::Forbidden().finish(),
711        other => {
712            tracing::error!(%other, "could not validate family membership for calendar sharing");
713            HttpResponse::InternalServerError().finish()
714        }
715    }
716}
717
718#[actix_web::put("/calendars/{calendar_id}/family-sharing")]
719async fn share_calendar_with_family(
720    request: HttpRequest,
721    auth: Data<crate::auth::TelegramAuth>,
722    identities: Data<Arc<FileUserIdentityStore>>,
723    state: Data<GoogleOAuthState>,
724    families: Data<Arc<FamilyService>>,
725    calendar_id: PathParam<String>,
726    body: Json<ShareCalendarWithFamilyRequest>,
727) -> impl Responder {
728    if !state.enabled() {
729        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
730    }
731    let owner = match current_user_id(&request, &auth, &identities) {
732        Ok(id) => id,
733        Err(response) => return response,
734    };
735    let calendar_id = match ConnectedCalendarId::from_str(&calendar_id) {
736        Ok(id) => id,
737        Err(_) => return HttpResponse::BadRequest().body("Invalid calendar ID"),
738    };
739    let family_id = match FamilyId::from_str(&body.family_id) {
740        Ok(id) => id,
741        Err(_) => return HttpResponse::BadRequest().body("Invalid family ID"),
742    };
743    // Sharing can only be configured with a family the calendar owner currently belongs to.
744    if let Err(error) = families.context_for_member(owner, family_id).await {
745        return family_sharing_error(error);
746    }
747    let calendar = state
748        .calendar_store
749        .as_ref()
750        .expect("enabled state has calendar storage")
751        .share_with_family(owner, calendar_id, family_id, body.access)
752        .await;
753    match calendar {
754        Ok(calendar) => {
755            tracing::info!(audit_event = "google_calendar_shared_with_family", user_id = %owner, calendar_id = %calendar.id, family_id = %family_id, access = ?body.access, "Google Calendar family sharing updated");
756            HttpResponse::Ok().json(ConnectedCalendarResponse::from(calendar))
757        }
758        Err(error) => calendar_storage_error(error),
759    }
760}
761
762#[actix_web::delete("/calendars/{calendar_id}/family-sharing")]
763async fn unshare_calendar_from_family(
764    request: HttpRequest,
765    auth: Data<crate::auth::TelegramAuth>,
766    identities: Data<Arc<FileUserIdentityStore>>,
767    state: Data<GoogleOAuthState>,
768    calendar_id: PathParam<String>,
769) -> impl Responder {
770    if !state.enabled() {
771        return HttpResponse::ServiceUnavailable().body("Google OAuth is not configured");
772    }
773    let owner = match current_user_id(&request, &auth, &identities) {
774        Ok(id) => id,
775        Err(response) => return response,
776    };
777    let calendar_id = match ConnectedCalendarId::from_str(&calendar_id) {
778        Ok(id) => id,
779        Err(_) => return HttpResponse::BadRequest().body("Invalid calendar ID"),
780    };
781    let calendar_store = state
782        .calendar_store
783        .as_ref()
784        .expect("enabled state has calendar storage");
785    let previous_family_id = match calendar_store.get_selected(calendar_id).await {
786        Ok(Some(calendar)) => calendar.family_id,
787        Ok(None) => None,
788        Err(error) => return calendar_storage_error(error),
789    };
790    let calendar = calendar_store.unshare_from_family(owner, calendar_id).await;
791    match calendar {
792        Ok(calendar) => {
793            tracing::info!(audit_event = "google_calendar_unshared_from_family", user_id = %owner, calendar_id = %calendar.id, family_id = ?previous_family_id, "Google Calendar family sharing removed");
794            HttpResponse::Ok().json(ConnectedCalendarResponse::from(calendar))
795        }
796        Err(error) => calendar_storage_error(error),
797    }
798}
799
800pub fn google_integrations_api() -> Scope {
801    web::scope("/integrations/google")
802        .service(start_oauth)
803        .service(oauth_callback)
804        .service(list_connections)
805        .service(disconnect)
806        .service(list_connected_calendars)
807        .service(sync_connected_calendars)
808        .service(update_connected_calendar)
809        .service(share_calendar_with_family)
810        .service(unshare_calendar_from_family)
811}
812
813#[cfg(test)]
814mod tests {
815    use super::parse_encryption_key;
816
817    #[test]
818    fn parses_exactly_32_bytes_of_hex_key_material() {
819        assert_eq!(parse_encryption_key(&"ab".repeat(32)).unwrap(), [0xab; 32]);
820        assert!(parse_encryption_key("abcd").is_err());
821        assert!(parse_encryption_key(&"xz".repeat(32)).is_err());
822    }
823}