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);
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;
}
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));
}
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));
};
[[nodiscard]] int Deinitialize() noexcept override;
- ~Bluetooth();
+ ~Bluetooth() override;
private:
bool m_initalized = false;
*/
#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;
remaining = 0;
}
val = le64toh(chunk);
- encoded << setw(chunkDigits) << setfill('0') << val;
+ encoded << std::setw(chunkDigits) << std::setfill('0') << val;
}
return encoded.str();
}
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;
}
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);
// 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;
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));
{
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));
}
{
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));
}
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));
}
{
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));
}
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));
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()
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); }
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)
{
}
// 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:
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)
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)),
{
}
-Container &Container::operator=(Container &&other)
+Container &Container::operator=(Container &&other) noexcept
{
if (this != &other) {
m_parent = std::exchange(other.m_parent, nullptr);
{
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));
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));
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)
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
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
}
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)
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
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();
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)
{
}
void Advance();
private:
- Container(const Container &) = delete;
- Container &operator=(const Container &) = delete;
void LeaveContainer(CborValue &childIt) noexcept;
protected:
// 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 {
KeyCopy PeekKey();
- size_t Length() const { return m_length; }
+ [[nodiscard]] size_t Length() const { return m_length; }
};
class Parser : public Container {
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 {
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>;
#include <cstdint>
#include <vector>
-typedef std::vector<uint8_t> CryptoBuffer;
+using CryptoBuffer = std::vector<uint8_t>;
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;
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;
};
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
unsigned int digestLen;
if (!HMAC(EVP_sha256(),
key.data(),
- key.size(),
+ static_cast<int>(key.size()),
data.data(),
data.size(),
digest.data(),
#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>
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
{
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{};
}
#include "crypto/common.h"
+#include <cstddef>
+
namespace Crypto {
CryptoBuffer RandomBytes(size_t bytes);
CryptoBuffer ImportAESKey(const uint8_t *rawKey, size_t rawKeySize)
{
- return CryptoBuffer(rawKey, rawKey + rawKeySize);
+ return {rawKey, rawKey + rawKeySize};
}
} // namespace Crypto
VerifyRpIdHash(rpId, res.response.m_authData.m_rpIdHash);
- ShutdownMessage shutdown;
+ const ShutdownMessage shutdown;
Buffer shutdownMsg;
shutdown.Serialize(shutdownMsg);
m_encryptedTunnel->WriteBinary(shutdownMsg);
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");
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);
}
#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;
* limitations under the License
*/
+#include "crypto/common.h"
#include "encrypted_tunnel.h"
#include "exception.h"
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");
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;
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>
{
}
- 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
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)
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] =
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;
#include "abstract_log_provider.h"
#include <cstring>
-#include <stddef.h>
namespace Log {
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
Pedantic
};
- virtual ~AbstractLogProvider() {}
+ virtual ~AbstractLogProvider() = default;
virtual void SetTag(const char *tag);
#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); }
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 },
} // 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)
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;
*/
class NullStream {
public:
- NullStream() {}
+ NullStream() = default;
template <typename T>
NullStream &operator<<(const T &)
//
/* 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)
} 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)
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,
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,
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);
}
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);
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);
}
}
{
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);
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++;
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;
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) {
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);
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");
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())
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);
// 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();
}
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)
std::string fidoUri;
CborEncoding::Cbor cbor;
cbor.EncodeQRContents(identityKeyCompressed, qrSecret, hint, stateAssisted, fidoUri);
- qrCodeCallback(std::move(fidoUri));
+ std::move(qrCodeCallback)(std::move(fidoUri));
}
* limitations under the License
*/
-#include "crypto/ecdh.h"
-#include "crypto/hmac.h"
#include "crypto/random.h"
#include "derive_key.h"
#include "exception.h"
{
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));
{
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();
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>(),
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;
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);
}
#include "state_assisted_transaction.h"
#include "to_wauthn_const_buff.h"
-#include <memory>
#include <mutex>
#include <webauthn-types.h>
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");
} 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);
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);
{
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: {
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>(),
} // 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),
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);
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();
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;
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");
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);
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) {
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;
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;
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;
#include "crypto/sha2.h"
#include "endian.h"
#include "exception.h"
-#include "log/log.h"
#include "tunnel_server_domain.h"
#include <cstring>
LWS_PROTOCOL_LIST_TERM
}
{
- [[maybe_unused]] static bool redirected = RedirectWebsocketsLogs();
+ [[maybe_unused]] static const bool redirected = RedirectWebsocketsLogs();
}
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));
}
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'}
class Websockets : public IWebsockets {
public:
Websockets() noexcept;
- ~Websockets() = default;
LwsContext *CreateContext() noexcept override;
Lws *ClientConnect(LwsContext *context, const std::string &url) noexcept override;
#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");
#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,
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)
[[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)
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["
{
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)
[[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)
{
if (!m_initialized) {
ADD_FAILURE() << "Attempting to stop scan on the uninitialized bluetooth adapter."
- << endl;
+ << '\n';
}
m_promise.set_value();
}
[[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)
{
if (!m_initialized) {
ADD_FAILURE() << "Attempting to stop scan on the uninitialized bluetooth adapter."
- << endl;
+ << '\n';
}
m_cancelFacilitator.Cancel();
}
#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};
}
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};
}
#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>
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,
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
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));
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));
}
{
std::string str;
- EXTRAKEY = true;
+ EXTRA_KEY = true;
MockRandCbor cb;
EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY1, SECRET1, MC, false, str));
{
std::string str;
- EXTRAKEY = false;
+ EXTRA_KEY = false;
MockRandCbor cb;
EXPECT_NO_THROW(cb.EncodeQRContents(PUBKEY1, SECRET1, MC, true, str));
// 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));
// 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));
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)
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)
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;
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)
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());
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)
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)
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());
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());
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));
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());
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)
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);
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());
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)
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);
}
{
+ // 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]);
}
{
+ // 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);
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);
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]);
}
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",
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();
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();
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");
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};
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,
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,
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{});
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,
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,
#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,
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,
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);
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);
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");
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));
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));
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));
class ProcessingFollowingUpdateMsgsMEncryptedTunnel : public IEncryptedTunnel {
public:
- ProcessingFollowingUpdateMsgsMEncryptedTunnel(std::vector<CryptoBuffer> &&messagesToRead)
+ explicit ProcessingFollowingUpdateMsgsMEncryptedTunnel(
+ std::vector<CryptoBuffer> &&messagesToRead)
: m_messagesToRead{std::move(messagesToRead)}
{
}
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;
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),
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}));
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{});
#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"
TEST(EncryptedTunnel, invalid_data)
{
- using namespace Exception;
+ using Exception::Unknown;
auto readerWriter = Crypto::Noise::SymmetricState::CipherState{
CryptoBuffer(Crypto::Noise::KEY_AND_HASH_LEN, 0x1)};
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"}};
}
{
}
- 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);
}
}
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{});
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);
}
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();
}
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;
}
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;
}
}
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(),
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);
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;
}
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;
}
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;
}
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;
}
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,
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;
}
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;
}
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
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;
}
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;
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;
// 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));
// 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),
// 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),
TEST(Messages, ShutdownMessage)
{
- ShutdownMessage shutdown;
+ const ShutdownMessage shutdown;
Buffer buffer;
ASSERT_NO_THROW(shutdown.Serialize(buffer));
EXPECT_EQ(ToBufferView(buffer), BUFFER_VIEW("\x00"));
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);
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);
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;
{
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;
});
*/
#include "crypto/random.h"
-#include "get_random.h"
#include "qr_transaction.h"
#include "transaction_test.h"
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{""};
{
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;";
};
void ThrowRuntimeError() { throw std::runtime_error{"xyz"}; }
-void ThrowInt() { throw 42; }
+void ThrowInt() { throw 42; } // NOLINT
} // namespace
*/
#include "derive_key.h"
-#include "get_random.h"
#include "state_assisted_transaction.h"
#include "to_wauthn_const_buff.h"
#include "transaction_test.h"
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("");
}
};
- LinkedDevice origLinkedDevice;
+ const LinkedDevice origLinkedDevice;
wauthn_hybrid_linked_data_s linkedDevice;
doTest(nullptr);
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();
}
#include <cassert>
#include <chrono>
#include <cstddef>
-#include <cstdint>
#include <exception>
#include <future>
#include <gtest/gtest.h>
// 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);
}
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{""};
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{""};
#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 {
};
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;
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));
}
};
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();
};
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)});
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());
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);
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);
{
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);
// perform "echo" response
mockedLws->PushEvent(LWS_CALLBACK_CLIENT_RECEIVE, std::move(buffer));
- return len;
+ return static_cast<int>(len);
} catch (...) {
return 0;
}
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;
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);
}();
// 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) {
// 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;
--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;
}
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;
}
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;
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();
#pragma once
-#include "constants.h"
#include "websockets.h"
#include <gtest/gtest-param-test.h>
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;
void SetListener(IWebsocketsListener *listener) noexcept override { m_listener = listener; }
-protected:
IWebsocketsListener *m_listener = nullptr;
};
#include "auto_tests.h"
#endif
#include "../get_random.h"
+#include "constants.h"
#include "exception.h"
#include "tunnel.h"
};
} // 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:
template <typename T>
struct TunnelTypedTests : public testing::Test {};
-TYPED_TEST_SUITE(TunnelTypedTests, MyTypes);
+TYPED_TEST_SUITE(TunnelTypedTests, MyTypes, );
TYPED_TEST(TunnelTypedTests, BigMessages)
{
};
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);
};
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);
};
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);
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));
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);
};
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));
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());
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>());
*/
#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 {
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;
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.
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("");
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);
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());
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();
#pragma once
-#include "constants.h"
-#include "tunnel.h"
+#include "websockets.h"
#include <gtest/gtest-param-test.h>
#include <gtest/gtest.h>
#include <tuple>
using std::cerr;
-using std::endl;
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) {
}
if (res == BT_ERROR_NONE)
cerr << " done.";
- cerr << endl;
+ cerr << '\n';
return res;
}