Compare commits

...

176 Commits

Author SHA1 Message Date
strawberry
d0069cc100 log out any sessions when the server emergency password is unset
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Matthias Ahouansou
556e78214a fix: only allow the server user to set the admin alias
Should make it safer to move the alias if the admin room broke on a public server.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
strawberry
8fff7ea706 cleanup+refactor admin room alias and server account accessing to globals
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Matthias Ahouansou
f712c0cefb fix: restrict who can remove aliases
Previously, anyone could remove any local alias, meaning that someone could re-route a popular alias elsewhere
Now, only the creator of the alias, users who can set canonical aliases for the room, server admins and the server user can delete aliases

added some additional changes/fixes to adapt to our codebase

Co-authored-by: strawberry <strawberry@puppygock.gay>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Matthias Ahouansou
26d103d314 fix: only process admin commands if server user is in the room
Should prevent some edge cases with a misconfigured admin room

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Benjamin Lee
0688a96c37 drop redacted events from search results
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Benjamin Lee
eb73d8c669 fix: de-index pdus when redacted
bit of code dedupe as well

Co-authored-by: strawberry <strawberry@puppygock.gay>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Benjamin Lee
20a54aacd6 factor search tokenization out into a function
This ensures that the tokenization algorithm will remain in sync between
querying, indexing, and deindexing. The existing code had slightly
different behavior for querying, because it did not discard words with
>50 bytes. This was inconsequential, because >50 byte tokens are never
present in the index.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Benjamin Lee
81cd677b4e fix dropped events in search
The previous code would drop some events entirely if any events between
`skip` and `skip + limit` were not visible to the user. This would cause
the set of events skipped by the `skip(skip)` method to extend past
`skip` in the raw result set, because `skip(skip)` was being called
*after* filtering out invisible events.

This bug will become much more severe with a full filtering
implementation, because it will be more likely for events to be filtered
out. Currently, it is only possible to trigger with rooms that have
history visibility set to "invited" or "joined".

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
Benjamin Lee
73da353e52 fix missing next_batch for search
The previous code would fail to return next_batch if any of the events
in the window were not visible to the user. It would also return an
unnecessary next_batch when no more results are available if the total
number of results is exactly `skip + limit`.

This bug will become much more severe with a full filtering
implementation, because we will be more likely to trigger it by
filtering out events in a search call. Currently, it is only possible to
trigger with rooms that have history visibility set to "invited" or
"joined".

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-12 14:04:47 -04:00
strawberry
d5677b6ae7 bump cargo.lock due to yanked httparse
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-11 20:18:28 -04:00
strawberry
01a77f8a71 add replaces_state and prev_sender in unsigned for membership changes
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-11 13:03:32 -04:00
strawberry
ea03a50e21 remove pfps/avatars and display names upon deactivation
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-11 01:19:18 -04:00
strawberry
25d44cad31 slightly dedupe pfp/displayname updates, update blurhash in PDUs too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-11 01:19:18 -04:00
strawberry
91519959ed mark account as deactivated before leaving rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-11 01:19:18 -04:00
strawberry
2e31bcc213 use our fork of axum-server instead
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-11 01:19:18 -04:00
strawberry
305dfc3b42 adminroom: cmds to view room topic and room members
this will be extended more

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 23:38:03 -04:00
strawberry
65fbb80145 adminroom: leave all rooms by default on manual deactivations
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 21:14:18 -04:00
strawberry
f1d90e5df6 log client/remote IP address on various routes tracing calls
this uses InsecureClientIp as this is purely for informational
and logging purposes

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 21:04:51 -04:00
strawberry
74b29ce067 adminroom: improved room list outputs, add counts
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
0e7c3cb338 adminroom: simplify codeblock checks
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
14a3471fcb adminroom: fix function typo
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
c834e86e67 adminroom: user cmds to put/get/delete room account data
primarily useful for inserting `m.server_notice` user account data
onto the admin room

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
b4f0a8a8b5 adminroom: clean up and optimise user commands
`deactivate-all` was terrible and incredibly inefficient

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
9bb90213e1 adminroom: add user ID parsing utils
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
fcdf1463ef refactor get_room_topic into 1 single function
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
88d038ffec refactor getting room's canonical alias into 1 function
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
4b4c0952a2 refactor guest_can_join into 1 single function
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
016270b33b adminroom: add server_in_room state cache accessor
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
d2063013b4 adminroom: add various state_cache db accessors
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
03ba9bde29 admin cmd to force download and use a server's room state
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
1287a86c05 client-api: export validate_and_add_event_id
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 19:45:04 -04:00
strawberry
8210e8c42e slightly adjust sliding sync code for ruma bump
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 17:20:59 -04:00
strawberry
adf0bfd894 bump ruma
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 16:57:44 -04:00
strawberry
6b843ec4dd switch to patch/fork of axum-server to fix shutdown hangs
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 16:55:40 -04:00
strawberry
ac02078395 bump cargo.lock, add tracing feature to axum-extra
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 16:55:40 -04:00
renovate[bot]
b9d38fd3ba chore(deps): update rust crate http-body-util to v0.1.2 2024-06-10 16:55:40 -04:00
renovate[bot]
1b2c8236fb chore(deps): update rust crate clap to v4.5.7 2024-06-10 16:55:40 -04:00
renovate[bot]
d7b8af627c chore(deps): update rust crate console-subscriber to 0.3 2024-06-10 16:55:40 -04:00
renovate[bot]
130aae8758 chore(deps): update rust crate url to v2.5.1 2024-06-10 16:55:40 -04:00
renovate[bot]
4741a76896 chore(deps): update rust crate regex to v1.10.5 2024-06-10 16:55:40 -04:00
strawberry
5bfb62e979 Revert "update complement results"
This reverts commit 9a3c52aa75.
2024-06-10 15:38:20 -04:00
strawberry
cb03654dc1 fix broken federated room invites/joins
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-10 14:53:26 -04:00
Jason Volk
f0557e3303 split migrations function
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:56:41 +00:00
Jason Volk
f52acd9cdf Fix idiomatic let if
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
eae41fc411 Fix use-self
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
c3c91e9d80 Fix suboptimal flops
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
a8de5d1e60 Fix futures not Send
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
7688d67870 Fix needless pass by ref mut
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
89d7d48324 Fix equatable if let
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
b525031a25 Fix derive partial eq without eq
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
67f4285504 Fix branches sharing code
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
b65f05ce19 simplify lifetime parameters
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
db2c9f28b6 split admin room moderation commands
prior stack frame allocated 170 KiB

Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
fc1b8326e6 split join_room_by_id_helper into local and remote
prior stack frame allocated 180 KiB

Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
Jason Volk
6e50b07bf5 Fix large future
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-09 20:06:50 +00:00
strawberry
9a3c52aa75 update complement results
they seem to be failures out of
our control (?)

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-09 12:05:30 -04:00
strawberry
ccf9f95cc9 retroactively fix bad data in roomuserid_joined, remove pointless prefix scans
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-09 03:55:04 -04:00
strawberry
0524e6ed52 remove unnecessary active_local_joined_users_in_room state_cache accessor
the underlying bug has been fixed

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-08 17:32:04 -04:00
strawberry
7f5b59afbb add conduwuit-specific db migration fixing double split db entries
for a few months now we accidentally had double 0xFF splits being
inserted into `roomuserid_joined` cf when membership counts and such
are being updated.

this is a conduwuit-specific db migration and does NOT break conduit
compatibility.

`fix_bad_double_separator_in_state_cache`

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-08 16:58:24 -04:00
strawberry
ab5db37851 fix bad double split insert on roomuserid_joined cf
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-08 16:57:48 -04:00
strawberry
c0c7f23a05 services(timeline): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
14ec41c211 services(state_cache): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
2230bc7339 services(state): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
0ebabba971 services(pdu_metadata): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
3ed561cb31 service(globals): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
a061644b2d service(event_handler): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
82ac6b01b2 service(auth_chain): use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
97ddb2ce87 bump conduwuit to version 0.4.2
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
a04ff7d4af fix(fed): dont reject /state_ids/ on world readable rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
10dfbf6420 fix(fed): dont reject /state/ on world readable rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
d10bc67c9d fix(fed): dont reject /event_auth/ on world readable rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
197a02bf8d fix(fed): dont reject /event/ on world readable rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
8103bd7310 fix(fed): dont reject /backfill/ on world readable rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
81487e3f07 fix(fed): dont reject /get_missing_events on world readable rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
bfbb29dded add is_world_readable state_accessor func, use self instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:10:00 -04:00
strawberry
1cc7cf54a7 add config option to allow guests to access TURN server
`turn_allow_guests`

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:09:59 -04:00
strawberry
40e4019f7f add missing TURN example config options
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-07 15:09:59 -04:00
Lux Aliaga
176d95c2a8 admin: media: Force flag on past media removal
When enabled, if a file is deemed unremovable, it skips past it and
continues deleting all other files that fit the criteria. Additionally,
fix age comparison under the same command.

Signed-off-by: Lux Aliaga <lux@nixgoat.me>
2024-06-07 15:08:08 -04:00
renovate[bot]
8d32fb1445 chore(deps): update sentry-rust monorepo to 0.34.0 2024-06-07 00:52:25 -04:00
renovate[bot]
82a3b73774 chore(deps): update rust crate clap to v4.5.6 2024-06-07 00:52:13 -04:00
renovate[bot]
1f19356693 chore(deps): update aquasecurity/trivy-action action to v0.22.0 2024-06-07 00:52:05 -04:00
Jason Volk
3ada847570 extract client ip from connection state
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
0bade5317f add connection info to router
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
c2267d4c03 add services state to router
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
aebae11c82 reintroduce the variadic macro for ruma handler.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
f871d8fd4e move impl FromRequest for Ruma up one level; some cleanup
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
4a68e28c71 use debug_warn for presence spam
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
6e59135a7d eliminate RotationHandler
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
0e74ade7d7 isolate axum shutdown in router; minor run-cycle/signalling tweaks
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-07 02:00:28 +00:00
Jason Volk
e4aa20ebeb move services ctor/dtor detail into service
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
427aa4645c cleanup/reduce some tracing spans.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
73718a1208 elminate generic argument in ruma_wrapper::auth
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
0e3d192ad2 fix trivial-casts
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
76a4d8aa4c additional clippy configuration
these are documentary values seeking review, not final standards set for the project.

Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
9bb52cb3ec add missing dev_release_log_level feature projection
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
dd49b3c3a1 fix/simplify emergency access initialization
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
b2e56777af fix missing toolchain in cargo smoketest run invocation.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
Jason Volk
f32380772f rename api::client_server to api::client
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 18:21:40 +00:00
strawberry
8428f43c78 add legacy element hack for UIAA using invalid user field
see:
- e9302a9556
- https://github.com/element-hq/element-android/issues/8043
- https://github.com/element-hq/element-ios/issues/7405

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-06 10:57:00 -04:00
Jason Volk
3af153f5ae split s2s into units
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-06 04:41:27 -04:00
strawberry
38238c309f appservices: remove unnecessary services() call for self
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 18:18:08 -04:00
strawberry
0857fe7907 abstract+add more "users in room" accessors, check membership state on active_local_joined_users_in_room
`roomuserid_joined` cf seems unreliable, so in the mean time we need to check
membership state (or maybe this is a more reliable check anyways)

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 18:18:08 -04:00
strawberry
c738c119f8 delete unnecessary real_users_cache, fix overwriting push_target iter, add proper function for getting local active users in room
this `real_users_cache` cache seems weird, and i have no idea what
prompted its creation upstream. perhaps they did this because
sqlite was very slow and their rocksdb setup is very poor, so
a "solution" was to stick member counts in memory.
slow iterators, scanning, etc do not apply to conduwuit where
our rocksdb is extremely tuned, and i seriously doubt something
like this would have any real world net-positive performance impact.

also for some reason, there is suspicious logic where we
overwrite the entire push target collection.

both of these things could be a potential cause for receiving
notifications in rooms we've left.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 18:18:08 -04:00
strawberry
c1227340b3 update complement results
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 18:17:46 -04:00
strawberry
bf10ff65a4 media: ignore Content-Type params, use binary_search
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 17:28:51 -04:00
strawberry
b781771a9b media: drop Content-Type detection support
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 16:33:53 -04:00
strawberry
df8ba04e31 media: trust client Content-Type again
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 16:33:53 -04:00
strawberry
19926ba00d sort ALLOWED_INLINE_CONTENT_TYPES
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 16:33:53 -04:00
strawberry
893cc50570 csp: set form-action 'none'
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 16:33:53 -04:00
strawberry
c9fbbdce1c csp: remove unusual directives, slight security improvement
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-05 02:50:44 -04:00
Jason Volk
732e8b82aa Abstract password hashing into util.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-05 03:00:23 +00:00
Tom Black
282c2feca8 Clarify purpose and temporary muting 2024-06-04 17:13:21 +01:00
strawberry
919735b4ce remove usages of &String and &Owned[..]
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 14:17:42 -04:00
strawberry
2e83e56a07 remove deleted config options and update address example option
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 14:17:42 -04:00
strawberry
ff7dfec74c slightly cleanup update check
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 14:17:42 -04:00
strawberry
84290bd668 update deps, remove unnecessary zstd crate, pin rust-rocksdb rev
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 14:17:32 -04:00
strawberry
b29a8791de admincmd: leave all rooms if deactivating all users with --force
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
83220b43a2 use saturating_add and vec with_capacity in even more places
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
4ea7af5780 ci(engage): use all-features devshell for cargo doc / rustdoc --all-features
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
79fb8091dc ci(engage): use all-features direnv devshell for clippy/all
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
f6fa2a4f65 use swap_remove instead of remove in a few places
`swap_remove` is faster if we don't care about the order (O(1))

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
b63937af0b ci(engage): add cargo test default, use all-features devshell for cargo test --all-features
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
3c4e325036 nix(bin): cache default devshell on top of all-features devshell
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
023fb41c49 load .env file before initializing flake to use DIRENV_DEVSHELL in .env
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
9a5f1dac57 drop unnecessarily verbose get_alias_helper logging
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
173ff26eb6 disable URL previews by default upon admin room creation
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:28 -04:00
strawberry
45e3fdba69 admin room: add get-latest-pdu and get-first-pdu commands
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-03 00:10:24 -04:00
strawberry
9f359e0550 make resolve_state public to resolve new forced compressed room state
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
ffdf47d1ea add latest_pdu_in_room timeline function
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
1af65e695d media: return application/octet-stream if no content-type was provided
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
b1886583d9 csp: fix typo, add base-uri none
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
f11103b43b media: check detected content-type against MSC2702
only return `inline` if the detected content-type is an allowed
inline content-type as defined by MSC2702

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
9b096cc67b fix: check if you've left the room before forgetting it
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
1ac72ab914 init a few state hashmaps using with_capacity
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
f0533e07ef fed: remove unnecessary mutables, use with_capacity in couple more places
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
68f42f5a2f fed: relax read receipt EDU check
so in theory: guest users, peaking over federation,
and world readable rooms should be allowed to send
read receipts even if they're not joined.

relaxing this check to only allow the read receipt if
the server has at least 1 member in the room makes
some of this still work

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
884cbab135 ci: comment out hardened_malloc clippy check for now
i need to either fix static linking, or just make it
dynamic always (but then kinda useless idk)

https://gitlab.com/conduwuit/conduwuit/-/jobs/6953419673#L3155

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
4aead5de7a reflax a couple restrictions on custom room IDs and aliases
🙃

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
strawberry
aef25ea1f7 enable tracing feature for axum
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 23:53:31 -04:00
Jason Volk
1a4736d40b support configuring multiple bind hosts; default to dual localhost.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-03 01:17:58 +00:00
strawberry
f09e0dc137 add conduwuit community code of conduct
this is a code of conduct that the moderation team made up,
specific to conduwuit's community spaces such as the matrix rooms.

the matrix foundation and contributor's covenant still apply, but
having conduwuit-specific additional guidelines help

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 21:02:38 -04:00
strawberry
de79b66cea misc docs changes
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-06-02 21:02:38 -04:00
strawberry
95ca9d00a2 nix: get all features from main crate 2024-06-02 23:01:12 +00:00
Jason Volk
887496d040 consolidate default cargo features
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 23:01:12 +00:00
Jason Volk
c2586737ae accept receipts prior to events
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 23:01:12 +00:00
Jason Volk
7d2f510cc3 single-source for defaulty log filter string
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 23:01:12 +00:00
Jason Volk
102bd1b4a6 use debug_warn for parse_incoming_pdu err results.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 23:01:12 +00:00
Jason Volk
89ab687f16 move signal handling out to main
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 23:01:12 +00:00
Jason Volk
1108235c63 misc simplifications and cleanup
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 20:17:45 +00:00
Jason Volk
90d9a997a5 split / cleanup core utils.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 20:17:45 +00:00
Jason Volk
5fe5ab279c split RouterExt impl related into ruma_wrapper unit.
slightly restrict client_server mod index.

Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 20:17:45 +00:00
Jason Volk
f1d1366129 split resolve_actual_dest
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 20:17:45 +00:00
Jason Volk
ba48758b89 impl fmt::Display for FedDest
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 20:17:45 +00:00
Jason Volk
9df5265c00 split sending resolver into unit.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 20:17:45 +00:00
Jason Volk
ee52d2f751 refactor lints into categories. lints are now more strict.
rust:
* ALL lints which rustc defaults to "allow" have been set to "warn".
* NEW "warn" lints which produce a warning as of this commit have been
explicitly identified and commented with a TODO for later review.

clippy:
* ALL categories (sans restriction) now fully enabled to "warn".
* redundant lints set to "warn" from categories now at "warn" are removed.
* previous "allow" sadness moved into respective categories.
* new warnings produced as of this commit have been explicitly identified:
	- nursery lints set to "allow" marked with TODO for later review.
	- pedantic lints set to "allow"

Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
53fe2362fc Fix path-buf-push-overwrite
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
38ab1083e3 Fix ptr-cast-constness
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
050841a871 Fix inefficient-to-string
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
4521e93d04 Fix stable-sort-primitive
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
0f3d43153b Fix unused-self
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
e5eccb3a0c Fix unreadable-literal
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
68cbf19154 Fix items-after-statements
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
2ab427fe99 Fix default-trait-access 2024-06-02 12:34:05 -04:00
Jason Volk
02081b66c4 Fix some unnecessary-unwraps w/ addl cleanup/simplification.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
b3fc8516ed Fix unnested-or-patterns
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
9e51525c25 Fix uninlined-format-args
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
14039d9df4 cleanup unused extern crates.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
eed8a2a801 add and sort incomplete package metadata
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 12:34:05 -04:00
Jason Volk
c3a0d28309 add tracing span; mute connection errors.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 01:20:28 -04:00
Jason Volk
6d1144bb69 move unix socket unlink from services to router
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 01:20:28 -04:00
Jason Volk
2e45cb281a split router::serve units.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 01:20:28 -04:00
Jason Volk
0baa57f5d9 add back unix socket listener.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 01:20:28 -04:00
Jason Volk
faa2b95c84 add unwrap_infallible tool
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 01:20:28 -04:00
Jason Volk
dd1d8fa760 upgrade to hyper-util 0.1.5
Signed-off-by: Jason Volk <jason@zemos.net>
2024-06-02 01:20:28 -04:00
Jayryn
f4cfc77a57 Check if database symlink already exists
test -L $object [object exists and is a symbolic link (same as -h)]

It is not recommended to use -h 
[True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead.]
2024-05-28 04:06:53 -04:00
192 changed files with 9019 additions and 7067 deletions

4
.envrc
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env bash
dotenv_if_exists
use flake ".#${DIRENV_DEVSHELL:-default}"
PATH_add bin
dotenv_if_exists

View File

@@ -26,7 +26,7 @@ jobs:
uses: actions/checkout@v4
- name: Run Trivy code and vulnerability scanner on repo
uses: aquasecurity/trivy-action@0.21.0
uses: aquasecurity/trivy-action@0.22.0
with:
scan-type: repo
format: sarif
@@ -34,7 +34,7 @@ jobs:
severity: CRITICAL,HIGH,MEDIUM,LOW
- name: Run Trivy code and vulnerability scanner on filesystem
uses: aquasecurity/trivy-action@0.21.0
uses: aquasecurity/trivy-action@0.22.0
with:
scan-type: fs
format: sarif

593
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,19 +6,21 @@ members = ["src/*"]
default-members = ["src/*"]
[workspace.package]
description = "a very cool fork of Conduit, a Matrix homeserver written in Rust"
license = "Apache-2.0"
authors = [
"strawberry <strawberry@puppygock.gay>",
"timokoesters <timo@koesters.xyz>",
]
version = "0.4.1"
categories = ["network-programming"]
description = "a very cool fork of Conduit, a Matrix homeserver written in Rust"
edition = "2021"
# See also `rust-toolchain.toml`
rust-version = "1.77.0"
homepage = "https://conduwuit.puppyirl.gay/"
repository = "https://github.com/girlbossceo/conduwuit"
keywords = ["chat", "matrix", "server"]
license = "Apache-2.0"
# See also `rust-toolchain.toml`
readme = "README.md"
repository = "https://github.com/girlbossceo/conduwuit"
rust-version = "1.77.0"
version = "0.4.2"
[workspace.metadata.crane]
name = "conduit"
@@ -26,10 +28,6 @@ name = "conduit"
[workspace.dependencies.sanitize-filename]
version = "0.5.0"
[workspace.dependencies.infer]
version = "0.15"
default-features = false
[workspace.dependencies.jsonwebtoken]
version = "9.3.0"
@@ -73,17 +71,21 @@ features = [
"json",
"matched-path",
"tokio",
"tracing",
]
[workspace.dependencies.axum-extra]
version = "0.9.3"
default-features = false
features = ["typed-header"]
features = ["typed-header", "tracing"]
[workspace.dependencies.axum-server]
version = "0.6.0"
features = ["tls-rustls"]
[workspace.dependencies.axum-client-ip]
version = "0.6.0"
[workspace.dependencies.tower]
version = "0.4.13"
features = ["util"]
@@ -111,7 +113,7 @@ features = [
]
[workspace.dependencies.serde]
version = "1.0.201"
version = "1.0.203"
features = ["rc"]
[workspace.dependencies.serde_json]
@@ -181,7 +183,7 @@ version = "0.3.30"
default-features = false
[workspace.dependencies.tokio]
version = "1.37.0"
version = "1.38.0"
features = [
"fs",
"net",
@@ -216,7 +218,14 @@ features = [
]
[workspace.dependencies.hyper-util]
version = "0.1.4"
version = "0.1.5"
features = [
"client",
"server-auto",
"server-graceful",
"service",
"tokio",
]
# to support multiple variations of setting a config option
[workspace.dependencies.either]
@@ -251,7 +260,7 @@ version = "2.1.1"
# used to replace the channels of the tokio runtime
[workspace.dependencies.loole]
version = "0.3.0"
version = "0.3.1"
[workspace.dependencies.async-trait]
version = "0.1.80"
@@ -303,9 +312,6 @@ features = [
"bzip2",
]
[workspace.dependencies.zstd]
version = "0.13.1"
# to listen on both HTTP and HTTPS if listening on TLS dierctly from conduwuit for complement or sytest
[workspace.dependencies.axum-server-dual-protocol]
version = "0.6"
@@ -334,7 +340,7 @@ features = ["rt-tokio"]
# optional sentry metrics for crash/panic reporting
[workspace.dependencies.sentry]
version = "0.32.3"
version = "0.34.0"
default-features = false
features = [
"backtrace",
@@ -350,9 +356,9 @@ features = [
]
[workspace.dependencies.sentry-tracing]
version = "0.32.3"
version = "0.34.0"
[workspace.dependencies.sentry-tower]
version = "0.32.3"
version = "0.34.0"
# jemalloc usage
[workspace.dependencies.tikv-jemalloc-sys]
@@ -376,7 +382,7 @@ features = ["bundled"]
# used only by rusqlite
[workspace.dependencies.parking_lot]
version = "0.12.2"
version = "0.12.3"
# used only by rusqlite
[workspace.dependencies.thread_local]
@@ -387,10 +393,10 @@ version = "0.3.1"
default-features = false
[workspace.dependencies.console-subscriber]
version = "0.2"
version = "0.3"
[workspace.dependencies.nix]
version = "0.28.0"
version = "0.29.0"
features = ["resource"]
[workspace.dependencies.sd-notify]
@@ -421,6 +427,11 @@ branch = "tracing-subscriber/env-filter-clone-0.1.x-backport"
git = "https://github.com/girlbossceo/tracing"
branch = "tracing-subscriber/env-filter-clone-0.1.x-backport"
# fixes hyper graceful shutdowns [https://github.com/programatik29/axum-server/issues/114]
[patch.crates-io.axum-server]
git = "https://github.com/girlbossceo/axum-server"
branch = "phlip9/fix-graceful-shutdown"
#
# Our crates
#
@@ -635,145 +646,176 @@ opt-level = 'z'
[profile.test]
incremental = false
###############################################################################
#
# Linting
#
[workspace.lints.rust]
missing_abi = "warn"
noop_method_call = "warn"
pointer_structural_match = "warn"
explicit_outlives_requirements = "warn"
unused_extern_crates = "warn"
unused_import_braces = "warn"
unused_lifetimes = "warn"
unused_qualifications = "warn"
unused_macro_rules = "warn"
dead_code = "warn"
elided_lifetimes_in_paths = "warn"
macro_use_extern_crate = "warn"
single_use_lifetimes = "warn"
unsafe_op_in_unsafe_fn = "warn"
unreachable_pub = "warn"
absolute-paths-not-starting-with-crate = "warn"
#box-pointers = "warn"
deprecated-in-future = "warn"
elided-lifetimes-in-paths = "warn"
explicit-outlives-requirements = "warn"
ffi-unwind-calls = "warn"
keyword-idents = "warn"
macro-use-extern-crate = "warn"
meta-variable-misuse = "warn"
missing-abi = "warn"
#missing-copy-implementations = "warn" # TODO
#missing-debug-implementations = "warn" # TODO
non-ascii-idents = "warn"
rust-2021-incompatible-closure-captures = "warn"
rust-2021-incompatible-or-patterns = "warn"
rust-2021-prefixes-incompatible-syntax = "warn"
rust-2021-prelude-collisions = "warn"
single-use-lifetimes = "warn"
trivial-casts = "warn"
trivial-numeric-casts = "warn"
unit-bindings = "warn"
#unnameable-types = "warn" # TODO
unreachable-pub = "warn"
unsafe-op-in-unsafe-fn = "warn"
unstable-features = "warn"
unused-extern-crates = "warn"
unused-import-braces = "warn"
unused-lifetimes = "warn"
unused-macro-rules = "warn"
unused-qualifications = "warn"
#unused-results = "warn" # TODO
# this seems to suggest broken code and is not working correctly
unused_braces = "allow"
# cfgs cannot be limited to features or cargo build --all-features panics for unsuspecting users.
## some sadness
let_underscore_drop = "allow"
missing_docs = "allow"
# cfgs cannot be limited to expected cfgs or their de facto non-transitive/opt-in use-case e.g.
# tokio_unstable will warn.
unexpected_cfgs = "allow"
# this seems to suggest broken code and is not working correctly
unused_braces = "allow"
# buggy, but worth checking on occasionally
unused_crate_dependencies = "allow"
unsafe_code = "allow"
variant_size_differences = "allow"
# some sadness
missing_docs = "allow"
#######################################
#
# Clippy lints
#
[workspace.lints.clippy]
# pedantic = "warn"
suspicious = "warn" # assume deny in practice
perf = "warn" # assume deny in practice
###################
cargo = "warn"
redundant_clone = "warn"
cloned_instead_of_copied = "warn"
expl_impl_clone_on_copy = "warn"
unnecessary_cast = "warn"
cast_lossless = "warn"
ptr_as_ptr = "warn"
mut_mut = "warn"
char_lit_as_u8 = "warn"
dbg_macro = "warn"
empty_structs_with_brackets = "warn"
get_unwrap = "warn"
negative_feature_names = "warn"
pub_without_shorthand = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
redundant_feature_names = "warn"
redundant_type_annotations = "warn"
rest_pat_in_fully_bound_structs = "warn"
str_to_string = "warn"
string_to_string = "warn"
tests_outside_test_module = "warn"
undocumented_unsafe_blocks = "warn"
unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn"
wildcard_dependencies = "warn"
or_fun_call = "warn"
unnecessary_lazy_evaluations = "warn"
## some sadness
multiple_crate_versions = { level = "allow", priority = 1 }
###################
complexity = "warn"
###################
correctness = "warn"
###################
nursery = "warn"
## some sadness
missing_const_for_fn = { level = "allow", priority = 1 } # TODO
needless_collect = { level = "allow", priority = 1 } # TODO
option_if_let_else = { level = "allow", priority = 1 } # TODO
redundant_pub_crate = { level = "allow", priority = 1 } # TODO
significant_drop_in_scrutinee = { level = "allow", priority = 1 } # TODO
significant_drop_tightening = { level = "allow", priority = 1 } # TODO
###################
pedantic = "warn"
## some sadness
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
doc_markdown = "allow"
error_impl_error = "allow"
expect_used = "allow"
if_not_else = "allow"
if_then_some_else_none = "allow"
implicit_return = "allow"
inline_always = "allow"
map_err_ignore = "allow"
missing_docs_in_private_items = "allow"
missing_errors_doc = "allow"
missing_panics_doc = "allow"
mod_module_files = "allow"
module_name_repetitions = "allow"
multiple_inherent_impl = "allow"
no_effect_underscore_binding = "allow"
ref_patterns = "allow"
same_name_method = "allow"
similar_names = { level = "allow", priority = 1 }
single_call_fn = "allow"
string_add = "allow"
string_slice = "allow"
struct_field_names = { level = "allow", priority = 1 }
unnecessary_wraps = { level = "allow", priority = 1 }
unused_async = { level = "allow", priority = 1 }
unwrap_used = "allow"
###################
perf = "warn"
###################
#restriction = "warn"
#arithmetic_side_effects = "warn" # TODO
#as_conversions = "warn" # TODO
assertions_on_result_states = "warn"
dbg_macro = "warn"
default_union_representation = "warn"
deref_by_slicing = "warn"
empty_drop = "warn"
empty_structs_with_brackets = "warn"
exit = "warn"
filetype_is_file = "warn"
float_cmp_const = "warn"
fn_to_numeric_cast_any = "warn"
format_push_string = "warn"
get_unwrap = "warn"
impl_trait_in_params = "warn"
let_underscore_must_use = "warn"
let_underscore_untyped = "warn"
lossy_float_literal = "warn"
mem_forget = "warn"
missing_assert_message = "warn"
mutex_atomic = "warn"
pub_without_shorthand = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
redundant_type_annotations = "warn"
rest_pat_in_fully_bound_structs = "warn"
semicolon_outside_block = "warn"
fn_to_numeric_cast = "warn"
fn_to_numeric_cast_with_truncation = "warn"
str_to_string = "warn"
string_lit_chars_any = "warn"
string_to_string = "warn"
suspicious_xor_used_as_pow = "warn"
tests_outside_test_module = "warn"
try_err = "warn"
undocumented_unsafe_blocks = "warn"
unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unnecessary_self_imports = "warn"
unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn"
verbose_file_reads = "warn"
cast_possible_wrap = "warn"
redundant_closure_for_method_calls = "warn"
large_futures = "warn"
semicolon_if_nothing_returned = "warn"
match_bool = "warn"
struct_excessive_bools = "warn"
must_use_candidate = "warn"
collapsible_else_if = "warn"
inconsistent_struct_constructor = "warn"
manual_string_new = "warn"
zero_sized_map_values = "warn"
unnecessary_box_returns = "warn"
map_unwrap_or = "warn"
implicit_clone = "warn"
match_wildcard_for_single_variants = "warn"
match_same_arms = "warn"
ignored_unit_patterns = "warn"
redundant_else = "warn"
explicit_into_iter_loop = "warn"
used_underscore_binding = "warn"
needless_pass_by_value = "warn"
too_many_lines = "warn"
let_underscore_untyped = "warn"
single_match = "warn"
single_match_else = "warn"
explicit_deref_methods = "warn"
explicit_iter_loop = "warn"
manual_let_else = "warn"
trivially_copy_pass_by_ref = "warn"
wildcard_imports = "warn"
checked_conversions = "warn"
let_underscore_must_use = "warn"
#integer_arithmetic = "warn"
#as_conversions = "warn"
# some sadness
missing_errors_doc = "allow"
missing_panics_doc = "allow"
module_name_repetitions = "allow"
if_not_else = "allow"
doc_markdown = "allow"
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
same_name_method = "allow"
mod_module_files = "allow"
unwrap_used = "allow"
expect_used = "allow"
if_then_some_else_none = "allow"
###################
style = "warn"
## some sadness
# trivial assertions are quite alright
assertions_on_constants = "allow"
###################
suspicious = "warn"
## some sadness
let_underscore_future = "allow"
map_err_ignore = "allow"
missing_docs_in_private_items = "allow"
multiple_inherent_impl = "allow"
error_impl_error = "allow"
string_add = "allow"
string_slice = "allow"
ref_patterns = "allow"
unnecessary_wraps = "allow"

View File

@@ -70,6 +70,7 @@ ci() {
--inputs-from "$toplevel"
# Keep sorted
"$toplevel#devShells.x86_64-linux.default"
"$toplevel#devShells.x86_64-linux.all-features"
attic#default
nixpkgs#direnv

View File

@@ -1 +1,7 @@
too-many-lines-threshold = 700
array-size-threshold = 4096
cognitive-complexity-threshold = 94 # TODO reduce me ALARA
excessive-nesting-threshold = 11 # TODO reduce me to 4 or 5
future-size-threshold = 7745 # TODO reduce me ALARA
stack-size-threshold = 144000 # reduce me ALARA
too-many-lines-threshold = 700 # TODO reduce me to <= 100
type-complexity-threshold = 250 # reduce me to ~200

View File

@@ -77,11 +77,16 @@ database_backend = "rocksdb"
# forwarded to the conduwuit instance running on this port
# Docker users: Don't change this, you'll need to map an external port to this.
# To listen on multiple ports, specify a vector e.g. [8080, 8448]
#
# default if unspecified is 8008
port = 6167
# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
# localhost (127.0.0.1 / ::1). If you are using Docker or a container NAT networking setup, you
# likely need this to be 0.0.0.0.
# To listen multiple addresses, specify a vector e.g. ["127.0.0.1", "::1"]
#
# default if unspecified is both IPv4 and IPv6 localhost: ["127.0.0.1", "::1"]
address = "127.0.0.1"
# Max request size for file uploads
@@ -375,15 +380,6 @@ allow_profile_lookup_federation_requests = true
# Defaults to 256.0
#db_cache_capacity_mb = 256.0
# Interval in seconds when conduwuit will run database cleanup operations.
#
# For SQLite: this will flush the WAL by executing `PRAGMA wal_checkpoint(RESTART)` (https://www.sqlite.org/pragma.html#pragma_wal_checkpoint)
# For RocksDB: this will run `flush_opt` to flush database memtables to SST files on disk (https://docs.rs/rocksdb/latest/rocksdb/struct.DBCommon.html#method.flush_opt)
# These operations always run on shutdown.
#
# Defaults to 30 minutes (1800 seconds) to avoid IO amplification from too frequent cleanups
#cleanup_second_interval = 1800
### RocksDB options
@@ -492,11 +488,6 @@ allow_profile_lookup_federation_requests = true
# Defaults to 1 (TolerateCorruptedTailRecords)
#rocksdb_recovery_mode = 1
# Controls whether memory buffers are written to storage at the fixed interval set by `cleanup_period_interval`
# even when they are not full. Setting this will increase load on the storage backplane and is never advised
# under normal circumstances.
#rocksdb_periodic_cleanup = false
### Domain Name Resolution and Caching
@@ -711,6 +702,44 @@ allow_profile_lookup_federation_requests = true
#typing_client_timeout_max_s = 45
### TURN / VoIP
# vector list of TURN URIs/servers to use
#
# No default
#turn_uris = ["turn:example.turn.uri?transport=udp", "turn:example.turn.uri?transport=tcp"]
# TURN secret to use for generating the HMAC-SHA1 hash apart of username and password generation
#
# this is more secure, but if needed you can use traditional username/password below.
#
# no default
#turn_secret = ""
# TURN username to provide the client
#
# no default
#turn_username = ""
# TURN password to provide the client
#
# no default
#turn_password = ""
# TURN TTL
#
# Default is 86400 seconds
#turn_ttl = 86400
# allow guests/unauthenticated users to access TURN credentials
#
# this is the equivalent of Synapse's `turn_allow_guests` config option. this allows
# any unauthenticated user to call `/_matrix/client/v3/voip/turnServer`.
#
# defaults to false
#turn_allow_guests = false
# Other options not in [global]:
#
#

6
debian/postinst vendored
View File

@@ -25,8 +25,10 @@ case "$1" in
# and permissions for the config.
mkdir -v -p "$CONDUWUIT_DATABASE_PATH"
# symlink the previous location for compatibility
ln -s -v "$CONDUWUIT_DATABASE_PATH" "/var/lib/matrix-conduit"
# symlink the previous location for compatibility if it does not exist yet.
if ! test -L "/var/lib/matrix-conduit" ; then
ln -s -v "$CONDUWUIT_DATABASE_PATH" "/var/lib/matrix-conduit"
fi
chown -v conduwuit:conduwuit -R "$CONDUWUIT_DATABASE_PATH"
chown -v conduwuit:conduwuit -R "$CONDUWUIT_CONFIG_PATH"

View File

@@ -1,7 +1,13 @@
[package]
name = "rust-rocksdb-uwu"
version = "0.0.1"
categories.workspace = true
description = "dylib wrapper for rust-rocksdb"
edition = "2021"
keywords.workspace = true
license.workspace = true
readme.workspace = true
repository.workspace = true
version = "0.0.1"
[features]
default = ["snappy", "lz4", "zstd", "zlib", "bzip2"]
@@ -21,7 +27,8 @@ malloc-usable-size = ["rust-rocksdb/malloc-usable-size"]
[dependencies.rust-rocksdb]
git = "https://github.com/zaidoon1/rust-rocksdb"
branch = "master"
rev = "e9e1cb5ba92a44ea225fe8d13b31aa23621b9035"
#branch = "master"
default-features = false
[lib]

View File

@@ -17,3 +17,4 @@ # Summary
- [Contributing](contributing.md)
- [Testing](development/testing.md)
- [Hot Reloading ("Live" Development)](development/hot_reload.md)
- [conduwuit Community Code of Conduct](conduwuit_coc.md)

View File

@@ -12,9 +12,9 @@ ## Set up the appservice - general instructions
At some point the appservice guide should ask you to add a registration yaml
file to the homeserver. In Synapse you would do this by adding the path to the
homeserver.yaml, but in Conduit you can do this from within Matrix:
homeserver.yaml, but in conduwuit you can do this from within Matrix:
First, go into the #admins room of your homeserver. The first person that
First, go into the `#admins` room of your homeserver. The first person that
registered on the homeserver automatically joins it. Then send a message into
the room like this:
@@ -31,13 +31,13 @@ ## Set up the appservice - general instructions
```
You can confirm it worked by sending a message like this:
`@conduit:your.server.name: appservices list`
`!admin appservices list`
The `@conduit` bot should answer with `Appservices (1): your-bridge`
Then you are done. Conduit will send messages to the appservices and the
Then you are done. conduwuit will send messages to the appservices and the
appservice can send requests to the homeserver. You don't need to restart
Conduit, but if it doesn't work, restarting while the appservice is running
conduwuit, but if it doesn't work, restarting while the appservice is running
could help.
## Appservice-specific instructions
@@ -46,16 +46,6 @@ ### Remove an appservice
To remove an appservice go to your admin room and execute
`@conduit:your.server.name: appservices unregister <name>`
`!admin appservices unregister <name>`
where `<name>` one of the output of `appservices list`.
### Tested appservices
These appservices have been tested and work with Conduit without any extra steps:
- [matrix-appservice-discord](https://github.com/Half-Shot/matrix-appservice-discord)
- [mautrix-hangouts](https://github.com/mautrix/hangouts/)
- [mautrix-telegram](https://github.com/mautrix/telegram/)
- [mautrix-signal](https://github.com/mautrix/signal/) from version `0.2.2` forward.
- [heisenbridge](https://github.com/hifi/heisenbridge/)

77
docs/conduwuit_coc.md Normal file
View File

@@ -0,0 +1,77 @@
# Conduwuit Community Code of Conduct
Welcome to the conduwuit community! Were excited to have you here. Conduwuit is a hard-fork of the Conduit homeserver,
aimed at making Matrix more accessible and inclusive for everyone.
This space is dedicated to fostering a positive, supportive, and inclusive environment for everyone. This Code of
Conduct applies to all conduwuit spaces, including any further community rooms that reference this CoC. Here are our
guidelines to help maintain the welcoming atmosphere that sets conduwuit apart.
For the foundational rules, please refer to the [Matrix.org Code of Conduct](https://matrix.org/legal/code-of-conduct/)
and the [Contributor's Covenant](https://github.com/girlbossceo/conduwuit/blob/main/CODE_OF_CONDUCT.md). Below are
additional guidelines specific to the conduwuit community.
## Our Values and Guidelines
1. **Respect and Inclusivity**: We are committed to maintaining a community where everyone feels safe and respected.
Discrimination, harassment, or hate speech of any kind will not be tolerated. Recognise that each community member
experiences the world differently based on their past experiences, background, and identity. Share your own
experiences and be open to learning about others' diverse perspectives.
2. **Positivity and Constructiveness**: Engage in constructive discussions and support each other. If you feel angry,
negative, or aggressive, take a break until you can participate in a positive and constructive manner. Process
intense feelings with a friend or in a private setting before engaging in community conversations to help maintain
a supportive and focused environment.
3. **Clarity and Understanding**: Our community includes neurodivergent individuals and those who may not appreciate
sarcasm or subtlety. Communicate clearly and kindly, avoiding sarcasm and ensuring your messages are easily
understood by all. Additionally, avoid putting the burden of education on marginalized groups by doing your own
research before asking for explanations.
4. **Be Open to Inclusivity**: Actively engage in conversations about making our community more inclusive. Report
discriminatory behavior to the moderators and be open to constructive feedback that aims to improve our community.
Understand that discussing discrimination and negative experiences can be emotionally taxing, so focus on the
message rather than critiquing the tone used.
5. **Commit to Inclusivity**: Building an inclusive community requires time, energy, and resources. Recognise that
addressing discrimination and bias is an ongoing process that necessitates commitment and action from all community
members.
## Matrix Community
This Code of Conduct applies to the entire [Conduwuit Matrix Space](https://matrix.to/#/#conduwuit-space:puppygock.gay)
and its rooms, including:
### [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay)
This room is for support and discussions about conduwuit. Ask questions, share insights, and help each other out.
### [#conduwuit-offtopic:girlboss.ceo](https://matrix.to/#/#conduwuit-offtopic:girlboss.ceo)
For off-topic community conversations about any subject. While this room allows for a wide range of topics, the same
CoC applies. Keep discussions respectful and inclusive, and avoid divisive subjects like country/world politics.
General topics, such as world events, are welcome as long as they follow the CoC.
### [#conduwuit-dev:puppygock.gay](https://matrix.to/#/#conduwuit-dev:puppygock.gay)
This room is dedicated to discussing active development of conduwuit. Posting requires an elevated power level, which
can be requested in one of the other rooms. Use this space to collaborate and innovate.
## Enforcement
We have a zero-tolerance policy for violations of this Code of Conduct. If someones behavior makes you uncomfortable,
please report it to the moderators. Actions we may take include:
1. **Warning**: A warning given directly in the room or via a private message from the moderators, identifying
the violation and requesting corrective action.
2. **Temporary Mute**: Temporary restriction from participating in discussions for a specified period to allow for
reflection and cooling off.
3. **Kick or Ban**: Egregious behavior may result in an immediate kick or ban to protect other community members.
Bans are considered permanent and will only be reversed in exceptional circumstances after proven good behavior.
Please highlight issues directly in rooms when possible, but if you don't feel comfortable doing that, then please send
a DM to one of the moderators directly.
Together, lets build a community where everyone feels valued and respected.
- The Conduwuit Moderation Team

View File

@@ -49,7 +49,7 @@ ## Creating the conduwuit configuration file
Now we need to create the conduwuit's config file in `/etc/conduwuit/conduwuit.toml`. The example config can be found at [conduwuit-example.toml](../configuration.md).**Please take a moment to read it. You need to change at least the server name.**
RocksDB (`rocksdb`) is the only supported database backend. SQLite only exists for historical reasons and is not recommended. Any performance issues, storage issues, database issues, etc will not be assisted if using SQLite and you will be asked to migrate to RocksDB first.
RocksDB is the only supported database backend. SQLite only exists for historical reasons, is not recommended, and will be removed soon (likely in v0.5.0). Any performance issues, storage issues, database issues, etc will not be assisted if using SQLite and you will be asked to migrate to RocksDB first.
## Setting the correct file permissions
@@ -74,6 +74,8 @@ ## Setting up the Reverse Proxy
Refer to the documentation or various guides online of your chosen reverse proxy software. A [Caddy](https://caddyserver.com/) example will be provided as this is the recommended reverse proxy for new users and is very trivial to use (handles TLS, reverse proxy headers, etc transparently with proper defaults).
Lighttpd is not supported as it seems to mess with the `X-Matrix` Authorization header, making federation non-functional. If using Apache, you need to use `nocanon` to prevent this.
### Caddy
Create `/etc/caddy/conf.d/conduwuit_caddyfile` and enter this (substitute for your server name).

View File

@@ -69,12 +69,15 @@ script = "cargo fmt --check -- --color=always"
name = "cargo-doc"
group = "lints"
script = """
RUSTDOCFLAGS="-D warnings" cargo doc \
--workspace \
--all-features \
--no-deps \
--document-private-items \
--color always
env DIRENV_DEVSHELL=all-features \
RUSTDOCFLAGS="-D warnings" \
direnv exec . \
cargo doc \
--workspace \
--all-features \
--no-deps \
--document-private-items \
--color always
"""
[[task]]
@@ -93,13 +96,15 @@ cargo clippy \
name = "clippy/all"
group = "lints"
script = """
cargo clippy \
--workspace \
--all-targets \
--all-features \
--color=always \
-- \
-D warnings
env DIRENV_DEVSHELL=all-features \
direnv exec . \
cargo clippy \
--workspace \
--all-targets \
--all-features \
--color=always \
-- \
-D warnings
"""
[[task]]
@@ -115,18 +120,18 @@ cargo clippy \
-D warnings
"""
[[task]]
name = "clippy/hardened_malloc"
group = "lints"
script = """
cargo clippy \
--workspace \
--features hardened_malloc \
--all-targets \
--color=always \
-- \
-D warnings
"""
#[[task]]
#name = "clippy/hardened_malloc"
#group = "lints"
#script = """
#cargo clippy \
# --workspace \
# --features hardened_malloc \
# --all-targets \
# --color=always \
# -- \
# -D warnings
#"""
[[task]]
name = "lychee"
@@ -134,13 +139,27 @@ group = "lints"
script = "lychee --verbose --offline docs *.md"
[[task]]
name = "cargo"
name = "cargo/all"
group = "tests"
script = """
env DIRENV_DEVSHELL=all-features \
direnv exec . \
cargo test \
--workspace \
--all-targets \
--all-features \
--color=always \
-- \
--color=always
"""
[[task]]
name = "cargo/default"
group = "tests"
script = """
cargo test \
--workspace \
--all-targets \
--all-features \
--color=always \
-- \
--color=always

View File

@@ -23,8 +23,6 @@
let
# We perform default-feature unification in nix, because some of the dependencies
# on the nix side depend on feature values.
workspaceMembers = builtins.map (member: "${inputs.self}/src/${member}")
(builtins.attrNames (builtins.readDir "${inputs.self}/src"));
crateFeatures = path:
let manifest = lib.importTOML "${path}/Cargo.toml"; in
lib.remove "default" (lib.attrNames manifest.features) ++
@@ -34,10 +32,8 @@ crateFeatures = path:
manifest.dependencies);
crateDefaultFeatures = path:
(lib.importTOML "${path}/Cargo.toml").features.default;
allDefaultFeatures = lib.unique
(lib.flatten (builtins.map crateDefaultFeatures workspaceMembers));
allFeatures = lib.unique
(lib.flatten (builtins.map crateFeatures workspaceMembers));
allDefaultFeatures = crateDefaultFeatures "${inputs.self}/src/main";
allFeatures = crateFeatures "${inputs.self}/src/main";
features' = lib.unique
(features ++
lib.optionals default_features allDefaultFeatures ++

View File

@@ -1,7 +1,13 @@
[package]
name = "conduit_admin"
version.workspace = true
categories.workspace = true
description.workspace = true
edition.workspace = true
keywords.workspace = true
license.workspace = true
readme.workspace = true
repository.workspace = true
version.workspace = true
[lib]
path = "mod.rs"
@@ -11,14 +17,6 @@ crate-type = [
]
[features]
default = [
"rocksdb",
"io_uring",
"jemalloc",
"zstd_compression",
"release_max_log_level",
]
dev_release_log_level = []
release_max_log_level = [
"tracing/max_level_trace",

View File

@@ -3,26 +3,26 @@
use crate::{escape_html, services, Result};
pub(crate) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let appservice_config = body[1..body.len().checked_sub(1).unwrap()].join("\n");
let parsed_config = serde_yaml::from_str::<Registration>(&appservice_config);
match parsed_config {
Ok(yaml) => match services().appservice.register_appservice(yaml).await {
Ok(id) => Ok(RoomMessageEventContent::text_plain(format!(
"Appservice registered with ID: {id}."
))),
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Failed to register appservice: {e}"
))),
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Could not parse appservice config: {e}"
))),
}
} else {
Ok(RoomMessageEventContent::text_plain(
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
));
}
let appservice_config = body[1..body.len().checked_sub(1).unwrap()].join("\n");
let parsed_config = serde_yaml::from_str::<Registration>(&appservice_config);
match parsed_config {
Ok(yaml) => match services().appservice.register_appservice(yaml).await {
Ok(id) => Ok(RoomMessageEventContent::text_plain(format!(
"Appservice registered with ID: {id}."
))),
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Failed to register appservice: {e}"
))),
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Could not parse appservice config: {e}"
))),
}
}
@@ -47,7 +47,7 @@ pub(crate) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Res
{
Some(config) => {
let config_str = serde_yaml::to_string(&config).expect("config should've been validated on register");
let output = format!("Config for {}:\n\n```yaml\n{}\n```", appservice_identifier, config_str,);
let output = format!("Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```",);
let output_html = format!(
"Config for {}:\n\n<pre><code class=\"language-yaml\">{}</code></pre>",
escape_html(&appservice_identifier),

View File

@@ -1,11 +1,17 @@
use std::{collections::BTreeMap, sync::Arc, time::Instant};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
time::Instant,
};
use api::client::validate_and_add_event_id;
use conduit::{utils::HtmlEscape, Error, Result};
use ruma::{
api::client::error::ErrorKind, events::room::message::RoomMessageEventContent, CanonicalJsonObject, EventId,
RoomId, RoomVersionId, ServerName,
api::{client::error::ErrorKind, federation::event::get_room_state},
events::room::message::RoomMessageEventContent,
CanonicalJsonObject, EventId, RoomId, RoomVersionId, ServerName,
};
use service::{rooms::event_handler::parse_incoming_pdu, sending::send::resolve_actual_dest, services, PduEvent};
use service::{rooms::event_handler::parse_incoming_pdu, sending::resolve::resolve_actual_dest, services, PduEvent};
use tokio::sync::RwLock;
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
@@ -37,28 +43,30 @@ pub(crate) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) ->
}
pub(crate) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) {
Ok(value) => match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
Ok(hash) => {
let event_id = EventId::parse(format!("${hash}"));
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
));
}
match serde_json::from_value::<PduEvent>(serde_json::to_value(value).expect("value is json")) {
Ok(pdu) => Ok(RoomMessageEventContent::text_plain(format!("EventId: {event_id:?}\n{pdu:#?}"))),
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"EventId: {event_id:?}\nCould not parse event: {e}"
))),
}
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!("Could not parse PDU JSON: {e:?}"))),
let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) {
Ok(value) => match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
Ok(hash) => {
let event_id = EventId::parse(format!("${hash}"));
match serde_json::from_value::<PduEvent>(serde_json::to_value(value).expect("value is json")) {
Ok(pdu) => Ok(RoomMessageEventContent::text_plain(format!("EventId: {event_id:?}\n{pdu:#?}"))),
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"EventId: {event_id:?}\nCould not parse event: {e}"
))),
}
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Invalid json in command body: {e}"
))),
}
} else {
Ok(RoomMessageEventContent::text_plain("Expected code block in command body."))
Err(e) => Ok(RoomMessageEventContent::text_plain(format!("Could not parse PDU JSON: {e:?}"))),
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Invalid json in command body: {e}"
))),
}
}
@@ -111,33 +119,40 @@ pub(crate) async fn get_remote_pdu_list(
if server == services().globals.server_name() {
return Ok(RoomMessageEventContent::text_plain(
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs from \
the database.",
));
}
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let list = body
.clone()
.drain(1..body.len().checked_sub(1).unwrap())
.filter_map(|pdu| EventId::parse(pdu).ok())
.collect::<Vec<_>>();
for pdu in list {
if force {
if let Err(e) = get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await {
warn!(%e, "Failed to get remote PDU, ignoring error");
}
} else {
get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await?;
}
}
return Ok(RoomMessageEventContent::text_plain("Fetched list of remote PDUs."));
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
));
}
Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
let list = body
.clone()
.drain(1..body.len().checked_sub(1).unwrap())
.filter_map(|pdu| EventId::parse(pdu).ok())
.collect::<Vec<_>>();
for pdu in list {
if force {
if let Err(e) = get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await {
services()
.admin
.send_message(RoomMessageEventContent::text_plain(format!(
"Failed to get remote PDU, ignoring error: {e}"
)))
.await;
warn!(%e, "Failed to get remote PDU, ignoring error");
}
} else {
get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await?;
}
}
Ok(RoomMessageEventContent::text_plain("Fetched list of remote PDUs."))
}
pub(crate) async fn get_remote_pdu(
@@ -294,8 +309,7 @@ pub(crate) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
}
Ok(RoomMessageEventContent::text_plain(format!(
"Got non-JSON response which took {ping_time:?} time:\n{0:?}",
response
"Got non-JSON response which took {ping_time:?} time:\n{response:?}"
)))
},
Err(e) => {
@@ -379,56 +393,239 @@ pub(crate) async fn change_log_level(
}
pub(crate) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
match serde_json::from_str(&string) {
Ok(mut value) => {
ruma::signatures::sign_json(
services().globals.server_name().as_str(),
services().globals.keypair(),
&mut value,
)
.expect("our request json is what ruma expects");
let json_text = serde_json::to_string_pretty(&value).expect("canonical json is valid json");
Ok(RoomMessageEventContent::text_plain(json_text))
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!("Invalid json: {e}"))),
}
} else {
Ok(RoomMessageEventContent::text_plain(
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
));
}
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
match serde_json::from_str(&string) {
Ok(mut value) => {
ruma::signatures::sign_json(
services().globals.server_name().as_str(),
services().globals.keypair(),
&mut value,
)
.expect("our request json is what ruma expects");
let json_text = serde_json::to_string_pretty(&value).expect("canonical json is valid json");
Ok(RoomMessageEventContent::text_plain(json_text))
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!("Invalid json: {e}"))),
}
}
pub(crate) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
match serde_json::from_str(&string) {
Ok(value) => {
let pub_key_map = RwLock::new(BTreeMap::new());
services()
.rooms
.event_handler
.fetch_required_signing_keys([&value], &pub_key_map)
.await?;
let pub_key_map = pub_key_map.read().await;
match ruma::signatures::verify_json(&pub_key_map, &value) {
Ok(()) => Ok(RoomMessageEventContent::text_plain("Signature correct")),
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Signature verification failed: {e}"
))),
}
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!("Invalid json: {e}"))),
}
} else {
Ok(RoomMessageEventContent::text_plain(
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
));
}
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
match serde_json::from_str(&string) {
Ok(value) => {
let pub_key_map = RwLock::new(BTreeMap::new());
services()
.rooms
.event_handler
.fetch_required_signing_keys([&value], &pub_key_map)
.await?;
let pub_key_map = pub_key_map.read().await;
match ruma::signatures::verify_json(&pub_key_map, &value) {
Ok(()) => Ok(RoomMessageEventContent::text_plain("Signature correct")),
Err(e) => Ok(RoomMessageEventContent::text_plain(format!(
"Signature verification failed: {e}"
))),
}
},
Err(e) => Ok(RoomMessageEventContent::text_plain(format!("Invalid json: {e}"))),
}
}
#[tracing::instrument(skip(_body))]
pub(crate) async fn first_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
if !services()
.rooms
.state_cache
.server_in_room(&services().globals.config.server_name, &room_id)?
{
return Ok(RoomMessageEventContent::text_plain(
"We are not participating in the room / we don't know about the room ID.",
));
}
let first_pdu = services()
.rooms
.timeline
.first_pdu_in_room(&room_id)?
.ok_or_else(|| Error::bad_database("Failed to find the first PDU in database"))?;
Ok(RoomMessageEventContent::text_plain(format!("{first_pdu:?}")))
}
#[tracing::instrument(skip(_body))]
pub(crate) async fn latest_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
if !services()
.rooms
.state_cache
.server_in_room(&services().globals.config.server_name, &room_id)?
{
return Ok(RoomMessageEventContent::text_plain(
"We are not participating in the room / we don't know about the room ID.",
));
}
let latest_pdu = services()
.rooms
.timeline
.latest_pdu_in_room(&room_id)?
.ok_or_else(|| Error::bad_database("Failed to find the latest PDU in database"))?;
Ok(RoomMessageEventContent::text_plain(format!("{latest_pdu:?}")))
}
#[tracing::instrument(skip(_body))]
pub(crate) async fn force_set_room_state_from_server(
_body: Vec<&str>, server_name: Box<ServerName>, room_id: Box<RoomId>,
) -> Result<RoomMessageEventContent> {
if !services()
.rooms
.state_cache
.server_in_room(&services().globals.config.server_name, &room_id)?
{
return Ok(RoomMessageEventContent::text_plain(
"We are not participating in the room / we don't know about the room ID.",
));
}
let first_pdu = services()
.rooms
.timeline
.latest_pdu_in_room(&room_id)?
.ok_or_else(|| Error::bad_database("Failed to find the latest PDU in database"))?;
let room_version = services().rooms.state.get_room_version(&room_id)?;
let mut state: HashMap<u64, Arc<EventId>> = HashMap::new();
let pub_key_map = RwLock::new(BTreeMap::new());
let remote_state_response = services()
.sending
.send_federation_request(
&server_name,
get_room_state::v1::Request {
room_id: room_id.clone().into(),
event_id: first_pdu.event_id.clone().into(),
},
)
.await?;
let mut events = Vec::with_capacity(remote_state_response.pdus.len());
for pdu in remote_state_response.pdus.clone() {
events.push(match parse_incoming_pdu(&pdu) {
Ok(t) => t,
Err(e) => {
warn!("Could not parse PDU, ignoring: {e}");
continue;
},
});
}
info!("Fetching required signing keys for all the state events we got");
services()
.rooms
.event_handler
.fetch_required_signing_keys(events.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
.await?;
info!("Going through room_state response PDUs");
for result in remote_state_response
.pdus
.iter()
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map))
{
let Ok((event_id, value)) = result.await else {
continue;
};
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
warn!("Invalid PDU in fetching remote room state PDUs response: {} {:?}", e, value);
Error::BadServerResponse("Invalid PDU in send_join response.")
})?;
services()
.rooms
.outlier
.add_pdu_outlier(&event_id, &value)?;
if let Some(state_key) = &pdu.state_key {
let shortstatekey = services()
.rooms
.short
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)?;
state.insert(shortstatekey, pdu.event_id.clone());
}
}
info!("Going through auth_chain response");
for result in remote_state_response
.auth_chain
.iter()
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map))
{
let Ok((event_id, value)) = result.await else {
continue;
};
services()
.rooms
.outlier
.add_pdu_outlier(&event_id, &value)?;
}
let new_room_state = services()
.rooms
.event_handler
.resolve_state(room_id.clone().as_ref(), &room_version, state)
.await?;
info!("Forcing new room state");
let (short_state_hash, new, removed) = services()
.rooms
.state_compressor
.save_state(room_id.clone().as_ref(), new_room_state)?;
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone().into())
.or_default(),
);
let state_lock = mutex_state.lock().await;
services()
.rooms
.state
.force_state(room_id.clone().as_ref(), short_state_hash, new, removed, &state_lock)
.await?;
info!(
"Updating joined counts for room just in case (e.g. we may have found a difference in the room's \
m.room.member state"
);
services().rooms.state_cache.update_joined_count(&room_id)?;
drop(state_lock);
Ok(RoomMessageEventContent::text_plain(
"Successfully forced the room state from the requested remote server.",
))
}
pub(crate) async fn resolve_true_destination(
@@ -446,10 +643,10 @@ pub(crate) async fn resolve_true_destination(
));
}
let (actual_dest, hostname_uri) = resolve_actual_dest(&server_name, no_cache).await?;
let (actual_dest, hostname_uri) = resolve_actual_dest(&server_name, !no_cache).await?;
Ok(RoomMessageEventContent::text_plain(format!(
"Actual destination: {actual_dest:?} | Hostname URI: {hostname_uri}"
"Actual destination: {actual_dest} | Hostname URI: {hostname_uri}"
)))
}

View File

@@ -1,4 +1,5 @@
use clap::Subcommand;
use debug_commands::{first_pdu_in_room, force_set_room_state_from_server, latest_pdu_in_room};
use ruma::{events::room::message::RoomMessageEventContent, EventId, RoomId, ServerName};
use self::debug_commands::{
@@ -45,7 +46,8 @@ pub(crate) enum DebugCommand {
server: Box<ServerName>,
},
/// Same as `get-remote-pdu` but accepts a codeblock newline delimited list
/// - Same as `get-remote-pdu` but accepts a codeblock newline delimited
/// list
/// of PDUs and a single server to fetch from
GetRemotePduList {
/// Argument for us to attempt to fetch all the events from the
@@ -107,6 +109,41 @@ pub(crate) enum DebugCommand {
/// the command.
VerifyJson,
/// - Prints the very first PDU in the specified room (typically
/// m.room.create)
FirstPduInRoom {
/// The room ID
room_id: Box<RoomId>,
},
/// - Prints the latest ("last") PDU in the specified room (typically a
/// message)
LatestPduInRoom {
/// The room ID
room_id: Box<RoomId>,
},
/// - Forcefully replaces the room state of our local copy of the specified
/// room, with the copy (auth chain and room state events) the specified
/// remote server says.
///
/// A common desire for room deletion is to simply "reset" our copy of the
/// room. While this admin command is not a replacement for that, if you
/// know you have split/broken room state and you know another server in the
/// room that has the best/working room state, this command can let you use
/// their room state. Such example is your server saying users are in a
/// room, but other servers are saying they're not in the room in question.
///
/// This command will get the latest PDU in the room we know about, and
/// request the room state at that point in time via
/// `/_matrix/federation/v1/state/{roomId}`.
ForceSetRoomStateFromServer {
/// The impacted room ID
room_id: Box<RoomId>,
/// The server we will use to query the room state for
server_name: Box<ServerName>,
},
/// - Runs a server name through conduwuit's true destination resolution
/// process
///
@@ -148,10 +185,20 @@ pub(crate) async fn process(command: DebugCommand, body: Vec<&str>) -> Result<Ro
} => change_log_level(body, filter, reset).await?,
DebugCommand::SignJson => sign_json(body).await?,
DebugCommand::VerifyJson => verify_json(body).await?,
DebugCommand::FirstPduInRoom {
room_id,
} => first_pdu_in_room(body, room_id).await?,
DebugCommand::LatestPduInRoom {
room_id,
} => latest_pdu_in_room(body, room_id).await?,
DebugCommand::GetRemotePduList {
server,
force,
} => get_remote_pdu_list(body, server, force).await?,
DebugCommand::ForceSetRoomStateFromServer {
room_id,
server_name,
} => force_set_room_state_from_server(body, server_name, room_id).await?,
DebugCommand::ResolveTrueDestination {
server_name,
no_cache,

View File

@@ -14,7 +14,7 @@ pub(crate) async fn enable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Resul
Ok(RoomMessageEventContent::text_plain("Room enabled."))
}
pub(crate) async fn incoming_federeation(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn incoming_federation(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let map = services().globals.roomid_federationhandletime.read().await;
let mut msg = format!("Handling {} incoming pdus:\n", map.len());
@@ -101,7 +101,8 @@ pub(crate) async fn remote_user_in_rooms(_body: Vec<&str>, user_id: Box<UserId>)
rooms.reverse();
let output_plain = format!(
"Rooms {user_id} shares with us:\n{}",
"Rooms {user_id} shares with us ({}):\n{}",
rooms.len(),
rooms
.iter()
.map(|(id, members, name)| format!("{id}\tMembers: {members}\tName: {name}"))
@@ -109,15 +110,16 @@ pub(crate) async fn remote_user_in_rooms(_body: Vec<&str>, user_id: Box<UserId>)
.join("\n")
);
let output_html = format!(
"<table><caption>Rooms {user_id} shares with \
us</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
"<table><caption>Rooms {user_id} shares with us \
({})</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
rooms.len(),
rooms
.iter()
.fold(String::new(), |mut output, (id, members, name)| {
writeln!(
output,
"<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>",
escape_html(id.as_ref()),
id,
members,
escape_html(name)
)

View File

@@ -2,7 +2,7 @@
use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName, UserId};
use self::federation_commands::{
disable_room, enable_room, fetch_support_well_known, incoming_federeation, remote_user_in_rooms,
disable_room, enable_room, fetch_support_well_known, incoming_federation, remote_user_in_rooms,
};
use crate::Result;
@@ -51,7 +51,7 @@ pub(crate) async fn process(command: FederationCommand, body: Vec<&str>) -> Resu
FederationCommand::EnableRoom {
room_id,
} => enable_room(body, room_id).await?,
FederationCommand::IncomingFederation => incoming_federeation(body).await?,
FederationCommand::IncomingFederation => incoming_federation(body).await?,
FederationCommand::FetchSupportWellKnown {
server_name,
} => fetch_support_well_known(body, server_name).await?,

View File

@@ -17,9 +17,8 @@ pub(crate) async fn check_all_users(_body: Vec<&str>) -> Result<RoomMessageEvent
let ok_count = users.iter().filter(|user| user.is_ok()).count();
let message = format!(
"Database query completed in {query_time:?}:\n\n```\nTotal entries: {:?}\nFailure/Invalid user count: \
{:?}\nSuccess/Valid user count: {:?}```",
total, err_count, ok_count
"Database query completed in {query_time:?}:\n\n```\nTotal entries: {total:?}\nFailure/Invalid user count: \
{err_count:?}\nSuccess/Valid user count: {ok_count:?}```"
);
Ok(RoomMessageEventContent::notice_html(message, String::new()))

View File

@@ -8,7 +8,7 @@
room::message::{Relation::Reply, RoomMessageEventContent},
TimelineEventType,
},
OwnedRoomId, OwnedUserId, ServerName, UserId,
OwnedRoomId, OwnedUserId, RoomId, ServerName, UserId,
};
use serde_json::value::to_raw_value;
use tokio::sync::MutexGuard;
@@ -81,7 +81,8 @@ async fn handle_event(event: AdminRoomEvent, admin_room: OwnedRoomId, server_use
let (mut message_content, reply) = match event {
AdminRoomEvent::SendMessage(content) => (content, None),
AdminRoomEvent::ProcessMessage(room_message, reply_id) => {
(process_admin_message(room_message).await, Some(reply_id))
// This future is ~8 KiB so it's better to start it off the stack.
(Box::pin(process_admin_message(room_message)).await, Some(reply_id))
},
};
@@ -125,7 +126,7 @@ async fn handle_event(event: AdminRoomEvent, admin_room: OwnedRoomId, server_use
}
async fn handle_response_error(
e: &Error, admin_room: &OwnedRoomId, server_user: &UserId, state_lock: &MutexGuard<'_, ()>,
e: &Error, admin_room: &RoomId, server_user: &UserId, state_lock: &MutexGuard<'_, ()>,
) -> Result<()> {
error!("Failed to build and append admin room response PDU: \"{e}\"");
let error_room_message = RoomMessageEventContent::text_plain(format!(

View File

@@ -23,7 +23,7 @@ pub(crate) async fn delete(
debug!("Got event ID to delete media from: {event_id}");
let mut mxc_urls = vec![];
let mut mxc_deletion_count = 0;
let mut mxc_deletion_count: usize = 0;
// parsing the PDU for any MXC URLs begins here
if let Some(event_json) = services().rooms.timeline.get_pdu_json(&event_id)? {
@@ -123,7 +123,7 @@ pub(crate) async fn delete(
for mxc_url in mxc_urls {
services().media.delete(mxc_url).await?;
mxc_deletion_count += 1;
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
}
return Ok(RoomMessageEventContent::text_plain(format!(
@@ -138,36 +138,38 @@ pub(crate) async fn delete(
}
pub(crate) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let mxc_list = body
.clone()
.drain(1..body.len().checked_sub(1).unwrap())
.collect::<Vec<_>>();
let mut mxc_deletion_count: usize = 0;
for mxc in mxc_list {
debug!("Deleting MXC {mxc} in bulk");
services().media.delete(mxc.to_owned()).await?;
mxc_deletion_count = mxc_deletion_count
.checked_add(1)
.expect("mxc_deletion_count should not get this high");
}
return Ok(RoomMessageEventContent::text_plain(format!(
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our database and the filesystem.",
)));
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
));
}
Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
let mxc_list = body
.clone()
.drain(1..body.len().checked_sub(1).unwrap())
.collect::<Vec<_>>();
let mut mxc_deletion_count: usize = 0;
for mxc in mxc_list {
debug!("Deleting MXC {mxc} in bulk");
services().media.delete(mxc.to_owned()).await?;
mxc_deletion_count = mxc_deletion_count
.checked_add(1)
.expect("mxc_deletion_count should not get this high");
}
Ok(RoomMessageEventContent::text_plain(format!(
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our database and the filesystem.",
)))
}
pub(crate) async fn delete_past_remote_media(_body: Vec<&str>, duration: String) -> Result<RoomMessageEventContent> {
pub(crate) async fn delete_past_remote_media(
_body: Vec<&str>, duration: String, force: bool,
) -> Result<RoomMessageEventContent> {
let deleted_count = services()
.media
.delete_all_remote_media_at_after_time(duration)
.delete_all_remote_media_at_after_time(duration, force)
.await?;
Ok(RoomMessageEventContent::text_plain(format!(

View File

@@ -32,6 +32,9 @@ pub(crate) enum MediaCommand {
/// - The duration (at or after), e.g. "5m" to delete all media in the
/// past 5 minutes
duration: String,
/// Continues deleting remote media if an undeletable object is found
#[arg(short, long)]
force: bool,
},
}
@@ -44,6 +47,7 @@ pub(crate) async fn process(command: MediaCommand, body: Vec<&str>) -> Result<Ro
MediaCommand::DeleteList => delete_list(body).await?,
MediaCommand::DeletePastRemoteMedia {
duration,
} => delete_past_remote_media(body, duration).await?,
force,
} => delete_past_remote_media(body, duration, force).await?,
})
}

View File

@@ -19,11 +19,8 @@ pub(crate) async fn account_data(subcommand: AccountData) -> Result<RoomMessageE
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
AccountData::Get {
@@ -39,11 +36,8 @@ pub(crate) async fn account_data(subcommand: AccountData) -> Result<RoomMessageE
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
}

View File

@@ -17,11 +17,8 @@ pub(crate) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEven
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
Appservice::All => {
@@ -30,11 +27,8 @@ pub(crate) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEven
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
}

View File

@@ -12,11 +12,8 @@ pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventConte
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
Globals::CurrentCount => {
@@ -25,11 +22,8 @@ pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventConte
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
Globals::LastCheckForUpdatesId => {
@@ -38,11 +32,8 @@ pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventConte
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
Globals::LoadKeypair => {
@@ -51,11 +42,8 @@ pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventConte
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
Globals::SigningKeysFor {
@@ -66,11 +54,8 @@ pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventConte
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
}

View File

@@ -3,10 +3,12 @@
pub(crate) mod globals;
pub(crate) mod presence;
pub(crate) mod room_alias;
pub(crate) mod room_state_cache;
pub(crate) mod sending;
pub(crate) mod users;
use clap::Subcommand;
use room_state_cache::room_state_cache;
use ruma::{
events::{room::message::RoomMessageEventContent, RoomAccountDataEventType},
RoomAliasId, RoomId, ServerName, UserId,
@@ -38,6 +40,10 @@ pub(crate) enum QueryCommand {
#[command(subcommand)]
RoomAlias(RoomAlias),
/// - rooms/state_cache iterators and getters
#[command(subcommand)]
RoomStateCache(RoomStateCache),
/// - globals.rs iterators and getters
#[command(subcommand)]
Globals(Globals),
@@ -127,6 +133,78 @@ pub(crate) enum RoomAlias {
AllLocalAliases,
}
#[cfg_attr(test, derive(Debug))]
#[derive(Subcommand)]
pub(crate) enum RoomStateCache {
ServerInRoom {
server: Box<ServerName>,
room_id: Box<RoomId>,
},
RoomServers {
room_id: Box<RoomId>,
},
ServerRooms {
server: Box<ServerName>,
},
RoomMembers {
room_id: Box<RoomId>,
},
LocalUsersInRoom {
room_id: Box<RoomId>,
},
ActiveLocalUsersInRoom {
room_id: Box<RoomId>,
},
RoomJoinedCount {
room_id: Box<RoomId>,
},
RoomInvitedCount {
room_id: Box<RoomId>,
},
RoomUserOnceJoined {
room_id: Box<RoomId>,
},
RoomMembersInvited {
room_id: Box<RoomId>,
},
GetInviteCount {
room_id: Box<RoomId>,
user_id: Box<UserId>,
},
GetLeftCount {
room_id: Box<RoomId>,
user_id: Box<UserId>,
},
RoomsJoined {
user_id: Box<UserId>,
},
RoomsLeft {
user_id: Box<UserId>,
},
RoomsInvited {
user_id: Box<UserId>,
},
InviteState {
user_id: Box<UserId>,
room_id: Box<RoomId>,
},
}
#[cfg_attr(test, derive(Debug))]
#[derive(Subcommand)]
/// All the getters and iterators from src/database/key_value/globals.rs
@@ -216,6 +294,7 @@ pub(crate) async fn process(command: QueryCommand, _body: Vec<&str>) -> Result<R
QueryCommand::Appservice(command) => appservice(command).await?,
QueryCommand::Presence(command) => presence(command).await?,
QueryCommand::RoomAlias(command) => room_alias(command).await?,
QueryCommand::RoomStateCache(command) => room_state_cache(command).await?,
QueryCommand::Globals(command) => globals(command).await?,
QueryCommand::Sending(command) => sending(command).await?,
QueryCommand::Users(command) => users(command).await?,

View File

@@ -14,11 +14,8 @@ pub(crate) async fn presence(subcommand: Presence) -> Result<RoomMessageEventCon
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
Presence::PresenceSince {
@@ -31,11 +28,8 @@ pub(crate) async fn presence(subcommand: Presence) -> Result<RoomMessageEventCon
let presence_since: Vec<(_, _, _)> = results.collect();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", presence_since),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
presence_since
),
format!("Query completed in {query_time:?}:\n\n```\n{presence_since:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{presence_since:?}\n</code></pre>"),
))
},
}

View File

@@ -14,11 +14,8 @@ pub(crate) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEvent
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomAlias::LocalAliasesForRoom {
@@ -31,11 +28,8 @@ pub(crate) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEvent
let aliases: Vec<_> = results.collect();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", aliases),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
aliases
),
format!("Query completed in {query_time:?}:\n\n```\n{aliases:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{aliases:?}\n</code></pre>"),
))
},
RoomAlias::AllLocalAliases => {
@@ -46,11 +40,8 @@ pub(crate) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEvent
let aliases: Vec<_> = results.collect();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", aliases),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
aliases
),
format!("Query completed in {query_time:?}:\n\n```\n{aliases:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{aliases:?}\n</code></pre>"),
))
},
}

View File

@@ -0,0 +1,249 @@
use ruma::events::room::message::RoomMessageEventContent;
use super::RoomStateCache;
use crate::{services, Result};
pub(crate) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomMessageEventContent> {
match subcommand {
RoomStateCache::ServerInRoom {
server,
room_id,
} => {
let timer = tokio::time::Instant::now();
let result = services()
.rooms
.state_cache
.server_in_room(&server, &room_id);
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{result:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{result:?}\n</code></pre>"),
))
},
RoomStateCache::RoomServers {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services()
.rooms
.state_cache
.room_servers(&room_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::ServerRooms {
server,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services().rooms.state_cache.server_rooms(&server).collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomMembers {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services()
.rooms
.state_cache
.room_members(&room_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::LocalUsersInRoom {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results: Vec<_> = services()
.rooms
.state_cache
.local_users_in_room(&room_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::ActiveLocalUsersInRoom {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results: Vec<_> = services()
.rooms
.state_cache
.active_local_users_in_room(&room_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomJoinedCount {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results = services().rooms.state_cache.room_joined_count(&room_id);
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomInvitedCount {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results = services().rooms.state_cache.room_invited_count(&room_id);
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomUserOnceJoined {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services()
.rooms
.state_cache
.room_useroncejoined(&room_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomMembersInvited {
room_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services()
.rooms
.state_cache
.room_members_invited(&room_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::GetInviteCount {
room_id,
user_id,
} => {
let timer = tokio::time::Instant::now();
let results = services()
.rooms
.state_cache
.get_invite_count(&room_id, &user_id);
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::GetLeftCount {
room_id,
user_id,
} => {
let timer = tokio::time::Instant::now();
let results = services()
.rooms
.state_cache
.get_left_count(&room_id, &user_id);
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomsJoined {
user_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services()
.rooms
.state_cache
.rooms_joined(&user_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomsInvited {
user_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services()
.rooms
.state_cache
.rooms_invited(&user_id)
.collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::RoomsLeft {
user_id,
} => {
let timer = tokio::time::Instant::now();
let results: Result<Vec<_>> = services().rooms.state_cache.rooms_left(&user_id).collect();
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
RoomStateCache::InviteState {
user_id,
room_id,
} => {
let timer = tokio::time::Instant::now();
let results = services()
.rooms
.state_cache
.invite_state(&user_id, &room_id);
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
}
}

View File

@@ -14,11 +14,8 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
let active_requests: Result<Vec<(_, _, _)>> = results.collect();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", active_requests),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
active_requests
),
format!("Query completed in {query_time:?}:\n\n```\n{active_requests:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{active_requests:?}\n</code></pre>"),
))
},
Sending::QueuedRequests {
@@ -96,11 +93,8 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
let queued_requests = results.collect::<Result<Vec<(_, _)>>>();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", queued_requests),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
queued_requests
),
format!("Query completed in {query_time:?}:\n\n```\n{queued_requests:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{queued_requests:?}\n</code></pre>"),
))
},
Sending::ActiveRequestsFor {
@@ -178,11 +172,8 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
let active_requests = results.collect::<Result<Vec<(_, _)>>>();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", active_requests),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
active_requests
),
format!("Query completed in {query_time:?}:\n\n```\n{active_requests:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{active_requests:?}\n</code></pre>"),
))
},
Sending::GetLatestEduCount {
@@ -193,11 +184,8 @@ pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
let query_time = timer.elapsed();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", results),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
results
),
format!("Query completed in {query_time:?}:\n\n```\n{results:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{results:?}\n</code></pre>"),
))
},
}

View File

@@ -14,11 +14,8 @@ pub(crate) async fn users(subcommand: Users) -> Result<RoomMessageEventContent>
let users = results.collect::<Vec<_>>();
Ok(RoomMessageEventContent::text_html(
format!("Query completed in {query_time:?}:\n\n```\n{:?}```", users),
format!(
"<p>Query completed in {query_time:?}:</p>\n<pre><code>{:?}\n</code></pre>",
users
),
format!("Query completed in {query_time:?}:\n\n```\n{users:?}```"),
format!("<p>Query completed in {query_time:?}:</p>\n<pre><code>{users:?}\n</code></pre>"),
))
},
}

View File

@@ -7,6 +7,7 @@
pub(crate) mod room_alias_commands;
pub(crate) mod room_commands;
pub(crate) mod room_directory_commands;
pub(crate) mod room_info_commands;
pub(crate) mod room_moderation_commands;
#[cfg_attr(test, derive(Debug))]
@@ -17,6 +18,10 @@ pub(crate) enum RoomCommand {
page: Option<usize>,
},
#[command(subcommand)]
/// - View information about a room we know about
Info(RoomInfoCommand),
#[command(subcommand)]
/// - Manage moderation of remote or local rooms
Moderation(RoomModerationCommand),
@@ -30,6 +35,23 @@ pub(crate) enum RoomCommand {
Directory(RoomDirectoryCommand),
}
#[cfg_attr(test, derive(Debug))]
#[derive(Subcommand)]
pub(crate) enum RoomInfoCommand {
/// - List joined members in a room
ListJoinedMembers {
room_id: Box<RoomId>,
},
/// - Displays room topic
///
/// Room topics can be huge, so this is in its
/// own separate command
ViewRoomTopic {
room_id: Box<RoomId>,
},
}
#[cfg_attr(test, derive(Debug))]
#[derive(Subcommand)]
pub(crate) enum RoomAliasCommand {
@@ -147,6 +169,8 @@ pub(crate) enum RoomModerationCommand {
pub(crate) async fn process(command: RoomCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
Ok(match command {
RoomCommand::Info(command) => room_info_commands::process(command, body).await?,
RoomCommand::Alias(command) => room_alias_commands::process(command, body).await?,
RoomCommand::Directory(command) => room_directory_commands::process(command, body).await?,

View File

@@ -6,6 +6,8 @@
use crate::{escape_html, services, Result};
pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
let server_user = &services().globals.server_user;
match command {
RoomAliasCommand::Set {
ref room_alias_localpart,
@@ -20,7 +22,7 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
let room_alias_str = format!("#{}:{}", room_alias_localpart, services().globals.server_name());
let room_alias = match RoomAliasId::parse_box(room_alias_str) {
Ok(alias) => alias,
Err(err) => return Ok(RoomMessageEventContent::text_plain(format!("Failed to parse alias: {}", err))),
Err(err) => return Ok(RoomMessageEventContent::text_plain(format!("Failed to parse alias: {err}"))),
};
match command {
RoomAliasCommand::Set {
@@ -28,18 +30,24 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
room_id,
..
} => match (force, services().rooms.alias.resolve_local_alias(&room_alias)) {
(true, Ok(Some(id))) => match services().rooms.alias.set_alias(&room_alias, &room_id) {
(true, Ok(Some(id))) => match services()
.rooms
.alias
.set_alias(&room_alias, &room_id, server_user)
{
Ok(()) => Ok(RoomMessageEventContent::text_plain(format!(
"Successfully overwrote alias (formerly {})",
id
"Successfully overwrote alias (formerly {id})"
))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Failed to remove alias: {}", err))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Failed to remove alias: {err}"))),
},
(false, Ok(Some(id))) => Ok(RoomMessageEventContent::text_plain(format!(
"Refusing to overwrite in use alias for {}, use -f or --force to overwrite",
id
"Refusing to overwrite in use alias for {id}, use -f or --force to overwrite"
))),
(_, Ok(None)) => match services().rooms.alias.set_alias(&room_alias, &room_id) {
(_, Ok(None)) => match services()
.rooms
.alias
.set_alias(&room_alias, &room_id, server_user)
{
Ok(()) => Ok(RoomMessageEventContent::text_plain("Successfully set alias")),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Failed to remove alias: {err}"))),
},
@@ -48,19 +56,24 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
RoomAliasCommand::Remove {
..
} => match services().rooms.alias.resolve_local_alias(&room_alias) {
Ok(Some(id)) => match services().rooms.alias.remove_alias(&room_alias) {
Ok(()) => Ok(RoomMessageEventContent::text_plain(format!("Removed alias from {}", id))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Failed to remove alias: {}", err))),
Ok(Some(id)) => match services()
.rooms
.alias
.remove_alias(&room_alias, server_user)
.await
{
Ok(()) => Ok(RoomMessageEventContent::text_plain(format!("Removed alias from {id}"))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Failed to remove alias: {err}"))),
},
Ok(None) => Ok(RoomMessageEventContent::text_plain("Alias isn't in use.")),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {}", err))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {err}"))),
},
RoomAliasCommand::Which {
..
} => match services().rooms.alias.resolve_local_alias(&room_alias) {
Ok(Some(id)) => Ok(RoomMessageEventContent::text_plain(format!("Alias resolves to {}", id))),
Ok(Some(id)) => Ok(RoomMessageEventContent::text_plain(format!("Alias resolves to {id}"))),
Ok(None) => Ok(RoomMessageEventContent::text_plain("Alias isn't in use.")),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {}", err))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {err}"))),
},
RoomAliasCommand::List {
..
@@ -93,7 +106,7 @@ pub(crate) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
let html = format!("Aliases for {room_id}:\n<ul>{html_list}</ul>");
Ok(RoomMessageEventContent::text_html(plain, html))
},
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to list aliases: {}", err))),
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to list aliases: {err}"))),
}
} else {
let aliases = services()

View File

@@ -0,0 +1,93 @@
use std::fmt::Write;
use ruma::{events::room::message::RoomMessageEventContent, RoomId};
use service::services;
use super::RoomInfoCommand;
use crate::{escape_html, Result};
pub(crate) async fn process(command: RoomInfoCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
match command {
RoomInfoCommand::ListJoinedMembers {
room_id,
} => list_joined_members(body, room_id).await,
RoomInfoCommand::ViewRoomTopic {
room_id,
} => view_room_topic(body, room_id).await,
}
}
async fn list_joined_members(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
let room_name = services()
.rooms
.state_accessor
.get_name(&room_id)
.ok()
.flatten()
.unwrap_or_else(|| room_id.to_string());
let members = services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(Result::ok);
let member_info = members
.into_iter()
.map(|user_id| {
(
user_id.clone(),
services()
.users
.displayname(&user_id)
.unwrap_or(None)
.unwrap_or_else(|| user_id.to_string()),
)
})
.collect::<Vec<_>>();
let output_plain = format!(
"{} Members in Room \"{}\":\n```\n{}\n```",
member_info.len(),
room_name,
member_info
.iter()
.map(|(mxid, displayname)| format!("{mxid} | {displayname}"))
.collect::<Vec<_>>()
.join("\n")
);
let output_html = format!(
"<table><caption>{} Members in Room \"{}\" </caption>\n<tr><th>MXID</th>\t<th>Display \
Name</th></tr>\n{}</table>",
member_info.len(),
room_name,
member_info
.iter()
.fold(String::new(), |mut output, (mxid, displayname)| {
writeln!(
output,
"<tr><td>{}</td>\t<td>{}</td></tr>",
mxid,
escape_html(displayname.as_ref())
)
.expect("should be able to write to string buffer");
output
})
);
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
}
async fn view_room_topic(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
let Some(room_topic) = services().rooms.state_accessor.get_room_topic(&room_id)? else {
return Ok(RoomMessageEventContent::text_plain("Room does not have a room topic set."));
};
let output_html = format!("<p>Room topic:</p>\n<hr>\n{}<hr>", escape_html(&room_topic));
Ok(RoomMessageEventContent::text_html(
format!("Room topic:\n\n```{room_topic}\n```"),
output_html,
))
}

View File

@@ -1,16 +1,13 @@
use std::fmt::Write;
use api::client_server::{get_alias_helper, leave_room};
use api::client::{get_alias_helper, leave_room};
use ruma::{
events::room::message::RoomMessageEventContent, OwnedRoomId, OwnedUserId, RoomAliasId, RoomId, RoomOrAliasId,
};
use tracing::{debug, error, info, warn};
use super::{
super::{escape_html, Service},
RoomModerationCommand,
};
use crate::{services, user_is_local, Result};
use super::{super::Service, RoomModerationCommand};
use crate::{escape_html, get_room_info, services, user_is_local, Result};
pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
match command {
@@ -18,91 +15,101 @@ pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) ->
force,
room,
disable_federation,
} => {
debug!("Got room alias or ID: {}", room);
} => ban_room(body, force, room, disable_federation).await,
RoomModerationCommand::BanListOfRooms {
force,
disable_federation,
} => ban_list_of_rooms(body, force, disable_federation).await,
RoomModerationCommand::UnbanRoom {
room,
enable_federation,
} => unban_room(body, room, enable_federation).await,
RoomModerationCommand::ListBannedRooms => list_banned_rooms(body).await,
}
}
let admin_room_alias: Box<RoomAliasId> = format!("#admins:{}", services().globals.server_name())
.try_into()
.expect("#admins:server_name is a valid alias name");
async fn ban_room(
_body: Vec<&str>, force: bool, room: Box<RoomOrAliasId>, disable_federation: bool,
) -> Result<RoomMessageEventContent> {
debug!("Got room alias or ID: {}", room);
if let Some(admin_room_id) = Service::get_admin_room().await? {
if room.to_string().eq(&admin_room_id) || room.to_string().eq(&admin_room_alias) {
return Ok(RoomMessageEventContent::text_plain("Not allowed to ban the admin room."));
}
let admin_room_alias = &services().globals.admin_alias;
if let Some(admin_room_id) = Service::get_admin_room()? {
if room.to_string().eq(&admin_room_id) || room.to_string().eq(admin_room_alias) {
return Ok(RoomMessageEventContent::text_plain("Not allowed to ban the admin room."));
}
}
let room_id = if room.is_room_id() {
let room_id = match RoomId::parse(&room) {
Ok(room_id) => room_id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
debug!("Room specified is a room ID, banning room ID");
services().rooms.metadata.ban_room(&room_id, true)?;
room_id
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
Ok(room_alias) => room_alias,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID locally, if not using \
get_alias_helper to fetch room ID remotely"
);
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
room_id
} else {
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
match get_alias_helper(room_alias, None).await {
Ok(response) => {
debug!("Got federation response fetching room ID for room {room}: {:?}", response);
response.room_id
},
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}"
)));
},
}
};
let room_id = if room.is_room_id() {
let room_id = match RoomId::parse(&room) {
Ok(room_id) => room_id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
services().rooms.metadata.ban_room(&room_id, true)?;
debug!("Room specified is a room ID, banning room ID");
room_id
} else {
return Ok(RoomMessageEventContent::text_plain(
"Room specified is not a room ID or room alias. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`)",
));
};
services().rooms.metadata.ban_room(&room_id, true)?;
room_id
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
Ok(room_alias) => room_alias,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID locally, if not \
using get_alias_helper to fetch room ID remotely"
);
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
room_id
} else {
debug!(
"We don't have this room alias to a room ID locally, attempting to fetch room ID over \
federation"
);
match get_alias_helper(room_alias, None).await {
Ok(response) => {
debug!("Got federation response fetching room ID for room {room}: {:?}", response);
response.room_id
},
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}"
)));
},
}
};
services().rooms.metadata.ban_room(&room_id, true)?;
room_id
} else {
return Ok(RoomMessageEventContent::text_plain(
"Room specified is not a room ID or room alias. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`)",
));
};
debug!("Making all users leave the room {}", &room);
if force {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
user_is_local(local_user)
debug!("Making all users leave the room {}", &room);
if force {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
user_is_local(local_user)
// additional wrapped check here is to avoid adding remote users
// who are in the admin room to the list of local users (would fail auth check)
&& (user_is_local(local_user)
@@ -110,30 +117,30 @@ pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) ->
.users
.is_admin(local_user)
.unwrap_or(true)) // since this is a force
// operation, assume user
// is an admin if somehow
// this fails
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!(
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
&local_user, &room_id
);
// operation, assume user
// is an admin if somehow
// this fails
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!(
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
&local_user, &room_id
);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
warn!(%e, "Failed to leave room");
}
}
} else {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
local_user.server_name() == services().globals.server_name()
if let Err(e) = leave_room(&local_user, &room_id, None).await {
warn!(%e, "Failed to leave room");
}
}
} else {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
local_user.server_name() == services().globals.server_name()
// additional wrapped check here is to avoid adding remote users
// who are in the admin room to the list of local users (would fail auth check)
&& (local_user.server_name()
@@ -142,140 +149,119 @@ pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) ->
.users
.is_admin(local_user)
.unwrap_or(false))
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
error!(
"Error attempting to make local user {} leave room {} during room banning: {}",
&local_user, &room_id, e
);
return Ok(RoomMessageEventContent::text_plain(format!(
"Error attempting to make local user {} leave room {} during room banning (room is still \
banned but not removing any more users): {}\nIf you would like to ignore errors, use \
--force",
&local_user, &room_id, e
)));
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
error!(
"Error attempting to make local user {} leave room {} during room banning: {}",
&local_user, &room_id, e
);
return Ok(RoomMessageEventContent::text_plain(format!(
"Error attempting to make local user {} leave room {} during room banning (room is still banned \
but not removing any more users): {}\nIf you would like to ignore errors, use --force",
&local_user, &room_id, e
)));
}
}
}
if disable_federation {
services().rooms.metadata.disable_room(&room_id, true)?;
return Ok(RoomMessageEventContent::text_plain(
"Room banned, removed all our local users, and disabled incoming federation with room.",
));
}
Ok(RoomMessageEventContent::text_plain(
"Room banned and removed all our local users, use `!admin federation disable-room` to stop receiving new \
inbound federation events as well if needed.",
))
}
async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: bool) -> Result<RoomMessageEventContent> {
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
));
}
let rooms_s = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
let admin_room_alias = &services().globals.admin_alias;
let mut room_ban_count: usize = 0;
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
for &room in &rooms_s {
match <&RoomOrAliasId>::try_from(room) {
Ok(room_alias_or_id) => {
if let Some(admin_room_id) = Service::get_admin_room()? {
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias) {
info!("User specified admin room in bulk ban list, ignoring");
continue;
}
}
}
if disable_federation {
services().rooms.metadata.disable_room(&room_id, true)?;
return Ok(RoomMessageEventContent::text_plain(
"Room banned, removed all our local users, and disabled incoming federation with room.",
));
}
Ok(RoomMessageEventContent::text_plain(
"Room banned and removed all our local users, use `!admin federation disable-room` to stop receiving \
new inbound federation events as well if needed.",
))
},
RoomModerationCommand::BanListOfRooms {
force,
disable_federation,
} => {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let rooms_s = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
let admin_room_alias: Box<RoomAliasId> = format!("#admins:{}", services().globals.server_name())
.try_into()
.expect("#admins:server_name is a valid alias name");
let mut room_ban_count = 0;
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
for &room in &rooms_s {
match <&RoomOrAliasId>::try_from(room) {
Ok(room_alias_or_id) => {
if let Some(admin_room_id) = Service::get_admin_room().await? {
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(&admin_room_alias) {
info!("User specified admin room in bulk ban list, ignoring");
continue;
}
if room_alias_or_id.is_room_id() {
let room_id = match RoomId::parse(room_alias_or_id) {
Ok(room_id) => room_id,
Err(e) => {
if force {
// ignore rooms we failed to parse if we're force banning
warn!(
"Error parsing room \"{room}\" during bulk room banning, ignoring error and \
logging here: {e}"
);
continue;
}
if room_alias_or_id.is_room_id() {
let room_id = match RoomId::parse(room_alias_or_id) {
Ok(room_id) => room_id,
Err(e) => {
if force {
// ignore rooms we failed to parse if we're force banning
warn!(
"Error parsing room \"{room}\" during bulk room banning, ignoring \
error and logging here: {e}"
);
continue;
}
return Ok(RoomMessageEventContent::text_plain(format!(
"{room} is not a valid room ID or room alias, please fix the list and try again: {e}"
)));
},
};
return Ok(RoomMessageEventContent::text_plain(format!(
"{room} is not a valid room ID or room alias, please fix the list and try \
again: {e}"
)));
},
room_ids.push(room_id);
}
if room_alias_or_id.is_room_alias_id() {
match RoomAliasId::parse(room_alias_or_id) {
Ok(room_alias) => {
let room_id =
if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
room_id
} else {
debug!(
"We don't have this room alias to a room ID locally, attempting to fetch room \
ID over federation"
);
match get_alias_helper(room_alias, None).await {
Ok(response) => {
debug!(
"Got federation response fetching room ID for room {room}: {:?}",
response
);
response.room_id
},
Err(e) => {
// don't fail if force blocking
if force {
warn!("Failed to resolve room alias {room} to a room ID: {e}");
continue;
}
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}"
)));
},
}
};
room_ids.push(room_id);
}
if room_alias_or_id.is_room_alias_id() {
match RoomAliasId::parse(room_alias_or_id) {
Ok(room_alias) => {
let room_id = if let Some(room_id) =
services().rooms.alias.resolve_local_alias(&room_alias)?
{
room_id
} else {
debug!(
"We don't have this room alias to a room ID locally, attempting to \
fetch room ID over federation"
);
match get_alias_helper(room_alias, None).await {
Ok(response) => {
debug!(
"Got federation response fetching room ID for room {room}: \
{:?}",
response
);
response.room_id
},
Err(e) => {
// don't fail if force blocking
if force {
warn!("Failed to resolve room alias {room} to a room ID: {e}");
continue;
}
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}"
)));
},
}
};
room_ids.push(room_id);
},
Err(e) => {
if force {
// ignore rooms we failed to parse if we're force deleting
error!(
"Error parsing room \"{room}\" during bulk room banning, ignoring \
error and logging here: {e}"
);
continue;
}
return Ok(RoomMessageEventContent::text_plain(format!(
"{room} is not a valid room ID or room alias, please fix the list and try \
again: {e}"
)));
},
}
}
room_ids.push(room_id);
},
Err(e) => {
if force {
@@ -293,22 +279,38 @@ pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) ->
},
}
}
},
Err(e) => {
if force {
// ignore rooms we failed to parse if we're force deleting
error!(
"Error parsing room \"{room}\" during bulk room banning, ignoring error and logging here: {e}"
);
continue;
}
for room_id in room_ids {
if services().rooms.metadata.ban_room(&room_id, true).is_ok() {
debug!("Banned {room_id} successfully");
room_ban_count += 1;
}
return Ok(RoomMessageEventContent::text_plain(format!(
"{room} is not a valid room ID or room alias, please fix the list and try again: {e}"
)));
},
}
}
debug!("Making all users leave the room {}", &room_id);
if force {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
local_user.server_name() == services().globals.server_name()
for room_id in room_ids {
if services().rooms.metadata.ban_room(&room_id, true).is_ok() {
debug!("Banned {room_id} successfully");
room_ban_count = room_ban_count.saturating_add(1);
}
debug!("Making all users leave the room {}", &room_id);
if force {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
local_user.server_name() == services().globals.server_name()
// additional wrapped check here is to avoid adding remote users
// who are in the admin room to the list of local users (would fail auth check)
&& (local_user.server_name()
@@ -317,32 +319,31 @@ pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) ->
.users
.is_admin(local_user)
.unwrap_or(true)) // since this is a
// force operation,
// assume user is
// an admin if
// somehow this
// fails
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!(
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting \
admins too)",
&local_user, room_id
);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
warn!(%e, "Failed to leave room");
}
}
} else {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
local_user.server_name() == services().globals.server_name()
// force operation,
// assume user is
// an admin if
// somehow this
// fails
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!(
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
&local_user, room_id
);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
warn!(%e, "Failed to leave room");
}
}
} else {
for local_user in services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
local_user.server_name() == services().globals.server_name()
// additional wrapped check here is to avoid adding remote users
// who are in the admin room to the list of local users (would fail auth check)
&& (local_user.server_name()
@@ -351,157 +352,171 @@ pub(crate) async fn process(command: RoomModerationCommand, body: Vec<&str>) ->
.users
.is_admin(local_user)
.unwrap_or(false))
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
error!(
"Error attempting to make local user {} leave room {} during bulk room banning: {}",
&local_user, &room_id, e
);
return Ok(RoomMessageEventContent::text_plain(format!(
"Error attempting to make local user {} leave room {} during room banning (room \
is still banned but not removing any more users and not banning any more rooms): \
{}\nIf you would like to ignore errors, use --force",
&local_user, &room_id, e
)));
}
}
}
if disable_federation {
services().rooms.metadata.disable_room(&room_id, true)?;
}
}
if disable_federation {
})
})
.collect::<Vec<OwnedUserId>>()
{
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
if let Err(e) = leave_room(&local_user, &room_id, None).await {
error!(
"Error attempting to make local user {} leave room {} during bulk room banning: {}",
&local_user, &room_id, e
);
return Ok(RoomMessageEventContent::text_plain(format!(
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, and disabled \
incoming federation with the room."
"Error attempting to make local user {} leave room {} during room banning (room is still \
banned but not removing any more users and not banning any more rooms): {}\nIf you would \
like to ignore errors, use --force",
&local_user, &room_id, e
)));
}
}
}
if disable_federation {
services().rooms.metadata.disable_room(&room_id, true)?;
}
}
if disable_federation {
Ok(RoomMessageEventContent::text_plain(format!(
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, and disabled incoming \
federation with the room."
)))
} else {
Ok(RoomMessageEventContent::text_plain(format!(
"Finished bulk room ban, banned {room_ban_count} total rooms and evicted all users."
)))
}
}
async fn unban_room(
_body: Vec<&str>, room: Box<RoomOrAliasId>, enable_federation: bool,
) -> Result<RoomMessageEventContent> {
let room_id = if room.is_room_id() {
let room_id = match RoomId::parse(&room) {
Ok(room_id) => room_id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Finished bulk room ban, banned {room_ban_count} total rooms and evicted all users."
)));
}
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
},
RoomModerationCommand::UnbanRoom {
room,
enable_federation,
} => {
let room_id = if room.is_room_id() {
let room_id = match RoomId::parse(&room) {
Ok(room_id) => room_id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
debug!("Room specified is a room ID, unbanning room ID");
debug!("Room specified is a room ID, unbanning room ID");
services().rooms.metadata.ban_room(&room_id, false)?;
services().rooms.metadata.ban_room(&room_id, false)?;
room_id
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
Ok(room_alias) => room_alias,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
room_id
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
Ok(room_alias) => room_alias,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to parse room ID {room}. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`): {e}"
)))
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID locally, if not using \
get_alias_helper to fetch room ID remotely"
);
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID locally, if not \
using get_alias_helper to fetch room ID remotely"
);
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
room_id
} else {
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
room_id
} else {
debug!(
"We don't have this room alias to a room ID locally, attempting to fetch room ID over \
federation"
);
match get_alias_helper(room_alias, None).await {
Ok(response) => {
debug!("Got federation response fetching room ID for room {room}: {:?}", response);
response.room_id
},
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}"
)));
},
}
};
services().rooms.metadata.ban_room(&room_id, false)?;
room_id
} else {
return Ok(RoomMessageEventContent::text_plain(
"Room specified is not a room ID or room alias. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`)",
));
};
if enable_federation {
services().rooms.metadata.disable_room(&room_id, false)?;
return Ok(RoomMessageEventContent::text_plain("Room unbanned."));
}
Ok(RoomMessageEventContent::text_plain(
"Room unbanned, you may need to re-enable federation with the room using enable-room if this is a \
remote room to make it fully functional.",
))
},
RoomModerationCommand::ListBannedRooms => {
let rooms = services()
.rooms
.metadata
.list_banned_rooms()
.collect::<Result<Vec<_>, _>>();
match rooms {
Ok(room_ids) => {
// TODO: add room name from our state cache if available, default to the room ID
// as the room name if we dont have it TODO: do same if we have a room alias for
// this
let plain_list = room_ids.iter().fold(String::new(), |mut output, room_id| {
writeln!(output, "- `{}`", room_id).unwrap();
output
});
let html_list = room_ids.iter().fold(String::new(), |mut output, room_id| {
writeln!(output, "<li><code>{}</code></li>", escape_html(room_id.as_ref())).unwrap();
output
});
let plain = format!("Rooms:\n{}", plain_list);
let html = format!("Rooms:\n<ul>{}</ul>", html_list);
Ok(RoomMessageEventContent::text_html(plain, html))
match get_alias_helper(room_alias, None).await {
Ok(response) => {
debug!("Got federation response fetching room ID for room {room}: {:?}", response);
response.room_id
},
Err(e) => {
error!("Failed to list banned rooms: {}", e);
Ok(RoomMessageEventContent::text_plain(format!(
"Unable to list room aliases: {}",
e
)))
return Ok(RoomMessageEventContent::text_plain(format!(
"Failed to resolve room alias {room} to a room ID: {e}"
)));
},
}
};
services().rooms.metadata.ban_room(&room_id, false)?;
room_id
} else {
return Ok(RoomMessageEventContent::text_plain(
"Room specified is not a room ID or room alias. Please note that this requires a full room ID \
(`!awIh6gGInaS5wLQJwa:example.com`) or a room alias (`#roomalias:example.com`)",
));
};
if enable_federation {
services().rooms.metadata.disable_room(&room_id, false)?;
return Ok(RoomMessageEventContent::text_plain("Room unbanned."));
}
Ok(RoomMessageEventContent::text_plain(
"Room unbanned, you may need to re-enable federation with the room using enable-room if this is a remote room \
to make it fully functional.",
))
}
async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let rooms = services()
.rooms
.metadata
.list_banned_rooms()
.collect::<Result<Vec<_>, _>>();
match rooms {
Ok(room_ids) => {
if room_ids.is_empty() {
return Ok(RoomMessageEventContent::text_plain("No rooms are banned."));
}
let mut rooms = room_ids
.into_iter()
.map(|room_id| get_room_info(&room_id))
.collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1);
rooms.reverse();
let output_plain = format!(
"Rooms Banned ({}):\n```\n{}```",
rooms.len(),
rooms
.iter()
.map(|(id, members, name)| format!("{id}\tMembers: {members}\tName: {name}"))
.collect::<Vec<_>>()
.join("\n")
);
let output_html = format!(
"<table><caption>Rooms Banned ({}) \
</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
rooms.len(),
rooms
.iter()
.fold(String::new(), |mut output, (id, members, name)| {
writeln!(
output,
"<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>",
id,
members,
escape_html(name.as_ref())
)
.expect("should be able to write to string buffer");
output
})
);
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
},
Err(e) => {
error!("Failed to list banned rooms: {}", e);
Ok(RoomMessageEventContent::text_plain(format!("Unable to list banned rooms: {e}")))
},
}
}

View File

@@ -1,7 +1,8 @@
pub(crate) mod user_commands;
use clap::Subcommand;
use ruma::events::room::message::RoomMessageEventContent;
use ruma::{events::room::message::RoomMessageEventContent, RoomId};
use user_commands::{delete_room_tag, get_room_tags, put_room_tag};
use self::user_commands::{create, deactivate, deactivate_all, list, list_joined_rooms, reset_password};
use crate::Result;
@@ -25,11 +26,11 @@ pub(crate) enum UserCommand {
/// - Deactivate a user
///
/// User will not be removed from all rooms by default.
/// Use --leave-rooms to force the user to leave all rooms
/// User will be removed from all rooms by default.
/// Use --no-leave-rooms to not leave all rooms by default.
Deactivate {
#[arg(short, long)]
leave_rooms: bool,
no_leave_rooms: bool,
user_id: String,
},
@@ -37,8 +38,10 @@ pub(crate) enum UserCommand {
///
/// Recommended to use in conjunction with list-local-users.
///
/// Users will not be removed from joined rooms by default.
/// Can be overridden with --leave-rooms flag.
/// Users will be removed from joined rooms by default.
///
/// Can be overridden with --no-leave-rooms.
///
/// Removing a mass amount of users from a room may cause a significant
/// amount of leave events. The time to leave rooms may depend significantly
/// on joined rooms and servers.
@@ -48,9 +51,9 @@ pub(crate) enum UserCommand {
DeactivateAll {
#[arg(short, long)]
/// Remove users from their joined rooms
leave_rooms: bool,
no_leave_rooms: bool,
#[arg(short, long)]
/// Also deactivate admin accounts
/// Also deactivate admin accounts and will assume leave all rooms too
force: bool,
},
@@ -62,6 +65,32 @@ pub(crate) enum UserCommand {
ListJoinedRooms {
user_id: String,
},
/// - Puts a room tag for the specified user and room ID.
///
/// This is primarily useful if you'd like to set your admin room
/// to the special "System Alerts" section in Element as a way to
/// permanently see your admin room without it being buried away in your
/// favourites or rooms. To do this, you would pass your user, your admin
/// room's internal ID, and the tag name `m.server_notice`.
PutRoomTag {
user_id: String,
room_id: Box<RoomId>,
tag: String,
},
/// - Deletes the room tag for the specified user and room ID
DeleteRoomTag {
user_id: String,
room_id: Box<RoomId>,
tag: String,
},
/// - Gets all the room tags for the specified user and room ID
GetRoomTags {
user_id: String,
room_id: Box<RoomId>,
},
}
pub(crate) async fn process(command: UserCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
@@ -72,18 +101,32 @@ pub(crate) async fn process(command: UserCommand, body: Vec<&str>) -> Result<Roo
password,
} => create(body, username, password).await?,
UserCommand::Deactivate {
leave_rooms,
no_leave_rooms,
user_id,
} => deactivate(body, leave_rooms, user_id).await?,
} => deactivate(body, no_leave_rooms, user_id).await?,
UserCommand::ResetPassword {
username,
} => reset_password(body, username).await?,
UserCommand::DeactivateAll {
leave_rooms,
no_leave_rooms,
force,
} => deactivate_all(body, leave_rooms, force).await?,
} => deactivate_all(body, no_leave_rooms, force).await?,
UserCommand::ListJoinedRooms {
user_id,
} => list_joined_rooms(body, user_id).await?,
UserCommand::PutRoomTag {
user_id,
room_id,
tag,
} => put_room_tag(body, user_id, room_id, tag).await?,
UserCommand::DeleteRoomTag {
user_id,
room_id,
tag,
} => delete_room_tag(body, user_id, room_id, tag).await?,
UserCommand::GetRoomTags {
user_id,
room_id,
} => get_room_tags(body, user_id, room_id).await?,
})
}

View File

@@ -1,20 +1,36 @@
use std::{fmt::Write as _, sync::Arc};
use std::{collections::BTreeMap, fmt::Write as _};
use api::client_server::{join_room_by_id_helper, leave_all_rooms};
use api::client::{join_room_by_id_helper, leave_all_rooms, update_avatar_url, update_displayname};
use conduit::utils;
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, UserId};
use ruma::{
events::{
room::message::RoomMessageEventContent,
tag::{TagEvent, TagEventContent, TagInfo},
RoomAccountDataEventType,
},
OwnedRoomId, OwnedUserId, RoomId,
};
use tracing::{error, info, warn};
use crate::{escape_html, get_room_info, services, user_is_local, Result};
use crate::{
escape_html, get_room_info, services,
utils::{parse_active_local_user_id, parse_local_user_id},
Result,
};
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
pub(crate) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
match services().users.list_local_users() {
Ok(users) => {
let mut msg = format!("Found {} local user account(s):\n", users.len());
msg += &users.join("\n");
Ok(RoomMessageEventContent::text_plain(&msg))
let mut plain_msg = format!("Found {} local user account(s):\n```\n", users.len());
plain_msg += &users.join("\n");
plain_msg += "\n```";
let mut html_msg = format!("<p>Found {} local user account(s):</p><pre><code>", users.len());
html_msg += &users.join("\n");
html_msg += "\n</code></pre>";
Ok(RoomMessageEventContent::text_html(&plain_msg, &html_msg))
},
Err(e) => Ok(RoomMessageEventContent::text_plain(e.to_string())),
}
@@ -23,34 +39,15 @@ pub(crate) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn create(
_body: Vec<&str>, username: String, password: Option<String>,
) -> Result<RoomMessageEventContent> {
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
// Validate user id
let user_id =
match UserId::parse_with_server_name(username.as_str().to_lowercase(), services().globals.server_name()) {
Ok(id) => id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {e}"
)))
},
};
if !user_is_local(&user_id) {
return Ok(RoomMessageEventContent::text_plain(format!(
"User {user_id} does not belong to our server."
)));
}
if user_id.is_historical() {
return Ok(RoomMessageEventContent::text_plain(format!(
"Userid {user_id} is not allowed due to historical"
)));
}
let user_id = parse_local_user_id(&username)?;
if services().users.exists(&user_id)? {
return Ok(RoomMessageEventContent::text_plain(format!("Userid {user_id} already exists")));
}
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
// Create user
services().users.create(&user_id, Some(password.as_str()))?;
@@ -131,79 +128,51 @@ pub(crate) async fn create(
}
pub(crate) async fn deactivate(
_body: Vec<&str>, leave_rooms: bool, user_id: String,
_body: Vec<&str>, no_leave_rooms: bool, user_id: String,
) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id =
match UserId::parse_with_server_name(user_id.as_str().to_lowercase(), services().globals.server_name()) {
Ok(id) => Arc::<UserId>::from(id),
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {e}"
)))
},
};
let user_id = parse_local_user_id(&user_id)?;
// check if user belongs to our server
if user_id.server_name() != services().globals.server_name() {
return Ok(RoomMessageEventContent::text_plain(format!(
"User {user_id} does not belong to our server."
)));
}
// don't deactivate the conduit service account
if user_id
== UserId::parse_with_server_name("conduit", services().globals.server_name()).expect("conduit user exists")
{
// don't deactivate the server service account
if user_id == services().globals.server_user {
return Ok(RoomMessageEventContent::text_plain(
"Not allowed to deactivate the Conduit service account.",
"Not allowed to deactivate the server service account.",
));
}
if services().users.exists(&user_id)? {
RoomMessageEventContent::text_plain(format!("Making {user_id} leave all rooms before deactivation..."));
services().users.deactivate_account(&user_id)?;
services().users.deactivate_account(&user_id)?;
if !no_leave_rooms {
services()
.admin
.send_message(RoomMessageEventContent::text_plain(format!(
"Making {user_id} leave all rooms after deactivation..."
)))
.await;
if leave_rooms {
leave_all_rooms(&user_id).await;
}
Ok(RoomMessageEventContent::text_plain(format!(
"User {user_id} has been deactivated"
)))
} else {
Ok(RoomMessageEventContent::text_plain(format!(
"User {user_id} doesn't exist on this server"
)))
let all_joined_rooms: Vec<OwnedRoomId> = services()
.rooms
.state_cache
.rooms_joined(&user_id)
.filter_map(Result::ok)
.collect();
update_displayname(user_id.clone(), None, all_joined_rooms.clone()).await?;
update_avatar_url(user_id.clone(), None, None, all_joined_rooms).await?;
leave_all_rooms(&user_id).await;
}
Ok(RoomMessageEventContent::text_plain(format!(
"User {user_id} has been deactivated"
)))
}
pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id =
match UserId::parse_with_server_name(username.as_str().to_lowercase(), services().globals.server_name()) {
Ok(id) => Arc::<UserId>::from(id),
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {e}"
)))
},
};
let user_id = parse_local_user_id(&username)?;
// check if user belongs to our server
if user_id.server_name() != services().globals.server_name() {
return Ok(RoomMessageEventContent::text_plain(format!(
"User {user_id} does not belong to our server."
)));
}
// Check if the specified user is valid
if !services().users.exists(&user_id)?
|| user_id
== UserId::parse_with_server_name("conduit", services().globals.server_name()).expect("conduit user exists")
{
return Ok(RoomMessageEventContent::text_plain("The specified user does not exist!"));
if user_id == services().globals.server_user {
return Ok(RoomMessageEventContent::text_plain(
"Not allowed to set the password for the server account. Please use the emergency password config option.",
));
}
let new_password = utils::random_string(AUTO_GEN_PASSWORD_LENGTH);
@@ -221,107 +190,103 @@ pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result
}
}
pub(crate) async fn deactivate_all(body: Vec<&str>, leave_rooms: bool, force: bool) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
let mut user_ids: Vec<&UserId> = Vec::new();
for &username in &usernames {
match <&UserId>::try_from(username) {
Ok(user_id) => user_ids.push(user_id),
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"{username} is not a valid username: {e}"
)))
},
}
}
let mut deactivation_count: u16 = 0;
let mut admins = Vec::new();
if !force {
user_ids.retain(|&user_id| match services().users.is_admin(user_id) {
Ok(is_admin) => {
if is_admin {
admins.push(user_id.localpart());
false
} else {
true
}
},
Err(_) => false,
});
}
for &user_id in &user_ids {
// check if user belongs to our server and skips over non-local users
if user_id.server_name() != services().globals.server_name() {
continue;
}
// don't deactivate the conduit service account
if user_id
== UserId::parse_with_server_name("conduit", services().globals.server_name())
.expect("conduit user exists")
{
continue;
}
// user does not exist on our server
if !services().users.exists(user_id)? {
continue;
}
if services().users.deactivate_account(user_id).is_ok() {
deactivation_count = deactivation_count.saturating_add(1);
}
}
if leave_rooms {
for &user_id in &user_ids {
leave_all_rooms(user_id).await;
}
}
if admins.is_empty() {
Ok(RoomMessageEventContent::text_plain(format!(
"Deactivated {deactivation_count} accounts."
)))
} else {
Ok(RoomMessageEventContent::text_plain(format!(
"Deactivated {} accounts.\nSkipped admin accounts: {:?}. Use --force to deactivate admin accounts",
deactivation_count,
admins.join(", ")
)))
}
} else {
Ok(RoomMessageEventContent::text_plain(
pub(crate) async fn deactivate_all(
body: Vec<&str>, no_leave_rooms: bool, force: bool,
) -> Result<RoomMessageEventContent> {
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
return Ok(RoomMessageEventContent::text_plain(
"Expected code block in command body. Add --help for details.",
))
));
}
let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
let mut user_ids: Vec<OwnedUserId> = Vec::with_capacity(usernames.len());
let mut admins = Vec::new();
for username in usernames {
match parse_active_local_user_id(username) {
Ok(user_id) => {
if services().users.is_admin(&user_id)? && !force {
services()
.admin
.send_message(RoomMessageEventContent::text_plain(format!(
"{username} is an admin and --force is not set, skipping over"
)))
.await;
admins.push(username);
continue;
}
// don't deactivate the server service account
if user_id == services().globals.server_user {
services()
.admin
.send_message(RoomMessageEventContent::text_plain(format!(
"{username} is the server service account, skipping over"
)))
.await;
continue;
}
user_ids.push(user_id);
},
Err(e) => {
services()
.admin
.send_message(RoomMessageEventContent::text_plain(format!(
"{username} is not a valid username, skipping over: {e}"
)))
.await;
continue;
},
}
}
let mut deactivation_count: usize = 0;
for user_id in user_ids {
match services().users.deactivate_account(&user_id) {
Ok(()) => {
deactivation_count = deactivation_count.saturating_add(1);
if !no_leave_rooms {
info!("Forcing user {user_id} to leave all rooms apart of deactivate-all");
let all_joined_rooms: Vec<OwnedRoomId> = services()
.rooms
.state_cache
.rooms_joined(&user_id)
.filter_map(Result::ok)
.collect();
update_displayname(user_id.clone(), None, all_joined_rooms.clone()).await?;
update_avatar_url(user_id.clone(), None, None, all_joined_rooms).await?;
leave_all_rooms(&user_id).await;
}
},
Err(e) => {
services()
.admin
.send_message(RoomMessageEventContent::text_plain(format!("Failed deactivating user: {e}")))
.await;
},
}
}
if admins.is_empty() {
Ok(RoomMessageEventContent::text_plain(format!(
"Deactivated {deactivation_count} accounts."
)))
} else {
Ok(RoomMessageEventContent::text_plain(format!(
"Deactivated {deactivation_count} accounts.\nSkipped admin accounts: {}. Use --force to deactivate admin \
accounts",
admins.join(", ")
)))
}
}
pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id =
match UserId::parse_with_server_name(user_id.as_str().to_lowercase(), services().globals.server_name()) {
Ok(id) => Arc::<UserId>::from(id),
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {e}"
)))
},
};
if !user_is_local(&user_id) {
return Ok(RoomMessageEventContent::text_plain("User does not belong to our server."));
}
if !services().users.exists(&user_id)? {
return Ok(RoomMessageEventContent::text_plain("User does not exist on this server."));
}
let user_id = parse_local_user_id(&user_id)?;
let mut rooms: Vec<(OwnedRoomId, u64, String)> = services()
.rooms
@@ -347,6 +312,7 @@ pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Resu
.collect::<Vec<_>>()
.join("\n")
);
let output_html = format!(
"<table><caption>Rooms {user_id} Joined \
({})</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
@@ -365,5 +331,97 @@ pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Resu
output
})
);
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
}
pub(crate) async fn put_room_tag(
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
) -> Result<RoomMessageEventContent> {
let user_id = parse_active_local_user_id(&user_id)?;
let event = services()
.account_data
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
let mut tags_event = event.map_or_else(
|| TagEvent {
content: TagEventContent {
tags: BTreeMap::new(),
},
},
|e| serde_json::from_str(e.get()).expect("Bad account data in database for user {user_id}"),
);
tags_event
.content
.tags
.insert(tag.clone().into(), TagInfo::new());
services().account_data.update(
Some(&room_id),
&user_id,
RoomAccountDataEventType::Tag,
&serde_json::to_value(tags_event).expect("to json value always works"),
)?;
Ok(RoomMessageEventContent::text_plain(format!(
"Successfully updated room account data for {user_id} and room {room_id} with tag {tag}"
)))
}
pub(crate) async fn delete_room_tag(
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
) -> Result<RoomMessageEventContent> {
let user_id = parse_active_local_user_id(&user_id)?;
let event = services()
.account_data
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
let mut tags_event = event.map_or_else(
|| TagEvent {
content: TagEventContent {
tags: BTreeMap::new(),
},
},
|e| serde_json::from_str(e.get()).expect("Bad account data in database for user {user_id}"),
);
tags_event.content.tags.remove(&tag.clone().into());
services().account_data.update(
Some(&room_id),
&user_id,
RoomAccountDataEventType::Tag,
&serde_json::to_value(tags_event).expect("to json value always works"),
)?;
Ok(RoomMessageEventContent::text_plain(format!(
"Successfully updated room account data for {user_id} and room {room_id}, deleting room tag {tag}"
)))
}
pub(crate) async fn get_room_tags(
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>,
) -> Result<RoomMessageEventContent> {
let user_id = parse_active_local_user_id(&user_id)?;
let event = services()
.account_data
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
let tags_event = event.map_or_else(
|| TagEvent {
content: TagEventContent {
tags: BTreeMap::new(),
},
},
|e| serde_json::from_str(e.get()).expect("Bad account data in database for user {user_id}"),
);
Ok(RoomMessageEventContent::text_html(
format!("<pre><code>\n{:?}\n</code></pre>", tags_event.content.tags),
format!("```\n{:?}\n```", tags_event.content.tags),
))
}

View File

@@ -1,7 +1,9 @@
pub(crate) use conduit::utils::HtmlEscape;
use ruma::OwnedRoomId;
use conduit_core::Error;
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
use service::user_is_local;
use crate::services;
use crate::{services, Result};
pub(crate) fn escape_html(s: &str) -> String {
s.replace('&', "&amp;")
@@ -9,9 +11,9 @@ pub(crate) fn escape_html(s: &str) -> String {
.replace('>', "&gt;")
}
pub(crate) fn get_room_info(id: &OwnedRoomId) -> (OwnedRoomId, u64, String) {
pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
(
id.clone(),
id.into(),
services()
.rooms
.state_cache
@@ -28,3 +30,35 @@ pub(crate) fn get_room_info(id: &OwnedRoomId) -> (OwnedRoomId, u64, String) {
.unwrap_or_else(|| id.to_string()),
)
}
/// Parses user ID
pub(crate) fn parse_user_id(user_id: &str) -> Result<OwnedUserId> {
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
.map_err(|e| Error::Err(format!("The supplied username is not a valid username: {e}")))
}
/// Parses user ID as our local user
pub(crate) fn parse_local_user_id(user_id: &str) -> Result<OwnedUserId> {
let user_id = parse_user_id(user_id)?;
if !user_is_local(&user_id) {
return Err(Error::Err(String::from("User does not belong to our server.")));
}
Ok(user_id)
}
/// Parses user ID that is an active (not guest or deactivated) local user
pub(crate) fn parse_active_local_user_id(user_id: &str) -> Result<OwnedUserId> {
let user_id = parse_local_user_id(user_id)?;
if !services().users.exists(&user_id)? {
return Err(Error::Err(String::from("User does not exist on this server.")));
}
if services().users.is_deactivated(&user_id)? {
return Err(Error::Err(String::from("User is deactivated.")));
}
Ok(user_id)
}

View File

@@ -1,7 +1,13 @@
[package]
name = "conduit_api"
version.workspace = true
categories.workspace = true
description.workspace = true
edition.workspace = true
keywords.workspace = true
license.workspace = true
readme.workspace = true
repository.workspace = true
version.workspace = true
[lib]
path = "mod.rs"
@@ -11,13 +17,6 @@ crate-type = [
]
[features]
default = [
"element_hacks",
"gzip_compression",
"brotli_compression",
"release_max_log_level",
]
element_hacks = []
dev_release_log_level = []
release_max_log_level = [
@@ -34,7 +33,7 @@ brotli_compression = [
]
[dependencies]
argon2.workspace = true
axum-client-ip.workspace = true
axum-extra.workspace = true
axum.workspace = true
base64.workspace = true

View File

@@ -1,5 +1,6 @@
use std::fmt::Write;
use axum_client_ip::InsecureClientIp;
use conduit::debug_info;
use register::RegistrationKind;
use ruma::{
@@ -14,13 +15,12 @@
uiaa::{AuthFlow, AuthType, UiaaInfo},
},
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
push, UserId,
push, OwnedRoomId, UserId,
};
use tracing::{error, info, warn};
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
use crate::{
client_server::{self, join_room_by_id_helper},
service::user_is_local,
services,
utils::{self},
@@ -40,8 +40,9 @@
///
/// Note: This will not reserve the username, so the username might become
/// invalid when trying to register
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn get_register_available_route(
body: Ruma<get_username_availability::v3::Request>,
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<get_username_availability::v3::Request>,
) -> Result<get_username_availability::v3::Response> {
// Validate user id
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services().globals.server_name())
@@ -88,7 +89,10 @@ pub(crate) async fn get_register_available_route(
/// - If `inhibit_login` is false: Creates a device and returns device id and
/// access_token
#[allow(clippy::doc_markdown)]
pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> {
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn register_route(
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<register::v3::Request>,
) -> Result<register::v3::Response> {
if !services().globals.allow_registration() && body.appservice_info.is_none() {
info!(
"Registration disabled and request not from known appservice, rejecting registration attempt for username \
@@ -105,8 +109,8 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
|| (services().globals.allow_registration() && services().globals.config.registration_token.is_some()))
{
info!(
"Guest registration disabled / registration enabled with token configured, rejecting guest registration, \
initial device name: {:?}",
"Guest registration disabled / registration enabled with token configured, rejecting guest registration \
attempt, initial device name: {:?}",
body.initial_device_display_name
);
return Err(Error::BadRequest(
@@ -174,8 +178,7 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
// UIAA
let mut uiaainfo;
let skip_auth;
if services().globals.config.registration_token.is_some() {
let skip_auth = if services().globals.config.registration_token.is_some() {
// Registration token required
uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
@@ -186,7 +189,7 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
session: None,
auth_error: None,
};
skip_auth = body.appservice_info.is_some();
body.appservice_info.is_some()
} else {
// No registration token necessary, but clients must still go through the flow
uiaainfo = UiaaInfo {
@@ -198,8 +201,8 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
session: None,
auth_error: None,
};
skip_auth = body.appservice_info.is_some() || is_guest;
}
body.appservice_info.is_some() || is_guest
};
if !skip_auth {
if let Some(auth) = &body.auth {
@@ -299,14 +302,14 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"New user \"{user_id}\" registered on this server."
"New user \"{user_id}\" registered on this server from IP {client_ip}."
)))
.await;
}
// log in conduit admin channel if a guest registered
if body.appservice_info.is_none() && is_guest && services().globals.log_guest_registrations() {
info!("New guest user \"{user_id}\" registered on this server.");
info!("New guest user \"{user_id}\" registered on this server from IP.");
if let Some(device_display_name) = &body.initial_device_display_name {
if body
@@ -318,14 +321,15 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with device display name `{device_display_name}` registered on this \
server."
server from IP {client_ip}."
)))
.await;
} else {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with no device display name registered on this server.",
"Guest user \"{user_id}\" with no device display name registered on this server from IP \
{client_ip}.",
)))
.await;
}
@@ -333,7 +337,8 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with no device display name registered on this server.",
"Guest user \"{user_id}\" with no device display name registered on this server from IP \
{client_ip}.",
)))
.await;
}
@@ -342,7 +347,7 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
// If this is the first real user, grant them admin privileges except for guest
// users Note: the server user, @conduit:servername, is generated first
if !is_guest {
if let Some(admin_room) = service::admin::Service::get_admin_room().await? {
if let Some(admin_room) = service::admin::Service::get_admin_room()? {
if services()
.rooms
.state_cache
@@ -354,7 +359,7 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
.make_user_admin(&user_id, displayname)
.await?;
warn!("Granting {} admin privileges as the first user", user_id);
warn!("Granting {user_id} admin privileges as the first user");
}
}
}
@@ -418,8 +423,9 @@ pub(crate) async fn register_route(body: Ruma<register::v3::Request>) -> Result<
/// last seen ts)
/// - Forgets to-device events
/// - Triggers device list updates
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn change_password_route(
body: Ruma<change_password::v3::Request>,
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<change_password::v3::Request>,
) -> Result<change_password::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -468,7 +474,7 @@ pub(crate) async fn change_password_route(
}
}
info!("User {} changed their password.", sender_user);
info!("User {sender_user} changed their password.");
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
@@ -506,7 +512,10 @@ pub(crate) async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoa
/// - Forgets all to-device events
/// - Triggers device list updates
/// - Removes ability to log in again
pub(crate) async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<deactivate::v3::Response> {
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn deactivate_route(
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<deactivate::v3::Request>,
) -> Result<deactivate::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -538,13 +547,23 @@ pub(crate) async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Res
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
// Make the user leave all rooms before deactivation
client_server::leave_all_rooms(sender_user).await;
// Remove devices and mark account as deactivated
services().users.deactivate_account(sender_user)?;
info!("User {} deactivated their account.", sender_user);
// Remove profile pictures and display name
let all_joined_rooms: Vec<OwnedRoomId> = services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(Result::ok)
.collect();
super::update_displayname(sender_user.clone(), None, all_joined_rooms.clone()).await?;
super::update_avatar_url(sender_user.clone(), None, None, all_joined_rooms).await?;
// Make the user leave all rooms before deactivation
super::leave_all_rooms(sender_user).await;
info!("User {sender_user} deactivated their account.");
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(

View File

@@ -8,7 +8,7 @@
},
federation,
},
OwnedRoomAliasId, OwnedRoomId, OwnedServerName,
OwnedRoomAliasId, OwnedServerName, RoomAliasId, RoomId,
};
use tracing::debug;
@@ -22,6 +22,8 @@
///
/// Creates a new room alias on this server.
pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result<create_alias::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
alias_checks(&body.room_alias, &body.appservice_info).await?;
// this isn't apart of alias_checks or delete alias route because we should
@@ -43,17 +45,10 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
return Err(Error::Conflict("Alias already exists."));
}
if services()
services()
.rooms
.alias
.set_alias(&body.room_alias, &body.room_id)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
));
};
.set_alias(&body.room_alias, &body.room_id, sender_user)?;
Ok(create_alias::v3::Response::new())
}
@@ -62,10 +57,12 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
///
/// Deletes a room alias from this server.
///
/// - TODO: additional access control checks
/// - TODO: Update canonical alias event
pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result<delete_alias::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
alias_checks(&body.room_alias, &body.appservice_info).await?;
if services()
.rooms
.alias
@@ -75,17 +72,11 @@ pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) ->
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist."));
}
if services()
services()
.rooms
.alias
.remove_alias(&body.room_alias)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
));
};
.remove_alias(&body.room_alias, sender_user)
.await?;
// TODO: update alt_aliases?
@@ -119,7 +110,7 @@ pub async fn get_alias_helper(
)
.await;
debug_info!("room alias server_name get_alias_helper response: {response:?}");
debug!("room alias server_name get_alias_helper response: {response:?}");
if let Err(ref e) = response {
debug_info!(
@@ -140,7 +131,7 @@ pub async fn get_alias_helper(
},
)
.await;
debug_info!("Got response from server {server} for room aliases: {response:?}");
debug!("Got response from server {server} for room aliases: {response:?}");
if let Ok(ref response) = response {
if !response.servers.is_empty() {
@@ -162,7 +153,7 @@ pub async fn get_alias_helper(
pre_servers.push(room_alias.server_name().into());
let servers = room_available_servers(&room_id, &room_alias, &Some(pre_servers));
debug_warn!(
debug!(
"room alias servers from federation response for room ID {room_id} and room alias {room_alias}: \
{servers:?}"
);
@@ -213,13 +204,13 @@ pub async fn get_alias_helper(
let servers = room_available_servers(&room_id, &room_alias, &None);
debug_warn!("room alias servers for room ID {room_id} and room alias {room_alias}");
debug!("room alias servers for room ID {room_id} and room alias {room_alias}");
Ok(get_alias::v3::Response::new(room_id, servers))
}
fn room_available_servers(
room_id: &OwnedRoomId, room_alias: &OwnedRoomAliasId, pre_servers: &Option<Vec<OwnedServerName>>,
room_id: &RoomId, room_alias: &RoomAliasId, pre_servers: &Option<Vec<OwnedServerName>>,
) -> Vec<OwnedServerName> {
// find active servers in room state cache to suggest
let mut servers: Vec<OwnedServerName> = services()
@@ -247,20 +238,20 @@ fn room_available_servers(
.iter()
.position(|server_name| server_is_ours(server_name))
{
servers.remove(server_index);
servers.swap_remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
} else if let Some(alias_server_index) = servers
.iter()
.position(|server| server == room_alias.server_name())
{
servers.remove(alias_server_index);
servers.swap_remove(alias_server_index);
servers.insert(0, room_alias.server_name().into());
}
servers
}
async fn alias_checks(room_alias: &OwnedRoomAliasId, appservice_info: &Option<RegistrationInfo>) -> Result<()> {
async fn alias_checks(room_alias: &RoomAliasId, appservice_info: &Option<RegistrationInfo>) -> Result<()> {
if !server_is_ours(room_alias.server_name()) {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server."));
}

View File

@@ -1,3 +1,4 @@
use axum_client_ip::InsecureClientIp;
use ruma::{
api::{
client::{
@@ -11,12 +12,8 @@
events::{
room::{
avatar::RoomAvatarEventContent,
canonical_alias::RoomCanonicalAliasEventContent,
create::RoomCreateEventContent,
guest_access::{GuestAccess, RoomGuestAccessEventContent},
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
join_rules::{JoinRule, RoomJoinRulesEventContent},
topic::RoomTopicEventContent,
},
StateEventType,
},
@@ -31,8 +28,9 @@
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn get_public_rooms_filtered_route(
body: Ruma<get_public_rooms_filtered::v3::Request>,
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<get_public_rooms_filtered::v3::Request>,
) -> Result<get_public_rooms_filtered::v3::Response> {
if let Some(server) = &body.server {
if services()
@@ -56,8 +54,8 @@ pub(crate) async fn get_public_rooms_filtered_route(
)
.await
.map_err(|e| {
warn!("Failed to return our /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list.")
warn!(?body.server, "Failed to return /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return the requested server's public room list.")
})?;
Ok(response)
@@ -68,8 +66,9 @@ pub(crate) async fn get_public_rooms_filtered_route(
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn get_public_rooms_route(
body: Ruma<get_public_rooms::v3::Request>,
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<get_public_rooms::v3::Request>,
) -> Result<get_public_rooms::v3::Response> {
if let Some(server) = &body.server {
if services()
@@ -93,8 +92,8 @@ pub(crate) async fn get_public_rooms_route(
)
.await
.map_err(|e| {
warn!("Failed to return our /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list.")
warn!(?body.server, "Failed to return /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return the requested server's public room list.")
})?;
Ok(get_public_rooms::v3::Response {
@@ -110,8 +109,9 @@ pub(crate) async fn get_public_rooms_route(
/// Sets the visibility of a given room in the room directory.
///
/// - TODO: Access control checks
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn set_room_visibility_route(
body: Ruma<set_room_visibility::v3::Request>,
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<set_room_visibility::v3::Request>,
) -> Result<set_room_visibility::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@@ -231,12 +231,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
canonical_alias: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomCanonicalAlias, "")?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomCanonicalAliasEventContent| c.alias)
.map_err(|_| Error::bad_database("Invalid canonical alias event in database."))
})?,
.get_canonical_alias(&room_id)?,
name: services().rooms.state_accessor.get_name(&room_id)?,
num_joined_members: services()
.rooms
@@ -251,40 +246,13 @@ pub(crate) async fn get_public_rooms_filtered_helper(
topic: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomTopic, "")?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomTopicEventContent| Some(c.topic))
.map_err(|e| {
error!("Invalid room topic event in database for room {room_id}: {e}");
Error::bad_database("Invalid room topic event in database.")
})
})
.get_room_topic(&room_id)
.unwrap_or(None),
world_readable: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")?
.map_or(Ok(false), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomHistoryVisibilityEventContent| {
c.history_visibility == HistoryVisibility::WorldReadable
})
.map_err(|e| {
error!(
"Invalid room history visibility event in database for room {room_id}, assuming is \"shared\": {e}",
);
Error::bad_database("Invalid room history visibility event in database.")
})}).unwrap_or(false),
world_readable: services().rooms.state_accessor.is_world_readable(&room_id)?,
guest_can_join: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")?
.map_or(Ok(false), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin)
.map_err(|_| Error::bad_database("Invalid room guest access event in database."))
})?,
.guest_can_join(&room_id)?,
avatar_url: services()
.rooms
.state_accessor

View File

@@ -248,7 +248,7 @@ pub(crate) async fn get_key_changes_route(
})
}
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
sender_user: Option<&UserId>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>, allowed_signatures: F,
include_display_names: bool,
) -> Result<get_keys::v3::Response> {

View File

@@ -22,9 +22,7 @@
services,
utils::{
self,
content_disposition::{
content_disposition_type, make_content_disposition, make_content_type, sanitise_filename,
},
content_disposition::{content_disposition_type, make_content_disposition, sanitise_filename},
},
Error, Result, Ruma, RumaResponse,
};
@@ -131,8 +129,6 @@ pub(crate) async fn create_content_route(
utils::random_string(MXC_LENGTH)
);
let content_type = Some(make_content_type(&body.file, &body.content_type).to_owned());
services()
.media
.create(
@@ -143,12 +139,12 @@ pub(crate) async fn create_content_route(
.map(|filename| {
format!(
"{}; filename={}",
content_disposition_type(&body.file, &content_type),
content_disposition_type(&body.content_type),
sanitise_filename(filename.to_owned())
)
})
.as_deref(),
content_type.as_deref(),
body.content_type.as_deref(),
&body.file,
)
.await?;
@@ -192,8 +188,7 @@ pub(crate) async fn get_content_route(body: Ruma<get_content::v3::Request>) -> R
content_disposition,
}) = services().media.get(mxc.clone()).await?
{
let content_disposition = Some(make_content_disposition(&file, &content_type, content_disposition, None));
let content_type = Some(make_content_type(&file, &content_type).to_owned());
let content_disposition = Some(make_content_disposition(&content_type, content_disposition, None));
Ok(get_content::v3::Response {
file,
@@ -217,16 +212,14 @@ pub(crate) async fn get_content_route(body: Ruma<get_content::v3::Request>) -> R
})?;
let content_disposition = Some(make_content_disposition(
&response.file,
&response.content_type,
response.content_disposition,
None,
));
let content_type = Some(make_content_type(&response.file, &response.content_type).to_owned());
Ok(get_content::v3::Response {
file: response.file,
content_type,
content_type: response.content_type,
content_disposition,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.to_owned()),
@@ -274,12 +267,10 @@ pub(crate) async fn get_content_as_filename_route(
}) = services().media.get(mxc.clone()).await?
{
let content_disposition = Some(make_content_disposition(
&file,
&content_type,
content_disposition,
Some(body.filename.clone()),
));
let content_type = Some(make_content_type(&file, &content_type).to_owned());
Ok(get_content_as_filename::v3::Response {
file,
@@ -300,18 +291,14 @@ pub(crate) async fn get_content_as_filename_route(
{
Ok(remote_content_response) => {
let content_disposition = Some(make_content_disposition(
&remote_content_response.file,
&remote_content_response.content_type,
remote_content_response.content_disposition,
None,
));
let content_type = Some(
make_content_type(&remote_content_response.file, &remote_content_response.content_type).to_owned(),
);
Ok(get_content_as_filename::v3::Response {
content_disposition,
content_type,
content_type: remote_content_response.content_type,
file: remote_content_response.file,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
@@ -375,8 +362,7 @@ pub(crate) async fn get_content_thumbnail_route(
)
.await?
{
let content_disposition = Some(make_content_disposition(&file, &content_type, content_disposition, None));
let content_type = Some(make_content_type(&file, &content_type).to_owned());
let content_disposition = Some(make_content_disposition(&content_type, content_disposition, None));
Ok(get_content_thumbnail::v3::Response {
file,
@@ -429,18 +415,14 @@ pub(crate) async fn get_content_thumbnail_route(
.await?;
let content_disposition = Some(make_content_disposition(
&get_thumbnail_response.file,
&get_thumbnail_response.content_type,
get_thumbnail_response.content_disposition,
None,
));
let content_type = Some(
make_content_type(&get_thumbnail_response.file, &get_thumbnail_response.content_type).to_owned(),
);
Ok(get_content_thumbnail::v3::Response {
file: get_thumbnail_response.file,
content_type,
content_type: get_thumbnail_response.content_type,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.to_owned()),
content_disposition,
@@ -503,28 +485,25 @@ async fn get_remote_content(
.await?;
let content_disposition = Some(make_content_disposition(
&content_response.file,
&content_response.content_type,
content_response.content_disposition,
None,
));
let content_type = Some(make_content_type(&content_response.file, &content_response.content_type).to_owned());
services()
.media
.create(
None,
mxc.to_owned(),
content_disposition.as_deref(),
content_type.as_deref(),
content_response.content_type.as_deref(),
&content_response.file,
)
.await?;
Ok(get_content::v3::Response {
file: content_response.file,
content_type,
content_type: content_response.content_type,
content_disposition,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.to_owned()),

83
src/api/client/mod.rs Normal file
View File

@@ -0,0 +1,83 @@
pub(super) mod account;
pub(super) mod alias;
pub(super) mod backup;
pub(super) mod capabilities;
pub(super) mod config;
pub(super) mod context;
pub(super) mod device;
pub(super) mod directory;
pub(super) mod filter;
pub(super) mod keys;
pub(super) mod media;
pub(super) mod membership;
pub(super) mod message;
pub(super) mod presence;
pub(super) mod profile;
pub(super) mod push;
pub(super) mod read_marker;
pub(super) mod redact;
pub(super) mod relations;
pub(super) mod report;
pub(super) mod room;
pub(super) mod search;
pub(super) mod session;
pub(super) mod space;
pub(super) mod state;
pub(super) mod sync;
pub(super) mod tag;
pub(super) mod thirdparty;
pub(super) mod threads;
pub(super) mod to_device;
pub(super) mod typing;
pub(super) mod unstable;
pub(super) mod unversioned;
pub(super) mod user_directory;
pub(super) mod voip;
pub(super) use account::*;
pub use alias::get_alias_helper;
pub(super) use alias::*;
pub(super) use backup::*;
pub(super) use capabilities::*;
pub(super) use config::*;
pub(super) use context::*;
pub(super) use device::*;
pub(super) use directory::*;
pub(super) use filter::*;
pub(super) use keys::*;
pub(super) use media::*;
pub(super) use membership::*;
pub use membership::{join_room_by_id_helper, leave_all_rooms, leave_room, validate_and_add_event_id};
pub(super) use message::*;
pub(super) use presence::*;
pub(super) use profile::*;
pub use profile::{update_all_rooms, update_avatar_url, update_displayname};
pub(super) use push::*;
pub(super) use read_marker::*;
pub(super) use redact::*;
pub(super) use relations::*;
pub(super) use report::*;
pub(super) use room::*;
pub(super) use search::*;
pub(super) use session::*;
pub(super) use space::*;
pub(super) use state::*;
pub(super) use sync::*;
pub(super) use tag::*;
pub(super) use thirdparty::*;
pub(super) use threads::*;
pub(super) use to_device::*;
pub(super) use typing::*;
pub(super) use unstable::*;
pub(super) use unversioned::*;
pub(super) use user_directory::*;
pub(super) use voip::*;
/// generated device ID length
const DEVICE_ID_LENGTH: usize = 10;
/// generated user access token length
const TOKEN_LENGTH: usize = 32;
/// generated user session ID length
const SESSION_ID_LENGTH: usize = service::uiaa::SESSION_ID_LENGTH;

View File

@@ -10,6 +10,7 @@
},
events::{room::member::RoomMemberEventContent, StateEventType, TimelineEventType},
presence::PresenceState,
OwnedMxcUri, OwnedRoomId, OwnedUserId,
};
use serde_json::value::to_raw_value;
use tracing::warn;
@@ -28,70 +29,14 @@ pub(crate) async fn set_displayname_route(
body: Ruma<set_display_name::v3::Request>,
) -> Result<set_display_name::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services()
.users
.set_displayname(sender_user, body.displayname.clone())
.await?;
// Send a new membership event and presence update into all joined rooms
let all_rooms_joined: Vec<_> = services()
let all_joined_rooms: Vec<OwnedRoomId> = services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(Result::ok)
.map(|room_id| {
Ok::<_, Error>((
PduBuilder {
event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent {
displayname: body.displayname.clone(),
join_authorized_via_users_server: None,
..serde_json::from_str(
services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomMember, sender_user.as_str())?
.ok_or_else(|| {
Error::bad_database("Tried to send displayname update for user not in the room.")
})?
.content
.get(),
)
.map_err(|_| Error::bad_database("Database contains invalid PDU."))?
})
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some(sender_user.to_string()),
redacts: None,
},
room_id,
))
})
.filter_map(Result::ok)
.collect();
for (pdu_builder, room_id) in all_rooms_joined {
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
if let Err(e) = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await
{
warn!(%e, "Failed to update/send new display name in room");
}
}
update_displayname(sender_user.clone(), body.displayname.clone(), all_joined_rooms).await?;
if services().globals.allow_local_presence() {
// Presence update
@@ -168,75 +113,20 @@ pub(crate) async fn set_avatar_url_route(
body: Ruma<set_avatar_url::v3::Request>,
) -> Result<set_avatar_url::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services()
.users
.set_avatar_url(sender_user, body.avatar_url.clone())
.await?;
services()
.users
.set_blurhash(sender_user, body.blurhash.clone())
.await?;
// Send a new membership event and presence update into all joined rooms
let all_joined_rooms: Vec<_> = services()
let all_joined_rooms: Vec<OwnedRoomId> = services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(Result::ok)
.map(|room_id| {
Ok::<_, Error>((
PduBuilder {
event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent {
avatar_url: body.avatar_url.clone(),
join_authorized_via_users_server: None,
..serde_json::from_str(
services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomMember, sender_user.as_str())?
.ok_or_else(|| {
Error::bad_database("Tried to send displayname update for user not in the room.")
})?
.content
.get(),
)
.map_err(|_| Error::bad_database("Database contains invalid PDU."))?
})
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some(sender_user.to_string()),
redacts: None,
},
room_id,
))
})
.filter_map(Result::ok)
.collect();
for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
if let Err(e) = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await
{
warn!(%e, "Failed to set/update room with new avatar URL / pfp");
}
}
update_avatar_url(
sender_user.clone(),
body.avatar_url.clone(),
body.blurhash.clone(),
all_joined_rooms,
)
.await?;
if services().globals.allow_local_presence() {
// Presence update
@@ -363,3 +253,126 @@ pub(crate) async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> R
displayname: services().users.displayname(&body.user_id)?,
})
}
pub async fn update_displayname(
user_id: OwnedUserId, displayname: Option<String>, all_joined_rooms: Vec<OwnedRoomId>,
) -> Result<()> {
services()
.users
.set_displayname(&user_id, displayname.clone())
.await?;
// Send a new join membership event into all joined rooms
let all_joined_rooms: Vec<_> = all_joined_rooms
.iter()
.map(|room_id| {
Ok::<_, Error>((
PduBuilder {
event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent {
displayname: displayname.clone(),
join_authorized_via_users_server: None,
..serde_json::from_str(
services()
.rooms
.state_accessor
.room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())?
.ok_or_else(|| {
Error::bad_database("Tried to send display name update for user not in the room.")
})?
.content
.get(),
)
.map_err(|_| Error::bad_database("Database contains invalid PDU."))?
})
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some(user_id.to_string()),
redacts: None,
},
room_id,
))
})
.filter_map(Result::ok)
.collect();
update_all_rooms(all_joined_rooms, user_id).await;
Ok(())
}
pub async fn update_avatar_url(
user_id: OwnedUserId, avatar_url: Option<OwnedMxcUri>, blurhash: Option<String>, all_joined_rooms: Vec<OwnedRoomId>,
) -> Result<()> {
services()
.users
.set_avatar_url(&user_id, avatar_url.clone())
.await?;
services()
.users
.set_blurhash(&user_id, blurhash.clone())
.await?;
// Send a new join membership event into all joined rooms
let all_joined_rooms: Vec<_> = all_joined_rooms
.iter()
.map(|room_id| {
Ok::<_, Error>((
PduBuilder {
event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent {
avatar_url: avatar_url.clone(),
blurhash: blurhash.clone(),
join_authorized_via_users_server: None,
..serde_json::from_str(
services()
.rooms
.state_accessor
.room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())?
.ok_or_else(|| {
Error::bad_database("Tried to send avatar URL update for user not in the room.")
})?
.content
.get(),
)
.map_err(|_| Error::bad_database("Database contains invalid PDU."))?
})
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some(user_id.to_string()),
redacts: None,
},
room_id,
))
})
.filter_map(Result::ok)
.collect();
update_all_rooms(all_joined_rooms, user_id).await;
Ok(())
}
pub async fn update_all_rooms(all_joined_rooms: Vec<(PduBuilder, &OwnedRoomId)>, user_id: OwnedUserId) {
for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
if let Err(e) = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, &user_id, room_id, &state_lock)
.await
{
warn!(%user_id, %room_id, %e, "Failed to update/send new profile join membership update in room");
}
}
}

View File

@@ -104,14 +104,14 @@ fn is_report_valid(
));
}
if let Some(true) = score.map(|s| s > int!(0) || s < int!(-100)) {
if score.map(|s| s > int!(0) || s < int!(-100)) == Some(true) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid score, must be within 0 to -100",
));
};
if let Some(true) = reason.clone().map(|s| s.len() >= 750) {
if reason.clone().map(|s| s.len() >= 750) == Some(true) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Reason too long, should be 750 characters or fewer",

View File

@@ -28,8 +28,8 @@
use serde_json::{json, value::to_raw_value};
use tracing::{error, info, warn};
use super::invite_helper;
use crate::{
client_server::invite_helper,
service::{appservice::RegistrationInfo, pdu::PduBuilder},
services, Error, Result, Ruma,
};
@@ -467,7 +467,10 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
// Homeserver specific stuff
if let Some(alias) = alias {
services().rooms.alias.set_alias(&alias, &room_id)?;
services()
.rooms
.alias
.set_alias(&alias, &room_id, sender_user)?;
}
if body.visibility == room::Visibility::Public {
@@ -787,7 +790,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
services()
.rooms
.alias
.set_alias(&alias, &replacement_room)?;
.set_alias(&alias, &replacement_room, sender_user)?;
}
// Get the old room power levels
@@ -886,7 +889,7 @@ fn default_power_levels_content(
/// if a room is being created with a room alias, run our checks
async fn room_alias_check(
room_alias_name: &String, appservice_info: &Option<RegistrationInfo>,
room_alias_name: &str, appservice_info: &Option<RegistrationInfo>,
) -> Result<OwnedRoomAliasId> {
// Basic checks on the room alias validity
if room_alias_name.contains(':') {
@@ -900,20 +903,6 @@ async fn room_alias_check(
ErrorKind::InvalidParam,
"Room alias contained spaces which is not a valid room alias.",
));
} else if room_alias_name.len() > 255 {
// there is nothing spec-wise saying to check the limit of this,
// however absurdly long room aliases are guaranteed to be unreadable or done
// maliciously. there is no reason a room alias should even exceed 100
// characters as is. generally in spec, 255 is matrix's fav number
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias is excessively long, clients may not be able to handle this. Please shorten it.",
));
} else if room_alias_name.contains('"') {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained `\"` which is not allowed.",
));
}
// check if room alias is forbidden
@@ -958,7 +947,7 @@ async fn room_alias_check(
}
/// if a room is being created with a custom room ID, run our checks against it
fn custom_room_id_check(custom_room_id: &String) -> Result<OwnedRoomId> {
fn custom_room_id_check(custom_room_id: &str) -> Result<OwnedRoomId> {
// apply forbidden room alias checks to custom room IDs too
if services()
.globals
@@ -979,8 +968,6 @@ fn custom_room_id_check(custom_room_id: &String) -> Result<OwnedRoomId> {
ErrorKind::InvalidParam,
"Custom room ID contained spaces which is not valid.",
));
} else if custom_room_id.len() > 255 {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Custom room ID is too long."));
}
let full_room_id = format!("!{}:{}", custom_room_id, services().globals.config.server_name);

View File

@@ -133,6 +133,7 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
let results: Vec<_> = results
.iter()
.skip(skip)
.filter_map(|result| {
services()
.rooms
@@ -140,11 +141,12 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
.get_pdu_from_id(result)
.ok()?
.filter(|pdu| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &pdu.room_id, &pdu.event_id)
.unwrap_or(false)
!pdu.is_redacted()
&& services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &pdu.room_id, &pdu.event_id)
.unwrap_or(false)
})
.map(|pdu| pdu.to_room_event())
})
@@ -162,15 +164,11 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
})
})
.filter_map(Result::ok)
.skip(skip)
.take(limit)
.collect();
let next_batch = if results.len() < limit {
None
} else {
Some(next_batch.to_string())
};
let more_unloaded_results = searches.iter_mut().any(|s| s.peek().is_some());
let next_batch = more_unloaded_results.then(|| next_batch.to_string());
Ok(search_events::v3::Response::new(ResultCategories {
room_events: ResultRoomEvents {

View File

@@ -1,4 +1,3 @@
use argon2::{PasswordHash, PasswordVerifier};
use ruma::{
api::client::{
error::ErrorKind,
@@ -21,7 +20,7 @@
use tracing::{debug, info, warn};
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{services, utils, Error, Result, Ruma};
use crate::{services, utils, utils::hash, Error, Result, Ruma};
#[derive(Debug, Deserialize)]
struct Claims {
@@ -87,15 +86,7 @@ pub(crate) async fn login_route(body: Ruma<login::v3::Request>) -> Result<login:
return Err(Error::BadRequest(ErrorKind::UserDeactivated, "The user has been deactivated"));
}
let parsed_hash = PasswordHash::new(&hash)
.map_err(|_| Error::BadServerResponse("Unknown error occurred hashing password."))?;
if services()
.globals
.argon
.verify_password(password.as_bytes(), &parsed_hash)
.is_err()
{
if hash::verify_password(password, &hash).is_err() {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Wrong username or password."));
}

View File

@@ -216,7 +216,7 @@ async fn allowed_to_send_state_event(
},
// admin room is a sensitive room, it should not ever be made public
StateEventType::RoomJoinRules => {
if let Some(admin_room_id) = service::admin::Service::get_admin_room().await? {
if let Some(admin_room_id) = service::admin::Service::get_admin_room()? {
if admin_room_id == room_id {
if let Ok(join_rule) = serde_json::from_str::<RoomJoinRulesEventContent>(json.json().get()) {
if join_rule.join_rule == JoinRule::Public {
@@ -231,7 +231,7 @@ async fn allowed_to_send_state_event(
},
// admin room is a sensitive room, it should not ever be made world readable
StateEventType::RoomHistoryVisibility => {
if let Some(admin_room_id) = service::admin::Service::get_admin_room().await? {
if let Some(admin_room_id) = service::admin::Service::get_admin_room()? {
if admin_room_id == room_id {
if let Ok(visibility_content) =
serde_json::from_str::<RoomHistoryVisibilityEventContent>(json.json().get())

View File

@@ -142,7 +142,7 @@ pub(crate) async fn sync_events_route(
.collect::<Vec<_>>();
// Coalesce database writes for the remainder of this scope.
let _cork = services().globals.cork_and_flush()?;
let _cork = services().globals.db.cork_and_flush();
for room_id in all_joined_rooms {
let room_id = room_id?;
@@ -492,8 +492,10 @@ async fn handle_left_room(
}
async fn process_presence_updates(
presence_updates: &mut HashMap<OwnedUserId, PresenceEvent>, since: u64, syncing_user: &OwnedUserId,
presence_updates: &mut HashMap<OwnedUserId, PresenceEvent>, since: u64, syncing_user: &UserId,
) -> Result<()> {
use crate::service::presence::Presence;
// Take presence updates
for (user_id, _, presence_bytes) in services().presence.presence_since(since) {
if !services()
@@ -504,7 +506,6 @@ async fn process_presence_updates(
continue;
}
use crate::service::presence::Presence;
let presence_event = Presence::from_json_bytes_to_event(&presence_bytes, &user_id)?;
match presence_updates.entry(user_id) {
Entry::Vacant(slot) => {
@@ -610,7 +611,7 @@ async fn load_joined_room(
.unwrap_or(0);
// Recalculate heroes (first 5 members)
let mut heroes = Vec::new();
let mut heroes: Vec<OwnedUserId> = Vec::with_capacity(5);
if joined_member_count.saturating_add(invited_member_count) <= 5 {
// Go through all PDUs and for each member event, check if the user is still
@@ -635,7 +636,7 @@ async fn load_joined_room(
&& (services().rooms.state_cache.is_joined(&user_id, room_id)?
|| services().rooms.state_cache.is_invited(&user_id, room_id)?)
{
Ok::<_, Error>(Some(state_key.clone()))
Ok::<_, Error>(Some(user_id))
} else {
Ok(None)
}
@@ -643,12 +644,11 @@ async fn load_joined_room(
Ok(None)
}
})
// Filter out buggy users
.filter_map(Result::ok)
// Filter for possible heroes
.flatten()
{
if heroes.contains(&hero) || hero == sender_user.as_str() {
if heroes.contains(&hero) || hero == sender_user {
continue;
}
@@ -1041,8 +1041,7 @@ fn load_timeline(
sender_user: &UserId, room_id: &RoomId, roomsincecount: PduCount, limit: u64,
) -> Result<(Vec<(PduCount, PduEvent)>, bool), Error> {
let timeline_pdus;
let limited;
if services()
let limited = if services()
.rooms
.timeline
.last_timeline_count(sender_user, room_id)?
@@ -1072,11 +1071,11 @@ fn load_timeline(
// They /sync response doesn't always return all messages, so we say the output
// is limited unless there are events in non_timeline_pdus
limited = non_timeline_pdus.next().is_some();
non_timeline_pdus.next().is_some()
} else {
timeline_pdus = Vec::new();
limited = false;
}
false
};
Ok((timeline_pdus, limited))
}
@@ -1584,6 +1583,7 @@ pub(crate) async fn sync_events_v4_route(
),
num_live: None, // Count events in timeline greater than global sync counter
timestamp: None,
heroes: None,
},
);
}

View File

@@ -10,7 +10,7 @@
error::ErrorKind,
};
use crate::{services, utils::conduwuit_version, Error, Result, Ruma};
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/versions`
///
@@ -145,7 +145,7 @@ pub(crate) async fn syncv3_client_server_json() -> Result<impl IntoResponse> {
Ok(Json(serde_json::json!({
"server": server_url,
"version": conduwuit_version(),
"version": conduit::version::conduwuit(),
})))
}
@@ -156,7 +156,7 @@ pub(crate) async fn syncv3_client_server_json() -> Result<impl IntoResponse> {
pub(crate) async fn conduwuit_server_version() -> Result<impl IntoResponse> {
Ok(Json(serde_json::json!({
"name": "conduwuit",
"version": conduwuit_version(),
"version": conduit::version::conduwuit(),
})))
}

View File

@@ -1,12 +1,15 @@
use std::time::{Duration, SystemTime};
use base64::{engine::general_purpose, Engine as _};
use conduit::utils;
use hmac::{Hmac, Mac};
use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch};
use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch, UserId};
use sha1::Sha1;
use crate::{services, Result, Ruma};
const RANDOM_USER_ID_LENGTH: usize = 10;
type HmacSha1 = Hmac<Sha1>;
/// # `GET /_matrix/client/r0/voip/turnServer`
@@ -15,8 +18,6 @@
pub(crate) async fn turn_server_route(
body: Ruma<get_turn_server_info::v3::Request>,
) -> Result<get_turn_server_info::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let turn_secret = services().globals.turn_secret().clone();
let (username, password) = if !turn_secret.is_empty() {
@@ -27,7 +28,15 @@ pub(crate) async fn turn_server_route(
)
.expect("time is valid");
let username: String = format!("{}:{}", expiry.get(), sender_user);
let user = body.sender_user.unwrap_or_else(|| {
UserId::parse_with_server_name(
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
&services().globals.config.server_name,
)
.unwrap()
});
let username: String = format!("{}:{}", expiry.get(), user);
let mut mac = HmacSha1::new_from_slice(turn_secret.as_bytes()).expect("HMAC can take key of any size");
mac.update(username.as_bytes());

View File

@@ -1,82 +0,0 @@
pub(crate) mod account;
pub(crate) mod alias;
pub(crate) mod backup;
pub(crate) mod capabilities;
pub(crate) mod config;
pub(crate) mod context;
pub(crate) mod device;
pub(crate) mod directory;
pub(crate) mod filter;
pub(crate) mod keys;
pub(crate) mod media;
pub(crate) mod membership;
pub(crate) mod message;
pub(crate) mod presence;
pub(crate) mod profile;
pub(crate) mod push;
pub(crate) mod read_marker;
pub(crate) mod redact;
pub(crate) mod relations;
pub(crate) mod report;
pub(crate) mod room;
pub(crate) mod search;
pub(crate) mod session;
pub(crate) mod space;
pub(crate) mod state;
pub(crate) mod sync;
pub(crate) mod tag;
pub(crate) mod thirdparty;
pub(crate) mod threads;
pub(crate) mod to_device;
pub(crate) mod typing;
pub(crate) mod unstable;
pub(crate) mod unversioned;
pub(crate) mod user_directory;
pub(crate) mod voip;
pub(crate) use account::*;
pub use alias::get_alias_helper;
pub(crate) use alias::*;
pub(crate) use backup::*;
pub(crate) use capabilities::*;
pub(crate) use config::*;
pub(crate) use context::*;
pub(crate) use device::*;
pub(crate) use directory::*;
pub(crate) use filter::*;
pub(crate) use keys::*;
pub(crate) use media::*;
pub(crate) use membership::*;
pub use membership::{join_room_by_id_helper, leave_all_rooms, leave_room};
pub(crate) use message::*;
pub(crate) use presence::*;
pub(crate) use profile::*;
pub(crate) use push::*;
pub(crate) use read_marker::*;
pub(crate) use redact::*;
pub(crate) use relations::*;
pub(crate) use report::*;
pub(crate) use room::*;
pub(crate) use search::*;
pub(crate) use session::*;
pub(crate) use space::*;
pub(crate) use state::*;
pub(crate) use sync::*;
pub(crate) use tag::*;
pub(crate) use thirdparty::*;
pub(crate) use threads::*;
pub(crate) use to_device::*;
pub(crate) use typing::*;
pub(crate) use unstable::*;
pub(crate) use unversioned::*;
pub(crate) use user_directory::*;
pub(crate) use voip::*;
/// generated device ID length
const DEVICE_ID_LENGTH: usize = 10;
/// generated user access token length
const TOKEN_LENGTH: usize = 32;
/// generated user session ID length
const SESSION_ID_LENGTH: usize = service::uiaa::SESSION_ID_LENGTH;

View File

@@ -1,14 +1,13 @@
pub mod client_server;
pub mod client;
pub mod router;
mod ruma_wrapper;
pub mod server_server;
pub mod server;
extern crate conduit_core as conduit;
extern crate conduit_service as service;
pub use client_server::membership::{join_room_by_id_helper, leave_all_rooms};
pub(crate) use conduit::{debug_error, debug_info, debug_warn, error::RumaResponse, utils, Error, Result};
pub(crate) use ruma_wrapper::Ruma;
pub(crate) use conduit::{debug_info, debug_warn, utils, Error, Result};
pub(crate) use ruma_wrapper::{Ruma, RumaResponse};
pub(crate) use service::{pdu::PduEvent, services, user_is_local};
conduit::mod_ctor! {}

View File

@@ -1,225 +1,220 @@
use std::future::Future;
use axum::{
response::IntoResponse,
routing::{any, get, on, post, MethodFilter},
routing::{any, get, post},
Router,
};
use conduit::{Error, Result, Server};
use http::{Method, Uri};
use ruma::api::{client::error::ErrorKind, IncomingRequest};
use conduit::{Error, Server};
use http::Uri;
use ruma::api::client::error::ErrorKind;
use crate::{client_server, server_server, Ruma, RumaResponse};
use crate::{client, ruma_wrapper::RouterExt, server};
pub fn build(router: Router, server: &Server) -> Router {
let config = &server.config;
let router = router
.ruma_route(client_server::get_supported_versions_route)
.ruma_route(client_server::get_register_available_route)
.ruma_route(client_server::register_route)
.ruma_route(client_server::get_login_types_route)
.ruma_route(client_server::login_route)
.ruma_route(client_server::whoami_route)
.ruma_route(client_server::logout_route)
.ruma_route(client_server::logout_all_route)
.ruma_route(client_server::change_password_route)
.ruma_route(client_server::deactivate_route)
.ruma_route(client_server::third_party_route)
.ruma_route(client_server::request_3pid_management_token_via_email_route)
.ruma_route(client_server::request_3pid_management_token_via_msisdn_route)
.ruma_route(client_server::check_registration_token_validity)
.ruma_route(client_server::get_capabilities_route)
.ruma_route(client_server::get_pushrules_all_route)
.ruma_route(client_server::set_pushrule_route)
.ruma_route(client_server::get_pushrule_route)
.ruma_route(client_server::set_pushrule_enabled_route)
.ruma_route(client_server::get_pushrule_enabled_route)
.ruma_route(client_server::get_pushrule_actions_route)
.ruma_route(client_server::set_pushrule_actions_route)
.ruma_route(client_server::delete_pushrule_route)
.ruma_route(client_server::get_room_event_route)
.ruma_route(client_server::get_room_aliases_route)
.ruma_route(client_server::get_filter_route)
.ruma_route(client_server::create_filter_route)
.ruma_route(client_server::set_global_account_data_route)
.ruma_route(client_server::set_room_account_data_route)
.ruma_route(client_server::get_global_account_data_route)
.ruma_route(client_server::get_room_account_data_route)
.ruma_route(client_server::set_displayname_route)
.ruma_route(client_server::get_displayname_route)
.ruma_route(client_server::set_avatar_url_route)
.ruma_route(client_server::get_avatar_url_route)
.ruma_route(client_server::get_profile_route)
.ruma_route(client_server::set_presence_route)
.ruma_route(client_server::get_presence_route)
.ruma_route(client_server::upload_keys_route)
.ruma_route(client_server::get_keys_route)
.ruma_route(client_server::claim_keys_route)
.ruma_route(client_server::create_backup_version_route)
.ruma_route(client_server::update_backup_version_route)
.ruma_route(client_server::delete_backup_version_route)
.ruma_route(client_server::get_latest_backup_info_route)
.ruma_route(client_server::get_backup_info_route)
.ruma_route(client_server::add_backup_keys_route)
.ruma_route(client_server::add_backup_keys_for_room_route)
.ruma_route(client_server::add_backup_keys_for_session_route)
.ruma_route(client_server::delete_backup_keys_for_room_route)
.ruma_route(client_server::delete_backup_keys_for_session_route)
.ruma_route(client_server::delete_backup_keys_route)
.ruma_route(client_server::get_backup_keys_for_room_route)
.ruma_route(client_server::get_backup_keys_for_session_route)
.ruma_route(client_server::get_backup_keys_route)
.ruma_route(client_server::set_read_marker_route)
.ruma_route(client_server::create_receipt_route)
.ruma_route(client_server::create_typing_event_route)
.ruma_route(client_server::create_room_route)
.ruma_route(client_server::redact_event_route)
.ruma_route(client_server::report_event_route)
.ruma_route(client_server::create_alias_route)
.ruma_route(client_server::delete_alias_route)
.ruma_route(client_server::get_alias_route)
.ruma_route(client_server::join_room_by_id_route)
.ruma_route(client_server::join_room_by_id_or_alias_route)
.ruma_route(client_server::joined_members_route)
.ruma_route(client_server::leave_room_route)
.ruma_route(client_server::forget_room_route)
.ruma_route(client_server::joined_rooms_route)
.ruma_route(client_server::kick_user_route)
.ruma_route(client_server::ban_user_route)
.ruma_route(client_server::unban_user_route)
.ruma_route(client_server::invite_user_route)
.ruma_route(client_server::set_room_visibility_route)
.ruma_route(client_server::get_room_visibility_route)
.ruma_route(client_server::get_public_rooms_route)
.ruma_route(client_server::get_public_rooms_filtered_route)
.ruma_route(client_server::search_users_route)
.ruma_route(client_server::get_member_events_route)
.ruma_route(client_server::get_protocols_route)
.ruma_route(client_server::send_message_event_route)
.ruma_route(client_server::send_state_event_for_key_route)
.ruma_route(client_server::get_state_events_route)
.ruma_route(client_server::get_state_events_for_key_route)
.ruma_route(client::get_supported_versions_route)
.ruma_route(client::get_register_available_route)
.ruma_route(client::register_route)
.ruma_route(client::get_login_types_route)
.ruma_route(client::login_route)
.ruma_route(client::whoami_route)
.ruma_route(client::logout_route)
.ruma_route(client::logout_all_route)
.ruma_route(client::change_password_route)
.ruma_route(client::deactivate_route)
.ruma_route(client::third_party_route)
.ruma_route(client::request_3pid_management_token_via_email_route)
.ruma_route(client::request_3pid_management_token_via_msisdn_route)
.ruma_route(client::check_registration_token_validity)
.ruma_route(client::get_capabilities_route)
.ruma_route(client::get_pushrules_all_route)
.ruma_route(client::set_pushrule_route)
.ruma_route(client::get_pushrule_route)
.ruma_route(client::set_pushrule_enabled_route)
.ruma_route(client::get_pushrule_enabled_route)
.ruma_route(client::get_pushrule_actions_route)
.ruma_route(client::set_pushrule_actions_route)
.ruma_route(client::delete_pushrule_route)
.ruma_route(client::get_room_event_route)
.ruma_route(client::get_room_aliases_route)
.ruma_route(client::get_filter_route)
.ruma_route(client::create_filter_route)
.ruma_route(client::set_global_account_data_route)
.ruma_route(client::set_room_account_data_route)
.ruma_route(client::get_global_account_data_route)
.ruma_route(client::get_room_account_data_route)
.ruma_route(client::set_displayname_route)
.ruma_route(client::get_displayname_route)
.ruma_route(client::set_avatar_url_route)
.ruma_route(client::get_avatar_url_route)
.ruma_route(client::get_profile_route)
.ruma_route(client::set_presence_route)
.ruma_route(client::get_presence_route)
.ruma_route(client::upload_keys_route)
.ruma_route(client::get_keys_route)
.ruma_route(client::claim_keys_route)
.ruma_route(client::create_backup_version_route)
.ruma_route(client::update_backup_version_route)
.ruma_route(client::delete_backup_version_route)
.ruma_route(client::get_latest_backup_info_route)
.ruma_route(client::get_backup_info_route)
.ruma_route(client::add_backup_keys_route)
.ruma_route(client::add_backup_keys_for_room_route)
.ruma_route(client::add_backup_keys_for_session_route)
.ruma_route(client::delete_backup_keys_for_room_route)
.ruma_route(client::delete_backup_keys_for_session_route)
.ruma_route(client::delete_backup_keys_route)
.ruma_route(client::get_backup_keys_for_room_route)
.ruma_route(client::get_backup_keys_for_session_route)
.ruma_route(client::get_backup_keys_route)
.ruma_route(client::set_read_marker_route)
.ruma_route(client::create_receipt_route)
.ruma_route(client::create_typing_event_route)
.ruma_route(client::create_room_route)
.ruma_route(client::redact_event_route)
.ruma_route(client::report_event_route)
.ruma_route(client::create_alias_route)
.ruma_route(client::delete_alias_route)
.ruma_route(client::get_alias_route)
.ruma_route(client::join_room_by_id_route)
.ruma_route(client::join_room_by_id_or_alias_route)
.ruma_route(client::joined_members_route)
.ruma_route(client::leave_room_route)
.ruma_route(client::forget_room_route)
.ruma_route(client::joined_rooms_route)
.ruma_route(client::kick_user_route)
.ruma_route(client::ban_user_route)
.ruma_route(client::unban_user_route)
.ruma_route(client::invite_user_route)
.ruma_route(client::set_room_visibility_route)
.ruma_route(client::get_room_visibility_route)
.ruma_route(client::get_public_rooms_route)
.ruma_route(client::get_public_rooms_filtered_route)
.ruma_route(client::search_users_route)
.ruma_route(client::get_member_events_route)
.ruma_route(client::get_protocols_route)
.ruma_route(client::send_message_event_route)
.ruma_route(client::send_state_event_for_key_route)
.ruma_route(client::get_state_events_route)
.ruma_route(client::get_state_events_for_key_route)
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these routes
// share one Ruma request / response type pair with {get,send}_state_event_for_key_route
.route(
"/_matrix/client/r0/rooms/:room_id/state/:event_type",
get(client_server::get_state_events_for_empty_key_route)
.put(client_server::send_state_event_for_empty_key_route),
get(client::get_state_events_for_empty_key_route)
.put(client::send_state_event_for_empty_key_route),
)
.route(
"/_matrix/client/v3/rooms/:room_id/state/:event_type",
get(client_server::get_state_events_for_empty_key_route)
.put(client_server::send_state_event_for_empty_key_route),
get(client::get_state_events_for_empty_key_route)
.put(client::send_state_event_for_empty_key_route),
)
// These two endpoints allow trailing slashes
.route(
"/_matrix/client/r0/rooms/:room_id/state/:event_type/",
get(client_server::get_state_events_for_empty_key_route)
.put(client_server::send_state_event_for_empty_key_route),
get(client::get_state_events_for_empty_key_route)
.put(client::send_state_event_for_empty_key_route),
)
.route(
"/_matrix/client/v3/rooms/:room_id/state/:event_type/",
get(client_server::get_state_events_for_empty_key_route)
.put(client_server::send_state_event_for_empty_key_route),
get(client::get_state_events_for_empty_key_route)
.put(client::send_state_event_for_empty_key_route),
)
.ruma_route(client_server::sync_events_route)
.ruma_route(client_server::sync_events_v4_route)
.ruma_route(client_server::get_context_route)
.ruma_route(client_server::get_message_events_route)
.ruma_route(client_server::search_events_route)
.ruma_route(client_server::turn_server_route)
.ruma_route(client_server::send_event_to_device_route)
.ruma_route(client_server::get_media_config_route)
.ruma_route(client_server::get_media_preview_route)
.ruma_route(client_server::create_content_route)
.ruma_route(client::sync_events_route)
.ruma_route(client::sync_events_v4_route)
.ruma_route(client::get_context_route)
.ruma_route(client::get_message_events_route)
.ruma_route(client::search_events_route)
.ruma_route(client::turn_server_route)
.ruma_route(client::send_event_to_device_route)
.ruma_route(client::get_media_config_route)
.ruma_route(client::get_media_preview_route)
.ruma_route(client::create_content_route)
// legacy v1 media routes
.route(
"/_matrix/media/v1/preview_url",
get(client_server::get_media_preview_v1_route)
get(client::get_media_preview_v1_route)
)
.route(
"/_matrix/media/v1/config",
get(client_server::get_media_config_v1_route)
get(client::get_media_config_v1_route)
)
.route(
"/_matrix/media/v1/upload",
post(client_server::create_content_v1_route)
post(client::create_content_v1_route)
)
.route(
"/_matrix/media/v1/download/:server_name/:media_id",
get(client_server::get_content_v1_route)
get(client::get_content_v1_route)
)
.route(
"/_matrix/media/v1/download/:server_name/:media_id/:file_name",
get(client_server::get_content_as_filename_v1_route)
get(client::get_content_as_filename_v1_route)
)
.route(
"/_matrix/media/v1/thumbnail/:server_name/:media_id",
get(client_server::get_content_thumbnail_v1_route)
get(client::get_content_thumbnail_v1_route)
)
.ruma_route(client_server::get_content_route)
.ruma_route(client_server::get_content_as_filename_route)
.ruma_route(client_server::get_content_thumbnail_route)
.ruma_route(client_server::get_devices_route)
.ruma_route(client_server::get_device_route)
.ruma_route(client_server::update_device_route)
.ruma_route(client_server::delete_device_route)
.ruma_route(client_server::delete_devices_route)
.ruma_route(client_server::get_tags_route)
.ruma_route(client_server::update_tag_route)
.ruma_route(client_server::delete_tag_route)
.ruma_route(client_server::upload_signing_keys_route)
.ruma_route(client_server::upload_signatures_route)
.ruma_route(client_server::get_key_changes_route)
.ruma_route(client_server::get_pushers_route)
.ruma_route(client_server::set_pushers_route)
// .ruma_route(client_server::third_party_route)
.ruma_route(client_server::upgrade_room_route)
.ruma_route(client_server::get_threads_route)
.ruma_route(client_server::get_relating_events_with_rel_type_and_event_type_route)
.ruma_route(client_server::get_relating_events_with_rel_type_route)
.ruma_route(client_server::get_relating_events_route)
.ruma_route(client_server::get_hierarchy_route)
.ruma_route(client_server::get_mutual_rooms_route)
.ruma_route(client_server::well_known_support)
.ruma_route(client_server::well_known_client)
.route("/_conduwuit/server_version", get(client_server::conduwuit_server_version))
.ruma_route(client::get_content_route)
.ruma_route(client::get_content_as_filename_route)
.ruma_route(client::get_content_thumbnail_route)
.ruma_route(client::get_devices_route)
.ruma_route(client::get_device_route)
.ruma_route(client::update_device_route)
.ruma_route(client::delete_device_route)
.ruma_route(client::delete_devices_route)
.ruma_route(client::get_tags_route)
.ruma_route(client::update_tag_route)
.ruma_route(client::delete_tag_route)
.ruma_route(client::upload_signing_keys_route)
.ruma_route(client::upload_signatures_route)
.ruma_route(client::get_key_changes_route)
.ruma_route(client::get_pushers_route)
.ruma_route(client::set_pushers_route)
// .ruma_route(client::third_party_route)
.ruma_route(client::upgrade_room_route)
.ruma_route(client::get_threads_route)
.ruma_route(client::get_relating_events_with_rel_type_and_event_type_route)
.ruma_route(client::get_relating_events_with_rel_type_route)
.ruma_route(client::get_relating_events_route)
.ruma_route(client::get_hierarchy_route)
.ruma_route(client::get_mutual_rooms_route)
.ruma_route(client::well_known_support)
.ruma_route(client::well_known_client)
.route("/_conduwuit/server_version", get(client::conduwuit_server_version))
.route("/_matrix/client/r0/rooms/:room_id/initialSync", get(initial_sync))
.route("/_matrix/client/v3/rooms/:room_id/initialSync", get(initial_sync))
.route("/client/server.json", get(client_server::syncv3_client_server_json));
.route("/client/server.json", get(client::syncv3_client_server_json));
if config.allow_federation {
router
.ruma_route(server_server::get_server_version_route)
.route("/_matrix/key/v2/server", get(server_server::get_server_keys_route))
.route(
"/_matrix/key/v2/server/:key_id",
get(server_server::get_server_keys_deprecated_route),
)
.ruma_route(server_server::get_public_rooms_route)
.ruma_route(server_server::get_public_rooms_filtered_route)
.ruma_route(server_server::send_transaction_message_route)
.ruma_route(server_server::get_event_route)
.ruma_route(server_server::get_backfill_route)
.ruma_route(server_server::get_missing_events_route)
.ruma_route(server_server::get_event_authorization_route)
.ruma_route(server_server::get_room_state_route)
.ruma_route(server_server::get_room_state_ids_route)
.ruma_route(server_server::create_leave_event_template_route)
.ruma_route(server_server::create_leave_event_v1_route)
.ruma_route(server_server::create_leave_event_v2_route)
.ruma_route(server_server::create_join_event_template_route)
.ruma_route(server_server::create_join_event_v1_route)
.ruma_route(server_server::create_join_event_v2_route)
.ruma_route(server_server::create_invite_route)
.ruma_route(server_server::get_devices_route)
.ruma_route(server_server::get_room_information_route)
.ruma_route(server_server::get_profile_information_route)
.ruma_route(server_server::get_keys_route)
.ruma_route(server_server::claim_keys_route)
.ruma_route(server_server::get_hierarchy_route)
.ruma_route(server_server::well_known_server)
.route("/_conduwuit/local_user_count", get(client_server::conduwuit_local_user_count))
.ruma_route(server::get_server_version_route)
.route("/_matrix/key/v2/server", get(server::get_server_keys_route))
.route("/_matrix/key/v2/server/:key_id", get(server::get_server_keys_deprecated_route))
.ruma_route(server::get_public_rooms_route)
.ruma_route(server::get_public_rooms_filtered_route)
.ruma_route(server::send_transaction_message_route)
.ruma_route(server::get_event_route)
.ruma_route(server::get_backfill_route)
.ruma_route(server::get_missing_events_route)
.ruma_route(server::get_event_authorization_route)
.ruma_route(server::get_room_state_route)
.ruma_route(server::get_room_state_ids_route)
.ruma_route(server::create_leave_event_template_route)
.ruma_route(server::create_leave_event_v1_route)
.ruma_route(server::create_leave_event_v2_route)
.ruma_route(server::create_join_event_template_route)
.ruma_route(server::create_join_event_v1_route)
.ruma_route(server::create_join_event_v2_route)
.ruma_route(server::create_invite_route)
.ruma_route(server::get_devices_route)
.ruma_route(server::get_room_information_route)
.ruma_route(server::get_profile_information_route)
.ruma_route(server::get_keys_route)
.ruma_route(server::claim_keys_route)
.ruma_route(server::get_hierarchy_route)
.ruma_route(server::well_known_server)
.route("/_conduwuit/local_user_count", get(client::conduwuit_local_user_count))
} else {
router
.route("/_matrix/federation/*path", any(federation_disabled))
@@ -234,66 +229,3 @@ async fn initial_sync(_uri: Uri) -> impl IntoResponse {
}
async fn federation_disabled() -> impl IntoResponse { Error::bad_config("Federation is disabled.") }
trait RouterExt {
fn ruma_route<H, T>(self, handler: H) -> Self
where
H: RumaHandler<T>,
T: 'static;
}
impl RouterExt for Router {
#[inline(always)]
fn ruma_route<H, T>(self, handler: H) -> Self
where
H: RumaHandler<T>,
T: 'static,
{
handler.add_routes(self)
}
}
trait RumaHandler<T> {
fn add_routes(&self, router: Router) -> Router;
fn add_route(&self, router: Router, path: &str) -> Router;
}
impl<Req, E, F, Fut> RumaHandler<Ruma<Req>> for F
where
Req: IncomingRequest + Send + 'static,
F: FnOnce(Ruma<Req>) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Result<Req::OutgoingResponse, E>> + Send,
E: IntoResponse,
{
#[inline(always)]
fn add_routes(&self, router: Router) -> Router {
Req::METADATA
.history
.all_paths()
.fold(router, |router, path| self.add_route(router, path))
}
#[inline(always)]
fn add_route(&self, router: Router, path: &str) -> Router {
let handle = self.clone();
let method = method_to_filter(Req::METADATA.method);
let action = |req| async { handle(req).await.map(RumaResponse) };
router.route(path, on(method, action))
}
}
#[inline]
fn method_to_filter(method: Method) -> MethodFilter {
match method {
Method::DELETE => MethodFilter::DELETE,
Method::GET => MethodFilter::GET,
Method::HEAD => MethodFilter::HEAD,
Method::OPTIONS => MethodFilter::OPTIONS,
Method::PATCH => MethodFilter::PATCH,
Method::POST => MethodFilter::POST,
Method::PUT => MethodFilter::PUT,
Method::TRACE => MethodFilter::TRACE,
m => panic!("Unsupported HTTP method: {m:?}"),
}
}

View File

@@ -1,10 +1,14 @@
use std::collections::BTreeMap;
use axum::RequestPartsExt;
use axum_extra::{headers::Authorization, typed_header::TypedHeaderRejectionReason, TypedHeader};
use axum_extra::{
headers::{authorization::Bearer, Authorization},
typed_header::TypedHeaderRejectionReason,
TypedHeader,
};
use http::uri::PathAndQuery;
use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest},
api::{client::error::ErrorKind, AuthScheme, Metadata},
CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
};
use tracing::warn;
@@ -20,18 +24,17 @@ enum Token {
}
pub(super) struct Auth {
pub(super) origin: Option<OwnedServerName>,
pub(super) sender_user: Option<OwnedUserId>,
pub(super) sender_device: Option<OwnedDeviceId>,
pub(super) origin: Option<OwnedServerName>,
pub(super) appservice_info: Option<RegistrationInfo>,
}
pub(super) async fn auth<T>(request: &mut Request) -> Result<Auth>
where
T: IncomingRequest,
{
let metadata = T::METADATA;
let token = match &request.auth {
pub(super) async fn auth(
request: &mut Request, json_body: &Option<CanonicalJsonValue>, metadata: &Metadata,
) -> Result<Auth> {
let bearer: Option<TypedHeader<Authorization<Bearer>>> = request.parts.extract().await?;
let token = match &bearer {
Some(TypedHeader(Authorization(bearer))) => Some(bearer.token()),
None => request.query.access_token.as_deref(),
};
@@ -82,25 +85,38 @@ pub(super) async fn auth<T>(request: &mut Request) -> Result<Auth>
(AuthScheme::AccessToken, Token::Appservice(info)) => Ok(auth_appservice(request, info)?),
(AuthScheme::None | AuthScheme::AccessTokenOptional | AuthScheme::AppserviceToken, Token::Appservice(info)) => {
Ok(Auth {
origin: None,
sender_user: None,
sender_device: None,
origin: None,
appservice_info: Some(*info),
})
},
(AuthScheme::AccessToken, Token::None) => {
Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))
(AuthScheme::AccessToken, Token::None) => match request.parts.uri.path() {
// TODO: can we check this better?
"/_matrix/client/v3/voip/turnServer" | "/_matrix/client/r0/voip/turnServer" => {
if services().globals.config.turn_allow_guests {
Ok(Auth {
origin: None,
sender_user: None,
sender_device: None,
appservice_info: None,
})
} else {
Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))
}
},
_ => Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")),
},
(
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::None,
Token::User((user_id, device_id)),
) => Ok(Auth {
origin: None,
sender_user: Some(user_id),
sender_device: Some(device_id),
origin: None,
appservice_info: None,
}),
(AuthScheme::ServerSignatures, Token::None) => Ok(auth_server(request).await?),
(AuthScheme::ServerSignatures, Token::None) => Ok(auth_server(request, json_body).await?),
(AuthScheme::None | AuthScheme::AppserviceToken | AuthScheme::AccessTokenOptional, Token::None) => Ok(Auth {
sender_user: None,
sender_device: None,
@@ -118,7 +134,7 @@ pub(super) async fn auth<T>(request: &mut Request) -> Result<Auth>
}
}
fn auth_appservice(request: &mut Request, info: Box<RegistrationInfo>) -> Result<Auth> {
fn auth_appservice(request: &Request, info: Box<RegistrationInfo>) -> Result<Auth> {
let user_id = request
.query
.user_id
@@ -143,14 +159,14 @@ fn auth_appservice(request: &mut Request, info: Box<RegistrationInfo>) -> Result
}
Ok(Auth {
origin: None,
sender_user: Some(user_id),
sender_device: None,
origin: None,
appservice_info: Some(*info),
})
}
async fn auth_server(request: &mut Request) -> Result<Auth> {
async fn auth_server(request: &mut Request, json_body: &Option<CanonicalJsonValue>) -> Result<Auth> {
if !services().globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled."));
}
@@ -171,15 +187,11 @@ async fn auth_server(request: &mut Request) -> Result<Auth> {
Error::BadRequest(ErrorKind::forbidden(), msg)
})?;
let origin_signatures = BTreeMap::from_iter([(x_matrix.key.clone(), CanonicalJsonValue::String(x_matrix.sig))]);
let signatures = BTreeMap::from_iter([(
x_matrix.origin.as_str().to_owned(),
CanonicalJsonValue::Object(origin_signatures),
)]);
let origin = &x_matrix.origin;
let signatures = BTreeMap::from_iter([(x_matrix.key.clone(), CanonicalJsonValue::String(x_matrix.sig))]);
let signatures = BTreeMap::from_iter([(origin.as_str().to_owned(), CanonicalJsonValue::Object(signatures))]);
let server_destination = services().globals.server_name().as_str().to_owned();
if let Some(destination) = x_matrix.destination.as_ref() {
if destination != &server_destination {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Invalid authorization."));
@@ -201,22 +213,19 @@ async fn auth_server(request: &mut Request) -> Result<Auth> {
CanonicalJsonValue::String(request.parts.method.to_string()),
),
("uri".to_owned(), signature_uri),
(
"origin".to_owned(),
CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()),
),
("origin".to_owned(), CanonicalJsonValue::String(origin.as_str().to_owned())),
("destination".to_owned(), CanonicalJsonValue::String(server_destination)),
("signatures".to_owned(), CanonicalJsonValue::Object(signatures)),
]);
if let Some(json_body) = &request.json {
if let Some(json_body) = json_body {
request_map.insert("content".to_owned(), json_body.clone());
};
let keys_result = services()
.rooms
.event_handler
.fetch_signing_keys_for_server(&x_matrix.origin, vec![x_matrix.key.clone()])
.fetch_signing_keys_for_server(origin, vec![x_matrix.key.clone()])
.await;
let keys = keys_result.map_err(|e| {
@@ -224,17 +233,17 @@ async fn auth_server(request: &mut Request) -> Result<Auth> {
Error::BadRequest(ErrorKind::forbidden(), "Failed to fetch signing keys.")
})?;
let pub_key_map = BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]);
let pub_key_map = BTreeMap::from_iter([(origin.as_str().to_owned(), keys)]);
match ruma::signatures::verify_json(&pub_key_map, &request_map) {
Ok(()) => Ok(Auth {
origin: Some(origin.clone()),
sender_user: None,
sender_device: None,
origin: Some(x_matrix.origin),
appservice_info: None,
}),
Err(e) => {
warn!("Failed to verify json request from {}: {e}\n{request_map:?}", x_matrix.origin);
warn!("Failed to verify json request from {origin}: {e}\n{request_map:?}");
if request.parts.uri.to_string().contains('@') {
warn!(

View File

@@ -0,0 +1,81 @@
use std::future::Future;
use axum::{
extract::FromRequestParts,
response::IntoResponse,
routing::{on, MethodFilter},
Router,
};
use conduit::Result;
use http::Method;
use ruma::api::IncomingRequest;
use super::{Ruma, RumaResponse};
pub(in super::super) trait RouterExt {
fn ruma_route<H, T>(self, handler: H) -> Self
where
H: RumaHandler<T>;
}
impl RouterExt for Router {
fn ruma_route<H, T>(self, handler: H) -> Self
where
H: RumaHandler<T>,
{
handler.add_routes(self)
}
}
pub(in super::super) trait RumaHandler<T> {
fn add_routes(&self, router: Router) -> Router;
fn add_route(&self, router: Router, path: &str) -> Router;
}
macro_rules! ruma_handler {
( $($tx:ident),* $(,)? ) => {
#[allow(non_snake_case)]
impl<Req, Ret, Fut, Fun, $($tx,)*> RumaHandler<($($tx,)* Ruma<Req>,)> for Fun
where
Req: IncomingRequest + Send + 'static,
Ret: IntoResponse,
Fut: Future<Output = Result<Req::OutgoingResponse, Ret>> + Send,
Fun: FnOnce($($tx,)* Ruma<Req>) -> Fut + Clone + Send + Sync + 'static,
$( $tx: FromRequestParts<()> + Send + 'static, )*
{
fn add_routes(&self, router: Router) -> Router {
Req::METADATA
.history
.all_paths()
.fold(router, |router, path| self.add_route(router, path))
}
fn add_route(&self, router: Router, path: &str) -> Router {
let handle = self.clone();
let method = method_to_filter(&Req::METADATA.method);
let action = |$($tx,)* req| async { handle($($tx,)* req).await.map(RumaResponse) };
router.route(path, on(method, action))
}
}
}
}
ruma_handler!();
ruma_handler!(T1);
ruma_handler!(T1, T2);
ruma_handler!(T1, T2, T3);
ruma_handler!(T1, T2, T3, T4);
const fn method_to_filter(method: &Method) -> MethodFilter {
match *method {
Method::DELETE => MethodFilter::DELETE,
Method::GET => MethodFilter::GET,
Method::HEAD => MethodFilter::HEAD,
Method::OPTIONS => MethodFilter::OPTIONS,
Method::PATCH => MethodFilter::PATCH,
Method::POST => MethodFilter::POST,
Method::PUT => MethodFilter::PUT,
Method::TRACE => MethodFilter::TRACE,
_ => panic!("Unsupported HTTP method"),
}
}

View File

@@ -1,23 +1,69 @@
mod auth;
mod handler;
mod request;
mod xmatrix;
use std::ops::Deref;
use std::{mem, ops::Deref};
use ruma::{CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId};
use axum::{async_trait, body::Body, extract::FromRequest};
use bytes::{BufMut, BytesMut};
pub(super) use conduit::error::RumaResponse;
use conduit::{debug, debug_warn, trace, warn};
use ruma::{
api::{client::error::ErrorKind, IncomingRequest},
CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
};
use crate::service::appservice::RegistrationInfo;
pub(super) use self::handler::RouterExt;
use self::{auth::Auth, request::Request};
use crate::{service::appservice::RegistrationInfo, services, Error, Result};
/// Extractor for Ruma request structs
pub(crate) struct Ruma<T> {
/// Request struct body
pub(crate) body: T,
pub(crate) sender_user: Option<OwnedUserId>,
pub(crate) sender_device: Option<OwnedDeviceId>,
/// X-Matrix origin/server
/// Federation server authentication: X-Matrix origin
/// None when not a federation server.
pub(crate) origin: Option<OwnedServerName>,
pub(crate) json_body: Option<CanonicalJsonValue>, // This is None when body is not a valid string
/// Local user authentication: user_id.
/// None when not an authenticated local user.
pub(crate) sender_user: Option<OwnedUserId>,
/// Local user authentication: device_id.
/// None when not an authenticated local user or no device.
pub(crate) sender_device: Option<OwnedDeviceId>,
/// Appservice authentication; registration info.
/// None when not an appservice.
pub(crate) appservice_info: Option<RegistrationInfo>,
/// Parsed JSON content.
/// None when body is not a valid string
pub(crate) json_body: Option<CanonicalJsonValue>,
}
#[async_trait]
impl<T, S> FromRequest<S, Body> for Ruma<T>
where
T: IncomingRequest,
{
type Rejection = Error;
async fn from_request(request: hyper::Request<Body>, _: &S) -> Result<Self, Self::Rejection> {
let mut request = request::from(request).await?;
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&request.body).ok();
let auth = auth::auth(&mut request, &json_body, &T::METADATA).await?;
Ok(Self {
body: make_body::<T>(&mut request, &mut json_body, &auth)?,
origin: auth.origin,
sender_user: auth.sender_user,
sender_device: auth.sender_device,
appservice_info: auth.appservice_info,
json_body,
})
}
}
impl<T> Deref for Ruma<T> {
@@ -25,3 +71,60 @@ impl<T> Deref for Ruma<T> {
fn deref(&self) -> &Self::Target { &self.body }
}
fn make_body<T>(request: &mut Request, json_body: &mut Option<CanonicalJsonValue>, auth: &Auth) -> Result<T>
where
T: IncomingRequest,
{
let body = if let Some(CanonicalJsonValue::Object(json_body)) = json_body {
let user_id = auth.sender_user.clone().unwrap_or_else(|| {
UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid")
});
let uiaa_request = json_body
.get("auth")
.and_then(|auth| auth.as_object())
.and_then(|auth| auth.get("session"))
.and_then(|session| session.as_str())
.and_then(|session| {
services().uiaa.get_uiaa_request(
&user_id,
&auth.sender_device.clone().unwrap_or_else(|| "".into()),
session,
)
});
if let Some(CanonicalJsonValue::Object(initial_request)) = uiaa_request {
for (key, value) in initial_request {
json_body.entry(key).or_insert(value);
}
}
let mut buf = BytesMut::new().writer();
serde_json::to_writer(&mut buf, &json_body).expect("value serialization can't fail");
buf.into_inner().freeze()
} else {
mem::take(&mut request.body)
};
let mut http_request = hyper::Request::builder()
.uri(request.parts.uri.clone())
.method(request.parts.method.clone());
*http_request.headers_mut().unwrap() = request.parts.headers.clone();
let http_request = http_request.body(body).unwrap();
debug!(
"{:?} {:?} {:?}",
http_request.method(),
http_request.uri(),
http_request.headers()
);
trace!("{:?} {:?} {:?}", http_request.method(), http_request.uri(), json_body);
let body = T::try_from_http_request(http_request, &request.path).map_err(|e| {
warn!("try_from_http_request failed: {e:?}",);
debug_warn!("JSON body: {:?}", json_body);
Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.")
})?;
Ok(body)
}

View File

@@ -1,25 +1,11 @@
use std::{mem, str};
use std::str;
use axum::{
async_trait,
extract::{FromRequest, Path},
RequestExt, RequestPartsExt,
};
use axum_extra::{
headers::{authorization::Bearer, Authorization},
TypedHeader,
};
use bytes::{BufMut, Bytes, BytesMut};
use conduit::debug_warn;
use axum::{extract::Path, RequestExt, RequestPartsExt};
use bytes::Bytes;
use http::request::Parts;
use ruma::{
api::{client::error::ErrorKind, IncomingRequest},
CanonicalJsonValue, UserId,
};
use ruma::api::client::error::ErrorKind;
use serde::Deserialize;
use tracing::{debug, trace, warn};
use super::{auth, auth::Auth, Ruma};
use crate::{services, Error, Result};
#[derive(Deserialize)]
@@ -29,99 +15,17 @@ pub(super) struct QueryParams {
}
pub(super) struct Request {
pub(super) auth: Option<TypedHeader<Authorization<Bearer>>>,
pub(super) path: Path<Vec<String>>,
pub(super) query: QueryParams,
pub(super) json: Option<CanonicalJsonValue>,
pub(super) body: Bytes,
pub(super) parts: Parts,
}
#[async_trait]
impl<T, S> FromRequest<S, axum::body::Body> for Ruma<T>
where
T: IncomingRequest,
{
type Rejection = Error;
async fn from_request(request: hyper::Request<axum::body::Body>, _state: &S) -> Result<Self, Self::Rejection> {
let mut request: Request = extract(request).await?;
let auth: Auth = auth::auth::<T>(&mut request).await?;
let body = make_body::<T>(&mut request, &auth)?;
Ok(Ruma {
body,
sender_user: auth.sender_user,
sender_device: auth.sender_device,
origin: auth.origin,
json_body: request.json,
appservice_info: auth.appservice_info,
})
}
}
fn make_body<T>(request: &mut Request, auth: &Auth) -> Result<T>
where
T: IncomingRequest,
{
let body = if let Some(CanonicalJsonValue::Object(json_body)) = &mut request.json {
let user_id = auth.sender_user.clone().unwrap_or_else(|| {
UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid")
});
let uiaa_request = json_body
.get("auth")
.and_then(|auth| auth.as_object())
.and_then(|auth| auth.get("session"))
.and_then(|session| session.as_str())
.and_then(|session| {
services().uiaa.get_uiaa_request(
&user_id,
&auth.sender_device.clone().unwrap_or_else(|| "".into()),
session,
)
});
if let Some(CanonicalJsonValue::Object(initial_request)) = uiaa_request {
for (key, value) in initial_request {
json_body.entry(key).or_insert(value);
}
}
let mut buf = BytesMut::new().writer();
serde_json::to_writer(&mut buf, &request.json).expect("value serialization can't fail");
buf.into_inner().freeze()
} else {
mem::take(&mut request.body)
};
let mut http_request = hyper::Request::builder()
.uri(request.parts.uri.clone())
.method(request.parts.method.clone());
*http_request.headers_mut().unwrap() = request.parts.headers.clone();
let http_request = http_request.body(body).unwrap();
debug!(
"{:?} {:?} {:?}",
http_request.method(),
http_request.uri(),
http_request.headers()
);
trace!("{:?} {:?} {:?}", http_request.method(), http_request.uri(), request.json);
let body = T::try_from_http_request(http_request, &request.path).map_err(|e| {
warn!("try_from_http_request failed: {e:?}",);
debug_warn!("JSON body: {:?}", request.json);
Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.")
})?;
Ok(body)
}
async fn extract(request: hyper::Request<axum::body::Body>) -> Result<Request> {
pub(super) async fn from(request: hyper::Request<axum::body::Body>) -> Result<Request> {
let limited = request.with_limited_body();
let (mut parts, body) = limited.into_parts();
let auth = parts.extract().await?;
let path = parts.extract().await?;
let path: Path<Vec<String>> = parts.extract().await?;
let query = serde_html_form::from_str(parts.uri.query().unwrap_or_default())
.map_err(|_| Error::BadRequest(ErrorKind::Unknown, "Failed to read query parameters"))?;
@@ -136,13 +40,9 @@ async fn extract(request: hyper::Request<axum::body::Body>) -> Result<Request> {
.await
.map_err(|_| Error::BadRequest(ErrorKind::TooLarge, "Request body too large"))?;
let json = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
Ok(Request {
auth,
path,
query,
json,
body,
parts,
})

View File

@@ -0,0 +1,73 @@
use ruma::{
api::{client::error::ErrorKind, federation::backfill::get_backfill},
uint, user_id, MilliSecondsSinceUnixEpoch,
};
use crate::{services, Error, PduEvent, Result, Ruma};
/// # `GET /_matrix/federation/v1/backfill/<room_id>`
///
/// Retrieves events from before the sender joined the room, if the room's
/// history visibility allows.
pub(crate) async fn get_backfill_route(body: Ruma<get_backfill::v1::Request>) -> Result<get_backfill::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
services()
.rooms
.event_handler
.acl_check(origin, &body.room_id)?;
if !services()
.rooms
.state_accessor
.is_world_readable(&body.room_id)?
&& !services()
.rooms
.state_cache
.server_in_room(origin, &body.room_id)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Server is not in room."));
}
let until = body
.v
.iter()
.map(|event_id| services().rooms.timeline.get_pdu_count(event_id))
.filter_map(|r| r.ok().flatten())
.max()
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event not found."))?;
let limit = body
.limit
.min(uint!(100))
.try_into()
.expect("UInt could not be converted to usize");
let all_events = services()
.rooms
.timeline
.pdus_until(user_id!("@doesntmatter:conduit.rs"), &body.room_id, until)?
.take(limit);
let events = all_events
.filter_map(Result::ok)
.filter(|(_, e)| {
matches!(
services()
.rooms
.state_accessor
.server_can_see_event(origin, &e.room_id, &e.event_id,),
Ok(true),
)
})
.map(|(_, pdu)| services().rooms.timeline.get_pdu_json(&pdu.event_id))
.filter_map(|r| r.ok().flatten())
.map(PduEvent::convert_to_outgoing_federation_event)
.collect();
Ok(get_backfill::v1::Response {
origin: services().globals.server_name().to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
pdus: events,
})
}

53
src/api/server/event.rs Normal file
View File

@@ -0,0 +1,53 @@
use ruma::{
api::{client::error::ErrorKind, federation::event::get_event},
MilliSecondsSinceUnixEpoch, RoomId,
};
use crate::{services, Error, PduEvent, Result, Ruma};
/// # `GET /_matrix/federation/v1/event/{eventId}`
///
/// Retrieves a single event from the server.
///
/// - Only works if a user of this server is currently invited or joined the
/// room
pub(crate) async fn get_event_route(body: Ruma<get_event::v1::Request>) -> Result<get_event::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
let event = services()
.rooms
.timeline
.get_pdu_json(&body.event_id)?
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Event not found."))?;
let room_id_str = event
.get("room_id")
.and_then(|val| val.as_str())
.ok_or_else(|| Error::bad_database("Invalid event in database."))?;
let room_id =
<&RoomId>::try_from(room_id_str).map_err(|_| Error::bad_database("Invalid room_id in event in database."))?;
if !services().rooms.state_accessor.is_world_readable(room_id)?
&& !services()
.rooms
.state_cache
.server_in_room(origin, room_id)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Server is not in room."));
}
if !services()
.rooms
.state_accessor
.server_can_see_event(origin, room_id, &body.event_id)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Server is not allowed to see event."));
}
Ok(get_event::v1::Response {
origin: services().globals.server_name().to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
pdu: PduEvent::convert_to_outgoing_federation_event(event),
})
}

View File

@@ -0,0 +1,63 @@
use std::sync::Arc;
use ruma::{
api::{client::error::ErrorKind, federation::authorization::get_event_authorization},
RoomId,
};
use crate::{services, Error, PduEvent, Result, Ruma};
/// # `GET /_matrix/federation/v1/event_auth/{roomId}/{eventId}`
///
/// Retrieves the auth chain for a given event.
///
/// - This does not include the event itself
pub(crate) async fn get_event_authorization_route(
body: Ruma<get_event_authorization::v1::Request>,
) -> Result<get_event_authorization::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
services()
.rooms
.event_handler
.acl_check(origin, &body.room_id)?;
if !services()
.rooms
.state_accessor
.is_world_readable(&body.room_id)?
&& !services()
.rooms
.state_cache
.server_in_room(origin, &body.room_id)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Server is not in room."));
}
let event = services()
.rooms
.timeline
.get_pdu_json(&body.event_id)?
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Event not found."))?;
let room_id_str = event
.get("room_id")
.and_then(|val| val.as_str())
.ok_or_else(|| Error::bad_database("Invalid event in database."))?;
let room_id =
<&RoomId>::try_from(room_id_str).map_err(|_| Error::bad_database("Invalid room_id in event in database."))?;
let auth_chain_ids = services()
.rooms
.auth_chain
.event_ids_iter(room_id, vec![Arc::from(&*body.event_id)])
.await?;
Ok(get_event_authorization::v1::Response {
auth_chain: auth_chain_ids
.filter_map(|id| services().rooms.timeline.get_pdu_json(&id).ok()?)
.map(PduEvent::convert_to_outgoing_federation_event)
.collect(),
})
}

View File

@@ -0,0 +1,90 @@
use ruma::{
api::{client::error::ErrorKind, federation::event::get_missing_events},
OwnedEventId, RoomId,
};
use crate::{services, Error, PduEvent, Result, Ruma};
/// # `POST /_matrix/federation/v1/get_missing_events/{roomId}`
///
/// Retrieves events that the sender is missing.
pub(crate) async fn get_missing_events_route(
body: Ruma<get_missing_events::v1::Request>,
) -> Result<get_missing_events::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
services()
.rooms
.event_handler
.acl_check(origin, &body.room_id)?;
if !services()
.rooms
.state_accessor
.is_world_readable(&body.room_id)?
&& !services()
.rooms
.state_cache
.server_in_room(origin, &body.room_id)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Server is not in room"));
}
let limit = body
.limit
.try_into()
.expect("UInt could not be converted to usize");
let mut queued_events = body.latest_events.clone();
// the vec will never have more entries the limit
let mut events = Vec::with_capacity(limit);
let mut i: usize = 0;
while i < queued_events.len() && events.len() < limit {
if let Some(pdu) = services().rooms.timeline.get_pdu_json(&queued_events[i])? {
let room_id_str = pdu
.get("room_id")
.and_then(|val| val.as_str())
.ok_or_else(|| Error::bad_database("Invalid event in database."))?;
let event_room_id = <&RoomId>::try_from(room_id_str)
.map_err(|_| Error::bad_database("Invalid room_id in event in database."))?;
if event_room_id != body.room_id {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Event from wrong room."));
}
if body.earliest_events.contains(&queued_events[i]) {
i = i.saturating_add(1);
continue;
}
if !services()
.rooms
.state_accessor
.server_can_see_event(origin, &body.room_id, &queued_events[i])?
{
i = i.saturating_add(1);
continue;
}
queued_events.extend_from_slice(
&serde_json::from_value::<Vec<OwnedEventId>>(
serde_json::to_value(
pdu.get("prev_events")
.cloned()
.ok_or_else(|| Error::bad_database("Event in db has no prev_events property."))?,
)
.expect("canonical json is valid json value"),
)
.map_err(|_| Error::bad_database("Invalid prev_events in event in database."))?,
);
events.push(PduEvent::convert_to_outgoing_federation_event(pdu));
}
i = i.saturating_add(1);
}
Ok(get_missing_events::v1::Response {
events,
})
}

View File

@@ -0,0 +1,21 @@
use ruma::api::{client::error::ErrorKind, federation::space::get_hierarchy};
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/federation/v1/hierarchy/{roomId}`
///
/// Gets the space tree in a depth-first manner to locate child rooms of a given
/// space.
pub(crate) async fn get_hierarchy_route(body: Ruma<get_hierarchy::v1::Request>) -> Result<get_hierarchy::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
if services().rooms.metadata.exists(&body.room_id)? {
services()
.rooms
.spaces
.get_federation_hierarchy(&body.room_id, origin, body.suggested_only)
.await
} else {
Err(Error::BadRequest(ErrorKind::NotFound, "Room does not exist."))
}
}

181
src/api/server/invite.rs Normal file
View File

@@ -0,0 +1,181 @@
use axum_client_ip::InsecureClientIp;
use ruma::{
api::{client::error::ErrorKind, federation::membership::create_invite},
events::room::member::{MembershipState, RoomMemberEventContent},
serde::JsonObject,
CanonicalJsonValue, EventId, OwnedUserId,
};
use tracing::warn;
use crate::{
service::server_is_ours,
services,
utils::{self},
Error, PduEvent, Result, Ruma,
};
/// # `PUT /_matrix/federation/v2/invite/{roomId}/{eventId}`
///
/// Invites a remote user to a room.
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn create_invite_route(
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<create_invite::v2::Request>,
) -> Result<create_invite::v2::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
// ACL check origin
services()
.rooms
.event_handler
.acl_check(origin, &body.room_id)?;
if !services()
.globals
.supported_room_versions()
.contains(&body.room_version)
{
return Err(Error::BadRequest(
ErrorKind::IncompatibleRoomVersion {
room_version: body.room_version.clone(),
},
"Server does not support this room version.",
));
}
if let Some(server) = body.room_id.server_name() {
if services()
.globals
.config
.forbidden_remote_server_names
.contains(&server.to_owned())
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
if services()
.globals
.config
.forbidden_remote_server_names
.contains(origin)
{
warn!(
"Received federated/remote invite from banned server {origin} for room ID {}. Rejecting.",
body.room_id
);
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
if let Some(via) = &body.via {
if via.is_empty() {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "via field must not be empty."));
}
}
let mut signed_event = utils::to_canonical_object(&body.event)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invite event is invalid."))?;
let invited_user: OwnedUserId = serde_json::from_value(
signed_event
.get("state_key")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event has no state_key property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "state_key is not a user ID."))?;
if !server_is_ours(invited_user.server_name()) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"User does not belong to this homeserver.",
));
}
// Make sure we're not ACL'ed from their room.
services()
.rooms
.event_handler
.acl_check(invited_user.server_name(), &body.room_id)?;
ruma::signatures::hash_and_sign_event(
services().globals.server_name().as_str(),
services().globals.keypair(),
&mut signed_event,
&body.room_version,
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Failed to sign event."))?;
// Generate event id
let event_id = EventId::parse(format!(
"${}",
ruma::signatures::reference_hash(&signed_event, &body.room_version)
.expect("ruma can calculate reference hashes")
))
.expect("ruma's reference hashes are valid event ids");
// Add event_id back
signed_event.insert("event_id".to_owned(), CanonicalJsonValue::String(event_id.to_string()));
let sender: OwnedUserId = serde_json::from_value(
signed_event
.get("sender")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event had no sender property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "sender is not a user ID."))?;
if services().rooms.metadata.is_banned(&body.room_id)? && !services().users.is_admin(&invited_user)? {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"This room is banned on this homeserver.",
));
}
if services().globals.block_non_admin_invites() && !services().users.is_admin(&invited_user)? {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"This server does not allow room invites.",
));
}
let mut invite_state = body.invite_room_state.clone();
let mut event: JsonObject = serde_json::from_str(body.event.get())
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid invite event bytes."))?;
event.insert("event_id".to_owned(), "$placeholder".into());
let pdu: PduEvent = serde_json::from_value(event.into())
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid invite event."))?;
invite_state.push(pdu.to_stripped_state_event());
// If we are active in the room, the remote server will notify us about the join
// via /send
if !services()
.rooms
.state_cache
.server_in_room(services().globals.server_name(), &body.room_id)?
{
services().rooms.state_cache.update_membership(
&body.room_id,
&invited_user,
RoomMemberEventContent::new(MembershipState::Invite),
&sender,
Some(invite_state),
body.via.clone(),
true,
)?;
}
Ok(create_invite::v2::Response {
event: PduEvent::convert_to_outgoing_federation_event(signed_event),
})
}

76
src/api/server/key.rs Normal file
View File

@@ -0,0 +1,76 @@
use std::{
collections::BTreeMap,
time::{Duration, SystemTime},
};
use axum::{response::IntoResponse, Json};
use ruma::{
api::{
federation::discovery::{get_server_keys, ServerSigningKeys, VerifyKey},
OutgoingResponse,
},
serde::{Base64, Raw},
MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId,
};
use crate::{services, Result};
/// # `GET /_matrix/key/v2/server`
///
/// Gets the public signing keys of this server.
///
/// - Matrix does not support invalidating public keys, so the key returned by
/// this will be valid
/// forever.
// Response type for this endpoint is Json because we need to calculate a
// signature for the response
pub(crate) async fn get_server_keys_route() -> Result<impl IntoResponse> {
let verify_keys: BTreeMap<OwnedServerSigningKeyId, VerifyKey> = BTreeMap::from([(
format!("ed25519:{}", services().globals.keypair().version())
.try_into()
.expect("found invalid server signing keys in DB"),
VerifyKey {
key: Base64::new(services().globals.keypair().public_key().to_vec()),
},
)]);
let mut response = serde_json::from_slice(
get_server_keys::v2::Response {
server_key: Raw::new(&ServerSigningKeys {
server_name: services().globals.server_name().to_owned(),
verify_keys,
old_verify_keys: BTreeMap::new(),
signatures: BTreeMap::new(),
valid_until_ts: MilliSecondsSinceUnixEpoch::from_system_time(
SystemTime::now()
.checked_add(Duration::from_secs(86400 * 7))
.expect("valid_until_ts should not get this high"),
)
.expect("time is valid"),
})
.expect("static conversion, no errors"),
}
.try_into_http_response::<Vec<u8>>()
.unwrap()
.body(),
)
.unwrap();
ruma::signatures::sign_json(
services().globals.server_name().as_str(),
services().globals.keypair(),
&mut response,
)
.unwrap();
Ok(Json(response))
}
/// # `GET /_matrix/key/v2/server/{keyId}`
///
/// Gets the public signing keys of this server.
///
/// - Matrix does not support invalidating public keys, so the key returned by
/// this will be valid
/// forever.
pub(crate) async fn get_server_keys_deprecated_route() -> impl IntoResponse { get_server_keys_route().await }

241
src/api/server/make_join.rs Normal file
View File

@@ -0,0 +1,241 @@
use std::sync::Arc;
use ruma::{
api::{client::error::ErrorKind, federation::membership::prepare_join_event},
events::{
room::{
join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent},
},
StateEventType, TimelineEventType,
},
RoomVersionId,
};
use serde_json::value::to_raw_value;
use tracing::warn;
use crate::{
service::{pdu::PduBuilder, user_is_local},
services, Error, Result, Ruma,
};
/// # `GET /_matrix/federation/v1/make_join/{roomId}/{userId}`
///
/// Creates a join template.
pub(crate) async fn create_join_event_template_route(
body: Ruma<prepare_join_event::v1::Request>,
) -> Result<prepare_join_event::v1::Response> {
if !services().rooms.metadata.exists(&body.room_id)? {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
}
let origin = body.origin.as_ref().expect("server is authenticated");
if body.user_id.server_name() != origin {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to join on behalf of another server/user",
));
}
// ACL check origin server
services()
.rooms
.event_handler
.acl_check(origin, &body.room_id)?;
if services()
.globals
.config
.forbidden_remote_server_names
.contains(origin)
{
warn!(
"Server {origin} for remote user {} tried joining room ID {} which has a server name that is globally \
forbidden. Rejecting.",
&body.user_id, &body.room_id,
);
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
if let Some(server) = body.room_id.server_name() {
if services()
.globals
.config
.forbidden_remote_server_names
.contains(&server.to_owned())
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let join_rules_event =
services()
.rooms
.state_accessor
.room_state_get(&body.room_id, &StateEventType::RoomJoinRules, "")?;
let join_rules_event_content: Option<RoomJoinRulesEventContent> = join_rules_event
.as_ref()
.map(|join_rules_event| {
serde_json::from_str(join_rules_event.content.get())
.map_err(|_| Error::bad_database("Invalid join rules event in db."))
})
.transpose()?;
let join_authorized_via_users_server = if let Some(join_rules_event_content) = join_rules_event_content {
if let JoinRule::Restricted(r) | JoinRule::KnockRestricted(r) = join_rules_event_content.join_rule {
if r.allow
.iter()
.filter_map(|rule| {
if let AllowRule::RoomMembership(membership) = rule {
Some(membership)
} else {
None
}
})
.any(|m| {
services()
.rooms
.state_cache
.is_joined(&body.user_id, &m.room_id)
.unwrap_or(false)
}) {
if services()
.rooms
.state_cache
.is_left(&body.user_id, &body.room_id)
.unwrap_or(true)
{
let members: Vec<_> = services()
.rooms
.state_cache
.room_members(&body.room_id)
.filter_map(Result::ok)
.filter(|user| user_is_local(user))
.collect();
let mut auth_user = None;
for user in members {
if services()
.rooms
.state_accessor
.user_can_invite(&body.room_id, &user, &body.user_id, &state_lock)
.await
.unwrap_or(false)
{
auth_user = Some(user);
break;
}
}
if auth_user.is_some() {
auth_user
} else {
return Err(Error::BadRequest(
ErrorKind::UnableToGrantJoin,
"No user on this server is able to assist in joining.",
));
}
} else {
// If the user has any state other than leave, either:
// - the auth_check will deny them (ban, knock - (until/unless MSC4123 is
// merged))
// - they are able to join via other methods (invite)
// - they are already in the room (join)
None
}
} else {
return Err(Error::BadRequest(
ErrorKind::UnableToAuthorizeJoin,
"User is not known to be in any required room.",
));
}
} else {
None
}
} else {
None
};
let room_version_id = services().rooms.state.get_room_version(&body.room_id)?;
if !body.ver.contains(&room_version_id) {
return Err(Error::BadRequest(
ErrorKind::IncompatibleRoomVersion {
room_version: room_version_id,
},
"Room version not supported.",
));
}
let content = to_raw_value(&RoomMemberEventContent {
avatar_url: None,
blurhash: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
reason: None,
join_authorized_via_users_server,
})
.expect("member event is valid value");
let (_pdu, mut pdu_json) = services().rooms.timeline.create_hash_and_sign_event(
PduBuilder {
event_type: TimelineEventType::RoomMember,
content,
unsigned: None,
state_key: Some(body.user_id.to_string()),
redacts: None,
},
&body.user_id,
&body.room_id,
&state_lock,
)?;
drop(state_lock);
// room v3 and above removed the "event_id" field from remote PDU format
match room_version_id {
RoomVersionId::V1 | RoomVersionId::V2 => {},
RoomVersionId::V3
| RoomVersionId::V4
| RoomVersionId::V5
| RoomVersionId::V6
| RoomVersionId::V7
| RoomVersionId::V8
| RoomVersionId::V9
| RoomVersionId::V10
| RoomVersionId::V11 => {
pdu_json.remove("event_id");
},
_ => {
warn!("Unexpected or unsupported room version {room_version_id}");
return Err(Error::BadRequest(
ErrorKind::BadJson,
"Unexpected or unsupported room version found",
));
},
};
Ok(prepare_join_event::v1::Response {
room_version: Some(room_version_id),
event: to_raw_value(&pdu_json).expect("CanonicalJson can be serialized to JSON"),
})
}

View File

@@ -0,0 +1,105 @@
use std::sync::Arc;
use ruma::{
api::{client::error::ErrorKind, federation::membership::prepare_leave_event},
events::{
room::member::{MembershipState, RoomMemberEventContent},
TimelineEventType,
},
RoomVersionId,
};
use serde_json::value::to_raw_value;
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma};
/// # `PUT /_matrix/federation/v1/make_leave/{roomId}/{eventId}`
///
/// Creates a leave template.
pub(crate) async fn create_leave_event_template_route(
body: Ruma<prepare_leave_event::v1::Request>,
) -> Result<prepare_leave_event::v1::Response> {
if !services().rooms.metadata.exists(&body.room_id)? {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
}
let origin = body.origin.as_ref().expect("server is authenticated");
if body.user_id.server_name() != origin {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to leave on behalf of another server/user",
));
}
// ACL check origin
services()
.rooms
.event_handler
.acl_check(origin, &body.room_id)?;
let room_version_id = services().rooms.state.get_room_version(&body.room_id)?;
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let content = to_raw_value(&RoomMemberEventContent {
avatar_url: None,
blurhash: None,
displayname: None,
is_direct: None,
membership: MembershipState::Leave,
third_party_invite: None,
reason: None,
join_authorized_via_users_server: None,
})
.expect("member event is valid value");
let (_pdu, mut pdu_json) = services().rooms.timeline.create_hash_and_sign_event(
PduBuilder {
event_type: TimelineEventType::RoomMember,
content,
unsigned: None,
state_key: Some(body.user_id.to_string()),
redacts: None,
},
&body.user_id,
&body.room_id,
&state_lock,
)?;
drop(state_lock);
// room v3 and above removed the "event_id" field from remote PDU format
match room_version_id {
RoomVersionId::V1 | RoomVersionId::V2 => {},
RoomVersionId::V3
| RoomVersionId::V4
| RoomVersionId::V5
| RoomVersionId::V6
| RoomVersionId::V7
| RoomVersionId::V8
| RoomVersionId::V9
| RoomVersionId::V10
| RoomVersionId::V11 => {
pdu_json.remove("event_id");
},
_ => {
return Err(Error::BadRequest(
ErrorKind::BadJson,
"Unexpected or unsupported room version found",
));
},
};
Ok(prepare_leave_event::v1::Response {
room_version: Some(room_version_id),
event: to_raw_value(&pdu_json).expect("CanonicalJson can be serialized to JSON"),
})
}

39
src/api/server/mod.rs Normal file
View File

@@ -0,0 +1,39 @@
pub(super) mod backfill;
pub(super) mod event;
pub(super) mod event_auth;
pub(super) mod get_missing_events;
pub(super) mod hierarchy;
pub(super) mod invite;
pub(super) mod key;
pub(super) mod make_join;
pub(super) mod make_leave;
pub(super) mod publicrooms;
pub(super) mod query;
pub(super) mod send;
pub(super) mod send_join;
pub(super) mod send_leave;
pub(super) mod state;
pub(super) mod state_ids;
pub(super) mod user;
pub(super) mod version;
pub(super) mod well_known;
pub(super) use backfill::*;
pub(super) use event::*;
pub(super) use event_auth::*;
pub(super) use get_missing_events::*;
pub(super) use hierarchy::*;
pub(super) use invite::*;
pub(super) use key::*;
pub(super) use make_join::*;
pub(super) use make_leave::*;
pub(super) use publicrooms::*;
pub(super) use query::*;
pub(super) use send::*;
pub(super) use send_join::*;
pub(super) use send_leave::*;
pub(super) use state::*;
pub(super) use state_ids::*;
pub(super) use user::*;
pub(super) use version::*;
pub(super) use well_known::*;

View File

@@ -0,0 +1,74 @@
use axum_client_ip::InsecureClientIp;
use ruma::{
api::{
client::error::ErrorKind,
federation::directory::{get_public_rooms, get_public_rooms_filtered},
},
directory::Filter,
};
use crate::{services, Error, Result, Ruma};
/// # `POST /_matrix/federation/v1/publicRooms`
///
/// Lists the public rooms on this server.
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn get_public_rooms_filtered_route(
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<get_public_rooms_filtered::v1::Request>,
) -> Result<get_public_rooms_filtered::v1::Response> {
if !services()
.globals
.allow_public_room_directory_over_federation()
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room directory is not public"));
}
let response = crate::client::get_public_rooms_filtered_helper(
None,
body.limit,
body.since.as_deref(),
&body.filter,
&body.room_network,
)
.await
.map_err(|_| Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list."))?;
Ok(get_public_rooms_filtered::v1::Response {
chunk: response.chunk,
prev_batch: response.prev_batch,
next_batch: response.next_batch,
total_room_count_estimate: response.total_room_count_estimate,
})
}
/// # `GET /_matrix/federation/v1/publicRooms`
///
/// Lists the public rooms on this server.
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn get_public_rooms_route(
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<get_public_rooms::v1::Request>,
) -> Result<get_public_rooms::v1::Response> {
if !services()
.globals
.allow_public_room_directory_over_federation()
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room directory is not public"));
}
let response = crate::client::get_public_rooms_filtered_helper(
None,
body.limit,
body.since.as_deref(),
&Filter::default(),
&body.room_network,
)
.await
.map_err(|_| Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list."))?;
Ok(get_public_rooms::v1::Response {
chunk: response.chunk,
prev_batch: response.prev_batch,
next_batch: response.next_batch,
total_room_count_estimate: response.total_room_count_estimate,
})
}

102
src/api/server/query.rs Normal file
View File

@@ -0,0 +1,102 @@
use get_profile_information::v1::ProfileField;
use rand::seq::SliceRandom;
use ruma::{
api::{
client::error::ErrorKind,
federation::query::{get_profile_information, get_room_information},
},
OwnedServerName,
};
use crate::{service::server_is_ours, services, Error, Result, Ruma};
/// # `GET /_matrix/federation/v1/query/directory`
///
/// Resolve a room alias to a room id.
pub(crate) async fn get_room_information_route(
body: Ruma<get_room_information::v1::Request>,
) -> Result<get_room_information::v1::Response> {
let room_id = services()
.rooms
.alias
.resolve_local_alias(&body.room_alias)?
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Room alias not found."))?;
let mut servers: Vec<OwnedServerName> = services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(Result::ok)
.collect();
servers.sort_unstable();
servers.dedup();
servers.shuffle(&mut rand::thread_rng());
// insert our server as the very first choice if in list
if let Some(server_index) = servers
.iter()
.position(|server| server == services().globals.server_name())
{
servers.swap_remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
}
Ok(get_room_information::v1::Response {
room_id,
servers,
})
}
/// # `GET /_matrix/federation/v1/query/profile`
///
///
/// Gets information on a profile.
pub(crate) async fn get_profile_information_route(
body: Ruma<get_profile_information::v1::Request>,
) -> Result<get_profile_information::v1::Response> {
if !services()
.globals
.allow_profile_lookup_federation_requests()
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Profile lookup over federation is not allowed on this homeserver.",
));
}
if !server_is_ours(body.user_id.server_name()) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"User does not belong to this server.",
));
}
let mut displayname = None;
let mut avatar_url = None;
let mut blurhash = None;
match &body.field {
Some(ProfileField::DisplayName) => {
displayname = services().users.displayname(&body.user_id)?;
},
Some(ProfileField::AvatarUrl) => {
avatar_url = services().users.avatar_url(&body.user_id)?;
blurhash = services().users.blurhash(&body.user_id)?;
},
// TODO: what to do with custom
Some(_) => {},
None => {
displayname = services().users.displayname(&body.user_id)?;
avatar_url = services().users.avatar_url(&body.user_id)?;
blurhash = services().users.blurhash(&body.user_id)?;
},
}
Ok(get_profile_information::v1::Response {
displayname,
avatar_url,
blurhash,
})
}

381
src/api/server/send.rs Normal file
View File

@@ -0,0 +1,381 @@
use std::{collections::BTreeMap, sync::Arc, time::Instant};
use axum_client_ip::InsecureClientIp;
use conduit::debug_warn;
use ruma::{
api::{
client::error::ErrorKind,
federation::transactions::{
edu::{DeviceListUpdateContent, DirectDeviceContent, Edu, SigningKeyUpdateContent},
send_transaction_message,
},
},
events::receipt::{ReceiptEvent, ReceiptEventContent, ReceiptType},
to_device::DeviceIdOrAllDevices,
};
use tokio::sync::RwLock;
use tracing::{debug, error, trace, warn};
use crate::{
service::rooms::event_handler::parse_incoming_pdu,
services,
utils::{self},
Error, Result, Ruma,
};
/// # `PUT /_matrix/federation/v1/send/{txnId}`
///
/// Push EDUs and PDUs to this server.
#[tracing::instrument(skip_all, fields(%client_ip))]
pub(crate) async fn send_transaction_message_route(
InsecureClientIp(client_ip): InsecureClientIp, body: Ruma<send_transaction_message::v1::Request>,
) -> Result<send_transaction_message::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
if *origin != body.body.origin {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Not allowed to send transactions on behalf of other servers",
));
}
if body.pdus.len() > 50_usize {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Not allowed to send more than 50 PDUs in one transaction",
));
}
if body.edus.len() > 100_usize {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Not allowed to send more than 100 EDUs in one transaction",
));
}
// This is all the auth_events that have been recursively fetched so they don't
// have to be deserialized over and over again.
// TODO: make this persist across requests but not in a DB Tree (in globals?)
// TODO: This could potentially also be some sort of trie (suffix tree) like
// structure so that once an auth event is known it would know (using indexes
// maybe) all of the auth events that it references.
// let mut auth_cache = EventMap::new();
let txn_start_time = Instant::now();
let mut parsed_pdus = Vec::with_capacity(body.pdus.len());
for pdu in &body.pdus {
parsed_pdus.push(match parse_incoming_pdu(pdu) {
Ok(t) => t,
Err(e) => {
debug_warn!("Could not parse PDU: {e}");
continue;
},
});
// We do not add the event_id field to the pdu here because of signature
// and hashes checks
}
trace!(
pdus = ?parsed_pdus.len(),
edus = ?body.edus.len(),
elapsed = ?txn_start_time.elapsed(),
id = ?body.transaction_id,
origin =?body.origin,
"Starting txn",
);
// We go through all the signatures we see on the PDUs and fetch the
// corresponding signing keys
let pub_key_map = RwLock::new(BTreeMap::new());
if !parsed_pdus.is_empty() {
services()
.rooms
.event_handler
.fetch_required_signing_keys(parsed_pdus.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
.await
.unwrap_or_else(|e| {
warn!("Could not fetch all signatures for PDUs from {origin}: {:?}", e);
});
debug!(
elapsed = ?txn_start_time.elapsed(),
"Fetched signing keys"
);
}
let mut resolved_map = BTreeMap::new();
for (event_id, value, room_id) in parsed_pdus {
let pdu_start_time = Instant::now();
let mutex = Arc::clone(
services()
.globals
.roomid_mutex_federation
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let mutex_lock = mutex.lock().await;
resolved_map.insert(
event_id.clone(),
services()
.rooms
.event_handler
.handle_incoming_pdu(origin, &room_id, &event_id, value, true, &pub_key_map)
.await
.map(|_| ()),
);
drop(mutex_lock);
debug!(
pdu_elapsed = ?pdu_start_time.elapsed(),
txn_elapsed = ?txn_start_time.elapsed(),
"Finished PDU {event_id}",
);
}
for pdu in &resolved_map {
if let Err(e) = pdu.1 {
if matches!(e, Error::BadRequest(ErrorKind::NotFound, _)) {
warn!("Incoming PDU failed {:?}", pdu);
}
}
}
for edu in body
.edus
.iter()
.filter_map(|edu| serde_json::from_str::<Edu>(edu.json().get()).ok())
{
match edu {
Edu::Presence(presence) => {
if !services().globals.allow_incoming_presence() {
continue;
}
for update in presence.push {
if update.user_id.server_name() != origin {
debug_warn!(%update.user_id, %origin, "received presence EDU for user not belonging to origin");
continue;
}
services().presence.set_presence(
&update.user_id,
&update.presence,
Some(update.currently_active),
Some(update.last_active_ago),
update.status_msg.clone(),
)?;
}
},
Edu::Receipt(receipt) => {
if !services().globals.allow_incoming_read_receipts() {
continue;
}
for (room_id, room_updates) in receipt.receipts {
if services()
.rooms
.event_handler
.acl_check(origin, &room_id)
.is_err()
{
debug_warn!(%origin, %room_id, "received read receipt EDU from ACL'd server");
continue;
}
for (user_id, user_updates) in room_updates.read {
if user_id.server_name() != origin {
debug_warn!(%user_id, %origin, "received read receipt EDU for user not belonging to origin");
continue;
}
if services()
.rooms
.state_cache
.room_members(&room_id)
.filter_map(Result::ok)
.any(|member| member.server_name() == user_id.server_name())
{
for event_id in &user_updates.event_ids {
let user_receipts = BTreeMap::from([(user_id.clone(), user_updates.data.clone())]);
let receipts = BTreeMap::from([(ReceiptType::Read, user_receipts)]);
let receipt_content = BTreeMap::from([(event_id.to_owned(), receipts)]);
let event = ReceiptEvent {
content: ReceiptEventContent(receipt_content),
room_id: room_id.clone(),
};
services()
.rooms
.read_receipt
.readreceipt_update(&user_id, &room_id, event)?;
}
} else {
debug_warn!(%user_id, %room_id, %origin, "received read receipt EDU from server who does not have a single member from their server in the room");
continue;
}
}
}
},
Edu::Typing(typing) => {
if !services().globals.config.allow_incoming_typing {
continue;
}
if typing.user_id.server_name() != origin {
debug_warn!(%typing.user_id, %origin, "received typing EDU for user not belonging to origin");
continue;
}
if services()
.rooms
.event_handler
.acl_check(typing.user_id.server_name(), &typing.room_id)
.is_err()
{
debug_warn!(%typing.user_id, %typing.room_id, %origin, "received typing EDU for ACL'd user's server");
continue;
}
if services()
.rooms
.state_cache
.is_joined(&typing.user_id, &typing.room_id)?
{
if typing.typing {
let timeout = utils::millis_since_unix_epoch().saturating_add(
services()
.globals
.config
.typing_federation_timeout_s
.saturating_mul(1000),
);
services()
.rooms
.typing
.typing_add(&typing.user_id, &typing.room_id, timeout)
.await?;
} else {
services()
.rooms
.typing
.typing_remove(&typing.user_id, &typing.room_id)
.await?;
}
} else {
debug_warn!(%typing.user_id, %typing.room_id, %origin, "received typing EDU for user not in room");
continue;
}
},
Edu::DeviceListUpdate(DeviceListUpdateContent {
user_id,
..
}) => {
if user_id.server_name() != origin {
debug_warn!(%user_id, %origin, "received device list update EDU for user not belonging to origin");
continue;
}
services().users.mark_device_key_update(&user_id)?;
},
Edu::DirectToDevice(DirectDeviceContent {
sender,
ev_type,
message_id,
messages,
}) => {
if sender.server_name() != origin {
debug_warn!(%sender, %origin, "received direct to device EDU for user not belonging to origin");
continue;
}
// Check if this is a new transaction id
if services()
.transaction_ids
.existing_txnid(&sender, None, &message_id)?
.is_some()
{
continue;
}
for (target_user_id, map) in &messages {
for (target_device_id_maybe, event) in map {
match target_device_id_maybe {
DeviceIdOrAllDevices::DeviceId(target_device_id) => {
services().users.add_to_device_event(
&sender,
target_user_id,
target_device_id,
&ev_type.to_string(),
event.deserialize_as().map_err(|e| {
error!("To-Device event is invalid: {event:?} {e}");
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
})?,
)?;
},
DeviceIdOrAllDevices::AllDevices => {
for target_device_id in services().users.all_device_ids(target_user_id) {
services().users.add_to_device_event(
&sender,
target_user_id,
&target_device_id?,
&ev_type.to_string(),
event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
})?,
)?;
}
},
}
}
}
// Save transaction id with empty data
services()
.transaction_ids
.add_txnid(&sender, None, &message_id, &[])?;
},
Edu::SigningKeyUpdate(SigningKeyUpdateContent {
user_id,
master_key,
self_signing_key,
}) => {
if user_id.server_name() != origin {
debug_warn!(%user_id, %origin, "received signing key update EDU from server that does not belong to user's server");
continue;
}
if let Some(master_key) = master_key {
services()
.users
.add_cross_signing_keys(&user_id, &master_key, &self_signing_key, &None, true)?;
}
},
Edu::_Custom(custom) => {
debug_warn!(?custom, "received custom/unknown EDU");
},
}
}
debug!(
pdus = ?body.pdus.len(),
edus = ?body.edus.len(),
elapsed = ?txn_start_time.elapsed(),
id = ?body.transaction_id,
origin =?body.origin,
"Finished txn",
);
Ok(send_transaction_message::v1::Response {
pdus: resolved_map
.into_iter()
.map(|(e, r)| (e, r.map_err(|e| e.sanitized_error())))
.collect(),
})
}

300
src/api/server/send_join.rs Normal file
View File

@@ -0,0 +1,300 @@
#![allow(deprecated)]
use std::{collections::BTreeMap, sync::Arc};
use ruma::{
api::{client::error::ErrorKind, federation::membership::create_join_event},
events::{room::member::MembershipState, StateEventType},
CanonicalJsonValue, OwnedServerName, OwnedUserId, RoomId, ServerName,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use tokio::sync::RwLock;
use tracing::warn;
use crate::{service::pdu::gen_event_id_canonical_json, services, Error, PduEvent, Result, Ruma};
/// helper method for /send_join v1 and v2
async fn create_join_event(
origin: &ServerName, room_id: &RoomId, pdu: &RawJsonValue,
) -> Result<create_join_event::v1::RoomState> {
if !services().rooms.metadata.exists(room_id)? {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
}
// ACL check origin server
services().rooms.event_handler.acl_check(origin, room_id)?;
// We need to return the state prior to joining, let's keep a reference to that
// here
let shortstatehash = services()
.rooms
.state
.get_room_shortstatehash(room_id)?
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Event state not found."))?;
let pub_key_map = RwLock::new(BTreeMap::new());
// let mut auth_cache = EventMap::new();
// We do not add the event_id field to the pdu here because of signature and
// hashes checks
let room_version_id = services().rooms.state.get_room_version(room_id)?;
let Ok((event_id, mut value)) = gen_event_id_canonical_json(pdu, &room_version_id) else {
// Event could not be converted to canonical json
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Could not convert event to canonical json.",
));
};
let event_type: StateEventType = serde_json::from_value(
value
.get("type")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing type property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Event has invalid event type."))?;
if event_type != StateEventType::RoomMember {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to send non-membership state event to join endpoint.",
));
}
let content = value
.get("content")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing content property."))?
.as_object()
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event content is empty or invalid."))?;
let membership: MembershipState = serde_json::from_value(
content
.get("membership")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event content missing membership property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Event has an invalid membership state."))?;
if membership != MembershipState::Join {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to send a non-join membership event to join endpoint.",
));
}
// ACL check sender server name
let sender: OwnedUserId = serde_json::from_value(
value
.get("sender")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing sender property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "sender is not a valid user ID."))?;
services()
.rooms
.event_handler
.acl_check(sender.server_name(), room_id)?;
// check if origin server is trying to send for another server
if sender.server_name() != origin {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to join on behalf of another server.",
));
}
let state_key: OwnedUserId = serde_json::from_value(
value
.get("state_key")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing state_key property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "state_key is invalid or not a user ID."))?;
if state_key != sender {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"State key does not match sender user",
));
}
ruma::signatures::hash_and_sign_event(
services().globals.server_name().as_str(),
services().globals.keypair(),
&mut value,
&room_version_id,
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Failed to sign event."))?;
let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(
value
.get("origin")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing origin property."))?,
)
.expect("CanonicalJson is valid json value"),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "origin is not a server name."))?;
services()
.rooms
.event_handler
.fetch_required_signing_keys([&value], &pub_key_map)
.await?;
let mutex = Arc::clone(
services()
.globals
.roomid_mutex_federation
.write()
.await
.entry(room_id.to_owned())
.or_default(),
);
let mutex_lock = mutex.lock().await;
let pdu_id: Vec<u8> = services()
.rooms
.event_handler
.handle_incoming_pdu(&origin, room_id, &event_id, value.clone(), true, &pub_key_map)
.await?
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Could not accept as timeline event."))?;
drop(mutex_lock);
let state_ids = services()
.rooms
.state_accessor
.state_full_ids(shortstatehash)
.await?;
let auth_chain_ids = services()
.rooms
.auth_chain
.event_ids_iter(room_id, state_ids.values().cloned().collect())
.await?;
services().sending.send_pdu_room(room_id, &pdu_id)?;
Ok(create_join_event::v1::RoomState {
auth_chain: auth_chain_ids
.filter_map(|id| services().rooms.timeline.get_pdu_json(&id).ok().flatten())
.map(PduEvent::convert_to_outgoing_federation_event)
.collect(),
state: state_ids
.iter()
.filter_map(|(_, id)| services().rooms.timeline.get_pdu_json(id).ok().flatten())
.map(PduEvent::convert_to_outgoing_federation_event)
.collect(),
// Event field is required if the room version supports restricted join rules.
event: Some(
to_raw_value(&CanonicalJsonValue::Object(value.clone()))
.expect("To raw json should not fail since only change was adding signature"),
),
})
}
/// # `PUT /_matrix/federation/v1/send_join/{roomId}/{eventId}`
///
/// Submits a signed join event.
pub(crate) async fn create_join_event_v1_route(
body: Ruma<create_join_event::v1::Request>,
) -> Result<create_join_event::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
if services()
.globals
.config
.forbidden_remote_server_names
.contains(origin)
{
warn!(
"Server {origin} tried joining room ID {} who has a server name that is globally forbidden. Rejecting.",
&body.room_id,
);
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
if let Some(server) = body.room_id.server_name() {
if services()
.globals
.config
.forbidden_remote_server_names
.contains(&server.to_owned())
{
warn!(
"Server {origin} tried joining room ID {} which has a server name that is globally forbidden. \
Rejecting.",
&body.room_id,
);
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
let room_state = create_join_event(origin, &body.room_id, &body.pdu).await?;
Ok(create_join_event::v1::Response {
room_state,
})
}
/// # `PUT /_matrix/federation/v2/send_join/{roomId}/{eventId}`
///
/// Submits a signed join event.
pub(crate) async fn create_join_event_v2_route(
body: Ruma<create_join_event::v2::Request>,
) -> Result<create_join_event::v2::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
if services()
.globals
.config
.forbidden_remote_server_names
.contains(origin)
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
if let Some(server) = body.room_id.server_name() {
if services()
.globals
.config
.forbidden_remote_server_names
.contains(&server.to_owned())
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
let create_join_event::v1::RoomState {
auth_chain,
state,
event,
} = create_join_event(origin, &body.room_id, &body.pdu).await?;
let room_state = create_join_event::v2::RoomState {
members_omitted: false,
auth_chain,
state,
event,
servers_in_room: None,
};
Ok(create_join_event::v2::Response {
room_state,
})
}

View File

@@ -0,0 +1,186 @@
#![allow(deprecated)]
use std::{collections::BTreeMap, sync::Arc};
use ruma::{
api::{client::error::ErrorKind, federation::membership::create_leave_event},
events::{room::member::MembershipState, StateEventType},
OwnedServerName, OwnedUserId, RoomId, ServerName,
};
use serde_json::value::RawValue as RawJsonValue;
use tokio::sync::RwLock;
use crate::{
service::{pdu::gen_event_id_canonical_json, server_is_ours},
services, Error, Result, Ruma,
};
/// # `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}`
///
/// Submits a signed leave event.
pub(crate) async fn create_leave_event_v1_route(
body: Ruma<create_leave_event::v1::Request>,
) -> Result<create_leave_event::v1::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
create_leave_event(origin, &body.room_id, &body.pdu).await?;
Ok(create_leave_event::v1::Response::new())
}
/// # `PUT /_matrix/federation/v2/send_leave/{roomId}/{eventId}`
///
/// Submits a signed leave event.
pub(crate) async fn create_leave_event_v2_route(
body: Ruma<create_leave_event::v2::Request>,
) -> Result<create_leave_event::v2::Response> {
let origin = body.origin.as_ref().expect("server is authenticated");
create_leave_event(origin, &body.room_id, &body.pdu).await?;
Ok(create_leave_event::v2::Response::new())
}
async fn create_leave_event(origin: &ServerName, room_id: &RoomId, pdu: &RawJsonValue) -> Result<()> {
if !services().rooms.metadata.exists(room_id)? {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
}
// ACL check origin
services().rooms.event_handler.acl_check(origin, room_id)?;
let pub_key_map = RwLock::new(BTreeMap::new());
// We do not add the event_id field to the pdu here because of signature and
// hashes checks
let room_version_id = services().rooms.state.get_room_version(room_id)?;
let Ok((event_id, value)) = gen_event_id_canonical_json(pdu, &room_version_id) else {
// Event could not be converted to canonical json
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Could not convert event to canonical json.",
));
};
let content = value
.get("content")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing content property."))?
.as_object()
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event content not an object."))?;
let membership: MembershipState = serde_json::from_value(
content
.get("membership")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event membership is missing."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Event membership state is not valid."))?;
if membership != MembershipState::Leave {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to send a non-leave membership event to leave endpoint.",
));
}
let event_type: StateEventType = serde_json::from_value(
value
.get("type")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing type property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Event does not have a valid state event type."))?;
if event_type != StateEventType::RoomMember {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to send non-membership state event to leave endpoint.",
));
}
// ACL check sender server name
let sender: OwnedUserId = serde_json::from_value(
value
.get("sender")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing sender property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "User ID in sender is invalid."))?;
services()
.rooms
.event_handler
.acl_check(sender.server_name(), room_id)?;
if sender.server_name() != origin {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to leave on behalf of another server.",
));
}
let state_key: OwnedUserId = serde_json::from_value(
value
.get("state_key")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing state_key property."))?
.clone()
.into(),
)
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "state_key is invalid or not a user ID"))?;
if state_key != sender {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"state_key does not match sender user.",
));
}
let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(
value
.get("origin")
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Event missing origin property."))?,
)
.expect("CanonicalJson is valid json value"),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "origin is not a server name."))?;
services()
.rooms
.event_handler
.fetch_required_signing_keys([&value], &pub_key_map)
.await?;
let mutex = Arc::clone(
services()
.globals
.roomid_mutex_federation
.write()
.await
.entry(room_id.to_owned())
.or_default(),
);
let mutex_lock = mutex.lock().await;
let pdu_id: Vec<u8> = services()
.rooms
.event_handler
.handle_incoming_pdu(&origin, room_id, &event_id, value, true, &pub_key_map)
.await?
.ok_or_else(|| Error::BadRequest(ErrorKind::InvalidParam, "Could not accept as timeline event."))?;
drop(mutex_lock);
let servers = services()
.rooms
.state_cache
.room_servers(room_id)
.filter_map(Result::ok)
.filter(|server| !server_is_ours(server));
services().sending.send_pdu_servers(servers, &pdu_id)?;
Ok(())
}

Some files were not shown because too many files have changed in this diff Show More