diff --git a/packages/cultcache-py/PARITY.md b/packages/cultcache-py/PARITY.md index 8c86896b..d65ddc18 100644 --- a/packages/cultcache-py/PARITY.md +++ b/packages/cultcache-py/PARITY.md @@ -39,6 +39,16 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti. `cultnet.error.v0`, and the local server advertises that version in hello responses because oversized snapshots and other peer failures use that contract on the wire. +- Python CultNet security/session primitives: + `CultNetClientSecurityOptions`, `CultNetServerSecurityOptions`, and + `CultNetSecret` mirror the C#/TS connection-key, server signing-secret, + development-default, environment-validation, base64url, and HMAC-SHA256 + session-token helper surface. Python creates C#-compatible versioned session + tokens with `userGuidN|expiresUnix|sessionVersion` payloads and still + validates legacy two-field tokens with session version `0`. AES-GCM string + and byte helpers use the same tag-prefix payload shape when the optional + `cryptography` dependency is available; without that dependency they fail + explicitly instead of pretending plaintext is secure. - Python CultNet shard catalog: Provides typed `CultNetShardCatalog` and `CultNetShardDescriptor` helpers for ingesting, filtering, and emitting shard topology responses, plus @@ -251,8 +261,9 @@ node --test packages\cultnet-ts\dist-test\test\interop\cultnet-interop.test.js workload. It has a measured local baseline plus a shared public `CultCache` upsert/get comparison harness with threshold status, not a universal performance victory certificate. -- Python does not own LiteNetLib security/session behavior; it speaks the - schema-v0 interop lane used by the package harness. +- Python does not implement the full LiteNetLib client/server auth flow. It now + owns the shared security/session primitives for helper parity, while the live + transport harness still speaks the schema-v0 interop lane. - Python does not implement the full C# daemon/server stack. Its current role is package runtime, raw interop peer, launchable local CultMesh endpoint, local CultMesh session facade, and typed state participant. diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index 58ee3c2d..b00fbc7c 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -149,7 +149,11 @@ member order. `cultnet_py` provides the Python schema-v0 wire helpers and an interop peer: ```python +from datetime import UTC, datetime + from cultnet_py import ( + CultNetSecret, + CultNetServerSecurityOptions, CultNetRawClient, CultNetSimulationObservation, CultNetWitnessArtifactBundle, @@ -205,8 +209,20 @@ witness = witness_artifact_bundle( ) typed_witness = CultNetWitnessArtifactBundle.from_wire(witness) witness_payload = typed_witness.to_payload() + +security = CultNetServerSecurityOptions.development() +token = CultNetSecret.create_session_token( + "318fb4b6-ff5e-4c4f-b911-d81807de53a8", + datetime(2035, 1, 1, tzinfo=UTC), + security, + session_version=1, +) +session = CultNetSecret.try_validate_session_token(token, security) ``` +AES-GCM string/byte encryption helpers are available through the same +`CultNetSecret` surface when the optional `crypto` extra is installed. + The peer can serve, dial, and probe the same raw-state interop lane used by the TypeScript, Rust, and C# test peers: diff --git a/packages/cultcache-py/pyproject.toml b/packages/cultcache-py/pyproject.toml index 66cf8c60..93ebf849 100644 --- a/packages/cultcache-py/pyproject.toml +++ b/packages/cultcache-py/pyproject.toml @@ -20,6 +20,7 @@ dependencies = ["msgpack>=1.0"] [project.optional-dependencies] msgpack = ["msgpack>=1.0"] +crypto = ["cryptography>=42"] [project.scripts] cultcache-py-interop = "cultcache_py.interop:main" diff --git a/packages/cultcache-py/src/cultcache_py/verify.py b/packages/cultcache-py/src/cultcache_py/verify.py index 0c7e1cd6..235db025 100644 --- a/packages/cultcache-py/src/cultcache_py/verify.py +++ b/packages/cultcache-py/src/cultcache_py/verify.py @@ -35,6 +35,9 @@ EXPECTED_EXPORTS: dict[str, tuple[str, ...]] = { "CultNetPeerError", "CultNetWitnessArtifactBundle", "CultNetRawClient", + "CultNetClientSecurityOptions", + "CultNetSecret", + "CultNetServerSecurityOptions", "CultNetRawDocumentRecord", "CultNetRawSnapshotResponse", "CultNetSchemaCatalog", @@ -63,6 +66,7 @@ EXPECTED_EXPORTS: dict[str, tuple[str, ...]] = { "CultNetSimulationObservation", "CultNetSimulationObservationHub", "INTEROP_WIRE_CONTRACT", + "ValidatedCultNetSessionToken", "apply_raw_document_record", "apply_raw_snapshot", "apply_shard_log_response", diff --git a/packages/cultcache-py/src/cultnet_py/__init__.py b/packages/cultcache-py/src/cultnet_py/__init__.py index 297a3e90..cdf6a573 100644 --- a/packages/cultcache-py/src/cultnet_py/__init__.py +++ b/packages/cultcache-py/src/cultnet_py/__init__.py @@ -35,6 +35,12 @@ from .schema_catalog import ( wire_message_schema_catalog, wire_message_schema_json, ) +from .security import ( + CultNetClientSecurityOptions, + CultNetSecret, + CultNetServerSecurityOptions, + ValidatedCultNetSessionToken, +) from .shard_catalog import CultNetShardCatalog, CultNetShardDescriptor from .shard_log import CultNetShardLogEntry, CultNetShardLogResponse from .shard_replication import ( @@ -70,6 +76,9 @@ __all__ = [ "CultNetDatabaseChange", "CultNetPeerError", "CultNetRawClient", + "CultNetClientSecurityOptions", + "CultNetSecret", + "CultNetServerSecurityOptions", "CultNetSchemaCatalog", "CultNetSchemaDescriptor", "CultNetShardCatalog", @@ -99,6 +108,7 @@ __all__ = [ "CultNetSimulationConsensusOptions", "CultNetSimulationObservation", "CultNetSimulationObservationHub", + "ValidatedCultNetSessionToken", "apply_raw_document_record", "apply_raw_snapshot", "apply_shard_log_response", diff --git a/packages/cultcache-py/src/cultnet_py/security.py b/packages/cultcache-py/src/cultnet_py/security.py new file mode 100644 index 00000000..074d900d --- /dev/null +++ b/packages/cultcache-py/src/cultnet_py/security.py @@ -0,0 +1,250 @@ +from __future__ import annotations + +import base64 +import hashlib +import hmac +import os +import time +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Mapping +from uuid import UUID + + +NONCE_LENGTH = 12 +TAG_LENGTH = 16 + + +@dataclass(frozen=True) +class CultNetClientSecurityOptions: + connection_key: str + + def __post_init__(self) -> None: + if not self.connection_key or not self.connection_key.strip(): + raise ValueError("Connection key must be provided.") + + @staticmethod + def development() -> "CultNetClientSecurityOptions": + return CultNetClientSecurityOptions("gamecult-dev-connection-key") + + def encryption_key(self) -> bytes: + return _sha256(self.connection_key.encode("utf-8")) + + +@dataclass(frozen=True) +class CultNetServerSecurityOptions(CultNetClientSecurityOptions): + CONNECTION_KEY_ENVIRONMENT_VARIABLE = "GAMECULT_CONNECTION_KEY" + SESSION_SIGNING_SECRET_ENVIRONMENT_VARIABLE = "GAMECULT_SESSION_SIGNING_SECRET" + + session_signing_secret: str + is_development: bool = False + + def __post_init__(self) -> None: + super().__post_init__() + if not self.session_signing_secret or not self.session_signing_secret.strip(): + raise ValueError("Session signing secret must be provided.") + + @staticmethod + def development() -> "CultNetServerSecurityOptions": + return CultNetServerSecurityOptions( + "gamecult-dev-connection-key", + "gamecult-dev-session-signing-secret", + True, + ) + + @staticmethod + def from_environment( + environment: Mapping[str, str | None] | None = None, + *, + allow_development_defaults: bool = False, + ) -> "CultNetServerSecurityOptions": + source = os.environ if environment is None else environment + connection_key = source.get(CultNetServerSecurityOptions.CONNECTION_KEY_ENVIRONMENT_VARIABLE) + session_signing_secret = source.get(CultNetServerSecurityOptions.SESSION_SIGNING_SECRET_ENVIRONMENT_VARIABLE) + missing_connection_key = not connection_key or not connection_key.strip() + missing_session_signing_secret = not session_signing_secret or not session_signing_secret.strip() + if missing_connection_key and missing_session_signing_secret: + if allow_development_defaults: + return CultNetServerSecurityOptions.development() + raise ValueError( + "Server security configuration is not configured. Set " + "GAMECULT_CONNECTION_KEY and GAMECULT_SESSION_SIGNING_SECRET, " + "or explicitly use CultNetServerSecurityOptions.development() for local development." + ) + if missing_connection_key or missing_session_signing_secret: + missing = [ + name + for name, is_missing in ( + (CultNetServerSecurityOptions.CONNECTION_KEY_ENVIRONMENT_VARIABLE, missing_connection_key), + (CultNetServerSecurityOptions.SESSION_SIGNING_SECRET_ENVIRONMENT_VARIABLE, missing_session_signing_secret), + ) + if is_missing + ] + raise ValueError(f"Server security configuration is partially configured. Missing: {', '.join(missing)}.") + return CultNetServerSecurityOptions(str(connection_key), str(session_signing_secret)) + + def session_signing_key(self) -> bytes: + return _sha256(self.session_signing_secret.encode("utf-8")) + + def to_client_options(self) -> CultNetClientSecurityOptions: + return CultNetClientSecurityOptions(self.connection_key) + + +@dataclass(frozen=True) +class ValidatedCultNetSessionToken: + user_id: UUID + expires_at_utc: datetime + session_version: int = 0 + + +class CultNetSecret: + @staticmethod + def new_nonce() -> bytes: + return os.urandom(NONCE_LENGTH) + + @staticmethod + def encrypt_string( + value: str | None, + nonce: bytes, + options: CultNetClientSecurityOptions | CultNetServerSecurityOptions, + ) -> bytes | None: + if not value: + return None + return CultNetSecret.encrypt_bytes(value.encode("utf-8"), nonce, options) + + @staticmethod + def decrypt_string( + encrypted: bytes | None, + nonce: bytes | None, + options: CultNetClientSecurityOptions | CultNetServerSecurityOptions, + ) -> str | None: + if encrypted is None or nonce is None: + return None + return CultNetSecret.decrypt_bytes(encrypted, nonce, options).decode("utf-8") + + @staticmethod + def encrypt_bytes( + value: bytes, + nonce: bytes, + options: CultNetClientSecurityOptions | CultNetServerSecurityOptions, + ) -> bytes: + aesgcm = _create_aesgcm(options.encryption_key()) + ciphertext_and_tag = aesgcm.encrypt(_validate_nonce(nonce), value, None) + ciphertext = ciphertext_and_tag[:-TAG_LENGTH] + tag = ciphertext_and_tag[-TAG_LENGTH:] + return tag + ciphertext + + @staticmethod + def decrypt_bytes( + encrypted: bytes, + nonce: bytes, + options: CultNetClientSecurityOptions | CultNetServerSecurityOptions, + ) -> bytes: + if len(encrypted) < TAG_LENGTH: + raise ValueError("Invalid encrypted data.") + aesgcm = _create_aesgcm(options.encryption_key()) + tag = encrypted[:TAG_LENGTH] + ciphertext = encrypted[TAG_LENGTH:] + return aesgcm.decrypt(_validate_nonce(nonce), ciphertext + tag, None) + + @staticmethod + def create_session_token( + user_id: str | UUID, + expires_at_utc: datetime | int | float, + options: CultNetServerSecurityOptions, + *, + session_version: int = 0, + ) -> str: + parsed_user_id = _parse_user_id(user_id) + expires_at_seconds = _expires_at_seconds(expires_at_utc) + payload = f"{parsed_user_id.hex}|{expires_at_seconds}|{int(session_version)}".encode("utf-8") + signature = hmac.new(options.session_signing_key(), payload, hashlib.sha256).digest() + return f"{CultNetSecret.to_base64url(payload)}.{CultNetSecret.to_base64url(signature)}" + + @staticmethod + def try_validate_session_token( + token: str | None, + options: CultNetServerSecurityOptions, + *, + now_utc: datetime | int | float | None = None, + ) -> ValidatedCultNetSessionToken | None: + if not token or not token.strip(): + return None + parts = token.split(".") + if len(parts) != 2: + return None + try: + payload = CultNetSecret.from_base64url(parts[0]) + signature = CultNetSecret.from_base64url(parts[1]) + except ValueError: + return None + expected = hmac.new(options.session_signing_key(), payload, hashlib.sha256).digest() + if not hmac.compare_digest(signature, expected): + return None + try: + decoded = payload.decode("utf-8") + payload_parts = decoded.split("|") + if len(payload_parts) not in (2, 3): + return None + user_id = UUID(payload_parts[0]) + expires_at_seconds = int(payload_parts[1]) + session_version = int(payload_parts[2]) if len(payload_parts) == 3 else 0 + except (ValueError, UnicodeDecodeError): + return None + if expires_at_seconds <= _now_seconds(now_utc): + return None + return ValidatedCultNetSessionToken( + user_id=user_id, + expires_at_utc=datetime.fromtimestamp(expires_at_seconds, UTC), + session_version=session_version, + ) + + @staticmethod + def to_base64url(value: bytes) -> str: + return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=") + + @staticmethod + def from_base64url(value: str) -> bytes: + try: + return base64.urlsafe_b64decode(value + "=" * ((4 - len(value) % 4) % 4)) + except Exception as exc: + raise ValueError("Invalid base64url data.") from exc + + +def _sha256(value: bytes) -> bytes: + return hashlib.sha256(value).digest() + + +def _validate_nonce(nonce: bytes) -> bytes: + if len(nonce) != NONCE_LENGTH: + raise ValueError("Invalid nonce.") + return nonce + + +def _parse_user_id(user_id: str | UUID) -> UUID: + return user_id if isinstance(user_id, UUID) else UUID(str(user_id)) + + +def _expires_at_seconds(expires_at_utc: datetime | int | float) -> int: + if isinstance(expires_at_utc, datetime): + value = expires_at_utc + if value.tzinfo is None: + value = value.replace(tzinfo=UTC) + return int(value.timestamp()) + return int(expires_at_utc) + + +def _now_seconds(now_utc: datetime | int | float | None) -> int: + if now_utc is None: + return int(time.time()) + return _expires_at_seconds(now_utc) + + +def _create_aesgcm(key: bytes) -> object: + try: + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + except ModuleNotFoundError as exc: + raise ImportError( + "AES-GCM encryption helpers require the optional 'cryptography' dependency." + ) from exc + return AESGCM(key) diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index 91928f88..202cc19e 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -9,6 +9,8 @@ import tempfile import threading import time import unittest +import hashlib +import hmac from dataclasses import asdict, dataclass from datetime import UTC, datetime, timedelta from pathlib import Path @@ -53,6 +55,9 @@ from cultnet_py import ( CultNetSchemaShardLogFetcher, CultNetSchemaShardSnapshotFetcher, CultNetPeerError, + CultNetClientSecurityOptions, + CultNetSecret, + CultNetServerSecurityOptions, CultNetShardReplicator, CultNetShardReplicatorOptions, CultNetShardMutationLogStore, @@ -413,6 +418,95 @@ class CultCacheTests(unittest.TestCase): self.assertEqual(by_name["public_exports"]["missing"], {}) self.assertEqual(by_name["cultmesh_capability_truth"]["failures"], []) + def test_cultnet_security_options_match_cultlib_defaults_and_environment_rules(self) -> None: + client = CultNetClientSecurityOptions.development() + server = CultNetServerSecurityOptions.development() + + self.assertEqual(client.connection_key, "gamecult-dev-connection-key") + self.assertEqual(server.connection_key, "gamecult-dev-connection-key") + self.assertTrue(server.is_development) + self.assertEqual(server.to_client_options().connection_key, client.connection_key) + self.assertEqual(client.encryption_key(), hashlib.sha256(b"gamecult-dev-connection-key").digest()) + self.assertEqual(server.session_signing_key(), hashlib.sha256(b"gamecult-dev-session-signing-secret").digest()) + self.assertEqual( + CultNetServerSecurityOptions.from_environment({}, allow_development_defaults=True), + server, + ) + with self.assertRaisesRegex(ValueError, "not configured"): + CultNetServerSecurityOptions.from_environment({}) + with self.assertRaisesRegex(ValueError, "GAMECULT_SESSION_SIGNING_SECRET"): + CultNetServerSecurityOptions.from_environment({"GAMECULT_CONNECTION_KEY": "key"}) + configured = CultNetServerSecurityOptions.from_environment({ + "GAMECULT_CONNECTION_KEY": "prod-key", + "GAMECULT_SESSION_SIGNING_SECRET": "prod-secret", + }) + self.assertEqual(configured.connection_key, "prod-key") + self.assertFalse(configured.is_development) + + def test_cultnet_secret_helpers_validate_csharp_versioned_session_tokens(self) -> None: + security = CultNetServerSecurityOptions("connection-key", "session-secret") + user_id = uuid4() + expires = datetime(2035, 1, 2, 3, 4, 5, tzinfo=UTC) + + token = CultNetSecret.create_session_token(user_id, expires, security, session_version=7) + payload_b64, signature_b64 = token.split(".") + self.assertEqual( + CultNetSecret.from_base64url(payload_b64).decode("utf-8"), + f"{user_id.hex}|{int(expires.timestamp())}|7", + ) + self.assertEqual( + CultNetSecret.from_base64url(signature_b64), + hmac.new( + hashlib.sha256(b"session-secret").digest(), + CultNetSecret.from_base64url(payload_b64), + hashlib.sha256, + ).digest(), + ) + + validated = CultNetSecret.try_validate_session_token( + token, + security, + now_utc=datetime(2035, 1, 2, 3, 4, 4, tzinfo=UTC), + ) + self.assertIsNotNone(validated) + assert validated is not None + self.assertEqual(validated.user_id, user_id) + self.assertEqual(validated.expires_at_utc, expires) + self.assertEqual(validated.session_version, 7) + + tampered = token[:-1] + ("A" if token[-1] != "A" else "B") + self.assertIsNone(CultNetSecret.try_validate_session_token(tampered, security)) + self.assertIsNone(CultNetSecret.try_validate_session_token(token, security, now_utc=expires)) + + def test_cultnet_secret_helpers_validate_legacy_two_field_session_tokens(self) -> None: + security = CultNetServerSecurityOptions.development() + user_id = uuid4() + expires_at_seconds = int(datetime(2036, 1, 1, tzinfo=UTC).timestamp()) + payload = f"{user_id.hex}|{expires_at_seconds}".encode("utf-8") + signature = hmac.new(security.session_signing_key(), payload, hashlib.sha256).digest() + token = f"{CultNetSecret.to_base64url(payload)}.{CultNetSecret.to_base64url(signature)}" + + validated = CultNetSecret.try_validate_session_token( + token, + security, + now_utc=datetime(2035, 12, 31, tzinfo=UTC), + ) + + self.assertIsNotNone(validated) + assert validated is not None + self.assertEqual(validated.user_id, user_id) + self.assertEqual(validated.session_version, 0) + + def test_cultnet_secret_encryption_helpers_are_optional_without_crypto_dependency(self) -> None: + nonce = b"123456789012" + security = CultNetServerSecurityOptions.development() + try: + encrypted = CultNetSecret.encrypt_string("hello", nonce, security.to_client_options()) + except ImportError as exc: + self.assertIn("cryptography", str(exc)) + return + self.assertEqual(CultNetSecret.decrypt_string(encrypted, nonce, security), "hello") + def test_cultnet_schema_message_frame_round_trip(self) -> None: message = hello(runtime_id="python-test", supported_schema_versions=["cultnet.hello.v0"]) parsed = parse_message(decode_frame(encode_frame(message.to_bytes())))