mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-16 13:37:34 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dda4bdc367 | ||
|
|
2a753e612e | ||
|
|
78db465556 | ||
|
|
48d4bd60cb | ||
|
|
9c2cec78e0 | ||
|
|
437bf0c3e6 | ||
|
|
372e956286 | ||
|
|
121652fa81 | ||
|
|
13bd60dda9 | ||
|
|
a535449f15 | ||
|
|
7e3022f6ae | ||
|
|
c7dc06c693 | ||
|
|
52562c4227 | ||
|
|
e9d0737e50 | ||
|
|
005ee45feb | ||
|
|
46f71d55f7 |
No files matched your search
@@ -7,7 +7,7 @@ runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install sccache
|
||||
uses: https://git.tomfos.tr/tom/sccache-action@v1
|
||||
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
|
||||
- name: Configure sccache
|
||||
uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
|
||||
with:
|
||||
|
||||
@@ -29,7 +29,7 @@ runs:
|
||||
steps:
|
||||
- name: Detect runner OS
|
||||
id: runner-os
|
||||
uses: https://git.tomfos.tr/actions/detect-versions@v1
|
||||
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
|
||||
|
||||
- name: Configure cross-compilation architecture
|
||||
if: inputs.dpkg-arch != ''
|
||||
|
||||
@@ -39,7 +39,7 @@ runs:
|
||||
steps:
|
||||
- name: Detect runner OS
|
||||
id: runner-os
|
||||
uses: https://git.tomfos.tr/actions/detect-versions@v1
|
||||
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
|
||||
|
||||
- name: Configure Cargo environment
|
||||
shell: bash
|
||||
@@ -147,7 +147,7 @@ runs:
|
||||
run: echo "::group::📦 Restoring build cache"
|
||||
|
||||
- name: Setup sccache
|
||||
uses: https://git.tomfos.tr/tom/sccache-action@v1
|
||||
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
|
||||
|
||||
- name: End build cache restore group
|
||||
shell: bash
|
||||
|
||||
@@ -37,9 +37,9 @@ creds:
|
||||
- registry: forgejo.ellis.link
|
||||
user: "{{env \"BUILTIN_REGISTRY_USER\"}}"
|
||||
pass: "{{env \"BUILTIN_REGISTRY_PASSWORD\"}}"
|
||||
- registry: registry.gitlab.com
|
||||
user: "{{env \"GITLAB_USERNAME\"}}"
|
||||
pass: "{{env \"GITLAB_TOKEN\"}}"
|
||||
# - registry: registry.gitlab.com
|
||||
# user: "{{env \"GITLAB_USERNAME\"}}"
|
||||
# pass: "{{env \"GITLAB_TOKEN\"}}"
|
||||
- registry: git.nexy7574.co.uk
|
||||
user: "{{env \"N7574_GIT_USERNAME\"}}"
|
||||
pass: "{{env \"N7574_GIT_TOKEN\"}}"
|
||||
@@ -58,10 +58,10 @@ defaults:
|
||||
|
||||
# Sync configuration - each registry gets different image sets
|
||||
sync:
|
||||
- source: *source
|
||||
target: registry.gitlab.com/continuwuity/continuwuity
|
||||
type: repository
|
||||
<<: *tags-main
|
||||
#- source: *source
|
||||
# target: registry.gitlab.com/continuwuity/continuwuity
|
||||
# type: repository
|
||||
# <<: *tags-main
|
||||
- source: *source
|
||||
target: ghcr.io/continuwuity/continuwuity
|
||||
type: repository
|
||||
|
||||
@@ -4,11 +4,6 @@ on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
auto-label:
|
||||
name: Apply labels based on changed files
|
||||
|
||||
@@ -60,7 +60,7 @@ jobs:
|
||||
cargo-debian-${{ steps.debian-version.outputs.distribution }}-${{ matrix.arch }}-
|
||||
|
||||
- name: Setup sccache
|
||||
uses: https://git.tomfos.tr/tom/sccache-action@v1
|
||||
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
|
||||
|
||||
- name: Configure sccache environment
|
||||
run: |
|
||||
|
||||
@@ -54,8 +54,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build
|
||||
permissions:
|
||||
contents: write
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
steps:
|
||||
- name: Download binary artifacts
|
||||
|
||||
@@ -4,11 +4,6 @@ on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
check-changelog:
|
||||
name: Check changelog is added
|
||||
|
||||
@@ -28,13 +28,13 @@ jobs:
|
||||
|
||||
- name: Detect runner environment
|
||||
id: runner-env
|
||||
uses: https://git.tomfos.tr/actions/detect-versions@v1
|
||||
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20'
|
||||
uses: https://github.com/actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: 24
|
||||
node-version: 26
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||
|
||||
@@ -7,10 +7,6 @@ on:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
jobs:
|
||||
fast-checks:
|
||||
name: Pre-commit & Formatting
|
||||
|
||||
@@ -31,11 +31,6 @@ jobs:
|
||||
build-release:
|
||||
name: "Build ${{ matrix.slug }} (release)"
|
||||
runs-on: dind
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -84,6 +79,7 @@ jobs:
|
||||
outputs: |
|
||||
${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }}
|
||||
type=local,dest=/tmp/binaries
|
||||
pull: true # Base images were becoming out of date
|
||||
env:
|
||||
SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }}
|
||||
- name: Upload Docker artifacts
|
||||
@@ -117,11 +113,6 @@ jobs:
|
||||
name: "Build ${{ matrix.slug }} (max-perf)"
|
||||
runs-on: dind
|
||||
needs: build-release
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -172,6 +163,7 @@ jobs:
|
||||
outputs: |
|
||||
${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }}
|
||||
type=local,dest=/tmp/binaries
|
||||
pull: true # Base images were becoming out of date
|
||||
env:
|
||||
SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }}
|
||||
- name: Upload max-perf Docker artifacts
|
||||
@@ -207,8 +199,6 @@ jobs:
|
||||
needs:
|
||||
- build-release
|
||||
- build-maxperf
|
||||
permissions:
|
||||
contents: write
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
steps:
|
||||
- name: Download binary artifacts
|
||||
|
||||
@@ -1,3 +1,24 @@
|
||||
# Continuwuity v26.9.4 (2026-11-14)
|
||||
|
||||
No significant changes.
|
||||
|
||||
|
||||
# Continuwuity v26.9.3 (2026-11-10)
|
||||
|
||||
No significant changes.
|
||||
|
||||
|
||||
# Continuwuity v26.9.2 (2026-11-10)
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- SEC15, reported by @stratself (SEC15)
|
||||
- SEC31, reported by @tulir (SEC31)
|
||||
- SEC34, reported by @jade (SEC34)
|
||||
- SEC36, reported by @nex (SEC36)
|
||||
- SEC39, reported by @Henry-Hiles (SEC39)
|
||||
|
||||
|
||||
# Continuwuity v26.9.1 (2026-09-28)
|
||||
|
||||
## Features
|
||||
|
||||
Generated
+12
-12
@@ -896,7 +896,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"clap",
|
||||
@@ -934,7 +934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_admin"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"conduwuit_api",
|
||||
@@ -959,7 +959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_api"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.23.1",
|
||||
@@ -992,7 +992,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_build_metadata"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"built",
|
||||
"cargo_metadata",
|
||||
@@ -1000,7 +1000,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_core"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"arrayvec",
|
||||
@@ -1065,7 +1065,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_database"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"conduwuit_core",
|
||||
@@ -1086,7 +1086,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_macros"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"itertools 0.15.0",
|
||||
"proc-macro2",
|
||||
@@ -1096,7 +1096,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_router"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"axum-server",
|
||||
@@ -1132,7 +1132,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_service"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"askama",
|
||||
"assign",
|
||||
@@ -1187,7 +1187,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "conduwuit_web"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"askama",
|
||||
"async-trait",
|
||||
@@ -5161,7 +5161,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruminuwuity"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"assign",
|
||||
"http",
|
||||
@@ -7301,7 +7301,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
dependencies = [
|
||||
"askama",
|
||||
"cargo_metadata",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ license = "Apache-2.0"
|
||||
# See also `rust-toolchain.toml`
|
||||
readme = "README.md"
|
||||
repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
|
||||
version = "26.9.1"
|
||||
version = "26.9.4"
|
||||
|
||||
[workspace.metadata.crane]
|
||||
name = "conduwuit"
|
||||
|
||||
+18
-3
@@ -523,7 +523,22 @@ where
|
||||
for (server, response) in futures {
|
||||
match response {
|
||||
| Ok(response) => {
|
||||
for (user, master_key) in response.master_keys {
|
||||
let is_wanted = |user_id: &UserId| {
|
||||
user_id.server_name() == server && device_keys_input.contains_key(user_id)
|
||||
};
|
||||
let filtered_master_keys = response
|
||||
.master_keys
|
||||
.into_iter()
|
||||
.filter(|(user_id, _)| is_wanted(user_id));
|
||||
let filtered_self_signing_keys = response
|
||||
.self_signing_keys
|
||||
.into_iter()
|
||||
.filter(|(user_id, _)| is_wanted(user_id));
|
||||
let filtered_device_keys = response
|
||||
.device_keys
|
||||
.into_iter()
|
||||
.filter(|(user_id, _)| is_wanted(user_id));
|
||||
for (user, master_key) in filtered_master_keys {
|
||||
let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?;
|
||||
|
||||
if let Ok(our_master_key) = services
|
||||
@@ -549,8 +564,8 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
self_signing_keys.extend(response.self_signing_keys);
|
||||
device_keys.extend(response.device_keys);
|
||||
self_signing_keys.extend(filtered_self_signing_keys);
|
||||
device_keys.extend(filtered_device_keys);
|
||||
},
|
||||
| Err(e) => {
|
||||
failures.insert(server.to_string(), json!({ "error": e.to_string() }));
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) async fn get_room_event_route(
|
||||
services.rooms.state_accessor.is_world_readable(room_id)
|
||||
);
|
||||
if !joined && !world_readable {
|
||||
return Err!(Request(NotFound("Event {} not found.", event_id)));
|
||||
return Err!(Request(NotFound("Event {event_id} not found.")));
|
||||
}
|
||||
|
||||
services
|
||||
@@ -32,10 +32,15 @@ pub(crate) async fn get_room_event_route(
|
||||
.timeline
|
||||
.get_remote_pdu(room_id, event_id)
|
||||
.await
|
||||
.map_err(|_| err!(Request(NotFound("Event {} not found.", event_id))))?
|
||||
.map_err(|_| err!(Request(NotFound("Event {event_id} not found."))))?
|
||||
},
|
||||
| Err(e) => return Err(e),
|
||||
};
|
||||
if !event.room_id_or_hash().eq(room_id) {
|
||||
// Return not found instead of invalid param to avoid revealing the
|
||||
// existence of events the user might not be allowed to know about.
|
||||
return Err!(Request(NotFound("Event {event_id} not found.")));
|
||||
}
|
||||
|
||||
// NOTE: checked after fetching, as visibility of an unknown event cannot
|
||||
// be determined (user_can_see_event returns true for those).
|
||||
|
||||
@@ -401,7 +401,6 @@ async fn validate_invite_create_event(
|
||||
if !state_res::auth_check(
|
||||
room_version_rules,
|
||||
pdu,
|
||||
None,
|
||||
|_, _| async {
|
||||
unreachable!("No state should be fetched when processing a lone create event");
|
||||
},
|
||||
|
||||
@@ -5,17 +5,21 @@ use futures::{
|
||||
future::{OptionFuture, join, join3},
|
||||
};
|
||||
use ruma::{
|
||||
Int, OwnedUserId, RoomVersionId, UserId,
|
||||
AnyKeyName, CanonicalJsonObject, Int, OwnedUserId, RoomVersionId, SigningKeyId, UserId,
|
||||
events::room::{
|
||||
join_rules::{JoinRule, RoomJoinRulesEventContent},
|
||||
member::{MembershipState, ThirdPartyInvite},
|
||||
member::MembershipState,
|
||||
power_levels::{RoomPowerLevelsEventContent, UserPowerLevel},
|
||||
third_party_invite::PublicKey,
|
||||
},
|
||||
int,
|
||||
room_version_rules::{RoomIdFormatVersion, RoomVersionRules},
|
||||
serde::Raw,
|
||||
serde::{Raw, base64, base64::Standard},
|
||||
signatures,
|
||||
signatures::to_canonical_json_string_for_signing,
|
||||
third_party_invite::IdentityServerBase64PublicKey,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue};
|
||||
|
||||
use super::{
|
||||
@@ -25,7 +29,7 @@ use super::{
|
||||
deserialize_power_levels_content_redact,
|
||||
},
|
||||
};
|
||||
use crate::{debug, error, trace, warn};
|
||||
use crate::{debug, err, error, trace, warn};
|
||||
|
||||
// FIXME: field extracting could be bundled for `content`
|
||||
#[derive(Deserialize)]
|
||||
@@ -48,6 +52,40 @@ struct RoomCreateContentFields {
|
||||
federate: bool,
|
||||
}
|
||||
|
||||
// Workaround for https://github.com/matrix-org/matrix-spec/issues/2471
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct RoomThirdPartyInviteContentFields {
|
||||
public_key: Option<IdentityServerBase64PublicKey>,
|
||||
public_keys: Option<Vec<PublicKey>>,
|
||||
}
|
||||
|
||||
// same here sort of (maintainers see https://forgejo.ellis.link/continuwuation/continuwuity-sec/issues/41)
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct MemberThirdPartyInviteSignedContent {
|
||||
signed: ThirdPartyInviteSignedObject,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct ThirdPartyInviteSignedObject(CanonicalJsonObject);
|
||||
|
||||
impl ThirdPartyInviteSignedObject {
|
||||
#[inline]
|
||||
fn mxid(&self) -> Option<OwnedUserId> {
|
||||
self.0
|
||||
.get("mxid")?
|
||||
.as_str()
|
||||
.and_then(|raw| UserId::parse(raw).ok())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn token(&self) -> Option<&str> { self.0.get("token")?.as_str() }
|
||||
|
||||
#[inline]
|
||||
fn signatures(&self) -> Option<CanonicalJsonObject> {
|
||||
self.0.get("signatures")?.as_object().map(ToOwned::to_owned)
|
||||
}
|
||||
}
|
||||
|
||||
/// For the given event `kind` what are the relevant auth events that are needed
|
||||
/// to authenticate this `content`.
|
||||
///
|
||||
@@ -61,7 +99,7 @@ pub fn auth_types_for_event(
|
||||
state_key: Option<&str>,
|
||||
content: &RawJsonValue,
|
||||
room_version: &RoomVersionRules,
|
||||
) -> serde_json::Result<Vec<(StateEventType, StateKey)>> {
|
||||
) -> crate::Result<Vec<(StateEventType, StateKey)>> {
|
||||
if kind == &TimelineEventType::RoomCreate {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
@@ -84,7 +122,7 @@ pub fn auth_types_for_event(
|
||||
#[allow(unused)]
|
||||
struct RoomMemberContentFields {
|
||||
membership: Option<Raw<MembershipState>>,
|
||||
third_party_invite: Option<Raw<ThirdPartyInvite>>,
|
||||
third_party_invite: Option<Raw<MemberThirdPartyInviteSignedContent>>,
|
||||
join_authorised_via_users_server: Option<Raw<OwnedUserId>>,
|
||||
}
|
||||
|
||||
@@ -116,16 +154,24 @@ pub fn auth_types_for_event(
|
||||
auth_types.push(key);
|
||||
}
|
||||
|
||||
// TODO: restore this once 3pid support isn't broken
|
||||
// if membership == MembershipState::Invite {
|
||||
// if let Some(Ok(t_id)) = content.third_party_invite.map(|t|
|
||||
// t.deserialize()) { let key =
|
||||
// (StateEventType::RoomThirdPartyInvite,
|
||||
// t_id.signed.token.into()); if !auth_types.contains(&
|
||||
// key) { auth_types.push(key);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if membership == MembershipState::Invite {
|
||||
if let Some(Ok(t_id)) = content.third_party_invite.map(|t| t.deserialize()) {
|
||||
let key = (
|
||||
StateEventType::RoomThirdPartyInvite,
|
||||
t_id.signed
|
||||
.token()
|
||||
.ok_or_else(|| {
|
||||
err!(Request(BadJson(
|
||||
"Third party invite content missing a token"
|
||||
)))
|
||||
})?
|
||||
.into(),
|
||||
);
|
||||
if !auth_types.contains(&key) {
|
||||
auth_types.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,12 +225,11 @@ fn get_user_power_level(
|
||||
pub async fn auth_check<E, F, Fut>(
|
||||
room_version: &RoomVersionRules,
|
||||
incoming_event: &E,
|
||||
current_third_party_invite: Option<&E>,
|
||||
fetch_state: F,
|
||||
create_event: &E,
|
||||
) -> Result<bool, Error>
|
||||
where
|
||||
F: Fn(&StateEventType, &str) -> Fut + Send,
|
||||
F: Fn(&StateEventType, &str) -> Fut + Send + Copy,
|
||||
Fut: Future<Output = Option<E>> + Send,
|
||||
E: Event + Send + Sync,
|
||||
for<'a> &'a E: Event + Send,
|
||||
@@ -444,13 +489,15 @@ where
|
||||
sender,
|
||||
sender_member_event.as_ref(),
|
||||
incoming_event,
|
||||
current_third_party_invite,
|
||||
fetch_state,
|
||||
power_levels_event.as_ref(),
|
||||
join_rules_event.as_ref(),
|
||||
user_for_join_auth.as_deref(),
|
||||
&user_for_join_auth_membership,
|
||||
&room_create_event,
|
||||
)? {
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -639,14 +686,14 @@ where
|
||||
/// event and the current State.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
fn valid_membership_change<E>(
|
||||
async fn valid_membership_change<E, F, Fut>(
|
||||
room_version: &RoomVersionRules,
|
||||
target_user: &UserId,
|
||||
target_user_membership_event: Option<&E>,
|
||||
sender: &UserId,
|
||||
sender_membership_event: Option<&E>,
|
||||
current_event: &E,
|
||||
current_third_party_invite: Option<&E>,
|
||||
fetch_state: F,
|
||||
power_levels_event: Option<&E>,
|
||||
join_rules_event: Option<&E>,
|
||||
user_for_join_auth: Option<&UserId>,
|
||||
@@ -655,11 +702,13 @@ fn valid_membership_change<E>(
|
||||
) -> Result<bool>
|
||||
where
|
||||
E: Event + Send + Sync,
|
||||
F: Fn(&StateEventType, &str) -> Fut + Send + Copy,
|
||||
Fut: Future<Output = Option<E>> + Send,
|
||||
for<'a> &'a E: Event + Send,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
struct GetThirdPartyInvite {
|
||||
third_party_invite: Option<Raw<ThirdPartyInvite>>,
|
||||
third_party_invite: Option<Raw<MemberThirdPartyInviteSignedContent>>,
|
||||
}
|
||||
let create_content = from_json_str::<RoomCreateContentFields>(create_room.content().get())?;
|
||||
let creator = if room_version.authorization.use_room_create_sender {
|
||||
@@ -901,22 +950,18 @@ where
|
||||
| MembershipState::Invite => {
|
||||
// If content has third_party_invite key
|
||||
trace!("starting target_membership=invite check");
|
||||
match third_party_invite.and_then(|i| i.deserialize().ok()) {
|
||||
| Some(tp_id) =>
|
||||
match third_party_invite {
|
||||
| Some(raw_tp_id) =>
|
||||
if target_user_current_membership == MembershipState::Ban {
|
||||
warn!(?target_user_membership_event_id, "Can't invite banned user");
|
||||
false
|
||||
} else {
|
||||
let allow = verify_third_party_invite(
|
||||
Some(target_user),
|
||||
sender,
|
||||
&tp_id,
|
||||
current_third_party_invite,
|
||||
);
|
||||
if !allow {
|
||||
warn!("Third party invite invalid");
|
||||
}
|
||||
allow
|
||||
let Ok(tp_id) = raw_tp_id.deserialize() else {
|
||||
warn!("Invite third party content is invalid");
|
||||
return Ok(false);
|
||||
};
|
||||
verify_third_party_invite(Some(target_user), sender, &tp_id, fetch_state)
|
||||
.await
|
||||
},
|
||||
| _ =>
|
||||
if !sender_is_joined {
|
||||
@@ -1435,14 +1480,133 @@ fn get_send_level(
|
||||
.unwrap_or_else(|| if state_key.is_some() { int!(50) } else { int!(0) })
|
||||
}
|
||||
|
||||
fn verify_third_party_invite(
|
||||
_target_user: Option<&UserId>,
|
||||
_sender: &UserId,
|
||||
_tp_id: &ThirdPartyInvite,
|
||||
_current_third_party_invite: Option<&impl Event>,
|
||||
) -> bool {
|
||||
// TODO: implement proper verification here
|
||||
true
|
||||
async fn verify_third_party_invite<F, Fut, E>(
|
||||
target_user: Option<&UserId>,
|
||||
sender: &UserId,
|
||||
tp_id: &MemberThirdPartyInviteSignedContent,
|
||||
fetch_state: F,
|
||||
) -> bool
|
||||
where
|
||||
F: Fn(&StateEventType, &str) -> Fut + Send,
|
||||
Fut: Future<Output = Option<E>> + Send,
|
||||
E: Event + Send + Sync,
|
||||
{
|
||||
// If content.third_party_invite does not have a signed property, reject.
|
||||
// ^ This would be a deserialization error before this function call, which
|
||||
// equates to a rejection
|
||||
let signed = &tp_id.signed;
|
||||
// If signed does not have mxid and token properties, reject.
|
||||
let Some(mxid) = signed.mxid() else {
|
||||
warn!("Invite third party signed content is missing or has invalid `mxid` property");
|
||||
return false;
|
||||
};
|
||||
let Some(token) = signed.token() else {
|
||||
warn!("Invite third party signed content is missing or has invalid `token` property");
|
||||
return false;
|
||||
};
|
||||
if let Err(e) = mxid.validate_historical() {
|
||||
warn!(error=?e, ?mxid, "Invite third party signed content has invalid `mxid` property");
|
||||
return false;
|
||||
}
|
||||
// If mxid does not match state_key, reject.
|
||||
// N.B. target_user is the state_key
|
||||
if target_user.is_none_or(|u| u != mxid) {
|
||||
warn!(?target_user, %mxid, "Invite third party mxid does not match membership state key");
|
||||
return false;
|
||||
}
|
||||
// If there is no m.room.third_party_invite event in the current room state
|
||||
// with state_key matching token, reject.
|
||||
let Some(current_third_party_invite) =
|
||||
fetch_state(&StateEventType::RoomThirdPartyInvite, token).await
|
||||
else {
|
||||
warn!("No third party invite associated with the invite's third party invite found");
|
||||
return false;
|
||||
};
|
||||
let Ok(tpi_content) = current_third_party_invite
|
||||
.get_content::<RoomThirdPartyInviteContentFields>()
|
||||
.inspect_err(
|
||||
|e| warn!(error=?e, "Third party invite event content is invalid (cannot deserialize)"),
|
||||
)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if current_third_party_invite.state_key() != Some(token) {
|
||||
warn!(
|
||||
state_key=?current_third_party_invite.state_key(),
|
||||
%token,
|
||||
"Third party invite state key mismatch with signed invite token"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// If sender does not match sender of the m.room.third_party_invite, reject.
|
||||
if sender != current_third_party_invite.sender() {
|
||||
warn!(
|
||||
?sender,
|
||||
third_party_invite_sender=%current_third_party_invite.sender(),
|
||||
"Third party invite sender does not match invite membership sender"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// If any signature in signed matches any public key in the
|
||||
// m.room.third_party_invite event, allow. The public keys are in content of
|
||||
// m.room.third_party_invite as:
|
||||
//
|
||||
// A single public key in the public_key property.
|
||||
// A list of public keys in the public_keys property.
|
||||
|
||||
// NOTE: Technically the two below operations shouldn't be fallible at this
|
||||
// point in execution, but if we can't de/serialize them now, we won't be
|
||||
// able to in the future, so rejecting the event is the right way to go.
|
||||
// We log an error though since this is unexpected.
|
||||
let Ok(signed_json) = to_canonical_json_string_for_signing(&signed.0).inspect_err(
|
||||
|e| error!(error=?e, "Canonical signed object cannot be cast to a signing string"),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let signatures = signed
|
||||
.signatures()
|
||||
.unwrap_or_default() // Empty sigs object will never pass so this is fine
|
||||
.values()
|
||||
.filter_map(|signatures| signatures.as_object())
|
||||
.flat_map(|signatures| {
|
||||
signatures.iter().map(|(key, sig)| {
|
||||
let key_id = SigningKeyId::<AnyKeyName>::parse(key).ok()?;
|
||||
base64::Base64::<Standard>::parse(sig.as_str()?)
|
||||
.map(|parsed| (key_id.algorithm(), parsed))
|
||||
.ok()
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for public_key_bytes in tpi_content
|
||||
.public_key
|
||||
.into_iter()
|
||||
.chain(
|
||||
tpi_content
|
||||
.public_keys
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|pk| pk.public_key.clone()),
|
||||
)
|
||||
.filter_map(|pk| pk.decode().ok())
|
||||
{
|
||||
for (algorithm, signature) in &signatures {
|
||||
if signatures::verify_canonical_json_bytes(
|
||||
algorithm,
|
||||
&public_key_bytes,
|
||||
signature.as_bytes(),
|
||||
signed_json.as_bytes(),
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
warn!("Invite via third party was not signed by any associated public keys");
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1461,7 +1625,7 @@ mod tests {
|
||||
use serde_json::value::to_raw_value as to_raw_json_value;
|
||||
|
||||
use crate::{
|
||||
matrix::{Event, EventTypeExt, Pdu as PduEvent},
|
||||
matrix::{Event, EventTypeExt},
|
||||
state_res::{
|
||||
StateMap,
|
||||
event_auth::valid_membership_change,
|
||||
@@ -1472,8 +1636,8 @@ mod tests {
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_ban_pass() {
|
||||
#[tokio::test]
|
||||
async fn test_ban_pass() {
|
||||
let _ = tracing::subscriber::set_default(
|
||||
tracing_subscriber::fmt().with_test_writer().finish(),
|
||||
);
|
||||
@@ -1495,6 +1659,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
|
||||
let async_fetch_state =
|
||||
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
|
||||
let target_user = charlie();
|
||||
let sender = alice();
|
||||
|
||||
@@ -1506,19 +1672,20 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
None,
|
||||
&MembershipState::Leave,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_join_non_creator() {
|
||||
#[tokio::test]
|
||||
async fn test_join_non_creator() {
|
||||
let _ = tracing::subscriber::set_default(
|
||||
tracing_subscriber::fmt().with_test_writer().finish(),
|
||||
);
|
||||
@@ -1540,6 +1707,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
|
||||
let async_fetch_state =
|
||||
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
|
||||
let target_user = charlie();
|
||||
let sender = charlie();
|
||||
|
||||
@@ -1551,19 +1720,20 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
None,
|
||||
&MembershipState::Leave,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_join_creator() {
|
||||
#[tokio::test]
|
||||
async fn test_join_creator() {
|
||||
let _ = tracing::subscriber::set_default(
|
||||
tracing_subscriber::fmt().with_test_writer().finish(),
|
||||
);
|
||||
@@ -1585,6 +1755,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
|
||||
let async_fetch_state =
|
||||
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
|
||||
let target_user = alice();
|
||||
let sender = alice();
|
||||
|
||||
@@ -1596,19 +1768,20 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
None,
|
||||
&MembershipState::Leave,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ban_fail() {
|
||||
#[tokio::test]
|
||||
async fn test_ban_fail() {
|
||||
let _ = tracing::subscriber::set_default(
|
||||
tracing_subscriber::fmt().with_test_writer().finish(),
|
||||
);
|
||||
@@ -1630,6 +1803,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
|
||||
let async_fetch_state =
|
||||
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
|
||||
let target_user = alice();
|
||||
let sender = charlie();
|
||||
|
||||
@@ -1641,19 +1816,20 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
None,
|
||||
&MembershipState::Leave,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restricted_join_rule() {
|
||||
#[tokio::test]
|
||||
async fn test_restricted_join_rule() {
|
||||
let _ = tracing::subscriber::set_default(
|
||||
tracing_subscriber::fmt().with_test_writer().finish(),
|
||||
);
|
||||
@@ -1692,6 +1868,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
|
||||
let async_fetch_state =
|
||||
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
|
||||
let target_user = ella();
|
||||
let sender = ella();
|
||||
|
||||
@@ -1703,13 +1881,14 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
Some(alice()),
|
||||
&MembershipState::Join,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
@@ -1721,19 +1900,20 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
Some(ella()),
|
||||
&MembershipState::Leave,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_knock() {
|
||||
#[tokio::test]
|
||||
async fn test_knock() {
|
||||
let _ = tracing::subscriber::set_default(
|
||||
tracing_subscriber::fmt().with_test_writer().finish(),
|
||||
);
|
||||
@@ -1764,6 +1944,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
|
||||
let async_fetch_state =
|
||||
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
|
||||
let target_user = ella();
|
||||
let sender = ella();
|
||||
|
||||
@@ -1775,13 +1957,14 @@ mod tests {
|
||||
sender,
|
||||
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
|
||||
&requester,
|
||||
None::<&PduEvent>,
|
||||
&async_fetch_state,
|
||||
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
|
||||
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
|
||||
None,
|
||||
&MembershipState::Leave,
|
||||
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -757,7 +757,8 @@ where
|
||||
Some(state_key),
|
||||
event.content(),
|
||||
room_version,
|
||||
)?;
|
||||
)
|
||||
.map_err(|e| Error::InvalidPdu(e.to_string()))?;
|
||||
trace!(list = ?auth_types, event_id = event.event_id().as_str(), "auth types for event");
|
||||
|
||||
let mut auth_state = StateMap::new();
|
||||
@@ -830,12 +831,6 @@ where
|
||||
|
||||
debug!(event_id = event.event_id().as_str(), "Running auth checks");
|
||||
|
||||
// The key for this is (eventType + a state_key of the signed token not
|
||||
// sender) so search for it
|
||||
let current_third_party = auth_state.iter().find_map(|(_, pdu)| {
|
||||
(*pdu.event_type() == TimelineEventType::RoomThirdPartyInvite).then_some(pdu)
|
||||
});
|
||||
|
||||
let fetch_state = |ty: &StateEventType, key: &str| {
|
||||
future::ready(
|
||||
auth_state
|
||||
@@ -847,7 +842,6 @@ where
|
||||
let auth_result = auth_check(
|
||||
room_version,
|
||||
&event,
|
||||
current_third_party,
|
||||
fetch_state,
|
||||
&fetch_state(&StateEventType::RoomCreate, "")
|
||||
.await
|
||||
|
||||
@@ -160,15 +160,9 @@ impl super::Service {
|
||||
ready(auth_events_by_key.get(&key).map(ToOwned::to_owned))
|
||||
};
|
||||
|
||||
state_res::event_auth::auth_check(
|
||||
room_version_rules,
|
||||
pdu,
|
||||
None, // TODO: third party invite
|
||||
state_fetch,
|
||||
create_event,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| err!("Event self-authentication failed: {e:?}"))
|
||||
state_res::event_auth::auth_check(room_version_rules, pdu, state_fetch, create_event)
|
||||
.await
|
||||
.map_err(|e| err!("Event self-authentication failed: {e:?}"))
|
||||
}
|
||||
|
||||
/// Checks that the event passes PDU check 5, which ensures that the event
|
||||
@@ -242,7 +236,6 @@ impl super::Service {
|
||||
let auth_check = state_res::event_auth::auth_check(
|
||||
room_version_rules,
|
||||
incoming_pdu,
|
||||
None, // TODO: third party invite
|
||||
|ty, sk| state_fetch(ty.clone(), sk.into()),
|
||||
create_event.as_pdu(),
|
||||
)
|
||||
@@ -292,7 +285,6 @@ impl super::Service {
|
||||
state_res::event_auth::auth_check(
|
||||
room_version_rules,
|
||||
incoming_pdu,
|
||||
None, // third-party invite
|
||||
state_fetch,
|
||||
create_event.as_pdu(),
|
||||
)
|
||||
|
||||
@@ -582,7 +582,6 @@ impl Service {
|
||||
let auth_check = state_res::event_auth::auth_check(
|
||||
&room_version.rules().unwrap(),
|
||||
&parsed_join_pdu,
|
||||
None, // TODO: third party invite
|
||||
|k, s| state_fetch(k.clone(), s.into()),
|
||||
&state_fetch(StateEventType::RoomCreate, "".into())
|
||||
.await
|
||||
|
||||
@@ -33,6 +33,16 @@ impl super::Service {
|
||||
return Err!(Request(Forbidden("Redacting m.room.create is not safe, forbidding.")));
|
||||
}
|
||||
|
||||
// Defense in depth, shouldn't be reachable
|
||||
if redacting_event
|
||||
.as_ref()
|
||||
.is_ok_and(|pdu| pdu.room_id() != Some(room_id))
|
||||
{
|
||||
return Err!(Request(Forbidden(
|
||||
"Cannot redact an event that belongs to a different room."
|
||||
)));
|
||||
}
|
||||
|
||||
if redacting_event
|
||||
.as_ref()
|
||||
.is_ok_and(|pdu| *pdu.kind() == TimelineEventType::RoomServerAcl)
|
||||
@@ -77,12 +87,20 @@ impl super::Service {
|
||||
room_id: &RoomId,
|
||||
event_id: &EventId,
|
||||
) -> bool {
|
||||
let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else {
|
||||
return true;
|
||||
};
|
||||
|
||||
let currently_member = self.services.state_cache.is_joined(user_id, room_id).await;
|
||||
|
||||
let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else {
|
||||
// We haven't calculated the state at this event, so we can't
|
||||
// properly history visibility check it. This happens for outliers
|
||||
// and backfilled events. Since continuwuity is primarily targeting
|
||||
// single-user/trusted deployments, an acceptable compromise for now
|
||||
// is to ensure that the user is currently joined to the room.
|
||||
// Federation fails closed here, but if that was replicated for the
|
||||
// check used for client-server, nobody would be allowed to see
|
||||
// events before their server started participating in the room.
|
||||
return currently_member;
|
||||
};
|
||||
|
||||
let history_visibility = self
|
||||
.state_get_content(shortstatehash, &StateEventType::RoomHistoryVisibility, "")
|
||||
.await
|
||||
|
||||
@@ -3,7 +3,10 @@ use std::{collections::BTreeMap, sync::Arc};
|
||||
use conduwuit::result::LogErr;
|
||||
use conduwuit_core::{
|
||||
Event, Result, err,
|
||||
matrix::pdu::{PduCount, PduEvent, PduId, RawPduId},
|
||||
matrix::{
|
||||
event::RelationTypeEqual,
|
||||
pdu::{PduCount, PduEvent, PduId, RawPduId},
|
||||
},
|
||||
utils::{
|
||||
ReadyExt,
|
||||
stream::{TryIgnore, WidebandExt},
|
||||
@@ -12,9 +15,14 @@ use conduwuit_core::{
|
||||
use conduwuit_database::{Deserialized, Map};
|
||||
use futures::{Stream, StreamExt};
|
||||
use ruma::{
|
||||
CanonicalJsonValue, EventId, OwnedUserId, RoomId, UserId,
|
||||
api::client::threads::get_threads::v1::IncludeThreads, events::relation::BundledThread,
|
||||
serde::Raw, uint,
|
||||
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedUserId, RoomId, UInt, UserId,
|
||||
api::{Direction, client::threads::get_threads::v1::IncludeThreads},
|
||||
events::{
|
||||
AnySyncMessageLikeEvent, AnySyncTimelineEvent,
|
||||
relation::{BundledThread, RelationType},
|
||||
},
|
||||
serde::Raw,
|
||||
uint,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -27,6 +35,7 @@ pub struct Service {
|
||||
|
||||
struct Services {
|
||||
short: Dep<rooms::short::Service>,
|
||||
pdu_metadata: Dep<rooms::pdu_metadata::Service>,
|
||||
timeline: Dep<rooms::timeline::Service>,
|
||||
}
|
||||
|
||||
@@ -42,6 +51,7 @@ impl crate::Service for Service {
|
||||
},
|
||||
services: Services {
|
||||
short: args.depend::<rooms::short::Service>("rooms::short"),
|
||||
pdu_metadata: args.depend::<rooms::pdu_metadata::Service>("rooms::pdu_metadata"),
|
||||
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
|
||||
},
|
||||
}))
|
||||
@@ -51,6 +61,88 @@ impl crate::Service for Service {
|
||||
}
|
||||
|
||||
impl Service {
|
||||
/// Serializes an event for the `latest_event` of a thread's aggregation,
|
||||
/// stripping `unsigned` as we don't want to send e.g. txnid to clients.
|
||||
fn latest_event<E>(event: &E) -> Raw<AnySyncMessageLikeEvent>
|
||||
where
|
||||
E: Event,
|
||||
{
|
||||
let mut latest_pdu = event.clone().into_pdu();
|
||||
latest_pdu.unsigned = None;
|
||||
latest_pdu
|
||||
.into_format::<Raw<AnySyncTimelineEvent>>()
|
||||
.cast_unchecked()
|
||||
}
|
||||
|
||||
fn set_thread(unsigned: &mut CanonicalJsonObject, thread: BundledThread) {
|
||||
let content = serde_json::to_value(thread).expect("to_value always works");
|
||||
unsigned.insert(
|
||||
"m.relations".to_owned(),
|
||||
json!({ "m.thread": content })
|
||||
.try_into()
|
||||
.expect("thread is valid json"),
|
||||
);
|
||||
}
|
||||
|
||||
/// Remove `event` from the aggregation of the thread matching
|
||||
/// `root_event_id`
|
||||
pub async fn remove_from_thread<E>(&self, root_event_id: &EventId, event: &E) -> Result
|
||||
where
|
||||
E: Event + Send + Sync,
|
||||
{
|
||||
let Ok(root_id) = self.services.timeline.get_pdu_id(root_event_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut root_pdu_json = self
|
||||
.services
|
||||
.timeline
|
||||
.get_pdu_json_from_id(&root_id)
|
||||
.await
|
||||
.map_err(|e| err!(Database("Thread root pdu not found: {e:?}")))?;
|
||||
|
||||
let Some(CanonicalJsonValue::Object(unsigned)) = root_pdu_json.get_mut("unsigned") else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let thread: Vec<_> = self
|
||||
.services
|
||||
.pdu_metadata
|
||||
.get_relations(
|
||||
event.sender(),
|
||||
&event.room_id_or_hash(),
|
||||
root_event_id,
|
||||
PduCount::max(),
|
||||
usize::MAX,
|
||||
0,
|
||||
Direction::Backward,
|
||||
)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|(_, pdu)| RelationType::Thread.relation_type_equal(pdu))
|
||||
.collect();
|
||||
|
||||
match thread.first() {
|
||||
| Some((_, latest)) => Self::set_thread(
|
||||
unsigned,
|
||||
BundledThread::new(
|
||||
Self::latest_event(latest),
|
||||
thread.len().try_into().unwrap_or(UInt::MAX),
|
||||
true,
|
||||
),
|
||||
),
|
||||
| None => {
|
||||
// No events are left in the thread, or the root is backfilled
|
||||
unsigned.remove("m.relations");
|
||||
},
|
||||
}
|
||||
|
||||
self.services
|
||||
.timeline
|
||||
.replace_pdu(&root_id, &root_pdu_json)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn add_to_thread<E>(&self, root_event_id: &EventId, event: &E) -> Result
|
||||
where
|
||||
E: Event + Send + Sync,
|
||||
@@ -78,11 +170,20 @@ impl Service {
|
||||
.await
|
||||
.map_err(|e| err!(Request(InvalidParam("Thread root pdu not found: {e:?}"))))?;
|
||||
|
||||
if let CanonicalJsonValue::Object(unsigned) = root_pdu_json
|
||||
.entry("unsigned".to_owned())
|
||||
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
|
||||
// get_relations doesn't support backfilled targets, so redactions
|
||||
// couldn't update the aggregation of a backfilled root
|
||||
//
|
||||
// TODO: Support backfilled threads. This needs
|
||||
// `src/service/rooms/pdu_metadata/mod.rs`'s
|
||||
// (TODO: Relations with backfilled pdus) to be implemented,
|
||||
// and then this check can be removed.
|
||||
if matches!(root_id.pdu_count(), PduCount::Normal(_))
|
||||
&& let CanonicalJsonValue::Object(unsigned) = root_pdu_json
|
||||
.entry("unsigned".to_owned())
|
||||
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
|
||||
{
|
||||
if let Some(mut relations) = unsigned
|
||||
let latest_event = Self::latest_event(event);
|
||||
let thread = match unsigned
|
||||
.get("m.relations")
|
||||
.and_then(|r| r.as_object())
|
||||
.and_then(|r| r.get("m.thread"))
|
||||
@@ -90,34 +191,16 @@ impl Service {
|
||||
serde_json::from_value::<BundledThread>(relations.clone().into()).ok()
|
||||
}) {
|
||||
// Thread already existed
|
||||
relations.count = relations.count.saturating_add(uint!(1));
|
||||
relations.latest_event = Raw::from_json(event.content().to_owned());
|
||||
|
||||
let content = serde_json::to_value(relations).expect("to_value always works");
|
||||
|
||||
unsigned.insert(
|
||||
"m.relations".to_owned(),
|
||||
json!({ "m.thread": content })
|
||||
.try_into()
|
||||
.expect("thread is valid json"),
|
||||
);
|
||||
} else {
|
||||
| Some(mut thread) => {
|
||||
thread.count = thread.count.saturating_add(uint!(1));
|
||||
thread.latest_event = latest_event;
|
||||
thread
|
||||
},
|
||||
// New thread
|
||||
let relations = BundledThread::new(
|
||||
Raw::from_json(event.content().to_owned()),
|
||||
uint!(1),
|
||||
true,
|
||||
);
|
||||
| None => BundledThread::new(latest_event, uint!(1), true),
|
||||
};
|
||||
|
||||
let content = serde_json::to_value(relations).expect("to_value always works");
|
||||
|
||||
unsigned.insert(
|
||||
"m.relations".to_owned(),
|
||||
json!({ "m.thread": content })
|
||||
.try_into()
|
||||
.expect("thread is valid json"),
|
||||
);
|
||||
}
|
||||
Self::set_thread(unsigned, thread);
|
||||
|
||||
self.services
|
||||
.timeline
|
||||
|
||||
@@ -252,15 +252,10 @@ impl super::Service {
|
||||
| _ => create_pdu.as_ref().unwrap().as_pdu(),
|
||||
};
|
||||
|
||||
let auth_check = state_res::auth_check(
|
||||
&room_version_rules,
|
||||
&pdu,
|
||||
None, // TODO: third_party_invite
|
||||
auth_fetch,
|
||||
create_event,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?;
|
||||
let auth_check =
|
||||
state_res::auth_check(&room_version_rules, &pdu, auth_fetch, create_event)
|
||||
.await
|
||||
.map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?;
|
||||
|
||||
if !auth_check {
|
||||
return Err!(Request(Forbidden("Event is not authorized.")));
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use conduwuit_core::{
|
||||
Result, err,
|
||||
Err, Result, err,
|
||||
matrix::event::Event,
|
||||
utils::{self},
|
||||
warn,
|
||||
};
|
||||
use ruma::EventId;
|
||||
use ruma::{EventId, events::room::encrypted::Relation};
|
||||
|
||||
use super::ExtractBody;
|
||||
use super::{ExtractBody, ExtractRelatesTo};
|
||||
use crate::rooms::short::ShortRoomId;
|
||||
|
||||
impl super::Service {
|
||||
@@ -31,6 +32,18 @@ impl super::Service {
|
||||
err!(Database(error!(?pdu_id, %event_id, ?e, "PDU ID points to invalid PDU.")))
|
||||
})?;
|
||||
|
||||
if pdu.room_id() != reason.room_id() {
|
||||
return Err!(Request(Forbidden(
|
||||
"Cannot redact an event that belongs to a different room."
|
||||
)));
|
||||
}
|
||||
|
||||
let thread_root = match pdu.get_content::<ExtractRelatesTo>() {
|
||||
| Ok(ExtractRelatesTo { relates_to: Relation::Thread(thread) }) =>
|
||||
Some(thread.event_id),
|
||||
| _ => None,
|
||||
};
|
||||
|
||||
if let Ok(content) = pdu.get_content::<ExtractBody>() {
|
||||
if let Some(body) = content.body {
|
||||
self.services
|
||||
@@ -51,6 +64,21 @@ impl super::Service {
|
||||
err!(Database(error!(%event_id, ?e, "Failed to convert PDU to canonical JSON")))
|
||||
})?;
|
||||
|
||||
self.replace_pdu(&pdu_id, &obj).await
|
||||
self.replace_pdu(&pdu_id, &obj).await?;
|
||||
|
||||
// So the thread's root doesn't keep the original content in its
|
||||
// `latest_event` aggregation
|
||||
if let Some(thread_root) = thread_root {
|
||||
self.services
|
||||
.threads
|
||||
.remove_from_thread(&thread_root, &pdu)
|
||||
.await
|
||||
.inspect_err(|e| {
|
||||
warn!("Failed to remove redacted event from thread {thread_root}: {e:?}");
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,7 @@ async fn get_register_email_validate(
|
||||
Some(email),
|
||||
&client
|
||||
)
|
||||
.boxed()
|
||||
.await?
|
||||
)
|
||||
}
|
||||
@@ -508,6 +509,7 @@ async fn begin_registration(
|
||||
// If email isn't required we can immediately complete registration
|
||||
Ok(response!(
|
||||
complete_registration(services, session_store, completed_registration, None, client)
|
||||
.boxed()
|
||||
.await?
|
||||
))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user