| 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 | "fmt" |
| 11 | |
| 12 | "maunium.net/go/mautrix" |
| 13 | "maunium.net/go/mautrix/id" |
| 14 | ) |
| 15 | |
| 16 | type CrossSigningPublicKeysCache struct { |
| 17 | MasterKey id.Ed25519 |
| 18 | SelfSigningKey id.Ed25519 |
| 19 | UserSigningKey id.Ed25519 |
| 20 | } |
| 21 | |
| 22 | func (mach *OlmMachine) GetOwnCrossSigningPublicKeys() *CrossSigningPublicKeysCache { |
| 23 | if mach.crossSigningPubkeys != nil { |
| 24 | return mach.crossSigningPubkeys |
| 25 | } |
| 26 | if mach.CrossSigningKeys != nil { |
| 27 | mach.crossSigningPubkeys = mach.CrossSigningKeys.PublicKeys() |
| 28 | return mach.crossSigningPubkeys |
| 29 | } |
| 30 | cspk, err := mach.GetCrossSigningPublicKeys(mach.Client.UserID) |
| 31 | if err != nil { |
| 32 | mach.Log.Error("Failed to get own cross-signing public keys: %v", err) |
| 33 | return nil |
| 34 | } |
| 35 | mach.crossSigningPubkeys = cspk |
| 36 | return mach.crossSigningPubkeys |
| 37 | } |
| 38 | |
| 39 | func (mach *OlmMachine) GetCrossSigningPublicKeys(userID id.UserID) (*CrossSigningPublicKeysCache, error) { |
| 40 | dbKeys, err := mach.CryptoStore.GetCrossSigningKeys(userID) |
| 41 | if err != nil { |
| 42 | return nil, fmt.Errorf("failed to get keys from database: %w", err) |
| 43 | } |
| 44 | if len(dbKeys) > 0 { |
| 45 | masterKey, ok := dbKeys[id.XSUsageMaster] |
| 46 | if ok { |
| 47 | selfSigning, _ := dbKeys[id.XSUsageSelfSigning] |
| 48 | userSigning, _ := dbKeys[id.XSUsageUserSigning] |
| 49 | return &CrossSigningPublicKeysCache{ |
| 50 | MasterKey: masterKey, |
| 51 | SelfSigningKey: selfSigning, |
| 52 | UserSigningKey: userSigning, |
| 53 | }, nil |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | keys, err := mach.Client.QueryKeys(&mautrix.ReqQueryKeys{ |
| 58 | DeviceKeys: mautrix.DeviceKeysRequest{ |
| 59 | userID: mautrix.DeviceIDList{}, |
| 60 | }, |
| 61 | }) |
| 62 | if err != nil { |
| 63 | return nil, fmt.Errorf("failed to query keys: %w", err) |
| 64 | } |
| 65 | |
| 66 | var cspk CrossSigningPublicKeysCache |
| 67 | |
| 68 | masterKeys, ok := keys.MasterKeys[userID] |
| 69 | if !ok { |
| 70 | return nil, nil |
| 71 | } |
| 72 | cspk.MasterKey = masterKeys.FirstKey() |
| 73 | |
| 74 | selfSigningKeys, ok := keys.SelfSigningKeys[userID] |
| 75 | if !ok { |
| 76 | return nil, nil |
| 77 | } |
| 78 | cspk.SelfSigningKey = selfSigningKeys.FirstKey() |
| 79 | |
| 80 | userSigningKeys, ok := keys.UserSigningKeys[userID] |
| 81 | if ok { |
| 82 | cspk.UserSigningKey = userSigningKeys.FirstKey() |
| 83 | } |
| 84 | return &cspk, nil |
| 85 | } |