Skip to content

feat: harden filer HTTP handling and logging - #102

Merged
uniqueg merged 5 commits into
devfrom
feat/http-hardening
Nov 7, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/http-hardening

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Hardens the filer's HTTP(S) handling and the logs of the filer and the taskmaster.

  • Timeout: every requests call of the filer (GET, PUT) has a timeout, FILER_HTTP_TIMEOUT seconds (default 300), for connecting and for each read; it doesn't limit whole transfers. The taskmaster passes the variable on from its environment (Filer.__init__); the filer ignores empty values and replaces invalid ones (not a positive number up to 1000000) with the default, logging an error once.
  • HTTP error bodies: logged as Response body: … (left out when empty), with URLs stripped (redact_urls), the request's query values and user info redacted wherever they appear (also percent-decoded and with escaped slashes), and cut after 1000 characters (body_for_log). After Sourcery's review, this also covers the URLs actually requested (as sent and of redirects) and the .netrc credentials that requests sends, also as a Basic authorization value.
  • Job manifests in the taskmaster's debug log: Util.pprint (used for job and PVC manifests) redacts a copy. It strips URLs in all strings and url fields whole, also in the task in JSON_INPUT, and hides the values of TESK_FTP_USERNAME and TESK_FTP_PASSWORD. The taskmaster's raw log of executor manifests is removed; Job.run_to_completion logs them redacted.
  • Docs: docs/filer.md (timeout, log redaction), docs/taskmaster.md (FILER_HTTP_TIMEOUT, --debug), docs/upgrading.md ("HTTP(S) timeout", including the upload case).

TESK's Helm chart gets a value for the timeout in a separate PR.

Closes #101

Verification

Full-review lane (2 rounds).

  • Tests first (tests/unit/test_http_hardening.py):
    • timeout parsing (default, values, invalid values logged once);
    • timeouts passed to GET and PUT, and timed-out requests failing the transfer;
    • error bodies redacted and truncated, empty bodies not logged;
    • redact_urls and body_for_log;
    • the taskmaster passing the variable (set, unset, empty);
    • pprint on manifests and odd data;
    • the executor and PVC debug logs end to end with mocked Kubernetes clients.
  • ruff check ., ruff format --check . and mypy pass.
  • pytest: 377 passed, after merging dev (PR 88).
  • mkdocs build --strict passes.
  • CI: see the checks of the head commit.

Declined review findings

  • Quality, medium: move the redaction helpers into a new module. transput.py imports nothing from tesk_core, so Util → transput can't form a cycle, and a move would change every import of url_for_log.

  • Quality, low: import HTTP_TIMEOUT_ENV into filer_class. The taskmaster would then import the filer's dependencies; a comment names the constant instead.

  • Adversarial, low: url_for_log keeps fragments and can't strip malformed user info (e.g. an unencoded / in a password). This behaviour is unchanged. Fragments aren't sent to servers, and such URLs fail the transfer.

  • Adversarial, low: secrets in error bodies with other encodings (e.g. lower-case percent escapes), and URLs with JSON-escaped slashes outside JSON_INPUT and url fields. These are rare; covering every encoding isn't feasible.

  • Adversarial, note: ex.body of Kubernetes API errors in job.py/pvc.py debug logs. No evidence that these bodies repeat manifest values. job.py is being changed in another PR.

  • Sourcery, medium: values shorter than 4 characters aren't redacted from bodies. Intended: they are rarely secrets, and replacing them would garble the body.

  • Sourcery, medium: DNS resolution isn't covered by the timeout. The system resolver can't be timed out by requests; it has its own timeouts.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 7, 2026 16:58
Time out the filer's HTTP(S) requests (FILER_HTTP_TIMEOUT, default
300 seconds, for connecting and each read), passed on by the
taskmaster. Log HTTP error bodies redacted and cut after 1000
characters, and job manifests without URL queries, user info or FTP
credentials. Docs and upgrade notes describe the changes.

Closes #101

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the taskmaster's raw log of executor manifests (the job logs them
redacted), strip url fields and the task in JSON_INPUT whole, never
fail on odd manifest data, redact escaped-slash secrets in bodies, and
document the upload case of the timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run the PVC log test on the real manifest, redact tuples too, and
describe how JSON_INPUT is redacted.

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

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Uses of the API

Remove the taskmaster's raw executor-manifest debug log so manifests are logged through the redacted job logging path.

  • src/tesk_core/taskmaster.py L91, L93 (removed lines)

Implementation

Add HTTP timeout validation and apply it to filer requests, while logging non-2xx response bodies with request, redirect, and .netrc secrets redacted and the body truncated.

  • src/tesk_core/filer.py L55-148, L171-175, L195-199 (+5 small edits)

Provide URL and response-body redaction helpers used to keep request-derived secrets out of filer logs.

  • src/tesk_core/transput.py L3, L8-11, L31-112

Make manifest pretty-printing redact URL strings and fields, task URLs in JSON_INPUT, and FTP credential values without modifying the input data.

  • src/tesk_core/Util.py L6-83, L89-91

Configuration

Pass the taskmaster's FILER_HTTP_TIMEOUT environment value through to filer jobs when it is set.

  • src/tesk_core/filer_class.py L128-133

Documentation

Document filer HTTP timeout and log-redaction behavior, taskmaster configuration and debug-log redaction, and the timeout upgrade considerations.

  • docs/filer.md L18-21, L41-50
  • docs/taskmaster.md L88, L106
  • docs/upgrading.md L30-45

Tests

Update HTTP request expectations for timeouts and add coverage for timeout parsing and propagation, secret redaction, manifest logging, and truncation.

  • tests/unit/test_filer_http.py L13-94 (4 small edits)
  • tests/unit/test_http_hardening.py L1-447

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

@uniqueg
uniqueg marked this pull request as ready for review November 7, 2026 16:32
@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.42%. Comparing base (889da9d) to head (1d88448).

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #102      +/-   ##
==========================================
+ Coverage   88.45%   89.42%   +0.97%     
==========================================
  Files          10       10              
  Lines        1039     1135      +96     
==========================================
+ Hits          919     1015      +96     
  Misses        120      120              

☔ 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.

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

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

## Individual Comments

### Comment 1
<location path="src/tesk_core/transput.py" line_range="92" />
<code_context>
+    # Also as JSON with escaped slashes, as some servers write it
+    secrets |= {value.replace("/", "\\/") for value in secrets}
+    for secret in sorted(secrets, key=len, reverse=True):
+        if len(secret) >= MIN_SECRET_LENGTH:
+            text = text.replace(secret, "<redacted>")
+    if len(text) > limit:
</code_context>
<issue_to_address>
**Short secrets remain in logs**

When an HTTP error body repeats a request username, password, or query value shorter than four characters, `body_for_log` skips these values because of `MIN_SECRET_LENGTH`, so it does not redact them and the filer logs them in plaintext.

Redact every nonempty request-derived secret in the body without applying the four-character minimum.

Also at `src/tesk_core/transput.py:93`, `docs/filer.md:19-20`.
</issue_to_address>

### Comment 2
<location path="src/tesk_core/transput.py" line_range="86-88" />
<code_context>
+    """
+    text = redact_urls(text)
+    parts = urlsplit(url)
+    raw = [parts.username or "", parts.password or ""]
+    raw += [pair.partition("=")[2] for pair in parts.query.split("&")]
+    secrets = set(raw) | {unquote_plus(value) for value in raw}
+    # Also as JSON with escaped slashes, as some servers write it
+    secrets |= {value.replace("/", "\\/") for value in secrets}
</code_context>
<issue_to_address>
**Authentication credentials escape body redaction**

When a task URL matches an entry in the filer's `.netrc` and the server echoes the resulting Basic credentials in an HTTP error body, requests can attach Basic credentials from `.netrc`, but `body_for_log` derives secrets only from the URL. When an HTTP error body echoes those credentials—such as in a Base64-encoded `Authorization` header—the filer logs them unredacted.

Redact the credentials actually used for the request, including `.netrc` credentials and encoded Basic authorization values, before logging the body.
</issue_to_address>

### Comment 3
<location path="src/tesk_core/filer.py" line_range="109" />
<code_context>
+        if req.status_code < 200 or req.status_code >= 300:
+            logging.error("Got status code: %d", req.status_code)
+            if req.text:
+                logging.error("Response body: %s", body_for_log(req.text, self.url))
+            return False
+        logging.debug("OK, got status code: %d", req.status_code)
</code_context>
<issue_to_address>
**Redirect tokens reach logs**

When a request follows a redirect to a URL with a distinct query token and the final error body repeats that token outside a URL, `_status_ok` passes the original `self.url` to `body_for_log`, so the final URL's token is not redacted and reaches the logs.

Pass the final response URL to `body_for_log` when redacting the error body.
</issue_to_address>

### Comment 4
<location path="src/tesk_core/transput.py" line_range="88-90" />
<code_context>
+    parts = urlsplit(url)
+    raw = [parts.username or "", parts.password or ""]
+    raw += [pair.partition("=")[2] for pair in parts.query.split("&")]
+    secrets = set(raw) | {unquote_plus(value) for value in raw}
+    # Also as JSON with escaped slashes, as some servers write it
+    secrets |= {value.replace("/", "\\/") for value in secrets}
+    for secret in sorted(secrets, key=len, reverse=True):
+        if len(secret) >= MIN_SECRET_LENGTH:
</code_context>
<issue_to_address>
**Normalized query secrets remain in logs**

When a user supplies an HTTP URL with a raw space or non-ASCII character in a query value and the server echoes its percent-encoded form outside a URL in an error body, `requests` can percent-encode raw spaces or non-ASCII query characters before sending the URL, but `body_for_log` only redacts the original and plus-decoded values. When an error body repeats the encoded value outside a URL, the filer logs that value unredacted.

Include the request library's normalized query-value representations in the body redaction, or redact query values using a context-aware URL parser.
</issue_to_address>

### Comment 5
<location path="src/tesk_core/filer.py" line_range="86" />
<code_context>
+        timeout = float(value)
+    except ValueError:
+        timeout = math.nan
+    if not math.isfinite(timeout) or timeout <= 0:
+        log_invalid_http_timeout()
+        return HTTP_TIMEOUT_DEFAULT
</code_context>
<issue_to_address>
**Large timeouts abort transfers**

When `FILER_HTTP_TIMEOUT` is finite and positive but exceeds the platform's supported socket timeout, `http_timeout()` accepts the value, then `requests.get` or `requests.put` raises an `OverflowError` while setting the socket timeout; the `RequestException` handlers do not catch it, so the filer exits instead of reporting a failed transfer.

Reject timeout values above the platform's supported socket timeout range and return the default.

Also at `src/tesk_core/filer.py:87`, `src/tesk_core/filer.py:89`, `src/tesk_core/filer.py:136`, `src/tesk_core/filer.py:160`.
</issue_to_address>

### Comment 6
<location path="src/tesk_core/filer.py" line_range="136" />
<code_context>
         try:
-            # No timeout, as before; transfers of large files can take long
-            req = requests.get(self.url)  # noqa: S113 -- see above
+            req = requests.get(self.url, timeout=http_timeout())
         except requests.exceptions.RequestException as err:
             return self._request_failed(err)
</code_context>
<issue_to_address>
**DNS stalls bypass timeout**

When DNS resolution for an HTTP(S) host stalls longer than the configured timeout, `requests.get` and `requests.put` apply their socket timeout only after hostname resolution, so the resolver stall leaves the filer blocked instead of failing the transfer.

Enforce a timeout that also covers hostname resolution.

Also at `src/tesk_core/filer.py:160`.
</issue_to_address>

Linked issues

#101 feat: harden filer HTTP handling and logging · 4 of 4 met

# Requirement Status Notes
1 Every filer requests call has a configurable timeout passed through the taskmaster, with a documented default. ✅ Met Both filer HTTP calls (GET and PUT) use http_timeout(), and Filer passes FILER_HTTP_TIMEOUT from the taskmaster environment; the 300-second default is documented.
2 The taskmaster's debug log contains no URL queries or user information from the task. ✅ Met Job manifests are logged through pprint, which redacts URLs in strings and URL fields, including task URLs in JSON_INPUT; the raw executor-manifest log is removed.
3 HTTP error bodies in the filer's log are truncated and contain no URL queries or user information. ✅ Met Non-empty error bodies are logged through body_for_log, which strips URLs, redacts request-derived query values and user information, and limits the logged body to 1000 characters.
4 Tests cover each point; the docs and upgrade notes describe the setting. ✅ Met The added tests cover timeout propagation and validation, redaction, truncation, and manifest logging; the filer and taskmaster docs and upgrade notes describe the timeout.

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and if a PUT reaches the server but the server takes longer than the timeout to respond, the filer can report failure even though the remote object was already written. That write survives a revert, though it is bounded and can generally be repaired by rerunning the upload.

Blocking findings: src/tesk_core/transput.py:92, src/tesk_core/transput.py:88, src/tesk_core/filer.py:109, src/tesk_core/transput.py:90, src/tesk_core/filer.py:86, and 1 more


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

Comment thread src/tesk_core/transput.py Resolved
Comment thread src/tesk_core/transput.py Resolved
Comment thread src/tesk_core/filer.py Resolved
Comment thread src/tesk_core/transput.py Resolved
Comment thread src/tesk_core/filer.py Resolved
Comment thread src/tesk_core/filer.py Resolved
Redact the query values of the URLs actually requested (normalized
and redirects) and the .netrc credentials sent, also as a Basic
authorization value; reject timeouts above 1000000 seconds, which
sockets can't take.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 8f827e0 into dev Nov 7, 2026
43 checks passed
@uniqueg
uniqueg deleted the feat/http-hardening branch November 7, 2026 16:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: harden filer HTTP handling and logging

1 participant