Skip to content

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

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

uniqueg merged 2 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, 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 (scripts/release_version.py) and then runs citation.py check.

Closes #190

Verification

Locally (Python 3.13):

  • coverage run --source cloud_registry,scripts -m pytest -W ignore::DeprecationWarning, coverage report -m: 859 passed, 210 skipped (no local MongoDB), 100% (scripts/citation.py 100%)
  • 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 it

CI: all checks pass on the last commit (tests with mongomock and MongoDB 7.0, static code analysis, docs, Helm chart, image scan, CodeQL, 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: 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).

🤖 Generated with Claude Code

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

Hardens citation updates by using secure, permission-preserving atomic writes and adds validation that versions are release versions and dates are not in the future, with focused regression tests and updated documentation.

Sequence diagram for hardened citation update

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

    Caller->>Main: main(argv, path)
    Main->>Main: set_release(text, version, date)
    Main->>Temp: mkstemp(prefix, suffix, dir)
    Temp-->>Main: descriptor, name
    Main->>Main: os.fdopen(descriptor).write(text)
    Main->>Main: Path.chmod(mode)
    Main->>File: temporary.replace(path)
    Main->>Main: temporary.unlink(missing_ok=True)
Loading

Flow diagram for citation validation

flowchart TD
    Start([citation.main]) --> Command{command}
    Command -->|set| Date[Select args.date or today]
    Date --> Future{date > today}
    Future -->|yes| RejectDate[Raise ValueError]
    Future -->|no| Set[set_release]
    Set --> Write[_write]
    Command -->|check| Check[check_release]
    Check --> Version[_check_version]
    Version --> Release{Release version?}
    Release -->|no| RejectVersion[Raise ValueError]
    Release -->|yes| Compare[Validate version and date]
    Compare --> Result([Return success])
    Write --> Result
Loading

File-Level Changes

Change Details Files
Harden atomic citation-file replacement against planted temporary files, symlinks, and concurrent runs while preserving permissions.
  • Create a uniquely named temporary file in the citation file's directory with tempfile.mkstemp.
  • Write through the returned descriptor, apply the original mode, atomically replace the target, and clean up the temporary path.
  • Add tests verifying a planted temporary symlink is untouched, permissions are retained, and temporary files are cleaned up.
scripts/citation.py
tests/test_citation.py
Enforce release-version and date constraints consistently for citation validation and updates.
  • Validate the requested version as a release version before comparing it with the file.
  • Reject future --date values in set using the current UTC date, with no file modification.
  • Document the version and date restrictions and test invalid versions and future dates.
scripts/citation.py
tests/test_citation.py

Assessment against linked issues

Issue Objective Addressed Explanation
#190 Make set write through a uniquely named temporary file in the same directory, without overwriting planted files or links, and preserve the existing file’s permissions. ✅
#190 Make check reject non-release versions even when the requested version matches the file, and make set --date reject dates later than today in UTC. ✅
#190 Update the relevant docstrings to describe the version and date constraints and the safer write behavior. ✅

Possibly linked issues

  • fix(scripts): harden citation.py #190: The PR implements the issue’s requested changes: unpredictable temporary files, preserved permissions, release-version validation, and future-date rejection.

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 (f4a8acd) to head (064c72a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #191   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           14        14           
  Lines          906       917   +11     
=========================================
+ Hits           906       917   +11     

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

@uniqueg
uniqueg marked this pull request as ready for review October 23, 2026 03:21

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

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

## Individual Comments

### Comment 1
<location path="scripts/citation.py" line_range="212" />
<code_context>
-        temporary.write_text(text, encoding="utf-8")
+        with os.fdopen(descriptor, "w", encoding="utf-8") as file:
+            file.write(text)
+        temporary.chmod(mode)
         temporary.replace(path)
     finally:
</code_context>
<issue_to_address>
**Attacker changes arbitrary permissions**

When a privileged `set` runs while an attacker can modify the parent directory, `temporary.chmod(mode)` follows a substituted symlink, and `temporary.replace(path)` can publish the substituted entry, so the attacker changes an arbitrary target’s permissions or replaces the citation file.

Use descriptor-based permission changes and a replacement strategy that cannot follow or publish an attacker-substituted temporary path.
</issue_to_address>

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

When two `set` processes read the same citation file and request different release metadata before either replaces it, `main` builds both outputs from the same snapshot, and `_write` replaces the file without serialization or checking for intervening updates; the later replacement discards the earlier successful update.

Serialize updates to each citation file or reject a replacement when its source snapshot is stale.
</issue_to_address>

### Comment 3
<location path="scripts/citation.py" line_range="213" />
<code_context>
+        with os.fdopen(descriptor, "w", encoding="utf-8") as file:
+            file.write(text)
+        temporary.chmod(mode)
         temporary.replace(path)
     finally:
         temporary.unlink(missing_ok=True)
</code_context>
<issue_to_address>
**File access metadata is lost**

When the original file has custom ownership, ACLs or extended attributes that differ from the temporary file, `_write` creates a new inode and copies only the mode bits, so replacing the original loses its owner, group, custom ACLs and extended attributes; collaborators relying on that metadata receive different access.

Preserve the original file’s ownership, ACLs and extended attributes on the temporary file before replacing it.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if the new checks or write logic are wrong, set could leave an incorrect version or release date in CITATION.cff; that value is bounded and can be corrected in the file. Reverting the script would not undo a file it has already written.

Blocking findings: scripts/citation.py:212, scripts/citation.py:213, scripts/citation.py:213


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
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 merged commit e0dc51d into dev Oct 23, 2026
17 checks passed
@uniqueg
uniqueg deleted the fix/harden-citation branch October 23, 2026 10:24
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.

fix(scripts): harden citation.py

1 participant