1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use ;
use crate::;
/// The fields to remove from a JSON object when serializing it for signing.
pub static FIELDS_TO_REMOVE_FOR_SIGNING: & = &;
/// Hashes and signs an event and adds the hash and signature to objects under the keys `hashes` and
/// `signatures`, respectively.
///
/// If `hashes` and/or `signatures` are already present, the new data will be appended to the
/// existing data.
///
/// This is a convenience function that calls [`add_content_hash_to_event()`] then [`sign_event()`].
///
/// # Parameters
///
/// * `entity_id`: The identifier of the entity creating the signature. Generally this means a
/// homeserver, e.g. "example.com".
/// * `key_pair`: A cryptographic key pair used to sign the event.
/// * `object`: A JSON object to be hashed and signed according to the Matrix specification.
/// * `redaction_rules`: The redaction rules for the version of the event's room.
///
/// # Errors
///
/// Returns an error if:
///
/// * `object` contains a field called `content` that is not a JSON object.
/// * `object` contains a field called `hashes` that is not a JSON object.
/// * `object` contains a field called `signatures` that is not a JSON object.
/// * `object` is missing the `type` field or the field is not a JSON string.
///
/// # Examples
///
/// ```rust
/// # use ruma_common::{RoomVersionId, serde::base64::Base64};
/// # use ruma_signatures::{hash_and_sign_event, Ed25519KeyPair};
/// #
/// const PKCS8: &str = "\
/// MFECAQEwBQYDK2VwBCIEINjozvdfbsGEt6DD+7Uf4PiJ/YvTNXV2mIPc/\
/// tA0T+6tgSEA3TPraTczVkDPTRaX4K+AfUuyx7Mzq1UafTXypnl0t2k\
/// ";
///
/// let document: Base64 = Base64::parse(PKCS8).unwrap();
///
/// // Create an Ed25519 key pair.
/// let key_pair = Ed25519KeyPair::from_der(
/// document.as_bytes(),
/// "1".into(), // The "version" of the key.
/// )
/// .unwrap();
///
/// // Deserialize an event from JSON.
/// let mut object = serde_json::from_str(
/// r#"{
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "signatures": {},
/// "hashes": {},
/// "type": "X",
/// "content": {},
/// "prev_events": [],
/// "auth_events": [],
/// "depth": 3,
/// "unsigned": {
/// "age_ts": 1000000
/// }
/// }"#,
/// )
/// .unwrap();
///
/// // Get the rules for the version of the current room.
/// let rules =
/// RoomVersionId::V1.rules().expect("The rules should be known for a supported room version");
///
/// // Hash and sign the JSON with the key pair.
/// assert!(hash_and_sign_event("domain", &key_pair, &mut object, &rules.redaction).is_ok());
/// ```
///
/// This will modify the JSON from the structure shown to a structure like this:
///
/// ```json
/// {
/// "auth_events": [],
/// "content": {},
/// "depth": 3,
/// "hashes": {
/// "sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
/// },
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "prev_events": [],
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "signatures": {
/// "domain": {
/// "ed25519:1": "KxwGjPSDEtvnFgU00fwFz+l6d2pJM6XBIaMEn81SXPTRl16AqLAYqfIReFGZlHi5KLjAWbOoMszkwsQma+lYAg"
/// }
/// },
/// "type": "X",
/// "unsigned": {
/// "age_ts": 1000000
/// }
/// }
/// ```
///
/// Notice the addition of `hashes` and `signatures`.
/// Compute and add the [signature] of the given event.
///
/// This adds or overwrites the signature for the given entity and key in the `signatures` object of
/// the event.
///
/// When creating a new event, [`add_content_hash_to_event()`](crate::add_content_hash_to_event)
/// should be called first.
///
/// # Parameters
///
/// * `entity_id`: The identifier of the entity creating the signature. Generally this means a
/// homeserver, e.g. "example.com".
/// * `key_pair`: The cryptographic key pair used to sign the event.
/// * `object`: The event to be signed according to the Matrix specification.
/// * `redaction_rules`: The redaction rules for the version of the event's room.
///
/// # Errors
///
/// Returns an error if:
///
/// * `object` contains a field called `content` that is not a JSON object.
/// * `object` contains a field called `signatures` that is not a JSON object.
/// * `object` is missing the `type` field or the field is not a JSON string.
///
/// # Examples
///
/// ```rust
/// use ruma_common::CanonicalJsonObject;
/// use ruma_signatures::sign_event;
/// # use ruma_common::serde::Base64;
/// #
/// # const PKCS8: &str = "\
/// # MFECAQEwBQYDK2VwBCIEINjozvdfbsGEt6DD+7Uf4PiJ/YvTNXV2mIPc/\
/// # tA0T+6tgSEA3TPraTczVkDPTRaX4K+AfUuyx7Mzq1UafTXypnl0t2k\
/// # ";
/// # let der: Base64 = Base64::parse(PKCS8)?;
/// # let key_pair = ruma_signatures::Ed25519KeyPair::from_der(
/// # der.as_bytes(),
/// # "1".into(), // The "version" of the key.
/// # )?;
/// # let room_version_rules = || { ruma_common::room_version_rules::RoomVersionRules::V6 };
///
/// // Deserialize an event from JSON.
/// let mut event = serde_json::from_str(
/// r#"{
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "type": "X",
/// "content": {},
/// "prev_events": [],
/// "auth_events": [],
/// "depth": 3,
/// "hashes": {
/// "sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
/// }
/// }"#,
/// )?;
///
/// // Get the rules for the version of the current room.
/// let rules = room_version_rules();
///
/// // Sign the event with the key pair.
/// sign_event("domain", &key_pair, &mut event, &rules.redaction)?;
///
/// // The signature was added.
/// assert_eq!(
/// event,
/// serde_json::from_str::<CanonicalJsonObject>(
/// r#"{
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "type": "X",
/// "content": {},
/// "prev_events": [],
/// "auth_events": [],
/// "depth": 3,
/// "hashes": {
/// "sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
/// },
/// "signatures": {
/// "domain": {
/// "ed25519:1": "PxOFMn6ORll8PFSQp0IRF6037MEZt3Mfzu/ROiT/gb/ccs1G+f6Ddoswez4KntLPBI3GKCGIkhctiK37JOy2Aw"
/// }
/// }
/// }"#,
/// )?
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [signature]: https://spec.matrix.org/v1.19/server-server-api/#signing-events
/// Signs an arbitrary JSON object and adds the signature to an object under the key `signatures`.
///
/// If `signatures` is already present, the new signature will be appended to the existing ones.
///
/// # Parameters
///
/// * `entity_id`: The identifier of the entity creating the signature. Generally this means a
/// homeserver, e.g. `example.com`.
/// * `key_pair`: A cryptographic key pair used to sign the JSON.
/// * `object`: A JSON object to sign according and append a signature to.
///
/// # Errors
///
/// Returns an error if:
///
/// * `object` contains a field called `signatures` that is not a JSON object.
///
/// # Examples
///
/// A homeserver signs JSON with a key pair:
///
/// ```rust
/// # use ruma_common::serde::base64::Base64;
/// #
/// const PKCS8: &str = "\
/// MFECAQEwBQYDK2VwBCIEINjozvdfbsGEt6DD+7Uf4PiJ/YvTNXV2mIPc/\
/// tA0T+6tgSEA3TPraTczVkDPTRaX4K+AfUuyx7Mzq1UafTXypnl0t2k\
/// ";
///
/// let document: Base64 = Base64::parse(PKCS8).unwrap();
///
/// // Create an Ed25519 key pair.
/// let key_pair = ruma_signatures::Ed25519KeyPair::from_der(
/// document.as_bytes(),
/// "1".into(), // The "version" of the key.
/// )
/// .unwrap();
///
/// // Deserialize some JSON.
/// let mut value = serde_json::from_str("{}").unwrap();
///
/// // Sign the JSON with the key pair.
/// assert!(ruma_signatures::sign_json("domain", &key_pair, &mut value).is_ok());
/// ```
///
/// This will modify the JSON from an empty object to a structure like this:
///
/// ```json
/// {
/// "signatures": {
/// "domain": {
/// "ed25519:1": "K8280/U9SSy9IVtjBuVeLr+HpOB4BQFWbg+UZaADMtTdGYI7Geitb76LTrr5QV/7Xg4ahLwYGYZzuHGZKM5ZAQ"
/// }
/// }
/// }
/// ```
/// Insert the given signature from the given entity in the given object.
///
/// Returns an error if object is malformed.
/// A cryptographic key pair for digitally signing data.
/// A digital signature.