morph 0.1.0
Asynchronous bridge between GUI thread and business models
Loading...
Searching...
No Matches
session_auth.hpp File Reference

Opt-in authenticated sessions: signed bearer tokens and a verifying IAuthorizer so a RemoteServer can trust the caller's identity. More...

#include <array>
#include <chrono>
#include <cstdint>
#include <expected>
#include <functional>
#include <glaze/glaze.hpp>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "../attributes.hpp"
#include "../core/profiler.hpp"
#include "session.hpp"

Go to the source code of this file.

Classes

struct  morph::session::SessionToken
 Verified claims carried by a session token. More...
struct  morph::session::TokenIssuanceError
 Thrown by TokenIssuer::issue if serialising the claims fails. More...
struct  morph::session::detail::EscapingWriteOpts
 Write options that escape ASCII control bytes as \\uXXXX sequences. More...
class  morph::session::TokenIssuer
 Mints signed bearer tokens from claims using a shared secret. More...
class  morph::session::TokenVerifier
 Verifies signed bearer tokens against a shared secret. More...
class  morph::session::SigningAuthorizer
 IAuthorizer that authenticates via a signed Context::token. More...

Typedefs

using morph::session::MacFunction = std::function<std::string(std::string_view key, std::string_view message)>
 Pluggable message-authentication primitive: mac(secret, message).
using morph::session::Clock = std::function<int64_t()>
 Wall-clock source (milliseconds since the Unix epoch), injectable for tests.

Enumerations

enum class  morph::session::AuthError : std::uint8_t { Malformed , BadSignature , Expired , NotYetValid }
 Why token verification failed. More...

Functions

std::string morph::session::detail::sha256 (std::string_view data)
 SHA-256 (FIPS 180-4). Returns the raw 32-byte digest.
std::string morph::session::detail::hmacSha256Raw (std::string_view key, std::string_view msg)
 HMAC-SHA256 (RFC 2104). Returns the raw 32-byte MAC.
bool morph::session::detail::constantTimeEquals (std::string_view lhs, std::string_view rhs)
 Constant-time byte-string equality (guards against MAC timing leaks).
std::string morph::session::detail::base64UrlEncode (std::string_view in)
 base64url-encodes in without padding (RFC 4648 §5).
std::optional< std::string > morph::session::detail::base64UrlDecode (std::string_view in)
 Decodes canonical base64url text (no padding). Returns nullopt on invalid input.
std::string morph::session::hmacSha256 (std::string_view key, std::string_view message)
 Reference HMAC-SHA256 MacFunction (the default). Returns raw MAC bytes.
int64_t morph::session::systemClockMs ()
 Default clock: std::chrono::system_clock in milliseconds since epoch.
void morph::session::detail::throwOnGlazeError (const glz::error_ctx &errCode, std::string_view context)
 Converts a Glaze error into a TokenIssuanceError, or does nothing if errCode reports success. See journal::detail::throwOnGlazeError for the identical pattern in the sibling writer.

Variables

constexpr std::string_view morph::session::detail::kB64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
 The url-safe base64 alphabet (RFC 4648 §5): - and _ replace +//.
constexpr int64_t morph::session::kClockSkewMs = 60'000
 Allowed clock skew (ms) between issuer and verifier for the not-before (issuedAtMs) check. Keeps a token minted a moment ahead of the verifier's clock from being spuriously rejected.

Detailed Description

Opt-in authenticated sessions: signed bearer tokens and a verifying IAuthorizer so a RemoteServer can trust the caller's identity.

Include this only if you want authentication. The token is a signed, stateless bearer credential — base64url(claimsJson) "." base64url(mac) — minted app-side by a login action via TokenIssuer and verified per request by SigningAuthorizer, which also feeds the verified principal back to RemoteServer so session::current()->principal is authoritative inside a model. The MAC primitive is pluggable (MacFunction); a self-contained, test-vector-verified HMAC-SHA256 (hmacSha256) is the default. See docs/spec/security.md for the full trust model and its limits.

Definition in file session_auth.hpp.

Typedef Documentation

◆ MacFunction

using morph::session::MacFunction = std::function<std::string(std::string_view key, std::string_view message)>

Pluggable message-authentication primitive: mac(secret, message).

Returns the raw MAC bytes. Defaults to hmacSha256; inject a vetted library's HMAC for production.

Definition at line 265 of file session_auth.hpp.

◆ Clock

using morph::session::Clock = std::function<int64_t()>

Wall-clock source (milliseconds since the Unix epoch), injectable for tests.

Definition at line 276 of file session_auth.hpp.

Enumeration Type Documentation

◆ AuthError

enum class morph::session::AuthError : std::uint8_t
strong

Why token verification failed.

Enumerator
Malformed 

Not payload.sig, bad base64url, or unparseable claims.

BadSignature 

MAC did not match — forged or tampered.

Expired 

Missing/non-positive expiresAtMs, or it is in the past.

NotYetValid 

issuedAtMs is set and more than kClockSkewMs in the future.

Definition at line 311 of file session_auth.hpp.

Function Documentation

◆ sha256()

std::string morph::session::detail::sha256 ( std::string_view data)
inline

SHA-256 (FIPS 180-4). Returns the raw 32-byte digest.

Parameters
dataMessage bytes to hash.
Returns
32-byte digest as a byte string.

Definition at line 48 of file session_auth.hpp.

◆ hmacSha256Raw()

std::string morph::session::detail::hmacSha256Raw ( std::string_view key,
std::string_view msg )
inline

HMAC-SHA256 (RFC 2104). Returns the raw 32-byte MAC.

Parameters
keySecret key bytes.
msgMessage bytes to authenticate.
Returns
32-byte MAC as a byte string.

Definition at line 136 of file session_auth.hpp.

◆ constantTimeEquals()

bool morph::session::detail::constantTimeEquals ( std::string_view lhs,
std::string_view rhs )
inline

Constant-time byte-string equality (guards against MAC timing leaks).

Parameters
lhsFirst string.
rhsSecond string.
Returns
true iff the strings are byte-for-byte equal.

Definition at line 158 of file session_auth.hpp.

◆ base64UrlEncode()

std::string morph::session::detail::base64UrlEncode ( std::string_view in)
inline

base64url-encodes in without padding (RFC 4648 §5).

Parameters
inBytes to encode.
Returns
The base64url text.

Definition at line 175 of file session_auth.hpp.

◆ base64UrlDecode()

std::optional< std::string > morph::session::detail::base64UrlDecode ( std::string_view in)
inline

Decodes canonical base64url text (no padding). Returns nullopt on invalid input.

Canonical decoding is enforced to remove token-string malleability: a token is a signed byte string, but base64url is a bit-oriented encoding, so a naive decoder that silently discards the leftover bits of the final symbol would map several distinct encodings onto the same bytes (e.g. the trailing character could be perturbed within the discarded low bits without changing the decoded MAC). This function rejects any such non-canonical input:

  • A length % 4 == 1 is impossible for real base64url output and is rejected.
  • The leftover bits that do not form a whole output byte (2 bits for a 1-remainder group, 4 bits for a 2-remainder group) must be zero; a nonzero remainder means the encoding is not the canonical one this decoder would itself produce, so it is rejected rather than truncated.

The result is thus a bijection over valid tokens: exactly one string decodes to any given byte sequence.

Parameters
inbase64url text.
Returns
Decoded bytes, or nullopt if in has an invalid character, an impossible length, or nonzero leftover (non-canonical) bits.

Definition at line 222 of file session_auth.hpp.

◆ hmacSha256()

std::string morph::session::hmacSha256 ( std::string_view key,
std::string_view message )
inline

Reference HMAC-SHA256 MacFunction (the default). Returns raw MAC bytes.

Parameters
keySecret key bytes.
messageMessage bytes to authenticate.
Returns
32-byte HMAC as a byte string.

Definition at line 271 of file session_auth.hpp.

◆ systemClockMs()

int64_t morph::session::systemClockMs ( )
inline

Default clock: std::chrono::system_clock in milliseconds since epoch.

Returns
Current time in ms since the Unix epoch.

Definition at line 280 of file session_auth.hpp.

◆ throwOnGlazeError()

void morph::session::detail::throwOnGlazeError ( const glz::error_ctx & errCode,
std::string_view context )
inline

Converts a Glaze error into a TokenIssuanceError, or does nothing if errCode reports success. See journal::detail::throwOnGlazeError for the identical pattern in the sibling writer.

Parameters
errCodeResult of a glz::write call.
contextBuffer passed to glz::format_error for the message.

Definition at line 337 of file session_auth.hpp.

Variable Documentation

◆ kB64Alphabet

std::string_view morph::session::detail::kB64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
inlineconstexpr

The url-safe base64 alphabet (RFC 4648 §5): - and _ replace +//.

Definition at line 170 of file session_auth.hpp.

◆ kClockSkewMs

int64_t morph::session::kClockSkewMs = 60'000
inlineconstexpr

Allowed clock skew (ms) between issuer and verifier for the not-before (issuedAtMs) check. Keeps a token minted a moment ahead of the verifier's clock from being spuriously rejected.

Definition at line 308 of file session_auth.hpp.