feat: Support acting as a notary server #2314
Labels
No labels
Abandoned
Blocked
Bug
Changelog
Added
Changelog
Missing
Changelog
None
Cherry-picking
Compliance
Database
Dependencies
Dependencies/Renovate
Difficulty
Easy
Difficulty
Hard
Difficulty
Medium
Documentation
Enhancement
Good first issue
Help wanted
Inherited
Matrix/Administration
Matrix/Appservices
Matrix/Auth
Matrix/Client
Matrix/Core
Matrix/E2EE
Matrix/Federation
Matrix/Hydra
Matrix/MSC
Matrix/Media
Matrix/T&S
Merge
Merge/Manual
Merge/Squash
Meta
Meta/CI
Meta/Packaging
Priority
Blocking
Priority
High
Priority
Low
Security
Status
Confirmed
Status
Duplicate
Status
Invalid
Status
Needs Investigation
Support
bob the builder
No assignees
4 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
continuwuation/continuwuity!2314
Loading…
Reference in a new issue
No description provided.
Delete branch "nex/feat/notary-server"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR implements
POST /_matrix/key/v2/queryandGET /_matrix/key/v2/query/{server_name}, allowing continuwuity to act as a key notary server, and finally a trusted server..Closes: #784, #1208
Pull request checklist:
mainbranch, and the branch is named something other thanmain.myself, if applicable. This includes ensuring code compiles.
@ -90,0 +103,4 @@State(services): State<crate::State>,body: Ruma<get_remote_server_keys_batch::v2::Request>,) -> Result<get_remote_server_keys_batch::v2::Response> {let total_queried_keys = bodyyou're gonna lose your mind when you learn about
BTreeMap::len()Yeah I will because you made me realise I'm calculating bullshit lmao. It's supposed to sum the length of each value map but instead it's just counting the length of the top level map. I can't believe I reimplemented len()
@ -90,0 +119,4 @@let mut response = Vec::with_capacity(total_queried_keys);for (server_name, queries) in &body.server_keys {if queries.is_empty() {there is a fair bit of logic duplicated between this
ifand the code after it@ -90,0 +151,4 @@else {continue;};if ssk.valid_until_ts < minimum_valid_until_ts || ssk.valid_until_ts > in_one_week() {you might as well fix !2312 while you're at it (maybe by having
in_one_week()be "in one week and one hour")Didn't see that issue, that's actually deliberate because otherwise the range check will always return true if someone returns keys that last forever, which defeats the purpose of the 7-day limit
I'm not sure I follow your logic, why isn't that possible with the current seven-day limit as opposed to a seven-day-and-one-hour limit?
If you query a key on 2026-01-01, and receive a response that expires at 2026-02-01, accepting that response will result in a cache hit against that response for every lookup until February. This means a request to the origin won't be made until Feb, meaning the origin can't revoke any keys that may have been maliciously injected, or leaked, etc. All that clamping would do is prevent someone then sending an event that was created on 2026-02-01, at 2026-01-02 (since the 1st of Feb is more than 7 days in the future as of the 2nd of Jan). Now imagine someone's web server was hacked and someone published a key response for a decade...
I don't know where this "plus one hour" is coming from, the spec very clearly states exactly 7 days
"plus one hour" allows for clock skew, basically. intentionally lightly imprecise definition of 7 days
But whose skew? That accounts for a +1 timezone offset, but there's more timezones with >+1. People should just have the right time?
A) the issue isn't timezones, that's not what clock skee is, but latency and clocks that are off by a second or two
B) that over-caching sounds like a bug to me, you can make it so that you only treat the key as valid for the clamped length and then recheck that it's still on the origin.
I can, but I'm not going to. It's not over-caching, it's working as intended: if there's a locally stored key that is in-date and valid, use that. I don't see why you'd do anything less?
(discussion out-of-band decided this is out of scope for this PR but Jade wants to tackle 2312 herself, so the issue was re-opened and assigned)
also you need a news fragment :3
feat: Support acting as a notary serverto WIP: feat: Support acting as a notary server80dd7d507169b4d6ffa4WIP: feat: Support acting as a notary serverto feat: Support acting as a notary server912880fb6a8cb173ad08@ -90,0 +137,4 @@// )));}if total_queried_keys > MAX_KEYS_PER_QUERY {// We shouldn't really enforce this before MSC4456 either, but not doingTypo (MSC4556)
@ -90,0 +203,4 @@// First contact the origin (if we're allowed to)if server_keys.notary_may_contact_origin(&remote) {debug_info!("Asking remote directly for verify keys");if let Ok(res) = server_keys.origin_request(remote.clone(), start).awaitSame here, i don't think this persists the keys
No check to avoid self-federation in these too I don't think
That check is in the federation execute layer*
*or it should be, ginger told me a few hours ago that it's suspiciously absent now
@ -90,0 +209,4 @@let index = results.len();results.push(ssk);for key_id in res.verify_keys.keys().chain(res.old_verify_keys.keys()) {if queries.is_empty()This changes during iteration, so the condition may change and cause additional keys to be returned
@ -90,0 +213,4 @@|| queries.get(key_id).and_then(|c| c.minimum_valid_until_ts).is_none_or(|m| res.valid_until_ts >= m)Did you mean something like
.and_then(|c| c.minimum_valid_until_ts.is_none_or(|m| res.valid_until_ts >= m))? Otherwise this will return keys that weren't queried forUhh probably? I think clippy complained when I did that though 🤔
@ -90,0 +322,4 @@.notary_may_contact_origin(&body.server_name)&& let Ok(response) = services.server_keys.origin_request(body.server_name.clone(), min_valid_ts)This doesn't persist the keys, right? Might that be an issue?
uhhh I guess storing the keys could be an optimisation, but it's not an issue otherwise afaik
@ -90,0 +242,4 @@}}).ready_for_each(|signed_ssk| {let ssk = signed_ssk.deserialize().unwrap();Can't you just yield the ssk in the broad_filter_map above in a tuple to avoid pointless work here?
I didn't want to because
sign_sskmoves ssk, but I suppose deserializing is probably more expensive than cloning@ -90,0 +332,4 @@services.globals.server_name(),).await.map(|r| Ok(get_remote_server_keys::v2::Response::new(vec![r])))?;.map(|r| get_remote_server_keys::v2::Response::new(vec![r]))?Has to return a
Result<get_remote_server_keys::v2::Response>so the wrap is necessary. I'll just rid of the mapHmm, actually that's visually worse
I'll keep the current chain
@ -90,0 +271,4 @@continue;};if ssk.valid_until_ts < minimum_valid_until_ts || ssk.valid_until_ts > in_one_week() {do you need to check
expired_tstoo? (and in other checks)@ -29,6 +34,7 @@ pub struct Service {verify_keys: VerifyKeys,services: Services,db: Data,last_lookup: SyncRwLock<HashMap<OwnedServerName, Instant>>,Woo! Unbounded growth! Not really a huge issue tho lol
Yeahh I'm not too sure how to get around that without a cleanup task (which just defines a time window for the unbounded growth). I think the map will hold small enough data that it won't really matter
@ -101,3 +101,3 @@};let mut canonical_object = to_canonical_object(notary_signatures)?;Self::strip_extraneous_signatures(&mut canonical_object, &server_keys.server_name, &[strip_extraneous_signatures(&mut canonical_object, &server_keys.server_name, &[This seems like dead code anyway
This is very much live code? what do you mean?
You're making and stripping a canonical object but then not using it for anything as far as I can read?
Oh yeah, you're right, it was meant to be passed to
to_canonical_json_string_for_signingbelowlook at jade's comments 👍she said most of the stuff I would've said
@ -90,0 +119,4 @@}let total_queried_servers = body.server_keys.len();let total_queried_keys = bodyHmm actually is this counting right? Might be overcounting
Deliberately so, if a request is
{"server_keys": {"servername.example": {}}}, we'll count zero total keys, but it's more likely that we'll end up fetching at least 1 key response, so I figured counting each server name in the total query count makes sense8cb173ad08ad9ca737b2ad9ca737b2adc0e5d3b858c5875013298113c0a6You have the wrong MSC in one of your commit messages I think. And tests are failing.
@ -28,0 +59,4 @@State(services): State<crate::State>,body: Ruma<get_remote_server_keys_batch::v2::Request>,) -> Result<get_remote_server_keys_batch::v2::Response> {query_inner(&services, &body.server_keys, false)false->true?@ -28,0 +99,7 @@// Count how many keys are being requested.// Each server incurs a cost of at least one, and then the count of each key// being queried per-server.let total_queried_servers = body.len();let total_queried_keys = body.values().fold(body.len(), |acc, q| acc.saturating_add(q.len()));Maybe
would be better? It'll be less of an overcount.
@ -28,0 +122,4 @@total_queried_servers > MAX_SERVERS_PER_QUERY || total_queried_keys > MAX_KEYS_PER_QUERY;debug_info!("Fetching {total_queried_keys} keys across {} servers", body.len());let mut futs: FuturesUnordered<_> = FuturesUnordered::new();Probably want something to limit concurrency here
futuresunordered is evil anyway, this really ought to be a
Vecof tokio tasks@ -83,0 +273,4 @@let minimum_valid_until_ts = criteria.clone().minimum_valid_until_ts.unwrap_or_else(|| MilliSecondsSinceUnixEpoch(uint!(0)));Doesn't this mean that the default could provide expired keys? But spec wants current time by default.
Perhaps:
@ -0,0 +23,4 @@rate_limited: true,authentication: ServerSignatures,history: {unstable("org.continuwuity.msc4553") => "/_matrix/key/unstable/org.continuwuity.msc4556/query",4556?@ -196,0 +260,4 @@// We need to verify that this response is still trusted based on// the current configuration. It's possible we got this response// from a notary who we no longer trust.if resp.valid_until_ts > in_one_week() || resp.valid_until_ts < now {Remind me to come back to this condition later.
@Jade this is your reminder 🗿
@ -100,13 +100,12 @@ impl super::Service {)));};let mut canonical_object = to_canonical_object(notary_signatures)?;Did you mean
let mut canonical_object = to_canonical_object(server_keys)?;(this is probably the cause of the test fail)
@ -0,0 +1,58 @@//! `POST /_matrix/key/*/query`I would endorse putting this in ruma, but it's fine here for now
I don't have time to upstream it unfortunately, it'd be a drive-by contribution if it were to be done at all, which wouldn't be nice :(
@ -0,0 +22,4 @@method: POST,rate_limited: true,authentication: ServerSignatures,history: {this should just be
path, federation API endpoints don't usehistory@ -196,0 +237,4 @@| None => self.discover_old_signing_keys().await,};let valid_until_ts = timepoint_from_now(VALID_UNTIL_TS_DURATION).map(|tp| {this could be
timepoint_from_now(...).ok().and_then(|tp| ...).expect(...)@ -150,3 +141,1 @@origin == server_name || notaries.iter().any(|ns| *ns == server_name)});Some(s)pub fn strip_extraneous_signatures(this could do with a docstring
tokio'sJoinSetinstead of the evilfuturesFuturesUnorder ed159f547e4c@ -54,0 +210,4 @@};let fetch_all = queries.is_empty();let mut results = Vec::with_capacity(queries.len().max(1));let mut keymap = HashMap::with_capacity(queries.len().max(1));as far as I can tell,
keymapis used for two purposes:I think you could clean this code up by:
keymapif fetch_all && keymap.is_empty()block to remove key IDs fromqueryas it gets them, like the "ask remote directly" logic already does. see also my other comment further downresultsmultiple times if necessary, instead of adding their indexes tokeymapmultiple times and then reading from those indexes at the end@ -77,2 +280,2 @@.map(|mut response| take(response.body_mut())).and_then(|body| serde_json::from_slice(&body).map_err(Into::into))?;// If we're still missing some keys, fetch them from the local cachefor (key_id, criteria) in queries {could this be in an
elseblock of theifabove it? as far as I can tell this code won't do anything if thatifruns, sincesigning_keys_forandget_signing_keyaccess the same database table.If it doesn't do anything after the
ifblock finishes execution then I don't think it needs to be in an else block 🤔sign_sskinto server_keys service c9f9f02590acquire_keys_as_notaryafc2a99a45acquire_keys_as_notary@ -223,0 +279,6 @@{key.expired_ts < minimum_valid_until_ts} else {// If the querying server didn't explicitly set a// minimum timestamp for an old verify key,// we should treat it as valid.mm no im pretty sure the spec says no min timestamp should default to the timestamp of the request
I'm copying the behavior from your own code, boss!
Yeah didn't I change that because Jade highlighted it to me?
not in the version you had me review
also like. think about that for a moment. if we check that the expiry timestamp of an old key is after the current time, we're going to reject every expired key. keys don't expire in the future!
hahahaha. seriously though you're right, fair enough
@ -285,3 +275,1 @@// minimum timestamp for an old verify key,// we should treat it as valid.false.filter_map(|(key_id, criterion)| {I don't think this properly applies queries to the keys they're supposed to apply to. it seems to allow any key that matches any query, and also never marks keys as seen that aren't listed in a query but still appear in a key response.
actually I think this change is just incorrect. the original purpose of the
signed_remote_key_idsmap was as an optimization, to let us skip including 100% redundant key chunks. since we either do or don't include every key in a chunk, the correct behavior is to always add every key tosigned_remote_key_idsif we decide to include a chunk, even ones that don't individually meet the criteria.I swear this code is cursed
Anyway the other big in the original code was it rejecting some historical keys it wasn't supposed to iirc.
yeah, that fix was fine. it's just this change that I think is wrong
I think you might be wrong? it only allows a key included in a chunk that newly satisfies a query criteria. I don't think it actually needs to mark keys that aren't listed, either, because they aren't... requested.
It's annoyingly hard to explain
matrix:roomid/c10y-8Hm3mAW99j9KEKoWPQH2M_FxGwG-EVHK06iLKg/e/vNEq0gDkcvc3FWLcAuEES72Md4MOMc0oLZROMN3XdXk?via=ellis.link&via=continuwuity.org&via=matrix.org
we hashed this out in a vc and decided that it's fine
473d456d8b6b0eebc553