Audit and observability

A Protector emits a cs-audit/1 event when each operation starts and another when it succeeds or fails. Events say what happened, never what was protected: they hold the operation, outcome, error code, policy, and provider, and they show key and envelope identifiers only as hashes. No field can hold plaintext, context values, key material, or paths.

Receive events

Any object with an emit(event) method is an audit sink:

from cryptography_suite import EncryptionContext, Policy, Protector
from cryptography_suite.audit import AuditEvent
from cryptography_suite.providers.hpke import HpkeRecipientProvider, generate_private_key


class PrintingSink:
    def emit(self, event: AuditEvent) -> None:
        print(event.event_type, event.outcome, event.error_code)


provider = HpkeRecipientProvider()
key = provider.add_identity("payments", generate_private_key())
protector = Protector(
    provider=provider, policy=Policy(), primary_key=key, audit_sink=PrintingSink()
)
context = EncryptionContext({"tenant": "acme"})
envelope = protector.seal(b"payroll", context=context)
# seal.started started None
# seal.succeeded succeeded None

emit runs synchronously in the operation. When the policy sets audit_required, as Policy.enterprise() does, an operation without an audit sink cannot be constructed, and an exception from emit fails the operation with IO_FAILED. Otherwise sink failures are ignored. A streaming operation records its success event before it publishes its output, so output never exists for an operation reported as failed for want of an audit record.

A tamper-evident audit trail

AuditChain writes each event as a signed, hash-chained JSON line. Anyone with the public key can verify the trail and detect any record that was edited, inserted, deleted, reordered, or re-signed, and cannot forge one.

import os
from pathlib import Path

from cryptography.hazmat.primitives.asymmetric import ed25519

from cryptography_suite.audit.chain import AuditChain, verify_audit_chain


class AppendOnlyFile:
    """One record per line, on disk before the call returns."""

    def __init__(self, path: Path) -> None:
        self._path = path

    def write_record(self, line: str) -> None:
        with open(self._path, "a", encoding="utf-8", newline="\n") as handle:
            handle.write(line + "\n")
            handle.flush()
            os.fsync(handle.fileno())


signing_key = ed25519.Ed25519PrivateKey.generate()
audit_chain = AuditChain(
    AppendOnlyFile(Path("audit.jsonl")), signing_key, chain_id="prod.payments"
)
audited = Protector(
    provider=provider,
    policy=Policy.enterprise(approved_providers=[provider.provider_id]),
    primary_key=key,
    audit_sink=audit_chain,
)
audited.open(audited.seal(b"payroll", context=context), context=context)

checkpoint = audit_chain.checkpoint()
lines = Path("audit.jsonl").read_text(encoding="utf-8").splitlines()
end = verify_audit_chain(
    lines, signing_key.public_key(), chain_id="prod.payments", expected_end=checkpoint
)
assert end == checkpoint

Verification failures raise AuditChainError with a reason and the line number:

from cryptography_suite.audit.chain import AuditChainError

try:
    verify_audit_chain(
        lines[:1] + lines[2:],  # one record deleted
        signing_key.public_key(),
        chain_id="prod.payments",
        expected_end=checkpoint,
    )
except AuditChainError as error:
    print(error.reason, error.line)  # sequence_gap 2

Deleting records from the end of a trail leaves a valid shorter trail. Publish audit_chain.checkpoint() periodically somewhere the writer cannot change, such as a WORM bucket, a ticketing system, or a transparency log, and verify against it with expected_end.

After a restart, continue the same trail with the last verified checkpoint:

resumed = AuditChain(
    AppendOnlyFile(Path("audit.jsonl")),
    signing_key,
    chain_id="prod.payments",
    resume_from=end,
)

The signing key belongs to the audit component, not to the data path: a service that can open envelopes should not be able to rewrite their history.

Post-quantum signatures

HybridSigningKey signs every record with Ed25519 and ML-DSA-65 (FIPS 204) together. The trail verifies only if both signatures do, so it stays unforgeable while either scheme holds.

from cryptography_suite.audit.chain import HybridSigningKey

hybrid_key = HybridSigningKey.generate()
hybrid_chain = AuditChain(
    AppendOnlyFile(Path("audit-pq.jsonl")), hybrid_key, chain_id="prod.payments-pq"
)

Verify a hybrid trail with hybrid_key.public_key(). The verifying key’s type fixes the record schema it accepts, so a hybrid trail cannot be passed off as an Ed25519-only one.

Metrics and traces

cryptography-suite-opentelemetry turns the same events into OpenTelemetry metrics and span events. FanOutAuditSink sends every event to several sinks; it tries all of them even when one fails, so a metrics outage never costs an audit record.

from opentelemetry import metrics, trace

from cryptography_suite.audit.fanout import FanOutAuditSink
from cryptography_suite_opentelemetry import OpenTelemetryAuditSink

telemetry = OpenTelemetryAuditSink(
    metrics.get_meter("payments"),
    span_source=trace.get_current_span,  # optional span events
)
protector = Protector(
    provider=provider,
    policy=Policy.enterprise(approved_providers=[provider.provider_id]),
    primary_key=key,
    audit_sink=FanOutAuditSink(audit_chain, telemetry),
)

Signal

Kind

Attributes

cryptosuite.operations

Counter of completed operations

cryptosuite.operation, cryptosuite.outcome, cryptosuite.provider_id, error.type

cryptosuite.operation.duration

Histogram, seconds

the same

cryptosuite.<operation>.<outcome>

Span event on the current span

the same, plus cryptosuite.operation_id and cryptosuite.policy_id

Metric attributes are low-cardinality: they never include operation, key, or envelope identifiers. Useful alerts:

  • a rise in error.type="AUTHENTICATION_FAILED": tampering, corruption, or a key mix-up;

  • PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, or PROVIDER_RATE_LIMITED: the key service, or quota;

  • KEY_NOT_FOUND on open: envelopes under a key this service does not trust.