Add M10.3a account-bound session grants and region session control
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 1m47s
Foundation / checks (client) (push) Failing after 9m42s
Foundation / checks (network) (push) Successful in 8m49s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (postgres) (push) Canceled after 8m13s
Foundation / checks (tsan) (push) Canceled after 7m13s
Foundation / checks (checks) (push) Canceled after 17m58s

Provider-independent 128-bit AccountIds; ECDSA P-256 session grants v1 signed by
issuer keys and verified by regions with public keys only, the environment byte
signed so dev grants never verify in stage or World0. Per-account serials make the
newest grant win: replay and older stolen grants are refused, a newer grant replaces
the account's session, and refresh renews in place. Attempt rates and capacities
are bounded. The evo_identity library provides the provider, account directory and
grant issuer interfaces with a dev-only test provider. ADR-0091.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-03 20:54:04 -04:00
co-authored by Claude Opus 5.5
parent 34e142f68d
commit 01b4b06a09
17 changed files with 1409 additions and 7 deletions
+9 -4
View File
@@ -31,14 +31,19 @@ add_subdirectory("${mbedtls_source}" "${PROJECT_BINARY_DIR}/mbedtls" EXCLUDE_FRO
# Dependency-free protocol: framing, envelopes, admission. No Mbed TLS types.
add_library(evo_network_protocol STATIC src/network/protocol/codec.cpp
src/network/protocol/admission.cpp)
src/network/protocol/admission.cpp src/network/protocol/session_control.cpp)
target_link_libraries(evo_network_protocol PUBLIC evo_client_views evo_client_controls)
evo_owned_target(evo_network_protocol)
# Mbed TLS adapters: dev grants (HMAC-SHA256 via PSA) and the TLS 1.3 channel.
# M10.3 session grants (ECDSA P-256 via PSA) share the adapter (ADR-0091).
add_library(evo_network_tls STATIC src/network/tls/dev_grant.cpp src/network/tls/channel.cpp
src/network/tls/dev_credentials.cpp)
src/network/tls/dev_credentials.cpp src/network/tls/session_grant.cpp)
target_link_libraries(evo_network_tls PUBLIC evo_network_protocol PRIVATE mbedtls)
evo_owned_target(evo_network_tls)
# M10.3 backend identity adapter: providers, account directory, grant issuer (library only).
add_library(evo_identity STATIC src/identity/identity.cpp)
target_link_libraries(evo_identity PUBLIC evo_network_tls)
evo_owned_target(evo_identity)
# M9.7 sessions: non-blocking TCP, the host-agnostic session server and the client.
add_library(evo_network_session STATIC src/network/socket/tcp.cpp src/network/session/server.cpp
src/network/session/client.cpp src/network/session/grant_ledger.cpp)
@@ -53,9 +58,9 @@ target_link_libraries(evo-dev-session PRIVATE evo_network_session)
evo_owned_target(evo-dev-session)
if(BUILD_TESTING)
add_executable(evo-network-tests tests/network_protocol.cpp tests/network_tls.cpp
tests/network_session.cpp tests/network_main.cpp)
tests/network_session.cpp tests/network_control.cpp tests/network_main.cpp)
# The TLS tests generate throwaway dev certificates with Mbed TLS directly.
target_link_libraries(evo-network-tests PRIVATE evo_network_session mbedtls)
target_link_libraries(evo-network-tests PRIVATE evo_network_session evo_identity mbedtls)
evo_owned_target(evo-network-tests)
add_test(NAME network COMMAND evo-network-tests)
set_tests_properties(network PROPERTIES TIMEOUT 120 LABELS "network")
+3 -1
View File
@@ -519,7 +519,9 @@ networking/M10_TIMING_TRACES.md); targets are not yet qualified on the reference
hardware (10.9). 10.2 split: 10.2a selection, pins and build of msquic/OpenSSL done
(ADR-0090); 10.2b bounded channels, exact CA pinning and the impairment relay done;
10.2c loss/head-of-line measurements done (networking/M10_TRANSPORT_MEASUREMENTS.md).
10.3-10.9 planned.
10.3 split (ADR-0091): 10.3a account ids, ECDSA grants, identity adapter and region
session control done; 10.3b QUIC session handshake and 10.3c durable control lease
follow. 10.4-10.9 planned.
**Entry:** M9 client/session evidence and M7/M8 dev/stage durability. Read
NETWORK_ARCHITECTURE, PERSISTENCE_ARCHITECTURE and ADR-0017. The M9 transport is
+5 -1
View File
@@ -16,7 +16,11 @@ check authoritative, minimum-MTU start) and the owned impairment relay, tested o
platforms. M10.2c measures loss and head-of-line blocking through the relay: under 5-10 %
loss the ordered stream's p95 latency is 3-5.5x the datagram channel's and exceeds the
250 ms target at 100 ms RTT, while datagrams stay <= 67 ms, which confirms the channel split
(networking/M10_TRANSPORT_MEASUREMENTS.md). M10.2 is complete. Next: M10.3 session binding.
(networking/M10_TRANSPORT_MEASUREMENTS.md). M10.2 is complete. M10.3a (ADR-0091) adds provider-independent account ids, ECDSA P-256
session grants verified with public keys only, the identity adapter and grant issuer
library, and per-region session control (newest grant wins and replaces the old session,
replay and stale grants refused, in-session refresh, attempt rate limits). Next: M10.3b
QUIC session handshake, then the durable control lease (10.3c).
## Previous gate - 2026-10-02
@@ -0,0 +1,86 @@
# ADR-0091: M10 session identity, grants and control authority
## Status
Accepted for M10.3 (2026-10-03). Decisions confirmed with the maintainer on 2026-10-03:
ECDSA P-256 grants through Mbed TLS PSA; an identity adapter and grant issuer as a
library (no service, no Steam yet); a newer grant replaces an account's existing
session; unique control backed by a durable per-world control lease. Delivery:
10.3a grants, identity adapter and region session control (this text);
10.3b the QUIC session handshake; 10.3c the durable control lease. Each segment
amends this ADR. The M9 dev path (ADR-0082/0083, protocol v1) is unchanged.
## Context
ADR-0017 and NETWORK_ARCHITECTURE require short-lived world/region/account-scoped
grants, reconnect that cannot duplicate control, secrets kept out of logs, and an
identity provider independent of Steam. ADR-0089 fixed that reconnect is a new grant,
a new session and a fresh baseline, and that no session survives an epoch change.
M9 has only dev grants: HMAC-SHA256, a u64 subject, refusal of a second session per
subject, single use remembered in a file ledger. No account backend exists, and no
controllable organism exists yet (organisms arrive with M11).
## Decision
**Accounts.** `AccountId` is 128 random bits assigned by the account directory and
never derived from a provider id. Providers authenticate a credential to a
`ProviderSubject` (provider kind plus opaque subject); the directory maps subjects to
accounts. Logs and events may carry only `log_label` (the first four id bytes).
**Grant format v1** (schemas/network/session-grant-v1.md): fixed 160 bytes,
`EVO-GRANT` marker, version, environment byte, issuer key id, grant id, account,
per-account serial, world/frame, region, issued/expiry seconds; ECDSA P-256 over
SHA-256 of the first 96 bytes (Mbed TLS 4.1.1 PSA, already pinned; no new dependency).
Issuers hold private keys (`GrantSigningKey`, non-exportable PSA keys); regions hold
only public keys (`GrantVerifier`, at most 8 per environment for rotation), so a
compromised region cannot mint grants. Verification checks the signature before any
claim and then requires the signed environment byte to equal the verifier's.
**Dev cannot reach production, by four independent checks:** M9 dev grants have
another marker and length; a dev-signed session grant carries the dev environment
byte and fails in stage/World0 even if a dev public key were misconfigured there;
`DevTestProvider` (credential `dev-test:<name>`, no secret) cannot be constructed
outside dev; `GrantIssuer` refuses a provider and key from different environments.
**Serials order grants; the newest wins.** The directory issues per-account serials
that strictly increase, with non-decreasing `issued_at`. A region accepts a grant only
if its serial is greater than every serial it accepted for that account. This gives
single use (replay is `stale_grant`) and makes an older unexpired grant, for example a
stolen one, useless once a newer grant was presented. A region remembers an account's
serial until the newest accepted `issued_at` plus its maximum lifetime, after which
every older grant has expired.
**Session control** (`SessionControl`, per region, single owner, transport-neutral):
environment, world, region, lifetime (default maximum 300 s), clock skew (30 s),
expiry and serial checks; at most one session per account. A valid newer grant for an
account that holds a session closes the old session first and reports it as
superseded, so control is never shared and a dropped client reconnects without waiting
for the 5 s liveness timeout. `refresh` renews the session in place with a newer grant
(no reconnect or new baseline); a session closes when its grant expires. An epoch
change closes every session. Bounds: sessions (32), tracked accounts (4,096; full fails
closed rather than forgetting serials), and attempt rates: region-wide attempts before
signature verification (64 per 60 s) and verified attempts per account (4 per 60 s),
counted whether or not accepted. A refused open (capacity) does not consume the grant.
These limits are engineering defaults, not game rules.
**Identity adapter** (`evo_identity`, library): `IdentityProvider`, `AccountDirectory`
(bounded in-memory implementation for tests and tools), `GrantIssuer` (credential to
signed grant, lifetime 1..3600 s). Production providers and a running issuer service
are later work behind these interfaces.
## Alternatives considered
| Option | Disposition |
|---|---|
| HMAC grants per environment | Every region could forge grants for its environment. |
| Ed25519 | Not in Mbed TLS; would need a new crypto dependency. |
| Refuse a second login (M9 behaviour) | A silently dropped client waits for the liveness timeout; kept for M9 only. |
| Per-grant single-use set | Does not stop an older unused grant (stolen) from taking control; serial ordering subsumes it. |
| Grant lifetime as session lifetime without refresh | Short grants would force reconnects and fresh baselines every few minutes. |
## Consequences and limits (10.3a)
- Serials and sessions are in memory: a restarted region process would accept an
already-used, still-unexpired grant again (bounded by the 300 s lifetime), and two
regions of one world could each admit the same account. The durable control lease
(10.3c) closes both. Until then nothing deploys M10 sessions.
- If a newer grant is stolen before its owner presents it, the thief can take control
until the owner presents a still newer grant. Grants travel only inside TLS and are
never logged; revocation (bans) and channel binding are not designed yet.
- Private-key provisioning: `GrantSigningKey::import` takes a raw 32-byte P-256 scalar;
a provisioning tool and secret handling come with the issuer service.
+1
View File
@@ -98,6 +98,7 @@ design. No unadopted candidate is a link dependency of the proof.
- [ADR-0084: Engineering UI toolkit](0084-engineering-ui-toolkit.md) - Dear ImGui 1.92.9b pinned (M9.8a) and integrated as the engineering client overlay with toolkit-first input routing (M9.8c).
- [ADR-0090: M10 QUIC transport](0090-m10-quic-transport.md) - msquic 2.6.2 with OpenSSL 3.5.9 LTS (TLS 1.3 only) from pinned sources on Windows and Linux; DATAGRAM frames for superseding state, streams for reliable actions; M9 TLS/TCP kept as dev fallback; owned impairment relay; exact CA pinning due in 10.2b.
- [ADR-0091: M10 session identity and control](0091-m10-session-identity-and-control.md) - provider-independent 128-bit AccountIds, ECDSA P-256 session grants (regions hold public keys only, signed environment byte), per-account serials where the newest grant wins, takeover of an existing session, in-session refresh, bounded attempt rates; identity adapter and issuer as a library; durable control lease follows (10.3c).
- [ADR-0089: M10 timing and budgets](0089-m10-timing-and-budgets.md) - ratified 50 ms tick, 1 s flush with final outcomes p95 <= 1.5 s, responsiveness LAN p95 <= 150 ms / 100 ms RTT <= 250 ms, reference hardware; derived scheduling, sequence, baseline, queue/byte/work budgets and the exact/tolerant determinism contract; records the per-tick biology coupling.
- [ADR-0088: Rendered deployment policy](0088-rendered-deployment-policy.md) - the deploy policy check renders every overlay with pinned kustomize v5.8.1 (checksum-verified, explicit preparation) and validates effective objects; unsupported kustomize features refused.
- [ADR-0087: Dev session route](0087-dev-session-route.md) - evolution-dev only: void.aeternalisgames.com:7400 via a dedicated internal MetalLB VIP to the region pod, TLS end to end, CIDR-limited, operator-opened windows enforced by evo-server; committed disabled with fail-closed policy tests.
+3 -1
View File
@@ -6,7 +6,9 @@ proposals for M10. M10 timing and workload budgets: ADR-0089 and
with OpenSSL (ADR-0090): bounded DATAGRAM and reliable-stream channels with exact CA
pinning (`evo_network_quic`, M10.2b); loss/head-of-line measurements (M10.2c,
[M10_TRANSPORT_MEASUREMENTS](../networking/M10_TRANSPORT_MEASUREMENTS.md)) confirm
superseding state on DATAGRAMs and reliable actions on the ordered stream. The scoped M9 dev session (TLS 1.3, protocol v1, dev-only grants)
superseding state on DATAGRAMs and reliable actions on the ordered stream. Session
identity and control (ADR-0091, M10.3): ECDSA-signed account-scoped grants
([session-grant-v1](../../schemas/network/session-grant-v1.md)), newest grant wins. The scoped M9 dev session (TLS 1.3, protocol v1, dev-only grants)
is specified in [DEV_SESSION_PROTOCOL](../networking/DEV_SESSION_PROTOCOL.md) and
ADR-0082. M0 has no networking. Steam distribution follows later through
an identity-provider adapter; core account IDs are independent of Steam IDs.
+30
View File
@@ -4087,7 +4087,37 @@ extension was negotiated (measurement now waits for it); clang-tidy widening fin
Executed: Linux format check, GCC 14 build, CTest `-L quic` 2/2, clang-tidy 19 on the tool
and relay; Windows MSVC preset `quic` build and CTest 3/3; both measurement runs.
Correction (later the same day): the Windows build preceded the final formatting pass,
which sorted `<timeapi.h>` before `<windows.h>`; the committed tool did not compile with
MSVC. Fixed in the next commit (separate include block); MSVC preset `quic` rebuilt, CTest
3/3 and a 2 s measurement run. The `-Action test` step of windows-check does not build:
always run `-Action build` first.
Limits: no kernel TCP/netem comparison (user-space relay by decision), single host and
loopback, development hardware, 15 samples of 16 KiB messages per configuration, run
length cuts off in-flight stream messages; msquic not under sanitizers; quic preset not
in CI.
## 2026-10-03 — M10.3a session grants, identity adapter and session control (ADR-0091)
Implemented `SessionControl` and `AccountId` (evo_network_protocol), ECDSA P-256 session
grants `GrantSigningKey`/`GrantVerifier` (evo_network_tls, Mbed TLS PSA) and the identity
adapter `evo_identity` (DevTestProvider, MemoryAccountDirectory, GrantIssuer); tests in
`tests/network_control.cpp` (part of `evo-network-tests`, label `network`).
Tests: sign/verify round trip; every one of the 160 grant bytes flipped is refused (key
id bytes as unknown key, others as bad signature); truncated and M9 dev grants refused;
dev-signed grants refused by stage and World0 verifiers with and without the dev public
key configured; key rotation, duplicate and excess keys, relabelled key id, invalid
point, key import and moved-from keys; DevTestProvider refused outside dev, credential
syntax; directory stability, capacity and serial/issue-time monotonicity; issuer end to
end into session control and environment mismatch; control scope (world, region,
environment), lifetime, skew and expiry; replay and older unexpired grants refused
(`stale_grant`), newest grant superseding the previous session, account and region
attempt limits with window reset, refused open not consuming the grant, account capacity
failing closed until older grants can no longer verify, refresh (extension, stale,
wrong account, unknown session), grant expiry and epoch change closing sessions; log label.
Executed: Linux GCC 14 preset `network` build and CTest `-L network` 1/1; Clang 19
ASan/UBSan (Debug, leak detection) `evo-network-tests`; clang-tidy 19 on the new sources
and tests; format check; Windows MSVC 19.44 preset `network` build and CTest 1/1.
Not done: QUIC session handshake (10.3b), durable control lease and serial persistence
across restarts and regions (10.3c), revocation, private-key provisioning tooling.
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include "evo/network/session_grant.hpp"
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <map>
#include <span>
#include <string>
#include <utility>
// M10.3 backend identity adapter (ADR-0091). An identity provider authenticates an
// external credential to a provider subject; the account directory maps subjects to
// provider-independent AccountIds and orders their grants; the issuer signs short-lived
// region-scoped session grants. Library only: no service, no Steam. Production
// providers plug in behind IdentityProvider later. Credentials are never stored or
// logged here.
namespace evo::identity {
using network::AccountId;
using network::DeploymentEnvironment;
enum class ProviderKind : std::uint8_t { dev_test = 1 };
struct ProviderSubject {
ProviderKind provider{};
std::string subject; // Provider-scoped, 1..128 bytes; never an account id.
auto operator<=>(const ProviderSubject&) const = default;
};
enum class IdentityError : std::uint8_t {
not_dev_environment,
wrong_environment,
unauthenticated,
invalid_request,
directory_full,
serial_exhausted,
signing
};
class IdentityProvider {
public:
IdentityProvider() = default;
IdentityProvider(const IdentityProvider&) = delete;
IdentityProvider& operator=(const IdentityProvider&) = delete;
virtual ~IdentityProvider() = default;
[[nodiscard]] virtual DeploymentEnvironment environment() const noexcept = 0;
[[nodiscard]] virtual std::expected<ProviderSubject, IdentityError>
authenticate(std::span<const std::uint8_t> credential) = 0;
protected:
IdentityProvider(IdentityProvider&&) = default;
IdentityProvider& operator=(IdentityProvider&&) = default;
};
// Dev-only test identities: the credential "dev-test:<name>" (name 1..32 of [a-z0-9-])
// authenticates as that name without any secret. It cannot be created outside dev.
class DevTestProvider final : public IdentityProvider {
public:
[[nodiscard]] static std::expected<DevTestProvider, IdentityError>
create(DeploymentEnvironment environment);
[[nodiscard]] DeploymentEnvironment environment() const noexcept override {
return DeploymentEnvironment::dev;
}
[[nodiscard]] std::expected<ProviderSubject, IdentityError>
authenticate(std::span<const std::uint8_t> credential) override;
private:
DevTestProvider() = default;
};
// Serial and issue time of the next grant for an account: both non-decreasing, serial
// strictly increasing (regions rely on this to bound how long serials are remembered).
struct GrantSequence {
std::uint64_t serial{}, issued_at{};
};
class AccountDirectory {
public:
AccountDirectory() = default;
AccountDirectory(const AccountDirectory&) = delete;
AccountDirectory& operator=(const AccountDirectory&) = delete;
virtual ~AccountDirectory() = default;
// The subject's account, created with a fresh random id on first sight.
[[nodiscard]] virtual std::expected<AccountId, IdentityError>
resolve(const ProviderSubject& subject) = 0;
[[nodiscard]] virtual std::expected<GrantSequence, IdentityError>
next_grant(const AccountId& account, std::uint64_t now_seconds) = 0;
protected:
AccountDirectory(AccountDirectory&&) = default;
AccountDirectory& operator=(AccountDirectory&&) = default;
};
// Bounded in-memory directory for tests and local tools; not durable.
class MemoryAccountDirectory final : public AccountDirectory {
public:
explicit MemoryAccountDirectory(std::size_t max_accounts) : max_accounts_{max_accounts} {}
[[nodiscard]] std::expected<AccountId, IdentityError>
resolve(const ProviderSubject& subject) override;
[[nodiscard]] std::expected<GrantSequence, IdentityError>
next_grant(const AccountId& account, std::uint64_t now_seconds) override;
private:
std::size_t max_accounts_;
std::map<ProviderSubject, AccountId> subjects_;
std::map<AccountId, GrantSequence> sequences_;
};
class GrantIssuer {
public:
// The provider and signing key must belong to the same environment. Lifetime is
// 1..3600 s; regions refuse lifetimes above their own maximum (300 s by default).
[[nodiscard]] static std::expected<GrantIssuer, IdentityError>
create(network::GrantSigningKey key, IdentityProvider& provider, AccountDirectory& directory,
std::uint64_t lifetime_seconds);
[[nodiscard]] std::expected<network::SessionGrant, IdentityError>
issue(std::span<const std::uint8_t> credential, world::WorldIdentity world,
std::uint64_t region, std::uint64_t now_seconds);
private:
GrantIssuer(network::GrantSigningKey key, IdentityProvider& provider,
AccountDirectory& directory, std::uint64_t lifetime)
: key_{std::move(key)}, provider_{&provider}, directory_{&directory}, lifetime_{lifetime} {}
network::GrantSigningKey key_;
IdentityProvider* provider_;
AccountDirectory* directory_;
std::uint64_t lifetime_;
};
} // namespace evo::identity
+138
View File
@@ -0,0 +1,138 @@
#pragma once
#include "evo/network/admission.hpp"
#include "evo/world/chunks.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <optional>
#include <string>
#include <vector>
// M10.3 account-bound session control for one region (ADR-0091). Transport-neutral and
// single-owner. It decides which session, if any, controls each account in this region
// and leaves intentions to 10.4. A grant authorizes opening (or refreshing) a session;
// per-account grant serials order grants so the newest wins: a grant is usable once and
// never after a newer one for the same account (replay and stolen stale grants fail).
// The M9 dev path (SessionAdmission, protocol v1) is unchanged.
namespace evo::network {
// Provider-independent account identity: 128 random bits assigned by the account
// directory, never derived from a provider id (Steam, dev test or otherwise).
struct AccountId {
std::array<std::uint8_t, 16> bytes{};
[[nodiscard]] bool valid() const noexcept;
auto operator<=>(const AccountId&) const = default;
};
// Short non-secret label for logs and events: the first 4 bytes in hex ("acct-1a2b3c4d").
// Grants, signatures and keys have no log form at all.
[[nodiscard]] std::string log_label(const AccountId& account);
// Claims of a production session grant (schemas/network/session-grant-v1.md).
struct GrantClaims {
std::uint64_t grant_id{};
AccountId account;
std::uint64_t serial{}; // Strictly increasing per account; issued by the directory.
world::WorldIdentity world;
std::uint64_t region{}, issued_at{}, expires_at{}; // Server clock, seconds.
};
class GrantVerifier;
// Only GrantVerifier::verify constructs this, after the signature and environment checked.
class VerifiedSessionGrant {
public:
[[nodiscard]] const GrantClaims& claims() const noexcept {
return claims_;
}
[[nodiscard]] DeploymentEnvironment environment() const noexcept {
return environment_;
}
private:
friend class GrantVerifier;
VerifiedSessionGrant(DeploymentEnvironment environment, const GrantClaims& claims)
: claims_{claims}, environment_{environment} {}
GrantClaims claims_;
DeploymentEnvironment environment_;
};
struct ControlConfig {
DeploymentEnvironment environment{DeploymentEnvironment::dev};
world::WorldIdentity world;
std::uint64_t region{}, epoch{};
std::size_t max_sessions{32};
std::size_t max_accounts{4096}; // Tracked accounts (sessions, serials, rates).
std::uint64_t max_grant_lifetime{300}; // Seconds; grants are short-lived.
std::uint64_t clock_skew{30}; // Seconds tolerated before issued_at.
// Every verified open or refresh by an account counts, accepted or not.
std::uint32_t max_account_attempts{4};
// Every attempt before signature verification counts, region-wide.
std::uint32_t max_region_attempts{64};
std::uint64_t attempt_window{60}; // Seconds, for both limits.
};
enum class ControlError : std::uint8_t {
invalid_config,
wrong_environment,
wrong_world,
wrong_region,
invalid_lifetime,
not_yet_valid,
expired,
stale_grant, // Serial not newer than one already presented for this account.
rate_limited,
sessions_full,
accounts_full, // Fail closed: never forget a serial early.
unknown_session,
wrong_account
};
struct OpenedSession {
std::uint64_t session{};
std::uint64_t superseded{}; // The account's previous session, now closed (0 if none).
std::uint64_t epoch{}, expires_at{};
};
class SessionControl {
public:
[[nodiscard]] static std::expected<SessionControl, ControlError> create(ControlConfig config);
// Region-wide attempt limit, checked before any signature work. Counts the attempt.
[[nodiscard]] std::expected<void, ControlError> attempt(std::uint64_t now_seconds);
// A newer grant for an account that already holds a session takes control: the old
// session is closed first and reported as superseded. Control is never shared.
[[nodiscard]] std::expected<OpenedSession, ControlError> open(const VerifiedSessionGrant& grant,
std::uint64_t now_seconds);
// In-session renewal with a newer grant for the same account: extends the expiry
// without a reconnect or new baseline.
[[nodiscard]] std::expected<std::uint64_t, ControlError>
refresh(std::uint64_t session, const VerifiedSessionGrant& grant, std::uint64_t now_seconds);
[[nodiscard]] std::expected<void, ControlError> close(std::uint64_t session);
// Sessions whose grant expired at `now_seconds`; they are closed by this call.
[[nodiscard]] std::vector<std::uint64_t> expire(std::uint64_t now_seconds);
// New ownership epoch: every session closes (ADR-0089: none survives an epoch change).
[[nodiscard]] std::expected<std::vector<std::uint64_t>, ControlError>
advance_epoch(std::uint64_t epoch);
[[nodiscard]] std::optional<std::uint64_t> holder(const AccountId& account) const;
[[nodiscard]] std::optional<AccountId> account_of(std::uint64_t session) const;
[[nodiscard]] std::size_t sessions() const noexcept;
[[nodiscard]] std::uint64_t epoch() const noexcept {
return config_.epoch;
}
private:
struct Account {
AccountId id;
std::uint64_t serial{}; // Newest grant serial presented and accepted.
std::uint64_t remember_until{}; // Every grant up to `serial` has expired by then.
std::uint64_t session{}, session_expires_at{};
std::uint64_t window_start{};
std::uint32_t attempts{};
};
explicit SessionControl(ControlConfig config) : config_{config} {}
[[nodiscard]] std::expected<Account*, ControlError> admit(const VerifiedSessionGrant& grant,
std::uint64_t now_seconds);
void accept(Account& account, const GrantClaims& claims);
void forget_idle(std::uint64_t now_seconds);
ControlConfig config_;
std::uint64_t next_session_{1};
std::uint64_t region_window_start_{};
std::uint32_t region_attempts_{};
std::vector<Account> accounts_;
};
} // namespace evo::network
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include "evo/network/session_control.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <span>
#include <vector>
// Production session grants v1 (ADR-0091, schemas/network/session-grant-v1.md): a fixed
// 160-byte record ("EVO-GRANT" marker, version, environment, issuer key id, claims)
// signed with ECDSA P-256/SHA-256 through Mbed TLS PSA. Regions hold only public keys,
// so a compromised region cannot mint grants. The signed environment byte must match
// the verifier's environment: a dev-signed grant never verifies in stage or World0, and
// M9 dev grants (a different marker and length) never verify here. Grant bytes and keys
// have no log form.
namespace evo::network {
inline constexpr std::size_t session_grant_bytes = 160;
inline constexpr std::size_t grant_private_key_bytes = 32; // P-256 scalar.
inline constexpr std::size_t grant_public_key_bytes = 65; // Uncompressed point.
using SessionGrant = std::array<std::uint8_t, session_grant_bytes>;
using GrantPublicKey = std::array<std::uint8_t, grant_public_key_bytes>;
enum class SessionGrantError : std::uint8_t {
invalid_key,
duplicate_key,
too_many_keys,
invalid_claims,
malformed,
wrong_marker,
unsupported_version,
wrong_environment,
unknown_key,
bad_signature,
crypto
};
// Issuer-side signing key (PSA, non-exportable private part). Move-only.
class GrantSigningKey {
public:
[[nodiscard]] static std::expected<GrantSigningKey, SessionGrantError>
generate(DeploymentEnvironment environment, std::uint32_t key_id);
[[nodiscard]] static std::expected<GrantSigningKey, SessionGrantError>
import(DeploymentEnvironment environment, std::uint32_t key_id,
std::span<const std::uint8_t> private_key);
GrantSigningKey(GrantSigningKey&& other) noexcept;
GrantSigningKey& operator=(GrantSigningKey&& other) noexcept;
GrantSigningKey(const GrantSigningKey&) = delete;
GrantSigningKey& operator=(const GrantSigningKey&) = delete;
~GrantSigningKey();
// Structural checks only (nonzero ids, serial and scope, ordered times).
[[nodiscard]] std::expected<SessionGrant, SessionGrantError>
sign(const GrantClaims& claims) const;
[[nodiscard]] std::expected<GrantPublicKey, SessionGrantError> public_key() const;
[[nodiscard]] DeploymentEnvironment environment() const noexcept {
return environment_;
}
[[nodiscard]] std::uint32_t key_id() const noexcept {
return key_id_;
}
private:
GrantSigningKey(DeploymentEnvironment environment, std::uint32_t key_id, std::uint32_t key)
: environment_{environment}, key_id_{key_id}, key_{key} {}
DeploymentEnvironment environment_;
std::uint32_t key_id_;
std::uint32_t key_; // PSA key id; zero when moved-from.
};
// Region-side verifier for one environment with up to 8 issuer public keys (rotation).
class GrantVerifier {
public:
static constexpr std::size_t max_keys = 8;
[[nodiscard]] static std::expected<GrantVerifier, SessionGrantError>
create(DeploymentEnvironment environment);
GrantVerifier(GrantVerifier&& other) noexcept;
GrantVerifier& operator=(GrantVerifier&& other) noexcept;
GrantVerifier(const GrantVerifier&) = delete;
GrantVerifier& operator=(const GrantVerifier&) = delete;
~GrantVerifier();
[[nodiscard]] std::expected<void, SessionGrantError>
add_key(std::uint32_t key_id, std::span<const std::uint8_t> public_key);
// Signature first: no claim byte is trusted before it verifies.
[[nodiscard]] std::expected<VerifiedSessionGrant, SessionGrantError>
verify(std::span<const std::uint8_t> grant) const;
private:
struct Key {
std::uint32_t key_id{}, key{};
};
explicit GrantVerifier(DeploymentEnvironment environment) : environment_{environment} {}
void destroy() noexcept;
DeploymentEnvironment environment_;
std::vector<Key> keys_;
};
// Cryptographically random bytes (PSA); used for account and grant ids.
[[nodiscard]] std::expected<void, SessionGrantError> random_bytes(std::span<std::uint8_t> out);
[[nodiscard]] std::expected<AccountId, SessionGrantError> generate_account_id();
} // namespace evo::network
+28
View File
@@ -0,0 +1,28 @@
# Session grant, version 1
Production session grant for M10 (ADR-0091). Implemented by `GrantSigningKey::sign` and
`GrantVerifier::verify` (include/evo/network/session_grant.hpp). Fixed length 160 bytes;
integers little-endian. Any other length, marker, version, reserved value or
environment is refused. Grants are credentials: never log, persist or display them.
| Offset | Size | Field | Rule |
|---|---|---|---|
| 0 | 16 | marker | `EVO-GRANT` followed by 7 zero bytes |
| 16 | 2 | version | 1 |
| 18 | 1 | environment | 1 dev, 2 stage, 3 World0; must equal the verifier's |
| 19 | 1 | reserved | 0 |
| 20 | 4 | key_id | issuer key id, nonzero; selects the verifying public key |
| 24 | 8 | grant_id | random, nonzero |
| 32 | 16 | account | AccountId, not all zero |
| 48 | 8 | serial | per-account, strictly increasing, nonzero |
| 56 | 8 | world | nonzero |
| 64 | 8 | frame | nonzero |
| 72 | 8 | region | nonzero |
| 80 | 8 | issued_at | seconds, issuer clock; non-decreasing per account |
| 88 | 8 | expires_at | seconds; greater than issued_at |
| 96 | 64 | signature | ECDSA P-256, SHA-256 over bytes 0..95, raw r \|\| s |
Verification order: length, key id lookup, signature, marker, version and reserved,
environment, claim structure. Regions then apply scope, lifetime (at most their
maximum, 300 s by default), clock skew, expiry and the serial rule (ADR-0091).
A change to any field or rule is a new version.
+115
View File
@@ -0,0 +1,115 @@
#include "evo/identity/identity.hpp"
#include <algorithm>
#include <limits>
#include <string_view>
namespace evo::identity {
namespace {
constexpr std::string_view dev_test_prefix = "dev-test:";
constexpr std::size_t max_dev_name = 32;
constexpr std::size_t max_subject = 128;
} // namespace
std::expected<DevTestProvider, IdentityError>
DevTestProvider::create(DeploymentEnvironment environment) {
// Test identities prove nothing; they must not exist outside dev.
if (environment != DeploymentEnvironment::dev)
return std::unexpected(IdentityError::not_dev_environment);
return DevTestProvider{};
}
std::expected<ProviderSubject, IdentityError>
DevTestProvider::authenticate(std::span<const std::uint8_t> credential) {
const std::string_view text{reinterpret_cast<const char*>(credential.data()),
credential.size()};
if (!text.starts_with(dev_test_prefix))
return std::unexpected(IdentityError::unauthenticated);
const auto name = text.substr(dev_test_prefix.size());
if (name.empty() || name.size() > max_dev_name || !std::ranges::all_of(name, [](char c) {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
}))
return std::unexpected(IdentityError::unauthenticated);
return ProviderSubject{ProviderKind::dev_test, std::string{name}};
}
std::expected<AccountId, IdentityError>
MemoryAccountDirectory::resolve(const ProviderSubject& subject) {
if (subject.subject.empty() || subject.subject.size() > max_subject)
return std::unexpected(IdentityError::invalid_request);
if (const auto found = subjects_.find(subject); found != subjects_.end())
return found->second;
if (subjects_.size() >= max_accounts_)
return std::unexpected(IdentityError::directory_full);
AccountId account;
do { // Collisions of 128 random bits are not expected; never reuse an id regardless.
auto generated = network::generate_account_id();
if (!generated)
return std::unexpected(IdentityError::signing);
account = *generated;
} while (sequences_.contains(account));
subjects_.emplace(subject, account);
sequences_.emplace(account, GrantSequence{});
return account;
}
std::expected<GrantSequence, IdentityError>
MemoryAccountDirectory::next_grant(const AccountId& account, std::uint64_t now_seconds) {
const auto found = sequences_.find(account);
if (found == sequences_.end())
return std::unexpected(IdentityError::invalid_request);
auto& s = found->second;
if (s.serial == std::numeric_limits<std::uint64_t>::max())
return std::unexpected(IdentityError::serial_exhausted);
++s.serial;
s.issued_at = std::max(s.issued_at, now_seconds); // Never earlier than a prior grant.
return s;
}
std::expected<GrantIssuer, IdentityError> GrantIssuer::create(network::GrantSigningKey key,
IdentityProvider& provider,
AccountDirectory& directory,
std::uint64_t lifetime_seconds) {
if (provider.environment() != key.environment())
return std::unexpected(IdentityError::wrong_environment);
if (lifetime_seconds == 0 || lifetime_seconds > 3600)
return std::unexpected(IdentityError::invalid_request);
return GrantIssuer{std::move(key), provider, directory, lifetime_seconds};
}
std::expected<network::SessionGrant, IdentityError>
GrantIssuer::issue(std::span<const std::uint8_t> credential, world::WorldIdentity world,
std::uint64_t region, std::uint64_t now_seconds) {
if (world.world == 0 || world.frame == 0 || region == 0 ||
now_seconds > std::numeric_limits<std::uint64_t>::max() - lifetime_)
return std::unexpected(IdentityError::invalid_request);
auto subject = provider_->authenticate(credential);
if (!subject)
return std::unexpected(subject.error());
auto account = directory_->resolve(*subject);
if (!account)
return std::unexpected(account.error());
auto sequence = directory_->next_grant(*account, now_seconds);
if (!sequence)
return std::unexpected(sequence.error());
network::GrantClaims claims;
do {
std::array<std::uint8_t, 8> bytes{};
if (!network::random_bytes(bytes))
return std::unexpected(IdentityError::signing);
for (std::size_t i = 0; i < bytes.size(); ++i)
claims.grant_id |= static_cast<std::uint64_t>(bytes.at(i)) << (8U * i);
} while (claims.grant_id == 0);
claims.account = *account;
claims.serial = sequence->serial;
claims.world = world;
claims.region = region;
claims.issued_at = sequence->issued_at;
if (sequence->issued_at > std::numeric_limits<std::uint64_t>::max() - lifetime_)
return std::unexpected(IdentityError::invalid_request);
claims.expires_at = sequence->issued_at + lifetime_;
auto grant = key_.sign(claims);
if (!grant)
return std::unexpected(IdentityError::signing);
return *grant;
}
} // namespace evo::identity
+192
View File
@@ -0,0 +1,192 @@
#include "evo/network/session_control.hpp"
#include <algorithm>
namespace evo::network {
namespace {
// Fixed attempt windows: restart when `now` left the window (or the clock went back).
bool window_over(std::uint64_t start, std::uint64_t now, std::uint64_t length) {
return now < start || now - start >= length;
}
} // namespace
bool AccountId::valid() const noexcept {
return std::ranges::any_of(bytes, [](std::uint8_t b) { return b != 0; });
}
std::string log_label(const AccountId& account) {
constexpr char digits[] = "0123456789abcdef";
std::string label{"acct-"};
for (std::size_t i = 0; i < 4; ++i) {
label.push_back(digits[account.bytes.at(i) >> 4U]);
label.push_back(digits[account.bytes.at(i) & 0xFU]);
}
return label;
}
std::expected<SessionControl, ControlError> SessionControl::create(ControlConfig config) {
if (config.world.world == 0 || config.world.frame == 0 || config.region == 0 ||
config.epoch == 0 || config.max_sessions == 0 || config.max_sessions > 1024 ||
config.max_accounts < config.max_sessions || config.max_accounts > (std::size_t{1} << 20) ||
config.max_grant_lifetime == 0 || config.max_grant_lifetime > 3600 ||
config.clock_skew > 300 || config.max_account_attempts == 0 ||
config.max_region_attempts == 0 || config.attempt_window == 0 ||
config.attempt_window > 3600)
return std::unexpected(ControlError::invalid_config);
SessionControl control{config};
control.accounts_.reserve(config.max_accounts);
return control;
}
std::expected<void, ControlError> SessionControl::attempt(std::uint64_t now_seconds) {
if (window_over(region_window_start_, now_seconds, config_.attempt_window)) {
region_window_start_ = now_seconds;
region_attempts_ = 0;
}
if (region_attempts_ >= config_.max_region_attempts)
return std::unexpected(ControlError::rate_limited);
++region_attempts_;
return {};
}
void SessionControl::forget_idle(std::uint64_t now_seconds) {
std::erase_if(accounts_, [&](const Account& a) {
return a.session == 0 && a.remember_until <= now_seconds &&
window_over(a.window_start, now_seconds, config_.attempt_window);
});
}
std::expected<SessionControl::Account*, ControlError>
SessionControl::admit(const VerifiedSessionGrant& grant, std::uint64_t now_seconds) {
const auto& c = grant.claims();
if (grant.environment() != config_.environment)
return std::unexpected(ControlError::wrong_environment);
if (c.world != config_.world)
return std::unexpected(ControlError::wrong_world);
if (c.region != config_.region)
return std::unexpected(ControlError::wrong_region);
if (c.expires_at <= c.issued_at || c.expires_at - c.issued_at > config_.max_grant_lifetime)
return std::unexpected(ControlError::invalid_lifetime);
if (c.issued_at > now_seconds && c.issued_at - now_seconds > config_.clock_skew)
return std::unexpected(ControlError::not_yet_valid);
if (now_seconds >= c.expires_at)
return std::unexpected(ControlError::expired);
forget_idle(now_seconds);
auto found =
std::ranges::find_if(accounts_, [&](const Account& a) { return a.id == c.account; });
if (found == accounts_.end()) {
if (accounts_.size() >= config_.max_accounts)
return std::unexpected(ControlError::accounts_full);
accounts_.push_back({c.account, 0, 0, 0, 0, now_seconds, 0});
found = std::prev(accounts_.end());
}
auto& a = *found;
// Every verified attempt by the account counts, accepted or not.
if (window_over(a.window_start, now_seconds, config_.attempt_window)) {
a.window_start = now_seconds;
a.attempts = 0;
}
if (a.attempts >= config_.max_account_attempts)
return std::unexpected(ControlError::rate_limited);
++a.attempts;
if (c.serial <= a.serial)
return std::unexpected(ControlError::stale_grant);
return &a;
}
void SessionControl::accept(Account& a, const GrantClaims& c) {
a.serial = c.serial;
// Issuers keep serial and issued_at non-decreasing per account, so every older grant
// expires by the newest issued_at plus the maximum lifetime: remember until then.
a.remember_until = std::max(a.remember_until, c.issued_at + config_.max_grant_lifetime);
a.session_expires_at = c.expires_at;
}
std::expected<OpenedSession, ControlError> SessionControl::open(const VerifiedSessionGrant& grant,
std::uint64_t now_seconds) {
auto admitted = admit(grant, now_seconds);
if (!admitted)
return std::unexpected(admitted.error());
auto& a = **admitted;
// A refused open leaves the grant unconsumed: its serial is not recorded.
if (a.session == 0 && sessions() >= config_.max_sessions)
return std::unexpected(ControlError::sessions_full);
OpenedSession opened;
opened.superseded = a.session; // Closed before the new session exists.
accept(a, grant.claims());
a.session = next_session_++;
opened.session = a.session;
opened.epoch = config_.epoch;
opened.expires_at = a.session_expires_at;
return opened;
}
std::expected<std::uint64_t, ControlError>
SessionControl::refresh(std::uint64_t session, const VerifiedSessionGrant& grant,
std::uint64_t now_seconds) {
const auto holder_of =
std::ranges::find_if(accounts_, [&](const Account& a) { return a.session == session; });
if (session == 0 || holder_of == accounts_.end())
return std::unexpected(ControlError::unknown_session);
if (holder_of->id != grant.claims().account)
return std::unexpected(ControlError::wrong_account);
auto admitted = admit(grant, now_seconds);
if (!admitted)
return std::unexpected(admitted.error());
accept(**admitted, grant.claims());
return (*admitted)->session_expires_at;
}
std::expected<void, ControlError> SessionControl::close(std::uint64_t session) {
const auto found =
std::ranges::find_if(accounts_, [&](const Account& a) { return a.session == session; });
if (session == 0 || found == accounts_.end())
return std::unexpected(ControlError::unknown_session);
found->session = 0;
return {};
}
std::vector<std::uint64_t> SessionControl::expire(std::uint64_t now_seconds) {
std::vector<std::uint64_t> closed;
for (auto& a : accounts_)
if (a.session != 0 && now_seconds >= a.session_expires_at) {
closed.push_back(a.session);
a.session = 0;
}
return closed;
}
std::expected<std::vector<std::uint64_t>, ControlError>
SessionControl::advance_epoch(std::uint64_t epoch) {
if (epoch <= config_.epoch)
return std::unexpected(ControlError::invalid_config);
config_.epoch = epoch;
std::vector<std::uint64_t> closed;
for (auto& a : accounts_)
if (a.session != 0) {
closed.push_back(a.session);
a.session = 0;
}
return closed;
}
std::optional<std::uint64_t> SessionControl::holder(const AccountId& account) const {
const auto found =
std::ranges::find_if(accounts_, [&](const Account& a) { return a.id == account; });
if (found == accounts_.end() || found->session == 0)
return std::nullopt;
return found->session;
}
std::optional<AccountId> SessionControl::account_of(std::uint64_t session) const {
const auto found =
std::ranges::find_if(accounts_, [&](const Account& a) { return a.session == session; });
if (session == 0 || found == accounts_.end())
return std::nullopt;
return found->id;
}
std::size_t SessionControl::sessions() const noexcept {
return static_cast<std::size_t>(
std::ranges::count_if(accounts_, [](const Account& a) { return a.session != 0; }));
}
} // namespace evo::network
+241
View File
@@ -0,0 +1,241 @@
#include "evo/network/session_grant.hpp"
#include <algorithm>
#include <psa/crypto.h>
#include <type_traits>
#include <utility>
namespace evo::network {
namespace {
static_assert(std::is_same_v<mbedtls_svc_key_id_t, std::uint32_t>,
"key ids are stored as plain PSA identifiers");
constexpr std::array<std::uint8_t, 16> marker{'E', 'V', 'O', '-', 'G', 'R', 'A', 'N',
'T', 0, 0, 0, 0, 0, 0, 0};
constexpr std::uint16_t grant_version = 1;
constexpr std::size_t signed_end = 96; // The signature covers bytes [0, 96).
constexpr std::size_t signature_bytes = session_grant_bytes - signed_end;
constexpr psa_algorithm_t algorithm = PSA_ALG_ECDSA(PSA_ALG_SHA_256);
static_assert(signature_bytes == PSA_ECDSA_SIGNATURE_SIZE(256));
std::uint8_t environment_byte(DeploymentEnvironment e) {
return static_cast<std::uint8_t>(static_cast<std::uint8_t>(e) + 1);
}
void put(SessionGrant& out, std::size_t at, std::uint64_t v, std::size_t count) {
for (std::size_t i = 0; i < count; ++i)
out.at(at + i) = static_cast<std::uint8_t>(v >> (8 * i));
}
std::uint64_t get(std::span<const std::uint8_t> in, std::size_t at, std::size_t count) {
std::uint64_t v = 0;
for (std::size_t i = 0; i < count; ++i)
v |= static_cast<std::uint64_t>(in[at + i]) << (8 * i);
return v;
}
bool structurally_valid(const GrantClaims& c) {
return c.grant_id != 0 && c.account.valid() && c.serial != 0 && c.world.world != 0 &&
c.world.frame != 0 && c.region != 0 && c.expires_at > c.issued_at;
}
std::expected<std::uint32_t, SessionGrantError> import_key(const psa_key_attributes_t& attributes,
std::span<const std::uint8_t> bytes) {
mbedtls_svc_key_id_t key = PSA_KEY_ID_NULL;
if (psa_import_key(&attributes, bytes.data(), bytes.size(), &key) != PSA_SUCCESS)
return std::unexpected(SessionGrantError::invalid_key);
return key;
}
psa_key_attributes_t pair_attributes() {
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&attributes, 256);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
psa_set_key_algorithm(&attributes, algorithm);
return attributes;
}
} // namespace
std::expected<void, SessionGrantError> random_bytes(std::span<std::uint8_t> out) {
if (psa_crypto_init() != PSA_SUCCESS ||
psa_generate_random(out.data(), out.size()) != PSA_SUCCESS)
return std::unexpected(SessionGrantError::crypto);
return {};
}
std::expected<AccountId, SessionGrantError> generate_account_id() {
AccountId id;
do {
if (auto r = random_bytes(id.bytes); !r)
return std::unexpected(r.error());
} while (!id.valid());
return id;
}
std::expected<GrantSigningKey, SessionGrantError>
GrantSigningKey::generate(DeploymentEnvironment environment, std::uint32_t key_id) {
if (key_id == 0)
return std::unexpected(SessionGrantError::invalid_key);
if (psa_crypto_init() != PSA_SUCCESS)
return std::unexpected(SessionGrantError::crypto);
auto attributes = pair_attributes();
mbedtls_svc_key_id_t key = PSA_KEY_ID_NULL;
const auto status = psa_generate_key(&attributes, &key);
psa_reset_key_attributes(&attributes);
if (status != PSA_SUCCESS)
return std::unexpected(SessionGrantError::crypto);
return GrantSigningKey{environment, key_id, key};
}
std::expected<GrantSigningKey, SessionGrantError>
GrantSigningKey::import(DeploymentEnvironment environment, std::uint32_t key_id,
std::span<const std::uint8_t> private_key) {
if (key_id == 0 || private_key.size() != grant_private_key_bytes)
return std::unexpected(SessionGrantError::invalid_key);
if (psa_crypto_init() != PSA_SUCCESS)
return std::unexpected(SessionGrantError::crypto);
auto attributes = pair_attributes();
auto key = import_key(attributes, private_key);
psa_reset_key_attributes(&attributes);
if (!key)
return std::unexpected(key.error());
return GrantSigningKey{environment, key_id, *key};
}
GrantSigningKey::GrantSigningKey(GrantSigningKey&& other) noexcept
: environment_{other.environment_}, key_id_{other.key_id_},
key_{std::exchange(other.key_, PSA_KEY_ID_NULL)} {}
GrantSigningKey& GrantSigningKey::operator=(GrantSigningKey&& other) noexcept {
if (this != &other) {
if (key_ != PSA_KEY_ID_NULL)
(void)psa_destroy_key(key_);
environment_ = other.environment_;
key_id_ = other.key_id_;
key_ = std::exchange(other.key_, PSA_KEY_ID_NULL);
}
return *this;
}
GrantSigningKey::~GrantSigningKey() {
if (key_ != PSA_KEY_ID_NULL)
(void)psa_destroy_key(key_);
}
std::expected<SessionGrant, SessionGrantError>
GrantSigningKey::sign(const GrantClaims& claims) const {
if (key_ == PSA_KEY_ID_NULL)
return std::unexpected(SessionGrantError::invalid_key);
if (!structurally_valid(claims))
return std::unexpected(SessionGrantError::invalid_claims);
SessionGrant out{};
std::ranges::copy(marker, out.begin());
put(out, 16, grant_version, 2);
out.at(18) = environment_byte(environment_);
out.at(19) = 0;
put(out, 20, key_id_, 4);
put(out, 24, claims.grant_id, 8);
std::ranges::copy(claims.account.bytes, out.begin() + 32);
put(out, 48, claims.serial, 8);
put(out, 56, claims.world.world, 8);
put(out, 64, claims.world.frame, 8);
put(out, 72, claims.region, 8);
put(out, 80, claims.issued_at, 8);
put(out, 88, claims.expires_at, 8);
std::size_t length = 0;
if (psa_sign_message(key_, algorithm, out.data(), signed_end, out.data() + signed_end,
signature_bytes, &length) != PSA_SUCCESS ||
length != signature_bytes)
return std::unexpected(SessionGrantError::crypto);
return out;
}
std::expected<GrantPublicKey, SessionGrantError> GrantSigningKey::public_key() const {
if (key_ == PSA_KEY_ID_NULL)
return std::unexpected(SessionGrantError::invalid_key);
GrantPublicKey out{};
std::size_t length = 0;
if (psa_export_public_key(key_, out.data(), out.size(), &length) != PSA_SUCCESS ||
length != out.size())
return std::unexpected(SessionGrantError::crypto);
return out;
}
std::expected<GrantVerifier, SessionGrantError>
GrantVerifier::create(DeploymentEnvironment environment) {
if (psa_crypto_init() != PSA_SUCCESS)
return std::unexpected(SessionGrantError::crypto);
return GrantVerifier{environment};
}
GrantVerifier::GrantVerifier(GrantVerifier&& other) noexcept
: environment_{other.environment_}, keys_{std::exchange(other.keys_, {})} {}
GrantVerifier& GrantVerifier::operator=(GrantVerifier&& other) noexcept {
if (this != &other) {
destroy();
environment_ = other.environment_;
keys_ = std::exchange(other.keys_, {});
}
return *this;
}
GrantVerifier::~GrantVerifier() {
destroy();
}
void GrantVerifier::destroy() noexcept {
for (const auto& k : keys_)
(void)psa_destroy_key(k.key);
keys_.clear();
}
std::expected<void, SessionGrantError>
GrantVerifier::add_key(std::uint32_t key_id, std::span<const std::uint8_t> public_key) {
if (key_id == 0 || public_key.size() != grant_public_key_bytes)
return std::unexpected(SessionGrantError::invalid_key);
if (std::ranges::any_of(keys_, [&](const Key& k) { return k.key_id == key_id; }))
return std::unexpected(SessionGrantError::duplicate_key);
if (keys_.size() >= max_keys)
return std::unexpected(SessionGrantError::too_many_keys);
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&attributes, 256);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_MESSAGE);
psa_set_key_algorithm(&attributes, algorithm);
auto key = import_key(attributes, public_key);
psa_reset_key_attributes(&attributes);
if (!key)
return std::unexpected(key.error());
keys_.push_back({key_id, *key});
return {};
}
std::expected<VerifiedSessionGrant, SessionGrantError>
GrantVerifier::verify(std::span<const std::uint8_t> grant) const {
if (grant.size() != session_grant_bytes)
return std::unexpected(SessionGrantError::malformed);
// The key id only selects which key must verify; it is itself signed.
const auto key_id = static_cast<std::uint32_t>(get(grant, 20, 4));
const auto key = std::ranges::find_if(keys_, [&](const Key& k) { return k.key_id == key_id; });
if (key == keys_.end())
return std::unexpected(SessionGrantError::unknown_key);
const auto status = psa_verify_message(key->key, algorithm, grant.data(), signed_end,
grant.data() + signed_end, signature_bytes);
if (status == PSA_ERROR_INVALID_SIGNATURE)
return std::unexpected(SessionGrantError::bad_signature);
if (status != PSA_SUCCESS)
return std::unexpected(SessionGrantError::crypto);
if (!std::equal(marker.begin(), marker.end(), grant.begin()))
return std::unexpected(SessionGrantError::wrong_marker);
if (get(grant, 16, 2) != grant_version || grant[19] != 0)
return std::unexpected(SessionGrantError::unsupported_version);
if (grant[18] != environment_byte(environment_))
return std::unexpected(SessionGrantError::wrong_environment);
GrantClaims claims;
claims.grant_id = get(grant, 24, 8);
std::copy_n(grant.begin() + 32, claims.account.bytes.size(), claims.account.bytes.begin());
claims.serial = get(grant, 48, 8);
claims.world = {get(grant, 56, 8), get(grant, 64, 8)};
claims.region = get(grant, 72, 8);
claims.issued_at = get(grant, 80, 8);
claims.expires_at = get(grant, 88, 8);
if (!structurally_valid(claims))
return std::unexpected(SessionGrantError::invalid_claims);
return VerifiedSessionGrant{environment_, claims};
}
} // namespace evo::network
+331
View File
@@ -0,0 +1,331 @@
#include "evo/identity/identity.hpp"
#include "evo/network/dev_grant.hpp"
#include "evo/network/session_control.hpp"
#include "evo/network/session_grant.hpp"
#include "network_test.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <string_view>
#include <vector>
namespace evo::network_test {
namespace {
using namespace evo::network;
using evo::identity::IdentityError;
constexpr world::WorldIdentity world_id{7, 3};
constexpr std::uint64_t region = 11;
constexpr std::uint64_t now = 1'800'000'000;
AccountId account(std::uint8_t tag) {
AccountId a;
a.bytes.fill(tag);
return a;
}
GrantClaims claims(const AccountId& who, std::uint64_t serial, std::uint64_t issued = now,
std::uint64_t lifetime = 60) {
GrantClaims c;
c.grant_id = 1000 + serial;
c.account = who;
c.serial = serial;
c.world = world_id;
c.region = region;
c.issued_at = issued;
c.expires_at = issued + lifetime;
return c;
}
std::span<const std::uint8_t> bytes(std::string_view text) {
return {reinterpret_cast<const std::uint8_t*>(text.data()), text.size()};
}
// One environment's issuer key and region verifier.
struct Keys {
explicit Keys(DeploymentEnvironment e, std::uint32_t key_id = 1)
: signer{*GrantSigningKey::generate(e, key_id)}, verifier{*GrantVerifier::create(e)} {
CHECK(verifier.add_key(key_id, *signer.public_key()));
}
VerifiedSessionGrant verified(const GrantClaims& c) const {
auto grant = signer.sign(c);
CHECK(grant);
auto v = verifier.verify(*grant);
CHECK(v);
return *v;
}
GrantSigningKey signer;
GrantVerifier verifier;
};
ControlConfig config() {
ControlConfig c;
c.environment = DeploymentEnvironment::dev;
c.world = world_id;
c.region = region;
c.epoch = 5;
c.max_sessions = 4;
c.max_accounts = 8;
return c;
}
void grants() {
Keys dev{DeploymentEnvironment::dev};
const auto who = account(0x42);
const auto grant = *dev.signer.sign(claims(who, 1));
const auto v = dev.verifier.verify(grant);
CHECK(v && v->claims().account == who && v->claims().serial == 1 &&
v->claims().world == world_id && v->claims().region == region &&
v->environment() == DeploymentEnvironment::dev);
// Every signed byte matters, including the key id and environment.
for (std::size_t i = 0; i < session_grant_bytes; ++i) {
auto tampered = grant;
tampered.at(i) ^= 0x01;
const auto r = dev.verifier.verify(tampered);
CHECK(!r);
CHECK(r.error() == (i >= 20 && i < 24 ? SessionGrantError::unknown_key
: SessionGrantError::bad_signature));
}
CHECK(refused(dev.verifier.verify(std::span{grant}.first(159)), SessionGrantError::malformed));
// A dev-signed grant never verifies in stage or World0, even if a dev public key were
// misconfigured there: the environment byte is signed.
for (const auto e : {DeploymentEnvironment::stage, DeploymentEnvironment::world0}) {
auto other = *GrantVerifier::create(e);
CHECK(refused(other.verify(grant), SessionGrantError::unknown_key));
CHECK(other.add_key(1, *dev.signer.public_key()));
CHECK(refused(other.verify(grant), SessionGrantError::wrong_environment));
}
// M9 dev grants are not session grants.
std::array<std::uint8_t, dev_key_bytes> secret{};
secret.fill(9);
const auto dev_key = *DevGrantKey::import(DeploymentEnvironment::dev, secret);
DevGrantClaims dc;
dc.grant_id = 1;
dc.subject = 2;
dc.world = world_id;
dc.region = region;
dc.issued_at = now;
dc.expires_at = now + 60;
CHECK(refused(dev.verifier.verify(*dev_key.issue(dc)), SessionGrantError::malformed));
// Rotation: a second key verifies alongside; ids are unique; at most 8 keys.
Keys rotated{DeploymentEnvironment::dev, 2};
CHECK(dev.verifier.add_key(2, *rotated.signer.public_key()));
CHECK(dev.verifier.verify(*rotated.signer.sign(claims(who, 2))));
CHECK(refused(dev.verifier.add_key(2, *rotated.signer.public_key()),
SessionGrantError::duplicate_key));
for (std::uint32_t id = 3; id <= GrantVerifier::max_keys; ++id)
CHECK(dev.verifier.add_key(id, *rotated.signer.public_key()));
CHECK(refused(dev.verifier.add_key(99, *rotated.signer.public_key()),
SessionGrantError::too_many_keys));
// A grant signed by key 2 but labelled key 1 fails (the label is signed too).
auto relabelled = *rotated.signer.sign(claims(who, 3));
relabelled.at(20) = 1;
CHECK(refused(dev.verifier.verify(relabelled), SessionGrantError::bad_signature));
GrantPublicKey not_a_point{};
not_a_point.fill(0x04);
auto fresh = *GrantVerifier::create(DeploymentEnvironment::dev);
CHECK(refused(fresh.add_key(1, not_a_point), SessionGrantError::invalid_key));
CHECK(refused(fresh.add_key(0, *dev.signer.public_key()), SessionGrantError::invalid_key));
// Structural claims and key import.
auto bad = claims(who, 1);
bad.serial = 0;
CHECK(refused(dev.signer.sign(bad), SessionGrantError::invalid_claims));
bad = claims(who, 1);
bad.account = {};
CHECK(refused(dev.signer.sign(bad), SessionGrantError::invalid_claims));
std::array<std::uint8_t, grant_private_key_bytes> scalar{};
scalar.back() = 7;
auto imported = GrantSigningKey::import(DeploymentEnvironment::stage, 4, scalar);
CHECK(imported);
auto stage = *GrantVerifier::create(DeploymentEnvironment::stage);
CHECK(stage.add_key(4, *imported->public_key()));
CHECK(stage.verify(*imported->sign(claims(who, 1))));
CHECK(refused(
GrantSigningKey::import(DeploymentEnvironment::stage, 4, std::span{scalar}.first(31)),
SessionGrantError::invalid_key));
scalar.fill(0);
CHECK(refused(GrantSigningKey::import(DeploymentEnvironment::stage, 4, scalar),
SessionGrantError::invalid_key));
// Moved-from keys are inert.
auto moved = std::move(imported).value();
CHECK(refused(imported->sign(claims(who, 1)), // NOLINT(bugprone-use-after-move)
SessionGrantError::invalid_key));
CHECK(moved.sign(claims(who, 1)));
}
void identity_adapter() {
using namespace evo::identity;
for (const auto e : {DeploymentEnvironment::stage, DeploymentEnvironment::world0})
CHECK(refused(DevTestProvider::create(e), IdentityError::not_dev_environment));
auto provider = *DevTestProvider::create(DeploymentEnvironment::dev);
CHECK(provider.authenticate(bytes("dev-test:alice"))->subject == "alice");
for (const auto bad : {"alice", "dev-test:", "dev-test:Alice", "dev-test:a b",
"dev-test:0123456789abcdef0123456789abcdefX", "steam:alice"})
CHECK(refused(provider.authenticate(bytes(bad)), IdentityError::unauthenticated));
MemoryAccountDirectory directory{2};
const ProviderSubject alice{ProviderKind::dev_test, "alice"};
const auto a1 = *directory.resolve(alice);
CHECK(a1.valid() && *directory.resolve(alice) == a1);
const auto b = *directory.resolve({ProviderKind::dev_test, "bob"});
CHECK(b != a1);
CHECK(refused(directory.resolve({ProviderKind::dev_test, "carol"}),
IdentityError::directory_full));
const auto s1 = *directory.next_grant(a1, now);
const auto s2 = *directory.next_grant(a1, now - 100); // Clock went back.
CHECK(s1.serial == 1 && s2.serial == 2 && s2.issued_at == now);
// End to end: credential -> account -> signed grant -> region control.
Keys dev{DeploymentEnvironment::dev};
MemoryAccountDirectory accounts{16};
auto issuer = GrantIssuer::create(std::move(dev.signer), provider, accounts, 60);
CHECK(issuer);
auto control = *SessionControl::create(config());
const auto g1 = issuer->issue(bytes("dev-test:alice"), world_id, region, now);
const auto opened = control.open(*dev.verifier.verify(*g1), now);
CHECK(opened && opened->superseded == 0);
const auto g2 = issuer->issue(bytes("dev-test:alice"), world_id, region, now + 1);
const auto again = control.open(*dev.verifier.verify(*g2), now + 1);
CHECK(again && again->superseded == opened->session);
CHECK(refused(issuer->issue(bytes("nobody"), world_id, region, now),
IdentityError::unauthenticated));
CHECK(refused(issuer->issue(bytes("dev-test:alice"), {0, 0}, region, now),
IdentityError::invalid_request));
// A dev provider cannot drive a stage or World0 key.
for (const auto e : {DeploymentEnvironment::stage, DeploymentEnvironment::world0})
CHECK(refused(GrantIssuer::create(*GrantSigningKey::generate(e, 1), provider, accounts, 60),
IdentityError::wrong_environment));
CHECK(refused(GrantIssuer::create(*GrantSigningKey::generate(DeploymentEnvironment::dev, 1),
provider, accounts, 0),
IdentityError::invalid_request));
}
void control_rules() {
Keys dev{DeploymentEnvironment::dev};
const auto alice = account(1), bob = account(2);
{
auto bad = config();
bad.max_accounts = 2; // Fewer than sessions.
CHECK(refused(SessionControl::create(bad), ControlError::invalid_config));
bad = config();
bad.max_grant_lifetime = 3601;
CHECK(refused(SessionControl::create(bad), ControlError::invalid_config));
}
// Scope and time.
{
auto control = *SessionControl::create(config());
auto c = claims(alice, 1);
c.world = {7, 4};
CHECK(refused(control.open(dev.verified(c), now), ControlError::wrong_world));
c = claims(alice, 1);
c.region = 12;
CHECK(refused(control.open(dev.verified(c), now), ControlError::wrong_region));
CHECK(refused(control.open(dev.verified(claims(alice, 1, now, 301)), now),
ControlError::invalid_lifetime));
CHECK(refused(control.open(dev.verified(claims(alice, 1, now + 31)), now),
ControlError::not_yet_valid));
CHECK(control.open(dev.verified(claims(alice, 1, now + 30)), now));
CHECK(refused(control.open(dev.verified(claims(bob, 1)), now + 60), ControlError::expired));
// Grants verified for another environment are refused by this region.
Keys stage{DeploymentEnvironment::stage};
CHECK(refused(control.open(stage.verified(claims(bob, 1)), now),
ControlError::wrong_environment));
}
// Replay, duplicate login (newest wins) and stolen stale grants.
{
auto c = config();
c.max_account_attempts = 16; // Rate limits are tested separately.
auto control = *SessionControl::create(c);
const auto first = dev.verified(claims(alice, 5));
const auto s1 = control.open(first, now);
CHECK(s1 && s1->superseded == 0 && s1->epoch == 5 && s1->expires_at == now + 60);
CHECK(refused(control.open(first, now + 1), ControlError::stale_grant)); // Replay.
// An older, unexpired grant (e.g. stolen earlier) cannot take control.
CHECK(refused(control.open(dev.verified(claims(alice, 4)), now + 1),
ControlError::stale_grant));
CHECK(control.holder(alice) == s1->session);
const auto s2 = control.open(dev.verified(claims(alice, 6)), now + 2);
CHECK(s2 && s2->superseded == s1->session && s2->session != s1->session);
CHECK(control.holder(alice) == s2->session && control.sessions() == 1);
CHECK(!control.account_of(s1->session));
CHECK(refused(control.close(s1->session), ControlError::unknown_session));
// After close, the stale serial stays refused until every older grant expired.
CHECK(control.close(s2->session));
CHECK(refused(control.open(dev.verified(claims(alice, 6)), now + 3),
ControlError::stale_grant));
}
// Rate limits: account attempts (every verified attempt counts) and region attempts.
{
auto c = config();
c.max_account_attempts = 3;
c.max_region_attempts = 5;
c.attempt_window = 10;
auto control = *SessionControl::create(c);
const auto replayed = dev.verified(claims(alice, 1));
CHECK(control.open(replayed, now));
CHECK(refused(control.open(replayed, now), ControlError::stale_grant));
CHECK(refused(control.open(replayed, now), ControlError::stale_grant));
CHECK(
refused(control.open(dev.verified(claims(alice, 2)), now), ControlError::rate_limited));
CHECK(control.open(dev.verified(claims(alice, 2)), now + 10)); // New window.
for (int i = 0; i < 5; ++i)
CHECK(control.attempt(now));
CHECK(refused(control.attempt(now), ControlError::rate_limited));
CHECK(refused(control.attempt(now + 9), ControlError::rate_limited));
CHECK(control.attempt(now + 10));
}
// Capacity: a refused open does not consume the grant; accounts fail closed.
{
auto c = config();
c.max_sessions = 1;
c.max_accounts = 2;
auto control = *SessionControl::create(c);
const auto a = control.open(dev.verified(claims(alice, 1)), now);
const auto bob_grant = dev.verified(claims(bob, 1));
CHECK(refused(control.open(bob_grant, now), ControlError::sessions_full));
CHECK(control.close(a->session));
CHECK(control.open(bob_grant, now)); // Same grant, now admitted.
CHECK(refused(control.open(dev.verified(claims(account(3), 1)), now),
ControlError::accounts_full));
// Idle accounts are forgotten only after their grants and windows end.
CHECK(refused(control.open(dev.verified(claims(account(3), 1, now + 299)), now + 299),
ControlError::accounts_full));
const auto later = dev.verified(claims(account(3), 1, now + 300));
CHECK(refused(control.open(later, now + 300), ControlError::sessions_full)); // Bob holds.
}
// Refresh, expiry and epochs.
{
auto control = *SessionControl::create(config());
const auto a = control.open(dev.verified(claims(alice, 1)), now);
const auto b = control.open(dev.verified(claims(bob, 1)), now);
CHECK(control.refresh(a->session, dev.verified(claims(alice, 2, now + 50)), now + 50) ==
now + 110);
CHECK(refused(control.refresh(a->session, dev.verified(claims(alice, 2)), now + 51),
ControlError::stale_grant));
CHECK(refused(control.refresh(a->session, dev.verified(claims(bob, 2)), now + 51),
ControlError::wrong_account));
CHECK(refused(control.refresh(999, dev.verified(claims(alice, 3)), now + 51),
ControlError::unknown_session));
const auto expired = control.expire(now + 60);
CHECK(expired == std::vector<std::uint64_t>{b->session});
CHECK(control.holder(alice) == a->session && !control.holder(bob));
const auto c2 = control.open(dev.verified(claims(bob, 2, now + 60)), now + 60);
auto closed = control.advance_epoch(6);
CHECK(closed && closed->size() == 2 && control.sessions() == 0 && control.epoch() == 6);
CHECK(std::ranges::find(*closed, c2->session) != closed->end());
CHECK(refused(control.advance_epoch(6), ControlError::invalid_config));
const auto reopened = control.open(dev.verified(claims(alice, 3, now + 61)), now + 61);
CHECK(reopened && reopened->epoch == 6 && reopened->superseded == 0);
}
// Redaction: the log label carries only the first four id bytes.
AccountId labelled;
for (std::size_t i = 0; i < labelled.bytes.size(); ++i)
labelled.bytes.at(i) = static_cast<std::uint8_t>(0xA0 + i);
CHECK(log_label(labelled) == "acct-a0a1a2a3");
}
} // namespace
void control_tests() {
grants();
identity_adapter();
control_rules();
}
} // namespace evo::network_test
+1
View File
@@ -6,6 +6,7 @@ int main() try {
evo::network_test::protocol_tests();
evo::network_test::tls_tests();
evo::network_test::session_tests();
evo::network_test::control_tests();
std::puts("network tests passed");
return 0;
} catch (const std::exception& e) {
+1
View File
@@ -26,5 +26,6 @@ template <typename T, typename E> bool refused(const std::expected<T, E>& r, E e
void protocol_tests();
void tls_tests();
void session_tests();
void control_tests();
} // namespace evo::network_test
#define CHECK(...) ::evo::network_test::check(static_cast<bool>(__VA_ARGS__))