LCOV - code coverage report
Current view: top level - foo/src/jamidht - account_manager.h (source / functions) Hit Total Coverage
Test: jami-coverage-filtered.info Lines: 14 24 58.3 %
Date: 2025-12-18 10:07:43 Functions: 5 14 35.7 %

          Line data    Source code
       1             : /*
       2             :  *  Copyright (C) 2004-2025 Savoir-faire Linux Inc.
       3             :  *
       4             :  *  This program is free software: you can redistribute it and/or modify
       5             :  *  it under the terms of the GNU General Public License as published by
       6             :  *  the Free Software Foundation, either version 3 of the License, or
       7             :  *  (at your option) any later version.
       8             :  *
       9             :  *  This program is distributed in the hope that it will be useful,
      10             :  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
      12             :  *  GNU General Public License for more details.
      13             :  *
      14             :  *  You should have received a copy of the GNU General Public License
      15             :  *  along with this program. If not, see <https://www.gnu.org/licenses/>.
      16             :  */
      17             : #pragma once
      18             : 
      19             : #ifdef HAVE_CONFIG_H
      20             : #include "config.h"
      21             : #endif
      22             : 
      23             : #include "contact_list.h"
      24             : #include "logger.h"
      25             : #include "namedirectory.h"
      26             : 
      27             : #include <opendht/crypto.h>
      28             : #include <optional>
      29             : #include <functional>
      30             : #include <map>
      31             : #include <string>
      32             : #include <filesystem>
      33             : 
      34             : #include <dhtnet/multiplexed_socket.h>
      35             : 
      36             : namespace dht {
      37             : class DhtRunner;
      38             : }
      39             : 
      40             : namespace jami {
      41             : 
      42             : using DeviceId = dht::PkId;
      43             : struct AccountArchive;
      44             : class AuthChannelHandler;
      45             : 
      46             : struct AccountInfo
      47             : {
      48             :     dht::crypto::Identity identity;
      49             :     std::unique_ptr<ContactList> contacts;
      50             :     std::string accountId;
      51             :     std::string deviceId;
      52             :     std::shared_ptr<dht::crypto::PublicKey> devicePk;
      53             :     std::shared_ptr<dht::Value> announce;
      54             :     std::string ethAccount;
      55             :     std::string username;
      56             : 
      57             :     std::string displayName;
      58             :     std::string photo;
      59             : };
      60             : 
      61             : template<typename To, typename From>
      62             : std::unique_ptr<To>
      63         776 : dynamic_unique_cast(std::unique_ptr<From>&& p)
      64             : {
      65         776 :     if (auto cast = dynamic_cast<To*>(p.get())) {
      66         776 :         std::unique_ptr<To> result(cast);
      67         776 :         p.release();
      68         776 :         return result;
      69         776 :     }
      70           0 :     return {};
      71             : }
      72             : 
      73             : class AccountManager : public std::enable_shared_from_this<AccountManager>
      74             : {
      75             : public:
      76             :     using OnChangeCallback = ContactList::OnChangeCallback;
      77             :     using clock = std::chrono::system_clock;
      78             :     using time_point = clock::time_point;
      79             :     using OnNewDeviceCb = std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>;
      80             :     using OnDeviceAnnouncedCb = std::function<void()>;
      81             : 
      82         792 :     AccountManager(const std::string& accountId, const std::filesystem::path& path, const std::string& nameServer)
      83        1584 :         : accountId_(accountId)
      84         792 :         , path_(path)
      85        1584 :         , nameDir_(NameDirectory::instance(nameServer)) {};
      86             : 
      87             :     virtual ~AccountManager();
      88             : 
      89             :     constexpr static const char* const DHT_TYPE_NS = "cx.ring";
      90             : 
      91             :     // Auth
      92             : 
      93             :     enum class AuthError { UNKNOWN, INVALID_ARGUMENTS, SERVER_ERROR, NETWORK };
      94             : 
      95             :     using AuthSuccessCallback = std::function<void(const AccountInfo& info,
      96             :                                                    const std::map<std::string, std::string>& config,
      97             :                                                    std::string&& receipt,
      98             :                                                    std::vector<uint8_t>&& receipt_signature)>;
      99             : 
     100             :     using AuthFailureCallback = std::function<void(AuthError error, const std::string& message)>;
     101             :     using DeviceSyncCallback = std::function<void(DeviceSync&& syncData)>;
     102             :     using CertRequest = std::future<std::unique_ptr<dht::crypto::CertificateRequest>>;
     103             :     using PrivateKey = std::shared_future<std::shared_ptr<dht::crypto::PrivateKey>>;
     104             : 
     105             :     CertRequest buildRequest(PrivateKey fDeviceKey);
     106             : 
     107             :     struct AccountCredentials
     108             :     {
     109             :         std::string scheme;
     110             :         std::string uri;
     111             :         std::string password_scheme;
     112             :         std::string password;
     113         772 :         virtual ~AccountCredentials() {};
     114             :     };
     115             : 
     116             :     virtual void initAuthentication(PrivateKey request,
     117             :                                     std::string deviceName,
     118             :                                     std::unique_ptr<AccountCredentials> credentials,
     119             :                                     AuthSuccessCallback onSuccess,
     120             :                                     AuthFailureCallback onFailure,
     121             :                                     const OnChangeCallback& onChange)
     122             :         = 0;
     123             : 
     124             :     virtual bool changePassword(const std::string& password_old, const std::string& password_new) = 0;
     125             : 
     126             :     virtual void syncDevices() = 0;
     127             :     virtual void onSyncData(DeviceSync&& device, bool checkDevice = true);
     128             : 
     129           0 :     virtual bool isPasswordValid(const std::string& /*password*/) { return false; };
     130           0 :     virtual std::vector<uint8_t> getPasswordKey(const std::string& /*password*/) { return {}; };
     131             : 
     132             :     dht::crypto::Identity loadIdentity(const std::string& crt_path,
     133             :                                        const std::string& key_path,
     134             :                                        const std::string& key_pwd) const;
     135             : 
     136             :     const AccountInfo* useIdentity(const dht::crypto::Identity& id,
     137             :                                    const std::string& receipt,
     138             :                                    const std::vector<uint8_t>& receiptSignature,
     139             :                                    const std::string& username,
     140             :                                    const OnChangeCallback& onChange);
     141             : 
     142         691 :     void setDht(const std::shared_ptr<dht::DhtRunner>& dht) { dht_ = dht; }
     143             : 
     144             :     virtual void startSync(const OnNewDeviceCb& cb, const OnDeviceAnnouncedCb& dcb, bool publishPresence = true);
     145             : 
     146       70754 :     const AccountInfo* getInfo() const { return info_.get(); }
     147             : 
     148             :     void reloadContacts();
     149             : 
     150             :     // Device management
     151             : 
     152             :     enum class AddDeviceError { INVALID_URI = -1, ALREADY_LINKING = -2, GENERIC = -3 };
     153             : 
     154             :     enum class RevokeDeviceResult {
     155             :         SUCCESS = 0,
     156             :         ERROR_CREDENTIALS,
     157             :         ERROR_NETWORK,
     158             :     };
     159             : 
     160             :     using RevokeDeviceCallback = std::function<void(RevokeDeviceResult)>;
     161             : 
     162             :     /**
     163             :      * Initiates the process of adding a new device to the account
     164             :      * @param uri The URI provided by the new device to be added
     165             :      * @param auth_scheme The auth scheme (currently only "password" is expected)
     166             :      * @param chanel
     167             :      * @return A positive operation ID if successful, or a negative value indicating an AddDeviceError:
     168             :      *         - INVALID_URI (-1): The provided URI is invalid
     169             :      *         - ALREADY_LINKING (-2): A device linking operation is already in progress
     170             :      *         - GENERIC (-3): A generic error occurred during the process
     171             :      */
     172           0 :     virtual int32_t addDevice(const std::string& /*uri*/, std::string_view /*auth_scheme*/, AuthChannelHandler*)
     173             :     {
     174           0 :         return 0;
     175             :     };
     176           0 :     virtual bool cancelAddDevice(uint32_t /*token*/) { return false; };
     177           0 :     virtual bool confirmAddDevice(uint32_t /*token*/) { return false; };
     178           0 :     virtual bool revokeDevice(const std::string& /*device*/,
     179             :                               std::string_view /*scheme*/,
     180             :                               const std::string& /*password*/,
     181             :                               RevokeDeviceCallback)
     182             :     {
     183           0 :         return false;
     184             :     };
     185             : 
     186             :     const std::map<dht::PkId, KnownDevice>& getKnownDevices() const;
     187             :     bool foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
     188             :                             const std::string& name = {},
     189        1147 :                             const time_point& last_sync = time_point::min());
     190             :     // bool removeAccountDevice(const dht::InfoHash& device);
     191             :     void setAccountDeviceName(/*const dht::InfoHash& device,  */ const std::string& name);
     192             :     std::string getAccountDeviceName() const;
     193             : 
     194             :     void forEachDevice(const dht::InfoHash& to,
     195             :                        std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op,
     196             :                        std::function<void(bool)>&& end = {});
     197             : 
     198             :     using PeerCertificateCb
     199             :         = std::function<void(const std::shared_ptr<dht::crypto::Certificate>& crt, const dht::InfoHash& peer_account)>;
     200             :     void onPeerMessage(const dht::crypto::PublicKey& peer_device, bool allowPublic, PeerCertificateCb&& cb);
     201             :     bool onPeerCertificate(const std::shared_ptr<dht::crypto::Certificate>& crt,
     202             :                            bool allowPublic,
     203             :                            dht::InfoHash& account_id);
     204             : 
     205             :     /**
     206             :      * Inform that a potential peer device have been found.
     207             :      * Returns true only if the device certificate is a valid device certificate.
     208             :      * In that case (true is returned) the account_id parameter is set to the peer account ID.
     209             :      */
     210             :     static bool foundPeerDevice(const std::string& accoundId,
     211             :                                 const std::shared_ptr<dht::crypto::Certificate>& crt,
     212             :                                 dht::InfoHash& account_id);
     213             : 
     214             :     // Contact requests
     215             : 
     216             :     std::vector<std::map<std::string, std::string>> getTrustRequests() const;
     217             :     // Note: includeConversation used for compatibility test, do not use if not in test env.
     218             :     bool acceptTrustRequest(const std::string& from, bool includeConversation = true);
     219             :     bool discardTrustRequest(const std::string& from);
     220             : 
     221             :     void sendTrustRequest(const std::string& to, const std::string& convId, const std::vector<uint8_t>& payload);
     222             :     void sendTrustRequestConfirm(const dht::InfoHash& to,
     223             :                                  const std::string& conversationId); // TODO ideally no convId here
     224             : 
     225             :     // Contact
     226             : 
     227             :     /**
     228             :      * Add contact to the account contact list.
     229             :      * Set confirmed if we know the contact also added us.
     230             :      */
     231             :     bool addContact(const dht::InfoHash& uri, bool confirmed = false, const std::string& conversationId = "");
     232             :     void removeContact(const std::string& uri, bool banned = true);
     233             :     void removeContactConversation(const std::string& uri); // for non swarm contacts
     234             :     void updateContactConversation(const std::string& uri, const std::string& convId, bool added = false);
     235             :     std::map<dht::InfoHash, Contact> getContacts(bool includeRemoved = false) const;
     236             : 
     237             :     /** Obtain details about one account contact in serializable form. */
     238             :     std::map<std::string, std::string> getContactDetails(const std::string& uri) const;
     239             :     std::optional<Contact> getContactInfo(const std::string& uri) const;
     240             : 
     241             :     virtual bool findCertificate(const dht::InfoHash& h,
     242             :                                  std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
     243             : 
     244             :     virtual bool findCertificate(const dht::PkId& h,
     245             :                                  std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
     246             : 
     247             :     bool setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status);
     248             :     bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
     249             :                               dhtnet::tls::TrustStore::PermissionStatus status,
     250             :                               bool local = true);
     251             :     std::vector<std::string> getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status);
     252             :     dhtnet::tls::TrustStore::PermissionStatus getCertificateStatus(const std::string& cert_id) const;
     253             :     bool isAllowed(const crypto::Certificate& crt, bool allowPublic = false);
     254             : 
     255             :     static std::shared_ptr<dht::Value> parseAnnounce(const std::string& announceBase64,
     256             :                                                      const std::string& accountId,
     257             :                                                      const std::string& deviceSha1,
     258             :                                                      const std::string& deviceSha256);
     259             : 
     260             :     // Name resolver
     261             :     using LookupCallback = NameDirectory::LookupCallback;
     262             :     using SearchResult = NameDirectory::SearchResult;
     263             :     using SearchCallback = NameDirectory::SearchCallback;
     264             :     using RegistrationCallback = NameDirectory::RegistrationCallback;
     265             :     using SearchResponse = NameDirectory::Response;
     266             : 
     267             :     virtual void lookupUri(const std::string& name, const std::string& defaultServer, LookupCallback cb);
     268             :     virtual void lookupAddress(const std::string& address, LookupCallback cb);
     269           0 :     virtual bool searchUser(const std::string& /*query*/, SearchCallback /*cb*/) { return false; }
     270             :     virtual void registerName(const std::string& name,
     271             :                               std::string_view scheme,
     272             :                               const std::string& password,
     273             :                               RegistrationCallback cb)
     274             :         = 0;
     275             : 
     276             :     dhtnet::tls::CertificateStore& certStore() const;
     277             : 
     278             : protected:
     279             :     const std::string accountId_;
     280             :     const std::filesystem::path path_;
     281             :     OnChangeCallback onChange_;
     282             :     std::unique_ptr<AccountInfo> info_;
     283             :     std::shared_ptr<dht::DhtRunner> dht_;
     284             :     std::reference_wrapper<NameDirectory> nameDir_;
     285             : };
     286             : 
     287             : } // namespace jami

Generated by: LCOV version 1.14