Skip to content

fix: log route templates instead of paths - #750

Merged
uniqueg merged 9 commits into
devfrom
fix/log-route-templates
Nov 9, 2026
Merged

uniqueg merged 9 commits into
devfrom
fix/log-route-templates

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #745 (#743): log lines at INFO and above no longer carry request paths or validators' reasons, which hold values of clients.

  • Traffic log (log_traffic, also FOCA's own controllers): request and response lines name the route, the path template of the operation, e.g., Incoming request: "GET /ga4gh/tes/v1/tasks/{id} HTTP/1.1" from 127.0.0.1, instead of the concrete path. Requests that no operation serves are logged with the placeholder <unknown route>. The concrete path is logged once per request at DEBUG (Path of request ...: /ga4gh/tes/v1/tasks/123).
  • Access denials (enforcement.py): Access denied: DELETE /items/{id} to 'alice' at the configured level (INFO for requests, DEBUG for is_permitted_for()). The path is logged at DEBUG (Path of the denied request: DELETE /items/1 to 'alice'). The DEBUG line Access granted is unchanged.
  • Request validation (_validation_handler_json): rejections without invalid fields are logged at INFO with the mapped detail, if any, or the title (Request rejected: Bad Request). The validator's reason is logged at DEBUG (Reason for rejecting the request: ...), shortened and escaped. Rejections with invalid fields are logged by location and code, as before.
  • Unchanged on purpose: audit logs of grants and resource changes, and the subject in denials.
  • Docs: logging utilities, "What FOCA logs" in the logging configuration, exceptions configuration, access control, migration guide to 0.22, and the 0.22.0 release notes (Security).

Closes #748

Verification

  • Test-first: the new and changed tests failed before the change: the route in traffic logs and denials, reasons at DEBUG only, and paths at DEBUG only. They pass now.
  • Full suite with a local MongoDB 7.0.34: 4910 passed, 2 skipped, 100% coverage.
  • ruff check, ruff format --check, mypy (foca, tests), ast-grep scan, semgrep (.semgrep), mkdocs build --strict: all passed.
  • Checked by hand that an app built by FOCA records the routes of the permissions API, e.g., /admin/access-control/permissions/{id}, so its traffic logs name the route. Some unit tests route the controllers with Flask directly, so those log <unknown route>.
  • Review (full lane): adversarial-reviewer and quality-reviewer, 2 rounds; round 2 found nothing.
  • After merging dev (with build: pick up OS security updates in images #749; ec5b32e): the only conflict was in docs/releases/0.22.0.md (both Security entries kept, #750 added to this one), so no further review. Rerun locally: full suite under coverage 4910 passed, 2 skipped, 100% coverage (test_address_fallback_bounded passed in both runs); ruff, mypy, ast-grep, semgrep (.semgrep), mkdocs build --strict passed.
  • CI on ec5b32e: all checks passed (29 passed, 3 intended skips), including the Scan image jobs, which failed before only because the zlib fix of build: pick up OS security updates in images #749 wasn't in dev.
  • Sourcery (2 medium): fixed in ba9d4e8 (docstring of validation_details named the wrong level for the reason) and 302300b (test asserts the logged path, not the count); tests/utils/test_logging.py (40 passed), ruff and mypy rerun locally. CI on the final head: see the checks.

Round 1 had no high findings. These were fixed:

  • Medium (docs): the docs didn't say that with exceptions.validation_details: false, validation exceptions are still logged at ERROR with the reason.
  • Medium (docs): paragraphs in the migration guide and in the utilities page were badly wrapped.
  • Low: the DEBUG denial line now names the subject.
  • Low: added a test for denials without a route and a test case that logs both request and response.

Declined review findings

  • Invalid-subject denial at INFO (medium): Access denied: invalid subject: <exc>. Not changed: the messages of validate_rule_value() are fixed texts, without the value.
  • Shared helper or public constant for <unknown route> (low): not done. The private constant is used in two places only.
  • Shared fixtures for capturing log methods (low): not done. They are small fixtures, local to their test modules.
  • Out of scope: foca/security/auth.py logs the token validation error's description at INFO. Checked: only errors without an invalid_token challenge reach that line, and their descriptions are fixed texts or URLs of the configured identity providers (from the trusted issuer or its discovery document), not values of clients or tokens. No change needed.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits November 8, 2026 19:43
Requests rejected by request validation without invalid fields were
logged at INFO with the validator's reason, which may quote rejected
values. Log the mapped detail or the title at INFO instead, and the
reason at DEBUG.

Refs #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The traffic log wrote the request line with the concrete path, whose
path parameters are values of clients. Log the route (path template of
the operation, or <unknown route>) instead, and the path at DEBUG.

Refs #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Denials of access control logged the request path at the denied level.
Log the route instead, and the path at DEBUG.

Refs #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document that request logs, access denials and validation rejections
log routes and titles at INFO and paths and reasons at DEBUG, in the
utilities, logging, exceptions and access control pages, the migration
guide and the 0.22.0 release notes.

Refs #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Controllers routed by Flask, not as operations, are logged with the
<unknown route> placeholder; validation reasons, which quote rejected
values, may appear at DEBUG. Also rewrap docs paragraphs.

Refs #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log the subject with the path of denied requests, test denials without
a route, and document that validation exceptions are logged at ERROR
without exceptions.validation_details.

Refs #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 8, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Log validation failures at INFO using invalid-field details, mapped detail, or title, and move potentially value-bearing validator reasons to DEBUG.

  • foca/errors/exceptions.py L296-301, L320, L348-365
  • foca/models/config.py L445-448

Use operation route templates for access-denial messages and log the concrete denied path, with the subject, at DEBUG.

  • foca/security/access_control/enforcement.py L802-817, L857-863 (+3 small edits)

Use route templates in traffic logs, represent missing routes with a placeholder, and log each concrete request path at DEBUG when traffic logging is enabled.

  • foca/utils/logging.py L14-17, L185-201, L268-273 (+1 small edits)

Documentation

Document route-based traffic and denial logs, DEBUG-level paths and validation reasons, and the related migration and release-note changes.

  • docs/access-control.md L432-435
  • docs/configuration/exceptions.md L158-163
  • docs/configuration/log.md L122-137
  • docs/migration-0.22.md L277-282, L301-320
  • docs/releases/0.22.0.md L17
  • docs/utilities.md L284-295

Tests

Verify validation responses and logs keep reasons at DEBUG while INFO summaries avoid rejected values.

  • tests/api/test_validation.py L791-794, L806-810
  • tests/errors/test_errors.py L132-151, L1059-1069, L1127-1132 (+10 small edits)

Verify traffic logs use routes or the unknown-route placeholder and emit escaped concrete paths at DEBUG only when needed.

  • tests/api/test_service_info.py L28, L303-304
  • tests/security/access_control/test_access_control_server.py L29, L578-579, L586
  • tests/utils/test_logging.py L87-109, L120-149, L155-193 (+3 small edits)

Verify access-denial logs use route templates at the denied level and include escaped paths only at DEBUG, including requests without a route.

  • tests/security/access_control/test_enforcement.py L627-678
  • tests/security/access_control/test_path_helpers.py L361-367

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

@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (b165cb9) to head (302300b).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #750   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           74        74           
  Lines         9434      9443    +9     
=========================================
+ Hits          9434      9443    +9     
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.

Keep both Security entries in docs/releases/0.22.0.md and add #750
to the entry for #748.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review November 9, 2026 01:12

@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 2 issues

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

## Individual Comments

### Comment 1
<location path="foca/errors/exceptions.py" line_range="357-363" />
<code_context>
         else:
-            logged = problem.get("detail")
+            logged = problem["title"]
         logger.info(
             "Request rejected: %s",
-            _shorten(
-                escape_log_value(problem["title"] if logged is None else logged),
-                conf.max_detail_length,
-            ),
+            _shorten(escape_log_value(logged), conf.max_detail_length),
         )
+        if reason is not None:
+            logger.debug(
+                "Reason for rejecting the request: %s",
+                _shorten(escape_log_value(reason), conf.max_detail_length),
+            )
</code_context>
<issue_to_address>
**Exception logging docs name wrong level**

When an application’s operators rely on the `ExceptionConfig` API documentation for validation-log behavior, users consulting the `ExceptionConfig` documentation are told that validation rejections without invalid fields log the validator’s reason at `INFO`. The handler now logs the mapped detail or title at `INFO` and the reason at `DEBUG`, so callers get incorrect guidance about which log level contains rejected values.

Update the `ExceptionConfig` docstring to describe the mapped detail or title at `INFO` and the reason at `DEBUG`.
</issue_to_address>

### Comment 2
<location path="tests/utils/test_logging.py" line_range="185" />
<code_context>
+
+    with request_context("/items/s3cr3t", client_address=CLIENT_ADDRESS, app=app):
+        mock_func()
+    assert len(debugs) == count


</code_context>
<issue_to_address>
**Debug count does not verify path**

When `log_request` or `log_response` is true, but the decorator logs one unrelated debug message instead of the request path, `test_logging_decorator_path_once` checks only `len(debugs)`, so with request-only or response-only logging a debug message unrelated to the request path still satisfies the assertion. The test therefore passes while that configuration omits the path.

Assert the expected path message for each enabled configuration, and assert no messages when both options are false.
</issue_to_address>

Linked issues

#748 Log route templates instead of request paths · 6 of 6 met

# Requirement Status Notes
1 Log route templates in traffic request and response lines, and concrete paths at DEBUG only. ✅ Met Traffic descriptions use the route or <unknown route>; the escaped request path is logged once at DEBUG when request or response logging is enabled.
2 Log route templates for access denials at the configured level, and concrete paths at DEBUG only. ✅ Met Denials use the route at the denied level and log the escaped path at DEBUG.
3 For validation rejections without invalid fields, log the mapped detail or title at INFO and the validator's reason at DEBUG. ✅ Met The handler selects the mapped detail or title for INFO and separately logs the shortened, escaped reason at DEBUG.
4 Use a fixed placeholder when no route template is known. ✅ Met Traffic logs and access denials use <unknown route> when the route is None.
5 Leave audit logs of grants and resource changes unchanged. ✅ Met The diff does not change audit logging.
6 Document the changes in logging, access control and exceptions configuration, the migration guide, and the 0.22.0 release notes. ✅ Met The diff updates all of the specified documentation pages.

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: foca/errors/exceptions.py:363, tests/utils/test_logging.py:185


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

Comment thread foca/errors/exceptions.py Resolved
Comment thread tests/utils/test_logging.py Resolved
uniqueg and others added 2 commits November 9, 2026 02:36
The docstring of validation_details still said that the reason is
logged at INFO; it is the mapped detail or the title, with the
reason at DEBUG only.

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.

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit 45c562e into dev Nov 9, 2026
78 of 83 checks passed
@uniqueg
uniqueg deleted the fix/log-route-templates branch November 9, 2026 01:55
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.

Log route templates instead of request paths

1 participant