2020-07-14 12:59:07 +01:00
|
|
|
// Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2020-07-13 16:02:35 +01:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
2020-07-14 12:59:07 +01:00
|
|
|
"bytes"
|
2020-07-13 16:02:35 +01:00
|
|
|
"context"
|
2020-07-15 18:40:41 +01:00
|
|
|
"encoding/json"
|
2022-08-03 17:35:17 +01:00
|
|
|
"errors"
|
2020-07-14 12:59:07 +01:00
|
|
|
"fmt"
|
2020-07-21 17:46:47 +01:00
|
|
|
"sync"
|
|
|
|
"time"
|
2020-07-13 16:02:35 +01:00
|
|
|
|
2020-07-15 18:40:41 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2020-07-22 17:04:57 +01:00
|
|
|
"github.com/matrix-org/util"
|
2020-08-12 22:43:02 +01:00
|
|
|
"github.com/sirupsen/logrus"
|
2020-07-14 12:59:07 +01:00
|
|
|
"github.com/tidwall/gjson"
|
2020-07-15 18:40:41 +01:00
|
|
|
"github.com/tidwall/sjson"
|
2022-09-20 10:32:03 +01:00
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
"github.com/matrix-org/dendrite/userapi/api"
|
2020-07-13 16:02:35 +01:00
|
|
|
)
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) QueryKeyChanges(ctx context.Context, req *api.QueryKeyChangesRequest, res *api.QueryKeyChangesResponse) error {
|
|
|
|
userIDs, latest, err := a.KeyDatabase.KeyChanges(ctx, req.Offset, req.ToOffset)
|
2020-07-28 18:25:16 +01:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: err.Error(),
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-07-28 18:25:16 +01:00
|
|
|
}
|
|
|
|
res.Offset = latest
|
|
|
|
res.UserIDs = userIDs
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-07-28 18:25:16 +01:00
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) PerformUploadKeys(ctx context.Context, req *api.PerformUploadKeysRequest, res *api.PerformUploadKeysResponse) error {
|
2020-07-14 12:59:07 +01:00
|
|
|
res.KeyErrors = make(map[string]map[string]*api.KeyError)
|
2022-04-25 14:22:46 +01:00
|
|
|
if len(req.DeviceKeys) > 0 {
|
|
|
|
a.uploadLocalDeviceKeys(ctx, req, res)
|
|
|
|
}
|
|
|
|
if len(req.OneTimeKeys) > 0 {
|
|
|
|
a.uploadOneTimeKeys(ctx, req, res)
|
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
otks, err := a.KeyDatabase.OneTimeKeysCount(ctx, req.UserID, req.DeviceID)
|
2022-10-06 11:30:24 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
res.OneTimeKeyCounts = []api.OneTimeKeysCount{*otks}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-07-13 16:02:35 +01:00
|
|
|
}
|
2020-07-21 14:47:53 +01:00
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) PerformClaimKeys(ctx context.Context, req *api.PerformClaimKeysRequest, res *api.PerformClaimKeysResponse) error {
|
2020-07-21 14:47:53 +01:00
|
|
|
res.OneTimeKeys = make(map[string]map[string]map[string]json.RawMessage)
|
|
|
|
res.Failures = make(map[string]interface{})
|
|
|
|
// wrap request map in a top-level by-domain map
|
|
|
|
domainToDeviceKeys := make(map[string]map[string]map[string]string)
|
|
|
|
for userID, val := range req.OneTimeKeys {
|
|
|
|
_, serverName, err := gomatrixserverlib.SplitID('@', userID)
|
|
|
|
if err != nil {
|
|
|
|
continue // ignore invalid users
|
|
|
|
}
|
|
|
|
nested, ok := domainToDeviceKeys[string(serverName)]
|
|
|
|
if !ok {
|
|
|
|
nested = make(map[string]map[string]string)
|
|
|
|
}
|
|
|
|
nested[userID] = val
|
|
|
|
domainToDeviceKeys[string(serverName)] = nested
|
|
|
|
}
|
2022-11-11 16:41:37 +00:00
|
|
|
for domain, local := range domainToDeviceKeys {
|
2023-02-20 13:58:03 +00:00
|
|
|
if !a.Config.Matrix.IsLocalServerName(gomatrixserverlib.ServerName(domain)) {
|
2022-11-11 16:41:37 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
// claim local keys
|
2023-02-20 13:58:03 +00:00
|
|
|
keys, err := a.KeyDatabase.ClaimKeys(ctx, local)
|
2020-07-21 14:47:53 +01:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("failed to ClaimKeys locally: %s", err),
|
|
|
|
}
|
|
|
|
}
|
2020-07-22 17:04:57 +01:00
|
|
|
util.GetLogger(ctx).WithField("keys_claimed", len(keys)).WithField("num_users", len(local)).Info("Claimed local keys")
|
|
|
|
for _, key := range keys {
|
|
|
|
_, ok := res.OneTimeKeys[key.UserID]
|
|
|
|
if !ok {
|
|
|
|
res.OneTimeKeys[key.UserID] = make(map[string]map[string]json.RawMessage)
|
|
|
|
}
|
|
|
|
_, ok = res.OneTimeKeys[key.UserID][key.DeviceID]
|
|
|
|
if !ok {
|
|
|
|
res.OneTimeKeys[key.UserID][key.DeviceID] = make(map[string]json.RawMessage)
|
|
|
|
}
|
|
|
|
for keyID, keyJSON := range key.KeyJSON {
|
|
|
|
res.OneTimeKeys[key.UserID][key.DeviceID][keyID] = keyJSON
|
|
|
|
}
|
|
|
|
}
|
2022-11-11 16:41:37 +00:00
|
|
|
delete(domainToDeviceKeys, domain)
|
2020-07-21 14:47:53 +01:00
|
|
|
}
|
2020-07-22 17:04:57 +01:00
|
|
|
if len(domainToDeviceKeys) > 0 {
|
|
|
|
a.claimRemoteKeys(ctx, req.Timeout, res, domainToDeviceKeys)
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-07-21 17:46:47 +01:00
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) claimRemoteKeys(
|
2020-07-21 17:46:47 +01:00
|
|
|
ctx context.Context, timeout time.Duration, res *api.PerformClaimKeysResponse, domainToDeviceKeys map[string]map[string]map[string]string,
|
|
|
|
) {
|
2022-10-27 15:34:26 +01:00
|
|
|
var wg sync.WaitGroup // Wait for fan-out goroutines to finish
|
|
|
|
var mu sync.Mutex // Protects the response struct
|
|
|
|
var claimed int // Number of keys claimed in total
|
|
|
|
var failures int // Number of servers we failed to ask
|
|
|
|
|
|
|
|
util.GetLogger(ctx).Infof("Claiming remote keys from %d server(s)", len(domainToDeviceKeys))
|
2020-07-21 17:46:47 +01:00
|
|
|
wg.Add(len(domainToDeviceKeys))
|
|
|
|
|
|
|
|
for d, k := range domainToDeviceKeys {
|
|
|
|
go func(domain string, keysToClaim map[string]map[string]string) {
|
|
|
|
fedCtx, cancel := context.WithTimeout(ctx, timeout)
|
|
|
|
defer cancel()
|
2022-10-27 15:34:26 +01:00
|
|
|
defer wg.Done()
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
claimKeyRes, err := a.FedClient.ClaimKeys(fedCtx, a.Config.Matrix.ServerName, gomatrixserverlib.ServerName(domain), keysToClaim)
|
2022-10-27 15:34:26 +01:00
|
|
|
|
|
|
|
mu.Lock()
|
|
|
|
defer mu.Unlock()
|
|
|
|
|
2020-07-21 17:46:47 +01:00
|
|
|
if err != nil {
|
2020-07-22 17:04:57 +01:00
|
|
|
util.GetLogger(ctx).WithError(err).WithField("server", domain).Error("ClaimKeys failed")
|
2020-07-21 17:46:47 +01:00
|
|
|
res.Failures[domain] = map[string]interface{}{
|
|
|
|
"message": err.Error(),
|
|
|
|
}
|
2022-10-27 15:34:26 +01:00
|
|
|
failures++
|
2020-07-21 17:46:47 +01:00
|
|
|
return
|
|
|
|
}
|
2020-07-13 16:02:35 +01:00
|
|
|
|
2022-10-27 15:34:26 +01:00
|
|
|
for userID, deviceIDToKeys := range claimKeyRes.OneTimeKeys {
|
|
|
|
res.OneTimeKeys[userID] = make(map[string]map[string]json.RawMessage)
|
|
|
|
for deviceID, keys := range deviceIDToKeys {
|
|
|
|
res.OneTimeKeys[userID][deviceID] = keys
|
|
|
|
claimed += len(keys)
|
2020-07-21 17:46:47 +01:00
|
|
|
}
|
|
|
|
}
|
2022-10-27 15:34:26 +01:00
|
|
|
}(d, k)
|
2020-07-21 17:46:47 +01:00
|
|
|
}
|
2022-10-27 15:34:26 +01:00
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
util.GetLogger(ctx).WithFields(logrus.Fields{
|
|
|
|
"num_keys": claimed,
|
|
|
|
"num_failures": failures,
|
|
|
|
}).Infof("Claimed remote keys from %d server(s)", len(domainToDeviceKeys))
|
2020-07-13 16:02:35 +01:00
|
|
|
}
|
2020-07-21 14:47:53 +01:00
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) PerformDeleteKeys(ctx context.Context, req *api.PerformDeleteKeysRequest, res *api.PerformDeleteKeysResponse) error {
|
|
|
|
if err := a.KeyDatabase.DeleteDeviceKeys(ctx, req.UserID, req.KeyIDs); err != nil {
|
2021-08-18 12:07:09 +01:00
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("Failed to delete device keys: %s", err),
|
|
|
|
}
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2021-08-18 12:07:09 +01:00
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) QueryOneTimeKeys(ctx context.Context, req *api.QueryOneTimeKeysRequest, res *api.QueryOneTimeKeysResponse) error {
|
|
|
|
count, err := a.KeyDatabase.OneTimeKeysCount(ctx, req.UserID, req.DeviceID)
|
2020-08-03 12:29:58 +01:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("Failed to query OTK counts: %s", err),
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-08-03 12:29:58 +01:00
|
|
|
}
|
|
|
|
res.Count = *count
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-08-03 12:29:58 +01:00
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) QueryDeviceMessages(ctx context.Context, req *api.QueryDeviceMessagesRequest, res *api.QueryDeviceMessagesResponse) error {
|
|
|
|
msgs, err := a.KeyDatabase.DeviceKeysForUser(ctx, req.UserID, nil, false)
|
2020-08-04 11:32:14 +01:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("failed to query DB for device keys: %s", err),
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-08-04 11:32:14 +01:00
|
|
|
}
|
2022-03-10 13:17:28 +00:00
|
|
|
maxStreamID := int64(0)
|
2022-10-07 09:54:42 +01:00
|
|
|
// remove deleted devices
|
|
|
|
var result []api.DeviceMessage
|
2020-08-04 11:32:14 +01:00
|
|
|
for _, m := range msgs {
|
|
|
|
if m.StreamID > maxStreamID {
|
|
|
|
maxStreamID = m.StreamID
|
|
|
|
}
|
2022-10-07 09:54:42 +01:00
|
|
|
if m.KeyJSON == nil || len(m.KeyJSON) == 0 {
|
2020-08-12 22:43:02 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
result = append(result, m)
|
|
|
|
}
|
|
|
|
res.Devices = result
|
2020-08-04 11:32:14 +01:00
|
|
|
res.StreamID = maxStreamID
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-08-04 11:32:14 +01:00
|
|
|
}
|
|
|
|
|
2022-09-20 10:32:03 +01:00
|
|
|
// PerformMarkAsStaleIfNeeded marks the users device list as stale, if the given deviceID is not present
|
|
|
|
// in our database.
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) PerformMarkAsStaleIfNeeded(ctx context.Context, req *api.PerformMarkAsStaleRequest, res *struct{}) error {
|
|
|
|
knownDevices, err := a.KeyDatabase.DeviceKeysForUser(ctx, req.UserID, []string{}, true)
|
2022-09-20 10:32:03 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(knownDevices) == 0 {
|
2022-10-03 12:59:56 +01:00
|
|
|
return nil // fmt.Errorf("unknown user %s", req.UserID)
|
2022-09-20 10:32:03 +01:00
|
|
|
}
|
2022-09-30 09:32:31 +01:00
|
|
|
|
|
|
|
for i := range knownDevices {
|
|
|
|
if knownDevices[i].DeviceID == req.DeviceID {
|
|
|
|
return nil // we already know about this device
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return a.Updater.ManualUpdate(ctx, req.Domain, req.UserID)
|
2022-09-20 10:32:03 +01:00
|
|
|
}
|
|
|
|
|
2022-03-24 10:03:22 +00:00
|
|
|
// nolint:gocyclo
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) QueryKeys(ctx context.Context, req *api.QueryKeysRequest, res *api.QueryKeysResponse) error {
|
2022-10-19 12:03:12 +01:00
|
|
|
var respMu sync.Mutex
|
2020-07-15 18:40:41 +01:00
|
|
|
res.DeviceKeys = make(map[string]map[string]json.RawMessage)
|
2021-08-04 17:56:29 +01:00
|
|
|
res.MasterKeys = make(map[string]gomatrixserverlib.CrossSigningKey)
|
|
|
|
res.SelfSigningKeys = make(map[string]gomatrixserverlib.CrossSigningKey)
|
|
|
|
res.UserSigningKeys = make(map[string]gomatrixserverlib.CrossSigningKey)
|
2020-07-15 18:40:41 +01:00
|
|
|
res.Failures = make(map[string]interface{})
|
2021-08-04 17:56:29 +01:00
|
|
|
|
2020-07-15 18:40:41 +01:00
|
|
|
// make a map from domain to device keys
|
2020-07-21 17:46:47 +01:00
|
|
|
domainToDeviceKeys := make(map[string]map[string][]string)
|
2021-08-04 17:56:29 +01:00
|
|
|
domainToCrossSigningKeys := make(map[string]map[string]struct{})
|
2020-07-15 18:40:41 +01:00
|
|
|
for userID, deviceIDs := range req.UserToDevices {
|
|
|
|
_, serverName, err := gomatrixserverlib.SplitID('@', userID)
|
|
|
|
if err != nil {
|
|
|
|
continue // ignore invalid users
|
|
|
|
}
|
|
|
|
domain := string(serverName)
|
|
|
|
// query local devices
|
2023-02-20 13:58:03 +00:00
|
|
|
if a.Config.Matrix.IsLocalServerName(serverName) {
|
|
|
|
deviceKeys, err := a.KeyDatabase.DeviceKeysForUser(ctx, userID, deviceIDs, false)
|
2020-07-15 18:40:41 +01:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("failed to query local device keys: %s", err),
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-07-15 18:40:41 +01:00
|
|
|
}
|
2020-07-22 17:04:57 +01:00
|
|
|
|
|
|
|
// pull out display names after we have the keys so we handle wildcards correctly
|
|
|
|
var dids []string
|
|
|
|
for _, dk := range deviceKeys {
|
|
|
|
dids = append(dids, dk.DeviceID)
|
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
var queryRes api.QueryDeviceInfosResponse
|
|
|
|
err = a.QueryDeviceInfos(ctx, &api.QueryDeviceInfosRequest{
|
2020-07-22 17:04:57 +01:00
|
|
|
DeviceIDs: dids,
|
|
|
|
}, &queryRes)
|
|
|
|
if err != nil {
|
|
|
|
util.GetLogger(ctx).Warnf("Failed to QueryDeviceInfos for device IDs, display names will be missing")
|
|
|
|
}
|
|
|
|
|
2020-07-15 18:40:41 +01:00
|
|
|
if res.DeviceKeys[userID] == nil {
|
|
|
|
res.DeviceKeys[userID] = make(map[string]json.RawMessage)
|
|
|
|
}
|
|
|
|
for _, dk := range deviceKeys {
|
2020-07-31 14:40:45 +01:00
|
|
|
if len(dk.KeyJSON) == 0 {
|
|
|
|
continue // don't include blank keys
|
|
|
|
}
|
2020-08-07 17:32:13 +01:00
|
|
|
// inject display name if known (either locally or remotely)
|
|
|
|
displayName := dk.DisplayName
|
|
|
|
if queryRes.DeviceInfo[dk.DeviceID].DisplayName != "" {
|
|
|
|
displayName = queryRes.DeviceInfo[dk.DeviceID].DisplayName
|
|
|
|
}
|
2020-07-22 17:04:57 +01:00
|
|
|
dk.KeyJSON, _ = sjson.SetBytes(dk.KeyJSON, "unsigned", struct {
|
|
|
|
DisplayName string `json:"device_display_name,omitempty"`
|
2020-08-07 17:32:13 +01:00
|
|
|
}{displayName})
|
2020-07-15 18:40:41 +01:00
|
|
|
res.DeviceKeys[userID][dk.DeviceID] = dk.KeyJSON
|
|
|
|
}
|
|
|
|
} else {
|
2020-07-21 17:46:47 +01:00
|
|
|
domainToDeviceKeys[domain] = make(map[string][]string)
|
|
|
|
domainToDeviceKeys[domain][userID] = append(domainToDeviceKeys[domain][userID], deviceIDs...)
|
2020-07-15 18:40:41 +01:00
|
|
|
}
|
2021-08-04 17:56:29 +01:00
|
|
|
// work out if our cross-signing request for this user was
|
|
|
|
// satisfied, if not add them to the list of things to fetch
|
|
|
|
if _, ok := res.MasterKeys[userID]; !ok {
|
|
|
|
if _, ok := domainToCrossSigningKeys[domain]; !ok {
|
|
|
|
domainToCrossSigningKeys[domain] = make(map[string]struct{})
|
|
|
|
}
|
|
|
|
domainToCrossSigningKeys[domain][userID] = struct{}{}
|
|
|
|
}
|
|
|
|
if _, ok := res.SelfSigningKeys[userID]; !ok {
|
|
|
|
if _, ok := domainToCrossSigningKeys[domain]; !ok {
|
|
|
|
domainToCrossSigningKeys[domain] = make(map[string]struct{})
|
|
|
|
}
|
|
|
|
domainToCrossSigningKeys[domain][userID] = struct{}{}
|
|
|
|
}
|
2020-07-15 18:40:41 +01:00
|
|
|
}
|
2020-08-07 17:32:13 +01:00
|
|
|
|
|
|
|
// attempt to satisfy key queries from the local database first as we should get device updates pushed to us
|
2022-10-19 12:03:12 +01:00
|
|
|
domainToDeviceKeys = a.remoteKeysFromDatabase(ctx, res, &respMu, domainToDeviceKeys)
|
2021-08-06 10:13:35 +01:00
|
|
|
if len(domainToDeviceKeys) > 0 || len(domainToCrossSigningKeys) > 0 {
|
|
|
|
// perform key queries for remote devices
|
|
|
|
a.queryRemoteKeys(ctx, req.Timeout, res, domainToDeviceKeys, domainToCrossSigningKeys)
|
2020-08-07 17:32:13 +01:00
|
|
|
}
|
2020-07-21 17:46:47 +01:00
|
|
|
|
2022-10-24 10:07:50 +01:00
|
|
|
// Now that we've done the potentially expensive work of asking the federation,
|
|
|
|
// try filling the cross-signing keys from the database that we know about.
|
|
|
|
a.crossSigningKeysFromDatabase(ctx, req, res)
|
|
|
|
|
2021-08-06 10:13:35 +01:00
|
|
|
// Finally, append signatures that we know about
|
|
|
|
// TODO: This is horrible because we need to round-trip the signature from
|
|
|
|
// JSON, add the signatures and marshal it again, for some reason?
|
2022-04-22 14:58:24 +01:00
|
|
|
|
|
|
|
for targetUserID, masterKey := range res.MasterKeys {
|
2022-04-28 11:34:19 +01:00
|
|
|
if masterKey.Signatures == nil {
|
|
|
|
masterKey.Signatures = map[string]map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{}
|
|
|
|
}
|
2022-04-22 14:58:24 +01:00
|
|
|
for targetKeyID := range masterKey.Keys {
|
2023-02-20 13:58:03 +00:00
|
|
|
sigMap, err := a.KeyDatabase.CrossSigningSigsForTarget(ctx, req.UserID, targetUserID, targetKeyID)
|
2022-04-22 14:58:24 +01:00
|
|
|
if err != nil {
|
2022-08-03 17:35:17 +01:00
|
|
|
// Stop executing the function if the context was canceled/the deadline was exceeded,
|
|
|
|
// as we can't continue without a valid context.
|
|
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2022-08-03 17:35:17 +01:00
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
logrus.WithError(err).Errorf("a.KeyDatabase.CrossSigningSigsForTarget failed")
|
2022-04-22 14:58:24 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if len(sigMap) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for sourceUserID, forSourceUser := range sigMap {
|
|
|
|
for sourceKeyID, sourceSig := range forSourceUser {
|
|
|
|
if _, ok := masterKey.Signatures[sourceUserID]; !ok {
|
|
|
|
masterKey.Signatures[sourceUserID] = map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{}
|
|
|
|
}
|
|
|
|
masterKey.Signatures[sourceUserID][sourceKeyID] = sourceSig
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for targetUserID, forUserID := range res.DeviceKeys {
|
|
|
|
for targetKeyID, key := range forUserID {
|
2023-02-20 13:58:03 +00:00
|
|
|
sigMap, err := a.KeyDatabase.CrossSigningSigsForTarget(ctx, req.UserID, targetUserID, gomatrixserverlib.KeyID(targetKeyID))
|
2021-08-06 10:13:35 +01:00
|
|
|
if err != nil {
|
2022-08-03 17:35:17 +01:00
|
|
|
// Stop executing the function if the context was canceled/the deadline was exceeded,
|
|
|
|
// as we can't continue without a valid context.
|
|
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2022-08-03 17:35:17 +01:00
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
logrus.WithError(err).Errorf("a.KeyDatabase.CrossSigningSigsForTarget failed")
|
2021-08-06 10:13:35 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if len(sigMap) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
var deviceKey gomatrixserverlib.DeviceKeys
|
|
|
|
if err = json.Unmarshal(key, &deviceKey); err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2022-02-09 12:11:43 +00:00
|
|
|
if deviceKey.Signatures == nil {
|
|
|
|
deviceKey.Signatures = map[string]map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{}
|
|
|
|
}
|
2021-08-06 10:13:35 +01:00
|
|
|
for sourceUserID, forSourceUser := range sigMap {
|
|
|
|
for sourceKeyID, sourceSig := range forSourceUser {
|
2022-02-09 12:11:43 +00:00
|
|
|
if _, ok := deviceKey.Signatures[sourceUserID]; !ok {
|
|
|
|
deviceKey.Signatures[sourceUserID] = map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{}
|
|
|
|
}
|
2021-08-06 10:13:35 +01:00
|
|
|
deviceKey.Signatures[sourceUserID][sourceKeyID] = sourceSig
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if js, err := json.Marshal(deviceKey); err == nil {
|
2022-04-22 14:58:24 +01:00
|
|
|
res.DeviceKeys[targetUserID][targetKeyID] = js
|
2021-08-06 10:13:35 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-08-11 15:29:33 +01:00
|
|
|
return nil
|
2020-07-21 17:46:47 +01:00
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) remoteKeysFromDatabase(
|
2022-10-19 12:03:12 +01:00
|
|
|
ctx context.Context, res *api.QueryKeysResponse, respMu *sync.Mutex, domainToDeviceKeys map[string]map[string][]string,
|
2020-08-07 17:32:13 +01:00
|
|
|
) map[string]map[string][]string {
|
|
|
|
fetchRemote := make(map[string]map[string][]string)
|
|
|
|
for domain, userToDeviceMap := range domainToDeviceKeys {
|
|
|
|
for userID, deviceIDs := range userToDeviceMap {
|
2020-08-12 22:43:02 +01:00
|
|
|
// we can't safely return keys from the db when all devices are requested as we don't
|
2020-08-07 17:32:13 +01:00
|
|
|
// know if one has just been added.
|
2020-08-12 22:43:02 +01:00
|
|
|
if len(deviceIDs) > 0 {
|
2022-10-19 12:03:12 +01:00
|
|
|
err := a.populateResponseWithDeviceKeysFromDatabase(ctx, res, respMu, userID, deviceIDs)
|
2020-08-12 22:43:02 +01:00
|
|
|
if err == nil {
|
|
|
|
continue
|
2020-08-07 17:32:13 +01:00
|
|
|
}
|
2020-08-12 22:43:02 +01:00
|
|
|
util.GetLogger(ctx).WithError(err).Error("populateResponseWithDeviceKeysFromDatabase")
|
2020-08-07 17:32:13 +01:00
|
|
|
}
|
2020-08-12 22:43:02 +01:00
|
|
|
// fetch device lists from remote
|
|
|
|
if _, ok := fetchRemote[domain]; !ok {
|
|
|
|
fetchRemote[domain] = make(map[string][]string)
|
2020-08-07 17:32:13 +01:00
|
|
|
}
|
2020-08-12 22:43:02 +01:00
|
|
|
fetchRemote[domain][userID] = append(fetchRemote[domain][userID], deviceIDs...)
|
|
|
|
|
2020-08-07 17:32:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return fetchRemote
|
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) queryRemoteKeys(
|
2021-08-04 17:56:29 +01:00
|
|
|
ctx context.Context, timeout time.Duration, res *api.QueryKeysResponse,
|
|
|
|
domainToDeviceKeys map[string]map[string][]string, domainToCrossSigningKeys map[string]map[string]struct{},
|
2020-07-21 17:46:47 +01:00
|
|
|
) {
|
|
|
|
resultCh := make(chan *gomatrixserverlib.RespQueryKeys, len(domainToDeviceKeys))
|
|
|
|
// allows us to wait until all federation servers have been poked
|
|
|
|
var wg sync.WaitGroup
|
2020-08-13 16:43:27 +01:00
|
|
|
// mutex for writing directly to res (e.g failures)
|
|
|
|
var respMu sync.Mutex
|
2020-07-21 17:46:47 +01:00
|
|
|
|
2021-08-04 17:56:29 +01:00
|
|
|
domains := map[string]struct{}{}
|
|
|
|
for domain := range domainToDeviceKeys {
|
2023-02-20 13:58:03 +00:00
|
|
|
if a.Config.Matrix.IsLocalServerName(gomatrixserverlib.ServerName(domain)) {
|
2021-08-09 14:35:24 +01:00
|
|
|
continue
|
|
|
|
}
|
2021-08-04 17:56:29 +01:00
|
|
|
domains[domain] = struct{}{}
|
|
|
|
}
|
|
|
|
for domain := range domainToCrossSigningKeys {
|
2023-02-20 13:58:03 +00:00
|
|
|
if a.Config.Matrix.IsLocalServerName(gomatrixserverlib.ServerName(domain)) {
|
2021-08-09 14:35:24 +01:00
|
|
|
continue
|
|
|
|
}
|
2021-08-04 17:56:29 +01:00
|
|
|
domains[domain] = struct{}{}
|
|
|
|
}
|
|
|
|
wg.Add(len(domains))
|
|
|
|
|
2020-07-21 17:46:47 +01:00
|
|
|
// fan out
|
2021-08-04 17:56:29 +01:00
|
|
|
for domain := range domains {
|
|
|
|
go a.queryRemoteKeysOnServer(
|
|
|
|
ctx, domain, domainToDeviceKeys[domain], domainToCrossSigningKeys[domain],
|
|
|
|
&wg, &respMu, timeout, resultCh, res,
|
|
|
|
)
|
2020-07-21 17:46:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close the result channel when the goroutines have quit so the for .. range exits
|
|
|
|
go func() {
|
|
|
|
wg.Wait()
|
|
|
|
close(resultCh)
|
|
|
|
}()
|
|
|
|
|
2022-10-20 16:54:18 +01:00
|
|
|
processResult := func(result *gomatrixserverlib.RespQueryKeys) {
|
|
|
|
respMu.Lock()
|
|
|
|
defer respMu.Unlock()
|
2020-07-21 17:46:47 +01:00
|
|
|
for userID, nest := range result.DeviceKeys {
|
|
|
|
res.DeviceKeys[userID] = make(map[string]json.RawMessage)
|
|
|
|
for deviceID, deviceKey := range nest {
|
|
|
|
keyJSON, err := json.Marshal(deviceKey)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
res.DeviceKeys[userID][deviceID] = keyJSON
|
|
|
|
}
|
|
|
|
}
|
2021-08-04 17:56:29 +01:00
|
|
|
|
|
|
|
for userID, body := range result.MasterKeys {
|
2021-08-09 14:35:24 +01:00
|
|
|
res.MasterKeys[userID] = body
|
2021-08-04 17:56:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
for userID, body := range result.SelfSigningKeys {
|
2021-08-09 14:35:24 +01:00
|
|
|
res.SelfSigningKeys[userID] = body
|
2021-08-04 17:56:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: do we want to persist these somewhere now
|
|
|
|
// that we have fetched them?
|
2020-07-21 17:46:47 +01:00
|
|
|
}
|
2022-10-20 16:54:18 +01:00
|
|
|
|
|
|
|
for result := range resultCh {
|
|
|
|
processResult(result)
|
|
|
|
}
|
2020-07-13 16:02:35 +01:00
|
|
|
}
|
2020-07-14 12:59:07 +01:00
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) queryRemoteKeysOnServer(
|
2021-08-04 17:56:29 +01:00
|
|
|
ctx context.Context, serverName string, devKeys map[string][]string, crossSigningKeys map[string]struct{},
|
|
|
|
wg *sync.WaitGroup, respMu *sync.Mutex, timeout time.Duration, resultCh chan<- *gomatrixserverlib.RespQueryKeys,
|
2020-08-13 16:43:27 +01:00
|
|
|
res *api.QueryKeysResponse,
|
|
|
|
) {
|
|
|
|
defer wg.Done()
|
2021-08-09 14:35:24 +01:00
|
|
|
fedCtx := ctx
|
|
|
|
if timeout > 0 {
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
fedCtx, cancel = context.WithTimeout(ctx, timeout)
|
|
|
|
defer cancel()
|
|
|
|
}
|
2020-08-13 16:43:27 +01:00
|
|
|
// for users who we do not have any knowledge about, try to start doing device list updates for them
|
|
|
|
// by hitting /users/devices - otherwise fallback to /keys/query which has nicer bulk properties but
|
|
|
|
// lack a stream ID.
|
2021-08-04 17:56:29 +01:00
|
|
|
userIDsForAllDevices := map[string]struct{}{}
|
2020-08-13 16:43:27 +01:00
|
|
|
for userID, deviceIDs := range devKeys {
|
|
|
|
if len(deviceIDs) == 0 {
|
2021-08-04 17:56:29 +01:00
|
|
|
userIDsForAllDevices[userID] = struct{}{}
|
2020-08-13 16:43:27 +01:00
|
|
|
}
|
|
|
|
}
|
2021-08-04 17:56:29 +01:00
|
|
|
// for cross-signing keys, it's probably easier just to hit /keys/query if we aren't already doing
|
|
|
|
// a device list update, so we'll populate those back into the /keys/query list if not
|
|
|
|
for userID := range crossSigningKeys {
|
|
|
|
if devKeys == nil {
|
|
|
|
devKeys = map[string][]string{}
|
|
|
|
}
|
|
|
|
if _, ok := userIDsForAllDevices[userID]; !ok {
|
|
|
|
devKeys[userID] = []string{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for userID := range userIDsForAllDevices {
|
2020-08-13 16:43:27 +01:00
|
|
|
err := a.Updater.ManualUpdate(context.Background(), gomatrixserverlib.ServerName(serverName), userID)
|
|
|
|
if err != nil {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
logrus.ErrorKey: err,
|
|
|
|
"user_id": userID,
|
|
|
|
"server": serverName,
|
|
|
|
}).Error("Failed to manually update device lists for user")
|
|
|
|
// try to do it via /keys/query
|
|
|
|
devKeys[userID] = []string{}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// refresh entries from DB: unlike remoteKeysFromDatabase we know we previously had no device info for this
|
|
|
|
// user so the fact that we're populating all devices here isn't a problem so long as we have devices.
|
2022-10-19 12:03:12 +01:00
|
|
|
err = a.populateResponseWithDeviceKeysFromDatabase(ctx, res, respMu, userID, nil)
|
2020-08-13 16:43:27 +01:00
|
|
|
if err != nil {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
logrus.ErrorKey: err,
|
|
|
|
"user_id": userID,
|
|
|
|
"server": serverName,
|
|
|
|
}).Error("Failed to manually update device lists for user")
|
|
|
|
// try to do it via /keys/query
|
|
|
|
devKeys[userID] = []string{}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(devKeys) == 0 {
|
|
|
|
return
|
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
queryKeysResp, err := a.FedClient.QueryKeys(fedCtx, a.Config.Matrix.ServerName, gomatrixserverlib.ServerName(serverName), devKeys)
|
2020-08-13 16:43:27 +01:00
|
|
|
if err == nil {
|
|
|
|
resultCh <- &queryKeysResp
|
|
|
|
return
|
|
|
|
}
|
|
|
|
respMu.Lock()
|
|
|
|
res.Failures[serverName] = map[string]interface{}{
|
|
|
|
"message": err.Error(),
|
|
|
|
}
|
2022-10-19 12:27:34 +01:00
|
|
|
respMu.Unlock()
|
2020-08-13 16:43:27 +01:00
|
|
|
|
|
|
|
// last ditch, use the cache only. This is good for when clients hit /keys/query and the remote server
|
|
|
|
// is down, better to return something than nothing at all. Clients can know about the failure by
|
|
|
|
// inspecting the failures map though so they can know it's a cached response.
|
|
|
|
for userID, dkeys := range devKeys {
|
|
|
|
// drop the error as it's already a failure at this point
|
2022-10-19 12:03:12 +01:00
|
|
|
_ = a.populateResponseWithDeviceKeysFromDatabase(ctx, res, respMu, userID, dkeys)
|
2020-08-13 16:43:27 +01:00
|
|
|
}
|
2022-02-16 16:56:45 +00:00
|
|
|
|
|
|
|
// Sytest expects no failures, if we still could retrieve keys, e.g. from local cache
|
2022-10-19 12:27:34 +01:00
|
|
|
respMu.Lock()
|
2022-02-16 16:56:45 +00:00
|
|
|
if len(res.DeviceKeys) > 0 {
|
|
|
|
delete(res.Failures, serverName)
|
|
|
|
}
|
2020-08-13 16:43:27 +01:00
|
|
|
respMu.Unlock()
|
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) populateResponseWithDeviceKeysFromDatabase(
|
2022-10-19 12:03:12 +01:00
|
|
|
ctx context.Context, res *api.QueryKeysResponse, respMu *sync.Mutex, userID string, deviceIDs []string,
|
2020-08-12 22:43:02 +01:00
|
|
|
) error {
|
2023-02-20 13:58:03 +00:00
|
|
|
keys, err := a.KeyDatabase.DeviceKeysForUser(ctx, userID, deviceIDs, false)
|
2020-08-12 22:43:02 +01:00
|
|
|
// if we can't query the db or there are fewer keys than requested, fetch from remote.
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("DeviceKeysForUser %s %v failed: %w", userID, deviceIDs, err)
|
|
|
|
}
|
|
|
|
if len(keys) < len(deviceIDs) {
|
|
|
|
return fmt.Errorf("DeviceKeysForUser %s returned fewer devices than requested, falling back to remote", userID)
|
|
|
|
}
|
|
|
|
if len(deviceIDs) == 0 && len(keys) == 0 {
|
|
|
|
return fmt.Errorf("DeviceKeysForUser %s returned no keys but wanted all keys, falling back to remote", userID)
|
|
|
|
}
|
2022-10-19 12:03:12 +01:00
|
|
|
respMu.Lock()
|
2020-08-12 22:43:02 +01:00
|
|
|
if res.DeviceKeys[userID] == nil {
|
|
|
|
res.DeviceKeys[userID] = make(map[string]json.RawMessage)
|
|
|
|
}
|
2022-10-19 12:03:12 +01:00
|
|
|
respMu.Unlock()
|
2020-08-12 22:43:02 +01:00
|
|
|
|
|
|
|
for _, key := range keys {
|
|
|
|
if len(key.KeyJSON) == 0 {
|
|
|
|
continue // ignore deleted keys
|
|
|
|
}
|
|
|
|
// inject the display name
|
|
|
|
key.KeyJSON, _ = sjson.SetBytes(key.KeyJSON, "unsigned", struct {
|
|
|
|
DisplayName string `json:"device_display_name,omitempty"`
|
|
|
|
}{key.DisplayName})
|
2022-10-19 12:03:12 +01:00
|
|
|
respMu.Lock()
|
2020-08-12 22:43:02 +01:00
|
|
|
res.DeviceKeys[userID][key.DeviceID] = key.KeyJSON
|
2022-10-19 12:03:12 +01:00
|
|
|
respMu.Unlock()
|
2020-08-12 22:43:02 +01:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) uploadLocalDeviceKeys(ctx context.Context, req *api.PerformUploadKeysRequest, res *api.PerformUploadKeysResponse) {
|
2022-02-18 11:31:05 +00:00
|
|
|
// get a list of devices from the user API that actually exist, as
|
|
|
|
// we won't store keys for devices that don't exist
|
2023-02-20 13:58:03 +00:00
|
|
|
uapidevices := &api.QueryDevicesResponse{}
|
|
|
|
if err := a.QueryDevices(ctx, &api.QueryDevicesRequest{UserID: req.UserID}, uapidevices); err != nil {
|
2022-02-18 11:31:05 +00:00
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: err.Error(),
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !uapidevices.UserExists {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("user %q does not exist", req.UserID),
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
existingDeviceMap := make(map[string]struct{}, len(uapidevices.Devices))
|
|
|
|
for _, key := range uapidevices.Devices {
|
|
|
|
existingDeviceMap[key.ID] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get all of the user existing device keys so we can check for changes.
|
2023-02-20 13:58:03 +00:00
|
|
|
existingKeys, err := a.KeyDatabase.DeviceKeysForUser(ctx, req.UserID, nil, true)
|
2022-02-18 11:31:05 +00:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("failed to query existing device keys: %s", err.Error()),
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Work out whether we have device keys in the keyserver for devices that
|
|
|
|
// no longer exist in the user API. This is mostly an exercise to ensure
|
|
|
|
// that we keep some integrity between the two.
|
|
|
|
var toClean []gomatrixserverlib.KeyID
|
|
|
|
for _, k := range existingKeys {
|
|
|
|
if _, ok := existingDeviceMap[k.DeviceID]; !ok {
|
|
|
|
toClean = append(toClean, gomatrixserverlib.KeyID(k.DeviceID))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(toClean) > 0 {
|
2023-02-20 13:58:03 +00:00
|
|
|
if err = a.KeyDatabase.DeleteDeviceKeys(ctx, req.UserID, toClean); err != nil {
|
2022-02-18 11:32:45 +00:00
|
|
|
logrus.WithField("user_id", req.UserID).WithError(err).Errorf("Failed to clean up %d stale keyserver device key entries", len(toClean))
|
|
|
|
} else {
|
|
|
|
logrus.WithField("user_id", req.UserID).Debugf("Cleaned up %d stale keyserver device key entries", len(toClean))
|
2022-02-18 11:31:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-03 17:07:06 +01:00
|
|
|
var keysToStore []api.DeviceMessage
|
2020-07-30 18:00:56 +01:00
|
|
|
|
2020-08-12 22:43:02 +01:00
|
|
|
if req.OnlyDisplayNameUpdates {
|
2022-04-29 16:02:55 +01:00
|
|
|
for _, existingKey := range existingKeys {
|
|
|
|
for _, newKey := range req.DeviceKeys {
|
|
|
|
switch {
|
|
|
|
case existingKey.UserID != newKey.UserID:
|
|
|
|
continue
|
|
|
|
case existingKey.DeviceID != newKey.DeviceID:
|
|
|
|
continue
|
|
|
|
case existingKey.DisplayName != newKey.DisplayName:
|
|
|
|
existingKey.DisplayName = newKey.DisplayName
|
|
|
|
}
|
|
|
|
}
|
|
|
|
keysToStore = append(keysToStore, existingKey)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// assert that the user ID / device ID are not lying for each key
|
|
|
|
for _, key := range req.DeviceKeys {
|
|
|
|
var serverName gomatrixserverlib.ServerName
|
|
|
|
_, serverName, err = gomatrixserverlib.SplitID('@', key.UserID)
|
|
|
|
if err != nil {
|
|
|
|
continue // ignore invalid users
|
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
if !a.Config.Matrix.IsLocalServerName(serverName) {
|
2022-04-29 16:02:55 +01:00
|
|
|
continue // ignore remote users
|
|
|
|
}
|
|
|
|
if len(key.KeyJSON) == 0 {
|
|
|
|
keysToStore = append(keysToStore, key.WithStreamID(0))
|
|
|
|
continue // deleted keys don't need sanity checking
|
|
|
|
}
|
|
|
|
// check that the device in question actually exists in the user
|
|
|
|
// API before we try and store a key for it
|
|
|
|
if _, ok := existingDeviceMap[key.DeviceID]; !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
gotUserID := gjson.GetBytes(key.KeyJSON, "user_id").Str
|
|
|
|
gotDeviceID := gjson.GetBytes(key.KeyJSON, "device_id").Str
|
|
|
|
if gotUserID == key.UserID && gotDeviceID == key.DeviceID {
|
|
|
|
keysToStore = append(keysToStore, key.WithStreamID(0))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
res.KeyError(key.UserID, key.DeviceID, &api.KeyError{
|
|
|
|
Err: fmt.Sprintf(
|
|
|
|
"user_id or device_id mismatch: users: %s - %s, devices: %s - %s",
|
|
|
|
gotUserID, key.UserID, gotDeviceID, key.DeviceID,
|
|
|
|
),
|
|
|
|
})
|
|
|
|
}
|
2020-08-12 22:43:02 +01:00
|
|
|
}
|
2022-04-25 14:22:46 +01:00
|
|
|
|
2020-07-14 12:59:07 +01:00
|
|
|
// store the device keys and emit changes
|
2023-02-20 13:58:03 +00:00
|
|
|
err = a.KeyDatabase.StoreLocalDeviceKeys(ctx, keysToStore)
|
2020-08-03 17:07:06 +01:00
|
|
|
if err != nil {
|
2020-07-14 12:59:07 +01:00
|
|
|
res.Error = &api.KeyError{
|
2020-07-15 12:02:34 +01:00
|
|
|
Err: fmt.Sprintf("failed to store device keys: %s", err.Error()),
|
2020-07-14 12:59:07 +01:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
err = emitDeviceKeyChanges(a.KeyChangeProducer, existingKeys, keysToStore, req.OnlyDisplayNameUpdates)
|
2020-07-23 16:41:36 +01:00
|
|
|
if err != nil {
|
|
|
|
util.GetLogger(ctx).Errorf("Failed to emitDeviceKeyChanges: %s", err)
|
|
|
|
}
|
2020-07-14 12:59:07 +01:00
|
|
|
}
|
|
|
|
|
2023-02-20 13:58:03 +00:00
|
|
|
func (a *UserInternalAPI) uploadOneTimeKeys(ctx context.Context, req *api.PerformUploadKeysRequest, res *api.PerformUploadKeysResponse) {
|
2021-03-02 11:40:20 +00:00
|
|
|
if req.UserID == "" {
|
|
|
|
res.Error = &api.KeyError{
|
|
|
|
Err: "user ID missing",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if req.DeviceID != "" && len(req.OneTimeKeys) == 0 {
|
2023-02-20 13:58:03 +00:00
|
|
|
counts, err := a.KeyDatabase.OneTimeKeysCount(ctx, req.UserID, req.DeviceID)
|
2021-03-02 11:40:20 +00:00
|
|
|
if err != nil {
|
|
|
|
res.Error = &api.KeyError{
|
2023-02-20 13:58:03 +00:00
|
|
|
Err: fmt.Sprintf("a.KeyDatabase.OneTimeKeysCount: %s", err),
|
2021-03-02 11:40:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if counts != nil {
|
|
|
|
res.OneTimeKeyCounts = append(res.OneTimeKeyCounts, *counts)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2020-07-14 12:59:07 +01:00
|
|
|
for _, key := range req.OneTimeKeys {
|
|
|
|
// grab existing keys based on (user/device/algorithm/key ID)
|
|
|
|
keyIDsWithAlgorithms := make([]string, len(key.KeyJSON))
|
|
|
|
i := 0
|
|
|
|
for keyIDWithAlgo := range key.KeyJSON {
|
|
|
|
keyIDsWithAlgorithms[i] = keyIDWithAlgo
|
|
|
|
i++
|
|
|
|
}
|
2023-02-20 13:58:03 +00:00
|
|
|
existingKeys, err := a.KeyDatabase.ExistingOneTimeKeys(ctx, req.UserID, req.DeviceID, keyIDsWithAlgorithms)
|
2020-07-14 12:59:07 +01:00
|
|
|
if err != nil {
|
2021-03-02 11:40:20 +00:00
|
|
|
res.KeyError(req.UserID, req.DeviceID, &api.KeyError{
|
2020-07-15 12:02:34 +01:00
|
|
|
Err: "failed to query existing one-time keys: " + err.Error(),
|
2020-07-14 12:59:07 +01:00
|
|
|
})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for keyIDWithAlgo := range existingKeys {
|
|
|
|
// if keys exist and the JSON doesn't match, error out as the key already exists
|
|
|
|
if !bytes.Equal(existingKeys[keyIDWithAlgo], key.KeyJSON[keyIDWithAlgo]) {
|
2021-03-02 11:40:20 +00:00
|
|
|
res.KeyError(req.UserID, req.DeviceID, &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("%s device %s: algorithm / key ID %s one-time key already exists", req.UserID, req.DeviceID, keyIDWithAlgo),
|
2020-07-14 12:59:07 +01:00
|
|
|
})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// store one-time keys
|
2023-02-20 13:58:03 +00:00
|
|
|
counts, err := a.KeyDatabase.StoreOneTimeKeys(ctx, key)
|
2020-07-15 12:02:34 +01:00
|
|
|
if err != nil {
|
2021-03-02 11:40:20 +00:00
|
|
|
res.KeyError(req.UserID, req.DeviceID, &api.KeyError{
|
|
|
|
Err: fmt.Sprintf("%s device %s : failed to store one-time keys: %s", req.UserID, req.DeviceID, err.Error()),
|
2020-07-14 12:59:07 +01:00
|
|
|
})
|
2020-07-15 12:02:34 +01:00
|
|
|
continue
|
2020-07-14 12:59:07 +01:00
|
|
|
}
|
2020-07-15 12:02:34 +01:00
|
|
|
// collect counts
|
|
|
|
res.OneTimeKeyCounts = append(res.OneTimeKeyCounts, *counts)
|
2020-07-14 12:59:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-02-22 16:34:53 +00:00
|
|
|
func emitDeviceKeyChanges(producer KeyChangeProducer, existing, new []api.DeviceMessage, onlyUpdateDisplayName bool) error {
|
|
|
|
// if we only want to update the display names, we can skip the checks below
|
|
|
|
if onlyUpdateDisplayName {
|
|
|
|
return producer.ProduceKeyChanges(new)
|
|
|
|
}
|
2020-07-23 16:41:36 +01:00
|
|
|
// find keys in new that are not in existing
|
2020-08-03 17:07:06 +01:00
|
|
|
var keysAdded []api.DeviceMessage
|
2020-07-23 16:41:36 +01:00
|
|
|
for _, newKey := range new {
|
|
|
|
exists := false
|
|
|
|
for _, existingKey := range existing {
|
2020-07-30 18:00:56 +01:00
|
|
|
// Do not treat the absence of keys as equal, or else we will not emit key changes
|
|
|
|
// when users delete devices which never had a key to begin with as both KeyJSONs are nil.
|
2022-02-22 15:43:17 +00:00
|
|
|
if existingKey.DeviceKeysEqual(&newKey) {
|
2020-07-23 16:41:36 +01:00
|
|
|
exists = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !exists {
|
|
|
|
keysAdded = append(keysAdded, newKey)
|
|
|
|
}
|
|
|
|
}
|
2020-08-18 11:14:20 +01:00
|
|
|
return producer.ProduceKeyChanges(keysAdded)
|
2020-07-14 12:59:07 +01:00
|
|
|
}
|