Debian Codegraph @

crypto/sql_store.go

raw
1 // Copyright (c) 2020 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package crypto
8
9 import (
10 "database/sql"
11 "database/sql/driver"
12 "fmt"
13 "strings"
14 "sync"
15
16 "maunium.net/go/mautrix/crypto/olm"
17 "maunium.net/go/mautrix/crypto/sql_store_upgrade"
18 "maunium.net/go/mautrix/event"
19 "maunium.net/go/mautrix/id"
20 )
21
22 var PostgresArrayWrapper func(interface{}) interface {
23 driver.Valuer
24 sql.Scanner
25 }
26
27 // SQLCryptoStore is an implementation of a crypto Store for a database backend.
28 type SQLCryptoStore struct {
29 DB *sql.DB
30 Log Logger
31 Dialect string
32
33 AccountID string
34 DeviceID id.DeviceID
35 SyncToken string
36 PickleKey []byte
37 Account *OlmAccount
38
39 olmSessionCache map[id.SenderKey]map[id.SessionID]*OlmSession
40 olmSessionCacheLock sync.Mutex
41 }
42
43 var _ Store = (*SQLCryptoStore)(nil)
44
45 // NewSQLCryptoStore initializes a new crypto Store using the given database, for a device's crypto material.
46 // The stored material will be encrypted with the given key.
47 func NewSQLCryptoStore(db *sql.DB, dialect string, accountID string, deviceID id.DeviceID, pickleKey []byte, log Logger) *SQLCryptoStore {
48 return &SQLCryptoStore{
49 DB: db,
50 Dialect: dialect,
51 Log: log,
52 PickleKey: pickleKey,
53 AccountID: accountID,
54 DeviceID: deviceID,
55
56 olmSessionCache: make(map[id.SenderKey]map[id.SessionID]*OlmSession),
57 }
58 }
59
60 // CreateTables applies all the pending database migrations.
61 func (store *SQLCryptoStore) CreateTables() error {
62 return sql_store_upgrade.Upgrade(store.DB, store.Dialect)
63 }
64
65 // Flush does nothing for this implementation as data is already persisted in the database.
66 func (store *SQLCryptoStore) Flush() error {
67 return nil
68 }
69
70 // PutNextBatch stores the next sync batch token for the current account.
71 func (store *SQLCryptoStore) PutNextBatch(nextBatch string) {
72 store.SyncToken = nextBatch
73 _, err := store.DB.Exec(`UPDATE crypto_account SET sync_token=$1 WHERE account_id=$2`, store.SyncToken, store.AccountID)
74 if err != nil {
75 store.Log.Warn("Failed to store sync token: %v", err)
76 }
77 }
78
79 // GetNextBatch retrieves the next sync batch token for the current account.
80 func (store *SQLCryptoStore) GetNextBatch() string {
81 if store.SyncToken == "" {
82 err := store.DB.
83 QueryRow("SELECT sync_token FROM crypto_account WHERE account_id=$1", store.AccountID).
84 Scan(&store.SyncToken)
85 if err != nil && err != sql.ErrNoRows {
86 store.Log.Warn("Failed to scan sync token: %v", err)
87 }
88 }
89 return store.SyncToken
90 }
91
92 // PutAccount stores an OlmAccount in the database.
93 func (store *SQLCryptoStore) PutAccount(account *OlmAccount) error {
94 store.Account = account
95 bytes := account.Internal.Pickle(store.PickleKey)
96 _, err := store.DB.Exec(`
97 INSERT INTO crypto_account (device_id, shared, sync_token, account, account_id) VALUES ($1, $2, $3, $4, $5)
98 ON CONFLICT (account_id) DO UPDATE SET shared=excluded.shared, sync_token=excluded.sync_token,
99 account=excluded.account, account_id=excluded.account_id
100 `, store.DeviceID, account.Shared, store.SyncToken, bytes, store.AccountID)
101 if err != nil {
102 store.Log.Warn("Failed to store account: %v", err)
103 }
104 return nil
105 }
106
107 // GetAccount retrieves an OlmAccount from the database.
108 func (store *SQLCryptoStore) GetAccount() (*OlmAccount, error) {
109 if store.Account == nil {
110 row := store.DB.QueryRow("SELECT shared, sync_token, account FROM crypto_account WHERE account_id=$1", store.AccountID)
111 acc := &OlmAccount{Internal: *olm.NewBlankAccount()}
112 var accountBytes []byte
113 err := row.Scan(&acc.Shared, &store.SyncToken, &accountBytes)
114 if err == sql.ErrNoRows {
115 return nil, nil
116 } else if err != nil {
117 return nil, err
118 }
119 err = acc.Internal.Unpickle(accountBytes, store.PickleKey)
120 if err != nil {
121 return nil, err
122 }
123 store.Account = acc
124 }
125 return store.Account, nil
126 }
127
128 // HasSession returns whether there is an Olm session for the given sender key.
129 func (store *SQLCryptoStore) HasSession(key id.SenderKey) bool {
130 store.olmSessionCacheLock.Lock()
131 cache, ok := store.olmSessionCache[key]
132 store.olmSessionCacheLock.Unlock()
133 if ok && len(cache) > 0 {
134 return true
135 }
136 var sessionID id.SessionID
137 err := store.DB.QueryRow("SELECT session_id FROM crypto_olm_session WHERE sender_key=$1 AND account_id=$2 LIMIT 1",
138 key, store.AccountID).Scan(&sessionID)
139 if err == sql.ErrNoRows {
140 return false
141 }
142 return len(sessionID) > 0
143 }
144
145 // GetSessions returns all the known Olm sessions for a sender key.
146 func (store *SQLCryptoStore) GetSessions(key id.SenderKey) (OlmSessionList, error) {
147 rows, err := store.DB.Query("SELECT session_id, session, created_at, last_encrypted, last_decrypted FROM crypto_olm_session WHERE sender_key=$1 AND account_id=$2 ORDER BY last_decrypted DESC",
148 key, store.AccountID)
149 if err != nil {
150 return nil, err
151 }
152 list := OlmSessionList{}
153 store.olmSessionCacheLock.Lock()
154 defer store.olmSessionCacheLock.Unlock()
155 cache := store.getOlmSessionCache(key)
156 for rows.Next() {
157 sess := OlmSession{Internal: *olm.NewBlankSession()}
158 var sessionBytes []byte
159 var sessionID id.SessionID
160 err := rows.Scan(&sessionID, &sessionBytes, &sess.CreationTime, &sess.LastEncryptedTime, &sess.LastDecryptedTime)
161 if err != nil {
162 return nil, err
163 } else if existing, ok := cache[sessionID]; ok {
164 list = append(list, existing)
165 } else {
166 err = sess.Internal.Unpickle(sessionBytes, store.PickleKey)
167 if err != nil {
168 return nil, err
169 }
170 list = append(list, &sess)
171 cache[sess.ID()] = &sess
172 }
173 }
174 return list, nil
175 }
176
177 func (store *SQLCryptoStore) getOlmSessionCache(key id.SenderKey) map[id.SessionID]*OlmSession {
178 data, ok := store.olmSessionCache[key]
179 if !ok {
180 data = make(map[id.SessionID]*OlmSession)
181 store.olmSessionCache[key] = data
182 }
183 return data
184 }
185
186 // GetLatestSession retrieves the Olm session for a given sender key from the database that has the largest ID.
187 func (store *SQLCryptoStore) GetLatestSession(key id.SenderKey) (*OlmSession, error) {
188 store.olmSessionCacheLock.Lock()
189 defer store.olmSessionCacheLock.Unlock()
190
191 row := store.DB.QueryRow("SELECT session_id, session, created_at, last_encrypted, last_decrypted FROM crypto_olm_session WHERE sender_key=$1 AND account_id=$2 ORDER BY last_decrypted DESC LIMIT 1",
192 key, store.AccountID)
193
194 sess := OlmSession{Internal: *olm.NewBlankSession()}
195 var sessionBytes []byte
196 var sessionID id.SessionID
197
198 err := row.Scan(&sessionID, &sessionBytes, &sess.CreationTime, &sess.LastEncryptedTime, &sess.LastDecryptedTime)
199 if err == sql.ErrNoRows {
200 return nil, nil
201 } else if err != nil {
202 return nil, err
203 }
204
205 cache := store.getOlmSessionCache(key)
206 if oldSess, ok := cache[sessionID]; ok {
207 return oldSess, nil
208 } else if err = sess.Internal.Unpickle(sessionBytes, store.PickleKey); err != nil {
209 return nil, err
210 } else {
211 cache[sessionID] = &sess
212 return &sess, nil
213 }
214 }
215
216 // AddSession persists an Olm session for a sender in the database.
217 func (store *SQLCryptoStore) AddSession(key id.SenderKey, session *OlmSession) error {
218 store.olmSessionCacheLock.Lock()
219 defer store.olmSessionCacheLock.Unlock()
220 sessionBytes := session.Internal.Pickle(store.PickleKey)
221 _, err := store.DB.Exec("INSERT INTO crypto_olm_session (session_id, sender_key, session, created_at, last_encrypted, last_decrypted, account_id) VALUES ($1, $2, $3, $4, $5, $6, $7)",
222 session.ID(), key, sessionBytes, session.CreationTime, session.LastEncryptedTime, session.LastDecryptedTime, store.AccountID)
223 store.getOlmSessionCache(key)[session.ID()] = session
224 return err
225 }
226
227 // UpdateSession replaces the Olm session for a sender in the database.
228 func (store *SQLCryptoStore) UpdateSession(_ id.SenderKey, session *OlmSession) error {
229 sessionBytes := session.Internal.Pickle(store.PickleKey)
230 _, err := store.DB.Exec("UPDATE crypto_olm_session SET session=$1, last_encrypted=$2, last_decrypted=$3 WHERE session_id=$4 AND account_id=$5",
231 sessionBytes, session.LastEncryptedTime, session.LastDecryptedTime, session.ID(), store.AccountID)
232 return err
233 }
234
235 // PutGroupSession stores an inbound Megolm group session for a room, sender and session.
236 func (store *SQLCryptoStore) PutGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, session *InboundGroupSession) error {
237 sessionBytes := session.Internal.Pickle(store.PickleKey)
238 forwardingChains := strings.Join(session.ForwardingChains, ",")
239 _, err := store.DB.Exec(`
240 INSERT INTO crypto_megolm_inbound_session
241 (session_id, sender_key, signing_key, room_id, session, forwarding_chains, account_id)
242 VALUES ($1, $2, $3, $4, $5, $6, $7)
243 ON CONFLICT (session_id, account_id) DO UPDATE
244 SET withheld_code=NULL, withheld_reason=NULL, sender_key=excluded.sender_key, signing_key=excluded.signing_key,
245 room_id=excluded.room_id, session=excluded.session, forwarding_chains=excluded.forwarding_chains
246 `, sessionID, senderKey, session.SigningKey, roomID, sessionBytes, forwardingChains, store.AccountID)
247 return err
248 }
249
250 // GetGroupSession retrieves an inbound Megolm group session for a room, sender and session.
251 func (store *SQLCryptoStore) GetGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*InboundGroupSession, error) {
252 var signingKey, forwardingChains, withheldCode sql.NullString
253 var sessionBytes []byte
254 err := store.DB.QueryRow(`
255 SELECT signing_key, session, forwarding_chains, withheld_code
256 FROM crypto_megolm_inbound_session
257 WHERE room_id=$1 AND sender_key=$2 AND session_id=$3 AND account_id=$4`,
258 roomID, senderKey, sessionID, store.AccountID,
259 ).Scan(&signingKey, &sessionBytes, &forwardingChains, &withheldCode)
260 if err == sql.ErrNoRows {
261 return nil, nil
262 } else if err != nil {
263 return nil, err
264 } else if withheldCode.Valid {
265 return nil, fmt.Errorf("%w (%s)", ErrGroupSessionWithheld, withheldCode.String)
266 }
267 igs := olm.NewBlankInboundGroupSession()
268 err = igs.Unpickle(sessionBytes, store.PickleKey)
269 if err != nil {
270 return nil, err
271 }
272 return &InboundGroupSession{
273 Internal: *igs,
274 SigningKey: id.Ed25519(signingKey.String),
275 SenderKey: senderKey,
276 RoomID: roomID,
277 ForwardingChains: strings.Split(forwardingChains.String, ","),
278 }, nil
279 }
280
281 func (store *SQLCryptoStore) PutWithheldGroupSession(content event.RoomKeyWithheldEventContent) error {
282 _, err := store.DB.Exec("INSERT INTO crypto_megolm_inbound_session (session_id, sender_key, room_id, withheld_code, withheld_reason, account_id) VALUES ($1, $2, $3, $4, $5, $6)",
283 content.SessionID, content.SenderKey, content.RoomID, content.Code, content.Reason, store.AccountID)
284 return err
285 }
286
287 func (store *SQLCryptoStore) GetWithheldGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*event.RoomKeyWithheldEventContent, error) {
288 var code, reason sql.NullString
289 err := store.DB.QueryRow(`
290 SELECT withheld_code, withheld_reason FROM crypto_megolm_inbound_session
291 WHERE room_id=$1 AND sender_key=$2 AND session_id=$3 AND account_id=$4`,
292 roomID, senderKey, sessionID, store.AccountID,
293 ).Scan(&code, &reason)
294 if err == sql.ErrNoRows {
295 return nil, nil
296 } else if err != nil || !code.Valid {
297 return nil, err
298 }
299 return &event.RoomKeyWithheldEventContent{
300 RoomID: roomID,
301 Algorithm: id.AlgorithmMegolmV1,
302 SessionID: sessionID,
303 SenderKey: senderKey,
304 Code: event.RoomKeyWithheldCode(code.String),
305 Reason: reason.String,
306 }, nil
307 }
308
309 func (store *SQLCryptoStore) scanGroupSessionList(rows *sql.Rows) (result []*InboundGroupSession) {
310 for rows.Next() {
311 var roomID id.RoomID
312 var signingKey, senderKey, forwardingChains sql.NullString
313 var sessionBytes []byte
314 err := rows.Scan(&roomID, &signingKey, &senderKey, &sessionBytes, &forwardingChains)
315 if err != nil {
316 store.Log.Warn("Failed to scan row: %v", err)
317 continue
318 }
319 igs := olm.NewBlankInboundGroupSession()
320 err = igs.Unpickle(sessionBytes, store.PickleKey)
321 if err != nil {
322 store.Log.Warn("Failed to unpickle session: %v", err)
323 continue
324 }
325 result = append(result, &InboundGroupSession{
326 Internal: *igs,
327 SigningKey: id.Ed25519(signingKey.String),
328 SenderKey: id.Curve25519(senderKey.String),
329 RoomID: roomID,
330 ForwardingChains: strings.Split(forwardingChains.String, ","),
331 })
332 }
333 return
334 }
335
336 func (store *SQLCryptoStore) GetGroupSessionsForRoom(roomID id.RoomID) ([]*InboundGroupSession, error) {
337 rows, err := store.DB.Query(`
338 SELECT room_id, signing_key, sender_key, session, forwarding_chains
339 FROM crypto_megolm_inbound_session WHERE room_id=$1 AND account_id=$2`,
340 roomID, store.AccountID,
341 )
342 if err == sql.ErrNoRows {
343 return []*InboundGroupSession{}, nil
344 } else if err != nil {
345 return nil, err
346 }
347 return store.scanGroupSessionList(rows), nil
348 }
349
350 func (store *SQLCryptoStore) GetAllGroupSessions() ([]*InboundGroupSession, error) {
351 rows, err := store.DB.Query(`
352 SELECT room_id, signing_key, sender_key, session, forwarding_chains
353 FROM crypto_megolm_inbound_session WHERE account_id=$2`,
354 store.AccountID,
355 )
356 if err == sql.ErrNoRows {
357 return []*InboundGroupSession{}, nil
358 } else if err != nil {
359 return nil, err
360 }
361 return store.scanGroupSessionList(rows), nil
362 }
363
364 // AddOutboundGroupSession stores an outbound Megolm session, along with the information about the room and involved devices.
365 func (store *SQLCryptoStore) AddOutboundGroupSession(session *OutboundGroupSession) error {
366 sessionBytes := session.Internal.Pickle(store.PickleKey)
367 _, err := store.DB.Exec(`
368 INSERT INTO crypto_megolm_outbound_session
369 (room_id, session_id, session, shared, max_messages, message_count, max_age, created_at, last_used, account_id)
370 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
371 ON CONFLICT (account_id, room_id) DO UPDATE
372 SET session_id=excluded.session_id, session=excluded.session, shared=excluded.shared,
373 max_messages=excluded.max_messages, message_count=excluded.message_count, max_age=excluded.max_age,
374 created_at=excluded.created_at, last_used=excluded.last_used, account_id=excluded.account_id
375 `, session.RoomID, session.ID(), sessionBytes, session.Shared, session.MaxMessages, session.MessageCount,
376 session.MaxAge, session.CreationTime, session.LastEncryptedTime, store.AccountID)
377 return err
378 }
379
380 // UpdateOutboundGroupSession replaces an outbound Megolm session with for same room and session ID.
381 func (store *SQLCryptoStore) UpdateOutboundGroupSession(session *OutboundGroupSession) error {
382 sessionBytes := session.Internal.Pickle(store.PickleKey)
383 _, err := store.DB.Exec("UPDATE crypto_megolm_outbound_session SET session=$1, message_count=$2, last_used=$3 WHERE room_id=$4 AND session_id=$5 AND account_id=$6",
384 sessionBytes, session.MessageCount, session.LastEncryptedTime, session.RoomID, session.ID(), store.AccountID)
385 return err
386 }
387
388 // GetOutboundGroupSession retrieves the outbound Megolm session for the given room ID.
389 func (store *SQLCryptoStore) GetOutboundGroupSession(roomID id.RoomID) (*OutboundGroupSession, error) {
390 var ogs OutboundGroupSession
391 var sessionBytes []byte
392 err := store.DB.QueryRow(`
393 SELECT session, shared, max_messages, message_count, max_age, created_at, last_used
394 FROM crypto_megolm_outbound_session WHERE room_id=$1 AND account_id=$2`,
395 roomID, store.AccountID,
396 ).Scan(&sessionBytes, &ogs.Shared, &ogs.MaxMessages, &ogs.MessageCount, &ogs.MaxAge, &ogs.CreationTime, &ogs.LastEncryptedTime)
397 if err == sql.ErrNoRows {
398 return nil, nil
399 } else if err != nil {
400 return nil, err
401 }
402 intOGS := olm.NewBlankOutboundGroupSession()
403 err = intOGS.Unpickle(sessionBytes, store.PickleKey)
404 if err != nil {
405 return nil, err
406 }
407 ogs.Internal = *intOGS
408 ogs.RoomID = roomID
409 return &ogs, nil
410 }
411
412 // RemoveOutboundGroupSession removes the outbound Megolm session for the given room ID.
413 func (store *SQLCryptoStore) RemoveOutboundGroupSession(roomID id.RoomID) error {
414 _, err := store.DB.Exec("DELETE FROM crypto_megolm_outbound_session WHERE room_id=$1 AND account_id=$2",
415 roomID, store.AccountID)
416 return err
417 }
418
419 // ValidateMessageIndex returns whether the given event information match the ones stored in the database
420 // for the given sender key, session ID and index.
421 // If the event information was not yet stored, it's stored now.
422 func (store *SQLCryptoStore) ValidateMessageIndex(senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) bool {
423 var resultEventID id.EventID
424 var resultTimestamp int64
425 err := store.DB.QueryRow(
426 `SELECT event_id, timestamp FROM crypto_message_index WHERE sender_key=$1 AND session_id=$2 AND "index"=$3`,
427 senderKey, sessionID, index,
428 ).Scan(&resultEventID, &resultTimestamp)
429 if err == sql.ErrNoRows {
430 _, err := store.DB.Exec(`INSERT INTO crypto_message_index (sender_key, session_id, "index", event_id, timestamp) VALUES ($1, $2, $3, $4, $5)`,
431 senderKey, sessionID, index, eventID, timestamp)
432 if err != nil {
433 store.Log.Warn("Failed to store message index: %v", err)
434 }
435 return true
436 } else if err != nil {
437 store.Log.Warn("Failed to scan message index: %v", err)
438 return true
439 }
440 if resultEventID != eventID || resultTimestamp != timestamp {
441 return false
442 }
443 return true
444 }
445
446 // GetDevices returns a map of device IDs to device identities, including the identity and signing keys, for a given user ID.
447 func (store *SQLCryptoStore) GetDevices(userID id.UserID) (map[id.DeviceID]*DeviceIdentity, error) {
448 var ignore id.UserID
449 err := store.DB.QueryRow("SELECT user_id FROM crypto_tracked_user WHERE user_id=$1", userID).Scan(&ignore)
450 if err == sql.ErrNoRows {
451 return nil, nil
452 } else if err != nil {
453 return nil, err
454 }
455
456 rows, err := store.DB.Query("SELECT device_id, identity_key, signing_key, trust, deleted, name FROM crypto_device WHERE user_id=$1", userID)
457 if err != nil {
458 return nil, err
459 }
460 data := make(map[id.DeviceID]*DeviceIdentity)
461 for rows.Next() {
462 var identity DeviceIdentity
463 err := rows.Scan(&identity.DeviceID, &identity.IdentityKey, &identity.SigningKey, &identity.Trust, &identity.Deleted, &identity.Name)
464 if err != nil {
465 return nil, err
466 }
467 identity.UserID = userID
468 data[identity.DeviceID] = &identity
469 }
470 return data, nil
471 }
472
473 // GetDevice returns the device dentity for a given user and device ID.
474 func (store *SQLCryptoStore) GetDevice(userID id.UserID, deviceID id.DeviceID) (*DeviceIdentity, error) {
475 var identity DeviceIdentity
476 err := store.DB.QueryRow(`
477 SELECT identity_key, signing_key, trust, deleted, name
478 FROM crypto_device WHERE user_id=$1 AND device_id=$2`,
479 userID, deviceID,
480 ).Scan(&identity.IdentityKey, &identity.SigningKey, &identity.Trust, &identity.Deleted, &identity.Name)
481 if err != nil {
482 if err == sql.ErrNoRows {
483 return nil, nil
484 }
485 return nil, err
486 }
487 identity.UserID = userID
488 identity.DeviceID = deviceID
489 return &identity, nil
490 }
491
492 // FindDeviceByKey finds a specific device by its sender key.
493 func (store *SQLCryptoStore) FindDeviceByKey(userID id.UserID, identityKey id.IdentityKey) (*DeviceIdentity, error) {
494 var identity DeviceIdentity
495 err := store.DB.QueryRow(`
496 SELECT device_id, signing_key, trust, deleted, name
497 FROM crypto_device WHERE user_id=$1 AND identity_key=$2`,
498 userID, identityKey,
499 ).Scan(&identity.DeviceID, &identity.SigningKey, &identity.Trust, &identity.Deleted, &identity.Name)
500 if err != nil {
501 if err == sql.ErrNoRows {
502 return nil, nil
503 }
504 return nil, err
505 }
506 identity.UserID = userID
507 identity.IdentityKey = identityKey
508 return &identity, nil
509 }
510
511 // PutDevice stores a single device for a user, replacing it if it exists already.
512 func (store *SQLCryptoStore) PutDevice(userID id.UserID, device *DeviceIdentity) error {
513 _, err := store.DB.Exec(`
514 INSERT INTO crypto_device (user_id, device_id, identity_key, signing_key, trust, deleted, name) VALUES ($1, $2, $3, $4, $5, $6, $7)
515 ON CONFLICT (user_id, device_id) DO UPDATE SET identity_key=excluded.identity_key, signing_key=excluded.signing_key, trust=excluded.trust, deleted=excluded.deleted, name=excluded.name`,
516 userID, device.DeviceID, device.IdentityKey, device.SigningKey, device.Trust, device.Deleted, device.Name)
517 return err
518 }
519
520 // PutDevices stores the device identity information for the given user ID.
521 func (store *SQLCryptoStore) PutDevices(userID id.UserID, devices map[id.DeviceID]*DeviceIdentity) error {
522 tx, err := store.DB.Begin()
523 if err != nil {
524 return err
525 }
526
527 _, err = tx.Exec("INSERT INTO crypto_tracked_user (user_id) VALUES ($1) ON CONFLICT (user_id) DO NOTHING", userID)
528 if err != nil {
529 return fmt.Errorf("failed to add user to tracked users list: %w", err)
530 }
531
532 _, err = tx.Exec("DELETE FROM crypto_device WHERE user_id=$1", userID)
533 if err != nil {
534 _ = tx.Rollback()
535 return fmt.Errorf("failed to delete old devices: %w", err)
536 }
537 if len(devices) == 0 {
538 err = tx.Commit()
539 if err != nil {
540 return fmt.Errorf("failed to commit changes (no devices added): %w", err)
541 }
542 return nil
543 }
544 deviceBatchLen := 5 // how many devices will be inserted per query
545 deviceIDs := make([]id.DeviceID, 0, len(devices))
546 for deviceID := range devices {
547 deviceIDs = append(deviceIDs, deviceID)
548 }
549 for batchDeviceIdx := 0; batchDeviceIdx < len(deviceIDs); batchDeviceIdx += deviceBatchLen {
550 var batchDevices []id.DeviceID
551 if batchDeviceIdx+deviceBatchLen < len(deviceIDs) {
552 batchDevices = deviceIDs[batchDeviceIdx : batchDeviceIdx+deviceBatchLen]
553 } else {
554 batchDevices = deviceIDs[batchDeviceIdx:]
555 }
556 values := make([]interface{}, 1, len(devices)*6+1)
557 values[0] = userID
558 valueStrings := make([]string, 0, len(devices))
559 i := 2
560 for _, deviceID := range batchDevices {
561 identity := devices[deviceID]
562 values = append(values, deviceID, identity.IdentityKey, identity.SigningKey, identity.Trust, identity.Deleted, identity.Name)
563 valueStrings = append(valueStrings, fmt.Sprintf("($1, $%d, $%d, $%d, $%d, $%d, $%d)", i, i+1, i+2, i+3, i+4, i+5))
564 i += 6
565 }
566 valueString := strings.Join(valueStrings, ",")
567 _, err = tx.Exec("INSERT INTO crypto_device (user_id, device_id, identity_key, signing_key, trust, deleted, name) VALUES "+valueString, values...)
568 if err != nil {
569 _ = tx.Rollback()
570 return fmt.Errorf("failed to insert new devices: %w", err)
571 }
572 }
573 err = tx.Commit()
574 if err != nil {
575 return fmt.Errorf("failed to commit changes: %w", err)
576 }
577 return nil
578 }
579
580 // FilterTrackedUsers finds all of the user IDs out of the given ones for which the database contains identity information.
581 func (store *SQLCryptoStore) FilterTrackedUsers(users []id.UserID) []id.UserID {
582 var rows *sql.Rows
583 var err error
584 if store.Dialect == "postgres" && PostgresArrayWrapper != nil {
585 rows, err = store.DB.Query("SELECT user_id FROM crypto_tracked_user WHERE user_id = ANY($1)", PostgresArrayWrapper(users))
586 } else {
587 queryString := make([]string, len(users))
588 params := make([]interface{}, len(users))
589 for i, user := range users {
590 queryString[i] = fmt.Sprintf("$%d", i+1)
591 params[i] = user
592 }
593 rows, err = store.DB.Query("SELECT user_id FROM crypto_tracked_user WHERE user_id IN ("+strings.Join(queryString, ",")+")", params...)
594 }
595 if err != nil {
596 store.Log.Warn("Failed to filter tracked users: %v", err)
597 return users
598 }
599 var ptr int
600 for rows.Next() {
601 err = rows.Scan(&users[ptr])
602 if err != nil {
603 store.Log.Warn("Failed to scan tracked user ID: %v", err)
604 } else {
605 ptr++
606 }
607 }
608 return users[:ptr]
609 }
610
611 // PutCrossSigningKey stores a cross-signing key of some user along with its usage.
612 func (store *SQLCryptoStore) PutCrossSigningKey(userID id.UserID, usage id.CrossSigningUsage, key id.Ed25519) error {
613 _, err := store.DB.Exec(`
614 INSERT INTO crypto_cross_signing_keys (user_id, usage, key) VALUES ($1, $2, $3)
615 ON CONFLICT (user_id, usage) DO UPDATE SET key=excluded.key
616 `, userID, usage, key)
617 return err
618 }
619
620 // GetCrossSigningKeys retrieves a user's stored cross-signing keys.
621 func (store *SQLCryptoStore) GetCrossSigningKeys(userID id.UserID) (map[id.CrossSigningUsage]id.Ed25519, error) {
622 rows, err := store.DB.Query("SELECT usage, key FROM crypto_cross_signing_keys WHERE user_id=$1", userID)
623 if err != nil {
624 return nil, err
625 }
626 data := make(map[id.CrossSigningUsage]id.Ed25519)
627 for rows.Next() {
628 var usage id.CrossSigningUsage
629 var key id.Ed25519
630 err := rows.Scan(&usage, &key)
631 if err != nil {
632 return nil, err
633 }
634 data[usage] = key
635 }
636
637 return data, nil
638 }
639
640 // PutSignature stores a signature of a cross-signing or device key along with the signer's user ID and key.
641 func (store *SQLCryptoStore) PutSignature(signedUserID id.UserID, signedKey id.Ed25519, signerUserID id.UserID, signerKey id.Ed25519, signature string) error {
642 _, err := store.DB.Exec(`
643 INSERT INTO crypto_cross_signing_signatures (signed_user_id, signed_key, signer_user_id, signer_key, signature) VALUES ($1, $2, $3, $4, $5)
644 ON CONFLICT (signed_user_id, signed_key, signer_user_id, signer_key) DO UPDATE SET signature=excluded.signature
645 `, signedUserID, signedKey, signerUserID, signerKey, signature)
646 return err
647 }
648
649 // GetSignaturesForKeyBy retrieves the stored signatures for a given cross-signing or device key, by the given signer.
650 func (store *SQLCryptoStore) GetSignaturesForKeyBy(userID id.UserID, key id.Ed25519, signerID id.UserID) (map[id.Ed25519]string, error) {
651 rows, err := store.DB.Query("SELECT signer_key, signature FROM crypto_cross_signing_signatures WHERE signed_user_id=$1 AND signed_key=$2 AND signer_user_id=$3", userID, key, signerID)
652 if err != nil {
653 return nil, err
654 }
655 data := make(map[id.Ed25519]string)
656 for rows.Next() {
657 var signerKey id.Ed25519
658 var signature string
659 err := rows.Scan(&signerKey, &signature)
660 if err != nil {
661 return nil, err
662 }
663 data[signerKey] = signature
664 }
665
666 return data, nil
667 }
668
669 // IsKeySignedBy returns whether a cross-signing or device key is signed by the given signer.
670 func (store *SQLCryptoStore) IsKeySignedBy(userID id.UserID, key id.Ed25519, signerID id.UserID, signerKey id.Ed25519) (bool, error) {
671 sigs, err := store.GetSignaturesForKeyBy(userID, key, signerID)
672 if err != nil {
673 return false, err
674 }
675 _, ok := sigs[signerKey]
676 return ok, nil
677 }
678
679 // DropSignaturesByKey deletes the signatures made by the given user and key from the store. It returns the number of signatures deleted.
680 func (store *SQLCryptoStore) DropSignaturesByKey(userID id.UserID, key id.Ed25519) (int64, error) {
681 res, err := store.DB.Exec("DELETE FROM crypto_cross_signing_signatures WHERE signer_user_id=$1 AND signer_key=$2", userID, key)
682 if err != nil {
683 return 0, err
684 }
685 count, err := res.RowsAffected()
686 if err != nil {
687 return 0, err
688 }
689 return count, nil
690 }