import io import json import ssl import sys import time import pytest from src import identity from src.errors import DomainError def test_expired_or_missing_scoped_snapshot_fails_closed( tmp_path, monkeypatch ): monkeypatch.setattr(identity, "IDENTITY", tmp_path) monkeypatch.setenv("IDENTITY_ENABLED", "1") with pytest.raises(DomainError) as denied: identity.ensure() assert denied.value.status == 503 snapshot = tmp_path / "secrets.json" snapshot.write_text( json.dumps( { "valid_until": time.time() + 30, "values": {"DATABASE_URL": "synthetic"}, } ) ) assert identity.secret("DATABASE_URL") == "synthetic" with pytest.raises(DomainError): identity.secret("FOREIGN_ADMIN_SECRET") snapshot.write_text( json.dumps( { "valid_until": time.time() - 1, "values": {"DATABASE_URL": "synthetic"}, } ) ) with pytest.raises(DomainError): identity.secret("DATABASE_URL") def test_bootstrap_repairs_config_without_changing_credentials( tmp_path, monkeypatch ): from scripts import bootstrap_security as bootstrap monkeypatch.setattr(bootstrap, "OPERATOR", tmp_path / "operator") monkeypatch.setattr(bootstrap, "SECRET", tmp_path / "secrets") monkeypatch.setattr(bootstrap, "TRUST", tmp_path / "trust") bootstrap.generate() private = bootstrap.OPERATOR / "service-secrets.json" original = private.read_bytes() config = bootstrap.SECRET / "broker.conf" expected = config.read_bytes() config.unlink() bootstrap.generate() assert private.read_bytes() == original assert config.read_bytes() == expected assert bootstrap.OPERATOR.stat().st_mode & 0o777 == 0o700 assert private.stat().st_mode & 0o777 == 0o600 def test_operator_leaf_install_preserves_pem_and_matching_pair( tmp_path, monkeypatch ): from cryptography import x509 from scripts.bootstrap_security import ( key_bytes, make_root, public, sign_leaf, ) from scripts.credentials import INSTALL root_key, root_cert = make_root() key, leaf = sign_leaf(root_key, root_cert, "worker", ["worker"]) payload = { "certificate": public(leaf).decode(), "private_key": key_bytes(key).decode(), "ca_chain": [public(root_cert).decode()], } monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(payload))) code = INSTALL.replace( "pathlib.Path('/run/identity')", "pathlib.Path(" + repr(str(tmp_path)) + ")", ) exec(compile(code, "operator-install-test", "exec"), {}) current = tmp_path / "current" assert current.is_symlink() assert ( len( x509.load_pem_x509_certificates( (current / "cert.pem").read_bytes() ) ) == 2 ) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(current / "cert.pem", current / "key.pem") assert (current / "key.pem").stat().st_mode & 0o777 == 0o600