Skip to content

feat: add audit logger with actor - #689

Merged
uniqueg merged 6 commits into
devfrom
feat/614-audit-logger
Nov 4, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/614-audit-logger

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #614.

  • foca.audit.log(action, target, **fields) writes to the logger foca.audit, on level INFO. The actor (subject, client, on_behalf_of) comes from the token and the header, request_id from foca.context.
  • Fields are in extra={"audit": {...}}, so the formatter json writes an object. The message has them as name=value with values as ASCII JSON, so values can't forge fields or lines.
  • Used by the permissions API (permission.create, .update, .delete, with the rule and the rule replaced) and the helpers for resource roles (resource_role.grant, .revoke, .revoke_all). Role operations of ownership.py use the helpers and keep their log lines.
  • log() doesn't fail what was logged: not if the actor can't be determined, and not if a handler or filter raises (reported on foca.audit_failures).

Docs: docs/configuration/log.md (routing, fields, limits, GDPR note), docs/access-control.md, docs/reference.md, docs/migration-0.21.md. For the release notes: the permissions API no longer logs Policy rule '...' added., updated. or deleted. (not breaking).

How it was verified

  • Local checks on Python 3.13 with own MongoDB: ruff, mypy, ast-grep, docs, pytest, 100% coverage.
  • Tests for actor extraction with and without claims, escaping, every call site, rollbacks and restored owners, rejected changes, and the routing example of the docs.
  • Reviewers: both, two rounds of adversarial, one of quality. Findings fixed: the docs example failing validation, partial remove_resource, delete events without the rule, PUT upserts logged as updates, text that wasn't JSON for some characters, replacing naming configured roles.
  • Not run: Celery workers (documented that their root level may be too high for INFO), real races (injected on mongomock), end-to-end requests with tokens through the API.
  • CI: see the checks of this PR.

Declined review findings

  • Events after failures of the database right after a change, other than in remove_resource: needs the adapter to report what it did at each step, for a rare case in which the request fails and the error is logged. Documented as a limit.

  • A kept field for grants that lose a concurrent grant_role(), and ordering of events under concurrency: the same, documented.

  • Rule identifiers on role events: helpers don't have them.

  • on_behalf_of being the header's value, also if an operation doesn't act for that user: documented; what it acted on is in subject.

  • foca.audit using the private helpers of foca.utils.logging: same package, as others do.

  • Long lines of revoke_all with many rules: resources have few roles.

  • Sourcery: stale previous rule or deleted rule under concurrent changes of one
    permission. Making the read and the write atomic would need a transaction or a lock
    per permission; the audit log documents that it isn't a transaction log.

Unrelated fixes

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Introduce structured, resilient audit logging for access-control changes while documenting how to route and retain the resulting events.

New Features:

  • Add a resilient audit logging API that records access-control actions with structured fields, actors, and request identifiers.
  • Emit audit events for permission changes and resource-role grants, revocations, bulk removals, replacements, and ownership operations.

Bug Fixes:

  • Skip the mongomock concurrency test because its non-atomic updates produce invalid results while retaining coverage against MongoDB.

Enhancements:

  • Make audit records safe for JSON and text log consumers by escaping values and preventing reserved-field spoofing.
  • Preserve audit information for partial or uncertain resource-role removals and report logging failures without failing the completed operation.

Documentation:

  • Document audit event fields, routing, limitations, and GDPR considerations, and update access-control and migration guidance.

Tests:

  • Add comprehensive coverage for audit event content, actor extraction, formatting, failure handling, permissions, resource roles, ownership rollbacks, and documentation configuration examples.

uniqueg and others added 3 commits November 4, 2026 10:35
Add `foca.audit.log()`, writing to the logger `foca.audit`, with the
actor and the request ID, in `extra` and as escaped JSON values in the
message. The permissions API and the helpers for resource roles use it.

The permissions API no longer logs its own "Policy rule" lines, with
the rule now in the event. Role operations keep their lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log values of stored rules at their positions, and the rule the API
changes rather than a configured one with that identifier. Leave a
trace of rules removed with a resource that grant no role. Say which
handler failures reach the failure logger, and more limits, in the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 09:55
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces a dedicated, failure-resistant structured audit logger and wires it into permission and resource-role mutations, including ownership rollbacks and restorations, with actor/request context, safe text and JSON output, extensive tests, and operational/GDPR documentation.

Sequence diagram for structured access-control audit logging

sequenceDiagram
    participant Mutation as AccessControlMutation
    participant Audit as foca.audit.log
    participant Context as TokenAndRequestContext
    participant Logger as foca.audit
    participant Failures as foca.audit_failures

    Mutation->>Mutation: Apply permission or role change
    Mutation->>Audit: log(action, target, fields)
    Audit->>Context: _get_actor()
    Context-->>Audit: subject, client, on_behalf_of
    Audit->>Context: request_id()
    Context-->>Audit: request_id or None
    Audit->>Logger: info(message, extra={audit: event})
    alt handler or filter raises
        Audit->>Failures: exception(...)
    end
    Audit-->>Mutation: return without interrupting completed change
Loading

Sequence diagram for resource-role changes and rollback audit events

sequenceDiagram
    participant Operation as ResourceRoleOrOwnershipOperation
    participant Helper as ResourceRoleHelper
    participant Adapter as CasbinAdapter
    participant Audit as foca.audit.log

    Operation->>Helper: add_resource_role() or remove_resource_role()
    Helper->>Adapter: add or remove role policy
    Adapter-->>Helper: changed
    alt role granted
        Helper->>Audit: log(resource_role.grant, resource, role fields)
    else role revoked
        Helper->>Audit: log(resource_role.revoke, resource, role fields)
    end
    Operation->>Helper: remove_resource()
    Helper->>Adapter: remove resource policies
    Helper->>Audit: log(resource_role.revoke_all, resource, rules, swept)
Loading

Flow diagram for permission mutation audit events

flowchart LR
    Request[Permission API request] --> Mutation{Mutation outcome}
    Mutation -->|create or PUT upsert| Create[permission.create]
    Mutation -->|update existing rule| Update[permission.update with previous]
    Mutation -->|delete| Delete[permission.delete with stored rule]
    Create --> Audit[foca.audit.log]
    Update --> Audit
    Delete --> Audit
    Audit --> Record[INFO record with actor and request_id]
Loading

File-Level Changes

Change Details Files
Added a resilient structured audit logging API that captures access-control actions, actor identity, and request context while preventing logging failures from affecting completed operations.
  • Added foca.audit.log() with structured extra fields and safe ASCII-JSON message formatting.
  • Extracted token subject, client, delegated user, and request ID with fault-tolerant fallbacks.
  • Reported handler, filter, actor lookup, and failure-logger errors without propagating them.
foca/audit.py
docs/configuration/log.md
docs/reference.md
tests/test_audit.py
Instrumented permission API mutations with create, update, and delete audit events containing the affected rule data.
  • Replaced legacy permission mutation log messages with audit events.
  • Distinguished PUT creates from updates and included the previous stored rule for updates.
  • Included deleted rule details when available and avoided logging rejected operations.
foca/security/access_control/access_control_server.py
tests/test_audit.py
docs/migration-0.21.md
Instrumented resource-role and ownership operations with audit events covering grants, replacements, revocations, bulk removal, rollbacks, and restorations.
  • Logged successful grants and revocations with resource, subject, role, subject type, and policy type.
  • Recorded replaced roles and whether a grant was already present.
  • Recorded bulk removals, swept rules, partial failures, and restored or rolled-back ownership changes.
foca/security/access_control/enforcement.py
foca/security/access_control/ownership.py
docs/access-control.md
tests/test_audit.py
Documented audit event schemas, routing, limitations, migration impact, and personal-data handling.
  • Added logger configuration and JSON formatter examples.
  • Documented event fields, failure behavior, concurrency and transaction limitations, Celery considerations, and GDPR guidance.
  • Updated access-control and migration documentation to describe the new audit stream and changed permission log messages.
docs/configuration/log.md
docs/access-control.md
docs/migration-0.21.md
docs/reference.md
Added comprehensive verification for formatting, actor extraction, failure resilience, call-site behavior, and documentation configuration.
  • Covered escaping, reserved fields, unusual values, JSON output, request context, and failing handlers.
  • Tested permission and role event semantics, rejected changes, partial failures, concurrency-related rollback paths, and ownership operations.
  • Validated the documented logging configuration example.
tests/test_audit.py
tests/security/access_control/test_access_control_server.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 9 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/audit.py" line_range="37" />
<code_context>
+    try:
+        return get()
+    except Exception:
+        logger.debug("Part of the actor not available", exc_info=True)
+        return None
+
</code_context>
<issue_to_address>
**Completed changes return errors**

When an actor lookup fails while DEBUG logging is enabled and an audit handler or filter raises, `_try()` lets the `logger.debug()` exception escape before `log()` reaches its protected INFO emit, so the completed access-control change returns an error to the caller.

Guard the diagnostic `logger.debug()` call so its exceptions cannot escape actor lookup.
</issue_to_address>

### Comment 2
<location path="foca/audit.py" line_range="136" />
<code_context>
+        "action": action,
+        "target": _to_json_value(target),
+        "actor": _get_actor(),
+        "request_id": request_id() or None,
+    }
+    event.update(
</code_context>
<issue_to_address>
**Request context can fail mutations**

When an active Celery task has request metadata whose access raises, `request_id()` runs before the `try` that protects logger failures, so an exception while reading request context escapes `audit.log()`. Since the audit calls follow completed access-control changes, the caller sees an error even though the change succeeded; in `remove_resource()`, it can also mask an existing exception.

Guard request-ID lookup so failures yield `None`, like failures when extracting actor fields.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/enforcement.py" line_range="1433" />
<code_context>
+            # if it granted a role: unmarked copies of configured rules still
+            # apply, and invalid rules are not loaded. Configured copies are
+            # kept by the adapter; the section (first argument) is not used.
+            if adapter.remove_policy(ptype[0], ptype, rule):
+                if rule not in configured and _is_valid_rule(ptype, rule, model):
+                    revoked.append(rule)
</code_context>
<issue_to_address>
**Deleted rules go unaudited**

When mongoDB deletes rules but the adapter's change-record update then fails, `remove_policy()` or `remove_filtered_policy()` raises before `remove_resource()` records the deleted rules in `revoked` or sets `swept`, so its `finally` block omits the deletion from the audit event.

Track or recover the rules deleted by adapter calls that raise so `remove_resource()` includes them in its audit event.

Also at `foca/security/access_control/enforcement.py:1441`.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/access_control_server.py" line_range="254" />
<code_context>
         raise BadRequest
     ptype, values = _get_rule()
     _check_not_configured(id)
+    previous = _get_stored_rule(id)
     try:
         current_app.config["casbin_adapter"].save_policy_line(
</code_context>
<issue_to_address>
**Permission history records stale changes**

When concurrent requests modify the same permission between `_get_stored_rule()` and the write or delete, `_get_stored_rule()` captures a preimage separately from the adapter mutation, so the audit event can report the wrong `previous` or deleted rule, or label a replacement as a create.

Make reading the prior rule and applying the write or delete atomic, or serialize mutations for each permission identifier.

Also at `foca/security/access_control/access_control_server.py:373`.
</issue_to_address>

### Comment 5
<location path="foca/security/access_control/enforcement.py" line_range="1453" />
<code_context>
+                "resource_role.revoke_all",
+                resource,
+                ptype=ptype,
+                rules=revoked,
+                swept=swept,
+            )
</code_context>
<issue_to_address>
**Large revocations exceed log limits**

When A resource has enough role assignments for its single revoke-all event to exceed the configured log sink's record-size limit, `remove_resource()` puts every revoked rule into one `rules` field, and `audit.log()` serializes that field into a single message as well as structured data. For resources with many subjects, the resulting record exceeds common log-ingestion size limits and is truncated or dropped, leaving a successful bulk revocation without a complete audit record.

Bound or batch revoke-all events so each emitted record fits supported log-sink limits.
</issue_to_address>

### Comment 6
<location path="foca/security/access_control/enforcement.py" line_range="1224" />
<code_context>
+        subject_type=subject_type,
+        role=role,
+        ptype=ptype,
+        replacing=sorted(others),
+        already_granted=not added,
+    )
</code_context>
<issue_to_address>
**Audit claims absent roles were replaced**

When a grant requests replacement of roles the subject does not currently hold, `others` contains every requested role except the granted role and configured roles, without checking whether the subject currently has those roles. `_replace_resource_role` therefore logs absent roles as `replacing`, so the event misstates what the grant actually replaced.

Determine which requested roles are actually removed and log only those roles as `replacing`.
</issue_to_address>

### Comment 7
<location path="tests/test_audit.py" line_range="220" />
<code_context>
+        with as_caller(app, claims, headers={HEADER: "bob"}):
+            audit.log("thing.create", "/things/1")
+        assert _events(caplog)[0]["actor"]["on_behalf_of"] is None
+        assert "rejected" not in caplog.text
+
+    def test_on_behalf_of_invalid(
</code_context>
<issue_to_address>
**Denial logs can leak**

When a denial-related log uses wording that does not contain `rejected`, `test_on_behalf_of_not_allowed` only rejects log text containing the word `rejected`, so a regression that logs the denied user with different wording, such as `not authorized for bob`, passes despite disclosing the denial.

Assert that no denial-related record or denied header value appears in the captured logs, rather than checking one word.
</issue_to_address>

### Comment 8
<location path="tests/test_audit.py" line_range="704" />
<code_context>
+                remove_resource(TASK)
+        events = _events(caplog)
+        assert len(events) == 1
+        assert len(events[0]["rules"]) == 1
+
+    def test_replace_keeps_configured(
</code_context>
<issue_to_address>
**Wrong removed rule passes**

When the partial-failure path logs one rule, but that rule is not the one successfully removed, `test_remove_resource_failure` checks only that one rule was logged, so logging an unremoved rule instead of the rule actually removed still passes and does not verify the partial-removal behavior named by the test.

Assert that the logged rule matches the rule whose removal succeeded.
</issue_to_address>

### Comment 9
<location path="tests/test_audit.py" line_range="618" />
<code_context>
+            pytest.raises(BadRequest),
+        ):
+            unwrap(postPermission)()
+        assert _events(caplog) == []
+
+    def test_values_keep_positions(
</code_context>
<issue_to_address>
**Removed rules remain stored**

When a removal operation reports its expected result and audit event but does not remove the rule, `test_remove_configured` can pass if `remove_resource_role` deletes the configured rule but returns `False` without logging; `test_remove_resource_invalid_rule` can pass if `remove_resource` reports `swept=True` but leaves the invalid rule stored. Neither test checks the stored state, so both removal regressions go unnoticed.

Assert that the configured rule remains after the first operation and that the invalid stored rule is absent after the second.

Also at `tests/test_audit.py:668-670`.
</issue_to_address>

Linked issues

#614 feat: add audit logger with actor · 6 of 7 met · 1 to check by hand

# Requirement Status Notes
1 Add foca.audit.log() on the foca.audit logger with the actor and request ID. ✅ Met The logger records the subject, client, on-behalf-of user, and request ID, using null where unavailable.
2 Put fields in extra={"audit": {...}} and escape text output to prevent log injection. ✅ Met Events include structured audit data and render field names and values as JSON in the message.
3 Use the audit logger for permissions API and resource-role helper changes. ✅ Met Permission create, update, and delete operations and resource-role grant, revoke, and revoke-all operations emit events; ownership operations use those helpers.
4 Document how to route the logger and include a GDPR note about the actor being personal data. ✅ Met The audit-log documentation covers routing and includes a personal-data warning.
5 Test actor extraction with and without claims, escaping, and every call site. ✅ Met The added tests cover actor contexts, output escaping, permissions operations, role helpers, and ownership operations.
6 Reach 100% coverage. 👀 Check by hand (external system) Check the PR's CI or coverage report confirms 100% coverage.
7 Release notes mention the changed log message texts and that the change is not breaking. ✅ Met The 0.21 migration notes state that the change is not breaking and describe the permissions API log-text change.

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and each access-rights change now writes actor details and rule or role subjects to foca.audit; unless routed separately, those events can also reach existing root handlers and be retained or exposed through their log destinations. Reverting stops future events but cannot remove records already written.

Blocking findings: foca/audit.py:37, foca/audit.py:136, foca/security/access_control/enforcement.py:1433, foca/security/access_control/access_control_server.py:254, foca/security/access_control/enforcement.py:1453, and 4 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/audit.py Resolved
Comment thread foca/audit.py Resolved
Comment thread tests/test_audit.py Resolved
Comment thread tests/test_audit.py Resolved
Comment thread tests/test_audit.py Resolved
@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8a64e44) to head (f572c8f).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #689   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           63        64    +1     
  Lines         8270      8346   +76     
=========================================
+ Hits          8270      8346   +76     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

uniqueg and others added 3 commits November 4, 2026 11:21
Review findings: log() also survives failing debug handlers and
request ID lookups. remove_resource() logs the rule a failing write may
have removed (`uncertain`, `incomplete`), and splits many rules into
events of up to 50. `replacing` only lists roles the subject holds.
Tests check stored state and the logged rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Updates of mongomock aren't atomic: a read can see the new version of
the recorded changes before its change, so that the cache misses one.
MongoDB's single-document updates are atomic, and the test still runs
against it. Failed CI on PR #688.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linked issues

#614 feat: add audit logger with actor · 6 of 7 met

# Requirement Status Notes
1 Write audit events to foca.audit at INFO ✅ Met foca.audit.log() sends events to that logger at INFO.
2 Include the actor from the token and header ✅ Met The event includes the subject, client and on-behalf-of user; the request ID is also included when available.
3 Put fields in extra and escape text output ✅ Met Events use extra={"audit": ...} and format message fields as JSON values.
4 Use the logger in the permissions API and resource-role helpers ✅ Met The permissions API and resource-role grant, revoke and remove operations emit audit events; ownership operations use those helpers.
5 Document logger routing and the GDPR personal-data consideration ✅ Met docs/configuration/log.md documents routing and includes a warning about personal data.
6 Test actor extraction, escaping and every call site; achieve 100% coverage ✅ Met tests/test_audit.py covers actor variants, escaping, the API and role-helper call sites, and ownership operations; the PR description reports 100% coverage.
7 Mention the changed log message texts in the release notes ❌ Not addressed The changed texts are described in the migration guide, but the diff does not add them to the curated release notes.

Comment thread docs/migration-0.21.md Resolved
@uniqueg
uniqueg merged commit f3ecc8c into dev Nov 4, 2026
58 checks passed
@uniqueg
uniqueg deleted the feat/614-audit-logger branch November 4, 2026 10:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add audit logger with actor

1 participant