Files
Library/docs/roadmap/modules/Security.md

9.8 KiB
Raw Permalink Blame History

Security implementation plan

Status: planning only; all feature tasks PLANNED. Baseline f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24. Authority: requirements R-004, R-006, R-009, R-012, R-014–R-016; architecture C-02–C-05, C-07, C-09, C-13.

Existing capabilities and boundary

Security.hpp exposes Void::Security random URL-safe bearer tokens, BLAKE2b-256 token digests and verification, Argon2id password hashing/verification, random secret keys and authenticated local secret envelopes. Security.cpp initializes libsodium once, uses sodium_memcmp for decoded token digests, sodium password presets and crypto_secretbox_easy. The actual secret format is a 24-byte nonce followed by secretbox's combined authenticated ciphertext, with 16 bytes authentication overhead; preserve these bytes rather than inferring layout from the header's informal description. Existing SecretKey is a copyable 32-byte array; existing plaintext/results are ordinary vectors/strings, not secure allocations.

module.cmake declares Functional and Sodium::Sodium. Tests cover token shape/digest, malformed digest rejection, salted Argon2id with Interactive tests, secret round-trip, tampering and wrong-key rejection. A test name mentioning constant time is not timing side-channel proof. No account store, login/session manager, policy engine, TLS identity service or revocation workflow ships here. Graph coverage for all four source files matched metadata with no recorded issue; source verification grounds these claims.

Backend and workflow architecture

Retain libsodium for existing primitives; do not write replacement crypto. Keep low-level primitives usable without Storage, Net or Runtime. Crypto owns interoperable hash/signature primitives; Net owns TLS peer checks. Security owns NEW authentication, principal/session and authorization workflows expressed through injected ports. Concrete Storage/Sqlite adapters are optional higher targets and cannot become primitive dependencies. External identity protocols such as OIDC are a later explicitly versioned adapter capability; initial completion is local accounts and opaque bearer sessions, not an implicit JWT system.

// NEW illustrative Void::Security shapes; not existing compilable APIs.
class SecureBuffer; // move-only; explicit readable span, wiped on release
struct Principal { SubjectId subject; std::vector<RoleId> roles; };
struct SessionPolicy { std::chrono::seconds ttl{3600}; std::size_t max_per_subject{16}; };
class AccountSessionPort { /* versioned compare/exchange, atomic session create/revoke */ };
class Authenticator {
  Task<Result<SessionGrant>> login(LoginInput, OperationOptions);
  Task<Result<Principal>> authenticate(BearerToken, OperationOptions);
  Task<Result<void>> revoke(SessionId, OperationOptions);
};
Decision authorize(const Principal&, ActionId, const ResourceAttributes&);

Result/operation/clock/executor shapes are owned by Functional/Async/Time. Identifiers above are NEW Security domain types; no bearer secret has implicit formatting/serialization. Authenticator holds port ownership through shutdown; a principal is an immutable value snapshot with an authorization-policy generation. Authentication validates identity; authorization evaluates explicit actions and resources, default deny, deny overrides allow. Limit roles to 64/principal, policy rules to 4,096 and expression depth to 16. First policy language is native typed predicates without arbitrary scripts or filesystem/network access.

Login dataflow: bounded parse → identity normalization → rate admission → account lookup → bounded password job → credential-version check → atomic session write → return raw token once. Unknown account and wrong password share public denial and comparable work using a precomputed dummy hash; internal audit reasons differ. Credential changes racing with login invalidate the write through the port's version precondition. Store only digest, subject, expiry, roles/policy version and revocation generation. Tokens contain 32 entropy bytes; logging, URLs and metrics never carry them. Rehash-on-success uses a version-checked update and must not accidentally resurrect disabled credentials.

Authenticate hashes the token and reads the authoritative session state on every call initially; positive caching is disabled so revocation has no hidden cache window. TTL uses civil time injected by Time with an explicit clock-health check; monotonic deadlines govern operations. Startup clock rollback beyond configured 60-second tolerance fails session admission until reconciled. This tolerance is not a distributed clock safety guarantee. Revocation succeeds only after durable port acknowledgement. Lost replies have unknown outcome; query/retry by session identity. Authorization has no network side effects.

Resource and failure decisions

NEW defaults: password input ≤1 KiB, encoded hashes ≤1 KiB, tokens ≤512 bytes, local secret plaintext ≤16 MiB. Select Moderate for new stored passwords; accept supported existing encoded strengths only within an operator-approved verification budget. Do not reduce hash strength silently. Password jobs reserve their encoded memory cost before starting: default aggregate 512 MiB, at most two jobs and 32 waiters. If a preset exceeds the budget, report configuration/resource error. Password computation is not forcibly interruptible; cancelled jobs retain buffers/budget until completion, discard output and cannot create a session. Default sessions: 10,000 total, 16/subject, one-hour TTL; capacity includes unexpired entries. Explicit expiry cleanup is bounded at 256 records/turn. Shutdown closes admission and joins credential jobs before clearing secure buffers.

SecureBuffer uses sodium-assisted wiping and optional locked allocation; inability to meet a required locked-memory policy is an error, never an implicit downgrade. It does not claim to prevent every copy made by application code, swapping policy or core dumps. Add a NEW versioned secret envelope with magic/version/algorithm/key-id/length and authenticated metadata; legacy nonce+combined-ciphertext decoding stays a separate explicitly selected API. New writers never guess legacy format after authentication failure. Key rotation reads old key IDs, writes only the active ID, and retires a key only after an inventory proves no required ciphertext remains.

Trigger Outcome and ownership Validation
Sodium init / randomness failure Backend error; publish no token/key Backend fault seam
Wrong/malformed credentials Public denied; bounded work and internal audit reason No user enumeration in response
Encoded password requests excessive cost Reject before costly allocation Malicious encoded-hash corpus
Store unavailable / policy load invalid Fail closed; do not issue anonymous success Port outage and version races
Stop during hash One cancelled result; running job drains, no session write Cancellation vs completion
Session expired/revoked Denied; never recreate from token alone Revoke/login/clock histories
Secret authentication fails Error with no plaintext publication Every field and key mutation
Observer/audit failure Explicit audit policy; local login default fails if mandatory audit cannot admit Full audit queue, no secrets retained

Task DAG and acceptance

ID Phase / dependencies Scope and gate Recommended role
M-SECURITY-01 P0; baseline Freeze token/password/secret fixtures including actual envelope bytes; distinguish test names from security proof sol_implementer
M-SECURITY-02 P1; M-SECURITY-01, Memory/Functional contracts SecureBuffer, input/cost validation, error separation; wipe and allocation-failure tests astra_implementer
M-SECURITY-03 P2; M-SECURITY-02, Async/Time/Resilience gates Account/session ports and local workflows; revocation, version races, capacity and hash-stop tests pass astra_implementer
M-SECURITY-04 P2; M-SECURITY-03 Typed default-deny authorization and versioned secret/key rotation; unknown policy/version fails closed astra_implementer
M-SECURITY-05 P3; M-SECURITY-04, Storage or Sqlite adapter, Net Durable auth adapter and network integration; no Security→Storage/Net cycle, restart/revocation acceptance sol_implementer
M-SECURITY-06 P4; M-SECURITY-05, Replication Optional replicated auth port; quorum revocation and partition denial tested; external identity remains a separate capability gate astra_implementer

CURRENT verification is existing VoidTests source coverage above; nothing rerun here. PROPOSED checks require deterministic port/clock fixtures, malformed hashes/envelopes, secret-lifetime instrumentation, concurrent revocation and backend error injection before new runner commands are documented. Measure password queue/work latency separately, token lookup p50/p95/p99, throughput, allocation/RSS/CPU and build cost; run under fixed memory budgets, not reduced password cost to improve a benchmark. See PERFORMANCE, VALIDATION, and BUILD-AND-DISTRIBUTION.

Migration preserves old verification and secret decoding, while new APIs adopt move-only secrets and explicit policy. Do not reinterpret old envelope bytes or silently turn existing digest storage into session authentication. Rollback keeps old keys/readers until all new records are supported; disable new writers before reverting. Invalid-policy rollback retains the last validated immutable policy only when the operator explicitly selects that policy; it cannot manufacture authorization. See MIGRATION.