Skip to content

audit_trail.visibility

What a caller may see of the audit log: Visibility and its rules.

A Visibility holds row rules and field rules. The row rules (allowlists, exclusions and per-type verb rules) become one SQL condition on audit_activity, so paging and counts only ever see the rows the caller may see. The field rules name values to hide in the rows that are shown: they are masked in Python after the rows are read and compacted, and never written back.

narrow combines two of them into one that shows only what both show. UNRESTRICTED is the Visibility that restricts nothing, and Visibility.NOTHING the one that shows nothing.

A default for every read is set with AuditTrail(visibility=resolver): a VisibilityResolver that maps the caller's AuditContext to a Visibility. by_actor_type builds one from a mapping of actor types.

UNRESTRICTED module-attribute

UNRESTRICTED: Final[Visibility] = Visibility()

The Visibility that restricts nothing.

narrow returns the other side unchanged when one side is UNRESTRICTED. Compare with is: an equal Visibility() is not it.

VisibilityResolver module-attribute

VisibilityResolver: TypeAlias = Callable[
    [AuditContext], Visibility
]

Maps the caller's AuditContext to what the caller may see.

Set as AuditTrail(visibility=...) or LabelResolver(visibility=...), it gives the default Visibility of every read. It must return a Visibility; an exception it raises fails the read.

TypeRule dataclass

TypeRule(
    verbs: Collection[str] | None = None,
    exclude_verbs: Collection[str] = (),
    hidden_fields: Collection[str] = (),
)

Rules for the entries of one object type, on top of the global ones.

A rule only hides more: an entry of the type must pass both the global rules and this one.

Attributes:

Name Type Description
verbs Collection[str] | None

Allowed verbs for the type. None means no restriction; an empty collection hides every entry of the type. A verb not listed is hidden, so a verb added later stays hidden until it is allowed.

exclude_verbs Collection[str]

Verbs hidden for the type.

hidden_fields Collection[str]

Attribute keys of the type's data.changes, data.payload and data.state whose values are hidden.

Raises:

Type Description
TypeError

A field is a str instead of a collection of them.

Visibility dataclass

Visibility(
    object_types: Collection[str] | None = None,
    verbs: Collection[str] | None = None,
    scope_ids: Collection[str] | None = None,
    exclude_object_types: Collection[str] = (),
    exclude_verbs: Collection[str] = (),
    hidden_fields: Collection[str] = (),
    hidden_header_fields: Collection[str] = (),
    types: Mapping[str, TypeRule] = dict(),
    mark_hidden: bool = False,
)

What the caller may see; applied to every row the query returns.

The library knows nothing about the host's permissions: the host builds a Visibility from its own rules. It restricts both which transactions are listed and which of their entries a group shows.

object_types, verbs and scope_ids are sets of allowed values. None means no restriction; an empty collection allows nothing. A row whose column is NULL never passes a restriction that is set, so access control fails closed: with scope_ids={"t1"}, entries without a scope are hidden.

The exclusions hide the rows whose column is one of their values. They never hide a row whose column is NULL.

types adds rules for single object types (see TypeRule). A type without a rule gets only the global rules.

The field rules mask values in what a read returns, after compaction, so compaction still works on the real values:

  • A hidden field (hidden_fields, or the hidden_fields of the entry's type rule) keeps its key in data.changes, data.payload and data.state, and each of its non-null values becomes MASKED ("[hidden]"): both sides of [old, new], every id of a relationship change, and a state value whole. None stays None; a redacted, erased or hashed value is masked like any other. An update whose fields are all hidden is still shown.
  • A hidden header field is None on TransactionHeader and listed in its masked, and is left out of each entry's data.context. actor_id and scope_id also become MASKED in each entry's column of that name (when not None), and correlation_id becomes None in it. meta hides all of meta, meta.<key> one key of it. With actor_id hidden, access_summary returns a single count over all actors.

Attributes:

Name Type Description
object_types Collection[str] | None

Allowed object_type values.

verbs Collection[str] | None

Allowed verb values.

scope_ids Collection[str] | None

Allowed scope_id values.

exclude_object_types Collection[str]

Hidden object_type values.

exclude_verbs Collection[str]

Hidden verb values, for every type.

hidden_fields Collection[str]

Attribute keys of data.changes, data.payload and data.state whose values are hidden, for every type.

hidden_header_fields Collection[str]

Header fields whose values are hidden: names of TransactionHeader fields (actor_id, remote_addr, meta, ...; not id, issued_at or from_snapshot), or meta.<key> for one key of meta.

types Mapping[str, TypeRule]

Rules per object type.

mark_hidden bool

Whether a group says that some of its entries are hidden: sets Group.partial on the groups of list_groups, object_history and related whose transaction has entries that the row rules hide, at the cost of one more query per page, and Operation.partial on the operations of list_operations with such entries.

Raises:

Type Description
TypeError

A collection field is a str instead of a collection of them, types is not a mapping, or one of its values is not a TypeRule.

ValueError

hidden_header_fields names an unknown header field.

NOTHING class-attribute

NOTHING: Visibility

A Visibility that allows no entry.

predicate

predicate(table: Table) -> ColumnElement[bool]

Return the SQL condition on audit_activity rows.

Parameters:

Name Type Description Default
table Table

The audit_activity table.

required

Returns:

Type Description
ColumnElement[bool]

The condition; true() when nothing is restricted.

Source code in audit_trail/visibility.py
def predicate(self, table: Table) -> ColumnElement[bool]:
    """Return the SQL condition on ``audit_activity`` rows.

    Args:
        table: The ``audit_activity`` table.

    Returns:
        The condition; ``true()`` when nothing is restricted.
    """
    object_type, verb = table.c.object_type, table.c.verb
    conditions = [
        _member_of(object_type, self.object_types),
        _member_of(verb, self.verbs),
        _member_of(table.c.scope_id, self.scope_ids),
        _not_in(object_type, self.exclude_object_types),
        _not_in(verb, self.exclude_verbs),
    ]
    for name, rule in sorted(self.types.items()):
        allowed = [
            condition
            for condition in (
                _member_of(verb, rule.verbs),
                _not_in(verb, rule.exclude_verbs),
            )
            if condition is not None
        ]
        if allowed:
            conditions.append(
                or_(object_type.is_distinct_from(name), and_(*allowed))
            )
    present = [condition for condition in conditions if condition is not None]
    return and_(*present) if present else true()

narrow

narrow(other: Visibility) -> Visibility

Return a Visibility that shows only what both show.

Allowlists intersect, globally and per type; exclusions and hidden fields add up; mark_hidden is set when either sets it. A type with a rule on one side only keeps that rule. UNRESTRICTED on either side returns the other side unchanged. A result that allows no entry (an empty object_types, verbs or scope_ids) is Visibility.NOTHING itself, which shows the same: nothing.

Parameters:

Name Type Description Default
other Visibility

The other Visibility.

required

Returns:

Type Description
Visibility

The combined Visibility.

Source code in audit_trail/visibility.py
def narrow(self, other: Visibility) -> Visibility:
    """Return a ``Visibility`` that shows only what both show.

    Allowlists intersect, globally and per type; exclusions and hidden
    fields add up; ``mark_hidden`` is set when either sets it. A type
    with a rule on one side only keeps that rule. ``UNRESTRICTED`` on
    either side returns the other side unchanged. A result that allows
    no entry (an empty ``object_types``, ``verbs`` or ``scope_ids``) is
    ``Visibility.NOTHING`` itself, which shows the same: nothing.

    Args:
        other: The other ``Visibility``.

    Returns:
        The combined ``Visibility``.
    """
    if other is UNRESTRICTED:
        return _or_nothing(self)
    if self is UNRESTRICTED:
        return _or_nothing(other)
    types = dict(self.types)
    for name, rule in other.types.items():
        mine = types.get(name)
        types[name] = rule if mine is None else _narrow_rule(mine, rule)
    return _or_nothing(
        Visibility(
            object_types=_intersect(self.object_types, other.object_types),
            verbs=_intersect(self.verbs, other.verbs),
            scope_ids=_intersect(self.scope_ids, other.scope_ids),
            exclude_object_types=_union(
                self.exclude_object_types, other.exclude_object_types
            ),
            exclude_verbs=_union(self.exclude_verbs, other.exclude_verbs),
            hidden_fields=_union(self.hidden_fields, other.hidden_fields),
            hidden_header_fields=_union(
                self.hidden_header_fields, other.hidden_header_fields
            ),
            types=types,
            mark_hidden=self.mark_hidden or other.mark_hidden,
        )
    )

by_actor_type

by_actor_type(
    mapping: Mapping[str, Visibility],
    *,
    default: Visibility = Visibility.NOTHING,
    same_scope: bool = False,
    unscoped: Collection[str] = (),
    models: _Models | None = None,
) -> VisibilityResolver

Build a resolver that picks a Visibility by the caller's actor type.

The resolver looks ctx.actor_type up in mapping. An actor type that is not in it gets default, which shows nothing unless given, and a warning is logged the first time each such type is seen (for the first 1024 such types; later ones get no warning).

Example::

audit = AuditTrail(
    engine,
    visibility=by_actor_type(
        {
            "admin": UNRESTRICTED,
            "user": Visibility(object_types={"Invoice"}),
        },
        same_scope=True,
        unscoped={"admin"},
    ),
)

With models, the rules in each audited model's AuditOptions(visibility=...) are added too::

class Invoice(Base, Audited):
    ...
    __audit__ = AuditOptions(
        visibility={"user": TypeRule(hidden_fields={"iban"})},
    )

resolver = by_actor_type({"user": Visibility()}, models=Base)
# "user" gets Visibility(types={"Invoice": TypeRule(hidden_fields={"iban"})})

Each model rule is narrowed into its actor type's types[object_type], where object_type is the one the model's entries are written with (AuditOptions.object_type or the class name). A model's rules are those of every __audit__ up its MRO, narrowed together, so a subclass with its own __audit__ keeps its bases' rules. Model rules only hide more: they also narrow an actor type mapped to UNRESTRICTED, and an actor type named only in model rules is not in mapping, so it gets default (narrowed by its model rules) and the warning.

The models are read on the first call of the resolver, not when it is built, so the order of imports does not matter, and read again when a registry has gained or lost mappers since. A hidden field of a model rule, or of a types rule in mapping or default for a model's object_type, that is not an audited attribute of that model (a column that is not excluded, or a collection relationship the model tracks) makes that call raise ValueError naming the model, the actor type and the field; so does every later call until it is fixed. check_models reports the model rules' fields without a resolver.

Parameters:

Name Type Description Default
mapping Mapping[str, Visibility]

Visibility by actor type. StrEnum keys match their value.

required
default Visibility

The Visibility of an actor type not in mapping.

NOTHING
same_scope bool

Narrow the Visibility to the caller's scope: scope_ids={ctx.scope_id}, or nothing at all when the context has no scope_id.

False
unscoped Collection[str]

Actor types that same_scope leaves as they are, for example administrators who see every tenant.

()
models _Models | None

The registry of the audited models, a declarative base class using it, or a sequence of them, whose AuditOptions.visibility rules to add. Their mappers are configured when they are read. None adds no model rules.

None

Returns:

Type Description
VisibilityResolver

The resolver.

Raises:

Type Description
TypeError

mapping is not a mapping, a key is not a str, a value or default is not a Visibility, unscoped is a str or holds something other than str, or models is or holds something that is neither a registry nor a declarative base class.

Source code in audit_trail/visibility.py
def by_actor_type(
    mapping: Mapping[str, Visibility],
    *,
    default: Visibility = Visibility.NOTHING,
    same_scope: bool = False,
    unscoped: Collection[str] = (),
    models: _Models | None = None,
) -> VisibilityResolver:
    """Build a resolver that picks a ``Visibility`` by the caller's actor type.

    The resolver looks ``ctx.actor_type`` up in ``mapping``. An actor type
    that is not in it gets ``default``, which shows nothing unless given, and
    a warning is logged the first time each such type is seen (for the
    first 1024 such types; later ones get no warning).

    Example::

        audit = AuditTrail(
            engine,
            visibility=by_actor_type(
                {
                    "admin": UNRESTRICTED,
                    "user": Visibility(object_types={"Invoice"}),
                },
                same_scope=True,
                unscoped={"admin"},
            ),
        )

    With ``models``, the rules in each audited model's
    ``AuditOptions(visibility=...)`` are added too::

        class Invoice(Base, Audited):
            ...
            __audit__ = AuditOptions(
                visibility={"user": TypeRule(hidden_fields={"iban"})},
            )

        resolver = by_actor_type({"user": Visibility()}, models=Base)
        # "user" gets Visibility(types={"Invoice": TypeRule(hidden_fields={"iban"})})

    Each model rule is narrowed into its actor type's ``types[object_type]``,
    where ``object_type`` is the one the model's entries are written with
    (``AuditOptions.object_type`` or the class name). A model's rules are
    those of every ``__audit__`` up its MRO, narrowed together, so a
    subclass with its own ``__audit__`` keeps its bases' rules. Model rules
    only hide more: they also narrow an actor type mapped to
    ``UNRESTRICTED``, and an actor type named only in model rules is not in
    ``mapping``, so it gets ``default`` (narrowed by its model rules) and
    the warning.

    The models are read on the first call of the resolver, not when it is
    built, so the order of imports does not matter, and read again when a
    registry has gained or lost mappers since. A hidden field of a model
    rule, or of a ``types`` rule in ``mapping`` or ``default`` for a model's
    ``object_type``, that is not an audited attribute of that model (a
    column that is not excluded, or a collection relationship the model
    tracks) makes that call raise ``ValueError`` naming the model, the
    actor type and the field; so does every later call until it is fixed.
    ``check_models`` reports the model rules' fields without a resolver.

    Args:
        mapping: ``Visibility`` by actor type. ``StrEnum`` keys match their
            value.
        default: The ``Visibility`` of an actor type not in ``mapping``.
        same_scope: Narrow the ``Visibility`` to the caller's scope:
            ``scope_ids={ctx.scope_id}``, or nothing at all when the context
            has no ``scope_id``.
        unscoped: Actor types that ``same_scope`` leaves as they are, for
            example administrators who see every tenant.
        models: The registry of the audited models, a declarative base
            class using it, or a sequence of them, whose
            ``AuditOptions.visibility`` rules to add. Their mappers are
            configured when they are read. ``None`` adds no model rules.

    Returns:
        The resolver.

    Raises:
        TypeError: ``mapping`` is not a mapping, a key is not a ``str``, a
            value or ``default`` is not a ``Visibility``, ``unscoped`` is a
            ``str`` or holds something other than ``str``, or ``models`` is
            or holds something that is neither a registry nor a declarative
            base class.
    """
    if not isinstance(mapping, Mapping):
        raise TypeError("mapping must be a mapping of actor types to Visibility")
    for key, visibility in mapping.items():
        if not isinstance(key, str):
            raise TypeError(f"mapping: actor type {key!r} must be a str")
        if not isinstance(visibility, Visibility):
            raise TypeError(f"mapping[{key!r}] must be a Visibility")
    if not isinstance(default, Visibility):
        raise TypeError("default must be a Visibility")
    _check_collection(unscoped, "unscoped")
    for actor_type in unscoped:
        if not isinstance(actor_type, str):
            raise TypeError(f"unscoped: actor type {actor_type!r} must be a str")
    # A `StrEnum` member is equal to its value and hashes like it, so the
    # keys need no conversion.
    known = frozenset(mapping)
    registries = _registries_of(models)
    free = frozenset(unscoped)
    unknown: set[str] = set()
    lock = threading.Lock()
    read_lock = threading.Lock()
    # The number of mappers the model rules were read from (-1: not read
    # yet) and the visibility per actor type, replaced together.
    read: tuple[int, dict[str, Visibility]] = (-1 if registries else 0, dict(mapping))

    def mapper_count() -> int:
        return sum(len(reg.mappers) for reg in registries)

    def visibilities() -> dict[str, Visibility]:
        nonlocal read
        count, by_type = read
        if not registries or count == mapper_count():
            return by_type
        with read_lock:
            count, by_type = read
            if count == mapper_count():
                return by_type
            for reg in registries:
                reg.configure()
            count = mapper_count()
            by_type = dict(mapping)
            for actor_type, types in _model_rules(registries, mapping, default).items():
                base = by_type.get(actor_type, default)
                by_type[actor_type] = base.narrow(Visibility(types=types))
            read = (count, by_type)
            return by_type

    def first_seen(actor_type: str) -> bool:
        with lock:
            if actor_type in unknown or len(unknown) >= _MAX_WARNED_TYPES:
                return False
            unknown.add(actor_type)
            return True

    def resolve(ctx: AuditContext) -> Visibility:
        actor_type = ctx.actor_type
        visibility = visibilities().get(actor_type, default)
        if actor_type not in known and first_seen(actor_type):
            logger.warning(
                "by_actor_type: no visibility for actor type %r, using the default",
                actor_type,
            )
        if not same_scope or actor_type in free:
            return visibility
        scope_ids = frozenset({ctx.scope_id}) if ctx.scope_id else frozenset()
        return visibility.narrow(Visibility(scope_ids=scope_ids))

    return resolve