158 lines
7.3 KiB
Python
158 lines
7.3 KiB
Python
# #region Test.SecurityOpsOffline [C:4] [TYPE Module] [SEMANTICS test,security,ops,key,rotation,redaction,pii,retention,evidence]
|
|
# @defgroup Tests for G-SECURITY-OPS offline: key rotation/expiry, evidence PII redaction, retention policy.
|
|
# @LAYER Test
|
|
# @RELATION BINDS_TO -> [Core.EncryptionKey.KeyAge]
|
|
# @RELATION BINDS_TO -> [Core.EncryptionKey.EncryptionKeyModule]
|
|
# @RELATION VERIFIES -> [ScenarioExecution.EvaluationAdapter.Raw]
|
|
# @RELATION VERIFIES -> [Plugin.Service.RedactionService]
|
|
# @TEST_INVARIANT Core.EncryptionKey.KeyAge: Fail-closed verdict — unknown age is a warning with
|
|
# reason age_unknown, never ok. -> VERIFIED_BY: test_key_age_unknown_is_warning
|
|
# @TEST_INVARIANT Rotation contract: a ciphertext under the old key is unreadable by the new key and
|
|
# readable again after re-encryption with the new key. -> VERIFIED_BY:
|
|
# test_rotation_reencrypt_roundtrip
|
|
# @TEST_INVARIANT ScenarioExecution.EvaluationAdapter.Raw: stored evidence bytes never carry
|
|
# credential/PII patterns; findings stay untouched. -> VERIFIED_BY:
|
|
# test_persist_raw_response_redacts_credentials_and_pii
|
|
# @TEST_INVARIANT Retention policy: the evidence retention window is declared in config and visible
|
|
# to a falsifiable check. -> VERIFIED_BY: test_retention_policy_declared_in_config
|
|
# @TEST_EDGE dry_run -> rotation reports the plan without writing
|
|
# @RATIONALE Hardcoded fixture keys and payloads keep the vectors independent of any live
|
|
# environment; the rotation vector proves the Fernet key-change failure mode that
|
|
# encryption health inventories (see encryption_health routes) diagnose.
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from cryptography.fernet import Fernet
|
|
|
|
|
|
# #region Test.SecurityOpsOffline.KeyAge [C:3] [TYPE Function] [SEMANTICS test,key,age,fail-closed]
|
|
# @BRIEF Unknown key age is a warning (fail-closed); a fresh env file is ok; an old one warns.
|
|
def test_key_age_unknown_is_warning(tmp_path: Path) -> None:
|
|
from src.core.encryption_key import encryption_key_age_verdict
|
|
|
|
missing = encryption_key_age_verdict(tmp_path / "no-such.env", max_age_days=90)
|
|
assert missing["status"] == "warning"
|
|
assert missing["reason"] == "age_unknown"
|
|
|
|
fresh_env = tmp_path / "fresh.env"
|
|
fresh_env.write_text("ENCRYPTION_KEY=" + Fernet.generate_key().decode() + "\n", encoding="utf-8")
|
|
fresh = encryption_key_age_verdict(fresh_env, max_age_days=90)
|
|
assert fresh["status"] == "ok"
|
|
|
|
old_env = tmp_path / "old.env"
|
|
old_env.write_text("ENCRYPTION_KEY=" + Fernet.generate_key().decode() + "\n", encoding="utf-8")
|
|
stamp = old_env.stat().st_mtime - 91 * 86400
|
|
os.utime(old_env, (stamp, stamp))
|
|
old = encryption_key_age_verdict(old_env, max_age_days=90)
|
|
assert old["status"] == "warning"
|
|
assert old["reason"] == "age_exceeded"
|
|
assert old["age_days"] >= 90
|
|
# #endregion Test.SecurityOpsOffline.KeyAge
|
|
|
|
|
|
# #region Test.SecurityOpsOffline.Rotation [C:3] [TYPE Function] [SEMANTICS test,key,rotation,reencrypt,fernet]
|
|
# @BRIEF Rotation contract: old-key ciphertext is unreadable under the new key, readable after reencrypt.
|
|
def test_rotation_reencrypt_roundtrip() -> None:
|
|
from src.scripts.reencrypt import _make_fernet, _reencrypt_value
|
|
|
|
old_key = Fernet.generate_key().decode()
|
|
new_key = Fernet.generate_key().decode()
|
|
old_fernet = _make_fernet(old_key)
|
|
new_fernet = _make_fernet(new_key)
|
|
|
|
secret = "sk-provider-key-0123456789abcdef"
|
|
ciphertext = old_fernet.encrypt(secret.encode()).decode()
|
|
|
|
# The new key cannot read the old-key ciphertext — the failure mode rotation diagnoses.
|
|
try:
|
|
new_fernet.decrypt(ciphertext.encode())
|
|
unreadable = False
|
|
except Exception:
|
|
unreadable = True
|
|
assert unreadable is True
|
|
|
|
# After re-encryption the new key reads the value; the old key no longer can.
|
|
reencrypted = _reencrypt_value(ciphertext, old_fernet, new_fernet)
|
|
assert reencrypted is not None
|
|
assert new_fernet.decrypt(reencrypted.encode()).decode() == secret
|
|
try:
|
|
old_fernet.decrypt(reencrypted.encode())
|
|
old_still_reads = True
|
|
except Exception:
|
|
old_still_reads = False
|
|
assert old_still_reads is False
|
|
|
|
# Non-fernet legacy values are reported, not silently converted.
|
|
assert _reencrypt_value("plaintext-legacy", old_fernet, new_fernet) is None
|
|
# #endregion Test.SecurityOpsOffline.Rotation
|
|
|
|
|
|
# #region Test.SecurityOpsOffline.Redaction [C:4] [TYPE Function] [SEMANTICS test,evidence,redaction,pii,credentials]
|
|
# @BRIEF Stored evidence bytes carry no credential/PII patterns; the digest/ref contract holds.
|
|
def test_persist_raw_response_redacts_credentials_and_pii(tmp_path: Path) -> None:
|
|
from src.services.dashboard_testing.execution.evaluation_adapter import _persist_raw_response
|
|
|
|
class _Storage:
|
|
def __init__(self) -> None:
|
|
self.stored: dict[str, bytes] = {}
|
|
|
|
def store(self, run_id: str, digest: str, payload: bytes) -> str:
|
|
self.stored[digest] = payload
|
|
return f"draft:{run_id}:{digest}"
|
|
|
|
storage = _Storage()
|
|
raw = {
|
|
"model": "vlm-1",
|
|
"message": "checked",
|
|
"notes": "password=hunter2 api_key=sk-1234567890abcdefgh token=abcdef1234567890", # gitleaks:allow
|
|
"contact": "analyst@corp.example",
|
|
"findings": [{"criterion_id": "c1", "status": "pass"}],
|
|
}
|
|
|
|
raw_bytes, digest, content_ref = _persist_raw_response(storage, "run-redact-044", raw)
|
|
|
|
stored_text = storage.stored[digest].decode()
|
|
assert "hunter2" not in stored_text
|
|
assert "sk-1234567890abcdefgh" not in stored_text
|
|
assert "abcdef1234567890" not in stored_text
|
|
assert "analyst@corp.example" not in stored_text
|
|
assert "password=***" in stored_text
|
|
assert "api_key=***" in stored_text
|
|
assert content_ref == f"draft:run-redact-044:{digest}"
|
|
assert storage.stored[digest] == raw_bytes
|
|
parsed = json.loads(stored_text)
|
|
assert parsed["findings"] == raw["findings"]
|
|
assert parsed["model"] == "vlm-1"
|
|
# #endregion Test.SecurityOpsOffline.Redaction
|
|
|
|
|
|
# #region Test.SecurityOpsOffline.Retention [C:2] [TYPE Function] [SEMANTICS test,retention,policy,config-check]
|
|
# @BRIEF The evidence retention window is declared in config defaults and a falsifiable check sees it.
|
|
def test_retention_policy_declared_in_config() -> None:
|
|
from src.core.config_models import GlobalSettings
|
|
|
|
fields = GlobalSettings.model_fields
|
|
assert "scenario_evidence_retention_days" in fields
|
|
assert "scenario_evidence_archive_target" in fields
|
|
|
|
defaults = GlobalSettings()
|
|
window = int(defaults.scenario_evidence_retention_days)
|
|
target = str(defaults.scenario_evidence_archive_target)
|
|
assert 1 <= window <= 3650, "retention window must be a sane positive day count"
|
|
assert target.strip() != "", "archive target must be declared and non-empty"
|
|
|
|
# The falsifiable config-check ops can run: window declared -> check passes; undeclared -> fails.
|
|
def retention_check(days: int | None, archive: str | None) -> bool:
|
|
return days is not None and int(days) > 0 and bool(str(archive or "").strip())
|
|
|
|
assert retention_check(window, target) is True
|
|
assert retention_check(None, target) is False
|
|
assert retention_check(window, " ") is False
|
|
# #endregion Test.SecurityOpsOffline.Retention
|
|
|
|
|
|
# #endregion Test.SecurityOpsOffline
|