Skip to content

OpenConceptLab/ocl_online#659 | Request and response bodies are no longer logged outside development; credential headers are masked - #1045

Merged
snyaggarwal merged 7 commits into
masterfrom
fix/659-no-body-logging
Nov 24, 2026
Merged

snyaggarwal merged 7 commits into
masterfrom
fix/659-no-body-logging

Conversation

@paynejd

@paynejd paynejd commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Refs OpenConceptLab/ocl_online#659

What changes

Request and response bodies are no longer logged outside development, and credential headers are masked in request logs. Bodies and GraphQL query text are logged only with the new LOG_REQUEST_BODIES setting (DEBUG and ENV == 'development'), so a deployment that leaves ENVIRONMENT unset doesn't log them.

  • Request logging, bodies. CustomLoggerMiddleware overrides django-request-logging's two body writers, _log_request_body (plain and multipart) and _log_resp (JSON response bodies), so they write nothing unless LOG_REQUEST_BODIES. The library writes bodies at the response's level: DEBUG for 2xx/3xx, ERROR for 4xx (its default REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL) and ERROR for 5xx (hard-coded). Raising django.request to INFO would therefore still log the body of every 4xx and 5xx request. None of the library's settings turns off response bodies without also dropping the METHOD path - status line, so the override is level-independent.
  • Request logging, headers. The middleware adds to the library's masked request headers those in AnalyticsEventEmitter.SENSITIVE_HEADERS, the list analytics events already redact (Authorization, Cookie, X-API-Key, X-Auth-Token, X-Amz-Security-Token, Proxy-Authorization, and now X-CSRFToken). A JSON response's logged headers are checked against the same names (one lower-cased set), Set-Cookie included, whether or not bodies are logged.
  • GraphQL errors. Strawberry logs each error with the lines of the query it points at, and an error the client caused echoes the values it sent. Unless LOG_REQUEST_BODIES (core/graphql/schema.py), only an unexpected exception is logged, in a resolver or one strawberry catches around execution, as GraphQL execution error with its traceback (not its path, which holds the client's aliases). A rejected query, bad variables or a GraphQLError a resolver raises go to the client only.
  • Still logged: the METHOD path and METHOD path - status lines (INFO), request headers (masked), and a JSON response's headers (masked), as today. No change to log levels, handlers or the library version.

Tests

Bodies, headers and queries carry marker strings, and the tests assert that no log record contains one:

  • core/middlewares/tests.py CustomLoggerMiddlewareTest (SimpleTestCase + RequestFactory, every django.request record captured at DEBUG):
    • JSON body with 201, 400 and 500 responses; the request lines are still there.
    • Multipart body (400).
    • Credential request headers, a header added through REQUEST_LOGGING_SENSITIVE_HEADERS, and a response with cookies set both ways, with and without LOG_REQUEST_BODIES.
  • core/graphql/tests/test_schema.py SchemaErrorLoggingTest, by real execution: a rejected query, bad variables and a resolver's GraphQLError aren't logged; a resolver's ValueError (under an alias) and an extension's exception in on_execute (no path) are logged without the query or the alias.
  • Controls with LOG_REQUEST_BODIES on, in both files, show that the capture does see the markers.

Against master's code, the new middleware tests fail and the GraphQL tests can't import the new Schema class. The pathless-exception test also fails on 5373c10, before the review fix. With this change, core.services core.graphql core.middlewares pass (133 tests, with db and es), and pylint -j0 core/ (4.0.9) is clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2

…response bodies outside development, and masks credential headers

CustomLoggerMiddleware skips the library's request-body and response-body
lines unless ENV is development, at every level (the library writes them at
DEBUG, and at ERROR for a 4xx or 5xx response). The request lines (method,
path, status) and a JSON response's headers are still logged.

REQUEST_LOGGING_SENSITIVE_HEADERS adds Cookie and X-Api-Key to the request
headers the library masks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
@paynejd
paynejd requested a review from snyaggarwal November 24, 2026 04:10
… query outside development; request logging masks every credential header analytics events redact

- core/graphql/schema.py: strawberry logs each error with the query lines it
  points at. Outside development a rejected query isn't logged, and an error
  a resolver raised is logged with its path and traceback only.
- CustomLoggerMiddleware masks the request headers in
  AnalyticsEventEmitter.SENSITIVE_HEADERS (now with X-CSRFToken), replacing
  the settings list, and the same names in a JSON response's logged headers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 1 (codex-cli 0.169.0, commit 0dcbf41)

Verdict: findings: 2 P1, 2 P2.

  • F1.1 (P1) core/graphql/schema.py:6: GraphQL validation errors still write request-body content to the application logs outside development.
  • F1.2 (P1) core/settings.py:316: The request header mask misses the CSRF cookie value sent by GraphiQL.
  • F1.3 (P2) core/middlewares/middlewares.py:53: The middleware still attaches both bodies to log records, and Django's default CI error handler prints form values.
  • F1.4 (P2) core/middlewares/middlewares.py:61: A credential supplied directly in a JSON response header is logged verbatim, and the cookie test misses that path.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "full",
  "commit": "0dcbf414",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "F1.1",
      "severity": "P1",
      "tag": null,
      "file": "core/graphql/schema.py",
      "line": 6,
      "claim": "GraphQL validation errors still write request-body content to the application logs outside development.",
      "scenario": "A staging or production client posts a GraphQL query with an inline search term and an unknown field on the same line. Strawberry logs the validation error at ERROR through `strawberry.execution`, including the source line with the search term.",
      "action": "Outside development, log GraphQL errors without query source or input values. Add an endpoint test that captures `strawberry.execution` and checks that a marker in the posted query stays out of the logs.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.2",
      "severity": "P1",
      "tag": null,
      "file": "core/settings.py",
      "line": 316,
      "claim": "The request header mask misses the CSRF cookie value sent by GraphiQL.",
      "scenario": "GraphiQL reads the `csrftoken` cookie and sends the same value in `X-CSRFToken`. Masking `Cookie` leaves that value visible in the `X-Csrftoken` entry Django passes to the logger.",
      "action": "Mask `X-Csrftoken` and add a test with a distinct marker for that header. Cover the credential headers already recognized by the analytics emitter, including `X-Auth-Token` and `X-Amz-Security-Token`.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.3",
      "severity": "P2",
      "tag": null,
      "file": "core/middlewares/middlewares.py",
      "line": 53,
      "claim": "The middleware still attaches both bodies to log records, and Django's default CI error handler prints form values.",
      "scenario": "With `ENVIRONMENT=ci` and `DEBUG=False`, a multipart POST that returns 400 generates an ERROR record containing the original request. Django's admin error handler reads `request.POST` and the console email backend prints its values. The production test still passes because it checks only `record.getMessage()`, while the library also attaches the original request and response to the record.",
      "action": "Pass only safe metadata in the middleware's logging context outside development. Test the record fields and exercise the default handler with a marked multipart 400 response.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.4",
      "severity": "P2",
      "tag": null,
      "file": "core/middlewares/middlewares.py",
      "line": 61,
      "claim": "A credential supplied directly in a JSON response header is logged verbatim, and the cookie test misses that path.",
      "scenario": "A JSON response with a `Set-Cookie` entry in `response.headers` writes the cookie value to the logs. The test uses `response.set_cookie()`, which stores the marker separately in `response.cookies`.",
      "action": "Mask credential response headers case-insensitively before logging them in any environment. Put a marker directly in `response.headers` in the regression test.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Response to Codex pass 1 (fixes in 6eb6ff0)

  • F1.1 (P1), fixed. core/graphql/schema.py subclasses strawberry's Schema. Outside development, a query rejected at validation isn't logged, and an error a resolver raised is logged as GraphQL error at <path> with its traceback, without the query. Development keeps strawberry's own logging. Tests: core/graphql/tests/test_schema.py (both fail on master; a development control shows that the capture sees the query).
  • F1.2 (P1), fixed. The middleware now masks every request header in AnalyticsEventEmitter.SENSITIVE_HEADERS (so X-Auth-Token and X-Amz-Security-Token too), and x-csrftoken joins that list. The settings list is gone, leaving one list. The test adds X-CSRFToken and X-Auth-Token. Analytics events are unchanged: X-CSRFToken isn't among the request headers they keep.
  • F1.3 (P2), accepted. This only happens under ENVIRONMENT=ci. Every deployed environment configures django.request with propagate: False and stream handlers whose format writes only the message, so the record's request never reaches the admin-mail handler. In CI, Django's own 5xx django.request records carry the request too, so dropping the library's extra wouldn't change what CI prints, and CI has only fixture data.
  • F1.4 (P2), fixed. Outside development, a JSON response's logged headers mask the same names, Set-Cookie included. The test now writes a marker straight into response['Set-Cookie'] as well as through set_cookie().

Tests: core.middlewares + core.graphql.tests.test_schema 34 OK (7 new fail on master); core.services core.graphql core.middlewares with db+es 130 OK; pylint -j0 core/ (4.0.9) clean.

…he client caused aren't logged; credential response headers are masked in every environment

- core/graphql/schema.py logs only an unexpected exception in a resolver
  (path and traceback). A rejected query, bad variables or a GraphQLError a
  resolver raises echo what the client sent, so they go to the client only.
- CustomLoggerMiddleware._log_resp masks a JSON response's credential headers
  in every environment and logs its body only in development.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 2 (codex-cli 0.169.0, commit 6eb6ff0)

Verdict: findings: 1 P1, 2 P2. Prior: F1.1 and F1.2 resolved; F1.3 unresolved (accepted in pass 1); F1.4 unresolved (development branch, now F2.3).

  • F2.1 (P1) core/graphql/schema.py:20: GraphQL execution errors still log values from the POST body outside development.
  • F2.2 (P2) core/middlewares/middlewares.py:59: The middleware still attaches the original request and response to log records, and Django's default CI handler prints submitted form values.
  • F2.3 (P2) core/middlewares/middlewares.py:65: Development still logs credential-bearing JSON response headers verbatim.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "verify",
  "commit": "6eb6ff0b",
  "verdict": "findings",
  "prior": [
    {
      "id": "F1.1",
      "status": "resolved"
    },
    {
      "id": "F1.2",
      "status": "resolved"
    },
    {
      "id": "F1.3",
      "status": "unresolved"
    },
    {
      "id": "F1.4",
      "status": "unresolved"
    }
  ],
  "findings": [
    {
      "id": "F2.1",
      "severity": "P1",
      "tag": null,
      "file": "core/graphql/schema.py",
      "line": 20,
      "claim": "GraphQL execution errors still log values from the POST body outside development.",
      "scenario": "A staging or production client supplies a source mnemonic that cannot be found or passes a string variable to the integer limit argument. The formatted exception includes the submitted value. A resolver error also logs any client-supplied field alias through error.path. All three cases reach strawberry.execution at ERROR.",
      "action": "Log server-controlled error metadata such as the exception type and stack locations. Add an async execution test with distinct markers in resolver arguments, invalid variables, and an alias, and check the formatted records.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.2",
      "severity": "P2",
      "tag": null,
      "file": "core/middlewares/middlewares.py",
      "line": 59,
      "claim": "The middleware still attaches the original request and response to log records, and Django's default CI handler prints submitted form values.",
      "scenario": "With ENVIRONMENT=ci and DEBUG=False, a multipart POST with a marker in an ordinary form field returns 400. The middleware's ERROR record reaches Django's admin email handler, which reads request.POST and prints the marker through the console email backend. The regression test captures only record.getMessage() and misses this output.",
      "action": "Give the request logger metadata-only context outside development and configure CI error handling to keep request lines without dumping form data, including on Django-generated 5xx records. Test both the record fields and the configured handler output.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.3",
      "severity": "P2",
      "tag": null,
      "file": "core/middlewares/middlewares.py",
      "line": 65,
      "claim": "Development still logs credential-bearing JSON response headers verbatim.",
      "scenario": "With ENVIRONMENT=development, a JSON response returning 400 carries a session token directly in its Set-Cookie header. The call to the library logs that header value at ERROR. The credential test exercises only the production branch.",
      "action": "Apply the same response-header masking in every environment and keep body logging conditional on development. Run the direct Set-Cookie regression case in both development and production.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Response to Codex pass 2 (fixes in 41252bb)

  • F2.1 (P1), fixed. Outside development, Schema.process_errors now logs only an unexpected exception in a resolver: an error with a path whose original_error isn't a GraphQLError. A rejected query, bad variables, and a GraphQLError a resolver raises (Source '…' was not found, Authentication required) all echo what the client sent, so they're returned to the client and not logged. The request line POST /graphql/ - <status> is still logged. An unexpected exception keeps its path and traceback, the same way Django's django.request handler logs a REST 500's traceback: a path holds field names or aliases, not argument values. Keeping exception text out of every server-fault traceback would be a wider change than this ticket. New tests: bad variables (a marker in $limit) and a resolver GraphQLError carrying a marker; neither is logged. All four production tests fail on master.
  • F2.2 (P2), accepted, as F1.3. Only ENVIRONMENT=ci has no LOGGING dict. There, django.request propagates to Django's default admin-mail handler, and Django's own 4xx/5xx django.request records carry the request too, so changing this middleware's extra wouldn't change CI output. Changing CI's logging is outside this ticket. Deployed environments stop django.request at stream handlers that write only the message.
  • F2.3 (P2), fixed. _log_resp now masks a JSON response's credential headers in every environment and logs the body only in development. The header test runs under both production and development (a Set-Cookie marker set directly and through set_cookie()).

Tests: core.middlewares + core.graphql.tests.test_schema 36 OK (the 10 non-control tests fail on master); core.services core.graphql core.middlewares with db+es 132 OK; pylint -j0 core/ (4.0.9) clean.

…is logged without its path; the library's own header masks are kept

- core/graphql/schema.py: the path holds the client's aliases, so outside
  development a resolver's unexpected exception is logged with its traceback
  only.
- CustomLoggerMiddleware adds the credential headers to the library's list
  (REQUEST_LOGGING_SENSITIVE_HEADERS or its default) instead of replacing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 3 (codex-cli 0.169.0, commit 41252bb)

Verdict: findings: 1 P1, 3 P2. Prior: F1.1, F1.2, F1.4, F2.3 resolved; F1.3/F2.2 unresolved (accepted, CI only); F2.1 unresolved (aliases in the path, now F3.1).

  • F3.1 (P1) core/graphql/schema.py:22: Unexpected GraphQL resolver errors still log client-supplied aliases from the POST body.
  • F3.2 (P2) core/middlewares/middlewares.py:71: The CI error handler still prints submitted form data from the request attached to ERROR records.
  • F3.3 (P2) core/middlewares/middlewares.py:48: The middleware drops credential header masks supplied by deployment settings.
  • F3.4 (P2) core/graphql/queries.py:460: The GraphQL search fallback still logs the submitted search text at INFO outside development.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "verify",
  "commit": "41252bbf",
  "verdict": "findings",
  "prior": [
    {
      "id": "F1.1",
      "status": "resolved"
    },
    {
      "id": "F1.2",
      "status": "resolved"
    },
    {
      "id": "F1.3",
      "status": "unresolved"
    },
    {
      "id": "F1.4",
      "status": "resolved"
    },
    {
      "id": "F2.1",
      "status": "unresolved"
    },
    {
      "id": "F2.2",
      "status": "unresolved"
    },
    {
      "id": "F2.3",
      "status": "resolved"
    }
  ],
  "findings": [
    {
      "id": "F3.1",
      "severity": "P1",
      "tag": null,
      "file": "core/graphql/schema.py",
      "line": 22,
      "claim": "Unexpected GraphQL resolver errors still log client-supplied aliases from the POST body.",
      "scenario": "A client uses an internal identifier as a field alias in a staging or production GraphQL POST. If the resolver hits a database timeout, `error.path` contains that alias and the ERROR record prints it verbatim. The current test uses the literal schema field name `concepts` as the path. [graphql-core alias handling](https://github.com/graphql-python/graphql-core/blob/v3.2.12/src/graphql/execution/collect_fields.py#L162-L164)",
      "action": "Log server-controlled exception metadata and stack locations. Add an async GraphQL POST test with a marked alias and a resolver failure, and check the formatted ERROR output.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F3.2",
      "severity": "P2",
      "tag": null,
      "file": "core/middlewares/middlewares.py",
      "line": 71,
      "claim": "The CI error handler still prints submitted form data from the request attached to ERROR records.",
      "scenario": "With `ENVIRONMENT=ci` and `DEBUG=False`, a multipart POST with a marker in an ordinary form field returns a JSON 400. The middleware passes the original request to Django's default admin email handler, and the console email backend prints the submitted value. The marker test reads only `record.getMessage()`. The handler path was checked against Django source. The sandbox denied access to Docker. [Django admin email handler](https://github.com/django/django/blob/stable/5.2.x/django/utils/log.py#L89-L128) [Django report template](https://github.com/django/django/blob/stable/5.2.x/django/views/templates/technical_500.txt#L37-L46)",
      "action": "Use metadata-only logging context outside development and configure CI error handling to preserve request lines without dumping form data from Django-generated errors. Test the configured handler output for a marked multipart 400.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F3.3",
      "severity": "P2",
      "tag": null,
      "file": "core/middlewares/middlewares.py",
      "line": 48,
      "claim": "The middleware drops credential header masks supplied by deployment settings.",
      "scenario": "A deployment lists `X-Forwarded-Access-Token` in `REQUEST_LOGGING_SENSITIVE_HEADERS` to protect its proxy's access token. The library masked that header before the change. The subclass now replaces the configured list, so the token appears in the request log.",
      "action": "Merge configured mask names with the built-in credential headers and test a deployment-specific credential header.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F3.4",
      "severity": "P2",
      "tag": null,
      "file": "core/graphql/queries.py",
      "line": 460,
      "claim": "The GraphQL search fallback still logs the submitted search text at INFO outside development.",
      "scenario": "With INFO logging enabled for `core.graphql.queries` during staging or production diagnostics, a client submits a search term in a GraphQL POST. When Elasticsearch returns zero hits, the fallback log includes the term verbatim, even if the database search succeeds.",
      "action": "Keep the fallback event and omit the submitted search text outside development. Test a zero-hit search with a marked term while capturing INFO records.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Response to Codex pass 3 (fixes in 67e1d6f)

  • F3.1 (P1), fixed. An unexpected resolver exception is now logged as GraphQL resolver error with its traceback, without error.path, which holds the client's aliases. The traceback still shows which resolver failed. The test now puts the marker in the path as an alias. The exception's own text stays in the traceback, as in a REST 500's traceback from Django's django.request handler. That's left for the reviewer: dropping exception text from server-fault tracebacks would be a wider change than this ticket.
  • F3.2 (P2), accepted, as F1.3/F2.2. CI only: deployed environments stop django.request at stream handlers that write only the message.
  • F3.3 (P2), fixed. The middleware now adds the credential headers to the library's list (REQUEST_LOGGING_SENSITIVE_HEADERS, or the library's default) as a new list, rather than replacing it. No deployment sets that setting today: settings.py doesn't read it from the environment.
  • F3.4 (P2), accepted. The core.graphql.queries INFO line isn't in this diff, and it isn't written in deployed web processes, where only django.request is configured and other loggers fall back to the root logger at WARNING. It would need someone to turn on INFO for that logger. Noted for the reviewer.

Tests: core.middlewares + core.graphql.tests.test_schema 36 OK; pylint -j0 core/ (4.0.9) clean. Next: the simplification review, then a Codex check of the commits after 41252bb.

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 67e1d6f: 1 important, 1 pre-existing, 3 nits, inline. They're new beyond Codex passes 1–3. I didn't repeat the items already accepted there (CI admin-mail handler, exception text in resolver tracebacks, the queries.py INFO line).

Comment thread core/graphql/schema.py Outdated
super().process_errors(errors, execution_context)
return
for error in errors:
if error.path and error.original_error and not isinstance(error.original_error, GraphQLError):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important: server exceptions that Strawberry catches outside a resolver are now dropped without a log line in production.

Strawberry's catch-all in execute/execute_sync (except Exception as exc: errors = [_coerce_error(exc)]) wraps the exception as GraphQLError(str(exc), original_error=exc) with no path. An extension hook (DjangoOptimizerExtension), context building, or a DB error there takes this route. error.path is falsy, so nothing is logged. The client gets HTTP 200 with an error body, so django.request doesn't log a traceback either, and the fault never appears in the logs.

The path check isn't needed to keep client-caused errors out. Parse and validation errors have original_error=None, and variable-coercion errors wrap a GraphQLError (graphql-core on_input_value_error), so the isinstance check already skips them:

Suggested change
if error.path and error.original_error and not isinstance(error.original_error, GraphQLError):
if error.original_error and not isinstance(error.original_error, GraphQLError):

A test with an extension whose on_execute raises would cover it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 019129e, thanks. The path check is gone: any original_error that isn't a GraphQLError is logged as GraphQL execution error with its traceback, without the path or the query. I checked the client cases against graphql-core 3.2.12. Parse and validation errors have no original_error, and variable errors (on_input_value_error) and a resolver's own GraphQLError (located_error) wrap a GraphQLError, so they stay out. New real-execution test: an extension whose on_execute raises gives a pathless error, which is now logged (test_logs_an_exception_strawberry_catches_outside_a_resolver; it fails on 5373c10).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified in 019129e/b63f5b45, resolved. The nodes and not path guard in b63f5b4 also handles a case my suggestion missed: a literal that fails validation with a ValueError (Codex FC.1).

def __call__(self, request):
if request.META.get('HTTP_USER_AGENT', '').startswith('ELB-HealthChecker'):
return self.get_response(request)
return super().__call__(request)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pre-existing (not from this change, not blocking): a GraphQL query sent over GET is still logged in full, through the request line.

The library writes request.get_full_path() at INFO in every environment (METHOD path and METHOD path - status). AuthenticatedGraphQLView keeps Strawberry's default allow_queries_via_get=True, so GET /graphql/?query={concepts(query:"...")} puts the whole query, and its argument values, in those lines. REST search terms (?q=) show up the same way. Codex's passes and the PR's tests only cover POST bodies.

Options: outside development, log request.path instead of get_full_path() (override _log_request, and the line process_response builds), or set allow_queries_via_get=False if GraphiQL and clients don't need GET. If query strings are out of scope for ocl_online#659, it's worth saying so on the ticket.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Left open, and noted on OpenConceptLab/ocl_online#659. A query string is part of the URL, not a body, and the request line logs the full path on every route (REST ?q= too). So a fix means deciding how request lines treat query strings across routes, or turning off GraphQL over GET, which changes the API. Neither is behaviour-neutral, so it's your call there.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Out of scope: #659 covers bodies only. Query strings in the request line stay as they are; no change needed here.

Comment thread core/middlewares/middlewares.py Outdated

@staticmethod
def log_bodies():
return settings.ENV == 'development'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit (optional): this fails open. ENV defaults to 'development' when ENVIRONMENT is unset (core/settings.py:41), so a deployment that forgets the variable logs every 4xx/5xx request and response body, and full GraphQL errors (core/graphql/schema.py:18), with no warning. docker-compose defaults to production, so only bare or custom runs are affected. Gating on an explicit opt-in (DEBUG, or a dedicated setting such as LOG_REQUEST_BODIES) would make the safe behaviour the default.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 019129e. LOG_REQUEST_BODIES = DEBUG and ENV == 'development' in settings gates bodies in the middleware and the query text in the GraphQL schema, so leaving ENVIRONMENT unset no longer logs them. A local run that wants bodies sets DEBUG=TRUE, which Django's default console handler needs anyway to show django.request lines.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified, resolved. LOG_REQUEST_BODIES = DEBUG and ENV == 'development' fails closed, and the dev compose already defaults DEBUG=TRUE.

Comment thread core/middlewares/middlewares.py Outdated
if not re.match('^application/json', response.get('Content-Type', ''), re.I):
return
headers = {
name: '*****' if name.lower() in AnalyticsEventEmitter.SENSITIVE_HEADERS else value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit (optional): request headers are masked with self.sensitive_headers (the library list or REQUEST_LOGGING_SENSITIVE_HEADERS, plus the analytics list), but response headers use only AnalyticsEventEmitter.SENSITIVE_HEADERS. A header added through the setting is masked on the request and logged in the clear on the response. You could build one lower-cased set in __init__ and check both against it:

Suggested change
name: '*****' if name.lower() in AnalyticsEventEmitter.SENSITIVE_HEADERS else value
name: '*****' if name.lower() in self.masked_header_names else value

with self.masked_header_names = {name.lower() for name in self.sensitive_headers} at the end of __init__.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 019129e. __init__ builds self.masked_header_names (lower-cased: the library's list plus the analytics list), and response headers are checked against it, so they mask the same names as request headers. The header test now sets REQUEST_LOGGING_SENSITIVE_HEADERS=['X-Deployment-Token'] and checks that header on both the request and the response.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified, resolved. masked_header_names covers both sides, and the X-Deployment-Token case tests the setting path.


self.assertIn("Variable '$limit'", result.errors[0].message)

def test_does_not_log_a_graphql_error_a_resolver_raises(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit (optional): this test and the next one build GraphQLErrors by hand and call process_errors directly, so they don't check the shapes real execution produces. A resolver that raises a GraphQLError reaches process_errors after located_error with original_error=None, not with original_error=GraphQLError(...) as built here, and nothing covers the pathless server exception from the schema.py:22 comment. Running schema.execute_sync against a resolver patched to raise GraphQLError and ValueError, plus an extension that raises in on_execute, would test the filter end to end.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 019129e. The GraphQL tests now run real execution against a small schema built with this Schema class: a resolver raising GraphQLError (not logged), one raising ValueError under an alias (logged without the alias or the query), and an extension raising in on_execute (pathless, logged). One detail from graphql-core 3.2.12: a resolver's GraphQLError reaches process_errors wrapped by located_error, with that GraphQLError as original_error rather than None. The isinstance check covers it either way.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified, resolved. Thanks for the correction: a resolver's raised GraphQLError has no path, so located_error wraps it and original_error is the GraphQLError, not None as I wrote. The real-execution tests cover all three shapes now.

…t check; the header test uses the shared log helper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Simplification review (Claude subagent, commit 67e1d6f)

Verdict: 4 cuts proposed; 3 applied in 5373c10, 1 declined.

  • S1 (dup-test) core/middlewares/tests.py: test_logs_no_multipart_body repeats test_logs_request_lines_but_no_body_at_any_status. Both go through the same overridden _log_request_body, which returns before reading the body whatever its content type. The multipart branch is library code, which the override never reaches. It is a 4xx case, which the subTest loop already covers. Response: Declined. The test checks behaviour (no multipart body is logged), not the override's shape. The library writes multipart bodies through their own function (_log_multipart), so the test still guards against a library upgrade.
  • S2 (shrink) core/middlewares/tests.py: assert_no_marker is a helper that is only called from tests that build the lines list first. test_masks_credential_headers_in_every_environment does not use log_lines, and it builds the middleware, the assertLogs block and the record parsing itself. It does not strip the colour codes that log_lines strips. Response: Applied. log_lines takes an optional response, and the header test uses it, so colour codes are stripped the same way in every test.
  • S3 (shrink) core/middlewares/middlewares.py: log_bodies is a staticmethod with two callers, and both are in this class. The same check is written inline in settings.ENV == 'development' elsewhere in the repo. Response: Applied. settings.ENV == 'development' is inlined at both call sites, as core/graphql/schema.py already does.
  • S4 (dup-test) core/graphql/tests/test_schema.py: test_does_not_log_a_graphql_error_a_resolver_raises builds a hand-made GraphQLError with a source and positions and calls process_errors directly. test_does_not_log_a_query_it_rejects and test_does_not_log_bad_variables already show that GraphQLErrors are not logged outside development. The only branch this test adds is the isinstance(original_error, GraphQLError) check, so the constructed error carries more fields (source, positions, path) than the check looks at. Response: Applied. That error now carries only its message, path and original_error.

Tests rerun: core.middlewares + core.graphql.tests.test_schema 36 OK; pylint -j0 core/ (4.0.9) clean.

simplify.json
{
  "reviewer": "claude subagent",
  "perspective": "simplify",
  "mode": "full",
  "commit": "67e1d6f5",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "S1",
      "severity": null,
      "tag": "dup-test",
      "file": "core/middlewares/tests.py",
      "line": 213,
      "claim": "test_logs_no_multipart_body repeats test_logs_request_lines_but_no_body_at_any_status. Both go through the same overridden _log_request_body, which returns before reading the body whatever its content type. The multipart branch is library code, which the override never reaches. It is a 4xx case, which the subTest loop already covers.",
      "scenario": null,
      "action": "Delete the test. If a multipart check is wanted, add one more case to the existing loop. Nothing else replaces it.",
      "lines_delta": -5,
      "confidence": "medium"
    },
    {
      "id": "S2",
      "severity": null,
      "tag": "shrink",
      "file": "core/middlewares/tests.py",
      "line": 200,
      "claim": "assert_no_marker is a helper that is only called from tests that build the lines list first. test_masks_credential_headers_in_every_environment does not use log_lines, and it builds the middleware, the assertLogs block and the record parsing itself. It does not strip the colour codes that log_lines strips.",
      "scenario": null,
      "action": "Give log_lines an optional view argument defaulting to the JSON-marker view, and use it in the masking test. This drops the duplicate assertLogs block and the list comprehension, and the ANSI handling becomes the same in both tests.",
      "lines_delta": -4,
      "confidence": "low"
    },
    {
      "id": "S3",
      "severity": null,
      "tag": "shrink",
      "file": "core/middlewares/middlewares.py",
      "line": 126,
      "claim": "log_bodies is a staticmethod with two callers, and both are in this class. The same check is written inline in settings.ENV == 'development' elsewhere in the repo.",
      "scenario": null,
      "action": "Keep it as a plain private method, or inline settings.ENV == 'development' at both call sites. Either way the staticmethod decorator and the public name go.",
      "lines_delta": -2,
      "confidence": "low"
    },
    {
      "id": "S4",
      "severity": null,
      "tag": "dup-test",
      "file": "core/graphql/tests/test_schema.py",
      "line": 69,
      "claim": "test_does_not_log_a_graphql_error_a_resolver_raises builds a hand-made GraphQLError with a source and positions and calls process_errors directly. test_does_not_log_a_query_it_rejects and test_does_not_log_bad_variables already show that GraphQLErrors are not logged outside development. The only branch this test adds is the isinstance(original_error, GraphQLError) check, so the constructed error carries more fields (source, positions, path) than the check looks at.",
      "scenario": null,
      "action": "Remove the source= and positions= arguments and keep only path and original_error, so the test pins the isinstance branch and nothing else. This is a shorter form of the test, not a deletion. Leave it in place if it pins the F3.1 fix, since the test pins the isinstance branch.",
      "lines_delta": -2,
      "confidence": "low"
    }
  ]
}

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex check of commits 41252bb..5373c10 (codex-cli 0.169.0, commit 5373c10)

Verdict: clean. Nothing in the pass-3 fixes (67e1d6f) or the simplification (5373c10) broke anything.

findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "5373c104",
  "verdict": "clean",
  "prior": [],
  "findings": []
}

Loop done: 3 Codex passes (P1s F1.1, F1.2, F2.1, F3.1 fixed; accepted P2s: F1.3/F2.2/F3.2, CI only, and F3.4, a pre-existing INFO line that deployed web processes don't write), simplification (3 of 4 cuts applied), and this check. Wider suites core.services core.graphql core.middlewares with db+es: 132 OK at 5373c10.

paynejd and others added 2 commits November 24, 2026 00:02
… exception; bodies are logged only with DEBUG in development; one header mask set

- core/graphql/schema.py logs any unexpected exception, also one strawberry
  catches outside a resolver (which has no path). Client errors stay out:
  their original_error is None or a GraphQLError.
- LOG_REQUEST_BODIES (DEBUG and ENV == 'development') gates bodies and GraphQL
  query text, so a deployment that leaves ENVIRONMENT unset doesn't log them.
- CustomLoggerMiddleware masks request and response headers with one set.
- GraphQL tests run real execution: a schema whose resolvers raise, and an
  extension that raises in on_execute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
…ng the query isn't logged as a server fault

An Int literal too long for int() fails validation with a ValueError and no
path. An error that points at the query without a field path came from
checking the query, so it goes to the client only; exceptions strawberry
catches around execution carry no nodes and are still logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex check of commit 5373c10..019129e (codex-cli 0.169.0, commit 019129e)

Verdict: findings: 2 P2. This commit addressed the maintainer review.

  • FC.1 (P2) core/graphql/schema.py:22: The new pathless exception rule logs some rejected GraphQL inputs as server faults.
  • FC.2 (P2) core/settings.py:44: The rewritten logging tests bypass the environment and DEBUG policy that this commit adds.

Responses

  • FC.1, fixed in b63f5b4. An error that points at the query (nodes) without a field path was raised while checking the query, so it isn't logged. Exceptions strawberry catches around execution carry no nodes, so they're still logged. New test: an Int literal of 5000 digits (validation wraps the ValueError) isn't logged; it fails on 019129e.
  • FC.2, accepted. LOG_REQUEST_BODIES is one expression next to DEBUG and ENV in core/settings.py. Testing its derivation would mean re-executing settings.py under each environment, which costs more than it guards. The behaviour tests override the setting itself.

Tests: core.middlewares + core.graphql.tests.test_schema 38 OK; pylint -j0 core/ (4.0.9) clean. Next: a Codex check of 019129e..b63f5b4.

findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "019129e2",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "FC.1",
      "severity": "P2",
      "tag": null,
      "file": "core/graphql/schema.py",
      "line": 22,
      "claim": "The new pathless exception rule logs some rejected GraphQL inputs as server faults.",
      "scenario": "When an inline `limit` exceeds Python's integer conversion digit limit, graphql-core rejects the query before any resolver runs. Its validation error has no path and wraps the conversion `ValueError`. The old guard skipped it. The new code emits an ERROR traceback for the rejected input. [graphql-core integer coercion](https://github.com/graphql-python/graphql-core/blob/v3.2.12/src/graphql/type/scalars.py#L82-L96) and [validation error wrapping](https://github.com/graphql-python/graphql-core/blob/v3.2.12/src/graphql/validation/rules/values_of_correct_type.py#L131-L155).",
      "action": "Keep input-driven validation failures out of the server fault log while preserving logging for unexpected extension and execution failures. Add a regression test for a validation error that wraps a non-GraphQLError.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "FC.2",
      "severity": "P2",
      "tag": null,
      "file": "core/settings.py",
      "line": 44,
      "claim": "The rewritten logging tests bypass the environment and DEBUG policy that this commit adds.",
      "scenario": "If the assignment regressed to `LOG_REQUEST_BODIES = DEBUG`, a production deployment with `DEBUG=TRUE` would log bodies and GraphQL query text. The middleware and GraphQL logging tests would still pass because they override `LOG_REQUEST_BODIES` directly.",
      "action": "Test the real settings derivation with DEBUG on and off in development and production, and with ENVIRONMENT unset under the default DEBUG setting.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex check of commit 019129e..b63f5b4 (codex-cli 0.169.0, commit b63f5b4)

Verdict: clean. The FC.1 fix broke nothing.

findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "final",
  "commit": "b63f5b45",
  "verdict": "clean",
  "prior": [],
  "findings": []
}

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review of 67e1d6f..b63f5b4. The four findings from my last review are fixed, and I've replied on each thread. One new optional nit is inline. The query-string thread (GET /graphql/?query= and REST ?q= in the request line) is still open for a decision on ocl_online#659. That doesn't block this PR. Pylint passes; Tests were still running when I checked.

def test_does_not_log_a_literal_it_cannot_convert(self):
"""An Int literal too long for int() fails validation with a ValueError, which is the query's fault."""
with self.assertNoLogs('strawberry.execution'):
result = schema.execute_sync(f'{{ concepts(query: "q", limit: {"9" * 5000}) {{ page }} }}')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit (optional): this test only produces a ValueError because of CPython's 4300-digit int() limit (3.11+). With PYTHONINTMAXSTRDIGITS=0 or sys.set_int_max_str_digits(0) in the environment, int() parses the literal, graphql-core's Int check raises a plain GraphQLError, and assertIsInstance(..., ValueError) fails. Docker and CI use 3.12 with the default limit, so this is only a heads-up. To pin it, you could note the dependency in the docstring, or patch sys.set_int_max_str_digits(4300) around the call.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks. Left as is, so the approved head doesn't move for a docstring. If an environment turned the limit off, this test would fail loudly on its assertIsInstance precondition rather than pass without checking anything. That's the failure mode I'd want, and the message would point at the cause. Happy to pin it with sys.set_int_max_str_digits in a follow-up if you'd rather.

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving b63f5b4. All review findings are addressed, and query strings are out of scope (#659 covers bodies only).

@snyaggarwal
snyaggarwal merged commit 525c804 into master Nov 24, 2026
3 checks passed
@snyaggarwal
snyaggarwal deleted the fix/659-no-body-logging branch November 24, 2026 05:33
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.

2 participants