Skip to content

fix(scripts): harden citation.py - #431

Merged
uniqueg merged 4 commits into
devfrom
fix/harden-citation
Oct 23, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/harden-citation

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports the hardening of scripts/citation.py from proTES (commit 2294b1c, elixir-cloud-aai/protes#244), with its tests, so that the copies in proTES, FOCA and Cloud Registry stay consistent:

  • set writes through a temporary file with a new, unpredictable name (tempfile.mkstemp) in the same directory instead of the fixed .CITATION.cff.tmp, and keeps the file's permissions: a planted file or link is never written to, and concurrent runs don't collide.
  • check rejects versions that are not release versions, also if the file has the same one.
  • set --date refuses dates after today (UTC), which check would reject.
  • The docstrings describe these limits.

Beyond proTES (from Sourcery's review of the same change in elixir-cloud-aai/cloud-registry#191, to be ported back to proTES): the temporary file's mode is set with os.fchmod on its descriptor instead of by name.

The module docstring and the VERSION comment keep their wording here: unlike proTES, this repository has a release workflow, which checks the tag and then runs citation.py check. FOCA's import order and datetime.UTC are kept.

Closes #430

Verification

Locally (Python 3.12):

  • pytest tests/test_citation.py: 45 passed
  • coverage run -m pytest -m "not mongodb", coverage report: 1738 passed, 100% (no local MongoDB for the mongodb tests; CI runs them)
  • ruff check, ruff format --check, mypy: pass
  • ast-grep scan, semgrep scan --config .semgrep --error on the changed files: no findings
  • pre-commit run --all-files could not run (the sandbox cannot fetch the hook repositories); CI runs the lint job

CI: all checks pass on the last commit (lint, unit tests on Python 3.11-3.14 with MongoDB 7.0 and 8.0, lowest direct dependencies, integration tests, image scans, charts on kind, docs, Codecov patch/project).

Declined review findings

  • Mention in the --date help text that later dates are refused; and drop the assert not path.is_symlink() that cannot fail in the new test: both left as in proTES, to keep the copies identical (could be changed in all three later).
  • A symlinked CITATION.cff is replaced by a regular file: unchanged behaviour, the repository's file is no link.
  • Sourcery (on cloud-registry#191): replace could publish an entry substituted for the temporary file (whoever can do that can replace CITATION.cff directly); concurrent set runs overwrite each other (manual, one-off release step; the file is always complete and check verifies it); owner, ACLs and extended attributes are not kept (Git keeps none of them; the mode is kept).
  • Sourcery (here): check rejects tags with leading zeros (v1.2.3rc01) that the tag pattern of the release workflow accepts (intended: non-canonical, set never writes them, and the workflows are out of scope); os.fchmod is missing on Windows before Python 3.13 (release steps are documented for a POSIX shell); setuid/setgid bits may be lost (Git keeps none); concurrent set runs (as above).

🤖 Generated with Claude Code

Summary by Sourcery

Harden citation metadata updates and validation to make release-file handling safer and more consistent.

Bug Fixes:

  • Harden citation updates and validation against unsafe temporary files, invalid release versions, and future release dates.

Enhancements:

  • Preserve citation file permissions while replacing it atomically with an unpredictable temporary file.

Documentation:

  • Clarify that release dates cannot be in the future and document the stricter version validation.

Tests:

  • Add coverage for invalid versions, permission preservation, planted temporary links, and future-date rejection.

Port the hardening of the citation helper from proTES (commit
2294b1c in elixir-cloud-aai/protes#244), so that the copies stay
consistent:

- Write through a temporary file with a new, unpredictable name
  (tempfile.mkstemp), so that a planted file or link is never written
  to and concurrent runs don't share it; keep the file's permissions.
- Check that the version passed to check is a release version, also if
  the file has the same invalid one.
- Refuse set --date with a date after today (UTC), which check rejects.
- Describe these limits in the docstrings.

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

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR ports citation hardening into the repository: it makes writes safer and permission-preserving via descriptor-based temporary files and atomic replacement, and aligns set/check validation around release versions and UTC date limits, with focused regression tests.

Sequence diagram for hardened citation update

sequenceDiagram
    participant Caller
    participant Main as citation.main
    participant File as CITATION.cff
    participant Temp as TemporaryFile

    Caller->>Main: main(argv, path)
    Main->>File: read_text()
    Main->>Main: set_release()
    Main->>Temp: tempfile.mkstemp()
    Main->>Temp: os.fchmod()
    Main->>Temp: write()
    Main->>Temp: replace(path)
    Main->>Temp: unlink(missing_ok=True)
Loading

Flow diagram for citation validation limits

flowchart TD
    A["citation.main()"] --> B["Read CITATION.cff"]
    B --> C{"set or check?"}
    C -->|set| D["Validate date is not after today UTC"]
    D --> E["set_release()"]
    E --> F["Atomic permission-preserving write"]
    C -->|check| G["_check_version()"]
    G --> H["check_release()"]
    H --> I["Validate version and released date"]
Loading

File-Level Changes

Change Details Files
Harden citation updates against unsafe temporary-file handling while preserving file permissions.
  • Create an unpredictable temporary file in the citation file’s directory using mkstemp.
  • Apply the original permission bits through the temporary file descriptor with fchmod.
  • Write and atomically replace the target, cleaning up the temporary file on completion.
  • Add coverage for planted links, permission preservation, and cleanup behavior.
scripts/citation.py
tests/test_citation.py
Enforce release-version and non-future-date invariants consistently for checking and setting citations.
  • Reject non-release versions in check_release, even when the citation contains the same version.
  • Reject --date values later than the current UTC date before writing.
  • Update command and function docstrings to document the validation limits.
  • Add tests for invalid versions and future dates, including ensuring failed writes leave the citation unchanged.
scripts/citation.py
tests/test_citation.py

Possibly linked issues

  • fix(scripts): harden citation.py #430: The PR implements all requested fixes: unpredictable same-directory temporary files, preserved permissions, release-version checks, and future-date refusal.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (004fe8e) to head (1692a69).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #431   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        27           
  Lines         2869      2869           
=========================================
  Hits          2869      2869           
Flag Coverage Δ
test_unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Set the permissions of the temporary file with os.fchmod on its
descriptor instead of by path, so that a link put in its place is not
followed (Sourcery review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 23, 2026 10:23

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

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

## Individual Comments

### Comment 1
<location path="scripts/citation.py" line_range="179" />
<code_context>
+            differs or is missing, or `date-released` is missing, invalid or
+            later than `today`.
     """
+    _check_version(version)
     actual = _value(text, "version")
     if actual != version:
</code_context>
<issue_to_address>
**Accepted release tags fail citation check**

When a release tag has a leading-zero version component or prerelease number, such as `v1.2.3rc01`, `_check_version(version)` rejects the tag even though the release workflow accepts it, so `citation.py check` fails and stops the release job.

Make `_check_version` accept the versions allowed by the release tag gate, or align the two validations.
</issue_to_address>

### Comment 2
<location path="scripts/citation.py" line_range="212" />
<code_context>
     try:
-        temporary.write_text(text, encoding="utf-8")
+        with os.fdopen(descriptor, "w", encoding="utf-8") as file:
+            os.fchmod(file.fileno(), mode)
+            file.write(text)
         temporary.replace(path)
</code_context>
<issue_to_address>
**Windows set command crashes**

When the documented `set` command runs on Windows, `os.fchmod` raises `AttributeError` because it is unavailable on Windows, and `main` does not catch that exception, so the command exits with a traceback without updating the citation file.

Avoid calling `os.fchmod` on Windows and use a platform-supported way to handle the file mode.
</issue_to_address>

### Comment 3
<location path="scripts/citation.py" line_range="214" />
<code_context>
+        with os.fdopen(descriptor, "w", encoding="utf-8") as file:
+            os.fchmod(file.fileno(), mode)
+            file.write(text)
         temporary.replace(path)
     finally:
         temporary.unlink(missing_ok=True)
</code_context>
<issue_to_address>
**Concurrent sets overwrite citation state**

When two `set` processes target the same citation file with different versions or dates, both `main` calls can read the same starting file, compute different release metadata, and then replace it in succession; the earlier caller still returns success even though its requested version or date is gone.

Serialize `set` operations or verify the file has not changed since it was read before replacing it.
</issue_to_address>

### Comment 4
<location path="scripts/citation.py" line_range="212" />
<code_context>
     try:
-        temporary.write_text(text, encoding="utf-8")
+        with os.fdopen(descriptor, "w", encoding="utf-8") as file:
+            os.fchmod(file.fileno(), mode)
+            file.write(text)
         temporary.replace(path)
</code_context>
<issue_to_address>
**Setuid or setgid bits are lost**

When the existing citation file has setuid or setgid bits, `_write` applies the original mode before writing, and writing can clear those bits on POSIX; `temporary.replace(path)` then publishes a file without them.

Apply the original mode after writing the temporary file and before replacing the citation file.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if the script writes an incorrect version or release date, that value remains in the citation file after reverting the code, but it is bounded and can be corrected or regenerated. The new checks and safer atomic replacement do not introduce an apparent irreversible or externally consequential action.

Blocking findings: scripts/citation.py:179, scripts/citation.py:212, scripts/citation.py:214, scripts/citation.py:212


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

Comment thread scripts/citation.py Resolved
Comment thread scripts/citation.py Resolved
Comment thread scripts/citation.py Resolved
Comment thread scripts/citation.py Resolved
@uniqueg
uniqueg merged commit 2023e9d into dev Oct 23, 2026
22 checks passed
@uniqueg
uniqueg deleted the fix/harden-citation branch October 23, 2026 12:21
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.

1 participant