Skip to content

Commit 8dba160

Browse files
PiquelChipsclaude
andcommitted
fix(auth): read unknown device labels as other; skip expired sessions on revoke
A browser or platform a newer release records no longer fails session and history reads during a rolling deploy or after a rollback. Signing out other devices no longer counts sessions that had already expired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7de7433 commit 8dba160

8 files changed

Lines changed: 66 additions & 20 deletions

File tree

‎crates/common/src/events.rs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -729,9 +729,10 @@ crate::str_enum! {
729729
Opera = "opera",
730730
/// Apple Safari.
731731
Safari = "safari",
732-
/// Anything else, including back-channel HTTP clients.
732+
/// Anything else, including back-channel HTTP clients, and browsers a newer
733+
/// release recognizes.
733734
Other = "other",
734-
}
735+
} else Other
735736
}
736737

737738
crate::str_enum! {
@@ -749,14 +750,16 @@ crate::str_enum! {
749750
MacOs = "macos",
750751
/// Windows.
751752
Windows = "windows",
752-
/// Anything else, including back-channel HTTP clients.
753+
/// Anything else, including back-channel HTTP clients, and platforms a newer
754+
/// release recognizes.
753755
Other = "other",
754-
}
756+
} else Other
755757
}
756758

757759
/// Coarse browser and platform of a `User-Agent` header, the only part of it auth
758760
/// keeps. Stored as text, `browser/platform` (`firefox/linux`); serialized as
759-
/// `{"browser": …, "platform": …}`.
761+
/// `{"browser": …, "platform": …}`. A browser or platform this release doesn't
762+
/// know reads as `other`, so a session or event a newer release tagged still loads.
760763
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
761764
pub struct UserAgentFamily {
762765
/// The browser.

‎crates/common/src/events/tests.rs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ fn user_agents_classify() {
7777
}
7878
}
7979

80-
/// The stored text round-trips and needs both halves.
80+
/// The stored text round-trips and needs both halves; a half a newer release
81+
/// wrote reads as `other`.
8182
#[test]
8283
fn user_agent_family_text_round_trips() {
8384
let family = UserAgentFamily {
@@ -87,5 +88,11 @@ fn user_agent_family_text_round_trips() {
8788
assert_eq!(family.to_string(), "firefox/linux");
8889
assert_eq!("firefox/linux".parse(), Ok(family));
8990
assert!("firefox".parse::<UserAgentFamily>().is_err());
90-
assert!("firefox/beos".parse::<UserAgentFamily>().is_err());
91+
assert_eq!(
92+
"samsung/harmony_os".parse(),
93+
Ok(UserAgentFamily {
94+
browser: Browser::Other,
95+
platform: Platform::Other,
96+
})
97+
);
9198
}

‎crates/common/src/lib.rs‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,26 @@ macro_rules! __str_enum_sqlx {
101101
}
102102

103103
/// Declares a documented, closed string vocabulary with serde and parsing support,
104-
/// plus `SQLx` text decoding when the `sqlx` feature is on.
104+
/// plus `SQLx` text decoding when the `sqlx` feature is on. Unknown spellings are
105+
/// rejected, unless an `else` variant follows the enum: then they read as it, for
106+
/// labels a newer release may extend that older ones can show coarsely.
107+
///
108+
/// ```
109+
/// piquel_common::str_enum! {
110+
/// /// A coarse label.
111+
/// pub enum Shade {
112+
/// /// Light.
113+
/// Light = "light",
114+
/// /// Anything else.
115+
/// Other = "other",
116+
/// } else Other
117+
/// }
118+
///
119+
/// assert_eq!("teal".parse(), Ok(Shade::Other));
120+
/// ```
105121
#[macro_export]
106122
macro_rules! str_enum {
107-
($(#[$meta:meta])* $vis:vis enum $name:ident { $($(#[$variant_meta:meta])* $variant:ident = $value:literal),+ $(,)? }) => {
123+
($(#[$meta:meta])* $vis:vis enum $name:ident { $($(#[$variant_meta:meta])* $variant:ident = $value:literal),+ $(,)? } $(else $fallback:ident)?) => {
108124
$(#[$meta])*
109125
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
110126
$vis enum $name { $($(#[$variant_meta])* $variant),+ }
@@ -121,22 +137,24 @@ macro_rules! str_enum {
121137
}
122138
impl ::std::str::FromStr for $name {
123139
type Err = $crate::VocabularyError;
124-
/// Parses the stable spelling and rejects values outside the closed vocabulary.
125-
fn from_str(value: &str) -> Result<Self, Self::Err> { match value { $($value => Ok(Self::$variant),)+ _ => Err($crate::VocabularyError { vocabulary: stringify!($name) }) } }
140+
/// Parses the stable spelling; an unknown one is rejected or reads as the `else` variant.
141+
fn from_str(value: &str) -> Result<Self, Self::Err> { match value { $($value => Ok(Self::$variant),)+ _ => $crate::str_enum!(@unknown $name $($fallback)?) } }
126142
}
127143
impl $crate::__serde::Serialize for $name {
128144
/// Writes the stable vocabulary spelling to its wire representation.
129145
fn serialize<S: $crate::__serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_str(self.as_str()) }
130146
}
131147
impl<'de> $crate::__serde::Deserialize<'de> for $name {
132-
/// Parses the wire spelling and rejects values outside the closed vocabulary.
148+
/// Parses the wire spelling as `FromStr` does.
133149
fn deserialize<D: $crate::__serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
134150
let value = <String as $crate::__serde::Deserialize>::deserialize(deserializer)?;
135151
value.parse().map_err($crate::__serde::de::Error::custom)
136152
}
137153
}
138154
$crate::__str_enum_sqlx!($name);
139155
};
156+
(@unknown $name:ident) => { Err($crate::VocabularyError { vocabulary: stringify!($name) }) };
157+
(@unknown $name:ident $fallback:ident) => { Ok(Self::$fallback) };
140158
(@count $($variant:ident),+) => { <[()]>::len(&[$($crate::str_enum!(@unit $variant)),+]) };
141159
(@unit $variant:ident) => { () };
142160
}

crates/database/.sqlx/query-d1547c3d68fef10266ba53c54d66d3e6b7a7a619e19d2f73ab3452843635db55.json renamed to crates/database/.sqlx/query-7532a32586493759c170937190720ca68c22afd0e33e0978124c3aaaa1285d1e.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/src/repositories/sessions.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -300,10 +300,11 @@ impl SessionRepository<'_> {
300300
)
301301
}
302302

303-
/// Revokes the `scope` sessions of `user_id`, with the refresh token families
304-
/// issued from them, and returns the IDs of the sessions it revoked, so the
305-
/// caller can record each revocation. Sessions of other accounts are never
306-
/// touched, whatever the scope names. This is the only way sessions end early;
303+
/// Revokes the active `scope` sessions of `user_id`, with the refresh token
304+
/// families issued from them, and returns the IDs of the sessions it revoked, so
305+
/// the caller can record each revocation. Sessions of other accounts are never
306+
/// touched, whatever the scope names, and expired ones are already over: no
307+
/// refresh family of theirs rotates. This is the only way sessions end early;
307308
/// callers run it in a transaction, so both updates commit together.
308309
///
309310
/// The families are revoked by a second statement: a code exchange that held a
@@ -327,6 +328,7 @@ impl SessionRepository<'_> {
327328
SET revoked_at = now(), passkey_confirmed_at = NULL
328329
WHERE user_id = $1
329330
AND revoked_at IS NULL
331+
AND expires_at > now()
330332
AND ($2::uuid IS NULL OR id = $2)
331333
AND ($3::uuid IS NULL OR id <> $3)
332334
RETURNING id AS "id: SessionId""#,

‎crates/database/src/repositories/tokens/tests.rs‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ async fn code_replay_by_another_client_revokes_nothing() {
376376
}
377377

378378
/// Revoking a session ends the refresh families issued from it, and never touches
379-
/// another account's session, whatever the scope names.
379+
/// another account's session, whatever the scope names, or an expired one.
380380
#[tokio::test]
381381
#[ignore = "requires a disposable TEST_DATABASE_URL"]
382382
async fn session_revocation_ends_its_families_and_only_its_owners() {
@@ -385,6 +385,18 @@ async fn session_revocation_ends_its_families_and_only_its_owners() {
385385
let mut tokens = TokenRepository::from_pool(&pool);
386386
let mine = Grant::new(&pool, &client).await;
387387
let theirs = Grant::new(&pool, &client).await;
388+
let expired = SessionId::new();
389+
sqlx::query(
390+
"INSERT INTO sessions (
391+
id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at
392+
) VALUES ($1, $2, '[]', now() - interval '2 hours', now() - interval '1 hour',
393+
now() - interval '2 hours')",
394+
)
395+
.bind(expired.as_uuid())
396+
.bind(mine.user.as_uuid())
397+
.execute(&pool)
398+
.await
399+
.expect("expired session");
388400
mine.family(&mut tokens, &client).await;
389401
theirs.family(&mut tokens, &client).await;
390402
let family_revoked = |grant: &Grant| {
@@ -399,6 +411,7 @@ async fn session_revocation_ends_its_families_and_only_its_owners() {
399411
for scope in [SessionScope::One(theirs.session), SessionScope::All] {
400412
let revoked = sessions.revoke(mine.user, scope).await.expect("revoke");
401413
assert!(!revoked.contains(&theirs.session), "{scope:?}");
414+
assert!(!revoked.contains(&expired), "{scope:?}");
402415
}
403416
assert!(
404417
sessions

‎docs/architecture/database-crate.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,8 @@ newest first.
228228
`SessionRepository::revoke(user_id, scope)` is the only way a session ends early.
229229
`SessionScope` names one session, every other session or all of them, and the
230230
query always filters on `user_id`, so no scope reaches another account's session.
231+
It skips expired sessions, which are already over, so the count it returns is what
232+
the account's session list showed.
231233
It revokes the refresh token families issued from the revoked sessions in a
232234
second statement of the same transaction, whose snapshot also sees a family a
233235
concurrent code exchange committed while the first one waited, and returns the revoked IDs, so the caller records one

‎docs/architecture/rust-conventions.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,8 @@ Keep separate variants when they identify different failures; merge indistinguis
105105
## Vocabulary and persistence
106106

107107
Use `str_enum!` for closed stored or wire strings and serde enums for JSON-only
108-
choices. Match domain enums exhaustively; use their `ALL` list rather than repeating
108+
choices. Give it an `else` variant, as `Browser` and `Platform` have, for labels a
109+
newer release may extend that older ones can read coarsely. Match domain enums exhaustively; use their `ALL` list rather than repeating
109110
variants. Limits and lifetimes are named constants. Preserve existing wire spellings.
110111

111112
Shared authentication vocabulary, JWT/JWK vocabulary and wire types live in

0 commit comments

Comments
 (0)