Repository navigation
feat: add audit logger with actor - #689
Conversation
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]>
Reviewer's GuideIntroduces 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 loggingsequenceDiagram
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
Sequence diagram for resource-role changes and rollback audit eventssequenceDiagram
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)
Flow diagram for permission mutation audit eventsflowchart 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]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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]>
There was a problem hiding this comment.
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. |
Summary
Closes #614.
foca.audit.log(action, target, **fields)writes to the loggerfoca.audit, on levelINFO. The actor (subject,client,on_behalf_of) comes from the token and the header,request_idfromfoca.context.extra={"audit": {...}}, so the formatterjsonwrites an object. The message has them asname=valuewith values as ASCII JSON, so values can't forge fields or lines.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 ofownership.pyuse 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 onfoca.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 logsPolicy rule '...' added.,updated.ordeleted.(not breaking).How it was verified
remove_resource, delete events without the rule, PUT upserts logged as updates, text that wasn't JSON for some characters,replacingnaming configured roles.INFO), real races (injected on mongomock), end-to-end requests with tokens through the API.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
keptfield for grants that lose a concurrentgrant_role(), and ordering of events under concurrency: the same, documented.Rule identifiers on role events: helpers don't have them.
on_behalf_ofbeing the header's value, also if an operation doesn't act for that user: documented; what it acted on is insubject.foca.auditusing the private helpers offoca.utils.logging: same package, as others do.Long lines of
revoke_allwith 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
test_concurrent_useis skipped on mongomock, whose updates aren't atomic: a read cansee the new version of the recorded changes without its change. It failed CI on feat: add worker jobs, index errors, key hints #688.
It still runs against MongoDB.
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:
Bug Fixes:
Enhancements:
Documentation:
Tests: