1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright 2024 New Vector Ltd.
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

use chrono::{DateTime, Utc};
use serde::Serialize;
use ulid::Ulid;

use super::UpstreamOAuthLink;
use crate::InvalidTransitionError;

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub enum UpstreamOAuthAuthorizationSessionState {
    #[default]
    Pending,
    Completed {
        completed_at: DateTime<Utc>,
        link_id: Ulid,
        id_token: Option<String>,
        extra_callback_parameters: Option<serde_json::Value>,
    },
    Consumed {
        completed_at: DateTime<Utc>,
        consumed_at: DateTime<Utc>,
        link_id: Ulid,
        id_token: Option<String>,
        extra_callback_parameters: Option<serde_json::Value>,
    },
}

impl UpstreamOAuthAuthorizationSessionState {
    /// Mark the upstream OAuth 2.0 authorization session as completed.
    ///
    /// # Errors
    ///
    /// Returns an error if the upstream OAuth 2.0 authorization session state
    /// is not [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    pub fn complete(
        self,
        completed_at: DateTime<Utc>,
        link: &UpstreamOAuthLink,
        id_token: Option<String>,
        extra_callback_parameters: Option<serde_json::Value>,
    ) -> Result<Self, InvalidTransitionError> {
        match self {
            Self::Pending => Ok(Self::Completed {
                completed_at,
                link_id: link.id,
                id_token,
                extra_callback_parameters,
            }),
            Self::Completed { .. } | Self::Consumed { .. } => Err(InvalidTransitionError),
        }
    }

    /// Mark the upstream OAuth 2.0 authorization session as consumed.
    ///
    /// # Errors
    ///
    /// Returns an error if the upstream OAuth 2.0 authorization session state
    /// is not [`Completed`].
    ///
    /// [`Completed`]: UpstreamOAuthAuthorizationSessionState::Completed
    pub fn consume(self, consumed_at: DateTime<Utc>) -> Result<Self, InvalidTransitionError> {
        match self {
            Self::Completed {
                completed_at,
                link_id,
                id_token,
                extra_callback_parameters,
            } => Ok(Self::Consumed {
                completed_at,
                link_id,
                consumed_at,
                id_token,
                extra_callback_parameters,
            }),
            Self::Pending | Self::Consumed { .. } => Err(InvalidTransitionError),
        }
    }

    /// Get the link ID for the upstream OAuth 2.0 authorization session.
    ///
    /// Returns `None` if the upstream OAuth 2.0 authorization session state is
    /// [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    #[must_use]
    pub fn link_id(&self) -> Option<Ulid> {
        match self {
            Self::Pending => None,
            Self::Completed { link_id, .. } | Self::Consumed { link_id, .. } => Some(*link_id),
        }
    }

    /// Get the time at which the upstream OAuth 2.0 authorization session was
    /// completed.
    ///
    /// Returns `None` if the upstream OAuth 2.0 authorization session state is
    /// [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    #[must_use]
    pub fn completed_at(&self) -> Option<DateTime<Utc>> {
        match self {
            Self::Pending => None,
            Self::Completed { completed_at, .. } | Self::Consumed { completed_at, .. } => {
                Some(*completed_at)
            }
        }
    }

    /// Get the ID token for the upstream OAuth 2.0 authorization session.
    ///
    /// Returns `None` if the upstream OAuth 2.0 authorization session state is
    /// [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    #[must_use]
    pub fn id_token(&self) -> Option<&str> {
        match self {
            Self::Pending => None,
            Self::Completed { id_token, .. } | Self::Consumed { id_token, .. } => {
                id_token.as_deref()
            }
        }
    }

    /// Get the extra query parameters that were sent to the upstream provider.
    ///
    /// Returns `None` if the upstream OAuth 2.0 authorization session state is
    /// not [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    #[must_use]
    pub fn extra_callback_parameters(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Pending => None,
            Self::Completed {
                extra_callback_parameters,
                ..
            }
            | Self::Consumed {
                extra_callback_parameters,
                ..
            } => extra_callback_parameters.as_ref(),
        }
    }

    /// Get the time at which the upstream OAuth 2.0 authorization session was
    /// consumed.
    ///
    /// Returns `None` if the upstream OAuth 2.0 authorization session state is
    /// not [`Consumed`].
    ///
    /// [`Consumed`]: UpstreamOAuthAuthorizationSessionState::Consumed
    #[must_use]
    pub fn consumed_at(&self) -> Option<DateTime<Utc>> {
        match self {
            Self::Pending | Self::Completed { .. } => None,
            Self::Consumed { consumed_at, .. } => Some(*consumed_at),
        }
    }

    /// Returns `true` if the upstream OAuth 2.0 authorization session state is
    /// [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    #[must_use]
    pub fn is_pending(&self) -> bool {
        matches!(self, Self::Pending)
    }

    /// Returns `true` if the upstream OAuth 2.0 authorization session state is
    /// [`Completed`].
    ///
    /// [`Completed`]: UpstreamOAuthAuthorizationSessionState::Completed
    #[must_use]
    pub fn is_completed(&self) -> bool {
        matches!(self, Self::Completed { .. })
    }

    /// Returns `true` if the upstream OAuth 2.0 authorization session state is
    /// [`Consumed`].
    ///
    /// [`Consumed`]: UpstreamOAuthAuthorizationSessionState::Consumed
    #[must_use]
    pub fn is_consumed(&self) -> bool {
        matches!(self, Self::Consumed { .. })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct UpstreamOAuthAuthorizationSession {
    pub id: Ulid,
    pub state: UpstreamOAuthAuthorizationSessionState,
    pub provider_id: Ulid,
    pub state_str: String,
    pub code_challenge_verifier: Option<String>,
    pub nonce: String,
    pub created_at: DateTime<Utc>,
}

impl std::ops::Deref for UpstreamOAuthAuthorizationSession {
    type Target = UpstreamOAuthAuthorizationSessionState;

    fn deref(&self) -> &Self::Target {
        &self.state
    }
}

impl UpstreamOAuthAuthorizationSession {
    /// Mark the upstream OAuth 2.0 authorization session as completed. Returns
    /// the updated session.
    ///
    /// # Errors
    ///
    /// Returns an error if the upstream OAuth 2.0 authorization session state
    /// is not [`Pending`].
    ///
    /// [`Pending`]: UpstreamOAuthAuthorizationSessionState::Pending
    pub fn complete(
        mut self,
        completed_at: DateTime<Utc>,
        link: &UpstreamOAuthLink,
        id_token: Option<String>,
        extra_callback_parameters: Option<serde_json::Value>,
    ) -> Result<Self, InvalidTransitionError> {
        self.state =
            self.state
                .complete(completed_at, link, id_token, extra_callback_parameters)?;
        Ok(self)
    }

    /// Mark the upstream OAuth 2.0 authorization session as consumed. Returns
    /// the updated session.
    ///
    /// # Errors
    ///
    /// Returns an error if the upstream OAuth 2.0 authorization session state
    /// is not [`Completed`].
    ///
    /// [`Completed`]: UpstreamOAuthAuthorizationSessionState::Completed
    pub fn consume(mut self, consumed_at: DateTime<Utc>) -> Result<Self, InvalidTransitionError> {
        self.state = self.state.consume(consumed_at)?;
        Ok(self)
    }
}