Remove the appservice feature from matrix-sdk, matrix-sdk-test

This commit is contained in:
Jonas Platte
2023-09-05 15:12:50 +02:00
committed by Jonas Platte
parent 7d674b39aa
commit 2d47aecd37
10 changed files with 20 additions and 229 deletions

13
Cargo.lock generated
View File

@@ -4847,7 +4847,6 @@ dependencies = [
"assign",
"js_int",
"js_option",
"ruma-appservice-api",
"ruma-client-api",
"ruma-common",
"ruma-events",
@@ -4856,18 +4855,6 @@ dependencies = [
"ruma-push-gateway-api",
]
[[package]]
name = "ruma-appservice-api"
version = "0.8.1"
source = "git+https://github.com/ruma/ruma?rev=f0c458dcfa6a27f4945cab520fd9dabc366080bf#f0c458dcfa6a27f4945cab520fd9dabc366080bf"
dependencies = [
"js_int",
"ruma-common",
"ruma-events",
"serde",
"serde_json",
]
[[package]]
name = "ruma-client-api"
version = "0.16.2"

View File

@@ -38,7 +38,6 @@ native-tls = ["reqwest/native-tls"]
rustls-tls = ["reqwest/rustls-tls"]
socks = ["reqwest/socks"]
sso-login = ["dep:hyper", "dep:rand", "dep:tower"]
appservice = ["ruma/appservice-api-s"]
image-proc = ["dep:image"]
image-rayon = ["image-proc", "image?/jpeg_rayon"]

View File

@@ -77,7 +77,6 @@ pub struct ClientBuilder {
store_config: BuilderStoreConfig,
request_config: RequestConfig,
respect_login_well_known: bool,
appservice_mode: bool,
server_versions: Option<Box<[MatrixVersion]>>,
handle_refresh_tokens: bool,
base_client: Option<BaseClient>,
@@ -93,7 +92,6 @@ impl ClientBuilder {
store_config: BuilderStoreConfig::Custom(StoreConfig::default()),
request_config: Default::default(),
respect_login_well_known: true,
appservice_mode: false,
server_versions: None,
handle_refresh_tokens: false,
base_client: None,
@@ -270,33 +268,6 @@ impl ClientBuilder {
self
}
/// Puts the client into application service mode
///
/// This is low-level functionality. For an high-level API check the
/// `matrix_sdk_appservice` crate.
#[doc(hidden)]
#[cfg(feature = "appservice")]
pub fn appservice_mode(mut self) -> Self {
self.appservice_mode = true;
self
}
/// All outgoing http requests will have a GET query key-value appended with
/// `user_id` being the key and the `user_id` from the `Session` being
/// the value. This is called [identity assertion] in the
/// Matrix Application Service Spec.
///
/// Requests that don't require authentication might not do identity
/// assertion.
///
/// [identity assertion]: https://spec.matrix.org/unstable/application-service-api/#identity-assertion
#[doc(hidden)]
#[cfg(feature = "appservice")]
pub fn assert_identity(mut self) -> Self {
self.request_config.assert_identity = true;
self
}
/// Specify the Matrix versions supported by the homeserver manually, rather
/// than `build()` doing it using a `get_supported_versions` request.
///
@@ -421,7 +392,6 @@ impl ClientBuilder {
Some(RequestConfig::short_retry()),
homeserver,
None,
None,
&[MatrixVersion::V1_0],
Default::default(),
)
@@ -457,7 +427,6 @@ impl ClientBuilder {
http_client,
base_client,
self.server_versions,
self.appservice_mode,
self.respect_login_well_known,
self.handle_refresh_tokens,
));

View File

@@ -45,8 +45,6 @@ use matrix_sdk_base::{
use matrix_sdk_common::instant::Instant;
#[cfg(feature = "experimental-sliding-sync")]
use ruma::api::client::error::ErrorKind;
#[cfg(feature = "appservice")]
use ruma::TransactionId;
use ruma::{
api::{
client::{
@@ -185,10 +183,6 @@ pub(crate) struct ClientInner {
notification_handlers: RwLock<Vec<NotificationHandlerFn>>,
pub(crate) room_update_channels: StdMutex<BTreeMap<OwnedRoomId, broadcast::Sender<RoomUpdate>>>,
pub(crate) sync_gap_broadcast_txs: StdMutex<BTreeMap<OwnedRoomId, Observable<()>>>,
/// Whether the client should operate in application service style mode.
/// This is low-level functionality. For an high-level API check the
/// `matrix_sdk_appservice` crate.
pub(crate) appservice_mode: bool,
/// Whether the client should update its homeserver URL with the discovery
/// information present in the login response.
respect_login_well_known: bool,
@@ -243,7 +237,6 @@ impl ClientInner {
http_client: HttpClient,
base_client: BaseClient,
server_versions: Option<Box<[MatrixVersion]>>,
appservice_mode: bool,
respect_login_well_known: bool,
handle_refresh_tokens: bool,
) -> Self {
@@ -268,7 +261,6 @@ impl ClientInner {
notification_handlers: Default::default(),
room_update_channels: Default::default(),
sync_gap_broadcast_txs: Default::default(),
appservice_mode,
respect_login_well_known,
sync_beat: event_listener::Event::new(),
handle_refresh_tokens,
@@ -355,50 +347,6 @@ impl Client {
Ok(res.capabilities)
}
/// Process a [transaction] received from the homeserver which has been
/// converted into a sync response.
///
/// # Arguments
///
/// * `transaction_id` - The id of the transaction, used to guard against
/// the same transaction being sent twice. This guarding currently isn't
/// implemented.
/// * `sync_response` - The sync response converted from a transaction
/// received from the homeserver.
///
/// [transaction]: https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid
#[cfg(feature = "appservice")]
pub async fn receive_transaction(
&self,
transaction_id: &TransactionId,
sync_response: sync_events::v3::Response,
) -> Result<()> {
const TXN_ID_KEY: &[u8] = b"appservice.txn_id";
let store = self.store();
let store_tokens = store.get_custom_value(TXN_ID_KEY).await?;
let mut txn_id_bytes = transaction_id.as_bytes().to_vec();
if let Some(mut store_tokens) = store_tokens {
// The data is separated by a NULL byte.
let mut store_tokens_split = store_tokens.split(|x| *x == b'\0');
if store_tokens_split.any(|x| x == transaction_id.as_bytes()) {
// We already encountered this transaction id before, so we exit early instead
// of processing further.
//
// Spec: https://spec.matrix.org/v1.3/application-service-api/#pushing-events
return Ok(());
}
store_tokens.push(b'\0');
store_tokens.append(&mut txn_id_bytes);
self.store().set_custom_value(TXN_ID_KEY, store_tokens).await?;
} else {
self.store().set_custom_value(TXN_ID_KEY, txn_id_bytes).await?;
}
self.process_sync(sync_response).await?;
Ok(())
}
/// Get a copy of the default request config.
///
/// The default request config is what's used when sending requests if no
@@ -1422,7 +1370,6 @@ impl Client {
config,
homeserver,
access_token,
self.user_id(),
self.server_versions().await?,
send_progress,
)
@@ -1446,7 +1393,6 @@ impl Client {
None,
self.homeserver().await.to_string(),
None,
None,
&[MatrixVersion::V1_0],
Default::default(),
)
@@ -2056,7 +2002,6 @@ impl Client {
self.inner.http_client.clone(),
self.inner.base_client.clone_with_in_memory_state_store(),
self.inner.server_versions.get().cloned(),
self.inner.appservice_mode,
self.inner.respect_login_well_known,
self.inner.handle_refresh_tokens,
)),

View File

@@ -45,13 +45,12 @@ pub struct RequestConfig {
pub(crate) retry_limit: Option<u64>,
pub(crate) retry_timeout: Option<Duration>,
pub(crate) force_auth: bool,
pub(crate) assert_identity: bool,
}
#[cfg(not(tarpaulin_include))]
impl Debug for RequestConfig {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { timeout, retry_limit, retry_timeout, force_auth, assert_identity } = self;
let Self { timeout, retry_limit, retry_timeout, force_auth } = self;
let mut res = fmt.debug_struct("RequestConfig");
res.field("timeout", timeout)
@@ -61,9 +60,6 @@ impl Debug for RequestConfig {
if *force_auth {
res.field("force_auth", &true);
}
if *assert_identity {
res.field("assert_identity", &true);
}
res.finish()
}
@@ -76,7 +72,6 @@ impl Default for RequestConfig {
retry_limit: Default::default(),
retry_timeout: Default::default(),
force_auth: false,
assert_identity: false,
}
}
}

View File

@@ -25,12 +25,9 @@ use std::{
use bytes::{Bytes, BytesMut};
use bytesize::ByteSize;
use eyeball::SharedObservable;
use ruma::{
api::{
error::{FromHttpResponseError, IntoHttpError},
AuthScheme, MatrixVersion, OutgoingRequest, OutgoingRequestAppserviceExt, SendAccessToken,
},
UserId,
use ruma::api::{
error::{FromHttpResponseError, IntoHttpError},
AuthScheme, MatrixVersion, OutgoingRequest, SendAccessToken,
};
use tracing::{debug, field::debug, instrument, trace};
@@ -69,7 +66,6 @@ impl HttpClient {
config: RequestConfig,
homeserver: String,
access_token: Option<&str>,
user_id: Option<&UserId>,
server_versions: &[MatrixVersion],
) -> Result<http::Request<Bytes>, IntoHttpError>
where
@@ -77,53 +73,28 @@ impl HttpClient {
{
trace!(request_type = type_name::<R>(), "Serializing request");
// We can't assert the identity without a user_id.
let request = if let Some((access_token, user_id)) =
access_token.filter(|_| config.assert_identity).zip(user_id)
{
request.try_into_http_request_with_user_id::<BytesMut>(
&homeserver,
SendAccessToken::Always(access_token),
user_id,
server_versions,
)?
} else {
let send_access_token = match access_token {
Some(access_token) => {
if config.force_auth {
SendAccessToken::Always(access_token)
} else {
SendAccessToken::IfRequired(access_token)
}
let send_access_token = match access_token {
Some(access_token) => {
if config.force_auth {
SendAccessToken::Always(access_token)
} else {
SendAccessToken::IfRequired(access_token)
}
None => SendAccessToken::None,
};
request.try_into_http_request::<BytesMut>(
&homeserver,
send_access_token,
server_versions,
)?
}
None => SendAccessToken::None,
};
let request = request.map(|body| body.freeze());
let request = request
.try_into_http_request::<BytesMut>(&homeserver, send_access_token, server_versions)?
.map(|body| body.freeze());
Ok(request)
}
#[allow(clippy::too_many_arguments)]
#[instrument(
skip(self, access_token, config, request, user_id, send_progress),
fields(
config,
path,
user_id,
request_size,
request_body,
request_id,
status,
response_size,
)
skip(self, access_token, config, request, send_progress),
fields(config, path, request_size, request_body, request_id, status, response_size,)
)]
pub async fn send<R>(
&self,
@@ -131,7 +102,6 @@ impl HttpClient {
config: Option<RequestConfig>,
homeserver: String,
access_token: Option<&str>,
user_id: Option<&UserId>,
server_versions: &[MatrixVersion],
send_progress: SharedObservable<TransmissionProgress>,
) -> Result<R::IncomingResponse, HttpError>
@@ -154,25 +124,13 @@ impl HttpClient {
// why we record it here, instead of in the #[instrument] macro.
span.record("config", debug(config)).record("request_id", request_id);
// The user ID is only used if we're an app-service. Only log the user_id if
// it's `Some` and if assert_identity is set.
if config.assert_identity {
span.record("user_id", user_id.map(debug));
}
let auth_scheme = R::METADATA.authentication;
if !matches!(auth_scheme, AuthScheme::AccessToken | AuthScheme::None) {
return Err(HttpError::NotClientRequest);
}
let request = self.serialize_request(
request,
config,
homeserver,
access_token,
user_id,
server_versions,
)?;
let request =
self.serialize_request(request, config, homeserver, access_token, server_versions)?;
let request_size = ByteSize(request.body().len().try_into().unwrap_or(u64::MAX));
span.record("request_size", request_size.to_string_as(true));

View File

@@ -43,7 +43,6 @@ use tracing::{debug, info, instrument};
use crate::{
authentication::AuthData,
client::SessionChange,
config::RequestConfig,
error::{HttpError, HttpResult},
Client, Error, RefreshTokenError, Result,
};
@@ -535,14 +534,7 @@ impl MatrixAuth {
) -> HttpResult<register::v3::Response> {
let homeserver = self.client.homeserver().await;
info!("Registering to {homeserver}");
let config = if self.client.inner.appservice_mode {
Some(RequestConfig::short_retry().force_auth())
} else {
None
};
self.client.send(request, config).await
self.client.send(request, None).await
}
/// Log out the current user.

View File

@@ -15,9 +15,6 @@ version = "0.6.0"
test = false
doctest = false
[features]
appservice = []
[dependencies]
http = { workspace = true }
matrix-sdk-test-macros = { version = "0.3.0", path = "../matrix-sdk-test-macros" }

View File

@@ -1,49 +0,0 @@
use ruma::{events::AnyTimelineEvent, serde::Raw};
use serde_json::Value;
use crate::{event_builder::TimelineTestEvent, test_json};
/// Clones the given [`Value`] and adds a `room_id` to it
///
/// Adding the `room_id` conditionally with `cfg` directly to the lazy_static
/// test_json values is blocked by "experimental attributes on expressions, see
/// issue #15701 <https://github.com/rust-lang/rust/issues/15701> for more information"
pub fn value_with_room_id(value: &mut Value) {
let room_id = Value::try_from(test_json::DEFAULT_SYNC_ROOM_ID.to_string()).expect("room_id");
value.as_object_mut().expect("mutable test_json").insert("room_id".to_owned(), room_id);
}
/// The `TransactionBuilder` struct can be used to easily generate valid
/// incoming appservice transactions in json value format for testing.
///
/// Usage is similar to [`super::SyncResponseBuilder`]
#[derive(Debug, Default)]
pub struct TransactionBuilder {
events: Vec<Raw<AnyTimelineEvent>>,
}
impl TransactionBuilder {
pub fn new() -> Self {
Default::default()
}
/// Add a room event.
pub fn add_timeline_event(&mut self, event: TimelineTestEvent) -> &mut Self {
let mut val = event.into_json_value();
value_with_room_id(&mut val);
let event = serde_json::from_value(val).unwrap();
self.events.push(event);
self
}
/// Build the transaction as a serialized HTTP body
pub fn build_transaction(&self) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({ "events": self.events })).unwrap()
}
pub fn clear(&mut self) {
self.events.clear();
}
}

View File

@@ -3,8 +3,6 @@ pub use matrix_sdk_test_macros::async_test;
use ruma::api::{client::sync::sync_events::v3::Response as SyncResponse, IncomingResponse};
use serde_json::Value as JsonValue;
#[cfg(feature = "appservice")]
pub mod appservice;
mod event_builder;
pub mod notification_settings;
pub mod test_json;