Skip to content

Use cryptographically secure random for new document ids#1162

Open
probicheaux wants to merge 1 commit intogoogleapis:mainfrom
probicheaux:main
Open

Use cryptographically secure random for new document ids#1162
probicheaux wants to merge 1 commit intogoogleapis:mainfrom
probicheaux:main

Conversation

@probicheaux
Copy link

Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

  • Make sure to open an issue as a bug/issue before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
  • Ensure the tests and linter pass
  • Code coverage does not decrease (if any source code was changed)
  • Appropriate docs were updated (if necessary)

Fixes #1161

@probicheaux probicheaux requested review from a team as code owners February 5, 2026 04:38
@probicheaux probicheaux requested a review from a team February 5, 2026 04:38
@google-cla
Copy link

google-cla bot commented Feb 5, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@product-auto-label product-auto-label bot added size: xs Pull request size is extra small. api: firestore Issues related to the googleapis/python-firestore API. labels Feb 5, 2026
@gemini-code-assist
Copy link

Summary of Changes

Hello @probicheaux, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the security posture of automatically generated Firestore document IDs by switching to a cryptographically secure random number generator. This change ensures that document IDs are more robust against prediction and potential exploits, while also maintaining compatibility with diverse operating environments through a thoughtful fallback mechanism.

Highlights

  • Enhanced Security for Document IDs: The generation of new document IDs now utilizes random.SystemRandom, a cryptographically secure pseudo-random number generator, to improve the unpredictability and security of auto-generated IDs.
  • Robust Fallback Mechanism: A try-except block has been introduced to handle NotImplementedError that might occur on very old Unix systems lacking os.urandom. In such cases, the system gracefully falls back to using random.choice.
Changelog
  • google/cloud/firestore_v1/base_collection.py
    • Imported random.SystemRandom and initialized a global instance system_random for use in ID generation.
    • Modified the _auto_id function to use system_random.choice for selecting characters, ensuring cryptographic randomness.
    • Wrapped the system_random.choice call in a try-except NotImplementedError block to provide a fallback to random.choice if os.urandom is not available on the system.
Activity
  • No specific activity (comments, reviews, etc.) has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request improves security by using a cryptographically secure random number generator (random.SystemRandom) for creating new document IDs. The change includes a fallback to the standard random module for compatibility with older systems.

However, the unit tests for _auto_id have not been updated to reflect this change, which is a critical issue that needs to be addressed. I've also included a suggestion to refactor the _auto_id function to reduce code duplication and improve maintainability.

Comment on lines +627 to +631
try:
return "".join(system_random.choice(_AUTO_ID_CHARS) for _ in range(20))
# Very old Unix systems don't have os.urandom (/dev/urandom), in which case use random.choice
except NotImplementedError:
return "".join(random.choice(_AUTO_ID_CHARS) for _ in range(20))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The existing unit test test__auto_id in tests/unit/v1/test_base_collection.py mocks random.choice. With this change, the test will likely fail as the code now primarily calls system_random.choice. The tests need to be updated to cover both the primary path (using system_random.choice) and the fallback path (using random.choice when NotImplementedError is raised).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

Comment on lines +627 to +631
try:
return "".join(system_random.choice(_AUTO_ID_CHARS) for _ in range(20))
# Very old Unix systems don't have os.urandom (/dev/urandom), in which case use random.choice
except NotImplementedError:
return "".join(random.choice(_AUTO_ID_CHARS) for _ in range(20))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While the current implementation is correct, it contains duplicated code for generating the random string. To improve maintainability, you could refactor this to select the appropriate random function first, and then use it to generate the string.

    try:
        # Use a cryptographically secure random number generator if available.
        # The .random() method will raise NotImplementedError on systems without os.urandom().
        system_random.random()
        choice_func = system_random.choice
    except NotImplementedError:
        # Fallback to the default pseudo-random generator on very old systems.
        choice_func = random.choice

    return "".join(choice_func(_AUTO_ID_CHARS) for _ in range(20))

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is slower

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, this is slower

@product-auto-label product-auto-label bot added size: s Pull request size is small. and removed size: xs Pull request size is extra small. labels Feb 5, 2026
Copy link
Contributor

@daniel-sanche daniel-sanche left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change looks good to me, but I think the coverage check will likely fail, because the new except case isn't covered by unit tests. So you'll likely have to add a new one, with random.SystemRandom mocked to raise an exception

I triggered the CI tests, so we'll see what comes up

Thanks for submitting this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: firestore Issues related to the googleapis/python-firestore API. size: s Pull request size is small.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cryptographically Insecure Random Document IDs (which can lead to database collisions)

4 participants