Repository navigation
OpenConceptLab/ocl_online#659 | Request and response bodies are no longer logged outside development; credential headers are masked - #1045
Conversation
…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
… 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
Codex review, pass 1 (codex-cli 0.169.0, commit 0dcbf41)Verdict: findings: 2 P1, 2 P2.
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"
}
]
} |
Response to Codex pass 1 (fixes in 6eb6ff0)
Tests: |
…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
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).
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"
}
]
} |
Response to Codex pass 2 (fixes in 41252bb)
Tests: |
…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
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).
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"
}
]
} |
Response to Codex pass 3 (fixes in 67e1d6f)
Tests: |
snyaggarwal
left a comment
There was a problem hiding this comment.
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).
| 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): |
There was a problem hiding this comment.
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:
| 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.
There was a problem hiding this comment.
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).
| def __call__(self, request): | ||
| if request.META.get('HTTP_USER_AGENT', '').startswith('ELB-HealthChecker'): | ||
| return self.get_response(request) | ||
| return super().__call__(request) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Out of scope: #659 covers bodies only. Query strings in the request line stay as they are; no change needed here.
|
|
||
| @staticmethod | ||
| def log_bodies(): | ||
| return settings.ENV == 'development' |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Verified, resolved. LOG_REQUEST_BODIES = DEBUG and ENV == 'development' fails closed, and the dev compose already defaults DEBUG=TRUE.
| if not re.match('^application/json', response.get('Content-Type', ''), re.I): | ||
| return | ||
| headers = { | ||
| name: '*****' if name.lower() in AnalyticsEventEmitter.SENSITIVE_HEADERS else value |
There was a problem hiding this comment.
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:
| 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__.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
Simplification review (Claude subagent, commit 67e1d6f)Verdict: 4 cuts proposed; 3 applied in 5373c10, 1 declined.
Tests rerun: 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"
}
]
} |
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 |
… 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
Codex check of commit 5373c10..019129e (codex-cli 0.169.0, commit 019129e)Verdict: findings: 2 P2. This commit addressed the maintainer review.
Responses
Tests: 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"
}
]
} |
snyaggarwal
left a comment
There was a problem hiding this comment.
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 }} }}') |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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 newLOG_REQUEST_BODIESsetting (DEBUG and ENV == 'development'), so a deployment that leavesENVIRONMENTunset doesn't log them.CustomLoggerMiddlewareoverrides django-request-logging's two body writers,_log_request_body(plain and multipart) and_log_resp(JSON response bodies), so they write nothing unlessLOG_REQUEST_BODIES. The library writes bodies at the response's level: DEBUG for 2xx/3xx, ERROR for 4xx (its defaultREQUEST_LOGGING_HTTP_4XX_LOG_LEVEL) and ERROR for 5xx (hard-coded). Raisingdjango.requestto 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 theMETHOD path - statusline, so the override is level-independent.AnalyticsEventEmitter.SENSITIVE_HEADERS, the list analytics events already redact (Authorization,Cookie,X-API-Key,X-Auth-Token,X-Amz-Security-Token,Proxy-Authorization, and nowX-CSRFToken). A JSON response's logged headers are checked against the same names (one lower-cased set),Set-Cookieincluded, whether or not bodies are logged.LOG_REQUEST_BODIES(core/graphql/schema.py), only an unexpected exception is logged, in a resolver or one strawberry catches around execution, asGraphQL execution errorwith its traceback (not its path, which holds the client's aliases). A rejected query, bad variables or aGraphQLErrora resolver raises go to the client only.METHOD pathandMETHOD path - statuslines (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.pyCustomLoggerMiddlewareTest(SimpleTestCase+RequestFactory, everydjango.requestrecord captured at DEBUG):REQUEST_LOGGING_SENSITIVE_HEADERS, and a response with cookies set both ways, with and withoutLOG_REQUEST_BODIES.core/graphql/tests/test_schema.pySchemaErrorLoggingTest, by real execution: a rejected query, bad variables and a resolver'sGraphQLErroraren't logged; a resolver'sValueError(under an alias) and an extension's exception inon_execute(no path) are logged without the query or the alias.LOG_REQUEST_BODIESon, 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 newSchemaclass. The pathless-exception test also fails on 5373c10, before the review fix. With this change,core.services core.graphql core.middlewarespass (133 tests, with db and es), andpylint -j0 core/(4.0.9) is clean.🤖 Generated with Claude Code
https://claude.ai/code/session_01AaZ4qXj8tLAhZvkGSGzEN2