Skip to content

fix(auth): add cleanup command for stale SIWE nonces#795

Open
web3blind wants to merge 2 commits into
genlayer-foundation:devfrom
web3blind:fix/cleanup-stale-nonces
Open

fix(auth): add cleanup command for stale SIWE nonces#795
web3blind wants to merge 2 commits into
genlayer-foundation:devfrom
web3blind:fix/cleanup-stale-nonces

Conversation

@web3blind

@web3blind web3blind commented Jun 14, 2026

Copy link
Copy Markdown

Closes #452.

SIWE authentication nonces are created for each auth attempt and are no longer useful once they are used or expired. Today they can remain in the database indefinitely, which creates avoidable storage growth and keeps stale auth material around longer than needed.

Changes:

  • Add ethereum_auth management command cleanup_nonces.
  • Delete only stale nonces after a configurable grace period: (used OR expired) AND expires_at <= now - hours.
  • Add --dry-run support so operators can preview cleanup impact before deleting rows.
  • Add focused Django tests for deletion behavior, dry-run behavior, and invalid retention input.

Verified:

  • python3 -m py_compile backend/ethereum_auth/management/commands/cleanup_nonces.py backend/ethereum_auth/tests.py
  • git diff --check

Note: I could not run the full Django test command locally because this environment only has Python 3.11 while the backend requirements pin Django 6, and Docker is not available to this user (permission denied on the Docker socket). The added test coverage is included for CI / a Python 3.12+ dev environment.

Summary by CodeRabbit

  • New Features
    • Added a Django management command to clean up stale SIWE nonces using a configurable --hours retention window, with --dry-run to preview deletions.
  • Bug Fixes
    • Improved --hours validation by rejecting negative, non-finite (NaN/±inf), and excessively large values.
  • Tests
    • Added command tests confirming only expired and/or previously used stale nonces are removed, --dry-run does not delete, and invalid inputs raise errors.
  • Documentation
    • Documented command usage for preview and cleanup modes.

@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 2709f287-97b7-47d1-9ec2-bafe4f275349

📥 Commits

Reviewing files that changed from the base of the PR and between a2e22ee and 1fc489a.

📒 Files selected for processing (3)
  • backend/CLAUDE.md
  • backend/ethereum_auth/management/commands/cleanup_nonces.py
  • backend/ethereum_auth/tests.py

📝 Walkthrough

Walkthrough

A new Django management command cleanup_nonces is added that queries Nonce records where used=True or expires_at is past, filtered further by a configurable grace-period cutoff (--hours, default 1). A --dry-run flag reports the count without deleting. Three tests cover deletion behavior, dry-run reporting, and rejection of invalid hour values.

Changes

cleanup_nonces Management Command

Layer / File(s) Summary
cleanup_nonces command: CLI options and execution logic
backend/ethereum_auth/management/commands/cleanup_nonces.py, backend/CLAUDE.md
Introduces the Command class with --hours (float, default 1) and --dry-run arguments. handle() validates that hours is finite and non-negative, computes a cutoff timestamp, builds a queryset of stale Nonce records (used=True OR already expired, both older than the cutoff), then either prints the count (dry-run) or deletes the rows and prints the deleted count. Documentation describes command usage and grace period behavior.
CleanupNoncesCommandTests test suite
backend/ethereum_auth/tests.py
Adds StringIO and CommandError imports. Introduces CleanupNoncesCommandTests with a _nonce factory helper and three tests: deletion of only stale (used/expired) nonces while preserving recent/active ones, dry-run reporting without deletion, and CommandError on negative or non-finite --hours values.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding a cleanup command for stale SIWE nonces, which is the primary objective of the PR.
Linked Issues check ✅ Passed The PR fully implements all coding requirements from issue #452: management command with --hours and --dry-run flags, validation of invalid inputs, and proper deletion logic for expired/used nonces.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the cleanup command for stale SIWE nonces as specified in issue #452. No extraneous modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/ethereum_auth/management/commands/cleanup_nonces.py`:
- Around line 27-31: The hours parameter validation in the cleanup_nonces
command only checks if hours is negative, but since type=float is used, nan and
inf values can bypass this check and cause ValueError or OverflowError when
passed to timedelta(hours=hours). Update the validation guard that checks if
hours < 0 to also use math.isfinite(hours) to reject non-finite values, ensuring
a proper CommandError is raised instead of a traceback. Additionally, add a
regression test to verify that nan and inf values are properly rejected, and
update backend/CLAUDE.md to document this management command in the Common
Commands section.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: a791d14d-8919-420a-9291-7c12acfaf09b

📥 Commits

Reviewing files that changed from the base of the PR and between 1b6c433 and 09a98e4.

📒 Files selected for processing (4)
  • backend/ethereum_auth/management/__init__.py
  • backend/ethereum_auth/management/commands/__init__.py
  • backend/ethereum_auth/management/commands/cleanup_nonces.py
  • backend/ethereum_auth/tests.py

@web3blind

Copy link
Copy Markdown
Author

Addressed CodeRabbit feedback in b1990df: validates non-finite --hours values (nan/inf), extends the regression test, and documents cleanup_nonces in backend/CLAUDE.md Common Commands.\n\nValidation: python3 -m py_compile backend/ethereum_auth/management/commands/cleanup_nonces.py backend/ethereum_auth/tests.py; git diff --check. Full Django tests still need Python 3.12+ / CI because this local environment only has Python 3.11 while Django 6 is pinned.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/ethereum_auth/management/commands/cleanup_nonces.py`:
- Line 32: Very large finite values for the `--hours` parameter pass the
`isfinite()` check but cause an `OverflowError` when passed to
`timedelta(hours=hours)`, resulting in an unhandled exception instead of a
controlled error. Wrap the `timedelta(hours=hours)` call at line 32 in a
try-catch block that catches `OverflowError` and raises a `CommandError` with a
clear message indicating that the hours value is too large, converting the
unhandled exception into a user-friendly error response.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4545d97f-8585-4225-b389-4e1a3bdc8e52

📥 Commits

Reviewing files that changed from the base of the PR and between 09a98e4 and b1990df.

📒 Files selected for processing (3)
  • backend/CLAUDE.md
  • backend/ethereum_auth/management/commands/cleanup_nonces.py
  • backend/ethereum_auth/tests.py

Comment thread backend/ethereum_auth/management/commands/cleanup_nonces.py Outdated
@web3blind web3blind force-pushed the fix/cleanup-stale-nonces branch from b1990df to cbba789 Compare June 14, 2026 13:40
@web3blind

Copy link
Copy Markdown
Author

Addressed the new CodeRabbit feedback in cbba789: wraps the timedelta(hours=hours) calculation and converts OverflowError for very large finite values into a CommandError, plus extends the invalid-hours regression coverage with a large finite value (1e20).\n\nValidation: python3 -m py_compile backend/ethereum_auth/management/commands/cleanup_nonces.py backend/ethereum_auth/tests.py; git diff --check; confirmed timedelta(hours=1e20) triggers OverflowError locally.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/CLAUDE.md`:
- Around line 476-480: The documentation for the cleanup_nonces command in
backend/CLAUDE.md is incomplete. Currently it shows examples for --dry-run and
default execution, but lacks documentation for the --hours parameter that allows
operators to configure a custom retention window. Add an example showing how to
invoke the cleanup_nonces command with the --hours flag to demonstrate the
configurable retention-window path that was introduced in this PR.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4ac94f63-b0d3-4ff2-b9d3-493131d0c493

📥 Commits

Reviewing files that changed from the base of the PR and between b1990df and cbba789.

📒 Files selected for processing (3)
  • backend/CLAUDE.md
  • backend/ethereum_auth/management/commands/cleanup_nonces.py
  • backend/ethereum_auth/tests.py

Comment thread backend/CLAUDE.md
@web3blind web3blind force-pushed the fix/cleanup-stale-nonces branch from cbba789 to a2e22ee Compare June 14, 2026 14:08
@web3blind

Copy link
Copy Markdown
Author

Addressed the latest CodeRabbit documentation feedback in a2e22ee: added a Common Commands example for the custom retention-window path with .\n\nValidation: python3 -m py_compile backend/ethereum_auth/management/commands/cleanup_nonces.py backend/ethereum_auth/tests.py; git diff --check.

@web3blind

Copy link
Copy Markdown
Author

Correction for the previous comment: the shell stripped the inline command while posting.

Addressed the latest CodeRabbit documentation feedback in a2e22ee: added a Common Commands example for the custom retention-window path:

python manage.py cleanup_nonces --hours 24

Validation: python3 -m py_compile backend/ethereum_auth/management/commands/cleanup_nonces.py backend/ethereum_auth/tests.py; git diff --check.

@web3blind web3blind force-pushed the fix/cleanup-stale-nonces branch from a2e22ee to 1fc489a Compare June 14, 2026 14:26
@web3blind

Copy link
Copy Markdown
Author

I did one more consistency pass over the command, tests, and CLAUDE.md after CodeRabbit approval and found one small ambiguity: the docs/help text said "used or expired" while the query was effectively expiry-threshold based.

Updated in 1fc489a:

  • made the cleanup predicate explicit: delete nonces expired before the threshold, or used nonces created before the threshold;
  • updated tests to cover an old used nonce with a future expiry and a recent used nonce that should be retained;
  • tightened CLAUDE.md/help wording so the documented behavior matches the implementation.

Validation: python3 -m py_compile backend/ethereum_auth/management/commands/cleanup_nonces.py backend/ethereum_auth/tests.py; git diff --check; changed-file secret scan found no findings.

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.

[Enhancement] Add automatic cleanup for expired authentication nonces

1 participant