core-adapters 0.1.1
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
secret_json.hpp File Reference

nlohmann/json hook for snicholls::secret<T>: read only. A secret is never written to JSON. More...

#include <string>
#include <utility>
#include <snicholls/core_adapters/nlohmann/json.hpp>
#include <snicholls/core/secret.hpp>

Go to the source code of this file.

Functions

template<typename T >
void snicholls::from_json (const nlohmann::json &j, secret< T > &s)
 Reads a secret from JSON. There is no to_json: a secret is never written.
 

Detailed Description

nlohmann/json hook for snicholls::secret<T>: read only. A secret is never written to JSON.

Overview
Configuration arrives as JSON with credentials in it, so j.get<snicholls::secret<std::string>>() reads the value into a secret straight away, and the plain value never sits in an ordinary variable. The other direction is deliberately missing: there is no to_json for secret<T>, so nlohmann::json j = s; does not compile. Writing the mask would lose the value silently; writing the value would leak it. To send a secret on purpose, write s.reveal() - a call that is easy to find in review.
const auto config = nlohmann::json::parse(R"({"api_key": "demo-key-123", "port": 5432})");
const auto key = config.at("api_key").get<snicholls::secret<std::string>>();
// nlohmann::json out = key; // does not compile: there is no to_json for a secret
static_assert(!std::is_constructible_v<nlohmann::json, snicholls::secret<std::string>>);
std::printf("the key has %zu characters\n", key.reveal().size()); // reveal(): the one way to the value
Relationships
Guarantees and contracts
  • The value never appears in an error: a failure names the expected type and the JSON type received, never the text.
  • Strong guarantee: on failure the target secret is unchanged.
Errors
snicholls::json_error for any value that does not convert to T (nlohmann's own type_error / out_of_range are caught and translated, without their message, which may quote the value).
Performance
Not benchmarked.
Tests and demos
  • Tests: tests/nlohmann/secret_json_test.cpp (including that nlohmann::json(secret) is ill-formed).
  • Demo: demos/nlohmann/secret_json_demo.cpp.
Dependencies
CMake target snicholls::core_json.
Known issues and gotchas
  • T must itself be readable by nlohmann/json (j.get<T>()).
Status
Experimental, pre-1.0.

Definition in file secret_json.hpp.