chore(auth): prefix Session data structures with the auth kind

This commit is contained in:
Benjamin Bouvier
2023-09-14 15:15:36 +02:00
parent 7665b15c5a
commit b9b042ec4a
16 changed files with 68 additions and 68 deletions

View File

@@ -3,7 +3,7 @@ use std::sync::Arc;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use matrix_sdk::{
config::StoreConfig,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
Client, RoomInfo, RoomState, StateChanges,
};
use matrix_sdk_base::{store::MemoryStore, SessionMeta, StateStore as _};
@@ -46,7 +46,7 @@ pub fn restore_session(c: &mut Criterion) {
changes.add_room(RoomInfo::new(&room_id, RoomState::Invited));
}
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@somebody:example.com").to_owned(),
device_id: device_id!("DEVICE_ID").to_owned(),

View File

@@ -10,7 +10,7 @@ use matrix_sdk::{
ClientMetadata, ClientMetadataVerificationError, VerifiedClientMetadata,
},
},
FullSession, OidcAccountManagementAction,
OidcAccountManagementAction, OidcSession,
},
ruma::{
api::client::{
@@ -921,7 +921,7 @@ impl Session {
match auth_api {
// Build the session from the regular Matrix Auth Session.
AuthApi::Matrix(a) => {
let matrix_sdk::matrix_auth::Session {
let matrix_sdk::matrix_auth::MatrixSession {
meta: matrix_sdk::SessionMeta { user_id, device_id },
tokens:
matrix_sdk::matrix_auth::MatrixSessionTokens { access_token, refresh_token },
@@ -993,7 +993,7 @@ impl TryFrom<Session> for AuthSession {
} = value;
if let Some(oidc_data) = oidc_data {
// Create an OIDC FullSession.
// Create an OidcSession.
let oidc_data = serde_json::from_str::<OidcUnvalidatedSessionData>(&oidc_data)?
.validate()
.context("OIDC metadata validation failed.")?;
@@ -1016,7 +1016,7 @@ impl TryFrom<Session> for AuthSession {
issuer_info: oidc_data.issuer_info,
};
let session = FullSession {
let session = OidcSession {
credentials: ClientCredentials::None { client_id: oidc_data.client_id },
metadata: oidc_data.client_metadata,
user: user_session,
@@ -1025,7 +1025,7 @@ impl TryFrom<Session> for AuthSession {
Ok(AuthSession::Oidc(session))
} else {
// Create a regular Matrix Session.
let session = matrix_sdk::matrix_auth::Session {
let session = matrix_sdk::matrix_auth::MatrixSession {
meta: matrix_sdk::SessionMeta {
user_id: user_id.try_into()?,
device_id: device_id.into(),

View File

@@ -570,7 +570,7 @@ mod tests {
use futures_util::{pin_mut, StreamExt};
use matrix_sdk::{
config::RequestConfig,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
reqwest::Url,
Client, SlidingSyncMode,
};
@@ -583,7 +583,7 @@ mod tests {
use super::{Error, RoomListService, State, ALL_ROOMS_LIST_NAME};
async fn new_client() -> (Client, MockServer) {
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -14,7 +14,7 @@
use matrix_sdk::{
config::RequestConfig,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
Client, ClientBuilder,
};
use matrix_sdk_base::SessionMeta;
@@ -58,7 +58,7 @@ async fn no_retry_test_client() -> (Client, MockServer) {
}
async fn logged_in_client() -> (Client, MockServer) {
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -97,11 +97,11 @@ pub enum AuthApi {
#[non_exhaustive]
pub enum AuthSession {
/// A session using the native Matrix authentication API.
Matrix(matrix_auth::Session),
Matrix(matrix_auth::MatrixSession),
/// A session using the OpenID Connect API.
#[cfg(feature = "experimental-oidc")]
Oidc(oidc::FullSession),
Oidc(oidc::OidcSession),
}
impl AuthSession {
@@ -142,15 +142,15 @@ impl AuthSession {
}
}
impl From<matrix_auth::Session> for AuthSession {
fn from(session: matrix_auth::Session) -> Self {
impl From<matrix_auth::MatrixSession> for AuthSession {
fn from(session: matrix_auth::MatrixSession) -> Self {
Self::Matrix(session)
}
}
#[cfg(feature = "experimental-oidc")]
impl From<oidc::FullSession> for AuthSession {
fn from(session: oidc::FullSession) -> Self {
impl From<oidc::OidcSession> for AuthSession {
fn from(session: oidc::OidcSession) -> Self {
Self::Oidc(session)
}
}

View File

@@ -1070,7 +1070,7 @@ mod tests {
use crate::{
config::RequestConfig,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
test_utils::logged_in_client,
Client,
};
@@ -1199,7 +1199,7 @@ mod tests {
async fn test_generation_counter_invalidates_olm_machine() {
// Create two clients using the same sqlite database.
let sqlite_path = std::env::temp_dir().join("generation_counter_sqlite.db");
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),
@@ -1283,7 +1283,7 @@ mod tests {
// Create two clients using the same sqlite database.
let sqlite_path =
std::env::temp_dir().join("generation_counter_no_spurious_invalidations.db");
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -612,7 +612,7 @@ impl MatrixAuth {
/// refresh token for this session change.
///
/// This can be used with [`MatrixAuth::session()`] to persist the
/// [`Session`] when the tokens change.
/// [`MatrixSession`] when the tokens change.
///
/// After login, the tokens should only change if support for [refreshing
/// access tokens] has been enabled.
@@ -675,7 +675,7 @@ impl MatrixAuth {
/// ```no_run
/// use futures_util::StreamExt;
/// use matrix_sdk::Client;
/// # fn persist_session(_: &matrix_sdk::matrix_auth::Session) {};
/// # fn persist_session(_: &matrix_sdk::matrix_auth::MatrixSession) {};
/// # async {
/// let homeserver = "http://example.com";
/// let client = Client::builder()
@@ -723,10 +723,10 @@ impl MatrixAuth {
///
/// Can be used with [`MatrixAuth::restore_session`] to restore a previously
/// logged-in session.
pub fn session(&self) -> Option<Session> {
pub fn session(&self) -> Option<MatrixSession> {
let meta = self.client.session_meta()?;
let tokens = self.session_tokens()?;
Some(Session { meta: meta.to_owned(), tokens })
Some(MatrixSession { meta: meta.to_owned(), tokens })
}
/// Restore a previously logged in session.
@@ -750,7 +750,7 @@ impl MatrixAuth {
///
/// ```no_run
/// use matrix_sdk::{
/// matrix_auth::{Session, SessionTokens},
/// matrix_auth::{MatrixSession, MatrixSessionTokens},
/// ruma::{device_id, user_id},
/// Client, SessionMeta,
/// };
@@ -760,12 +760,12 @@ impl MatrixAuth {
/// let homeserver = Url::parse("http://example.com")?;
/// let client = Client::new(homeserver).await?;
///
/// let session = Session {
/// let session = MatrixSession {
/// meta: SessionMeta {
/// user_id: user_id!("@example:localhost").to_owned(),
/// device_id: device_id!("MYDEVICEID").to_owned(),
/// },
/// tokens: SessionTokens {
/// tokens: MatrixSessionTokens {
/// access_token: "My-Token".to_owned(),
/// refresh_token: None,
/// },
@@ -775,7 +775,7 @@ impl MatrixAuth {
/// # anyhow::Ok(()) };
/// ```
///
/// The `Session` object can also be created from the response the
/// The `MatrixSession` object can also be created from the response the
/// [`LoginBuilder::send()`] method returns:
///
/// ```no_run
@@ -789,7 +789,7 @@ impl MatrixAuth {
///
/// let response = auth.login_username("example", "my-password").send().await?;
///
/// // Persist the `Session` so it can later be used to restore the login.
/// // Persist the `MatrixSession` so it can later be used to restore the login.
///
/// auth.restore_session((&response).into()).await?;
/// # anyhow::Ok(()) };
@@ -798,7 +798,7 @@ impl MatrixAuth {
/// [`login`]: #method.login
/// [`LoginBuilder::send()`]: crate::matrix_auth::LoginBuilder::send
#[instrument(skip_all)]
pub async fn restore_session(&self, session: Session) -> Result<()> {
pub async fn restore_session(&self, session: MatrixSession) -> Result<()> {
debug!("Restoring Matrix auth session");
self.set_session(session).await?;
debug!("Done restoring Matrix auth session");
@@ -822,7 +822,7 @@ impl MatrixAuth {
Ok(())
}
async fn set_session(&self, session: Session) -> Result<()> {
async fn set_session(&self, session: MatrixSession) -> Result<()> {
self.set_session_tokens(session.tokens);
self.client.base_client().set_session_meta(session.meta).await?;
@@ -836,17 +836,17 @@ impl MatrixAuth {
///
/// ```
/// use matrix_sdk::{
/// matrix_auth::{Session, SessionTokens},
/// matrix_auth::{MatrixSession, MatrixSessionTokens},
/// SessionMeta,
/// };
/// use ruma::{device_id, user_id};
///
/// let session = Session {
/// let session = MatrixSession {
/// meta: SessionMeta {
/// user_id: user_id!("@example:localhost").to_owned(),
/// device_id: device_id!("MYDEVICEID").to_owned(),
/// },
/// tokens: SessionTokens {
/// tokens: MatrixSessionTokens {
/// access_token: "My-Token".to_owned(),
/// refresh_token: None,
/// },
@@ -855,7 +855,7 @@ impl MatrixAuth {
/// assert_eq!(session.meta.device_id.as_str(), "MYDEVICEID");
/// ```
#[derive(Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Session {
pub struct MatrixSession {
/// The Matrix user session info.
#[serde(flatten)]
pub meta: SessionMeta,
@@ -866,13 +866,13 @@ pub struct Session {
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for Session {
impl fmt::Debug for MatrixSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session").field("meta", &self.meta).finish_non_exhaustive()
f.debug_struct("MatrixSession").field("meta", &self.meta).finish_non_exhaustive()
}
}
impl From<&login::v3::Response> for Session {
impl From<&login::v3::Response> for MatrixSession {
fn from(response: &login::v3::Response) -> Self {
let login::v3::Response { user_id, access_token, device_id, refresh_token, .. } = response;
Self {
@@ -901,7 +901,7 @@ pub struct MatrixSessionTokens {
}
impl MatrixSessionTokens {
/// Update this `SessionTokens` with the values found in the given
/// Update this `MatrixSessionTokens` with the values found in the given
/// response.
pub fn update_with_refresh_response(&mut self, response: &refresh_token::v3::Response) {
self.access_token = response.access_token.clone();

View File

@@ -253,13 +253,13 @@ mod tests {
use super::compute_session_hash;
use crate::{
oidc::{FullSession, OidcSessionTokens, UserSession},
oidc::{OidcSession, OidcSessionTokens, UserSession},
test_utils::test_client_builder,
Error,
};
fn fake_session(tokens: OidcSessionTokens) -> FullSession {
FullSession {
fn fake_session(tokens: OidcSessionTokens) -> OidcSession {
OidcSession {
credentials: ClientCredentials::None { client_id: "test_client_id".to_owned() },
metadata: ClientMetadata {
redirect_uris: Some(vec![]), // empty vector is ok lol

View File

@@ -503,7 +503,7 @@ impl Oidc {
/// ```no_run
/// use futures_util::StreamExt;
/// use matrix_sdk::Client;
/// # fn persist_session(_: &matrix_sdk::oidc::FullSession) {}
/// # fn persist_session(_: &matrix_sdk::oidc::OidcSession) {}
/// # _ = async {
/// let homeserver = "http://example.com";
/// let client = Client::builder()
@@ -574,10 +574,10 @@ impl Oidc {
///
/// Returns `None` if the client was not logged in with the OpenID Connect
/// API.
pub fn full_session(&self) -> Option<FullSession> {
pub fn full_session(&self) -> Option<OidcSession> {
let user = self.user_session()?;
let data = self.data()?;
Some(FullSession {
Some(OidcSession {
credentials: data.credentials.clone(),
metadata: data.metadata.clone(),
user,
@@ -730,8 +730,8 @@ impl Oidc {
/// # Panic
///
/// Panics if authentication data was already set.
pub async fn restore_session(&self, session: FullSession) -> Result<()> {
let FullSession { credentials, metadata, user: UserSession { meta, tokens, issuer_info } } =
pub async fn restore_session(&self, session: OidcSession) -> Result<()> {
let OidcSession { credentials, metadata, user: UserSession { meta, tokens, issuer_info } } =
session;
let data = OidcAuthData {
@@ -1313,7 +1313,7 @@ impl Oidc {
/// A full session for the OpenID Connect API.
#[derive(Debug, Clone)]
pub struct FullSession {
pub struct OidcSession {
/// The credentials obtained after registration.
pub credentials: ClientCredentials,
@@ -1544,7 +1544,7 @@ mod tests {
use url::Url;
use crate::{
oidc::{FullSession, OidcAccountManagementAction, OidcSessionTokens, UserSession},
oidc::{OidcAccountManagementAction, OidcSession, OidcSessionTokens, UserSession},
ClientBuilder,
};
@@ -1555,7 +1555,7 @@ mod tests {
let client = builder.build().await.unwrap();
client
.restore_session(FullSession {
.restore_session(OidcSession {
credentials: ClientCredentials::None { client_id: "client_id".to_owned() },
metadata: ClientMetadata {
redirect_uris: Some(vec![Url::parse("https://example.com/login").unwrap()]),

View File

@@ -2486,7 +2486,7 @@ mod tests {
use crate::{
config::RequestConfig,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
Client,
};
@@ -2494,7 +2494,7 @@ mod tests {
#[async_test]
async fn test_cache_invalidation_while_encrypt() {
let sqlite_path = std::env::temp_dir().join("cache_invalidation_while_encrypt.db");
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -7,7 +7,7 @@ use ruma::{api::MatrixVersion, device_id, user_id};
use crate::{
config::RequestConfig,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
Client, ClientBuilder,
};
@@ -25,7 +25,7 @@ pub(crate) async fn no_retry_test_client(homeserver_url: Option<String>) -> Clie
}
pub(crate) async fn logged_in_client(homeserver_url: Option<String>) -> Client {
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -3,7 +3,7 @@
use matrix_sdk::{
config::{RequestConfig, SyncSettings},
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
Client, ClientBuilder,
};
use matrix_sdk_base::SessionMeta;
@@ -45,7 +45,7 @@ async fn no_retry_test_client() -> (Client, MockServer) {
}
async fn logged_in_client() -> (Client, MockServer) {
let session = Session {
let session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -1,6 +1,6 @@
use assert_matches::assert_matches;
use matrix_sdk::{
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
AuthApi, AuthSession, RumaApiError,
};
use matrix_sdk_base::SessionMeta;
@@ -262,7 +262,7 @@ fn deserialize_session() {
"user_id": "@user:localhost",
"device_id": "EFGHIJ",
});
let session: Session = from_json_value(json).unwrap();
let session: MatrixSession = from_json_value(json).unwrap();
assert_eq!(session.tokens.access_token, "abcd");
assert_eq!(session.meta.user_id, "@user:localhost");
assert_eq!(session.meta.device_id, "EFGHIJ");
@@ -275,7 +275,7 @@ fn deserialize_session() {
"user_id": "@user:localhost",
"device_id": "EFGHIJ",
});
let session: Session = from_json_value(json).unwrap();
let session: MatrixSession = from_json_value(json).unwrap();
assert_eq!(session.tokens.access_token, "abcd");
assert_eq!(session.meta.user_id, "@user:localhost");
assert_eq!(session.meta.device_id, "EFGHIJ");
@@ -285,7 +285,7 @@ fn deserialize_session() {
#[test]
fn serialize_session() {
// Without refresh token.
let mut session = Session {
let mut session = MatrixSession {
meta: SessionMeta {
user_id: user_id!("@user:localhost").to_owned(),
device_id: device_id!("EFGHIJ").to_owned(),

View File

@@ -9,7 +9,7 @@ use futures_util::StreamExt;
use matrix_sdk::{
config::RequestConfig,
executor::spawn,
matrix_auth::{MatrixSessionTokens, Session},
matrix_auth::{MatrixSession, MatrixSessionTokens},
HttpError, RefreshTokenError, SessionChange,
};
use matrix_sdk_base::SessionMeta;
@@ -30,8 +30,8 @@ use wiremock::{
use crate::{logged_in_client, no_retry_test_client, test_client_builder};
fn session() -> Session {
Session {
fn session() -> MatrixSession {
MatrixSession {
meta: SessionMeta {
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("DEVICEID").to_owned(),

View File

@@ -35,8 +35,8 @@ use matrix_sdk::{
requests::GrantType,
scope::{Scope, ScopeToken},
},
AuthorizationCode, AuthorizationResponse, FullSession, OidcAccountManagementAction,
OidcAuthorizationData, UserSession,
AuthorizationCode, AuthorizationResponse, OidcAccountManagementAction,
OidcAuthorizationData, OidcSession, UserSession,
},
room::Room,
ruma::{
@@ -287,7 +287,7 @@ impl OidcCli {
println!("Restoring session for {}", user_session.meta.user_id);
let session = FullSession {
let session = OidcSession {
credentials: ClientCredentials::None { client_id: client_credentials.client_id },
metadata: client_metadata(),
user: user_session,

View File

@@ -5,7 +5,7 @@ use std::{
use matrix_sdk::{
config::SyncSettings,
matrix_auth::Session,
matrix_auth::MatrixSession,
ruma::{
api::client::filter::FilterDefinition,
events::room::message::{MessageType, OriginalSyncRoomMessageEvent},
@@ -36,7 +36,7 @@ struct FullSession {
client_session: ClientSession,
/// The Matrix user session.
user_session: Session,
user_session: MatrixSession,
/// The latest sync token.
///