Fix issues found by clang-tidy and some more 49/311149/3
authorKrzysztof Malysa <k.malysa@samsung.com>
Tue, 14 May 2024 14:28:42 +0000 (16:28 +0200)
committerKrzysztof Malysa <k.malysa@samsung.com>
Thu, 16 May 2024 12:06:46 +0000 (14:06 +0200)
Change-Id: I19b208e147910f3c82dbbdcc6b2d3a8c937412a1

69 files changed:
srcs/base64.cpp
srcs/bluetooth_advert.cpp
srcs/bluetooth_advert.h
srcs/cbor_encoding.cpp
srcs/cbor_encoding.h
srcs/cbor_parsing.cpp
srcs/cbor_parsing.h
srcs/common.h
srcs/crypto/common.h
srcs/crypto/ec_key.cpp
srcs/crypto/ec_key.h
srcs/crypto/encryptor.cpp
srcs/crypto/hkdf.cpp
srcs/crypto/hmac.cpp
srcs/crypto/noise/noise.cpp
srcs/crypto/openssl_error.h
srcs/crypto/random.cpp
srcs/crypto/random.h
srcs/crypto/symmetric_key.cpp
srcs/ctap_message_processor.cpp
srcs/derive_key.cpp
srcs/derive_key.h
srcs/encrypted_tunnel.cpp
srcs/exception.h
srcs/handshake.cpp
srcs/handshake.h
srcs/log/abstract_log_provider.cpp
srcs/log/abstract_log_provider.h
srcs/log/dlog_log_provider.cpp
srcs/log/dlog_log_provider.h
srcs/log/log.h
srcs/message.cpp
srcs/qr_code_shower.cpp
srcs/qr_transaction.cpp
srcs/qr_transaction.h
srcs/request_handler.cpp
srcs/request_handler.h
srcs/state_assisted_transaction.cpp
srcs/state_assisted_transaction.h
srcs/tunnel.cpp
srcs/tunnel.h
srcs/tunnel_server_domain.cpp
srcs/websockets.cpp
srcs/websockets.h
tests/base64_tests.cpp
tests/bluetooth_tests.cpp
tests/buffer.h
tests/buffer_view.h
tests/cbor_tests.cpp
tests/crypto/hkdf_unittest.cpp
tests/crypto/noise/noise_unittest.cpp
tests/ctap_message_processor_tests.cpp
tests/derive_key_tests.cpp
tests/encrypted_tunnel_tests.cpp
tests/handshake_tests.cpp
tests/man_tests.cpp
tests/message_tests.cpp
tests/qr_code_shower_tests.cpp
tests/qr_transaction_tests.cpp
tests/request_handler_tests.cpp
tests/state_assisted_transaction_tests.cpp
tests/test_cancel_from_the_other_thread.h
tests/transaction_test.h
tests/tunnel/auto_tests.cpp
tests/tunnel/auto_tests.h
tests/tunnel/common_tests.cpp
tests/tunnel/manual_tests.cpp
tests/tunnel/manual_tests.h
tests/turn_bluetooth.cpp

index 71c78286a7929ee963518b75571558b780d8764b..03d4705153f851872befe930f991d826f9740a73 100644 (file)
 
 std::string Base64UrlEncode(BufferView buff)
 {
-    size_t len = (buff.size() + 2) / 3 * 4;
+    const size_t len = (buff.size() + 2) / 3 * 4;
     std::string res(len, '\0');
-    [[maybe_unused]] auto outLen =
-        EVP_EncodeBlock(reinterpret_cast<uint8_t *>(res.data()), buff.data(), buff.size());
+    [[maybe_unused]] auto outLen = EVP_EncodeBlock(
+        reinterpret_cast<uint8_t *>(res.data()), buff.data(), static_cast<int>(buff.size()));
     assert(len == static_cast<size_t>(outLen));
     // Remove padding
     res.resize((buff.size() * 4 + 2) / 3);
index aeb9b9652ca494ab3b95a3eb25be8b9e19df0409..c4b278bcb50829893ecb51ce743f632f594cfe76 100644 (file)
@@ -39,7 +39,7 @@ int Bluetooth::Initialize() noexcept
         return ret;
 
     m_initalized = true;
-    m_mainloop = g_main_loop_new(NULL, FALSE);
+    m_mainloop = g_main_loop_new(nullptr, FALSE);
     return BT_ERROR_NONE;
 }
 
@@ -261,7 +261,8 @@ int Bluetooth::Deinitialize() noexcept
 Bluetooth::~Bluetooth()
 {
     if (m_initalized) {
-        int err = Deinitialize();
+        const int err = Bluetooth::Deinitialize(); // Call like this to make it clear that
+                                                   // non-virtual method is called from destructor.
         if (err != BT_ERROR_NONE)
             TRY_LOG_ERROR("Bluetooth deinitialization error: " << BtErrorToString(err));
     }
@@ -285,7 +286,7 @@ void BtAdvertScanner::AwaitAdvert(const CryptoBuffer &eidKey, CryptoBuffer &decr
         THROW_UNKNOWN("Bluetooth initialization error: " << BtErrorToString(err));
 
     auto btDeinitialize = [this] {
-        int err2 = m_bluetooth->Deinitialize();
+        const int err2 = m_bluetooth->Deinitialize();
         if (err2 != BT_ERROR_NONE)
             THROW_UNKNOWN("Bluetooth deinitialization error: " << BtErrorToString(err2));
     };
index 9d4a917620479f15a03d31eda9010f78a303dad2..bc355093d599592706ef9f7dd2a5a558aa596bd5 100644 (file)
@@ -98,7 +98,7 @@ public:
 
     [[nodiscard]] int Deinitialize() noexcept override;
 
-    ~Bluetooth();
+    ~Bluetooth() override;
 
 private:
     bool m_initalized = false;
index 5ba634f13e1f8c379e398fe4da908e7aca922fe4..905cabea5db27f23970b4f670c89523743b4af5e 100644 (file)
@@ -15,7 +15,6 @@
  */
 
 #include "cbor_encoding.h"
-#include "crypto/random.h"
 #include "exception.h"
 #include "log/log.h"
 #include "lowercase_hex_string_of.h"
 #include <iomanip>
 #include <sstream>
 
-using namespace std;
-
 namespace CborEncoding {
 
 namespace {
 
-string DigitEncode(const CryptoBuffer &cbor)
+std::string DigitEncode(const CryptoBuffer &cbor)
 {
     constexpr size_t chunkSize = 7;
-    size_t chunkDigits = 17;
+    int chunkDigits = 17;
     const int partialChunkDigits = 0x0fda8530;
 
     size_t remaining = cbor.size();
-    stringstream encoded;
+    std::stringstream encoded;
 
     while (remaining > 0) {
         uint64_t chunk = 0;
@@ -55,7 +52,7 @@ string DigitEncode(const CryptoBuffer &cbor)
             remaining = 0;
         }
         val = le64toh(chunk);
-        encoded << setw(chunkDigits) << setfill('0') << val;
+        encoded << std::setw(chunkDigits) << std::setfill('0') << val;
     }
     return encoded.str();
 }
@@ -65,7 +62,7 @@ string DigitEncode(const CryptoBuffer &cbor)
 int64_t Cbor::getEpoch() const
 {
     auto now = std::chrono::system_clock::now().time_since_epoch();
-    int64_t epoch = std::chrono::duration_cast<std::chrono::seconds>(now).count();
+    const int64_t epoch = std::chrono::duration_cast<std::chrono::seconds>(now).count();
     return epoch;
 }
 
@@ -79,10 +76,8 @@ void Cbor::EncodeQRContents(const CryptoBuffer &publicKey,
                             const CryptoBuffer &qrSecret,
                             const Hint &hint,
                             bool stateAssisted,
-                            string &fidoUri)
+                            std::string &fidoUri)
 {
-    using namespace Exception;
-
     size_t buffSize = 73; // epoch is int64 which may take up to 8B (9B with key) in CBOR
     size_t mapElements = 6;
     CryptoBuffer buffer(buffSize, 0);
@@ -93,10 +88,10 @@ void Cbor::EncodeQRContents(const CryptoBuffer &publicKey,
     // Integer value < 24 uses only one byte, larger value use more bytes
     if (ASSIGNED_TUNNEL_SERVER_DOMAINS.size() >= 24) {
         LogError("larger encoding needed!");
-        throw EncodingFailed{};
+        throw Exception::EncodingFailed{};
     }
 
-    bool extraKey = getGrease();
+    const bool extraKey = getGrease();
     if (extraKey) {
         ++mapElements;
         buffSize += 4;
@@ -131,11 +126,11 @@ void Cbor::EncodeQRContents(const CryptoBuffer &publicKey,
     LogDebug("QR code contents encoded: " << fidoUri);
 }
 
-void Container::CloseContainer(const CborEncoder &mapEncoder) noexcept
+void Container::CloseContainer(const CborEncoder &containerEncoder) noexcept
 {
     assert(m_appendingToChild);
 
-    CborError err = cbor_encoder_close_container(&m_encoder, &mapEncoder);
+    const CborError err = cbor_encoder_close_container(&m_encoder, &containerEncoder);
     if (err != CborNoError)
         TRY_LOG_ERROR("cbor_encoder_close_container() failed with " << static_cast<int>(err));
 
@@ -169,7 +164,7 @@ void Container::AppendInt64(int64_t value)
 {
     assert(!m_appendingToChild);
 
-    CborError err = cbor_encode_int(&m_encoder, value);
+    const CborError err = cbor_encode_int(&m_encoder, value);
     if (err != CborNoError)
         THROW_ENCODING("cbor_encode_int() failed with " << static_cast<int>(err));
 }
@@ -178,7 +173,7 @@ void Container::AppendByteString(const Buffer &value)
 {
     assert(!m_appendingToChild);
 
-    CborError err = cbor_encode_byte_string(&m_encoder, value.data(), value.size());
+    const CborError err = cbor_encode_byte_string(&m_encoder, value.data(), value.size());
     if (err != CborNoError)
         THROW_ENCODING("cbor_encode_byte_string() failed with " << static_cast<int>(err));
 }
@@ -190,7 +185,7 @@ void Container::AppendByteString(const wauthn_const_buffer_s &value)
     if (!value.data && value.size != 0)
         THROW_INVALID_PARAM("Data is NULL but size is not 0");
 
-    CborError err = cbor_encode_byte_string(&m_encoder, value.data, value.size);
+    const CborError err = cbor_encode_byte_string(&m_encoder, value.data, value.size);
     if (err != CborNoError)
         THROW_ENCODING("cbor_encode_byte_string() failed with " << static_cast<int>(err));
 }
@@ -199,7 +194,7 @@ void Container::AppendBoolean(bool value)
 {
     assert(!m_appendingToChild);
 
-    CborError err = cbor_encode_boolean(&m_encoder, value);
+    const CborError err = cbor_encode_boolean(&m_encoder, value);
     if (err != CborNoError)
         THROW_ENCODING("cbor_encode_boolean() failed with " << static_cast<int>(err));
 }
@@ -209,7 +204,7 @@ Container Container::OpenArray(size_t elements)
     assert(!m_appendingToChild);
 
     CborEncoder arrayEncoder;
-    CborError err = cbor_encoder_create_array(&m_encoder, &arrayEncoder, elements);
+    const CborError err = cbor_encoder_create_array(&m_encoder, &arrayEncoder, elements);
     if (err != CborNoError)
         THROW_ENCODING("cbor_encoder_create_array() failed with " << static_cast<int>(err));
 
@@ -222,12 +217,12 @@ SortedMap Container::OpenMap(size_t elements)
     assert(!m_appendingToChild);
 
     CborEncoder mapEncoder;
-    CborError err = cbor_encoder_create_map(&m_encoder, &mapEncoder, elements);
+    const CborError err = cbor_encoder_create_map(&m_encoder, &mapEncoder, elements);
     if (err != CborNoError)
         THROW_ENCODING("cbor_encoder_create_map() failed with " << static_cast<int>(err));
 
     m_appendingToChild = true;
-    return SortedMap(std::move(mapEncoder), this);
+    return SortedMap{std::move(mapEncoder), this};
 }
 
 Container::~Container()
@@ -316,7 +311,7 @@ Encoder Encoder::Create(uint8_t *output, size_t size)
         THROW_UNKNOWN("NULL output buffer");
     CborEncoder encoder;
     cbor_encoder_init(&encoder, output, size, 0);
-    return Encoder(std::move(encoder), output);
+    return {std::move(encoder), output};
 }
 
 size_t Encoder::GetBufferSize() const { return cbor_encoder_get_buffer_size(&m_encoder, m_output); }
index 5195578f6344cfafa228917bd0b0aac83738648a..48a09665463faeb07aa3812d2cab0946137a6cf5 100644 (file)
@@ -43,15 +43,15 @@ public:
                           std::string &fidoUri);
 
 protected:
-    virtual int64_t getEpoch() const;
-    virtual bool getGrease() const;
+    [[nodiscard]] virtual int64_t getEpoch() const;
+    [[nodiscard]] virtual bool getGrease() const;
 };
 
 class SortedMap;
 
 class Container {
 public:
-    Container(CborEncoder &&encoder, Container *parent = nullptr)
+    explicit Container(CborEncoder &&encoder, Container *parent = nullptr)
     : m_encoder(std::move(encoder)), m_parent(parent)
     {
     }
@@ -86,7 +86,7 @@ private:
 // const char * is for dealing with const char * arguments, since std::string_view may not be
 // sufficient if a nullptr is passed (it can lead to Segfault of the program); std::string_view can
 // handle both std::string and std::string_view arguments
-typedef std::variant<int64_t, const char *, std::string_view> Key;
+using Key = std::variant<int64_t, const char *, std::string_view>;
 
 class SortedMap : protected Container {
 public:
@@ -109,7 +109,7 @@ private:
 class Encoder : public Container {
 public:
     static Encoder Create(uint8_t *output, size_t size);
-    size_t GetBufferSize() const;
+    [[nodiscard]] size_t GetBufferSize() const;
 
 private:
     Encoder(CborEncoder &&encoder, uint8_t *output)
index d449e58105ed6958bd9b745c82c5b38a812afce0..6db2f2ae6866276001213df5f1ed02fd0467107e 100644 (file)
@@ -29,7 +29,7 @@ namespace CborParsing {
 
 const Key CURRENT_KEY;
 
-Container::Container(Container &&other)
+Container::Container(Container &&other) noexcept
 : m_it(std::move(other.m_it)),
   m_length(other.m_length),
   m_parsingChild(std::exchange(other.m_parsingChild, false)),
@@ -37,7 +37,7 @@ Container::Container(Container &&other)
 {
 }
 
-Container &Container::operator=(Container &&other)
+Container &Container::operator=(Container &&other) noexcept
 {
     if (this != &other) {
         m_parent = std::exchange(other.m_parent, nullptr);
@@ -70,7 +70,7 @@ SortedMap Container::EnterMap()
 {
     assert(!m_parsingChild);
 
-    CborType type = cbor_value_get_type(&m_it);
+    const CborType type = cbor_value_get_type(&m_it);
     if (type != CborMapType)
         THROW_UNKNOWN("Expected map type, got " << static_cast<int>(type));
 
@@ -85,14 +85,14 @@ SortedMap Container::EnterMap()
         THROW_UNKNOWN("cbor_value_enter_container failed with " << static_cast<int>(err));
 
     m_parsingChild = true;
-    return SortedMap(std::move(mapIt), this, length);
+    return SortedMap{std::move(mapIt), this, length};
 }
 
 Container Container::EnterArray()
 {
     assert(!m_parsingChild);
 
-    CborType type = cbor_value_get_type(&m_it);
+    const CborType type = cbor_value_get_type(&m_it);
     if (type != CborArrayType)
         THROW_UNKNOWN("Expected array type, got " << static_cast<int>(type));
 
@@ -239,7 +239,7 @@ bool SortedMap::LocateKey(const Key &key)
         if (std::holds_alternative<int64_t>(key)) {
             auto intKey = std::get<int64_t>(key);
             try {
-                int64_t tmpKey = GetInt64();
+                const int64_t tmpKey = GetInt64();
                 if (tmpKey > intKey)
                     return restoreIt(); // bigger key found
                 if (tmpKey == intKey)
@@ -258,7 +258,7 @@ bool SortedMap::LocateKey(const Key &key)
                 return std::string_view{std::get<const char *>(key)};
             }();
             try {
-                std::string tmpKey = GetTextString();
+                const std::string tmpKey = GetTextString();
                 if (tmpKey.size() > strKey.size() ||
                     (tmpKey.size() == strKey.size() && tmpKey > strKey))
                     return restoreIt(); // bigger key found
@@ -271,10 +271,10 @@ bool SortedMap::LocateKey(const Key &key)
             if (m_it.type == CborIntegerType || m_it.type == CborTextStringType) {
                 Advance(); // skip key
                 return true;
-            } else
-                THROW_UNKNOWN("Unsupported key type");
+            }
+            THROW_UNKNOWN("Unsupported key type");
         } else {
-            THROW_UNKNOWN("Unexpeceted variant type");
+            THROW_UNKNOWN("Unexpected variant type");
         }
         Advance(); // skip value
     }
@@ -351,7 +351,8 @@ KeyCopy SortedMap::PeekKey()
             THROW_UNKNOWN("cbor_value_get_int64_checked failed with " << static_cast<int>(err));
 
         return value;
-    } else if (cbor_value_is_text_string(&m_it)) {
+    }
+    if (cbor_value_is_text_string(&m_it)) {
         size_t length;
         err = cbor_value_get_string_length(&m_it, &length);
         if (err != CborNoError)
@@ -392,7 +393,7 @@ Parser Parser::Create(const uint8_t *input, size_t size)
     if (err != CborNoError)
         THROW_UNKNOWN("CBOR validation failed with " << static_cast<int>(err));
 
-    return Parser(std::move(parser), std::move(root));
+    return {std::move(parser), std::move(root)};
 }
 
 } // namespace CborParsing
index 3d8572125a51da8424758248c1155cf3a4161983..210ae65b88f91bde88d029347901d334c0f81f31 100644 (file)
@@ -29,8 +29,10 @@ class SortedMap;
 
 class Container {
 public:
-    Container(Container &&other);
-    Container &operator=(Container &&other);
+    Container(Container &&other) noexcept;
+    Container(const Container &) = delete;
+    Container &operator=(const Container &) = delete;
+    Container &operator=(Container &&other) noexcept;
     virtual ~Container();
 
     SortedMap EnterMap();
@@ -42,10 +44,10 @@ public:
     bool GetBoolean();
     uint64_t GetUint64();
 
-    size_t Length() const { return m_length; }
+    [[nodiscard]] size_t Length() const { return m_length; }
 
 protected:
-    Container(CborValue &&it, Container *parent = nullptr, size_t length = 0)
+    explicit Container(CborValue &&it, Container *parent = nullptr, size_t length = 0)
     : m_it(std::move(it)), m_length(length), m_parent(parent)
     {
     }
@@ -53,8 +55,6 @@ protected:
     void Advance();
 
 private:
-    Container(const Container &) = delete;
-    Container &operator=(const Container &) = delete;
     void LeaveContainer(CborValue &childIt) noexcept;
 
 protected:
@@ -69,8 +69,8 @@ private:
 // const char* is for const char* arguments, since string_view is not enough because in case of
 // passing a nullptr it Segfaults the program; std::string_view is for std::string and
 // std::string_view arguments
-typedef std::variant<std::monostate, int64_t, const char *, std::string_view> Key;
-typedef std::variant<int64_t, std::string> KeyCopy;
+using Key = std::variant<std::monostate, int64_t, const char *, std::string_view>;
+using KeyCopy = std::variant<int64_t, std::string>;
 extern const Key CURRENT_KEY;
 
 class SortedMap : protected Container {
@@ -91,7 +91,7 @@ public:
 
     KeyCopy PeekKey();
 
-    size_t Length() const { return m_length; }
+    [[nodiscard]] size_t Length() const { return m_length; }
 };
 
 class Parser : public Container {
index 29c1d7861364d77f8f6e00d856e7963900021235..b6f83589612b6c42b922c523c26dbbd24ea319e1 100644 (file)
@@ -25,7 +25,7 @@
 constexpr size_t QR_SECRET_LEN = 16;
 constexpr size_t BLUETOOTH_ADVERT_LEN = 16;
 
-typedef std::array<char, 2> Hint;
+using Hint = std::array<char, 2>;
 
 template <typename T>
 class OnScopeExit {
@@ -38,5 +38,5 @@ private:
     T m_cleanupFn;
 };
 
-typedef std::vector<uint8_t> Buffer;
-typedef std::basic_string_view<uint8_t> BufferView;
+using Buffer = std::vector<uint8_t>;
+using BufferView = std::basic_string_view<uint8_t>;
index 88b1cd484b76776dc513cb80c4ccf26094b03926..41a020f45e7150d746ad10f17271a585b4c97d35 100644 (file)
@@ -19,4 +19,4 @@
 #include <cstdint>
 #include <vector>
 
-typedef std::vector<uint8_t> CryptoBuffer;
+using CryptoBuffer = std::vector<uint8_t>;
index 9768bdcb132865948b4f2de0dbf43b85183563a6..e10d03967c49486c6f46aabb0e24e0e8eb16e9f4 100644 (file)
@@ -194,7 +194,7 @@ CryptoBuffer X9_62_P_256_Key::ExportPrivateKey() const
 CryptoBuffer X9_62_P_256_Key::ExportPublicKey(bool compressed) const
 {
     CryptoBuffer res(compressed ? 33 : 65);
-    point_conversion_form_t form =
+    const point_conversion_form_t form =
         compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED;
     size_t buffLen;
     unsigned char *buff = nullptr;
index 68d1d4a39d8262de5913cc2e50c75c2b7a36a5e6..442a2850dccd812420133a6ce6cba35b7423684e 100644 (file)
@@ -40,13 +40,13 @@ public:
     static X9_62_P_256_Key ImportPrivateKey(const CryptoBuffer &input);
     static X9_62_P_256_Key ImportPublicKey(const CryptoBuffer &input);
 
-    CryptoBuffer ExportPrivateKey() const;
-    CryptoBuffer ExportPublicKey(bool compressed) const;
+    [[nodiscard]] CryptoBuffer ExportPrivateKey() const;
+    [[nodiscard]] CryptoBuffer ExportPublicKey(bool compressed) const;
 
-    EVP_PKEY *get() const noexcept { return m_key; }
+    [[nodiscard]] EVP_PKEY *get() const noexcept { return m_key; }
 
 private:
-    explicit X9_62_P_256_Key(EVP_PKEY *key) noexcept { m_key = key; }
+    explicit X9_62_P_256_Key(EVP_PKEY *key) noexcept : m_key{key} {}
 
     EVP_PKEY *m_key = nullptr;
 };
index 7837a2c65168e5faf46a9998da338fe005178bca..50817a4b4419688ab569f50bb8056da3ea091928 100644 (file)
@@ -44,7 +44,8 @@ CryptoBuffer Crypt(bool encrypt, const CryptoBuffer &key, const CryptoBuffer &in
         TRY_LOG_ERROR("EVP_CIPHER_CTX_set_padding() error");
         goto opensslError;
     }
-    if (EVP_CipherUpdate(ctx, output.data(), &len, input.data(), input.size()) != 1) {
+    if (EVP_CipherUpdate(ctx, output.data(), &len, input.data(), static_cast<int>(input.size())) !=
+        1) {
         TRY_LOG_ERROR("EVP_CipherUpdate() error");
         goto opensslError;
     }
@@ -91,7 +92,8 @@ CryptoBuffer EncryptAes256GCM(const CryptoBuffer &key,
     size_t outputLen = 0;
     CryptoBuffer output(plaintext.size() + TAG_LEN);
 
-    if (!(ctx = EVP_CIPHER_CTX_new())) {
+    ctx = EVP_CIPHER_CTX_new();
+    if (!ctx) {
         TRY_LOG_ERROR("EVP_CIPHER_CTX_new() error");
         goto opensslError;
     }
@@ -99,7 +101,8 @@ CryptoBuffer EncryptAes256GCM(const CryptoBuffer &key,
         TRY_LOG_ERROR("EVP_EncryptInit_ex() error");
         goto opensslError;
     }
-    if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.size(), nullptr)) {
+    if (1 !=
+        EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, static_cast<int>(iv.size()), nullptr)) {
         TRY_LOG_ERROR("EVP_CIPHER_CTX_ctrl() error");
         goto opensslError;
     }
@@ -107,12 +110,14 @@ CryptoBuffer EncryptAes256GCM(const CryptoBuffer &key,
         TRY_LOG_ERROR("EVP_EncryptInit_ex() error");
         goto opensslError;
     }
-    if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, aad.data(), aad.size())) {
+    if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, aad.data(), static_cast<int>(aad.size()))) {
         TRY_LOG_ERROR("EVP_EncryptUpdate() error");
         goto opensslError;
     }
 
-    if (1 != EVP_EncryptUpdate(ctx, output.data(), &len, plaintext.data(), plaintext.size())) {
+    if (1 !=
+        EVP_EncryptUpdate(
+            ctx, output.data(), &len, plaintext.data(), static_cast<int>(plaintext.size()))) {
         TRY_LOG_ERROR("EVP_EncryptUpdate() error");
         goto opensslError;
     }
@@ -158,7 +163,8 @@ CryptoBuffer DecryptAes256GCM(const CryptoBuffer &key,
     size_t outputLen = 0;
     CryptoBuffer output(ciphertext.size() - TAG_LEN);
 
-    if (!(ctx = EVP_CIPHER_CTX_new())) {
+    ctx = EVP_CIPHER_CTX_new();
+    if (!ctx) {
         TRY_LOG_ERROR("EVP_CIPHER_CTX_new() error");
         goto opensslError;
     }
@@ -166,7 +172,8 @@ CryptoBuffer DecryptAes256GCM(const CryptoBuffer &key,
         TRY_LOG_ERROR("EVP_DecryptInit_ex() error");
         goto opensslError;
     }
-    if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.size(), nullptr)) {
+    if (1 !=
+        EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, static_cast<int>(iv.size()), nullptr)) {
         TRY_LOG_ERROR("EVP_CIPHER_CTX_ctrl() error");
         goto opensslError;
     }
@@ -174,14 +181,17 @@ CryptoBuffer DecryptAes256GCM(const CryptoBuffer &key,
         TRY_LOG_ERROR("EVP_DecryptInit_ex() error");
         goto opensslError;
     }
-    if (1 != EVP_DecryptUpdate(ctx, nullptr, &len, aad.data(), aad.size())) {
+    if (1 != EVP_DecryptUpdate(ctx, nullptr, &len, aad.data(), static_cast<int>(aad.size()))) {
         TRY_LOG_ERROR("EVP_DecryptUpdate() error");
         goto opensslError;
     }
 
     if (1 !=
-        EVP_DecryptUpdate(
-            ctx, output.data(), &len, ciphertext.data(), ciphertext.size() - TAG_LEN)) {
+        EVP_DecryptUpdate(ctx,
+                          output.data(),
+                          &len,
+                          ciphertext.data(),
+                          static_cast<int>(ciphertext.size()) - TAG_LEN)) {
         TRY_LOG_ERROR("EVP_DecryptUpdate() error");
         goto opensslError;
     }
index 44ac565c05862ad1ad2764950e9ce45a74f9b00d..fdb35333bd2aa6be4497861eed75125dff728a22 100644 (file)
@@ -63,7 +63,8 @@ CryptoBuffer HkdfSha256(const CryptoBuffer &secret,
             TRY_LOG_ERROR("EVP_PKEY_CTX_hkdf_mode() error");
             goto opensslError;
         }
-        if (!HMAC(EVP_sha256(), salt.data(), salt.size(), nullptr, 0, key, &len)) {
+        if (!HMAC(
+                EVP_sha256(), salt.data(), static_cast<int>(salt.size()), nullptr, 0, key, &len)) {
             TRY_LOG_ERROR("HMAC() error");
             goto opensslError;
         }
index d9dc8b8dae0c907c9f1fa29cfb66d59a8caece32..6d922d53246c9c62b812302530798b18bc0b4f91 100644 (file)
@@ -31,7 +31,7 @@ CryptoBuffer HmacSha256(const CryptoBuffer &key, const CryptoBuffer &data)
     unsigned int digestLen;
     if (!HMAC(EVP_sha256(),
               key.data(),
-              key.size(),
+              static_cast<int>(key.size()),
               data.data(),
               data.size(),
               digest.data(),
index d53695009465fd360d19405348b161a01334816d..be00e36956553d9142ebdc3d397983086e638f79 100644 (file)
 #include "crypto/encryptor.h"
 #include "crypto/hkdf.h"
 #include "crypto/noise/noise.h"
-#include "crypto/openssl_error.h"
 #include "crypto/sha2.h"
-#include "log/log.h"
 
-#include <array>
 #include <cassert>
 #include <cstring>
 #include <endian.h>
index d7a6d649703a3a3544dad2ffc3fd5b228cc3ced5..8ee44842d82db44006f9b9fd185a55e7b56c8b04 100644 (file)
@@ -22,7 +22,7 @@ namespace Crypto {
 
 class OpensslError : public std::exception {
 public:
-    const char *what() const noexcept override { return "openssl error"; }
+    [[nodiscard]] const char *what() const noexcept override { return "openssl error"; }
 };
 
 } // namespace Crypto
index 75567e46318af13808539ac339f549e6cc3ae2a2..24e2c156979d15b302b94c1f91bf61dda74e9708 100644 (file)
@@ -27,7 +27,7 @@ CryptoBuffer RandomBytes(size_t bytes)
 {
     CryptoBuffer random(bytes);
 
-    if (RAND_bytes(random.data(), random.size()) <= 0) {
+    if (RAND_bytes(random.data(), static_cast<int>(random.size())) <= 0) {
         LogError("RAND_bytes() error");
         throw OpensslError{};
     }
index 968afb7182fe03bff31852f269fe58ad35ada2fc..b8199ad03f0db0603a9f57876a3f9e9166026f57 100644 (file)
@@ -18,6 +18,8 @@
 
 #include "crypto/common.h"
 
+#include <cstddef>
+
 namespace Crypto {
 
 CryptoBuffer RandomBytes(size_t bytes);
index 99b6acef3570d639bdda236b3cba590897718fa4..644ad029a0fb6041271e92b4cb7ee43f1d4861ca 100644 (file)
@@ -30,7 +30,7 @@ CryptoBuffer GenerateAESKey(size_t keySizeInBits)
 
 CryptoBuffer ImportAESKey(const uint8_t *rawKey, size_t rawKeySize)
 {
-    return CryptoBuffer(rawKey, rawKey + rawKeySize);
+    return {rawKey, rawKey + rawKeySize};
 }
 
 } // namespace Crypto
index f5cde5fc14f5b845ab3224b0d144a51a538e9fc1..5a6ed3d7617f12eb2eb853b789a14cf3a06f484d 100644 (file)
@@ -91,7 +91,7 @@ Result CtapMessageProcessor::DoCommand(const char *commandName,
 
     VerifyRpIdHash(rpId, res.response.m_authData.m_rpIdHash);
 
-    ShutdownMessage shutdown;
+    const ShutdownMessage shutdown;
     Buffer shutdownMsg;
     shutdown.Serialize(shutdownMsg);
     m_encryptedTunnel->WriteBinary(shutdownMsg);
@@ -122,7 +122,7 @@ void CtapMessageProcessor::ProcessFollowingUpdateMsgs(
 void VerifyRpIdHash(const char *rpId, const BufferView &rpIdHash)
 {
     assert(rpId);
-    CryptoBuffer rpIdBuffer(rpId, rpId + strlen(rpId));
+    const CryptoBuffer rpIdBuffer(rpId, rpId + strlen(rpId));
     auto expected = Crypto::Sha256Hash(rpIdBuffer);
     if (BufferView(expected.data(), expected.size()) != rpIdHash)
         THROW_UNKNOWN("RP id hash does not match");
index c584bedf1e50f7973f6655e8d614b7760c0f231e..a54d94beedceb99630147caccb27da74ba76db76 100644 (file)
@@ -22,6 +22,6 @@ CryptoBuffer DeriveKey(const CryptoBuffer &secret,
                        KeyPurpose purpose,
                        size_t derivedKeySize)
 {
-    CryptoBuffer purpose32 = {static_cast<uint8_t>(purpose), 0, 0, 0};
+    const CryptoBuffer purpose32 = {static_cast<uint8_t>(purpose), 0, 0, 0};
     return Crypto::HkdfSha256(secret, salt, purpose32, derivedKeySize);
 }
index fb06f43cb5c284205594292acb0b312e1f0605a3..0ac7fa42c05ce2c20909770f23a7046ef1060b28 100644 (file)
@@ -18,6 +18,9 @@
 
 #include "crypto/common.h"
 
+#include <cstddef>
+#include <cstdint>
+
 constexpr size_t EID_KEY_LEN = 64;
 constexpr size_t TUNNEL_ID_LEN = 16;
 constexpr size_t PSK_LEN = 32;
index b4d31a82ca4ce4085e41ac0b141ab30249d8fdd5..c044cc00e3652dc08695e81ea12e3464135adab3 100644 (file)
@@ -14,6 +14,7 @@
  *  limitations under the License
  */
 
+#include "crypto/common.h"
 #include "encrypted_tunnel.h"
 #include "exception.h"
 
@@ -28,12 +29,12 @@ EncryptedTunnel::EncryptedTunnel(std::unique_ptr<ITunnel> tunnel,
 
 CryptoBuffer EncryptedTunnel::ReadBinary()
 {
-    CryptoBuffer ciphertext = m_tunnel->ReadBinary();
+    const CryptoBuffer ciphertext = m_tunnel->ReadBinary();
     auto msg = m_reader.DecryptWithAd(ciphertext, {});
     if (msg.empty())
         THROW_UNKNOWN("invalid message");
 
-    size_t paddingBytes = msg.back();
+    const size_t paddingBytes = msg.back();
     if (paddingBytes + 1 > msg.size())
         THROW_UNKNOWN("invalid message");
 
@@ -47,7 +48,7 @@ void EncryptedTunnel::WriteBinary(CryptoBuffer msg)
         THROW_UNKNOWN("message too large");
 
     constexpr size_t paddingGranularity = 32;
-    size_t extraBytes = paddingGranularity - msg.size() % paddingGranularity;
+    const size_t extraBytes = paddingGranularity - msg.size() % paddingGranularity;
     msg.resize(msg.size() + extraBytes, 0);
     msg.back() = static_cast<uint8_t>(extraBytes) - 1;
 
index 07b5dcd10b14221e4893ea9575e88388e18872c8..d7670045e0540e4629efc82514068c06ec35334d 100644 (file)
@@ -28,7 +28,7 @@ namespace Exception {
 struct ExceptionBase : public std::runtime_error {
     using std::runtime_error::runtime_error;
 
-    virtual wauthn_error_e Code() const = 0;
+    [[nodiscard]] virtual wauthn_error_e Code() const = 0;
 };
 
 template <wauthn_error_e C>
@@ -40,22 +40,22 @@ struct Exception : public ExceptionBase {
     {
     }
 
-    wauthn_error_e Code() const override { return C; }
+    [[nodiscard]] wauthn_error_e Code() const override { return C; }
 };
 
-typedef Exception<WAUTHN_ERROR_UNKNOWN> Unknown;
-typedef Exception<WAUTHN_ERROR_INVALID_PARAMETER> InvalidParam;
-typedef Exception<WAUTHN_ERROR_PERMISSION_DENIED> PermissionDenied;
-typedef Exception<WAUTHN_ERROR_NOT_SUPPORTED> NotSupported;
-typedef Exception<WAUTHN_ERROR_NOT_ALLOWED> NotAllowed;
-typedef Exception<WAUTHN_ERROR_INVALID_STATE> InvalidState;
-typedef Exception<WAUTHN_ERROR_ENCODING_FAILED> EncodingFailed;
-typedef Exception<WAUTHN_ERROR_SOCKET> SocketError;
-typedef Exception<WAUTHN_ERROR_NO_SUCH_SERVICE> NoSuchService;
-typedef Exception<WAUTHN_ERROR_ACCESS_DENIED> AccessDenied;
-typedef Exception<WAUTHN_ERROR_MEMORY> MemoryError;
-typedef Exception<WAUTHN_ERROR_CANCELLED> Cancelled;
-typedef Exception<WAUTHN_ERROR_TIMEOUT> Timeout;
+using Unknown = Exception<WAUTHN_ERROR_UNKNOWN>;
+using InvalidParam = Exception<WAUTHN_ERROR_INVALID_PARAMETER>;
+using PermissionDenied = Exception<WAUTHN_ERROR_PERMISSION_DENIED>;
+using NotSupported = Exception<WAUTHN_ERROR_NOT_SUPPORTED>;
+using NotAllowed = Exception<WAUTHN_ERROR_NOT_ALLOWED>;
+using InvalidState = Exception<WAUTHN_ERROR_INVALID_STATE>;
+using EncodingFailed = Exception<WAUTHN_ERROR_ENCODING_FAILED>;
+using SocketError = Exception<WAUTHN_ERROR_SOCKET>;
+using NoSuchService = Exception<WAUTHN_ERROR_NO_SUCH_SERVICE>;
+using AccessDenied = Exception<WAUTHN_ERROR_ACCESS_DENIED>;
+using MemoryError = Exception<WAUTHN_ERROR_MEMORY>;
+using Cancelled = Exception<WAUTHN_ERROR_CANCELLED>;
+using Timeout = Exception<WAUTHN_ERROR_TIMEOUT>;
 
 } // namespace Exception
 
index 03b70601816360cce112a2ffec62aef170d84854..782843538af5c9878415ff07e280feedb1fe7720 100644 (file)
@@ -78,7 +78,7 @@ struct ProcessedHandshakeResponse {
 ProcessedHandshakeResponse processHandshakeResponse(const CryptoBuffer &peerHandshakeMessage,
                                                     const Crypto::X9_62_P_256_Key &ephemeralKey,
                                                     const Crypto::X9_62_P_256_Key *privKey,
-                                                    Crypto::Noise::SymmetricState &&noise)
+                                                    Crypto::Noise::SymmetricState &&noise) // NOLINT
 {
     constexpr size_t p256X962Length = 1 + 32 + 32;
     if (peerHandshakeMessage.size() < p256X962Length)
@@ -171,7 +171,8 @@ IHandshake::HandshakeResult Handshake::DoHandshake(const CryptoBuffer &psk,
 
     m_tunnel->WriteBinary(msg); // Should throw if Cancel is already called.
 
-    CryptoBuffer response = m_tunnel->ReadBinary(); // Should throw if Cancel is already called.
+    const CryptoBuffer response =
+        m_tunnel->ReadBinary(); // Should throw if Cancel is already called.
 
     // process response
     auto [splitRes, handshakeHash] =
index 7b82eda8f835a57dd73cad4908a8a3af98d9c5c5..ad5dc430eefedb1f2e414b8c2c588d475038fed7 100644 (file)
@@ -65,16 +65,16 @@ public:
     explicit Handshake(std::unique_ptr<ITunnel> tunnel = std::make_unique<Tunnel>());
 
     // May be called only once. Throws Cancelled on cancel.
-    virtual void QrInitiatedConnect(const std::string &tunnelServerDomain,
-                                    const BufferView &routingId,
-                                    const BufferView &tunnelId) override;
+    void QrInitiatedConnect(const std::string &tunnelServerDomain,
+                            const BufferView &routingId,
+                            const BufferView &tunnelId) override;
 
     HandshakeResult DoQrInitiatedHandshake(const CryptoBuffer &psk,
                                            const Crypto::X9_62_P_256_Key &identityKey) override;
 
-    virtual void StateAssistedConnect(const std::string &tunnelServerDomain,
-                                      const BufferView &contactId,
-                                      const BufferView &clientPayload) override;
+    void StateAssistedConnect(const std::string &tunnelServerDomain,
+                              const BufferView &contactId,
+                              const BufferView &clientPayload) override;
 
     HandshakeResult DoStateAssistedHandshake(const CryptoBuffer &psk,
                                              const CryptoBuffer &peerIdentity) override;
index 475c57a4109d9471cc93d98bbe3f6fd38b48d1e5..daf36dd355979542136a44acaee0475d27843f7d 100644 (file)
@@ -16,7 +16,6 @@
 #include "abstract_log_provider.h"
 
 #include <cstring>
-#include <stddef.h>
 
 namespace Log {
 
@@ -25,7 +24,7 @@ void AbstractLogProvider::SetTag(const char *) {}
 const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
 {
     const char *ptr = strrchr(filename, '/');
-    return ptr != NULL ? ptr + 1 : filename;
+    return ptr != nullptr ? ptr + 1 : filename;
 }
 
 } // namespace Log
index 1216cc4875d8637777c350bc5fc305731d55bd08..211604cc1fffdbfb53c1430a90e6e91b3a805df7 100644 (file)
@@ -28,7 +28,7 @@ public:
         Pedantic
     };
 
-    virtual ~AbstractLogProvider() {}
+    virtual ~AbstractLogProvider() = default;
 
     virtual void SetTag(const char *tag);
 
index afe018c6112465ea0310981eda840c4b6a3f831c..9d3ae69fcd4e95b8ad1c36c436e554e7b3958a3c 100644 (file)
 #include "dlog.h"
 #include "dlog_log_provider.h"
 
+#include <cstddef>
 #include <cstring>
 #include <map>
 #include <sstream>
-#include <stddef.h>
 #include <stdexcept>
 
 namespace Log {
 
 namespace {
-typedef void (*DlogMacro)(const char *, const char *);
+using DlogMacro = void (*)(const char *, const char *);
 
 // I can't map LOG_ values because SLOG uses token concatenation
 void Error(const char *tag, const char *msg) { print_system_log(DLOG_ERROR, tag, "%s", msg); }
@@ -39,7 +39,7 @@ void Debug(const char *tag, const char *msg) { print_system_log(DLOG_DEBUG, tag,
 
 void Pedantic(const char *tag, const char *msg) { print_system_log(DLOG_VERBOSE, tag, "%s", msg); }
 
-std::map<AbstractLogProvider::LogLevel, DlogMacro> dlogMacros = {
+const std::map<AbstractLogProvider::LogLevel, DlogMacro> dlogMacros = {
   // [](const char* tag, const char* msg) { SLOG(LOG_ERROR, tag, "%s", msg); } won't compile
     {AbstractLogProvider::LogLevel::Error,    Error   },
     {AbstractLogProvider::LogLevel::Warning,  Warning },
@@ -50,13 +50,9 @@ std::map<AbstractLogProvider::LogLevel, DlogMacro> dlogMacros = {
 
 } // namespace
 
-DLOGLogProvider::DLOGLogProvider() {}
-
-DLOGLogProvider::~DLOGLogProvider() {}
-
 void DLOGLogProvider::SetTag(const char *tag)
 {
-    size_t size = strlen(tag) + 1;
+    const size_t size = strlen(tag) + 1;
     char *buff = new (std::nothrow) char[size];
 
     if (buff)
index b2a3f2b85189686e1c0b8530bb16521d78703aea..ce54d23b51a3ea6e550765013dd5e87f7eff25ff 100644 (file)
 namespace Log {
 class DLOGLogProvider : public AbstractLogProvider {
 public:
-    DLOGLogProvider();
-    virtual ~DLOGLogProvider();
+    DLOGLogProvider() = default;
 
-    virtual void Log(AbstractLogProvider::LogLevel level,
-                     const char *message,
-                     const char *fileName,
-                     int line,
-                     const char *function) const;
+    void Log(AbstractLogProvider::LogLevel level,
+             const char *message,
+             const char *fileName,
+             int line,
+             const char *function) const override;
 
     // Set global Tag according to DLOG
-    void SetTag(const char *tag);
+    void SetTag(const char *tag) override;
 
 private:
     std::unique_ptr<char[]> m_tag;
index f84bfd726e14174059e29e88cd22fa195b5e0b57..49a4003e2eadc38094146d015cb26021c528b963 100644 (file)
@@ -48,7 +48,7 @@ private:
  */
 class NullStream {
 public:
-    NullStream() {}
+    NullStream() = default;
 
     template <typename T>
     NullStream &operator<<(const T &)
@@ -65,16 +65,16 @@ public:
 //
 
 /* avoid warnings about unused variables */
-#define DPL_MACRO_DUMMY_LOGGING(message, level) \
-    do {                                        \
-        Log::NullStream ns;                     \
-        ns << message;                          \
+#define DPL_MACRO_DUMMY_LOGGING(message, level)                 \
+    do {                                                        \
+        Log::NullStream ns;                                     \
+        ns << message; /* NOLINT(bugprone-macro-parentheses) */ \
     } while (false)
 
 #define DPL_MACRO_FOR_LOGGING(message, level)                                    \
     do {                                                                         \
         std::ostringstream platformLog;                                          \
-        platformLog << message;                                                  \
+        platformLog << message; /* NOLINT(bugprone-macro-parentheses) */         \
         Log::LogSystem::Instance().Log(                                          \
             level, platformLog.str().c_str(), __FILE__, __LINE__, __FUNCTION__); \
     } while (false)
@@ -123,18 +123,18 @@ public:
     } catch (...) {               \
     }
 
-#define ERROR_LOGGED_THROW(exceptionType, msg)              \
-    do {                                                    \
-        std::ostringstream oss;                             \
-        oss << msg;                                         \
-        TRY_LOG_ERROR("Throwing exception: " << oss.str()); \
-        throw exceptionType(oss.str());                     \
+#define ERROR_LOGGED_THROW(exceptionType, msg)               \
+    do {                                                     \
+        std::ostringstream oss;                              \
+        oss << msg; /* NOLINT(bugprone-macro-parentheses) */ \
+        TRY_LOG_ERROR("Throwing exception: " << oss.str());  \
+        throw exceptionType(oss.str());                      \
     } while (false)
 
-#define DEBUG_LOGGED_THROW(exceptionType, msg)              \
-    do {                                                    \
-        std::ostringstream oss;                             \
-        oss << msg;                                         \
-        TRY_LOG_DEBUG("Throwing exception: " << oss.str()); \
-        throw exceptionType(oss.str());                     \
+#define DEBUG_LOGGED_THROW(exceptionType, msg)               \
+    do {                                                     \
+        std::ostringstream oss;                              \
+        oss << msg; /* NOLINT(bugprone-macro-parentheses) */ \
+        TRY_LOG_DEBUG("Throwing exception: " << oss.str());  \
+        throw exceptionType(oss.str());                      \
     } while (false)
index c76acf85257c362c62548eeb6ff3f08ffdb00b49..098a4d1cd28b165c3105d8c0ef1609ee27efb477 100644 (file)
@@ -94,11 +94,11 @@ enum class StatusCode : uint8_t {
     CTAP2_ERR_VENDOR_LAST = 0xFF,     // Vendor specific error.
 };
 
-constexpr int64_t KEY_KTY = 1;
-constexpr int64_t KEY_ALG = 3;
-constexpr int64_t KEY_CRV = -1;
-constexpr int64_t KEY_X = -2;
-constexpr int64_t KEY_Y = -3;
+constexpr inline int64_t KEY_KTY = 1;
+constexpr inline int64_t KEY_ALG = 3;
+constexpr inline int64_t KEY_CRV = -1;
+constexpr inline int64_t KEY_X = -2;
+constexpr inline int64_t KEY_Y = -3;
 
 enum class KeyType : int64_t {
     OKP = 1,
@@ -125,89 +125,89 @@ enum class Curve : int64_t {
     P521 = 3,
 };
 
-constexpr char CREDENTIAL_TYPE_PUBLIC_KEY[] = "public-key";
+constexpr inline char CREDENTIAL_TYPE_PUBLIC_KEY[] = "public-key";
 
-constexpr size_t AAGUID_SIZE = 16;
+constexpr inline size_t AAGUID_SIZE = 16;
 
 // Get Info response
-constexpr int64_t KEY_GI_BUFFER = 0x01;
-constexpr int64_t KEY_GI_RSP_VERSIONS = 0x01;
-constexpr int64_t KEY_GI_RSP_EXTENSIONS = 0x02;
-constexpr int64_t KEY_GI_RSP_AAGUID = 0x03;
-constexpr int64_t KEY_GI_RSP_OPTIONS = 0x04;
-constexpr int64_t KEY_GI_RSP_MAX_MSG_SIZE = 0x05;
-constexpr int64_t KEY_GI_RSP_PIN_UV_AUTH_PROTOCOLS = 0x06;
-constexpr int64_t KEY_GI_RSP_MAX_CREDENTIAL_COUNT_IN_LIST = 0x07;
-constexpr int64_t KEY_GI_RSP_MAX_CREDENTIAL_ID_LENGTH = 0x08;
-constexpr int64_t KEY_GI_RSP_TRANSPORTS = 0x09;
-constexpr int64_t KEY_GI_RSP_ALGORITHMS = 0x0A;
-constexpr int64_t KEY_GI_RSP_MAX_SERIALIZED_LARGE_BLOB_ARRAY = 0x0B;
-constexpr int64_t KEY_GI_RSP_FORCE_PIN_CHANGE = 0x0C;
-constexpr int64_t KEY_GI_RSP_MIN_PIN_LENGTH = 0x0D;
-constexpr int64_t KEY_GI_RSP_FIRMWARE_VERSION = 0x0E;
-constexpr int64_t KEY_GI_RSP_MAX_CRED_BLOB_LENGTH = 0x0F;
-constexpr int64_t KEY_GI_RSP_MAX_RPIDS_FOR_SET_MIN_PIN_LENGTH = 0x10;
-constexpr int64_t KEY_GI_RSP_PREFERRED_PLATFORM_UV_ATTEMPTS = 0x11;
-constexpr int64_t KEY_GI_RSP_UV_MODALITY = 0x12;
-constexpr int64_t KEY_GI_RSP_CERTIFICATIONS = 0x13;
-constexpr int64_t KEY_GI_RSP_REMAINING_DISCOVERABLE_CREDENTIALS = 0x14;
-constexpr int64_t KEY_GI_RSP_VENDOR_PROTOTYPE_CONFIG_COMMANDS = 0x15;
-constexpr int64_t KEY_GI_RSP_ATTESTATION_FORMATS = 0x16;
-constexpr int64_t KEY_GI_RSP_UV_COUNT_SINCE_LAST_PIN_ENTRY = 0x17;
-constexpr int64_t KEY_GI_RSP_LONG_TOUCH_FOR_RESET = 0x18;
+constexpr inline int64_t KEY_GI_BUFFER = 0x01;
+constexpr inline int64_t KEY_GI_RSP_VERSIONS = 0x01;
+constexpr inline int64_t KEY_GI_RSP_EXTENSIONS = 0x02;
+constexpr inline int64_t KEY_GI_RSP_AAGUID = 0x03;
+constexpr inline int64_t KEY_GI_RSP_OPTIONS = 0x04;
+constexpr inline int64_t KEY_GI_RSP_MAX_MSG_SIZE = 0x05;
+constexpr inline int64_t KEY_GI_RSP_PIN_UV_AUTH_PROTOCOLS = 0x06;
+constexpr inline int64_t KEY_GI_RSP_MAX_CREDENTIAL_COUNT_IN_LIST = 0x07;
+constexpr inline int64_t KEY_GI_RSP_MAX_CREDENTIAL_ID_LENGTH = 0x08;
+constexpr inline int64_t KEY_GI_RSP_TRANSPORTS = 0x09;
+constexpr inline int64_t KEY_GI_RSP_ALGORITHMS = 0x0A;
+constexpr inline int64_t KEY_GI_RSP_MAX_SERIALIZED_LARGE_BLOB_ARRAY = 0x0B;
+constexpr inline int64_t KEY_GI_RSP_FORCE_PIN_CHANGE = 0x0C;
+constexpr inline int64_t KEY_GI_RSP_MIN_PIN_LENGTH = 0x0D;
+constexpr inline int64_t KEY_GI_RSP_FIRMWARE_VERSION = 0x0E;
+constexpr inline int64_t KEY_GI_RSP_MAX_CRED_BLOB_LENGTH = 0x0F;
+constexpr inline int64_t KEY_GI_RSP_MAX_RPIDS_FOR_SET_MIN_PIN_LENGTH = 0x10;
+constexpr inline int64_t KEY_GI_RSP_PREFERRED_PLATFORM_UV_ATTEMPTS = 0x11;
+constexpr inline int64_t KEY_GI_RSP_UV_MODALITY = 0x12;
+constexpr inline int64_t KEY_GI_RSP_CERTIFICATIONS = 0x13;
+constexpr inline int64_t KEY_GI_RSP_REMAINING_DISCOVERABLE_CREDENTIALS = 0x14;
+constexpr inline int64_t KEY_GI_RSP_VENDOR_PROTOTYPE_CONFIG_COMMANDS = 0x15;
+constexpr inline int64_t KEY_GI_RSP_ATTESTATION_FORMATS = 0x16;
+constexpr inline int64_t KEY_GI_RSP_UV_COUNT_SINCE_LAST_PIN_ENTRY = 0x17;
+constexpr inline int64_t KEY_GI_RSP_LONG_TOUCH_FOR_RESET = 0x18;
 
 // Make Credential command
-constexpr int64_t KEY_MC_CMD_CLIENT_DATA_HASH = 0x01;
-constexpr int64_t KEY_MC_CMD_RP = 0x02;
-constexpr int64_t KEY_MC_CMD_USER = 0x03;
-constexpr int64_t KEY_MC_CMD_PUB_KEY_CRED_PARAMS = 0x04;
-constexpr int64_t KEY_MC_CMD_EXCLUDE_LIST = 0x05;
-constexpr int64_t KEY_MC_CMD_EXTENSIONS = 0x06;
-constexpr int64_t KEY_MC_CMD_OPTIONS = 0x07;
-constexpr int64_t KEY_MC_CMD_PIN_UV_AUTH_PARAM = 0x08;
-constexpr int64_t KEY_MC_CMD_PIN_UV_AUTH_PROTOCOL = 0x09;
-constexpr int64_t KEY_MC_CMD_ENTERPRISE_ATTESTATION = 0x0A;
-constexpr int64_t KEY_MC_CMD_ATTESTATION_FORMAT_PREFERENCE = 0x0B;
+constexpr inline int64_t KEY_MC_CMD_CLIENT_DATA_HASH = 0x01;
+constexpr inline int64_t KEY_MC_CMD_RP = 0x02;
+constexpr inline int64_t KEY_MC_CMD_USER = 0x03;
+constexpr inline int64_t KEY_MC_CMD_PUB_KEY_CRED_PARAMS = 0x04;
+constexpr inline int64_t KEY_MC_CMD_EXCLUDE_LIST = 0x05;
+constexpr inline int64_t KEY_MC_CMD_EXTENSIONS = 0x06;
+constexpr inline int64_t KEY_MC_CMD_OPTIONS = 0x07;
+// constexpr inline int64_t KEY_MC_CMD_PIN_UV_AUTH_PARAM = 0x08;
+// constexpr inline int64_t KEY_MC_CMD_PIN_UV_AUTH_PROTOCOL = 0x09;
+constexpr inline int64_t KEY_MC_CMD_ENTERPRISE_ATTESTATION = 0x0A;
+constexpr inline int64_t KEY_MC_CMD_ATTESTATION_FORMAT_PREFERENCE = 0x0B;
 
 // Make Credential response
-constexpr int64_t KEY_MC_RSP_FMT = 0x01;
-constexpr int64_t KEY_MC_RSP_AUTH_DATA = 0x02;
-constexpr int64_t KEY_MC_RSP_ATT_STMT = 0x03;
-constexpr int64_t KEY_MC_RSP_EP_ATT = 0x04;
-constexpr int64_t KEY_MC_RSP_LARGE_BLOB_KEY = 0x05;
-constexpr int64_t KEY_MC_RSP_UNSIGNED_EXTENSIONS_OUTPUT = 0x06;
+constexpr inline int64_t KEY_MC_RSP_FMT = 0x01;
+constexpr inline int64_t KEY_MC_RSP_AUTH_DATA = 0x02;
+constexpr inline int64_t KEY_MC_RSP_ATT_STMT = 0x03;
+constexpr inline int64_t KEY_MC_RSP_EP_ATT = 0x04;
+constexpr inline int64_t KEY_MC_RSP_LARGE_BLOB_KEY = 0x05;
+// constexpr inline int64_t KEY_MC_RSP_UNSIGNED_EXTENSIONS_OUTPUT = 0x06;
 
 // Get Assertion command
-constexpr int64_t KEY_GA_CMD_RP_ID = 0x01;
-constexpr int64_t KEY_GA_CMD_CLIENT_DATA_HASH = 0x02;
-constexpr int64_t KEY_GA_CMD_ALLOW_LIST = 0x03;
-constexpr int64_t KEY_GA_CMD_EXTENSIONS = 0x04;
-constexpr int64_t KEY_GA_CMD_OPTIONS = 0x05;
-constexpr int64_t KEY_GA_CMD_PIN_UV_AUTH_PARAM = 0x06;
-constexpr int64_t KEY_GA_CMD_PIN_UV_AUTH_PROTOCOL = 0x07;
-constexpr int64_t KEY_GA_CMD_ENTERPRISE_ATTESTATION = 0x08;
-constexpr int64_t KEY_GA_CMD_ATTESTATION_FORMAT_PREFERENCE = 0x09;
+constexpr inline int64_t KEY_GA_CMD_RP_ID = 0x01;
+constexpr inline int64_t KEY_GA_CMD_CLIENT_DATA_HASH = 0x02;
+constexpr inline int64_t KEY_GA_CMD_ALLOW_LIST = 0x03;
+// constexpr inline int64_t KEY_GA_CMD_EXTENSIONS = 0x04;
+constexpr inline int64_t KEY_GA_CMD_OPTIONS = 0x05;
+// constexpr inline int64_t KEY_GA_CMD_PIN_UV_AUTH_PARAM = 0x06;
+// constexpr inline int64_t KEY_GA_CMD_PIN_UV_AUTH_PROTOCOL = 0x07;
+// constexpr inline int64_t KEY_GA_CMD_ENTERPRISE_ATTESTATION = 0x08;
+// constexpr inline int64_t KEY_GA_CMD_ATTESTATION_FORMAT_PREFERENCE = 0x09;
 
 // Get Assertion response
-constexpr int64_t KEY_GA_RSP_CREDENTIAL = 0x01;
-constexpr int64_t KEY_GA_RSP_AUTH_DATA = 0x02;
-constexpr int64_t KEY_GA_RSP_SIGNATURE = 0x03;
-constexpr int64_t KEY_GA_RSP_USER = 0x04;
-constexpr int64_t KEY_GA_RSP_NUMBER_OF_CREDENTIALS = 0x05;
-constexpr int64_t KEY_GA_RSP_USER_SELECTED = 0x06;
-constexpr int64_t KEY_GA_RSP_LARGE_BLOB_KEY = 0x07;
-constexpr int64_t KEY_GA_RSP_UNSIGNED_EXTENSIONS_OUTPUT = 0x08;
-constexpr int64_t KEY_GA_RSP_EP_ATT = 0x09;
-constexpr int64_t KEY_GA_RSP_ATT_STMT = 0x0A;
+constexpr inline int64_t KEY_GA_RSP_CREDENTIAL = 0x01;
+constexpr inline int64_t KEY_GA_RSP_AUTH_DATA = 0x02;
+constexpr inline int64_t KEY_GA_RSP_SIGNATURE = 0x03;
+constexpr inline int64_t KEY_GA_RSP_USER = 0x04;
+// constexpr inline int64_t KEY_GA_RSP_NUMBER_OF_CREDENTIALS = 0x05;
+// constexpr inline int64_t KEY_GA_RSP_USER_SELECTED = 0x06;
+// constexpr inline int64_t KEY_GA_RSP_LARGE_BLOB_KEY = 0x07;
+// constexpr inline int64_t KEY_GA_RSP_UNSIGNED_EXTENSIONS_OUTPUT = 0x08;
+// constexpr inline int64_t KEY_GA_RSP_EP_ATT = 0x09;
+// constexpr inline int64_t KEY_GA_RSP_ATT_STMT = 0x0A;
 
 // Update message
-constexpr int64_t KEY_UP_LINK_INFO = 0x01;
-constexpr int64_t KEY_UP_CMD_CONTACT_ID = 0x01;
-constexpr int64_t KEY_UP_CMD_LINK_ID = 0x02;
-constexpr int64_t KEY_UP_CMD_LINK_SECRET = 0x03;
-constexpr int64_t KEY_UP_CMD_AUTHENTICATOR_PUBLIC_KEY = 0x04;
-constexpr int64_t KEY_UP_CMD_AUTHENTICATOR_NAME = 0x05;
-constexpr int64_t KEY_UP_CMD_HANDSHAKE_SIGNATURE = 0x06;
+constexpr inline int64_t KEY_UP_LINK_INFO = 0x01;
+constexpr inline int64_t KEY_UP_CMD_CONTACT_ID = 0x01;
+constexpr inline int64_t KEY_UP_CMD_LINK_ID = 0x02;
+constexpr inline int64_t KEY_UP_CMD_LINK_SECRET = 0x03;
+constexpr inline int64_t KEY_UP_CMD_AUTHENTICATOR_PUBLIC_KEY = 0x04;
+constexpr inline int64_t KEY_UP_CMD_AUTHENTICATOR_NAME = 0x05;
+constexpr inline int64_t KEY_UP_CMD_HANDSHAKE_SIGNATURE = 0x06;
 
 void SerializePubkeyCredDescriptors(CborEncoding::SortedMap &map,
                                     const CborEncoding::Key &key,
@@ -289,9 +289,9 @@ CtapCommand::CtapCommand(Method method,
     if (!clientData.client_data_json || !clientData.client_data_json->data)
         THROW_INVALID_PARAM("Missing client data JSON");
 
-    CryptoBuffer clientDataBuffer(clientData.client_data_json->data,
-                                  clientData.client_data_json->data +
-                                      clientData.client_data_json->size);
+    const CryptoBuffer clientDataBuffer(clientData.client_data_json->data,
+                                        clientData.client_data_json->data +
+                                            clientData.client_data_json->size);
 
     m_clientDataHash = Crypto::Sha256Hash(clientDataBuffer);
 }
@@ -317,8 +317,8 @@ void MakeCredentialCommand::Serialize(Buffer &output) const
 
     size_t elements = 0;
 
-    constexpr size_t CBOR_MAX_SIZE = 1024;
-    size_t prefixSize = output.size();
+    static constexpr size_t CBOR_MAX_SIZE = 1024;
+    const size_t prefixSize = output.size();
     output.resize(prefixSize + CBOR_MAX_SIZE);
 
     auto encoder = CborEncoding::Encoder::Create(output.data() + prefixSize, CBOR_MAX_SIZE);
@@ -450,8 +450,8 @@ void MakeCredentialCommand::Serialize(Buffer &output) const
                 if (!format.data)
                     THROW_INVALID_PARAM("Empty attestation format");
 
-                std::string_view formatStr(reinterpret_cast<const char *>(format.data),
-                                           format.size);
+                const std::string_view formatStr(reinterpret_cast<const char *>(format.data),
+                                                 format.size);
                 formatsArray.AppendTextString(formatStr);
             }
         }
@@ -470,8 +470,8 @@ void GetAssertionCommand::Serialize(Buffer &output) const
 {
     CtapCommand::Serialize(output);
 
-    constexpr size_t CBOR_MAX_SIZE = 1024;
-    size_t prefixSize = output.size();
+    static constexpr size_t CBOR_MAX_SIZE = 1024;
+    const size_t prefixSize = output.size();
     output.resize(prefixSize + CBOR_MAX_SIZE);
 
     auto encoder = CborEncoding::Encoder::Create(output.data() + prefixSize, CBOR_MAX_SIZE);
@@ -480,7 +480,7 @@ void GetAssertionCommand::Serialize(Buffer &output) const
         if (m_options.allow_credentials)
             keys++;
 
-        bool uv = (m_options.user_verification == UVR_REQUIRED) ||
+        const bool uv = (m_options.user_verification == UVR_REQUIRED) ||
             (m_options.user_verification == UVR_PREFERRED && m_supportedOptions.uv);
         if (uv)
             keys++;
@@ -521,7 +521,7 @@ void CtapResponse::Deserialize(BufferView &input)
         THROW_UNKNOWN("Incomplete message received");
 
     auto status = static_cast<StatusCode>(input[0]);
-    auto uStatus = static_cast<unsigned short>(status);
+    auto uStatus = static_cast<uint16_t>(status);
     switch (status) {
     case StatusCode::CTAP2_OK: break;
 
@@ -600,10 +600,15 @@ CtapResponse::AuthData::AttestationData::AttestationData(BufferView &attestation
         CborParsing::Parser::Create(attestationDataView.data(), attestationDataView.size());
     auto credentialPublicKeyMap = publicKeyParser.EnterMap();
 
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     auto kty = credentialPublicKeyMap.GetInt64At(KEY_KTY).value(); // Key Type
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     auto alg = credentialPublicKeyMap.GetInt64At(KEY_ALG).value(); // wauthn_cose_algorithm_e
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     auto crv = credentialPublicKeyMap.GetInt64At(KEY_CRV).value(); // Value
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     auto x = credentialPublicKeyMap.GetByteStringAt(KEY_X).value();
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     auto y = credentialPublicKeyMap.GetByteStringAt(KEY_Y).value();
 
     if (static_cast<KeyType>(kty) == KeyType::EC2) {
@@ -636,9 +641,9 @@ CtapResponse::AuthData::AttestationData::AttestationData(BufferView &attestation
         auto cleanupBy = OnScopeExit([&by] { BN_free(by); });
 
         // TODO compressed format
-        if (BN_bin2bn(x.data(), x.size(), bx) == nullptr)
+        if (BN_bin2bn(x.data(), static_cast<int>(x.size()), bx) == nullptr)
             THROW_UNKNOWN("Bignum x creation failed");
-        if (BN_bin2bn(y.data(), y.size(), by) == nullptr)
+        if (BN_bin2bn(y.data(), static_cast<int>(y.size()), by) == nullptr)
             THROW_UNKNOWN("Bignum y creation failed");
 
         auto ecKey = EC_KEY_new_by_curve_name(algInfo->second.nid);
@@ -651,7 +656,7 @@ CtapResponse::AuthData::AttestationData::AttestationData(BufferView &attestation
 
         m_publicKeyDer.resize(200);
         auto publicKeyDerData = m_publicKeyDer.data();
-        int ret = i2d_EC_PUBKEY(ecKey, &publicKeyDerData); // deprecated in 3.0
+        const int ret = i2d_EC_PUBKEY(ecKey, &publicKeyDerData); // deprecated in 3.0
         if (ret < 0)
             THROW_UNKNOWN("i2d_EC_PUBKEY() failed");
 
@@ -709,8 +714,10 @@ void MakeCredentialResponse::Deserialize(BufferView &input)
     auto map = helper.EnterMap();
 
     // "packed", "tpm", "android-key", "android-safetynet", "fido-u2f", "none", "apple"
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     m_format = map.GetTextStringAt(KEY_MC_RSP_FMT).value();
 
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     DeserializeAuthData(map.GetByteStringAt(KEY_MC_RSP_AUTH_DATA).value());
 
     if (!m_authData.m_attestationData.has_value())
@@ -734,10 +741,11 @@ void GetAssertionResponse::Deserialize(BufferView &input)
     auto map = helper.EnterMap();
 
     {
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto credentialMap = map.EnterMapAt(KEY_GA_RSP_CREDENTIAL).value();
-
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         m_credentialId = credentialMap.GetByteStringAt("id").value();
-
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto type = credentialMap.GetTextStringAt("type").value();
         if (type != CREDENTIAL_TYPE_PUBLIC_KEY)
             THROW_UNKNOWN("Unexpected key type: " << type);
@@ -745,16 +753,21 @@ void GetAssertionResponse::Deserialize(BufferView &input)
         // TODO optional transports
     }
 
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     DeserializeAuthData(map.GetByteStringAt(KEY_GA_RSP_AUTH_DATA).value());
 
     if (m_authData.m_attestationData.has_value())
         THROW_UNKNOWN("Unexpected attestation data in Get Assertion response");
 
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     m_signature = map.GetByteStringAt(KEY_GA_RSP_SIGNATURE).value();
 
     if (auto userMap = map.EnterMapAt(KEY_GA_RSP_USER)) {
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         m_userId = userMap->GetByteStringAt("id").value();
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         m_userName = userMap->GetTextStringAt("name").value();
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         m_userDisplayName = userMap->GetTextStringAt("displayName").value();
     }
 
@@ -881,11 +894,17 @@ void UpdateMessage::Deserialize(BufferView &input)
     if (!linkingMap)
         return;
 
-    m_linkData = {linkingMap->GetByteStringAt(KEY_UP_CMD_CONTACT_ID).value(),
+    m_linkData = {// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
+                  linkingMap->GetByteStringAt(KEY_UP_CMD_CONTACT_ID).value(),
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   linkingMap->GetByteStringAt(KEY_UP_CMD_LINK_ID).value(),
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   linkingMap->GetByteStringAt(KEY_UP_CMD_LINK_SECRET).value(),
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   linkingMap->GetByteStringAt(KEY_UP_CMD_AUTHENTICATOR_PUBLIC_KEY).value(),
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   linkingMap->GetTextStringAt(KEY_UP_CMD_AUTHENTICATOR_NAME).value(),
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   linkingMap->GetByteStringAt(KEY_UP_CMD_HANDSHAKE_SIGNATURE).value()};
 
     if (m_linkData->m_linkId.size() != 8)
index 94090815cd78ef786462cc7379e2f30bdd68967a..92f8aa347832fae6a869b078f00422b405be3583 100644 (file)
@@ -26,5 +26,5 @@ void QrCodeShower::ShowQrCode(const CryptoBuffer &qrSecret,
     std::string fidoUri;
     CborEncoding::Cbor cbor;
     cbor.EncodeQRContents(identityKeyCompressed, qrSecret, hint, stateAssisted, fidoUri);
-    qrCodeCallback(std::move(fidoUri));
+    std::move(qrCodeCallback)(std::move(fidoUri));
 }
index bb8fef3ba419324544784dd2607b4aa5ab35744c..1cecd47671d17cc62addc5d3a4b9a2a03bf40686 100644 (file)
@@ -14,8 +14,6 @@
  *  limitations under the License
  */
 
-#include "crypto/ecdh.h"
-#include "crypto/hmac.h"
 #include "crypto/random.h"
 #include "derive_key.h"
 #include "exception.h"
@@ -70,8 +68,8 @@ Result QrTransaction::DoPerformTransaction(
 {
     UpdateStateAndCheckForCancel(State::SHOWING_QR_CODE);
 
-    CryptoBuffer qrSecret = Crypto::RandomBytes(QR_SECRET_LEN);
-    Crypto::X9_62_P_256_Key identityKey = Crypto::X9_62_P_256_Key::Create();
+    const CryptoBuffer qrSecret = Crypto::RandomBytes(QR_SECRET_LEN);
+    const Crypto::X9_62_P_256_Key identityKey = Crypto::X9_62_P_256_Key::Create();
     m_qrCodeShower->ShowQrCode(
         qrSecret, identityKey.ExportPublicKey(true), m_hint, true, std::move(m_qrCodeCallback));
 
@@ -134,8 +132,8 @@ void QrTransaction::Cancel()
 {
     auto guard = std::lock_guard{m_lock};
     switch (m_state) {
-    case State::CANCELLED: break;
-    case State::NOT_IN_PROGRESS: break;
+    case State::CANCELLED:
+    case State::NOT_IN_PROGRESS:
     case State::SHOWING_QR_CODE: break; // Cannot cancel that :(
     case State::AWAITING_BLE_ADVERT: {
         m_btAdvertScanner->Cancel();
index 1e9aa3bc1be0b0a8f00e55d7b7c5e654488e4923..e81e0dfa255b7850f8f21a8b39d1f7d3144f06e6 100644 (file)
@@ -25,6 +25,7 @@
 class IQrTransaction : public ITransaction {
 public:
     virtual void
+    // NOLINTNEXTLINE(google-default-arguments)
     Initialize(Hint &&hint,
                std::function<void(std::string &&)> &&qrCodeCallback,
                std::unique_ptr<IQrCodeShower> &&qrCodeShower = std::make_unique<QrCodeShower>(),
index 207f862216e04644f9f52ac87441e61e5abcbf2e..02804c3dcf0af77feee393291a0ce5174884b708 100644 (file)
@@ -27,7 +27,7 @@ RequestHandler &RequestHandler::Instance() noexcept
 wauthn_error_e RequestHandler::Cancel() noexcept
 {
     try {
-        std::lock_guard<std::mutex> lock(m_mutex);
+        const std::lock_guard<std::mutex> lock(m_mutex);
         if (!m_currentTransaction) {
             LogError("No request is being processed");
             return WAUTHN_ERROR_NOT_ALLOWED;
@@ -68,7 +68,7 @@ RequestHandler::AssignAndGetLinkedData(ForCallbacksCommon &forCallbacks) noexcep
 
 RequestHandler::RequestHandler() noexcept
 {
-    int err = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
+    const int err = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
     if (err)
         TRY_LOG_ERROR("pthread_setcancelstate() failed with error: " << err);
 }
index 2039d516b087bd51d0d1fdd421f8e15ee0e2a8fb..9fa23d2ed0620d1c2f6c3699d8947c22c845cbe3 100644 (file)
@@ -23,7 +23,6 @@
 #include "state_assisted_transaction.h"
 #include "to_wauthn_const_buff.h"
 
-#include <memory>
 #include <mutex>
 #include <webauthn-types.h>
 
@@ -121,8 +120,8 @@ public:
     template <RequestKind REQUEST_KIND>
     void Process(const wauthn_client_data_s *clientData,
                  Request<REQUEST_KIND> request,
-                 IQrTransaction &&qrTransaction,
-                 IStateAssistedTransaction &&stateAssistedTransaction) noexcept
+                 IQrTransaction &&qrTransaction,                                // NOLINT
+                 IStateAssistedTransaction &&stateAssistedTransaction) noexcept // NOLINT
     {
         if (!request.callbacks) {
             TRY_LOG_ERROR("Missing callbacks");
@@ -159,7 +158,7 @@ public:
                 } else {
                     transaction = &qrTransaction;
                     qrTransaction.Initialize(
-                        Hint{Request<REQUEST_KIND>::HINT}, [&](std::string &&qrCodeContents) {
+                        Hint{Request<REQUEST_KIND>::HINT}, [&](const std::string &qrCodeContents) {
                             try {
                                 request.callbacks->qrcode_callback(qrCodeContents.c_str(),
                                                                    request.callbacks->user_data);
@@ -273,7 +272,7 @@ private:
     template <RequestKind REQUEST_KIND, class TransactionResult>
     void ProcessTransactionResult(wauthn_const_buffer_s *clientDataJson,
                                   ForCallbacks<REQUEST_KIND> &forCallbacks,
-                                  TransactionResult &&transactionRes)
+                                  TransactionResult &&transactionRes) // NOLINT
     {
         forCallbacks.upMsg = std::move(transactionRes.ctapResult.upMsg);
         forCallbacks.clientPlatformPrivKey = std::move(transactionRes.clientPlatformPrivKey);
index 7fe2345509b1f4de7a5902399ea297529905e7eb..b0b1a6e7d33a50560ba8eed7d2232529edfc5ec9 100644 (file)
@@ -155,7 +155,7 @@ void StateAssistedTransaction::Cancel()
 {
     auto guard = std::lock_guard{m_lock};
     switch (m_state) {
-    case State::CANCELLED: break;
+    case State::CANCELLED:
     case State::NOT_IN_PROGRESS: break;
     case State::CONNECTING:
     case State::DOING_HANDSHAKE: {
index e68e6d1b9f80d67bf59371a8c110b4364e045438..12e6f1c9d55fe250bc44bb73e2107611285da8ae 100644 (file)
@@ -24,6 +24,7 @@
 class IStateAssistedTransaction : public ITransaction {
 public:
     virtual void
+    // NOLINTNEXTLINE(google-default-arguments)
     Initialize(Hint &&hint,
                std::unique_ptr<IHandshake> &&handshake = std::make_unique<Handshake>(),
                IBtAdvertScannerUPtr &&btAdvertScanner = std::make_unique<BtAdvertScanner>(),
index 55f19646e6531060541e0ca54703ce772b48d473..e9ac8a0236e7b4fd38831b5896d4927e4a6286ac 100644 (file)
@@ -86,7 +86,7 @@ const std::unordered_map<enum lws_close_status, std::string> CLOSE_STATUS2STR =
 } // namespace
 
 Tunnel::Tunnel(std::shared_ptr<IWebsockets> ws)
-: m_ws(ws),
+: m_ws(std::move(ws)),
   m_context(nullptr),
   m_connection(nullptr),
   m_writtenBytesNum(0),
@@ -99,13 +99,15 @@ Tunnel::Tunnel(std::shared_ptr<IWebsockets> ws)
 Tunnel::~Tunnel()
 {
     try {
-        Disconnect();
+        Tunnel::Disconnect(); // Call like this to make it clear that non-virtual method is called
+                              // from destructor.
         m_ws->SetListener(nullptr);
     } catch (...) {
         TRY_LOG_ERROR("Unexpected exception caught");
     }
 }
 
+// NOLINTNEXTLINE(google-default-arguments)
 void Tunnel::Connect(const std::string &url, std::optional<ExtraHttpHeader> extraHttpHeader)
 {
     LogDebug("Connecting to " << url);
@@ -119,7 +121,7 @@ void Tunnel::Connect(const std::string &url, std::optional<ExtraHttpHeader> extr
         THROW_UNKNOWN("Header name must end with ':'");
 
     {
-        std::lock_guard<std::mutex> guard(m_mutex);
+        const std::lock_guard<std::mutex> guard(m_mutex);
         if (m_cancelled) {
             m_cancelled = false;
             THROW_CANCELLED();
@@ -204,7 +206,7 @@ void Tunnel::Disconnect()
 void Tunnel::Cancel()
 {
     LogDebug("Cancelling");
-    std::lock_guard<std::mutex> guard(m_mutex);
+    const std::lock_guard<std::mutex> guard(m_mutex);
 
     if (m_cancelled)
         return;
@@ -301,7 +303,7 @@ bool Tunnel::HandleEvent(Lws *wsi, enum lws_callback_reasons reason, void *in, s
                         wsi,
                         reinterpret_cast<const unsigned char *>(m_extraHttpHeader->name.c_str()),
                         reinterpret_cast<const unsigned char *>(m_extraHttpHeader->value.c_str()),
-                        m_extraHttpHeader->value.size(),
+                        static_cast<int>(m_extraHttpHeader->value.size()),
                         p,
                         end)) {
                     LogError("Failed to add extra HTTP header");
@@ -321,10 +323,10 @@ bool Tunnel::HandleEvent(Lws *wsi, enum lws_callback_reasons reason, void *in, s
             break;
 
         case LWS_CALLBACK_CLIENT_RECEIVE: {
-            bool binary = m_ws->FrameIsBinary(wsi);
-            bool first = m_ws->IsFirstFragment(wsi);
-            bool last = m_ws->IsFinalFragment(wsi);
-            uint8_t *data = reinterpret_cast<uint8_t *>(in);
+            const bool binary = m_ws->FrameIsBinary(wsi);
+            const bool first = m_ws->IsFirstFragment(wsi);
+            const bool last = m_ws->IsFinalFragment(wsi);
+            auto *data = reinterpret_cast<uint8_t *>(in);
 
             LogDebug("Received " << len << "B, binary:" << binary << " first:" << first
                                  << " last:" << last);
@@ -377,8 +379,8 @@ bool Tunnel::HandleEvent(Lws *wsi, enum lws_callback_reasons reason, void *in, s
                 return true;
             }
 
-            size_t toWrite = m_out.size() - m_writtenBytesNum - LWS_PRE;
-            int written =
+            const size_t toWrite = m_out.size() - m_writtenBytesNum - LWS_PRE;
+            const int written =
                 m_ws->WriteBinary(wsi, m_out.data() + m_writtenBytesNum + LWS_PRE, toWrite);
 
             if (written <= 0) {
@@ -414,7 +416,7 @@ bool Tunnel::HandleEvent(Lws *wsi, enum lws_callback_reasons reason, void *in, s
             return true;
 
         case LWS_CALLBACK_EVENT_WAIT_CANCELLED: {
-            std::unique_lock<std::mutex> lock(m_mutex);
+            const std::unique_lock<std::mutex> lock(m_mutex);
             if (m_cancelled) {
                 LogDebug("Cancelled");
                 m_state = State::FAILED;
index 571e82e89b4ed1e339d8184d1b49452ac2b9bcf4..7a32c6b8db82e72f541abe1eb6b33a04cbfbf738 100644 (file)
@@ -44,6 +44,7 @@ protected:
 public:
     virtual ~ITunnel() = default;
 
+    // NOLINTNEXTLINE(google-default-arguments)
     virtual void Connect(const std::string &url,
                          std::optional<ExtraHttpHeader> extraHttpHeader = std::nullopt) = 0;
     virtual void WriteBinary(const std::vector<uint8_t> &msg) = 0;
@@ -57,11 +58,12 @@ public:
 class Tunnel : public ITunnel, public IWebsocketsListener {
 public:
     explicit Tunnel(std::shared_ptr<IWebsockets> ws = std::make_shared<Websockets>());
-    ~Tunnel();
+    ~Tunnel() override;
 
     Tunnel(const Tunnel &) = delete;
     Tunnel &operator=(const Tunnel &) = delete;
 
+    // NOLINTNEXTLINE(google-default-arguments)
     void Connect(const std::string &url,
                  std::optional<ExtraHttpHeader> extraHttpHeader = std::nullopt) override;
     void WriteBinary(const std::vector<uint8_t> &msg) override;
index 8a8b1e9259c874356c75649d47fcae7c1839be68..8ef8f055cb8069004726f7d3a6f35dd9b94e7d24 100644 (file)
@@ -18,7 +18,6 @@
 #include "crypto/sha2.h"
 #include "endian.h"
 #include "exception.h"
-#include "log/log.h"
 #include "tunnel_server_domain.h"
 
 #include <cstring>
index b7b277a26c48c20514ae6bbc19d04a430976e403..05730fa61578a28f7d2e844023337c0eac2a8509 100644 (file)
@@ -60,7 +60,7 @@ Websockets::Websockets() noexcept
       LWS_PROTOCOL_LIST_TERM
 }
 {
-    [[maybe_unused]] static bool redirected = RedirectWebsocketsLogs();
+    [[maybe_unused]] static const bool redirected = RedirectWebsocketsLogs();
 }
 
 LwsContext *Websockets::CreateContext() noexcept
@@ -72,8 +72,8 @@ LwsContext *Websockets::CreateContext() noexcept
     contextInfo.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
     contextInfo.port = CONTEXT_PORT_NO_LISTEN; // we are not a server
     contextInfo.protocols = m_protocols;
-    contextInfo.gid = (gid_t)-1;
-    contextInfo.uid = (uid_t)-1;
+    contextInfo.gid = static_cast<gid_t>(-1);
+    contextInfo.uid = static_cast<uid_t>(-1);
 
     return Native2Context(lws_create_context(&contextInfo));
 }
@@ -86,7 +86,8 @@ Lws *Websockets::ClientConnectViaInfo(const struct lws_client_connect_info &info
 Lws *Websockets::DoClientConnect(LwsContext *context, const std::string &url, int sslFlags) noexcept
 {
     struct lws_client_connect_info cInfo;
-    const char *protocol, *path;
+    const char *protocol;
+    const char *path;
 
     std::vector<char> urlMutable;
     urlMutable.reserve(url.size() + 3); // leave place for inserting {'/', '\0'}
index 2e45b535c0f9b679b9c7310d3d7909b7073b74fa..e9f343d2e53441531b87b1a5c307e89ee3925eff 100644 (file)
@@ -184,7 +184,6 @@ public:
 class Websockets : public IWebsockets {
 public:
     Websockets() noexcept;
-    ~Websockets() = default;
 
     LwsContext *CreateContext() noexcept override;
     Lws *ClientConnect(LwsContext *context, const std::string &url) noexcept override;
index b3a446022b90950fc2460063890c15c25a678c42..9554eec842d407961c07d86cafd18378c9e91770 100644 (file)
 
 #include "base64.h"
 
+#include <cstddef>
 #include <gtest/gtest.h>
 
 TEST(base64, Base64UrlEncode)
 {
     unsigned char data[] = "\x00\x01\x02\x03\x04\x05";
-    EXPECT_EQ(Base64UrlEncode({data, 0}), "");
+    EXPECT_EQ(Base64UrlEncode({}), "");
     EXPECT_EQ(Base64UrlEncode({data, 1}), "AA");
     EXPECT_EQ(Base64UrlEncode({data, 2}), "AAE");
     EXPECT_EQ(Base64UrlEncode({data, 3}), "AAEC");
index da064606f63fbb488ab39376c39c13a3d36902da..2c4d2ae038ed3da511abb6a18cb63ad9bf49119e 100644 (file)
 #include <utility>
 
 using std::cerr;
-using std::endl;
 
 TEST(BluetoothTest, safely_deferring_callback_to_be_run_after_g_main_loop_run)
 {
     // This test ensures this logic works in the Bluetooth:StopLEScan() preventing a deadlock
     using Data = std::pair<GMainLoop *, bool>;
-    auto data = Data{g_main_loop_new(NULL, FALSE), false};
+    auto data = Data{g_main_loop_new(nullptr, FALSE), false};
     g_timeout_add_full(
         G_PRIORITY_HIGH,
         0,
@@ -93,7 +92,7 @@ TEST(BluetoothTest, scan_for_up_to_1_second)
                        void * /*userData*/) noexcept {
         cerr << "Scanned advert: UUID = " << serviceUUID << " data = "
              << LowercaseHexStringOf(CryptoBuffer{serviceData, serviceData + serviceDataLen})
-             << endl;
+             << '\n';
         return IBluetooth::Scanning::CONTINUE;
     };
     EXPECT_EQ(err = bt.StartLEAdvertScanAndAwaitStop(callback, nullptr), BT_ERROR_CANCELLED)
@@ -165,7 +164,7 @@ public:
     [[nodiscard]] int StartLEAdvertScanAndAwaitStop(CallbackType callback, void *userData) override
     {
         if (!m_initialized) {
-            ADD_FAILURE() << "Attempting to scan on uninitialized bluetooth adapter." << endl;
+            ADD_FAILURE() << "Attempting to scan on uninitialized bluetooth adapter." << '\n';
             return BT_ERROR_NOT_INITIALIZED;
         }
         if (!m_turnedOn)
@@ -178,7 +177,7 @@ public:
         for (const auto &advert : m_bleAdverts) {
             auto callbackRes = callback(advert.serviceUUID,
                                         advert.serviceData.raw.data(),
-                                        advert.serviceData.raw.size(),
+                                        static_cast<int>(advert.serviceData.raw.size()),
                                         userData);
             if (callbackRes != advert.expectedCallbackRes) {
                 ADD_FAILURE() << "callback returned unexpected result for advert: bleAdverts["
@@ -202,14 +201,14 @@ public:
     {
         if (!m_initialized) {
             ADD_FAILURE() << "Attempting to stop scan on the uninitialized bluetooth adapter."
-                          << endl;
+                          << '\n';
         }
     }
 
     [[nodiscard]] int Deinitialize() noexcept override
     {
         if (!m_initialized) {
-            ADD_FAILURE() << "Attempting to deinitialize uninitialized bluetooth adapter." << endl;
+            ADD_FAILURE() << "Attempting to deinitialize uninitialized bluetooth adapter." << '\n';
             return BT_ERROR_NOT_INITIALIZED;
         }
         if (m_deinitializeRes != BT_ERROR_NONE)
@@ -364,7 +363,7 @@ public:
     [[nodiscard]] int StartLEAdvertScanAndAwaitStop(CallbackType callback, void *userData) override
     {
         if (!m_initialized) {
-            ADD_FAILURE() << "Attempting to scan on uninitialized bluetooth adapter." << endl;
+            ADD_FAILURE() << "Attempting to scan on uninitialized bluetooth adapter." << '\n';
             return BT_ERROR_NOT_INITIALIZED;
         }
         if (!m_turnedOn)
@@ -382,7 +381,7 @@ public:
     {
         if (!m_initialized) {
             ADD_FAILURE() << "Attempting to stop scan on the uninitialized bluetooth adapter."
-                          << endl;
+                          << '\n';
         }
         m_promise.set_value();
     }
@@ -421,7 +420,7 @@ public:
     [[nodiscard]] int StartLEAdvertScanAndAwaitStop(CallbackType callback, void *userData) override
     {
         if (!m_initialized) {
-            ADD_FAILURE() << "Attempting to scan on uninitialized bluetooth adapter." << endl;
+            ADD_FAILURE() << "Attempting to scan on uninitialized bluetooth adapter." << '\n';
             return BT_ERROR_NOT_INITIALIZED;
         }
         if (!m_turnedOn)
@@ -440,7 +439,7 @@ public:
     {
         if (!m_initialized) {
             ADD_FAILURE() << "Attempting to stop scan on the uninitialized bluetooth adapter."
-                          << endl;
+                          << '\n';
         }
         m_cancelFacilitator.Cancel();
     }
index 1811a4def6e7e1b6276b3754f5f8ff93ff16f67f..27d232b492474093c17c38e4ca754ff0dc24166d 100644 (file)
 
 #include "common.h"
 
-inline Buffer ToBuffer(const BufferView &bv) { return Buffer(bv.begin(), bv.end()); }
+inline Buffer ToBuffer(const BufferView &bv) { return {bv.begin(), bv.end()}; }
 
 // Use with string literals only, because it assumes the input array to be null-terminated.
 template <size_t N>
 Buffer BUFFER(const char (&data)[N])
 {
-    return Buffer{reinterpret_cast<const uint8_t *>(data),
-                  reinterpret_cast<const uint8_t *>(data) + N - 1};
+    return {reinterpret_cast<const uint8_t *>(data),
+            reinterpret_cast<const uint8_t *>(data) + N - 1};
 }
index 89009f55ddd09a17be50a880ba7a9624f7349c9f..7622a74e360d4d370c700230c32f377adc3abb44 100644 (file)
@@ -22,12 +22,12 @@ template <class T>
 BufferView ToBufferView(T &buffer) noexcept
 {
     static_assert(sizeof(decltype(*buffer.data())) == 1, "for reinterpret_cast below");
-    return BufferView{reinterpret_cast<const uint8_t *>(buffer.data()), buffer.size()};
+    return {reinterpret_cast<const uint8_t *>(buffer.data()), buffer.size()};
 }
 
 // Use with string literals only, because it assumes the input array to be null-terminated.
 template <size_t N>
 BufferView BUFFER_VIEW(const char (&data)[N])
 {
-    return BufferView(reinterpret_cast<const uint8_t *>(data), N - 1);
+    return {reinterpret_cast<const uint8_t *>(data), N - 1};
 }
index f61e7051af99f6306f9004599db76b20e7f1d514..49fef3c77d0b38791b6d62f33582728f23f8f3be 100644 (file)
@@ -21,9 +21,9 @@
 #include "exception.h"
 
 #include <cstdint>
+#include <ctime>
 #include <gtest/gtest.h>
 #include <string>
-#include <time.h>
 #include <unistd.h>
 #include <webauthn-types.h>
 #include <webauthn.h>
@@ -42,8 +42,8 @@ struct date {
     int year;
 };
 
-struct date DT = {12, 0, 0, 1, 1, 1970};
-bool EXTRAKEY = true;
+struct date DT = {12, 0, 0, 1, 1, 1970}; // NOLINT
+bool EXTRA_KEY = true;                   // NOLINT
 
 const CryptoBuffer PUBKEY1 = {0x03, 0x09, 0x09, 0xDC, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0, 0x1,
                               0x2,  0x3,  0x4,  0x5,  0x6, 0x7, 0x8, 0x9, 0x0, 0x1, 0x2,
@@ -142,29 +142,29 @@ struct tm convertToTm(struct date &date)
 
 int64_t tmToEpoch(struct tm &tmDate)
 {
-    time_t time = timegm(&tmDate);
+    const time_t time = timegm(&tmDate);
     assert(time != -1);
-    int64_t epoch = static_cast<int64_t>(time);
+    auto epoch = static_cast<int64_t>(time);
     return epoch;
 }
 
 int64_t dateToEpoch(struct date &date)
 {
     struct tm tmDate = convertToTm(date);
-    int64_t epoch = tmToEpoch(tmDate);
+    const int64_t epoch = tmToEpoch(tmDate);
     return epoch;
 }
 
 class MockCbor : public CborEncoding::Cbor {
 private:
-    int64_t getEpoch() const override { return dateToEpoch(DT); }
+    [[nodiscard]] int64_t getEpoch() const override { return dateToEpoch(DT); }
 
-    bool getGrease() const override { return EXTRAKEY; }
+    [[nodiscard]] bool getGrease() const override { return EXTRA_KEY; }
 };
 
 class MockRandCbor : public CborEncoding::Cbor {
 private:
-    bool getGrease() const override { return EXTRAKEY; }
+    [[nodiscard]] bool getGrease() const override { return EXTRA_KEY; }
 };
 
 } // namespace
@@ -181,7 +181,7 @@ TEST(CborEncoding, testCborEncodeGivenTime)
     std::string str;
 
     DT = {4, 46, 30, 7, 6, 2023};
-    EXTRAKEY = true;
+    EXTRA_KEY = true;
 
     MockCbor cb;
     EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY1, SECRET1, MC, false, str));
@@ -190,11 +190,11 @@ TEST(CborEncoding, testCborEncodeGivenTime)
 TEST(CborEncoding, testCborEncodeMaxLength)
 {
     struct MaxCbor : public MockRandCbor {
-        int64_t getEpoch() const override { return INT64_MAX; }
+        [[nodiscard]] int64_t getEpoch() const override { return INT64_MAX; }
     } cb;
 
     std::string str;
-    EXTRAKEY = true;
+    EXTRA_KEY = true;
 
     EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY1, SECRET1, MC, false, str));
 }
@@ -203,7 +203,7 @@ TEST(CborEncoding, testCborEncodeExtraKey)
 {
     std::string str;
 
-    EXTRAKEY = true;
+    EXTRA_KEY = true;
 
     MockRandCbor cb;
     EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY1, SECRET1, MC, false, str));
@@ -213,7 +213,7 @@ TEST(CborEncoding, testCborEncodeStateAssisted)
 {
     std::string str;
 
-    EXTRAKEY = false;
+    EXTRA_KEY = false;
 
     MockRandCbor cb;
     EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY1, SECRET1, MC, true, str));
@@ -225,13 +225,13 @@ TEST(CborEncoding, testCborDocsExample1)
 
     // this string is an CBOR map generated via cbor.me based on parameters used in this test
     //  and encoded with digitEncode function in golang, presented in CTAP spec
-    std::string exp = "FIDO:/02543183839363239340602324839577240098435191071915118"
-                      "7005327550457265868974431945030026559112733094195355904206775"
-                      "8233600668650798290081467374921971146260714619586490906000065"
-                      "535";
+    const std::string exp = "FIDO:/02543183839363239340602324839577240098435191071915118"
+                            "7005327550457265868974431945030026559112733094195355904206775"
+                            "8233600668650798290081467374921971146260714619586490906000065"
+                            "535";
 
     DT = {4, 46, 30, 7, 6, 2023}; // 2023-06-07 4:46:30 = 1686113190
-    EXTRAKEY = true;
+    EXTRA_KEY = true;
 
     MockCbor cb;
     EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY_EXAMPLE_1, SECRET_EXAMPLE_1, MC, true, str));
@@ -244,12 +244,12 @@ TEST(CborEncoding, testCborDocsExample2)
 
     // this string is an CBOR map generated via cbor.me based on parameters used in this test
     //  and encoded with digitEncode function in golang, presented in CTAP spec
-    std::string exp = "FIDO:/06864260241555622302709464829026825146786230434385011"
-                      "1348978781761713839576763962157447985046715480496111683815354"
-                      "781970067505799178140427369594873840386107096654083332";
+    const std::string exp = "FIDO:/06864260241555622302709464829026825146786230434385011"
+                            "1348978781761713839576763962157447985046715480496111683815354"
+                            "781970067505799178140427369594873840386107096654083332";
 
     DT = {8, 14, 25, 7, 6, 2023}; // 2023-06-07 8:14:25 = 1686125665
-    EXTRAKEY = false;
+    EXTRA_KEY = false;
 
     MockCbor cb;
     EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY_EXAMPLE_2, SECRET_EXAMPLE_2, GA, true, str));
@@ -289,7 +289,7 @@ TEST(Cbor, MapInt64EncodingAndDecoding)
     auto parserMap = parser.EnterMap();
 
     for (int64_t i = 0; i < static_cast<int64_t>(MAP_SIZE); i++)
-        EXPECT_EQ(parserMap.GetInt64At(i).value(), INT64_VALUES[i]);
+        EXPECT_EQ(parserMap.GetInt64At(i), INT64_VALUES[i]);
 }
 
 TEST(Cbor, MapBoolEncodingAndDecoding)
@@ -309,7 +309,7 @@ TEST(Cbor, MapBoolEncodingAndDecoding)
     auto parserMap = parser.EnterMap();
 
     for (int64_t i = 0; i < static_cast<int64_t>(MAP_SIZE); i++)
-        EXPECT_EQ(parserMap.GetBooleanAt(i).value(), BOOL_VALUES[i]);
+        EXPECT_EQ(parserMap.GetBooleanAt(i), BOOL_VALUES[i]);
 }
 
 TEST(Cbor, MapByteStringEncodingAndDecoding)
@@ -326,7 +326,7 @@ TEST(Cbor, MapByteStringEncodingAndDecoding)
     auto parser = CborParsing::Parser::Create(buffer.data(), buffer.size());
     auto parserMap = parser.EnterMap();
 
-    EXPECT_EQ(parserMap.GetByteStringAt(0).value(), BYTE_STRING_VALUE);
+    EXPECT_EQ(parserMap.GetByteStringAt(0), BYTE_STRING_VALUE);
 
     Buffer buffer2(21);
     wauthn_const_buffer_s wauthnConstBuffer;
@@ -363,7 +363,7 @@ TEST(Cbor, MapStringZEncodingAndDecoding)
     auto parserMap = parser.EnterMap();
 
     for (int64_t i = 0; i < static_cast<int64_t>(MAP_SIZE); i++)
-        EXPECT_EQ(parserMap.GetTextStringAt(i).value(), STRING_VIEW_VALUES[i]);
+        EXPECT_EQ(parserMap.GetTextStringAt(i), STRING_VIEW_VALUES[i]);
 }
 
 TEST(Cbor, ArrayStringEncodingAndDecoding)
@@ -373,8 +373,8 @@ TEST(Cbor, ArrayStringEncodingAndDecoding)
     auto encoder = CborEncoding::Encoder::Create(buffer.data(), buffer.size());
     {
         auto array = encoder.OpenArray(ARRAY_SIZE);
-        for (int64_t i = 0; i < static_cast<int64_t>(ARRAY_SIZE); i++)
-            EXPECT_NO_THROW(array.AppendTextString(STRING_VIEW_VALUES[i]));
+        for (const auto &sv : STRING_VIEW_VALUES)
+            EXPECT_NO_THROW(array.AppendTextString(sv));
     }
 
     EXPECT_EQ(encoder.GetBufferSize(), buffer.size());
@@ -382,8 +382,8 @@ TEST(Cbor, ArrayStringEncodingAndDecoding)
     auto parser = CborParsing::Parser::Create(buffer.data(), buffer.size());
     auto parserArray = parser.EnterArray();
 
-    for (int64_t i = 0; i < static_cast<int64_t>(ARRAY_SIZE); i++)
-        EXPECT_EQ(parserArray.GetTextString(), STRING_VIEW_VALUES[i]);
+    for (const auto &sv : STRING_VIEW_VALUES)
+        EXPECT_EQ(parserArray.GetTextString(), sv);
 }
 
 TEST(Cbor, MapOptionalTextStringEncodingAndDecoding)
@@ -405,7 +405,7 @@ TEST(Cbor, MapOptionalTextStringEncodingAndDecoding)
 
     EXPECT_EQ(parserMap.GetTextStringAt(-1), std::nullopt);
     for (int64_t i = 0; i < static_cast<int64_t>(MAP_SIZE); i++)
-        EXPECT_EQ(parserMap.GetTextStringAt(i).value(), STRING_VIEW_VALUES[i].data());
+        EXPECT_EQ(parserMap.GetTextStringAt(i), STRING_VIEW_VALUES[i].data());
 }
 
 TEST(Cbor, EncodingToNullBuffer)
@@ -431,14 +431,14 @@ TEST(Cbor, MapDecodingValuesOfDifferentTypeThanExpected)
     static constexpr bool BOOL_VALUE = true;
     static constexpr int64_t INT64T_VALUE = 117;
     static constexpr char STRING_VALUE[] = "characters";
-    const Buffer BYTE_STRING_VALUE = {0x86, 0x33, 0x45, 0x17};
+    const Buffer LOCAL_BYTE_STRING_VALUE = {0x86, 0x33, 0x45, 0x17};
     auto encoder = CborEncoding::Encoder::Create(buffer.data(), buffer.size());
     {
         auto map = encoder.OpenMap(4);
         EXPECT_NO_THROW(map.AppendBooleanAt(0, BOOL_VALUE));
         EXPECT_NO_THROW(map.AppendInt64At(1, INT64T_VALUE));
         EXPECT_NO_THROW(map.AppendTextStringZAt(2, STRING_VALUE));
-        EXPECT_NO_THROW(map.AppendByteStringAt(3, BYTE_STRING_VALUE));
+        EXPECT_NO_THROW(map.AppendByteStringAt(3, LOCAL_BYTE_STRING_VALUE));
     }
 
     EXPECT_EQ(encoder.GetBufferSize(), buffer.size());
@@ -458,13 +458,13 @@ TEST(Cbor, DecodingMapWithNotSortedKeysFails)
     Buffer buffer(19);
     static constexpr int64_t INT64T_VALUE = 117;
     static constexpr char STRING_VALUE[] = "text";
-    const Buffer BYTE_STRING_VALUE = {0x86, 0x33, 0x45, 0x17};
+    const Buffer LOCAL_BYTE_STRING_VALUE = {0x86, 0x33, 0x45, 0x17};
     auto encoder = CborEncoding::Encoder::Create(buffer.data(), buffer.size());
     {
         auto map = encoder.OpenMap(3);
         EXPECT_NO_THROW(map.AppendInt64At(0x66, INT64T_VALUE));
         EXPECT_NO_THROW(map.AppendTextStringZAt(0x33, STRING_VALUE));
-        EXPECT_NO_THROW(map.AppendByteStringAt(0x24, BYTE_STRING_VALUE));
+        EXPECT_NO_THROW(map.AppendByteStringAt(0x24, LOCAL_BYTE_STRING_VALUE));
     }
 
     EXPECT_EQ(encoder.GetBufferSize(), buffer.size());
@@ -577,7 +577,8 @@ TEST(CborParsing, SortedMapPeekAndLocateKey)
     static constexpr int VALUE = 16;
     static constexpr std::string_view TEXT = "text";
 
-    CborEncoder encoder, mapEncoder;
+    CborEncoder encoder;
+    CborEncoder mapEncoder;
     ASSERT_NO_THROW(cbor_encoder_init(&encoder, buffer.data(), buffer.size(), 0));
     ASSERT_NO_THROW(cbor_encoder_create_map(&encoder, &mapEncoder, 2));
     ASSERT_NO_THROW(cbor_encode_int(&mapEncoder, KEY));
@@ -600,13 +601,13 @@ TEST(Cbor, SkippingUnknownKeysWhileDecodingMap)
     Buffer buffer(23);
     static constexpr int64_t INT64T_VALUE = 64;
     static constexpr char STRING_VALUE[] = "string_value";
-    const Buffer BYTE_STRING_VALUE = {0x27, 0x48, 0x75};
+    const Buffer LOCAL_BYTE_STRING_VALUE = {0x27, 0x48, 0x75};
     auto encoder = CborEncoding::Encoder::Create(buffer.data(), buffer.size());
     {
         auto map = encoder.OpenMap(3);
         EXPECT_NO_THROW(map.AppendInt64At(0x00, INT64T_VALUE));
         EXPECT_NO_THROW(map.AppendTextStringZAt(0x02, STRING_VALUE));
-        EXPECT_NO_THROW(map.AppendByteStringAt(0x03, BYTE_STRING_VALUE));
+        EXPECT_NO_THROW(map.AppendByteStringAt(0x03, LOCAL_BYTE_STRING_VALUE));
     }
 
     EXPECT_EQ(encoder.GetBufferSize(), buffer.size());
@@ -619,7 +620,7 @@ TEST(Cbor, SkippingUnknownKeysWhileDecodingMap)
 
     EXPECT_EQ(parserMap.GetUint64At(0x00), INT64T_VALUE);
     EXPECT_EQ(parserMap.GetTextStringAt(0x02), STRING_VALUE);
-    EXPECT_EQ(parserMap.GetByteStringAt(0x03), BYTE_STRING_VALUE);
+    EXPECT_EQ(parserMap.GetByteStringAt(0x03), LOCAL_BYTE_STRING_VALUE);
 }
 
 TEST(Cbor, DecodingGarbageAtEnd)
@@ -665,7 +666,7 @@ TEST(Cbor, DecodingMapNonexistentKeys)
     static constexpr u_int64_t UINT64T_VALUES = 128;
     static constexpr bool BOOL_VALUE = false;
     static constexpr char STRING_VALUE[] = "fourtyfour";
-    const Buffer BYTE_STRING_VALUE = {0x08, 0x10, 0x12};
+    const Buffer LOCAL_BYTE_STRING_VALUE = {0x08, 0x10, 0x12};
     auto encoder = CborEncoding::Encoder::Create(buffer.data(), buffer.size());
     {
         auto map = encoder.OpenMap(5);
@@ -673,7 +674,7 @@ TEST(Cbor, DecodingMapNonexistentKeys)
         EXPECT_NO_THROW(map.AppendInt64At(0x01, UINT64T_VALUES));
         EXPECT_NO_THROW(map.AppendBooleanAt(0x02, BOOL_VALUE));
         EXPECT_NO_THROW(map.AppendTextStringZAt(0x03, STRING_VALUE));
-        EXPECT_NO_THROW(map.AppendByteStringAt(0x04, BYTE_STRING_VALUE));
+        EXPECT_NO_THROW(map.AppendByteStringAt(0x04, LOCAL_BYTE_STRING_VALUE));
     }
 
     EXPECT_EQ(encoder.GetBufferSize(), buffer.size());
@@ -694,7 +695,7 @@ TEST(Cbor, DecodingMapNonexistentKeys)
     EXPECT_EQ(parserMap.GetTextStringAt(0x03), STRING_VALUE);
 
     EXPECT_EQ(parserMap.GetByteStringAt(0x128), std::nullopt);
-    EXPECT_EQ(parserMap.GetByteStringAt(0x04), BYTE_STRING_VALUE);
+    EXPECT_EQ(parserMap.GetByteStringAt(0x04), LOCAL_BYTE_STRING_VALUE);
 }
 
 TEST(Cbor, NestedStructuresEncodingAndDecoding1)
@@ -734,6 +735,7 @@ TEST(Cbor, NestedStructuresEncodingAndDecoding1)
     auto parserMap = parser.EnterMap();
 
     {
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto firstArrayParser = parserMap.EnterArrayAt(0).value();
         for (auto x : INT64T_VALUES)
             EXPECT_EQ(firstArrayParser.GetInt64(), x);
@@ -741,6 +743,7 @@ TEST(Cbor, NestedStructuresEncodingAndDecoding1)
     }
 
     {
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto firstMapParser = parserMap.EnterMapAt(1).value();
         EXPECT_EQ(firstMapParser.GetTextStringAt("text_0"), STRING_VALUES[0]);
         EXPECT_EQ(firstMapParser.GetTextStringAt("text_1"), STRING_VALUES[1]);
@@ -748,9 +751,10 @@ TEST(Cbor, NestedStructuresEncodingAndDecoding1)
     }
 
     {
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto secondMapParser = parserMap.EnterMapAt(2).value();
         EXPECT_EQ(secondMapParser.GetBooleanAt(3), true);
-
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto secondArrayParser = secondMapParser.EnterArrayAt(4).value();
         for (auto x : INT64T_VALUES)
             EXPECT_EQ(secondArrayParser.GetInt64(), x);
@@ -800,6 +804,7 @@ TEST(Cbor, NestedStructuresEncodingAndDecoding2)
         EXPECT_EQ(firstMapParser.GetTextStringAt(2), STRING_VALUES[1]);
         EXPECT_EQ(firstMapParser.GetTextStringAt(3), STRING_VALUES[2]);
 
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
         auto nestedArrayParser = firstMapParser.EnterArrayAt(4).value();
         for (auto x : INT64T_VALUES)
             EXPECT_EQ(nestedArrayParser.GetInt64(), x);
@@ -880,17 +885,19 @@ TEST(Cbor, SkippingUndecodedEntriesUponContainerClose)
     auto parserMap = parser.EnterMap();
 
     {
-        auto nestedMapParser = parserMap.EnterMapAt(2);
-        EXPECT_EQ(nestedMapParser.value().GetInt64At(1), INT64T_VALUES[1]);
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
+        auto nestedMapParser = parserMap.EnterMapAt(2).value();
+        EXPECT_EQ(nestedMapParser.GetInt64At(1), INT64T_VALUES[1]);
     }
 
     EXPECT_EQ(parserMap.GetTextStringAt(3), STRING_VALUES[1]);
 
     {
-        auto parserArray = parserMap.EnterArrayAt(4);
-        EXPECT_EQ(parserArray.value().GetInt64(), INT64T_VALUES[0]);
+        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
+        auto parserArray = parserMap.EnterArrayAt(4).value();
+        EXPECT_EQ(parserArray.GetInt64(), INT64T_VALUES[0]);
 
-        auto nestedArrayParser = parserArray.value().EnterArray();
+        auto nestedArrayParser = parserArray.EnterArray();
         EXPECT_EQ(nestedArrayParser.GetInt64(), INT64T_VALUES[1]);
     }
 
@@ -982,8 +989,8 @@ TEST_CBOR_ENCODING(ContainerZeroValueInAppendInt64,
                    array.AppendInt64(0))
 
 // AppendByteString tests
-const unsigned char wauthnChars[] = {0x83, 0x03, 0x6B};
-wauthn_const_buffer_s wauthnConstBuffer = {wauthnChars, sizeof(wauthnChars)};
+constexpr inline unsigned char wauthnChars[] = {0x83, 0x03, 0x6B};
+constexpr inline wauthn_const_buffer_s wauthnConstBuffer = {wauthnChars, sizeof(wauthnChars)};
 
 TEST_CBOR_ENCODING(ContainerEmptyStringInBufferTypeAppendByteString,
                    "\x81\x40",
@@ -1492,12 +1499,15 @@ TEST_CBOR_PARSING(SortedMapMapInEnterArrayAt,
 TEST_CBOR_PARSING(SortedMapEmptyArrayInEnterArrayAt,
                   "\xa1\x07\x80",
                   auto outerMap = parser.EnterMap();
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   auto map = outerMap.EnterArrayAt(7).value(),
                   EXPECT_THROW(map.GetInt64(), Unknown))
 TEST_CBOR_PARSING(SortedMapNonEmptyArrayInEnterArrayAt,
                   "\xa1\x07\x81\x07",
                   auto outerMap = parser.EnterMap();
-                  auto map = outerMap.EnterArrayAt(7).value(), EXPECT_EQ(map.GetInt64(), 7))
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
+                  auto map = outerMap.EnterArrayAt(7).value(),
+                  EXPECT_EQ(map.GetInt64(), 7))
 TEST_CBOR_PARSING(SortedMapCurrentKeyNullKeyInEnterArrayAt,
                   "\xa1\xF6\x81\x07",
                   auto outerMap = parser.EnterMap();
@@ -1537,12 +1547,15 @@ TEST_CBOR_PARSING(SortedMapArrayInEnterMapAt,
                   EXPECT_THROW(parser.EnterMap().EnterMapAt(7), Unknown),
                   {})
 TEST_CBOR_PARSING(SortedMapEmptyMapInEnterMapAt, "\xa1\x07\xa0", auto outerMap = parser.EnterMap();
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
                   auto map = outerMap.EnterMapAt(7).value(),
                   EXPECT_EQ(map.GetInt64At(CborParsing::CURRENT_KEY), std::nullopt))
 TEST_CBOR_PARSING(SortedMapNonEmptyMapInEnterMapAt,
                   "\xa1\x07\xa1\x01\x07",
                   auto outerMap = parser.EnterMap();
-                  auto map = outerMap.EnterMapAt(7).value(), EXPECT_EQ(map.GetInt64At(1), 7))
+                  // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
+                  auto map = outerMap.EnterMapAt(7).value(),
+                  EXPECT_EQ(map.GetInt64At(1), 7))
 TEST_CBOR_PARSING(SortedMapCurrentKeyNullKeyInEnterMapAt,
                   "\xa1\xF6\xa1\x01\x07",
                   auto outerMap = parser.EnterMap();
@@ -1983,26 +1996,34 @@ TEST_CBOR_PARSING(SortedMapArrayOfSize3Length,
                   EXPECT_EQ(array.Length(), 3))
 
 // Asserts
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::GetInt64 == &CborParsing::Container::GetInt64,
               "Copy GetInt64 test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::GetTextString == &CborParsing::Container::GetTextString,
               "Copy GetTextString test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::GetByteString == &CborParsing::Container::GetByteString,
               "Copy GetByteString test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::GetBoolean == &CborParsing::Container::GetBoolean,
               "Copy GetBoolean test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::GetUint64 == &CborParsing::Container::GetUint64,
               "Copy GetUint64 test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::Length == &CborParsing::Container::Length,
               "Copy Length test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::EnterMap == &CborParsing::Container::EnterMap,
               "Copy EnterMap test from Container");
 
+// NOLINTNEXTLINE(misc-redundant-expression)
 static_assert(&CborParsing::Parser::EnterArray == &CborParsing::Container::EnterArray,
               "Copy EnterArray test from Container");
index b943a22040099d731a4dd1b9c12d296d746e8034..f25f93f30efa37584c7a315a6ad9a3fb361b1962 100644 (file)
@@ -24,7 +24,7 @@ TEST(HkdfSha256Test, RFC5869TestCase0)
     const CryptoBuffer secret = {'s', 'e', 'c', 'r', 'e', 't'};
     const CryptoBuffer salt = {'s', 'a', 'l', 't'};
     const CryptoBuffer info = {'l', 'a', 'b', 'e', 'l'};
-    size_t derivedKeySize = 10;
+    static constexpr size_t derivedKeySize = 10;
 
     const CryptoBuffer expected = {0x2a, 0xc4, 0x36, 0x9f, 0x52, 0x59, 0x96, 0xf8, 0xde, 0x13};
 
@@ -38,7 +38,7 @@ TEST(HkdfSha256Test, RFC5869TestCase1)
     const CryptoBuffer salt = {
         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c};
     const CryptoBuffer info = {0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9};
-    size_t derivedKeySize = 42;
+    static constexpr size_t derivedKeySize = 42;
 
     const CryptoBuffer expected = {0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f,
                                    0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a,
@@ -54,7 +54,7 @@ TEST(HkdfSha256Test, RFC5869TestCase3)
     const CryptoBuffer secret(22, 0x0b);
     const CryptoBuffer salt;
     const CryptoBuffer info;
-    size_t derivedKeySize = 42;
+    static constexpr size_t derivedKeySize = 42;
 
     const CryptoBuffer expected = {0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80,
                                    0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1,
@@ -70,7 +70,7 @@ TEST(HkdfSha256Test, EmptyBufferTestCase4)
     const CryptoBuffer secret(22, 0x0b);
     const CryptoBuffer salt;
     const CryptoBuffer info;
-    size_t derivedKeySize = 0;
+    static constexpr size_t derivedKeySize = 0;
 
     auto derivedKey = Crypto::HkdfSha256(secret, salt, info, derivedKeySize);
     EXPECT_EQ(derivedKey, CryptoBuffer{});
@@ -81,7 +81,7 @@ TEST(HkdfSha256Test, empty_secret)
     const CryptoBuffer secret;
     const CryptoBuffer salt = {0xde, 0xad, 0xbe, 0xef};
     const CryptoBuffer info = {0xaa, 0xbb, 0xcc};
-    size_t derivedKeySize = 42;
+    static constexpr size_t derivedKeySize = 42;
 
     const CryptoBuffer expected = {0xbd, 0x61, 0x63, 0xe5, 0xf0, 0x38, 0x2a, 0xc3, 0x67, 0xee, 0x1c,
                                    0x56, 0xc2, 0xfb, 0x50, 0x63, 0x0a, 0xc2, 0x75, 0xba, 0x40, 0x9c,
@@ -97,7 +97,7 @@ TEST(HkdfSha256Test, empty_secret_long)
     const CryptoBuffer secret;
     const CryptoBuffer salt(100, 0x0b);
     const CryptoBuffer info(76, 0xff);
-    size_t derivedKeySize = 42;
+    static constexpr size_t derivedKeySize = 42;
 
     const CryptoBuffer expected = {0xca, 0x1d, 0x24, 0x2f, 0x20, 0xbe, 0x4d, 0x14, 0x41, 0xd5, 0x56,
                                    0x68, 0x75, 0x26, 0x6a, 0x9f, 0x0d, 0xc6, 0x34, 0x2f, 0x27, 0xc5,
index a0d178e5bcddb29dc99b408ab64b3f0947c2cb7b..4ef8b33c58f83fe31ff558de96a3591f8a1317cc 100644 (file)
 
 #include <gtest/gtest.h>
 
-using namespace Crypto::Noise;
+using namespace Crypto::Noise; // NOLINT
 
 TEST(NoiseTest, KNpsk0_P256_AESGCM_SHA256_initial_state)
 {
-    SymmetricState noise{SymmetricState::HandshakeKind::KNpsk0_P256_AESGCM_SHA256};
+    const SymmetricState noise{SymmetricState::HandshakeKind::KNpsk0_P256_AESGCM_SHA256};
     // Values come from an alternative implementation of Dong Sun Lee
     EXPECT_EQ(noise.GetHandshakeHash(),
               (CryptoBuffer{0x4e, 0x6f, 0x69, 0x73, 0x65, 0x5f, 0x4b, 0x4e, 0x70, 0x73, 0x6b,
                             0x30, 0x5f, 0x50, 0x32, 0x35, 0x36, 0x5f, 0x41, 0x45, 0x53, 0x47,
                             0x43, 0x4d, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x00}));
-    auto splitRes = noise.Split();
+    const auto splitRes = noise.Split();
     EXPECT_EQ(splitRes.first.Key(),
               (CryptoBuffer{0xa4, 0xdb, 0x02, 0x9f, 0x61, 0x2c, 0x32, 0x49, 0x75, 0x2f, 0x90,
                             0xb9, 0x2d, 0xee, 0x29, 0xce, 0x0e, 0xa6, 0xe4, 0x97, 0xbd, 0xf9,
@@ -41,13 +41,13 @@ TEST(NoiseTest, KNpsk0_P256_AESGCM_SHA256_initial_state)
 
 TEST(NoiseTest, NKpsk0_P256_AESGCM_SHA256_initial_state)
 {
-    SymmetricState noise{SymmetricState::HandshakeKind::NKpsk0_P256_AESGCM_SHA256};
+    const SymmetricState noise{SymmetricState::HandshakeKind::NKpsk0_P256_AESGCM_SHA256};
     // Values come from an alternative implementation of Dong Sun Lee
     EXPECT_EQ(noise.GetHandshakeHash(),
               (CryptoBuffer{0x4e, 0x6f, 0x69, 0x73, 0x65, 0x5f, 0x4e, 0x4b, 0x70, 0x73, 0x6b,
                             0x30, 0x5f, 0x50, 0x32, 0x35, 0x36, 0x5f, 0x41, 0x45, 0x53, 0x47,
                             0x43, 0x4d, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x00}));
-    auto splitRes = noise.Split();
+    const auto splitRes = noise.Split();
     EXPECT_EQ(splitRes.first.Key(),
               (CryptoBuffer{0xd8, 0xf4, 0x83, 0x2e, 0x80, 0x4c, 0x5e, 0x6b, 0x5b, 0x5f, 0xd9,
                             0xd7, 0x70, 0x88, 0x78, 0xef, 0xbb, 0x72, 0xfb, 0x0d, 0x76, 0x79,
@@ -183,8 +183,8 @@ TEST(NoiseTest, KNpsk0_P256_AESGCM_SHA256_Encrypt_Decrypt)
     SymmetricState noise{SymmetricState::HandshakeKind::KNpsk0_P256_AESGCM_SHA256};
     noise.MixKeyAndHash({'a', 'b', 'c'});
 
-    CryptoBuffer msg1 = {'x', 'y', 'z'};
-    CryptoBuffer msg2(77, 0x0b);
+    const CryptoBuffer msg1 = {'x', 'y', 'z'};
+    const CryptoBuffer msg2(77, 0x0b);
 
     auto noise2 = noise;
     auto ciphertext1 = noise.EncryptAndHash(msg1);
@@ -233,8 +233,8 @@ TEST(NoiseTest, NKpsk0_P256_AESGCM_SHA256_Encrypt_Decrypt)
     SymmetricState noise{SymmetricState::HandshakeKind::NKpsk0_P256_AESGCM_SHA256};
     noise.MixKeyAndHash({'a', 'b', 'c'});
 
-    CryptoBuffer msg1 = {'x', 'y', 'z'};
-    CryptoBuffer msg2(77, 0x0b);
+    const CryptoBuffer msg1 = {'x', 'y', 'z'};
+    const CryptoBuffer msg2(77, 0x0b);
 
     auto noise2 = noise;
     auto ciphertext1 = noise.EncryptAndHash(msg1);
index 5d4e725662a4c1a6f7345b5c3cbbcb6d4df5d648..b95560f2ad43f068ae6c2d13a7eca752efe4293e 100644 (file)
@@ -205,14 +205,14 @@ void CheckAndroidPostHandshakeResponse(const PostHandshakeResponse &phr)
 void CheckAndroidUpdateMessage(const UpdateMessage &upMsg, const BufferView &rawUpdateMsg)
 {
     ASSERT_NE(upMsg.GetLinkData(), std::nullopt);
-    EXPECT_EQ(ToBufferView(upMsg.GetLinkData()->m_contactId), rawUpdateMsg.substr(185, 152));
-    EXPECT_EQ(ToBufferView(upMsg.GetLinkData()->m_linkId), rawUpdateMsg.substr(339, 8));
-    EXPECT_EQ(ToBufferView(upMsg.GetLinkData()->m_linkSecret), rawUpdateMsg.substr(350, 32));
-    EXPECT_EQ(ToBufferView(upMsg.GetLinkData()->m_authenticatorPublicKey),
-              rawUpdateMsg.substr(385, 65));
-    EXPECT_EQ(ToBufferView(upMsg.GetLinkData()->m_authenticatorName), rawUpdateMsg.substr(452, 5));
-    EXPECT_EQ(ToBufferView(upMsg.GetLinkData()->m_handshakeSignature),
-              rawUpdateMsg.substr(460, 32));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
+    const auto &linkData = *upMsg.GetLinkData();
+    EXPECT_EQ(ToBufferView(linkData.m_contactId), rawUpdateMsg.substr(185, 152));
+    EXPECT_EQ(ToBufferView(linkData.m_linkId), rawUpdateMsg.substr(339, 8));
+    EXPECT_EQ(ToBufferView(linkData.m_linkSecret), rawUpdateMsg.substr(350, 32));
+    EXPECT_EQ(ToBufferView(linkData.m_authenticatorPublicKey), rawUpdateMsg.substr(385, 65));
+    EXPECT_EQ(ToBufferView(linkData.m_authenticatorName), rawUpdateMsg.substr(452, 5));
+    EXPECT_EQ(ToBufferView(linkData.m_handshakeSignature), rawUpdateMsg.substr(460, 32));
 }
 
 const auto CTAP_SHUTDOWN_MESSAGE = BUFFER_VIEW("\x00");
@@ -247,9 +247,12 @@ TEST(CtapMessageProcessor, IphoneExampleMakeCredential)
     EXPECT_EQ(res.response.m_authData.m_rpIdHash, rawMCResp.substr(12, 32));
     EXPECT_EQ(res.response.m_authData.m_flags, rawMCResp[44]);
     ASSERT_NE(res.response.m_authData.m_attestationData, std::nullopt);
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(res.response.m_authData.m_attestationData->m_credentialId, rawMCResp.substr(67, 20));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(ToBufferView(res.response.m_authData.m_attestationData->m_publicKeyDer),
               BUFFER_VIEW(IPHONE_EXAMPLE_MAKE_CREDENTIAL_RAW_RESPONSE_PUBLIC_KEY_DER));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(res.response.m_authData.m_attestationData->m_alg,
               WAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256);
     EXPECT_EQ(ToBufferView(res.response.m_attestationObject), rawMCResp.substr(2));
@@ -286,9 +289,12 @@ TEST(CtapMessageProcessor, AndroidExampleMakeCredentialWithoutUpdateMessage)
     EXPECT_EQ(res.response.m_authData.m_rpIdHash, rawMCResp.substr(12, 32));
     EXPECT_EQ(res.response.m_authData.m_flags, rawMCResp[44]);
     ASSERT_NE(res.response.m_authData.m_attestationData, std::nullopt);
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(res.response.m_authData.m_attestationData->m_credentialId, rawMCResp.substr(67, 32));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(ToBufferView(res.response.m_authData.m_attestationData->m_publicKeyDer),
               BUFFER_VIEW(ANDROID_EXAMPLE_MAKE_CREDENTIAL_RAW_RESPONSE_PUBLIC_KEY_DER));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(res.response.m_authData.m_attestationData->m_alg,
               WAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256);
     EXPECT_EQ(ToBufferView(res.response.m_attestationObject), rawMCResp.substr(2));
@@ -327,9 +333,12 @@ TEST(CtapMessageProcessor, AndroidExampleMakeCredentialWithUpdateMessage)
     EXPECT_EQ(res.response.m_authData.m_rpIdHash, rawMCResp.substr(12, 32));
     EXPECT_EQ(res.response.m_authData.m_flags, rawMCResp[44]);
     ASSERT_NE(res.response.m_authData.m_attestationData, std::nullopt);
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(res.response.m_authData.m_attestationData->m_credentialId, rawMCResp.substr(67, 32));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(ToBufferView(res.response.m_authData.m_attestationData->m_publicKeyDer),
               BUFFER_VIEW(ANDROID_EXAMPLE_MAKE_CREDENTIAL_RAW_RESPONSE_PUBLIC_KEY_DER));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(res.response.m_authData.m_attestationData->m_alg,
               WAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256);
     EXPECT_EQ(ToBufferView(res.response.m_attestationObject), rawMCResp.substr(2));
@@ -793,7 +802,8 @@ namespace {
 
 class ProcessingFollowingUpdateMsgsMEncryptedTunnel : public IEncryptedTunnel {
 public:
-    ProcessingFollowingUpdateMsgsMEncryptedTunnel(std::vector<CryptoBuffer> &&messagesToRead)
+    explicit ProcessingFollowingUpdateMsgsMEncryptedTunnel(
+        std::vector<CryptoBuffer> &&messagesToRead)
     : m_messagesToRead{std::move(messagesToRead)}
     {
     }
@@ -883,7 +893,7 @@ TEST(CtapMessageProcessor, ProcessFollowingUpdateMsgs_passes_parsed_messages_to_
         cmp.SetEncryptedTunnel(std::move(encryptedTunnelUPtr));
 
         size_t callbackCalledNum = 0;
-        EXPECT_NO_THROW(cmp.ProcessFollowingUpdateMsgs([&](UpdateMessage &&updateMsg) {
+        EXPECT_NO_THROW(cmp.ProcessFollowingUpdateMsgs([&](const UpdateMessage &updateMsg) {
             ++callbackCalledNum;
 
             UpdateMessage expectedUpdateMsg;
index b6c9d72edac039fdd27c4e255c7529dc33e25cee..f14e289ded016a334fd929a4236ee3d483699406 100644 (file)
@@ -20,8 +20,8 @@
 
 TEST(DeriveKey, Simple)
 {
-    CryptoBuffer secret = {'s', 'e', 'c', 'r', 'e', 't'};
-    CryptoBuffer salt = {'s', 'a', 'l', 't'};
+    const CryptoBuffer secret = {'s', 'e', 'c', 'r', 'e', 't'};
+    const CryptoBuffer salt = {'s', 'a', 'l', 't'};
 
     EXPECT_EQ(
         DeriveKey(secret, salt, KeyPurpose::EIDKey, 64),
@@ -57,8 +57,8 @@ TEST(DeriveKey, Simple)
 
 TEST(DeriveKey, empty_salt)
 {
-    CryptoBuffer secret = {'s', 'e', 'c', 'r', 'e', 't'};
-    CryptoBuffer salt;
+    const CryptoBuffer secret = {'s', 'e', 'c', 'r', 'e', 't'};
+    const CryptoBuffer salt;
 
     EXPECT_EQ(DeriveKey(secret, salt, KeyPurpose::EIDKey, 8),
               (CryptoBuffer{0x38, 0x6f, 0x97, 0x0e, 0xbc, 0x4f, 0xac, 0x0e}));
@@ -72,8 +72,8 @@ TEST(DeriveKey, empty_salt)
 
 TEST(DeriveKey, empty_key)
 {
-    CryptoBuffer secret;
-    CryptoBuffer salt;
+    const CryptoBuffer secret;
+    const CryptoBuffer salt;
 
     EXPECT_EQ(DeriveKey(secret, salt, KeyPurpose::EIDKey, 0), CryptoBuffer{});
     EXPECT_EQ(DeriveKey(secret, salt, KeyPurpose::TunnelID, 0), CryptoBuffer{});
index 2044eab9fff6e7aa2407bccb684a76bce0e11ce5..6bd07d2fda133ea68707eb4a8bd961ae04eeab83 100644 (file)
@@ -17,6 +17,7 @@
 #include "crypto/openssl_error.h"
 #include "crypto/random.h"
 #include "encrypted_tunnel.h"
+#include "exception.h"
 #include "test_cancel_from_the_other_thread.h"
 #include "tunnel.h"
 
@@ -117,7 +118,7 @@ TEST(EncryptedTunnel, works)
 
 TEST(EncryptedTunnel, invalid_data)
 {
-    using namespace Exception;
+    using Exception::Unknown;
 
     auto readerWriter = Crypto::Noise::SymmetricState::CipherState{
         CryptoBuffer(Crypto::Noise::KEY_AND_HASH_LEN, 0x1)};
@@ -150,33 +151,33 @@ namespace {
 
 class CloseConnectionAfterMTunnel : public ITunnel {
 public:
-    void Connect(const std::string &, std::optional<ExtraHttpHeader>)
+    void Connect(const std::string &, std::optional<ExtraHttpHeader>) override
     {
         throw std::runtime_error{__FUNCTION__ + std::string{"() should not be called"}};
     }
 
-    void WriteBinary(const std::vector<uint8_t> &)
+    void WriteBinary(const std::vector<uint8_t> &) override
     {
         throw std::runtime_error{__FUNCTION__ + std::string{"() should not be called"}};
     }
 
-    std::vector<uint8_t> ReadBinary()
+    std::vector<uint8_t> ReadBinary() override
     {
         throw std::runtime_error{__FUNCTION__ + std::string{"() should not be called"}};
     }
 
-    void CloseConnectionAfter(uint32_t usecs)
+    void CloseConnectionAfter(uint32_t usecs) override
     {
         m_called += "CloseConnectionAfter;";
         m_closeConnectionAfterUsecs = usecs;
     }
 
-    void Disconnect()
+    void Disconnect() override
     {
         throw std::runtime_error{__FUNCTION__ + std::string{"() should not be called"}};
     }
 
-    void Cancel()
+    void Cancel() override
     {
         throw std::runtime_error{__FUNCTION__ + std::string{"() should not be called"}};
     }
index 4e9fe74c9d68887ef505eaffbacb082f1694884a..1e6a9a160776f57d9c07813d0bb844a73117d823 100644 (file)
@@ -76,13 +76,14 @@ public:
     {
     }
 
-    void Connect(const std::string &url,
-                 std::optional<ExtraHttpHeader> extraHttpHeader = std::nullopt) override
+    void Connect(const std::string &url, std::optional<ExtraHttpHeader> extraHttpHeader) override
     {
         EXPECT_EQ(url, m_expectedUrl);
-        EXPECT_EQ(extraHttpHeader.has_value(), m_expectedExtraHttpHeader.has_value());
+        ASSERT_EQ(extraHttpHeader.has_value(), m_expectedExtraHttpHeader.has_value());
         if (extraHttpHeader) {
+            // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
             EXPECT_EQ(extraHttpHeader->name, m_expectedExtraHttpHeader->name);
+            // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
             EXPECT_EQ(extraHttpHeader->value, m_expectedExtraHttpHeader->value);
         }
     }
@@ -187,7 +188,8 @@ public:
             noise.MixKey(
                 Crypto::deriveECDHSharedSecret(*m_authenticatorPrivKey, platformEphemeralPubKey));
 
-        auto ciphertext = CryptoBuffer{msg.begin() + exportedPlatformEphemeralPubKeyLen, msg.end()};
+        auto ciphertext = CryptoBuffer{
+            msg.begin() + static_cast<int>(exportedPlatformEphemeralPubKeyLen), msg.end()};
         auto plaintext = noise.DecryptAndHash(ciphertext);
         EXPECT_EQ(plaintext, CryptoBuffer{});
 
@@ -272,7 +274,7 @@ public:
 
     void RunAndTestHandshake(IHandshake &handshake)
     {
-        CryptoBuffer authenticatorPubKey = m_authenticatorPrivKey.ExportPublicKey(false);
+        const CryptoBuffer authenticatorPubKey = m_authenticatorPrivKey.ExportPublicKey(false);
         auto res = handshake.DoStateAssistedHandshake(m_psk, authenticatorPubKey);
         EXPECT_EQ(res.encryptedTunnel->ReadBinary(), m_getInfoMsg);
     }
@@ -303,7 +305,7 @@ namespace {
 
 class CancellationConnectMTunnel : public ShouldNotBeUsedMTunnel {
 public:
-    void Connect(const std::string &, std::optional<ExtraHttpHeader> = std::nullopt) override
+    void Connect(const std::string &, std::optional<ExtraHttpHeader>) override
     {
         m_cancelFacilitator.CancelCheck();
     }
index 3521344f05f8d7fa47eb661c08ff9df23f3b81bc..8f85fd9b9af10bb313f6cbcd82846e1c53296795 100644 (file)
@@ -74,7 +74,8 @@ struct TestContents {
             linkedData->tunnelServerDomain = ToBuffer(*ld->tunnel_server_domain);
             linkedData->identityKey = ToBuffer(*ld->identity_key);
             std::cout << "  linked data: authenticator's public key: "
-                      << LowercaseHexStringOf(linkedData->authenticatorPubKey) << std::endl;
+                      << LowercaseHexStringOf(linkedData->authenticatorPubKey)
+                      << std::endl; // NOLINT(performance-avoid-endl)
         } else {
             linkedData = std::nullopt;
         }
@@ -84,26 +85,28 @@ struct TestContents {
 void DisplayQR(struct TestContents &testContents)
 {
     int ret;
-    std::string command = "chsmack -a '_' '";
-    command += testContents.qrCodeImagePath.c_str();
+    std::string command = "/usr/bin/chsmack -a '_' '";
+    command += testContents.qrCodeImagePath;
     command += '\'';
 
+    // NOLINTNEXTLINE(cert-env33-c,concurrency-mt-unsafe)
     ret = system(command.c_str());
     if (ret) {
         std::cout << "chsmack command failed\n"
-                  << "System() returned: " << ret << std::endl;
+                  << "System() returned: " << ret << std::endl; // NOLINT(performance-avoid-endl)
         testContents.succeeded = false;
         return;
     }
 
-    command = "launch_app org.tizen.image-viewer Path ";
-    command += testContents.qrCodeImagePath.c_str();
+    command = "/usr/bin/launch_app org.tizen.image-viewer Path ";
+    command += testContents.qrCodeImagePath;
 
-    std::cout << "Launching QR code viewer..." << std::endl;
+    std::cout << "Launching QR code viewer..." << std::endl; // NOLINT(performance-avoid-endl)
+    // NOLINTNEXTLINE(cert-env33-c,concurrency-mt-unsafe)
     ret = system(command.c_str());
     if (ret) {
         std::cout << "launch_app command failed\n"
-                  << "System() returned: " << ret << std::endl;
+                  << "System() returned: " << ret << std::endl; // NOLINT(performance-avoid-endl)
         testContents.succeeded = false;
     }
 }
@@ -115,11 +118,11 @@ void GenerateAndDisplayQR(const std::string &encoded, struct TestContents &testC
     static constexpr int height = 300;
     static constexpr int qr_version = 5;
 
-    mv_engine_config_h engine_cfg = NULL;
-    mv_barcode_type_e type = MV_BARCODE_QR;
-    mv_barcode_qr_mode_e qr_enc_mode = MV_BARCODE_QR_MODE_UTF8;
-    mv_barcode_qr_ecc_e qr_ecc = MV_BARCODE_QR_ECC_LOW;
-    mv_barcode_image_format_e image_format = MV_BARCODE_IMAGE_FORMAT_PNG;
+    mv_engine_config_h engine_cfg = nullptr;
+    const mv_barcode_type_e type = MV_BARCODE_QR;
+    const mv_barcode_qr_mode_e qr_enc_mode = MV_BARCODE_QR_MODE_UTF8;
+    const mv_barcode_qr_ecc_e qr_ecc = MV_BARCODE_QR_ECC_LOW;
+    const mv_barcode_image_format_e image_format = MV_BARCODE_IMAGE_FORMAT_PNG;
 
     ret = mv_barcode_generate_image(engine_cfg,
                                     encoded.c_str(),
@@ -134,7 +137,7 @@ void GenerateAndDisplayQR(const std::string &encoded, struct TestContents &testC
 
     if (ret != MEDIA_VISION_ERROR_NONE) {
         std::cout << "mv_barcode_generate_image failed\n"
-                  << "Error code: " << ret << std::endl;
+                  << "Error code: " << ret << std::endl; // NOLINT(performance-avoid-endl)
         testContents.succeeded = false;
     } else {
         DisplayQR(testContents);
@@ -143,15 +146,17 @@ void GenerateAndDisplayQR(const std::string &encoded, struct TestContents &testC
 
 void DisplayQRCallback(const char *qrContents, void *data)
 {
-    std::cout << "qrcode_callback() was called." << std::endl;
+    std::cout << "qrcode_callback() was called." << std::endl; // NOLINT(performance-avoid-endl)
     auto testContents = static_cast<TestContents *>(data);
     if (!qrContents) {
-        std::cout << "qrcode_callback(): NULL qrContents" << std::endl;
+        std::cout << "qrcode_callback(): NULL qrContents"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (testContents->qrCodeImagePath.empty()) {
-        std::cout << "qrcode_callback(): empty QR code path" << std::endl;
+        std::cout << "qrcode_callback(): empty QR code path"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
@@ -318,64 +323,76 @@ void MCCallback(const wauthn_pubkey_credential_attestation_s *pubkey_cred,
                 wauthn_error_e result,
                 void *data)
 {
-    std::cout << "MakeCredential: response_callback() was called." << std::endl;
+    std::cout << "MakeCredential: response_callback() was called."
+              << std::endl; // NOLINT(performance-avoid-endl)
     auto *testContents = static_cast<TestContents *>(data);
     if (result != WAUTHN_ERROR_NONE) {
-        std::cout << __FUNCTION__ << ": response_callback failed with code " << result << std::endl;
+        std::cout << __FUNCTION__ << ": response_callback failed with code " << result
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (!pubkey_cred) {
-        std::cout << __FUNCTION__ << ": pubkey_cred is NULL" << std::endl;
+        std::cout << __FUNCTION__ << ": pubkey_cred is NULL"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (!pubkey_cred->rawId) {
-        std::cout << __FUNCTION__ << ": pubkey_cred->rawId is NULL" << std::endl;
+        std::cout << __FUNCTION__ << ": pubkey_cred->rawId is NULL"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (!pubkey_cred->response) {
-        std::cout << __FUNCTION__ << ": pubkey_cred->response is NULL" << std::endl;
+        std::cout << __FUNCTION__ << ": pubkey_cred->response is NULL"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
 
     testContents->credentialRawId = ToBuffer(*pubkey_cred->rawId);
     std::cout << "MakeCredential: credentialRawId: "
-              << LowercaseHexStringOf(testContents->credentialRawId) << std::endl;
+              << LowercaseHexStringOf(testContents->credentialRawId)
+              << std::endl; // NOLINT(performance-avoid-endl)
     testContents->transports = pubkey_cred->response->transports;
     testContents->UpdateLinkedData(pubkey_cred->linked_device);
 
     testContents->GAThread = std::thread([testContents] { TestGA(*testContents); });
 
-    std::cout << "MakeCredential: awaiting potential CTAP UPDATE messages..." << std::endl;
+    std::cout << "MakeCredential: awaiting potential CTAP UPDATE messages..."
+              << std::endl; // NOLINT(performance-avoid-endl)
 }
 
 void GACallback(const wauthn_pubkey_credential_assertion_s *pubkey_cred,
                 wauthn_error_e result,
                 void *data)
 {
-    std::cout << "GetAssertion: response_callback() was called." << std::endl;
+    std::cout << "GetAssertion: response_callback() was called."
+              << std::endl; // NOLINT(performance-avoid-endl)
     auto *testContents = static_cast<TestContents *>(data);
     auto lock = std::lock_guard{testContents->mutex};
     if (result != WAUTHN_ERROR_NONE) {
-        std::cout << __FUNCTION__ << ": response_callback failed with code " << result << std::endl;
+        std::cout << __FUNCTION__ << ": response_callback failed with code " << result
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (!pubkey_cred) {
-        std::cout << __FUNCTION__ << ": pubkey_cred is NULL" << std::endl;
+        std::cout << __FUNCTION__ << ": pubkey_cred is NULL"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (!pubkey_cred->rawId) {
-        std::cout << __FUNCTION__ << ": pubkey_cred->rawId is NULL" << std::endl;
+        std::cout << __FUNCTION__ << ": pubkey_cred->rawId is NULL"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
     if (!pubkey_cred->response) {
-        std::cout << __FUNCTION__ << ": pubkey_cred->response is NULL" << std::endl;
+        std::cout << __FUNCTION__ << ": pubkey_cred->response is NULL"
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
@@ -383,7 +400,8 @@ void GACallback(const wauthn_pubkey_credential_assertion_s *pubkey_cred,
     auto credentialRawId = ToBuffer(*pubkey_cred->rawId);
     if (credentialRawId != testContents->credentialRawId) {
         std::cout << "Error: invalid credentialRawId in GA: "
-                  << LowercaseHexStringOf(credentialRawId) << std::endl;
+                  << LowercaseHexStringOf(credentialRawId)
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents->succeeded = false;
         return;
     }
@@ -392,7 +410,7 @@ void GACallback(const wauthn_pubkey_credential_assertion_s *pubkey_cred,
         auto userHandle = ToBuffer(*pubkey_cred->response->user_handle);
         if (userHandle != testContents->userId) {
             std::cout << "Error: invalid userHandle in GA: " << LowercaseHexStringOf(userHandle)
-                      << std::endl;
+                      << std::endl; // NOLINT(performance-avoid-endl)
             testContents->succeeded = false;
             return;
         }
@@ -400,7 +418,8 @@ void GACallback(const wauthn_pubkey_credential_assertion_s *pubkey_cred,
 
     testContents->UpdateLinkedData(pubkey_cred->linked_device);
 
-    std::cout << "GetAssertion: awaiting potential CTAP UPDATE messages..." << std::endl;
+    std::cout << "GetAssertion: awaiting potential CTAP UPDATE messages..."
+              << std::endl; // NOLINT(performance-avoid-endl)
 }
 
 void UpdateLinkedDataCallbackImpl(const wauthn_hybrid_linked_data_s *linkedData,
@@ -413,7 +432,7 @@ void UpdateLinkedDataCallbackImpl(const wauthn_hybrid_linked_data_s *linkedData,
         std::cout
             << __FUNCTION__
             << ": update_linked_data callback called after it was called with WAUTHN_ERROR_NONE"
-            << std::endl;
+            << std::endl; // NOLINT(performance-avoid-endl)
         testContents.succeeded = false;
         return;
     }
@@ -421,7 +440,7 @@ void UpdateLinkedDataCallbackImpl(const wauthn_hybrid_linked_data_s *linkedData,
         seenLastUpdateCallback = true;
     else if (result != WAUTHN_ERROR_NONE_AND_WAIT) {
         std::cout << __FUNCTION__ << ": update_linked_data callback failed with code: " << result
-                  << std::endl;
+                  << std::endl; // NOLINT(performance-avoid-endl)
         testContents.succeeded = false;
         return;
     }
@@ -432,27 +451,30 @@ void MCUpdateLinkedDataCallback(const wauthn_hybrid_linked_data_s *linkedData,
                                 wauthn_error_e result,
                                 void *data)
 {
-    std::cout << "MakeCredential: update_linked_data() was called." << std::endl;
+    std::cout << "MakeCredential: update_linked_data() was called."
+              << std::endl; // NOLINT(performance-avoid-endl)
     auto *testContents = static_cast<TestContents *>(data);
     auto lock = std::lock_guard{testContents->mutex};
     UpdateLinkedDataCallbackImpl(
         linkedData, result, *testContents, lock, testContents->seenLastMCUpdateCallback);
     if (result == WAUTHN_ERROR_NONE)
         std::cout << "MakeCredential: finished awaiting potential CTAP UPDATE messages."
-                  << std::endl;
+                  << std::endl; // NOLINT(performance-avoid-endl)
 }
 
 void GAUpdateLinkedDataCallback(const wauthn_hybrid_linked_data_s *linkedData,
                                 wauthn_error_e result,
                                 void *data)
 {
-    std::cout << "GetAssertion: update_linked_data() was called." << std::endl;
+    std::cout << "GetAssertion: update_linked_data() was called."
+              << std::endl; // NOLINT(performance-avoid-endl)
     auto *testContents = static_cast<TestContents *>(data);
     auto lock = std::lock_guard{testContents->mutex};
     UpdateLinkedDataCallbackImpl(
         linkedData, result, *testContents, lock, testContents->seenLastGAUpdateCallback);
     if (result == WAUTHN_ERROR_NONE)
-        std::cout << "GetAssertion: finished awaiting potential CTAP UPDATE messages." << std::endl;
+        std::cout << "GetAssertion: finished awaiting potential CTAP UPDATE messages."
+                  << std::endl; // NOLINT(performance-avoid-endl)
 }
 
 } // anonymous namespace
@@ -480,9 +502,10 @@ int main(int argc, char *argv[])
     if (argc == 2 && std::string_view("-n") == argv[1])
         testContents.negative = true;
 
-    int err = TurnBluetoothOn();
+    const int err = TurnBluetoothOn();
     if (err != BT_ERROR_NONE) {
-        std::cout << "Turning bluetooth on failed with " << BtErrorToString(err) << std::endl;
+        std::cout << "Turning bluetooth on failed with " << BtErrorToString(err)
+                  << std::endl; // NOLINT(performance-avoid-endl)
         return 2;
     }
 
@@ -494,6 +517,7 @@ int main(int argc, char *argv[])
         ret = 1;
     }
 
+    // NOLINTNEXTLINE(cert-env33-c,concurrency-mt-unsafe)
     if (system("/usr/bin/killall /usr/apps/org.tizen.image-viewer_common/bin/image-viewer")) {
         std::cout << "Cannot close org.tizen.image-viewer\n";
         ret = 1;
index a44168f55b919af7ebda675078920a5cabff58d6..be5a418df61ec0c77a991e1c7e39929d0d0b5a37 100644 (file)
@@ -256,8 +256,8 @@ TEST(Messages, ParsePostHandshakeMessage2)
 
 TEST(Messages, DomainName)
 {
-    std::string notTooLongLabel(63, 'a');
-    std::string tooLongLabel(64, 'a');
+    const std::string notTooLongLabel(63, 'a');
+    const std::string tooLongLabel(64, 'a');
     std::string tooLongDomain = notTooLongLabel;
     while (tooLongDomain.size() < 254)
         tooLongDomain += "." + notTooLongLabel;
@@ -352,7 +352,7 @@ TEST(Messages, SerializeMakeCredential1)
 
     // serialize MC command
     Buffer buffer;
-    MakeCredentialCommand msg(client_data, options, {false, false});
+    const MakeCredentialCommand msg(client_data, options, {false, false});
 
     ASSERT_NO_THROW(msg.Serialize(buffer));
 
@@ -440,7 +440,7 @@ TEST(Messages, SerializeMakeCredential2)
 
     // serialize MC command
     Buffer buffer;
-    MakeCredentialCommand msg(client_data, options, {false, false});
+    const MakeCredentialCommand msg(client_data, options, {false, false});
 
     ASSERT_NO_THROW(msg.Serialize(buffer));
     EXPECT_EQ(ToBufferView(buffer),
@@ -502,7 +502,7 @@ TEST(Messages, SerializeGetAssertion)
 
     // serialize GA command
     Buffer buffer;
-    GetAssertionCommand msg(client_data, options, {false, false});
+    const GetAssertionCommand msg(client_data, options, {false, false});
 
     ASSERT_NO_THROW(msg.Serialize(buffer));
     EXPECT_EQ(ToBufferView(buffer),
@@ -511,7 +511,7 @@ TEST(Messages, SerializeGetAssertion)
 
 TEST(Messages, ShutdownMessage)
 {
-    ShutdownMessage shutdown;
+    const ShutdownMessage shutdown;
     Buffer buffer;
     ASSERT_NO_THROW(shutdown.Serialize(buffer));
     EXPECT_EQ(ToBufferView(buffer), BUFFER_VIEW("\x00"));
@@ -531,9 +531,12 @@ TEST(Messages, ParseMakeCredentialResponseFromIphone)
     EXPECT_NO_THROW(VerifyRpIdHash("acme.com", msg.m_authData.m_rpIdHash));
     EXPECT_EQ(msg.m_authData.m_flags, blob[43]);
     ASSERT_NE(msg.m_authData.m_attestationData, std::nullopt);
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(msg.m_authData.m_attestationData->m_credentialId, (BufferView{blob + 66, 20}));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(msg.m_authData.m_attestationData->m_publicKeyDer,
               BUFFER(IPHONE_EXAMPLE_MAKE_CREDENTIAL_RAW_RESPONSE_PUBLIC_KEY_DER));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(msg.m_authData.m_attestationData->m_alg,
               WAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256);
     EXPECT_EQ(ToBufferView(msg.m_attestationObject), view);
@@ -556,9 +559,12 @@ TEST(Messages, ParseMakeCredentialResponseFromAndroid)
     EXPECT_NO_THROW(VerifyRpIdHash("acme.com", msg.m_authData.m_rpIdHash));
     EXPECT_EQ(msg.m_authData.m_flags, blob[43]);
     ASSERT_NE(msg.m_authData.m_attestationData, std::nullopt);
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(msg.m_authData.m_attestationData->m_credentialId, (BufferView{blob + 66, 32}));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(msg.m_authData.m_attestationData->m_publicKeyDer,
               BUFFER(ANDROID_EXAMPLE_MAKE_CREDENTIAL_RAW_RESPONSE_PUBLIC_KEY_DER));
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     EXPECT_EQ(msg.m_authData.m_attestationData->m_alg,
               WAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256);
     EXPECT_EQ(ToBufferView(msg.m_attestationObject), view);
@@ -616,6 +622,7 @@ TEST(Messages, ParseUpdateMessage)
 
     auto linkDataOpt = msg.GetLinkData();
     ASSERT_NE(linkDataOpt, std::nullopt);
+    // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
     const auto &linkData = *linkDataOpt;
 
     const auto *blob = reinterpret_cast<const uint8_t *>(ANDROID_EXAMPLE_RAW_UPDATE_MSG) + 1;
index cc1b4b17c91219a98c0d634384e9123e6eedc46d..091718eea1f37e438910667106c7c903e872f495 100644 (file)
@@ -23,7 +23,7 @@ TEST(QrCodeShower, callback_is_called)
 {
     QrCodeShower qrCodeShower;
     int calledNumTimes = 0;
-    qrCodeShower.ShowQrCode({}, {}, {'m', 'c'}, true, [&](std::string &&contents) {
+    qrCodeShower.ShowQrCode({}, {}, {'m', 'c'}, true, [&](const std::string &contents) {
         EXPECT_THAT(contents, testing::StartsWith("FIDO:/"));
         ++calledNumTimes;
     });
index db40d19cf115fce4be77665f6577e7525e431871..93e85b5015db8fddc752bd8b15ed3c8474423897 100644 (file)
@@ -15,7 +15,6 @@
  */
 
 #include "crypto/random.h"
-#include "get_random.h"
 #include "qr_transaction.h"
 #include "transaction_test.h"
 
@@ -89,8 +88,7 @@ public:
         return {};
     }
 
-    virtual void
-    StateAssistedConnect(const std::string &, const BufferView &, const BufferView &) override
+    void StateAssistedConnect(const std::string &, const BufferView &, const BufferView &) override
     {
         ADD_FAILURE() << "This should not be called";
         throw std::runtime_error{""};
index a3e29e36a00c168070e294aec015bca42d58fa5c..5703413f53b36bdcf026a772c7063bac0c0e0b63 100644 (file)
@@ -695,8 +695,8 @@ TEST(RequestHandler, perform_transaction_throws_int)
 {
     TestAll4Transactions<PotentialErrorsTest>(
         [](auto &test, auto &options) {
-            options.mcResultProcessor = [](auto &) { throw 42; };
-            options.gaResultProcessor = [](auto &) { throw 42; };
+            options.mcResultProcessor = [](auto &) { throw 42; }; // NOLINT
+            options.gaResultProcessor = [](auto &) { throw 42; }; // NOLINT
             options.followingCtapUpdatesProcessor = [&](auto &&) {
                 test.called += "update_processor;";
             };
@@ -761,7 +761,7 @@ void TestResponseCallbackThrows()
 
 void ThrowRuntimeError() { throw std::runtime_error{"xyz"}; }
 
-void ThrowInt() { throw 42; }
+void ThrowInt() { throw 42; } // NOLINT
 
 } // namespace
 
index b05b616fbf92ebc76ddaaa27f4ed77ebc13661ba..d266ad87bb9e7d45ae511d98fffdf6cd06c06ff1 100644 (file)
@@ -15,7 +15,6 @@
  */
 
 #include "derive_key.h"
-#include "get_random.h"
 #include "state_assisted_transaction.h"
 #include "to_wauthn_const_buff.h"
 #include "transaction_test.h"
@@ -67,9 +66,9 @@ public:
         throw std::runtime_error{""};
     }
 
-    virtual void StateAssistedConnect(const std::string &tunnelServerDomain,
-                                      const BufferView &contactId,
-                                      const BufferView &clientPayload) override
+    void StateAssistedConnect(const std::string &tunnelServerDomain,
+                              const BufferView &contactId,
+                              const BufferView &clientPayload) override
     {
         SCOPED_TRACE("");
 
@@ -281,7 +280,7 @@ TEST(StateAssistedTransaction, InvalidLinkData)
         }
     };
 
-    LinkedDevice origLinkedDevice;
+    const LinkedDevice origLinkedDevice;
 
     wauthn_hybrid_linked_data_s linkedDevice;
     doTest(nullptr);
@@ -328,8 +327,7 @@ public:
         throw std::runtime_error{""};
     }
 
-    virtual void
-    StateAssistedConnect(const std::string &, const BufferView &, const BufferView &) override
+    void StateAssistedConnect(const std::string &, const BufferView &, const BufferView &) override
     {
         m_cancelFacilitator.CancelCheck();
     }
index 7099e3107a270eb54728e96b81801ef7dedd97c4..b111db054854a2f28b1782f0bba44990bd4a8e30 100644 (file)
@@ -22,7 +22,6 @@
 #include <cassert>
 #include <chrono>
 #include <cstddef>
-#include <cstdint>
 #include <exception>
 #include <future>
 #include <gtest/gtest.h>
@@ -201,7 +200,7 @@ void TestCancelFromTheOtherThread(size_t reps,
 
     // Needs to be done on cout not to race with gtest output
     std::cout << "successfulCancellations: " << successfulCancellations << " of " << reps
-              << std::endl;
+              << std::endl; // NOLINT(performance-avoid-endl)
     // Reasonable number of cancellations has to happen, otherwise this code is wrong.
     EXPECT_GE(successfulCancellations, minExpectedCancellationsNum);
 }
index 7c3e331d3db7ded04130cdb99c541273679f682b..2bfa484fd56566ab1adac93178c8ac784c9071c9 100644 (file)
@@ -153,8 +153,7 @@ public:
 
 class ShouldNotBeCalledMHandshake : public IHandshake {
 public:
-    virtual void
-    QrInitiatedConnect(const std::string &, const BufferView &, const BufferView &) override
+    void QrInitiatedConnect(const std::string &, const BufferView &, const BufferView &) override
     {
         ADD_FAILURE() << "This should not be called";
         throw std::runtime_error{""};
@@ -167,8 +166,7 @@ public:
         throw std::runtime_error{""};
     }
 
-    virtual void
-    StateAssistedConnect(const std::string &, const BufferView &, const BufferView &) override
+    void StateAssistedConnect(const std::string &, const BufferView &, const BufferView &) override
     {
         ADD_FAILURE() << "This should not be called";
         throw std::runtime_error{""};
index 3961845e362b6d6a22ff54c264894e74646a6473..20558506623f1c17af471518291f1a608bead8da 100644 (file)
 #include "exception.h"
 #include "tunnel.h"
 
-#include <algorithm>
 #include <array>
 #include <cstring>
 #include <deque>
 #include <iostream>
 #include <memory>
 #include <optional>
+#include <sys/types.h>
 #include <thread>
 #include <unistd.h>
+#include <utility>
 
 namespace {
 struct Event {
@@ -55,7 +56,7 @@ struct MockedContext {
 };
 
 struct MockedLws {
-    MockedLws(MockedContext *ctx, const std::string &url) : m_mockedContext(ctx), m_url(url) {}
+    MockedLws(MockedContext *ctx, std::string url) : m_mockedContext(ctx), m_url(std::move(url)) {}
 
     MockedContext *m_mockedContext = nullptr;
     std::string m_url;
@@ -66,7 +67,7 @@ struct MockedLws {
     void PushEvent(enum lws_callback_reasons reason,
                    std::vector<uint8_t> data = std::vector<uint8_t>())
     {
-        std::lock_guard<std::mutex> lock(m_mutex);
+        const std::lock_guard<std::mutex> lock(m_mutex);
         m_queue.emplace_back(reason, std::move(data));
     }
 };
@@ -99,7 +100,7 @@ public:
 
     void ProcessEvent(MockedLws *mockedLws,
                       enum lws_callback_reasons reason,
-                      std::vector<uint8_t> data = {}) override
+                      std::vector<uint8_t> data) override
     {
         if (m_eventNo == m_runBefore)
             m_hook();
@@ -115,7 +116,7 @@ private:
 };
 
 class DelayedSockets : public MockedSockets {
-    void RandomDelay() const noexcept
+    static void RandomDelay() noexcept
     {
         try {
             std::this_thread::sleep_for(std::chrono::nanoseconds{get_random(0, 100'000)});
@@ -232,7 +233,7 @@ void MockedSockets::ProcessEvent(MockedLws *mockedLws,
             if (!mockedLws->m_extraHttpHeader ||
                 mockedLws->m_extraHttpHeader->name != TEST_HEADER_NAME ||
                 mockedLws->m_extraHttpHeader->value != TEST_HEADER_VALUE)
-                throw 1;
+                throw 1; // NOLINT
         }
     } else {
         m_listener->HandleEvent(lws, reason, data.empty() ? nullptr : data.data(), data.size());
@@ -249,7 +250,7 @@ Lws *MockedSockets::ClientConnect(LwsContext *lwsContext, const std::string &url
     try {
         auto mockedContext = Context2Mocked(lwsContext);
         {
-            std::lock_guard<std::mutex> guard(mockedContext->m_mutex);
+            const std::lock_guard<std::mutex> guard(mockedContext->m_mutex);
             if (mockedContext->m_cancelled)
                 return nullptr;
             mockedContext->m_connection = new MockedLws(mockedContext, url);
@@ -257,10 +258,10 @@ Lws *MockedSockets::ClientConnect(LwsContext *lwsContext, const std::string &url
         auto mockedLws = mockedContext->m_connection;
 
         // process events immediately
-        ProcessEvent(mockedLws, LWS_CALLBACK_PROTOCOL_INIT);
-        ProcessEvent(mockedLws, LWS_CALLBACK_CLIENT_HTTP_BIND_PROTOCOL);
-        ProcessEvent(mockedLws, LWS_CALLBACK_CONNECTING);
-        ProcessEvent(mockedLws, LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED);
+        ProcessEvent(mockedLws, LWS_CALLBACK_PROTOCOL_INIT, {});
+        ProcessEvent(mockedLws, LWS_CALLBACK_CLIENT_HTTP_BIND_PROTOCOL, {});
+        ProcessEvent(mockedLws, LWS_CALLBACK_CONNECTING, {});
+        ProcessEvent(mockedLws, LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, {});
 
         // schedule events
         mockedLws->PushEvent(LWS_CALLBACK_WSI_CREATE);
@@ -340,7 +341,7 @@ void MockedSockets::CancelService(LwsContext *lwsContext) noexcept
 {
     auto mockedContext = Context2Mocked(lwsContext);
     try {
-        std::lock_guard<std::mutex> guard(mockedContext->m_mutex);
+        const std::lock_guard<std::mutex> guard(mockedContext->m_mutex);
         mockedContext->m_cancelled = true;
         if (mockedContext->m_connection)
             mockedContext->m_connection->PushEvent(LWS_CALLBACK_EVENT_WAIT_CANCELLED);
@@ -359,7 +360,7 @@ int MockedSockets::WriteBinary(Lws *lws, unsigned char *buf, size_t len) noexcep
 
         // perform "echo" response
         mockedLws->PushEvent(LWS_CALLBACK_CLIENT_RECEIVE, std::move(buffer));
-        return len;
+        return static_cast<int>(len);
     } catch (...) {
         return 0;
     }
@@ -371,11 +372,11 @@ void MockedSockets::ContextDestroy(LwsContext *lwsContext) noexcept
         auto mockedContext = Context2Mocked(lwsContext);
         auto mockedLws = mockedContext->m_connection;
 
-        ProcessEvent(mockedLws, LWS_CALLBACK_CLIENT_CLOSED);
-        ProcessEvent(mockedLws, LWS_CALLBACK_WSI_DESTROY);
-        ProcessEvent(mockedLws, LWS_CALLBACK_PROTOCOL_DESTROY);
+        ProcessEvent(mockedLws, LWS_CALLBACK_CLIENT_CLOSED, {});
+        ProcessEvent(mockedLws, LWS_CALLBACK_WSI_DESTROY, {});
+        ProcessEvent(mockedLws, LWS_CALLBACK_PROTOCOL_DESTROY, {});
 
-        std::lock_guard<std::mutex> guard(mockedContext->m_mutex);
+        const std::lock_guard<std::mutex> guard(mockedContext->m_mutex);
         delete mockedContext->m_connection;
         mockedContext->m_connection = nullptr;
 
@@ -391,13 +392,14 @@ void MockedSockets::ContextDestroy(LwsContext *lwsContext) noexcept
 TEST(TunnelMockedTests, Cancel)
 {
     const std::string test = "sdfjisdjkfhdfjkghsdfkghdgkjhd";
-    std::vector<uint8_t> in, out;
+    std::vector<uint8_t> in;
+    std::vector<uint8_t> out;
     out.assign(test.c_str(), test.c_str() + test.size());
 
     std::unique_ptr<Tunnel> tunnel;
     auto cancel = [&] { tunnel->Cancel(); };
     auto sockets = std::make_shared<HookedSockets<decltype(cancel)>>(cancel);
-    tunnel.reset(new Tunnel(sockets));
+    tunnel = std::make_unique<Tunnel>(sockets);
 
     for (unsigned eventNo = 0; eventNo < 15; eventNo++) {
         sockets->RunBefore(eventNo);
@@ -486,7 +488,7 @@ TEST(TunnelMockedTests, InjectedEvents)
     }();
 
     // Max number of injections
-    constexpr size_t MAX_INJECTIONS = 2;
+    static constexpr size_t MAX_INJECTIONS = 2;
 
     using InjectionsMap = std::vector<EventInfo>;
     auto iterateAllInjections = [&](auto &&callback) {
@@ -501,7 +503,7 @@ TEST(TunnelMockedTests, InjectedEvents)
         // pow(REASONS.size(), MAX_INJECTIONS) combinations
         std::vector<size_t> reasonsIndices;
         std::vector<size_t> lastReasonsIndices;
-        assert(EVENT_ID_CNT > 0 && "needed for the first iteration to be valid");
+        static_assert(EVENT_ID_CNT > 0, "needed for the first iteration to be valid");
         for (;;) {
             // Skip places having value -1
             size_t startPos = 0;
@@ -541,7 +543,7 @@ TEST(TunnelMockedTests, InjectedEvents)
                 --i;
             }
             // Fix later places that are now equal to EVENT_ID_CNT
-            int minAvailablePlace = places[i];
+            const int minAvailablePlace = places[i];
             while (++i < places.size())
                 places[i] = minAvailablePlace;
         }
@@ -551,15 +553,15 @@ TEST(TunnelMockedTests, InjectedEvents)
     public:
         void ProcessEvent(MockedLws *mockedLws,
                           enum lws_callback_reasons reason,
-                          std::vector<uint8_t> data = std::vector<uint8_t>()) override
+                          std::vector<uint8_t> data) override
         {
             auto &expectedEvent = EXPECTED_ORDER[m_eventNo];
             EXPECT_EQ(reason, expectedEvent.reason) << "m_eventNo: " << m_eventNo;
 
             while (m_injectionsMapNextEventIdx < m_injectionsMap->size() &&
                    (*m_injectionsMap)[m_injectionsMapNextEventIdx].id == expectedEvent.id) {
-                MockedSockets::ProcessEvent(mockedLws,
-                                            (*m_injectionsMap)[m_injectionsMapNextEventIdx].reason);
+                MockedSockets::ProcessEvent(
+                    mockedLws, (*m_injectionsMap)[m_injectionsMapNextEventIdx].reason, {});
                 ++m_injectionsMapNextEventIdx;
             }
 
@@ -595,7 +597,8 @@ TEST(TunnelMockedTests, InjectedEvents)
     auto sockets = std::make_shared<InjectingSockets>();
     Tunnel tunnel(sockets);
     const std::string test = "sdfjisdjkfhdfjkghsdfkghdgkjhd";
-    std::vector<uint8_t> in, out;
+    std::vector<uint8_t> in;
+    std::vector<uint8_t> out;
     out.assign(test.c_str(), test.c_str() + test.size());
 
     size_t successes = 0;
@@ -637,7 +640,8 @@ TEST(TunnelMockedTests, CancelFromTheOtherThread)
 
         void Perform()
         {
-            std::vector<uint8_t> in, out(42);
+            std::vector<uint8_t> in;
+            const std::vector<uint8_t> out(42);
             m_tunnel.Connect(TestUrl());
             m_tunnel.WriteBinary(out);
             in = m_tunnel.ReadBinary();
index 7f2cb831f5d5e406da8d0b95cc3dfb9def1a73d8..3d46c0127cb3a824daf87231b74b568d6f221855 100644 (file)
@@ -16,7 +16,6 @@
 
 #pragma once
 
-#include "constants.h"
 #include "websockets.h"
 
 #include <gtest/gtest-param-test.h>
@@ -26,9 +25,8 @@ struct MockedLws;
 
 class MockedSockets : public IWebsockets {
 protected:
-    virtual void ProcessEvent(MockedLws *mockedLws,
-                              enum lws_callback_reasons reason,
-                              std::vector<uint8_t> data = {});
+    virtual void
+    ProcessEvent(MockedLws *mockedLws, enum lws_callback_reasons reason, std::vector<uint8_t> data);
     LwsContext *CreateContext() noexcept override;
     Lws *ClientConnect(LwsContext *lwsContext, const std::string &url) noexcept override;
     bool Service(LwsContext *lwsContext) noexcept override;
@@ -57,7 +55,6 @@ protected:
 
     void SetListener(IWebsocketsListener *listener) noexcept override { m_listener = listener; }
 
-protected:
     IWebsocketsListener *m_listener = nullptr;
 };
 
index 59af65f19f2e88fa193da89652406b1a427261c8..cd885a8545d2c968eefaa50485d6b160a8fcd2c6 100644 (file)
@@ -20,6 +20,7 @@
 #include "auto_tests.h"
 #endif
 #include "../get_random.h"
+#include "constants.h"
 #include "exception.h"
 #include "tunnel.h"
 
@@ -60,7 +61,10 @@ private:
 };
 } // namespace
 
-using namespace Exception;
+using Exception::Cancelled;
+using Exception::InvalidParam;
+using Exception::InvalidState;
+using Exception::Unknown;
 
 /*
  * Tests below are executed using two different websockets implementations:
@@ -72,7 +76,7 @@ using namespace Exception;
 template <typename T>
 struct TunnelTypedTests : public testing::Test {};
 
-TYPED_TEST_SUITE(TunnelTypedTests, MyTypes);
+TYPED_TEST_SUITE(TunnelTypedTests, MyTypes);
 
 TYPED_TEST(TunnelTypedTests, BigMessages)
 {
@@ -134,7 +138,7 @@ TYPED_TEST(TunnelTypedTests, FailingCallbackOnWritable)
     };
 
     Tunnel tunnel(std::make_shared<TestSockets>());
-    std::vector<uint8_t> out(16);
+    const std::vector<uint8_t> out(16);
 
     EXPECT_NO_THROW(tunnel.Connect(TestUrl()));
     EXPECT_THROW(tunnel.WriteBinary(out), InvalidState);
@@ -158,7 +162,7 @@ TYPED_TEST(TunnelTypedTests, WriteWrongState)
     };
 
     TestTunnel tunnel(std::make_shared<TypeParam>());
-    std::vector<uint8_t> out(16);
+    const std::vector<uint8_t> out(16);
 
     EXPECT_NO_THROW(tunnel.Connect(TestUrl()));
     EXPECT_THROW(tunnel.WriteBinary(out), InvalidState);
@@ -171,7 +175,7 @@ TYPED_TEST(TunnelTypedTests, WriteFailure)
     };
 
     Tunnel tunnel(std::make_shared<TestSockets>());
-    std::vector<uint8_t> out(16);
+    const std::vector<uint8_t> out(16);
 
     EXPECT_NO_THROW(tunnel.Connect(TestUrl()));
     EXPECT_THROW(tunnel.WriteBinary(out), InvalidState);
@@ -194,7 +198,7 @@ TYPED_TEST(TunnelTypedTests, TruncatedWrite)
 
     auto sockets = std::make_shared<TestSockets>();
     Tunnel tunnel(sockets);
-    std::vector<uint8_t> out(sockets->m_toWrite);
+    const std::vector<uint8_t> out(sockets->m_toWrite);
 
     EXPECT_NO_THROW(tunnel.Connect(TestUrl()));
     EXPECT_NO_THROW(tunnel.WriteBinary(out));
@@ -227,7 +231,7 @@ TYPED_TEST(TunnelTypedTests, TruncatedWriteFailingCallbackOnWritable)
 
     auto sockets = std::make_shared<TestSockets>();
     Tunnel tunnel(sockets);
-    std::vector<uint8_t> out(sockets->m_toWrite);
+    const std::vector<uint8_t> out(sockets->m_toWrite);
 
     EXPECT_NO_THROW(tunnel.Connect(TestUrl()));
     EXPECT_THROW(tunnel.WriteBinary(out), InvalidState);
@@ -250,7 +254,8 @@ TYPED_TEST(TunnelTypedTests, ReadWrongState)
     };
 
     TestTunnel tunnel(std::make_shared<TypeParam>());
-    std::vector<uint8_t> out(16), in;
+    const std::vector<uint8_t> out(16);
+    const std::vector<uint8_t> in;
 
     EXPECT_NO_THROW(tunnel.Connect(TestUrl()));
     EXPECT_NO_THROW(tunnel.WriteBinary(out));
@@ -282,7 +287,8 @@ TYPED_TEST(TunnelTypedTests, Connection)
     Tunnel tunnel(std::make_shared<TypeParam>());
 
     const std::string test = "sdfjisdjkfhdfjkghsdfkghdgkjhd";
-    std::vector<uint8_t> in, out;
+    std::vector<uint8_t> in;
+    std::vector<uint8_t> out;
     out.assign(test.c_str(), test.c_str() + test.size());
 
     EXPECT_NO_THROW(tunnel.Disconnect());
@@ -382,7 +388,8 @@ TYPED_TEST(TunnelTypedTests, WrongHeaders)
 TYPED_TEST(TunnelTypedTests, ValidHeaders)
 {
     const std::string test = "sdfjisdjkfhdfjkghsdfkghdgkjhd";
-    std::vector<uint8_t> in, out;
+    std::vector<uint8_t> in;
+    std::vector<uint8_t> out;
     out.assign(test.c_str(), test.c_str() + test.size());
 
     Tunnel tunnel(std::make_shared<TypeParam>());
index 8fdcef12b3967fb350e4601392fe7d348c58f993..14b7d28c9db33dc0c34077aca4622d6fc550f29e 100644 (file)
  */
 
 #include "../test_cancel_from_the_other_thread.h"
+#include "constants.h"
 #include "exception.h"
 #include "manual_tests.h"
+#include "tunnel.h"
 
-#include <cassert>
 #include <chrono>
 
 namespace {
@@ -62,7 +63,7 @@ public:
                 m_testServer = argv[i] + strlen(SERVER_PREFIX);
     }
 
-    const std::string &TestUrl() const
+    [[nodiscard]] const std::string &TestUrl() const
     {
         static const std::string TEST_URL = std::string("wss://") + m_testServer;
         return TEST_URL;
@@ -76,7 +77,8 @@ private:
 
 const std::string &TestUrl() { return Config::Instance().TestUrl(); }
 
-using namespace Exception;
+using Exception::InvalidParam;
+using Exception::InvalidState;
 
 /*
  * TunnelDummyServerTests require a running websocket server implementing "echo" functionality.
@@ -87,11 +89,12 @@ using namespace Exception;
 TEST(TunnelDummyServerTests, WrongUrl)
 {
     UnsafeTunnel tunnel;
-    std::string routingId = "123456";                          // 3B
-    std::string tunnelId = "0123456789abcdef0123456789abcdef"; // 16B
+    const std::string routingId = "123456";                          // 3B
+    const std::string tunnelId = "0123456789abcdef0123456789abcdef"; // 16B
     std::ostringstream oss;
     const std::string test = "sdfjisdjkfhdfjkghsdfkghdgkjhd";
-    std::vector<uint8_t> in, out;
+    const std::vector<uint8_t> in;
+    std::vector<uint8_t> out;
     out.assign(test.c_str(), test.c_str() + test.size());
 
     oss.str("");
@@ -105,7 +108,7 @@ TEST(TunnelDummyServerTests, WrongUrl)
     oss << "wss://a" << TUNNEL_SERVER_DOMAINS[0] << "/cable/connect/" << routingId << "/"
         << tunnelId;
     // May fail at different stage with different error depending on the network setup
-    EXPECT_THROW(tunnel.Connect(oss.str()), ExceptionBase);
+    EXPECT_THROW(tunnel.Connect(oss.str()), ::Exception::ExceptionBase);
     EXPECT_NO_THROW(tunnel.Disconnect());
 
     EXPECT_THROW(tunnel.WriteBinary(out), InvalidState);
@@ -148,7 +151,7 @@ TEST(TunnelDummyServerTests, UriParsing)
     EXPECT_NO_THROW(tunnel.Disconnect());
     sockets->CheckPath("/c");
 
-    std::string tmp(1024, 'o');
+    const std::string tmp(1024, 'o');
     oss << tmp;
     EXPECT_NO_THROW(tunnel.Connect(oss.str()));
     EXPECT_NO_THROW(tunnel.Disconnect());
@@ -195,7 +198,8 @@ TEST(TunnelDummyServerTests, CancelFromTheOtherThread)
     public:
         void Perform()
         {
-            std::vector<uint8_t> in, out(42);
+            std::vector<uint8_t> in;
+            const std::vector<uint8_t> out(42);
             m_tunnel.Connect(TestUrl());
             m_tunnel.WriteBinary(out);
             in = m_tunnel.ReadBinary();
index ccfe03522e7a6bbfa85d14fc24b9afa23699ee3e..80aa1dbf771a7e7c80171dbc50365d6b62a59e28 100644 (file)
@@ -16,8 +16,7 @@
 
 #pragma once
 
-#include "constants.h"
-#include "tunnel.h"
+#include "websockets.h"
 
 #include <gtest/gtest-param-test.h>
 #include <gtest/gtest.h>
index d2e884ce167b58226e6c34e5e25e0fd62d52163c..3be2810c0c0e5d96516fb4387260ce843eb1545d 100644 (file)
@@ -21,7 +21,6 @@
 #include <tuple>
 
 using std::cerr;
-using std::endl;
 
 namespace {
 
@@ -31,10 +30,10 @@ namespace {
     cerr << "Turning bluetooth " << (on ? "on" : "off") << "...";
     int res = bt_initialize();
     if (res != BT_ERROR_NONE) {
-        cerr << " cannot initialize." << endl;
+        cerr << " cannot initialize." << '\n';
         return res;
     }
-    auto *gmainloop = g_main_loop_new(NULL, FALSE);
+    auto *gmainloop = g_main_loop_new(nullptr, FALSE);
     auto data = std::tuple{static_cast<int>(BT_ERROR_OPERATION_FAILED), gmainloop, on};
     using Data = decltype(data);
     auto callback = [](int result, bt_adapter_state_e adapterState, void *userData) {
@@ -89,7 +88,7 @@ cleanup_gmainloop:
     }
     if (res == BT_ERROR_NONE)
         cerr << " done.";
-    cerr << endl;
+    cerr << '\n';
     return res;
 }