1use std::{
2 fmt,
3 sync::{Arc, Mutex, MutexGuard},
4};
5
6use serde::{Deserialize, Deserializer, Serialize};
7use zeroize::Zeroizing;
8
9use crate::error::{Error, ErrorCategory, LocalAction, RetryPolicy};
10
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12enum HandoffState {
13 Available,
14 Reserved,
15 Consumed,
16}
17
18pub(crate) struct HandoffGuard {
19 state: Mutex<HandoffState>,
20}
21
22impl HandoffGuard {
23 pub(crate) fn new() -> Self {
24 Self {
25 state: Mutex::new(HandoffState::Available),
26 }
27 }
28
29 fn state(&self) -> MutexGuard<'_, HandoffState> {
30 self.state
31 .lock()
32 .unwrap_or_else(std::sync::PoisonError::into_inner)
33 }
34
35 pub(crate) fn reserve(&self) -> bool {
36 let mut state = self.state();
37 if *state != HandoffState::Available {
38 return false;
39 }
40 *state = HandoffState::Reserved;
41 true
42 }
43
44 pub(crate) fn release(&self) {
45 *self.state() = HandoffState::Available;
46 }
47
48 pub(crate) fn consume(&self) {
49 *self.state() = HandoffState::Consumed;
50 }
51
52 pub(crate) fn available(&self) -> bool {
53 *self.state() == HandoffState::Available
54 }
55
56 pub(crate) fn consumed(&self) -> bool {
57 *self.state() == HandoffState::Consumed
58 }
59}
60
61fn deserialize_required_nullable<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
62where
63 D: Deserializer<'de>,
64{
65 Option::<String>::deserialize(deserializer)
66}
67
68macro_rules! secret_string {
69 ($name:ident, $label:literal) => {
70 pub struct $name(Zeroizing<String>);
71
72 impl $name {
73 pub(crate) fn new(value: String) -> Self {
74 Self(Zeroizing::new(value))
75 }
76
77 #[must_use]
79 pub fn expose(&self) -> &str {
80 self.0.as_str()
81 }
82 }
83
84 impl fmt::Debug for $name {
85 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86 formatter.write_str(concat!($label, "([REDACTED])"))
87 }
88 }
89 };
90}
91
92secret_string!(AccessToken, "AccessToken");
93secret_string!(RefreshToken, "RefreshToken");
94
95#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
97pub struct PublicProvider {
98 pub key: String,
99 pub display_name: String,
100 pub kind: String,
101}
102
103#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
105#[allow(
106 clippy::struct_excessive_bools,
107 reason = "the public wire contract exposes orthogonal current capability facts"
108)]
109pub struct PublicConfiguration {
110 pub project_public_id: String,
111 pub project_display_name: String,
112 pub application_public_id: String,
113 pub application_display_name: String,
114 pub publishable_keys: Vec<String>,
115 pub providers: Vec<PublicProvider>,
116 pub email_available: bool,
117 pub email_otp_enabled: bool,
118 pub email_magic_link_enabled: bool,
119 pub login_available: bool,
120}
121
122#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
124#[serde(deny_unknown_fields)]
125pub struct PublicJwk {
126 pub kty: String,
127 pub crv: String,
128 pub alg: String,
129 #[serde(rename = "use")]
130 pub key_use: String,
131 pub kid: String,
132 pub x: String,
133}
134
135#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
137pub struct JwksDocument {
138 pub keys: Vec<PublicJwk>,
139 pub revision: i64,
140 pub signing_epoch: i64,
141}
142
143#[derive(Clone, Deserialize, PartialEq, Serialize)]
145#[serde(deny_unknown_fields)]
146pub struct UserProjection {
147 pub user_id: String,
148 pub user_revision: i64,
149 pub projection_schema: String,
150 pub projection_revision: i64,
151 #[serde(deserialize_with = "deserialize_required_nullable")]
152 pub display_name: Option<String>,
153 #[serde(deserialize_with = "deserialize_required_nullable")]
154 pub picture_url: Option<String>,
155 #[serde(deserialize_with = "deserialize_required_nullable")]
156 pub locale: Option<String>,
157 #[serde(deserialize_with = "deserialize_required_nullable")]
158 pub verified_email: Option<String>,
159 pub status: String,
160 pub created_at: String,
161 pub updated_at: String,
162}
163
164impl fmt::Debug for UserProjection {
165 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166 formatter
167 .debug_struct("UserProjection")
168 .field("user_id", &self.user_id)
169 .field("user_revision", &self.user_revision)
170 .field("projection_schema", &self.projection_schema)
171 .field("projection_revision", &self.projection_revision)
172 .field("profile", &"[REDACTED]")
173 .field("status", &self.status)
174 .finish_non_exhaustive()
175 }
176}
177
178pub struct PendingLogin {
180 pub(crate) schema_version: u8,
181 pub(crate) runtime_origin: String,
182 pub(crate) runtime_base_path: String,
183 pub(crate) project_id: String,
184 pub(crate) application_id: String,
185 pub(crate) redirect_uri: String,
186 pub(crate) verifier: Zeroizing<String>,
187 pub(crate) state: Zeroizing<String>,
188 pub(crate) created_at: i64,
189 pub(crate) expires_at: i64,
190 pub(crate) guard: Arc<HandoffGuard>,
191}
192
193#[derive(Clone, Deserialize, PartialEq, Serialize)]
195#[serde(deny_unknown_fields)]
196pub struct PendingLoginRecord {
197 pub(crate) schema_version: u8,
198 pub(crate) runtime_origin: String,
199 pub(crate) runtime_base_path: String,
200 pub(crate) project_id: String,
201 pub(crate) application_id: String,
202 pub(crate) redirect_uri: String,
203 pub(crate) verifier: String,
204 pub(crate) state: String,
205 pub(crate) created_at: i64,
206 pub(crate) expires_at: i64,
207}
208
209impl fmt::Debug for PendingLoginRecord {
210 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211 formatter
212 .debug_struct("PendingLoginRecord")
213 .field("schema_version", &self.schema_version)
214 .field("runtime_origin", &self.runtime_origin)
215 .field("runtime_base_path", &self.runtime_base_path)
216 .field("project_id", &self.project_id)
217 .field("application_id", &self.application_id)
218 .field("redirect_uri", &"[REDACTED]")
219 .field("verifier", &"[REDACTED]")
220 .field("state", &"[REDACTED]")
221 .field("created_at", &self.created_at)
222 .field("expires_at", &self.expires_at)
223 .finish()
224 }
225}
226
227impl PendingLogin {
228 #[must_use]
229 pub const fn schema_version(&self) -> u8 {
230 self.schema_version
231 }
232
233 #[must_use]
234 pub fn project_id(&self) -> &str {
235 &self.project_id
236 }
237
238 #[must_use]
239 pub fn application_id(&self) -> &str {
240 &self.application_id
241 }
242
243 #[must_use]
244 pub fn redirect_uri(&self) -> &str {
245 &self.redirect_uri
246 }
247
248 #[must_use]
249 pub const fn created_at(&self) -> i64 {
250 self.created_at
251 }
252
253 #[must_use]
254 pub const fn expires_at(&self) -> i64 {
255 self.expires_at
256 }
257
258 pub fn export_record(&self) -> Result<PendingLoginRecord, Error> {
263 let state = self.guard.state();
264 if *state != HandoffState::Available {
265 return Err(Error::new(
266 ErrorCategory::Handoff,
267 "pending_consumed",
268 "Reserved or consumed pending login state cannot be exported.",
269 RetryPolicy::Never,
270 LocalAction::DiscardPendingLogin,
271 "exchange_handoff",
272 ));
273 }
274 let record = PendingLoginRecord {
275 schema_version: self.schema_version,
276 runtime_origin: self.runtime_origin.clone(),
277 runtime_base_path: self.runtime_base_path.clone(),
278 project_id: self.project_id.clone(),
279 application_id: self.application_id.clone(),
280 redirect_uri: self.redirect_uri.clone(),
281 verifier: self.verifier.to_string(),
282 state: self.state.to_string(),
283 created_at: self.created_at,
284 expires_at: self.expires_at,
285 };
286 drop(state);
287 Ok(record)
288 }
289
290 #[must_use]
291 pub fn available(&self) -> bool {
292 self.guard.available()
293 }
294
295 #[must_use]
296 pub fn consumed(&self) -> bool {
297 self.guard.consumed()
298 }
299}
300
301impl fmt::Debug for PendingLogin {
302 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
303 formatter
304 .debug_struct("PendingLogin")
305 .field("schema_version", &self.schema_version)
306 .field("runtime_origin", &self.runtime_origin)
307 .field("runtime_base_path", &self.runtime_base_path)
308 .field("project_id", &self.project_id)
309 .field("application_id", &self.application_id)
310 .field("redirect_uri", &"[REDACTED]")
311 .field("verifier", &"[REDACTED]")
312 .field("state", &"[REDACTED]")
313 .field("created_at", &self.created_at)
314 .field("expires_at", &self.expires_at)
315 .field("consumed", &self.consumed())
316 .finish_non_exhaustive()
317 }
318}
319
320pub struct LoginStart {
322 pub hosted_url: String,
323 pub pending: PendingLogin,
324}
325
326impl fmt::Debug for LoginStart {
327 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328 formatter
329 .debug_struct("LoginStart")
330 .field("hosted_url", &"[REDACTED]")
331 .field("pending", &self.pending)
332 .finish()
333 }
334}
335
336pub struct ValidatedCallback {
338 pub(crate) handoff: Zeroizing<String>,
339 pub(crate) verifier: Zeroizing<String>,
340 pub(crate) guard: Arc<HandoffGuard>,
341}
342
343impl fmt::Debug for ValidatedCallback {
344 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
345 formatter.write_str("ValidatedCallback([REDACTED])")
346 }
347}
348
349#[derive(Clone, Deserialize, PartialEq, Serialize)]
351#[serde(deny_unknown_fields)]
352pub struct CredentialPairRecord {
353 pub(crate) schema_version: u8,
354 pub(crate) runtime_origin: String,
355 pub(crate) runtime_base_path: String,
356 pub(crate) project_id: String,
357 pub(crate) application_id: String,
358 pub(crate) user_id: String,
359 pub(crate) session_id: String,
360 pub(crate) refresh_generation: i64,
361 pub(crate) access_token: String,
362 pub(crate) refresh_token: String,
363 pub(crate) token_type: String,
364 pub(crate) access_expires_at: i64,
365 pub(crate) projection: UserProjection,
366 pub(crate) projection_revision: i64,
367 pub(crate) session_expires_at: String,
368}
369
370impl fmt::Debug for CredentialPairRecord {
371 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
372 formatter
373 .debug_struct("CredentialPairRecord")
374 .field("schema_version", &self.schema_version)
375 .field("runtime_origin", &self.runtime_origin)
376 .field("runtime_base_path", &self.runtime_base_path)
377 .field("project_id", &self.project_id)
378 .field("application_id", &self.application_id)
379 .field("user_id", &self.user_id)
380 .field("session_id", &self.session_id)
381 .field("refresh_generation", &self.refresh_generation)
382 .field("access_token", &"[REDACTED]")
383 .field("refresh_token", &"[REDACTED]")
384 .field("token_type", &self.token_type)
385 .field("access_expires_at", &self.access_expires_at)
386 .field("projection", &"[REDACTED]")
387 .field("projection_revision", &self.projection_revision)
388 .field("session_expires_at", &self.session_expires_at)
389 .finish()
390 }
391}
392
393pub struct CredentialPair {
395 runtime_origin: String,
396 runtime_base_path: String,
397 project_id: String,
398 application_id: String,
399 user_id: String,
400 session_id: String,
401 refresh_generation: i64,
402 access_token: AccessToken,
403 refresh_token: RefreshToken,
404 token_type: String,
405 expires_in: i64,
406 access_expires_at: i64,
407 projection: UserProjection,
408 projection_revision: i64,
409 session_expires_at: String,
410}
411
412impl CredentialPair {
413 #[must_use]
414 pub fn runtime_origin(&self) -> &str {
415 &self.runtime_origin
416 }
417 #[must_use]
418 pub fn runtime_base_path(&self) -> &str {
419 &self.runtime_base_path
420 }
421 #[must_use]
422 pub fn project_id(&self) -> &str {
423 &self.project_id
424 }
425 #[must_use]
426 pub fn application_id(&self) -> &str {
427 &self.application_id
428 }
429 #[must_use]
430 pub fn user_id(&self) -> &str {
431 &self.user_id
432 }
433 #[must_use]
434 pub fn session_id(&self) -> &str {
435 &self.session_id
436 }
437 #[must_use]
438 pub const fn refresh_generation(&self) -> i64 {
439 self.refresh_generation
440 }
441 #[must_use]
442 pub const fn access_token(&self) -> &AccessToken {
443 &self.access_token
444 }
445 #[must_use]
446 pub const fn refresh_token(&self) -> &RefreshToken {
447 &self.refresh_token
448 }
449 #[must_use]
450 pub fn token_type(&self) -> &str {
451 &self.token_type
452 }
453 #[must_use]
454 pub const fn expires_in(&self) -> i64 {
455 self.expires_in
456 }
457 #[must_use]
458 pub const fn access_expires_at(&self) -> i64 {
459 self.access_expires_at
460 }
461 #[must_use]
462 pub const fn projection(&self) -> &UserProjection {
463 &self.projection
464 }
465 #[must_use]
466 pub const fn projection_revision(&self) -> i64 {
467 self.projection_revision
468 }
469 #[must_use]
470 pub fn session_expires_at(&self) -> &str {
471 &self.session_expires_at
472 }
473
474 #[must_use]
476 pub fn export_record(&self) -> CredentialPairRecord {
477 CredentialPairRecord {
478 schema_version: 1,
479 runtime_origin: self.runtime_origin.clone(),
480 runtime_base_path: self.runtime_base_path.clone(),
481 project_id: self.project_id.clone(),
482 application_id: self.application_id.clone(),
483 user_id: self.user_id.clone(),
484 session_id: self.session_id.clone(),
485 refresh_generation: self.refresh_generation,
486 access_token: self.access_token.expose().to_owned(),
487 refresh_token: self.refresh_token.expose().to_owned(),
488 token_type: self.token_type.clone(),
489 access_expires_at: self.access_expires_at,
490 projection: self.projection.clone(),
491 projection_revision: self.projection_revision,
492 session_expires_at: self.session_expires_at.clone(),
493 }
494 }
495
496 pub(crate) fn from_record(value: CredentialPairRecord, expires_in: i64) -> Self {
497 Self {
498 runtime_origin: value.runtime_origin,
499 runtime_base_path: value.runtime_base_path,
500 project_id: value.project_id,
501 application_id: value.application_id,
502 user_id: value.user_id,
503 session_id: value.session_id,
504 refresh_generation: value.refresh_generation,
505 access_token: AccessToken::new(value.access_token),
506 refresh_token: RefreshToken::new(value.refresh_token),
507 token_type: value.token_type,
508 expires_in,
509 access_expires_at: value.access_expires_at,
510 projection: value.projection,
511 projection_revision: value.projection_revision,
512 session_expires_at: value.session_expires_at,
513 }
514 }
515
516 pub(crate) fn from_wire(
517 value: CredentialPairWire,
518 runtime_origin: String,
519 runtime_base_path: String,
520 access_expires_at: i64,
521 ) -> Self {
522 Self {
523 runtime_origin,
524 runtime_base_path,
525 project_id: value.project_id,
526 application_id: value.application_id,
527 user_id: value.user_id,
528 session_id: value.session_id,
529 refresh_generation: value.refresh_generation,
530 access_token: AccessToken::new(value.access_token),
531 refresh_token: RefreshToken::new(value.refresh_token),
532 token_type: value.token_type,
533 expires_in: value.expires_in,
534 access_expires_at,
535 projection: value.projection,
536 projection_revision: value.projection_revision,
537 session_expires_at: value.session_expires_at,
538 }
539 }
540}
541
542impl fmt::Debug for CredentialPair {
543 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
544 formatter
545 .debug_struct("CredentialPair")
546 .field("runtime_origin", &self.runtime_origin)
547 .field("runtime_base_path", &self.runtime_base_path)
548 .field("project_id", &self.project_id)
549 .field("application_id", &self.application_id)
550 .field("user_id", &self.user_id)
551 .field("session_id", &self.session_id)
552 .field("refresh_generation", &self.refresh_generation)
553 .field("access_token", &self.access_token)
554 .field("refresh_token", &self.refresh_token)
555 .field("token_type", &self.token_type)
556 .field("expires_in", &self.expires_in)
557 .field("access_expires_at", &self.access_expires_at)
558 .field("projection", &"[REDACTED]")
559 .field("projection_revision", &self.projection_revision)
560 .field("session_expires_at", &self.session_expires_at)
561 .finish()
562 }
563}
564
565#[derive(Clone, Deserialize, PartialEq)]
567#[serde(deny_unknown_fields)]
568pub struct CurrentUser {
569 pub project_id: String,
570 pub application_id: String,
571 pub user_id: String,
572 pub projection: UserProjection,
573 pub projection_revision: i64,
574 pub authenticated_at: String,
575 pub session_expires_at: String,
576}
577
578impl fmt::Debug for CurrentUser {
579 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
580 formatter
581 .debug_struct("CurrentUser")
582 .field("project_id", &self.project_id)
583 .field("application_id", &self.application_id)
584 .field("user_id", &self.user_id)
585 .field("projection", &"[REDACTED]")
586 .field("projection_revision", &self.projection_revision)
587 .field("authenticated_at", &self.authenticated_at)
588 .field("session_expires_at", &self.session_expires_at)
589 .finish()
590 }
591}
592
593#[derive(Clone, Deserialize, Eq, PartialEq)]
595pub struct BrowserLogoutPreparation {
596 pub hosted_url: String,
597 pub expires_at: String,
598}
599
600impl fmt::Debug for BrowserLogoutPreparation {
601 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
602 formatter
603 .debug_struct("BrowserLogoutPreparation")
604 .field("hosted_url", &"[REDACTED]")
605 .field("expires_at", &self.expires_at)
606 .finish()
607 }
608}
609
610#[derive(Serialize)]
611pub(crate) struct LoginStartRequest<'a> {
612 pub application_id: &'a str,
613 pub publishable_key: &'a str,
614 pub redirect_uri: &'a str,
615 pub pkce_challenge: &'a str,
616 pub state: &'a str,
617 pub presentation_hint: Option<&'a str>,
618}
619
620#[derive(Deserialize)]
621pub(crate) struct LoginStartResponse {
622 pub hosted_url: String,
623 pub expires_at: String,
624}
625
626#[derive(Serialize)]
627pub(crate) struct HandoffRequest<'a> {
628 pub application_id: &'a str,
629 pub publishable_key: &'a str,
630 pub handoff: &'a str,
631 pub pkce_verifier: &'a str,
632}
633
634#[derive(Serialize)]
635pub(crate) struct RefreshRequest<'a> {
636 pub application_id: &'a str,
637 pub publishable_key: &'a str,
638 pub refresh_token: &'a str,
639}
640
641#[derive(Deserialize)]
642#[serde(deny_unknown_fields)]
643pub(crate) struct CredentialPairWire {
644 pub project_id: String,
645 pub application_id: String,
646 pub user_id: String,
647 pub session_id: String,
648 pub refresh_generation: i64,
649 pub access_token: String,
650 pub refresh_token: String,
651 pub token_type: String,
652 pub expires_in: i64,
653 pub projection: UserProjection,
654 pub projection_revision: i64,
655 pub session_expires_at: String,
656}
657
658#[derive(Deserialize)]
659pub(crate) struct CompletionResponse {
660 pub completed: bool,
661}
662
663#[derive(Deserialize)]
664#[serde(deny_unknown_fields)]
665pub(crate) struct RuntimeErrorWire {
666 pub code: String,
667 pub message: String,
668 pub request_id: String,
669}