Repository navigation
fix: generate IDs and tokens with secrets - #70
Conversation
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]>
Reviewer's GuideUses of the APIHave repository, build, subscription, and user registration resolve their configured character sets through
ImplementationAdd a fixed, validated parser for charset settings and the helpers used to resolve and check them.
Generate IDs with
ConfigurationValidate charset settings during app startup before creating the admin user or repairing stored timestamps, and add a pointer to the configuration reference.
DocumentationDocument the supported charset forms, allowed characters, validation rules, and upgrade behavior.
TestsCover charset parsing and validation, startup failure before database writes, and configured-character behavior for generated IDs, tokens, and subscriptions.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
- 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]>
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 withsecrets.choiceinstead ofrandom.choice. It raises aValueErrorwhen no character is left for the start and end of values.pubgrade/charsets.py: the settingsendpoints.repository.id_charset,endpoints.user.uid_charsetandendpoints.access_token.charsetare read with a fixed lookup instead ofeval. A setting can be: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, '.', '-'];+, or listed in brackets;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.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/deployment.mdhas the settings in "Configuration" and a note in the upgrade notes. The image's values are unchanged.pubgrade/config.yamlhas 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.secrets.choiceis used and that repositories, users and subscriptions use the configured characters.create_app()before it writes to the database.mkdocs build --strict: passed.Review
Full review: adversarial and quality reviewers, two rounds each. All findings are fixed except the declined one below.
Declined review findings
generate_id()raises a plainValueError. Callers that go throughget_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:
Bug Fixes:
Enhancements:
Documentation:
Tests: