You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(utils)!: do not eval charset in generate_id - #268
First phase-2 PR of the v0.14.0 maintenance series. Builds on #267 (and #266, #265); the new commits are fix(utils)!: do not eval charset in generate_id and docs(utils): qualify generate_id entropy claim.
foca.utils.misc.generate_id() passed its charset argument to eval(). Apps read the charset from their config files (e.g., proTES, cloud-registry), so anybody able to change the config could execute arbitrary code.
charset is now used literally (duplicates are still ignored)
characters are drawn with secrets.choice() instead of random.choice()
charsets that look like the previously evaluated string module expressions (e.g., string.ascii_uppercase + string.digits) raise a ValueError with a hint, rather than silently producing IDs containing ., +, spaces etc.
length no longer accepts booleans
README updated; the docstring notes that secure sampling makes IDs unpredictable from previous ones, but that guessability depends on charset and length (defaults: ~36 bits, fine for resource IDs, not for secrets; thanks Copilot)
Breaking change: apps configuring charsets as expressions need to list the characters themselves:
This affects at least proTES (custom.controllers.post_task.task_id.charset) and cloud-registry (custom.endpoints.services.id.charset); both will fail loudly at ID generation with the hint above until updated.
Test-first: the updated tests/utils/test_misc.py failed against the old implementation (6 failures: literal use of charsets, expression rejection, boolean length), and passes with the new one (14 passed).
Replace setup.py and the requirements*.txt files with PEP 621 metadata
in pyproject.toml (setuptools backend). Distribution name, import
package and the `dev` and `docs` extras are unchanged.
- declare `requires-python = ">=3.10"` (3.9 is end of life)
- ship `py.typed` inside the package so the "Typed" classifier holds
- package only `foca*`, so `tests` is no longer installed into
site-packages; configure pytest `pythonpath` so tests still import
- declare `typing_extensions` as a runtime dependency (it is imported
by `foca.models.config`)
- drop the obsolete `typing` backport and the unused `toml`,
`mypy-extensions`, `types-urllib3`, `types-setuptools`, `pylint`,
`python-semantic-release` and `readthedocs-sphinx-ext`
- drop `setup_requires` and the setuptools-git based MANIFEST.in
- remove the stale semantic-release config from setup.cfg; move the
mypy config to pyproject.toml (flake8 config stays in setup.cfg until
ruff replaces it)
- install FOCA directly from the source tree in the Docker image
Closes#232
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Update runtime, dev and docs dependencies while staying on Connexion 2.
Ranges now allow minor/patch updates within the current major version.
- connexion >=2.15.1,<3: makes explicit what was already resolved
(2.15 is the only 2.x line compatible with Werkzeug 3)
- Flask >=3.1.3,<4 (fixes CVE-2026-27205); Flask-PyMongo 3.x
- cryptography >=50 (fixes six advisories in 44.x)
- flask-authz <2.8 (2.8+ hard-pins a vulnerable Flask)
- swagger-ui-bundle >=1.1 (Swagger UI 4; required by connexion 2.15)
- raise floors of celery, Flask-Cors, PyJWT, requests and dev/docs
tools (Sphinx >=8, sphinx-rtd-theme >=3)
pip-audit reports no known vulnerabilities for the updated set.
BREAKING CHANGE: FOCA now requires Flask 3. Apps using APIs removed in
Flask 3 (e.g. `flask.Markup`, `_app_ctx_stack`, custom JSON encoders)
need to be updated.
Closes#216
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Docker: default to python:3.13-slim-trixie (Debian 13), use
trixie-based images in CI, fix Dockerfile lint (`AS`, `ENV K=V`)
- examples: MongoDB 8.0, Python 3.13 images, drop obsolete compose
`version` key
- Read the Docs: Ubuntu 24.04 and Python 3.13; install only the
`docs` extra
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- update actions (Node 24 versions) and pin them by commit SHA
- split into lint/build, unit test, integration test and image jobs
- test Python 3.10-3.14 against MongoDB 8.0 (plus 3.13 on 7.0)
instead of 16 jobs with EOL MongoDB versions; upload coverage and
run the petstore integration tests once
- check that sdist and wheel build and pass `twine check`
- wait for the petstore app instead of sleeping; show logs on failure
- push Docker images only for pushes to `dev`, add Python 3.13/3.14
images and move `latest` to 3.13; skip image builds on PRs (the
integration job already builds one)
- restrict token permissions, cancel superseded PR runs, set job
timeouts, cache pip downloads
- replace the blanket `-W ignore::DeprecationWarning` with targeted
pytest filters for connexion's use of deprecated jsonschema APIs
- add Python 3.13 and 3.14 classifiers
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build sdist and wheel when a GitHub release is published, check that
the release tag matches the package version, and upload to PyPI via
trusted publishing from the `pypi` environment (no API token).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Weekly grouped updates for Python dependencies, GitHub Actions and the
Docker base image, targeting `dev`. Connexion major updates are ignored
until the Connexion 3 migration (#188).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Configure ruff for linting and formatting (line length 79, as used by
the existing code) with pycodestyle, Pyflakes, isort, pyupgrade,
pydocstyle (Google convention), Pylint, bugbear, simplify,
comprehensions and Ruff-specific rules. Complexity limits are left
disabled for now. Tests are exempt from docstring and magic-value
rules.
Run `ruff check` and `ruff format --check` in CI instead of flake8, and
add a pre-commit config with ruff and basic file hygiene hooks.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Automatic, behaviour-preserving fixes by `ruff check --fix`: PEP 585
and PEP 604 annotations (closes#231), sorted imports, docstring
whitespace, f-strings, and simplified conditionals and with-blocks.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
One-off reformat of all Python files with `ruff format` (Black style,
line length 79). No functional changes; one `type: ignore` comment was
moved back to the line it applies to.
Closes#237
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Docstrings (closes#239):
- add package, class and method docstrings where missing
- shorten multi-line summaries to one line (Google convention)
Linting (closes#238):
- chain exceptions raised in `except` blocks (`raise ... from exc`)
- replace mutable argument default in `_validate_jwt_public_key()`
- replace attribute probe with `hasattr()` and try/except/pass with
`contextlib.suppress()` in exception config validation
- merge nested `with` statements in tests; minor simplifications
Disable magic-value comparisons (PLR2004), which only flag HTTP status
codes and Casbin rule lengths, and docstring rules for docs and
examples.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`generate_id()` passed its `charset` argument to `eval()`, so a charset
read from a config file could execute arbitrary code. Use the charset
literally instead, and draw characters with `secrets.choice()` rather
than `random.choice()`.
Charsets that look like the previously evaluated `string` module
expressions (e.g., `string.ascii_uppercase + string.digits`) now raise
a `ValueError` with a hint, instead of silently producing IDs with
unexpected characters. `length` no longer accepts booleans.
BREAKING CHANGE: `charset` is no longer evaluated. Apps that configure
charsets as expressions (e.g., proTES, cloud-registry) need to list
the characters themselves, e.g.,
`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`.
Closes#242
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The PR removes code execution from generate_id configuration, switches ID sampling to secrets-based randomness with explicit validation and migration errors, documents the revised security/entropy contract, and simultaneously modernizes the repository’s tooling, dependency constraints, CI/release automation, containers, documentation, and typing/formatting across the codebase.
Sequence diagram for secure literal ID generation
sequenceDiagram
participant Config as Application config
participant Generate as generate_id
participant Secrets as secrets.choice
Config->>Generate: generate_id(charset, length)
Generate->>Generate: Validate charset and length
alt charset looks like string expression
Generate-->>Config: ValueError with migration hint
else valid literal charset
Generate->>Generate: Deduplicate charset
loop for each requested character
Generate->>Secrets: choice(charset)
Secrets-->>Generate: Selected character
end
Generate-->>Config: Return generated ID
end
Loading
File-Level Changes
Change
Details
Files
Make identifier generation safe and cryptographically stronger while preserving duplicate-character handling and providing migration diagnostics.
Remove charset eval-based execution and treat configured values literally.
Reject legacy string-module expressions with a migration-focused ValueError.
Use secrets.choice for unpredictable sampling and reject boolean lengths.
Update unit tests, README guidance, and entropy documentation for the new contract.
Remove evaluation of the charset argument so callers must provide a literal string of allowed characters, preventing code injection through configuration.
Make former string module expressions fail with a clear migration hint rather than silently generating IDs from the expression text.
✅
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!
Exclude the deliberately malformed YAML fixture from `check-yaml` and
keep Markdown hard line breaks in `trailing-whitespace`, so that
`pre-commit run --all-files` passes.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
One-off fixes by the `end-of-file-fixer` and `trailing-whitespace`
pre-commit hooks. No content changes.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Whitespace-containing legacy charset expressions bypass migration validation and silently produce identifiers from the wrong alphabet.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Reject legacy expressions with whitespace around attribute dots
foca/utils/misc.py:9
Valid legacy expressions such as string . digits bypass this pattern because Python allows whitespace around the attribute dot. Instead of raising the migration error, generate_id() samples the expression literally, producing letters, spaces, and punctuation rather than digits. Match optional whitespace around the dot and add whitespace variants to the expression-rejection tests.
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
<locationpath="foca/utils/misc.py"line_range="9" />
<code_context>
+
+# Matches charsets that look like expressions using the `string` module,
+# which were evaluated by previous versions of `generate_id()`
+_STRING_EXPRESSION = re.compile(r"\bstring\.[a-z_]+")
</code_context>
<issue_to_address>
**Literal charsets get rejected**
When a caller's literal charset contains a substring matching `string.<lowercase_or_underscore>`, `_STRING_EXPRESSION.search()` matches that substring anywhere in the charset, so `generate_id()` raises `ValueError` instead of generating an ID from the literal characters.
Recognize a legacy expression only when the whole charset matches it.
Also at `foca/utils/misc.py:46`.
</issue_to_address>
### Comment 2
<locationpath="foca/utils/misc.py"line_range="9" />
<code_context>
+
+# Matches charsets that look like expressions using the `string` module,
+# which were evaluated by previous versions of `generate_id()`
+_STRING_EXPRESSION = re.compile(r"\bstring\.[a-z_]+")
</code_context>
<issue_to_address>
**Legacy expressions become ID characters**
When a former `string` expression has whitespace around the attribute-access dot, `_STRING_EXPRESSION` requires `string.` with no whitespace, so `generate_id()` treats the expression as a literal charset and samples spaces and punctuation instead of the intended characters.
Allow whitespace around the dot when matching legacy `string` expressions.
</issue_to_address>
### Comment 3
<locationpath="tests/utils/test_misc.py"line_range="33" />
<code_context>
charset = "''.join([])"
- with pytest.raises(TypeError):+ res = generate_id(charset=charset, length=20)+ assert set(res) <= set(charset)++ def test_charset_digit_string(self):
</code_context>
<issue_to_address>
**Literal charset test accepts empty IDs**
When `generate_id` returns an empty string despite the requested length of 20, `test_charset_not_evaluated` passes when `generate_id` returns `""`, because the empty set is a subset of `charset`; a generator that produces no identifier therefore escapes this test.
Also assert that `len(res) == 20`.
</issue_to_address>
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and publishing a GitHub release now uploads the built distributions to PyPI using trusted publishing, so a faulty release can become externally available for users to install. Reverting the workflow stops future uploads but cannot fully retract an artifact that has already been published.
Detect former charset expressions by references to actual constants
of the `string` module, allowing whitespace around the dot, so that
literal charsets that merely contain `string.<name>` are accepted and
spaced-out expressions are still rejected. Assert ID lengths in tests
of literal charsets.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
First phase-2 PR of the v0.14.0 maintenance series. Builds on #267 (and #266, #265); the new commits are
fix(utils)!: do not eval charset in generate_idanddocs(utils): qualify generate_id entropy claim.foca.utils.misc.generate_id()passed itscharsetargument toeval(). Apps read the charset from their config files (e.g., proTES, cloud-registry), so anybody able to change the config could execute arbitrary code.charsetis now used literally (duplicates are still ignored)secrets.choice()instead ofrandom.choice()stringmodule expressions (e.g.,string.ascii_uppercase + string.digits) raise aValueErrorwith a hint, rather than silently producing IDs containing.,+, spaces etc.lengthno longer accepts booleanscharsetandlength(defaults: ~36 bits, fine for resource IDs, not for secrets; thanks Copilot)Breaking change: apps configuring charsets as expressions need to list the characters themselves:
This affects at least proTES (
custom.controllers.post_task.task_id.charset) and cloud-registry (custom.endpoints.services.id.charset); both will fail loudly at ID generation with the hint above until updated.Closes #242
Verification
Test-first: the updated
tests/utils/test_misc.pyfailed against the old implementation (6 failures: literal use of charsets, expression rejection, boolean length), and passes with the new one (14 passed).Locally (Python 3.13):
ruff check,ruff format --check,mypy focaclean.CI: all checks pass (run): ruff, mypy, build, unit tests incl. MongoDB-dependent tests on Python 3.10–3.14, petstore integration tests, Read the Docs.
Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Harden
generate_id()against configuration-driven code execution while improving identifier randomness, validation, and migration guidance.Bug Fixes:
generate_id()by treating configured charsets as literal character sets instead of evaluating them.stringmodule expressions with a clear migration error and disallow boolean lengths.Enhancements:
Documentation:
Tests: