Skip to main content

media_tools/providers/
trakt_oauth.rs

1//! Trakt OAuth account linking and refresh-token lifecycle.
2use std::{
3    collections::HashMap,
4    sync::Arc,
5    time::{Duration, Instant},
6};
7
8use agent_storage::{
9    ExternalConnectionId, ExternalConnectionStatus, ExternalConnectionStore, FamilyId, FamilyRole,
10    FamilyStore, NewExternalAuthorization, NewExternalConnection, UserId,
11};
12use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
13use chrono::{DateTime, Duration as ChronoDuration, Utc};
14use reqwest::{Client, StatusCode};
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17use tokio::sync::Mutex;
18use url::Url;
19use uuid::Uuid;
20
21use crate::{
22    MediaExternalConnectionLink, MediaProfileId, MediaStore, MediaStoreError, PendingTraktLink,
23};
24
25const DEFAULT_AUTHORIZE_URL: &str = "https://auth.trakt.tv/oauth/authorize";
26const DEFAULT_TOKEN_URL: &str = "https://api.trakt.tv/oauth/token";
27const DEFAULT_API_BASE_URL: &str = "https://api.trakt.tv";
28
29/// OAuth application credentials and Trakt API endpoints.
30#[derive(Clone)]
31pub struct TraktOAuthConfig {
32    pub client_id: String,
33    pub redirect_uri: String,
34    pub authorize_url: String,
35    pub token_url: String,
36    pub api_base_url: String,
37}
38
39impl TraktOAuthConfig {
40    pub fn new(
41        client_id: impl Into<String>,
42        redirect_uri: impl Into<String>,
43    ) -> Result<Self, TraktError> {
44        Self::with_endpoints(
45            client_id,
46            redirect_uri,
47            DEFAULT_AUTHORIZE_URL,
48            DEFAULT_TOKEN_URL,
49            DEFAULT_API_BASE_URL,
50        )
51    }
52
53    /// Custom endpoints allow deterministic OAuth tests without contacting Trakt.
54    pub fn with_endpoints(
55        client_id: impl Into<String>,
56        redirect_uri: impl Into<String>,
57        authorize_url: impl Into<String>,
58        token_url: impl Into<String>,
59        api_base_url: impl Into<String>,
60    ) -> Result<Self, TraktError> {
61        let config = Self {
62            client_id: client_id.into(),
63            redirect_uri: redirect_uri.into(),
64            authorize_url: authorize_url.into(),
65            token_url: token_url.into(),
66            api_base_url: api_base_url.into().trim_end_matches('/').to_owned(),
67        };
68        if config.client_id.trim().is_empty() || config.redirect_uri.trim().is_empty() {
69            return Err(TraktError::Configuration(
70                "client ID and redirect URI are required".into(),
71            ));
72        }
73        Url::parse(&config.redirect_uri)
74            .map_err(|error| TraktError::Configuration(error.to_string()))?;
75        Url::parse(&config.authorize_url)
76            .map_err(|error| TraktError::Configuration(error.to_string()))?;
77        Url::parse(&config.token_url)
78            .map_err(|error| TraktError::Configuration(error.to_string()))?;
79        Url::parse(&config.api_base_url)
80            .map_err(|error| TraktError::Configuration(error.to_string()))?;
81        Ok(config)
82    }
83}
84
85/// URL and expiry for a pending Trakt consent flow.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct TraktAuthorization {
88    pub authorization_url: String,
89    pub expires_at: DateTime<Utc>,
90}
91
92/// A Trakt OAuth account-linking and credential service.
93pub struct TraktOAuthService {
94    config: TraktOAuthConfig,
95    http: Client,
96    media: MediaStore,
97    families: Arc<dyn FamilyStore>,
98    external_connections: Arc<dyn ExternalConnectionStore>,
99    token_manager: TraktTokenManager,
100}
101
102impl TraktOAuthService {
103    pub fn new(
104        config: TraktOAuthConfig,
105        media: MediaStore,
106        families: Arc<dyn FamilyStore>,
107        external_connections: Arc<dyn ExternalConnectionStore>,
108    ) -> Result<Self, TraktError> {
109        let http = http_client()?;
110        let token_manager = TraktTokenManager::new(config.clone(), external_connections.clone())?;
111        Ok(Self {
112            config,
113            http,
114            media,
115            families,
116            external_connections,
117            token_manager,
118        })
119    }
120
121    /// Begin linking a Trakt account to a media profile.
122    ///
123    /// Only the EME user assigned to the media profile can attach their own
124    /// external account. The pending state is hashed and consumed once.
125    pub async fn begin_link(
126        &self,
127        owner_id: UserId,
128        family_id: FamilyId,
129        profile_id: MediaProfileId,
130    ) -> Result<TraktAuthorization, TraktError> {
131        self.require_profile_owner(owner_id, family_id, profile_id)
132            .await?;
133        let state = Uuid::new_v4().to_string();
134        let (pkce_verifier, code_challenge) = pkce_pair();
135        let expires_at = Utc::now() + ChronoDuration::minutes(10);
136        self.media
137            .create_pending_trakt_link(
138                &state,
139                &PendingTraktLink {
140                    owner_id,
141                    family_id: Some(family_id),
142                    profile_id,
143                },
144                expires_at,
145            )
146            .await
147            .map_err(TraktError::MediaStorage)?;
148        self.external_connections
149            .begin_authorization(NewExternalAuthorization {
150                user_id: owner_id,
151                provider: "trakt".into(),
152                state: state.clone(),
153                pkce_verifier,
154                requested_scopes: Vec::new(),
155                expires_at,
156            })
157            .await
158            .map_err(TraktError::ExternalStorage)?;
159
160        let mut url = Url::parse(&self.config.authorize_url)
161            .map_err(|error| TraktError::Configuration(error.to_string()))?;
162        url.query_pairs_mut()
163            .append_pair("response_type", "code")
164            .append_pair("client_id", &self.config.client_id)
165            .append_pair("redirect_uri", &self.config.redirect_uri)
166            .append_pair("code_challenge", &code_challenge)
167            .append_pair("code_challenge_method", "S256")
168            .append_pair("state", &state);
169        Ok(TraktAuthorization {
170            authorization_url: url.into(),
171            expires_at,
172        })
173    }
174
175    /// Start OAuth for a personal profile without requiring a family membership.
176    pub async fn begin_personal_link(
177        &self,
178        owner_id: UserId,
179        profile_id: MediaProfileId,
180    ) -> Result<TraktAuthorization, TraktError> {
181        self.require_personal_profile_owner(owner_id, profile_id)
182            .await?;
183        let state = Uuid::new_v4().to_string();
184        let (pkce_verifier, code_challenge) = pkce_pair();
185        let expires_at = Utc::now() + ChronoDuration::minutes(10);
186        self.media
187            .create_pending_trakt_link(
188                &state,
189                &PendingTraktLink {
190                    owner_id,
191                    family_id: None,
192                    profile_id,
193                },
194                expires_at,
195            )
196            .await
197            .map_err(TraktError::MediaStorage)?;
198        self.external_connections
199            .begin_authorization(NewExternalAuthorization {
200                user_id: owner_id,
201                provider: "trakt".into(),
202                state: state.clone(),
203                pkce_verifier,
204                requested_scopes: Vec::new(),
205                expires_at,
206            })
207            .await
208            .map_err(TraktError::ExternalStorage)?;
209        let mut url = Url::parse(&self.config.authorize_url)
210            .map_err(|error| TraktError::Configuration(error.to_string()))?;
211        url.query_pairs_mut()
212            .append_pair("response_type", "code")
213            .append_pair("client_id", &self.config.client_id)
214            .append_pair("redirect_uri", &self.config.redirect_uri)
215            .append_pair("code_challenge", &code_challenge)
216            .append_pair("code_challenge_method", "S256")
217            .append_pair("state", &state);
218        Ok(TraktAuthorization {
219            authorization_url: url.into(),
220            expires_at,
221        })
222    }
223
224    /// Complete a callback, validate its one-time state, and persist the encrypted refresh token.
225    pub async fn complete_link(
226        &self,
227        expected_owner_id: UserId,
228        state: &str,
229        code: &str,
230    ) -> Result<MediaExternalConnectionLink, TraktError> {
231        if code.trim().is_empty() {
232            return Err(TraktError::InvalidResponse(
233                "authorization code must not be empty".into(),
234            ));
235        }
236        let pending = self
237            .media
238            .get_pending_trakt_link(state)
239            .await
240            .map_err(TraktError::MediaStorage)?;
241        if pending.owner_id != expected_owner_id {
242            return Err(TraktError::Forbidden);
243        }
244        let pending = self
245            .media
246            .consume_pending_trakt_link(state, Utc::now())
247            .await
248            .map_err(TraktError::MediaStorage)?;
249        let authorization = self
250            .external_connections
251            .consume_authorization("trakt", state, Utc::now())
252            .await
253            .map_err(TraktError::ExternalStorage)?;
254        if authorization.user_id != pending.owner_id {
255            return Err(TraktError::Forbidden);
256        }
257        if let Some(family_id) = pending.family_id {
258            self.require_profile_owner(pending.owner_id, family_id, pending.profile_id)
259                .await?;
260        } else {
261            self.require_personal_profile_owner(pending.owner_id, pending.profile_id)
262                .await?;
263        }
264
265        let tokens = self
266            .exchange_code(code, &authorization.pkce_verifier)
267            .await?;
268        let refresh_token = tokens
269            .refresh_token
270            .clone()
271            .filter(|token| !token.is_empty())
272            .ok_or(TraktError::MissingRefreshToken)?;
273        let user = self.fetch_user_settings(&tokens.access_token).await?;
274        let connection = self
275            .external_connections
276            .create_connection(NewExternalConnection {
277                owner_id: pending.owner_id,
278                provider: "trakt".into(),
279                provider_subject: user.username.clone(),
280                display_email: None,
281                refresh_token,
282                granted_scopes: if tokens.scopes().is_empty() {
283                    authorization.requested_scopes
284                } else {
285                    tokens.scopes()
286                },
287            })
288            .await
289            .map_err(TraktError::ExternalStorage)?;
290
291        let previous_link = self
292            .media
293            .get_external_connection_link(pending.profile_id, "trakt")
294            .await
295            .map_err(TraktError::MediaStorage)?;
296        let link = MediaExternalConnectionLink {
297            owner_id: pending.owner_id,
298            family_id: pending.family_id,
299            profile_id: pending.profile_id,
300            provider: "trakt".into(),
301            external_connection_id: connection.id,
302            provider_subject: user.username,
303            display_name: user.name,
304            linked_at: Utc::now(),
305        };
306        self.media
307            .save_external_connection_link(&link)
308            .await
309            .map_err(TraktError::MediaStorage)?;
310        if let Some(previous) = previous_link
311            && previous.external_connection_id != link.external_connection_id
312        {
313            self.external_connections
314                .revoke_connection(previous.owner_id, previous.external_connection_id)
315                .await
316                .map_err(TraktError::ExternalStorage)?;
317            self.token_manager
318                .invalidate(previous.external_connection_id)
319                .await;
320        }
321        Ok(link)
322    }
323
324    /// Remove a profile link and revoke its encrypted external credential.
325    pub async fn unlink_profile(
326        &self,
327        actor_id: UserId,
328        family_id: FamilyId,
329        profile_id: MediaProfileId,
330    ) -> Result<(), TraktError> {
331        if self
332            .media
333            .get_profile(family_id, profile_id)
334            .await
335            .map_err(TraktError::MediaStorage)?
336            .is_none()
337        {
338            return Err(TraktError::Forbidden);
339        }
340        let link = self
341            .media
342            .get_external_connection_link(profile_id, "trakt")
343            .await
344            .map_err(TraktError::MediaStorage)?
345            .ok_or(TraktError::ConnectionUnavailable)?;
346        if link.owner_id != actor_id && !self.is_family_admin(actor_id, family_id).await? {
347            return Err(TraktError::Forbidden);
348        }
349        self.external_connections
350            .revoke_connection(link.owner_id, link.external_connection_id)
351            .await
352            .map_err(TraktError::ExternalStorage)?;
353        self.media
354            .delete_external_connection_link(profile_id, "trakt")
355            .await
356            .map_err(TraktError::MediaStorage)?;
357        self.token_manager
358            .invalidate(link.external_connection_id)
359            .await;
360        Ok(())
361    }
362
363    async fn is_family_admin(
364        &self,
365        user_id: UserId,
366        family_id: FamilyId,
367    ) -> Result<bool, TraktError> {
368        let families = self
369            .families
370            .list_families(user_id)
371            .await
372            .map_err(|error| TraktError::Family(error.to_string()))?;
373        if !families.iter().any(|family| family.id == family_id) {
374            return Ok(false);
375        }
376        let members = self
377            .families
378            .list_members(family_id)
379            .await
380            .map_err(|error| TraktError::Family(error.to_string()))?;
381        Ok(members.iter().any(|member| {
382            member.user_id == user_id
383                && matches!(member.role, FamilyRole::Owner | FamilyRole::Admin)
384        }))
385    }
386
387    /// Validate that the actor still owns the assigned profile and belongs to its family.
388    pub async fn validate_profile_owner(
389        &self,
390        user_id: UserId,
391        family_id: FamilyId,
392        profile_id: MediaProfileId,
393    ) -> Result<(), TraktError> {
394        let profile = self
395            .media
396            .get_profile(family_id, profile_id)
397            .await
398            .map_err(TraktError::MediaStorage)?
399            .ok_or(TraktError::Forbidden)?;
400        if profile.user_id != Some(user_id) {
401            return Err(TraktError::Forbidden);
402        }
403        let families = self
404            .families
405            .list_families(user_id)
406            .await
407            .map_err(|error| TraktError::Family(error.to_string()))?;
408        if !families.iter().any(|family| family.id == family_id) {
409            return Err(TraktError::Forbidden);
410        }
411        let members = self
412            .families
413            .list_members(family_id)
414            .await
415            .map_err(|error| TraktError::Family(error.to_string()))?;
416        if members.iter().any(|member| member.user_id == user_id) {
417            Ok(())
418        } else {
419            Err(TraktError::Forbidden)
420        }
421    }
422
423    /// Validate direct ownership of a personal profile.
424    pub async fn validate_personal_profile_owner(
425        &self,
426        user_id: UserId,
427        profile_id: MediaProfileId,
428    ) -> Result<(), TraktError> {
429        self.require_personal_profile_owner(user_id, profile_id)
430            .await
431    }
432
433    async fn require_personal_profile_owner(
434        &self,
435        owner_id: UserId,
436        profile_id: MediaProfileId,
437    ) -> Result<(), TraktError> {
438        self.media
439            .get_personal_profile(owner_id, profile_id)
440            .await
441            .map_err(TraktError::MediaStorage)?
442            .ok_or(TraktError::Forbidden)?;
443        Ok(())
444    }
445
446    /// Disconnect a Trakt account from the caller's own personal profile.
447    pub async fn unlink_personal_profile(
448        &self,
449        actor_id: UserId,
450        profile_id: MediaProfileId,
451    ) -> Result<(), TraktError> {
452        self.require_personal_profile_owner(actor_id, profile_id)
453            .await?;
454        let link = self
455            .media
456            .get_external_connection_link(profile_id, "trakt")
457            .await
458            .map_err(TraktError::MediaStorage)?
459            .ok_or(TraktError::ConnectionUnavailable)?;
460        if link.owner_id != actor_id {
461            return Err(TraktError::Forbidden);
462        }
463        self.external_connections
464            .revoke_connection(link.owner_id, link.external_connection_id)
465            .await
466            .map_err(TraktError::ExternalStorage)?;
467        self.media
468            .delete_external_connection_link(profile_id, "trakt")
469            .await
470            .map_err(TraktError::MediaStorage)?;
471        self.token_manager
472            .invalidate(link.external_connection_id)
473            .await;
474        Ok(())
475    }
476
477    /// Access-token manager used by Trakt history and rating synchronization.
478    pub fn token_manager(&self) -> &TraktTokenManager {
479        &self.token_manager
480    }
481
482    async fn require_profile_owner(
483        &self,
484        owner_id: UserId,
485        family_id: FamilyId,
486        profile_id: MediaProfileId,
487    ) -> Result<(), TraktError> {
488        let profile = self
489            .media
490            .get_profile(family_id, profile_id)
491            .await
492            .map_err(TraktError::MediaStorage)?
493            .ok_or(TraktError::Forbidden)?;
494        if profile.user_id != Some(owner_id) {
495            return Err(TraktError::Forbidden);
496        }
497        let families = self
498            .families
499            .list_families(owner_id)
500            .await
501            .map_err(|error| TraktError::Family(error.to_string()))?;
502        if !families.iter().any(|family| family.id == family_id) {
503            return Err(TraktError::Forbidden);
504        }
505        Ok(())
506    }
507
508    async fn exchange_code(
509        &self,
510        code: &str,
511        code_verifier: &str,
512    ) -> Result<TraktTokenResponse, TraktError> {
513        self.token_request(&[
514            ("code", code),
515            ("client_id", &self.config.client_id),
516            ("redirect_uri", &self.config.redirect_uri),
517            ("grant_type", "authorization_code"),
518            ("code_verifier", code_verifier),
519        ])
520        .await
521    }
522
523    async fn fetch_user_settings(&self, access_token: &str) -> Result<TraktUser, TraktError> {
524        let response = self
525            .http
526            .get(format!("{}/users/settings", self.config.api_base_url))
527            .bearer_auth(access_token)
528            .header(reqwest::header::CONTENT_TYPE, "application/json")
529            .header("trakt-api-version", "2")
530            .header("trakt-api-key", &self.config.client_id)
531            .send()
532            .await?;
533        let response = ensure_success(response).await?;
534        let settings: TraktUserSettings = response.json().await?;
535        if settings.user.username.trim().is_empty() {
536            return Err(TraktError::InvalidResponse(
537                "Trakt account did not return a username".into(),
538            ));
539        }
540        Ok(settings.user)
541    }
542
543    async fn token_request(
544        &self,
545        fields: &[(&str, &str)],
546    ) -> Result<TraktTokenResponse, TraktError> {
547        let response = self
548            .http
549            .post(&self.config.token_url)
550            .json(&TokenRequest(fields))
551            .send()
552            .await?;
553        ensure_success(response)
554            .await?
555            .json()
556            .await
557            .map_err(TraktError::Request)
558    }
559}
560
561/// Cached short-lived access tokens; refresh tokens remain in agent-storage only.
562#[derive(Clone)]
563pub struct TraktTokenManager {
564    config: TraktOAuthConfig,
565    http: Client,
566    external_connections: Arc<dyn ExternalConnectionStore>,
567    connections: Arc<Mutex<HashMap<ExternalConnectionId, Arc<Mutex<Option<CachedAccessToken>>>>>>,
568}
569
570struct CachedAccessToken {
571    refresh_token_hash: [u8; 32],
572    access_token: String,
573    expires_at: Instant,
574}
575
576impl TraktTokenManager {
577    pub fn new(
578        config: TraktOAuthConfig,
579        external_connections: Arc<dyn ExternalConnectionStore>,
580    ) -> Result<Self, TraktError> {
581        Ok(Self {
582            config,
583            http: http_client()?,
584            external_connections,
585            connections: Arc::new(Mutex::new(HashMap::new())),
586        })
587    }
588
589    /// Return a valid token, refreshing once under concurrent requests per connection.
590    pub async fn access_token(
591        &self,
592        owner_id: UserId,
593        connection_id: ExternalConnectionId,
594    ) -> Result<String, TraktError> {
595        let connection_metadata = self
596            .external_connections
597            .get_connection(owner_id, connection_id)
598            .await
599            .map_err(TraktError::ExternalStorage)?
600            .ok_or(TraktError::ConnectionUnavailable)?;
601        if connection_metadata.status != ExternalConnectionStatus::Active {
602            return Err(TraktError::ConnectionUnavailable);
603        }
604        let refresh_token = self
605            .external_connections
606            .refresh_token(owner_id, connection_id)
607            .await
608            .map_err(TraktError::ExternalStorage)?;
609        let refresh_token_hash: [u8; 32] = Sha256::digest(refresh_token.as_bytes()).into();
610        let connection = {
611            let mut connections = self.connections.lock().await;
612            connections
613                .entry(connection_id)
614                .or_insert_with(|| Arc::new(Mutex::new(None)))
615                .clone()
616        };
617        let mut cached = connection.lock().await;
618        if let Some(token) = cached.as_ref().filter(|token| {
619            token.refresh_token_hash == refresh_token_hash
620                && token.expires_at > Instant::now() + Duration::from_secs(30)
621        }) {
622            return Ok(token.access_token.clone());
623        }
624
625        let token = self.refresh(&refresh_token).await?;
626        let new_refresh_token = token
627            .refresh_token
628            .clone()
629            .ok_or(TraktError::MissingRefreshToken)?;
630        let scopes = if token.scope.is_some() {
631            token.scopes()
632        } else {
633            connection_metadata.granted_scopes.clone()
634        };
635        self.external_connections
636            .update_credentials(
637                owner_id,
638                connection_id,
639                Some(new_refresh_token.clone()),
640                scopes,
641            )
642            .await
643            .map_err(TraktError::ExternalStorage)?;
644        let lifetime = token
645            .expires_in_seconds()
646            .unwrap_or(300)
647            .saturating_sub(30)
648            .max(1);
649        let access_token = token.access_token;
650        let effective_refresh_token_hash: [u8; 32] =
651            Sha256::digest(new_refresh_token.as_bytes()).into();
652        *cached = Some(CachedAccessToken {
653            refresh_token_hash: effective_refresh_token_hash,
654            access_token: access_token.clone(),
655            expires_at: Instant::now() + Duration::from_secs(lifetime),
656        });
657        Ok(access_token)
658    }
659
660    pub async fn invalidate(&self, connection_id: ExternalConnectionId) {
661        let connection = self.connections.lock().await.get(&connection_id).cloned();
662        if let Some(connection) = connection {
663            *connection.lock().await = None;
664        }
665    }
666
667    async fn refresh(&self, refresh_token: &str) -> Result<TraktTokenResponse, TraktError> {
668        let response = self
669            .http
670            .post(&self.config.token_url)
671            .json(&TokenRequest(&[
672                ("refresh_token", refresh_token),
673                ("client_id", &self.config.client_id),
674                ("redirect_uri", &self.config.redirect_uri),
675                ("grant_type", "refresh_token"),
676            ]))
677            .send()
678            .await?;
679        ensure_success(response)
680            .await?
681            .json()
682            .await
683            .map_err(TraktError::Request)
684    }
685}
686
687#[derive(Debug, thiserror::Error)]
688pub enum TraktError {
689    #[error("invalid Trakt OAuth configuration: {0}")]
690    Configuration(String),
691    #[error("Trakt request failed: {0}")]
692    Request(#[from] reqwest::Error),
693    #[error("Trakt returned HTTP {status}: {message}")]
694    Api { status: StatusCode, message: String },
695    #[error("Trakt account did not issue a refresh token")]
696    MissingRefreshToken,
697    #[error("Trakt external connection is missing or revoked")]
698    ConnectionUnavailable,
699    #[error("family membership or profile permissions do not allow this operation")]
700    Forbidden,
701    #[error("family storage failed: {0}")]
702    Family(String),
703    #[error("media storage failed: {0}")]
704    MediaStorage(#[source] MediaStoreError),
705    #[error("external connection storage failed: {0}")]
706    ExternalStorage(#[source] agent_storage::ExternalConnectionStorageError),
707    #[error("Trakt returned an invalid response: {0}")]
708    InvalidResponse(String),
709}
710
711fn pkce_pair() -> (String, String) {
712    // Two UUIDs provide 256 bits of entropy and a verifier within RFC 7636's
713    // 43-128 character range. Only the encrypted verifier is persisted.
714    let verifier = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
715    let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
716    (verifier, challenge)
717}
718
719fn http_client() -> Result<Client, TraktError> {
720    Client::builder()
721        .user_agent(concat!("EME/", env!("CARGO_PKG_VERSION")))
722        .redirect(reqwest::redirect::Policy::none())
723        .build()
724        .map_err(TraktError::Request)
725}
726
727async fn ensure_success(response: reqwest::Response) -> Result<reqwest::Response, TraktError> {
728    let status = response.status();
729    if status.is_success() {
730        return Ok(response);
731    }
732    let message = response
733        .text()
734        .await
735        .unwrap_or_else(|_| "request failed".into());
736    Err(TraktError::Api { status, message })
737}
738
739struct TokenRequest<'a>(&'a [(&'a str, &'a str)]);
740
741impl Serialize for TokenRequest<'_> {
742    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
743    where
744        S: serde::Serializer,
745    {
746        use serde::ser::SerializeMap;
747        let mut map = serializer.serialize_map(Some(self.0.len()))?;
748        for (key, value) in self.0 {
749            map.serialize_entry(key, value)?;
750        }
751        map.end()
752    }
753}
754
755#[derive(Debug, Deserialize)]
756struct TraktTokenResponse {
757    access_token: String,
758    refresh_token: Option<String>,
759    expires_in: Option<u64>,
760    scope: Option<String>,
761}
762
763impl TraktTokenResponse {
764    fn scopes(&self) -> Vec<String> {
765        self.scope
766            .as_deref()
767            .unwrap_or_default()
768            .split([',', ' '])
769            .filter(|scope| !scope.is_empty())
770            .map(str::to_owned)
771            .collect()
772    }
773
774    fn expires_in_seconds(&self) -> Option<u64> {
775        self.expires_in
776    }
777}
778
779#[derive(Debug, Deserialize)]
780struct TraktUserSettings {
781    user: TraktUser,
782}
783
784#[derive(Debug, Clone, Deserialize)]
785struct TraktUser {
786    username: String,
787    name: Option<String>,
788}
789
790#[cfg(test)]
791mod tests {
792    use std::{fs, sync::Arc};
793
794    use agent_storage::{
795        Family, FamilyMember, FamilyRole, InMemoryFamilyStore, SqliteExternalConnectionStore,
796    };
797    use chrono::Utc;
798    use wiremock::{
799        Mock, MockServer, ResponseTemplate,
800        matchers::{header, method, path},
801    };
802
803    use super::*;
804
805    async fn family_and_profile() -> (
806        Arc<InMemoryFamilyStore>,
807        UserId,
808        FamilyId,
809        MediaStore,
810        MediaProfileId,
811    ) {
812        let families = Arc::new(InMemoryFamilyStore::default());
813        let user_id = UserId::new();
814        let family_id = FamilyId::new();
815        let now = Utc::now();
816        families
817            .create_family(
818                Family {
819                    id: family_id,
820                    name: "Home".into(),
821                    creator_id: user_id,
822                    created_at: now,
823                    updated_at: now,
824                },
825                FamilyMember {
826                    family_id,
827                    user_id,
828                    role: FamilyRole::Owner,
829                    relationship: agent_storage::FamilyRelationship::Father,
830                    joined_at: now,
831                },
832            )
833            .await
834            .unwrap();
835        let media = MediaStore::open_in_memory().unwrap();
836        let mut profile = crate::MediaProfile::new(family_id, "Child");
837        profile.user_id = Some(user_id);
838        let profile_id = profile.id;
839        media.save_profile(&profile).await.unwrap();
840        (families, user_id, family_id, media, profile_id)
841    }
842
843    #[tokio::test]
844    async fn authorization_callback_links_profile_to_encrypted_external_connection() {
845        let server = MockServer::start().await;
846        Mock::given(method("POST"))
847            .and(path("/oauth/token"))
848            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
849                "access_token": "short-lived-access",
850                "refresh_token": "durable-refresh",
851                "expires_in": 7200
852            })))
853            .mount(&server)
854            .await;
855        Mock::given(method("GET"))
856            .and(path("/users/settings"))
857            .and(header("Authorization", "Bearer short-lived-access"))
858            .and(header(
859                "User-Agent",
860                concat!("EME/", env!("CARGO_PKG_VERSION")),
861            ))
862            .and(header("Content-Type", "application/json"))
863            .and(header("trakt-api-version", "2"))
864            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
865                "user": {"username": "example-user", "name": "Example"}
866            })))
867            .mount(&server)
868            .await;
869
870        let (families, user_id, family_id, media, profile_id) = family_and_profile().await;
871        let db_path = std::env::temp_dir().join(format!("media-trakt-{}.db", Uuid::new_v4()));
872        let external = Arc::new(SqliteExternalConnectionStore::open(&db_path, [7; 32]).unwrap());
873        let external_trait: Arc<dyn ExternalConnectionStore> = external.clone();
874        let service = TraktOAuthService::new(
875            TraktOAuthConfig::with_endpoints(
876                "client",
877                "http://localhost/callback",
878                format!("{}/authorize", server.uri()),
879                format!("{}/oauth/token", server.uri()),
880                server.uri(),
881            )
882            .unwrap(),
883            media.clone(),
884            families,
885            external_trait,
886        )
887        .unwrap();
888
889        let authorization = service
890            .begin_link(user_id, family_id, profile_id)
891            .await
892            .unwrap();
893        let url = Url::parse(&authorization.authorization_url).unwrap();
894        let state = url
895            .query_pairs()
896            .find(|(key, _)| key == "state")
897            .unwrap()
898            .1
899            .into_owned();
900        let query = url
901            .query_pairs()
902            .collect::<std::collections::HashMap<_, _>>();
903        assert_eq!(
904            query
905                .get("code_challenge_method")
906                .map(|value| value.as_ref()),
907            Some("S256")
908        );
909        assert!(
910            !query.contains_key("scope"),
911            "Trakt authorization requests must not send an unsupported scope"
912        );
913        assert!(query.contains_key("code_challenge"));
914        let link = service
915            .complete_link(user_id, &state, "one-time-code")
916            .await
917            .unwrap();
918
919        assert_eq!(link.provider_subject, "example-user");
920        assert_eq!(link.display_name.as_deref(), Some("Example"));
921        assert_eq!(
922            media
923                .get_external_connection_link(profile_id, "trakt")
924                .await
925                .unwrap(),
926            Some(link.clone())
927        );
928        assert_eq!(
929            external
930                .refresh_token(user_id, link.external_connection_id)
931                .await
932                .unwrap(),
933            "durable-refresh"
934        );
935        assert!(matches!(
936            service
937                .complete_link(user_id, &state, "one-time-code")
938                .await,
939            Err(TraktError::MediaStorage(MediaStoreError::PendingNotFound))
940        ));
941
942        // The same complete OAuth flow works for a user with no family.
943        let personal_user = UserId::new();
944        let personal = media
945            .get_or_create_personal_profile(personal_user)
946            .await
947            .unwrap();
948        let personal_authorization = service
949            .begin_personal_link(personal_user, personal.id)
950            .await
951            .unwrap();
952        let personal_state = Url::parse(&personal_authorization.authorization_url)
953            .unwrap()
954            .query_pairs()
955            .find(|(key, _)| key == "state")
956            .unwrap()
957            .1
958            .into_owned();
959        let personal_link = service
960            .complete_link(personal_user, &personal_state, "personal-one-time-code")
961            .await
962            .unwrap();
963        assert_eq!(personal_link.owner_id, personal_user);
964        assert_eq!(personal_link.family_id, None);
965        assert_eq!(
966            media
967                .get_external_connection_link(personal.id, "trakt")
968                .await
969                .unwrap(),
970            Some(personal_link)
971        );
972
973        drop(service);
974        drop(external);
975        let _ = fs::remove_file(db_path);
976    }
977
978    #[tokio::test]
979    async fn token_manager_rotates_refresh_tokens_and_reuses_cached_access_tokens() {
980        let server = MockServer::start().await;
981        Mock::given(method("POST"))
982            .and(path("/oauth/token"))
983            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
984                "access_token": "cached-access",
985                "refresh_token": "rotated-refresh",
986                "expires_in": 3600,
987                "scope": "private"
988            })))
989            .expect(1)
990            .mount(&server)
991            .await;
992
993        let db_path = std::env::temp_dir().join(format!("media-trakt-token-{}.db", Uuid::new_v4()));
994        let external = Arc::new(SqliteExternalConnectionStore::open(&db_path, [9; 32]).unwrap());
995        let owner_id = UserId::new();
996        let connection = external
997            .create_connection(NewExternalConnection {
998                owner_id,
999                provider: "trakt".into(),
1000                provider_subject: "example-user".into(),
1001                display_email: None,
1002                refresh_token: "original-refresh".into(),
1003                granted_scopes: vec!["public".into()],
1004            })
1005            .await
1006            .unwrap();
1007        let external_trait: Arc<dyn ExternalConnectionStore> = external.clone();
1008        let manager = TraktTokenManager::new(
1009            TraktOAuthConfig::with_endpoints(
1010                "client",
1011                "http://localhost/callback",
1012                format!("{}/authorize", server.uri()),
1013                format!("{}/oauth/token", server.uri()),
1014                server.uri(),
1015            )
1016            .unwrap(),
1017            external_trait,
1018        )
1019        .unwrap();
1020
1021        assert_eq!(
1022            manager.access_token(owner_id, connection.id).await.unwrap(),
1023            "cached-access"
1024        );
1025        assert_eq!(
1026            manager.access_token(owner_id, connection.id).await.unwrap(),
1027            "cached-access"
1028        );
1029        assert_eq!(
1030            external
1031                .refresh_token(owner_id, connection.id)
1032                .await
1033                .unwrap(),
1034            "rotated-refresh"
1035        );
1036
1037        drop(manager);
1038        drop(external);
1039        let _ = fs::remove_file(db_path);
1040    }
1041
1042    #[tokio::test]
1043    async fn only_the_assigned_user_can_link_their_profile() {
1044        let (families, user_id, family_id, media, profile_id) = family_and_profile().await;
1045        let member_id = UserId::new();
1046        families
1047            .add_member(FamilyMember {
1048                family_id,
1049                user_id: member_id,
1050                role: FamilyRole::Member,
1051                relationship: agent_storage::FamilyRelationship::Partner,
1052                joined_at: Utc::now(),
1053            })
1054            .await
1055            .unwrap();
1056        let db_path = std::env::temp_dir().join(format!("media-trakt-{}.db", Uuid::new_v4()));
1057        let external = Arc::new(SqliteExternalConnectionStore::open(&db_path, [8; 32]).unwrap());
1058        let external_trait: Arc<dyn ExternalConnectionStore> = external.clone();
1059        let service = TraktOAuthService::new(
1060            TraktOAuthConfig::new("client", "http://localhost/callback").unwrap(),
1061            media.clone(),
1062            families,
1063            external_trait,
1064        )
1065        .unwrap();
1066        assert!(matches!(
1067            service.begin_link(member_id, family_id, profile_id).await,
1068            Err(TraktError::Forbidden)
1069        ));
1070
1071        let mut member_profile = crate::MediaProfile::new(family_id, "Member");
1072        member_profile.user_id = Some(member_id);
1073        let member_profile_id = member_profile.id;
1074        media.save_profile(&member_profile).await.unwrap();
1075        assert!(
1076            service
1077                .begin_link(member_id, family_id, member_profile_id)
1078                .await
1079                .is_ok(),
1080            "a regular family member can link their own assigned profile"
1081        );
1082        // A user with no family membership can still link their own personal profile.
1083        let standalone_user = UserId::new();
1084        let personal = media
1085            .get_or_create_personal_profile(standalone_user)
1086            .await
1087            .unwrap();
1088        assert!(
1089            service
1090                .begin_personal_link(standalone_user, personal.id)
1091                .await
1092                .is_ok()
1093        );
1094        assert!(matches!(
1095            service.begin_personal_link(member_id, personal.id).await,
1096            Err(TraktError::Forbidden)
1097        ));
1098
1099        drop(service);
1100        drop(external);
1101        let _ = fs::remove_file(db_path);
1102        let _ = user_id;
1103    }
1104}