Skip to content

fix: generate IDs and tokens with secrets - #70

Merged
uniqueg merged 6 commits into
devfrom
fix/secrets-ids
Nov 7, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/secrets-ids

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR moves generated identifiers and access tokens to standard practice and makes the character set settings sturdier to read.

  • generate_id() draws characters with secrets.choice instead of random.choice. It raises a ValueError when no character is left for the start and end of values.
  • New module pubgrade/charsets.py: the settings endpoints.repository.id_charset, endpoints.user.uid_charset and endpoints.access_token.charset are read with a fixed lookup instead of eval. A setting can be:
    • a list of named character sets (string.ascii_letters, string.ascii_lowercase, string.ascii_uppercase, string.digits, string.hexdigits) and literal characters, such as the image's [string.ascii_lowercase, string.digits, '.', '-'];
    • a string with such items joined by +, or listed in brackets;
    • a single name or quoted string;
    • plain literal characters.
      Literal characters are ASCII letters, digits, ., - and ~; repository identifiers, which also name the pods of builds, take lowercase letters, digits, . and - only. Each setting needs at least two characters.
  • The endpoints read the settings with get_charset().
  • create_app() checks the settings before anything else. A value that can't be used stops the app with an error naming the setting: an unknown or misspelt name, a name in quotes, a wrong type, other characters, or no character left for the start and end of values.
  • Docs: docs/deployment.md has the settings in "Configuration" and a note in the upgrade notes. The image's values are unchanged. pubgrade/config.yaml has a pointer comment.

Closes #69

Verification

  • make test (Python 3.13): 470 passed, 100% coverage. New tests:
    • tests/test_charsets.py: every form, the errors, and the image's configuration.
    • Tests that secrets.choice is used and that repositories, users and subscriptions use the configured characters.
    • A test that a bad setting stops create_app() before it writes to the database.
  • mkdocs build --strict: passed.
  • CI: all checks passed (including smoke and upgrade tests), CI passed.

Review

Full review: adversarial and quality reviewers, two rounds each. All findings are fixed except the declined one below.

Declined review findings

  • Quality, low: the guard in generate_id() raises a plain ValueError. Callers that go through get_charset() can't reach it, so no change is needed.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Harden generated identifiers and access tokens by using secure randomness, safe character-set configuration, and startup validation.

New Features:

  • Support configurable, validated character sets for repository IDs, user IDs, and access tokens using named Python character sets and literal characters.

Bug Fixes:

  • Generate identifiers and access tokens with cryptographically secure randomness and reject unusable character sets instead of relying on unsafe expression evaluation.

Enhancements:

  • Validate all identifier and token character-set settings during application startup and enforce repository-compatible characters.

Documentation:

  • Document the supported character-set configuration formats, validation rules, and upgrade considerations.

Tests:

  • Add coverage for character-set parsing, validation, secure generation, configured-character usage, and startup failure behavior.

uniqueg and others added 4 commits November 7, 2026 05:21
Add pubgrade.charsets: resolve_charset() reads a character set setting
as names of character sets (e.g., string.digits) and literal
characters, as a list, a string joined with +, a single name or
literal characters, without eval; check_charsets() checks the three
settings of the configuration.

Refs #69

Co-Authored-By: Claude Opus 5.5 <[email protected]>
generate_id() draws characters with secrets.choice instead of
random.choice, and the endpoints read the character set settings with
resolve_charset() instead of eval. The app checks the settings at start
and stops with an error naming a setting that can't be used. Document
the settings in the configuration reference and the upgrade notes.

Closes #69

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Read quoted strings and bracketed lists as whole values, with a
  tokenizer that respects quotes; reject strings that mention string.
  but can't be read.
- Allow only ASCII letters, digits, '.', '-', '~' and '_' as
  characters.
- Add get_charset() for the endpoints, and a guard in generate_id()
  against characters that can't start or end a value.
- Use monkeypatch for configuration changes in tests.
- Structure the configuration reference by form.

Refs #69

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Names of character sets in quotes, misspelt or without string. are
  errors instead of literal characters.
- Literal characters are ASCII letters, digits, '.', '-' and '~'.
- Quoted items are unquoted only as single strings without escapes.
- Name both forms in the error for unreadable strings.
- Test that subscriptions use the configured characters.

Refs #69

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

Have repository, build, subscription, and user registration resolve their configured character sets through get_charset().

  • pubgrade/modules/endpoints/builds.py L17, L142
  • pubgrade/modules/endpoints/repositories.py L58-62
  • pubgrade/modules/endpoints/subscriptions.py L6, L86
  • pubgrade/modules/endpoints/users.py L3, L54-58

Implementation

Add a fixed, validated parser for charset settings and the helpers used to resolve and check them.

  • pubgrade/charsets.py L1-239

Generate IDs with secrets.choice, reject unusable character sets, and keep the required imports and generation documentation with the implementation.

  • pubgrade/modules/endpoints/repositories.py L129-157 (+3 small edits)

Configuration

Validate charset settings during app startup before creating the admin user or repairing stored timestamps, and add a pointer to the configuration reference.

  • pubgrade/app.py L14, L57-58, L64-65
  • pubgrade/config.yaml L91-93

Documentation

Document the supported charset forms, allowed characters, validation rules, and upgrade behavior.

  • docs/deployment.md L59-81, L115-123

Tests

Cover charset parsing and validation, startup failure before database writes, and configured-character behavior for generated IDs, tokens, and subscriptions.

  • tests/pubgrade/endpoints/test_repositories.py L20, L122-176
  • tests/pubgrade/endpoints/test_subscriptions.py L123-137
  • tests/pubgrade/endpoints/test_users.py L3, L65-77
  • tests/test_app.py L12, L96-115
  • tests/test_charsets.py L1-185

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

@read-the-docs-community

read-the-docs-community Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35713674 | 📁 Comparing 4b78d77 against latest (146ad9b)

  🔍 Preview build  

1 file changed
± deployment/index.html

@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 100.00%. Comparing base (146ad9b) to head (4b78d77).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #70   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           15        16    +1     
  Lines         1135      1192   +57     
=========================================
+ Hits          1135      1192   +57     

☔ 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 November 7, 2026 04:42
@uniqueg
uniqueg requested a review from akash2237778 as a code owner November 7, 2026 04:42

@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="pubgrade/charsets.py" line_range="180" />
<code_context>
+            f"{setting}: characters {''.join(sorted(characters - ALLOWED))!r} "
+            f"not allowed; use ASCII letters, digits, '.', '-' and '~'"
+        )
+    if not usable("".join(characters)):
+        raise CharsetError(
+            f"{setting}: needs at least one character other than "
</code_context>
<issue_to_address>
**Access tokens become forgeable**

When a configured ID or access-token charset contains exactly one usable character, such as `a`, `resolve_charset()` only requires one character usable at the ends, so `generate_id()` repeats that character for every access token; anyone can forge those credentials and authenticate, while repeated IDs exhaust duplicate retries.

Reject charsets that have only one distinct character usable at the start and end of generated values.
</issue_to_address>

### Comment 2
<location path="pubgrade/charsets.py" line_range="41" />
<code_context>
+}
+
+# Characters that the settings may contain
+ALLOWED = frozenset(string.ascii_letters + string.digits + ".-~")
+
+# Characters that generated values never contain (`EXCLUDED`), or not at
</code_context>
<issue_to_address>
**Configured IDs break build pods**

When builds are enabled and `endpoints.repository.id_charset` includes uppercase letters or `~`, `build_id` is used directly as the Kubernetes `metadata.name`; uppercase letters and `~` are invalid in Kubernetes resource names, so builds with those generated characters fail when Kubernetes creates the build pod.

Restrict repository identifiers used for build resource names to Kubernetes-compatible characters, or normalize the build resource name before creating the pod.
</issue_to_address>

### Comment 3
<location path="tests/pubgrade/endpoints/test_users.py" line_range="73-74" />
<code_context>
+        monkeypatch.setitem(endpoints["access_token"], "charset", ["x", "y"])
+        with self.app.app_context():
+            response = register_user({"name": "Name"})
+        assert set(response["uid"]) <= set(string.ascii_uppercase)
+        assert set(response["user_access_token"]) <= {"x", "y"}
+
     def test_register_user_logs_no_token(self, caplog):
</code_context>
<issue_to_address>
**Empty registrations pass charset checks**

When `register_user` returns empty strings for the UID and access token, `test_register_user_charsets` checks only that each result’s character set is a subset of the configured characters; for an empty UID or token, `set("")` passes both assertions. The test therefore passes even when registration returns empty identifiers and tokens.

Assert that both generated values are nonempty (and, if intended here, have their configured lengths) before checking their characters.
</issue_to_address>

Linked issues

#69 fix: generate IDs and tokens with secrets · 4 of 4 met

# Requirement Status Notes
1 Draw characters with secrets.choice instead of random.choice in generate_id(). ✅ Met generate_id() uses secrets.choice.
2 Read the character set settings with a fixed lookup of named character sets plus literal characters, while keeping the current forms working. ✅ Met resolve_charset() uses a fixed NAMED lookup and handles lists, joined strings, bracketed strings, single names, quoted strings and literal characters; the endpoints use get_charset() instead of eval.
3 Check these settings at start, and stop with an error naming the setting if one can't be used. ✅ Met create_app() checks all three settings before creating admin users or repairing stored timestamps; errors include the setting name.
4 Document the settings in the configuration reference and the upgrade notes. ✅ Met docs/deployment.md documents the settings under Configuration and describes their constraints in the upgrade notes.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and this changes how access tokens are generated and how their configured character sets are interpreted. If a mistake makes tokens predictable, they could grant unauthorized access; reverting would stop future generation changes but would not undo access already obtained with issued tokens.

Blocking findings: pubgrade/charsets.py:180, pubgrade/charsets.py:41, tests/pubgrade/endpoints/test_users.py:74


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

Comment thread pubgrade/charsets.py Resolved
Comment thread pubgrade/charsets.py Resolved
Comment thread tests/pubgrade/endpoints/test_users.py Resolved
uniqueg and others added 2 commits November 7, 2026 05:48
- Each character set needs at least two characters.
- Repository identifiers, which also name the pods of builds, take
  lowercase letters, digits, '.' and '-' only.
- Tests check the length of generated values too.

Refs #69

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit a8a8b23 into dev Nov 7, 2026
31 checks passed
@uniqueg
uniqueg deleted the fix/secrets-ids branch November 7, 2026 04:59
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: generate IDs and tokens with secrets

1 participant