-
Notifications
You must be signed in to change notification settings - Fork 593
Feat: Add SHA-256 hashing option #988
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Pouyanpi
merged 5 commits into
NVIDIA-NeMo:develop
from
datarobot-forks:feature/enable-fips-support
Feb 27, 2025
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
mdambski marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # Hashing settings | ||
|
|
||
| ## Overview | ||
|
|
||
| Nemo Guardrails uses hashing mainly for caching purposes. By default, the `md5` hashing algorithm is used. Caching of search queries is disabled by default, but this does not disable it entirely. | ||
|
|
||
| ## FIPS considerations | ||
|
|
||
| In some regulated environments, the `md5` hashing algorithm may not be available (e.g., FIPS-compliant Python). In such cases, `sha256` hashing will be used instead. This default applies across the library unless explicitly overridden. | ||
|
|
||
| ## Setting hashing algorithm | ||
|
|
||
| To explicitly set the hashing algorithm, call the following function before running the Nemo Guardrails library code: | ||
|
|
||
| ```python | ||
| from nemoguardrails.hashing import set_default_hash_algorithm | ||
| set_default_hash_algorithm('sha256') | ||
| ``` | ||
|
|
||
| ## Additional considerations | ||
|
|
||
| When caching is enabled and `key_generator` is set in the configuration, it overrides the library default for caching embedding searches. | ||
|
|
||
| Example: | ||
|
|
||
| ```yaml | ||
| knowledge_base: | ||
| embedding_search_provider: | ||
| name: default | ||
| parameters: | ||
| embedding_engine: FastEmbed | ||
| embedding_model: all-MiniLM-L6-v2 | ||
| use_batching: False | ||
| max_batch_size: 10 | ||
| max_batch_hold: 0.01 | ||
| search_threshold: None | ||
| cache: | ||
| enabled: True | ||
| key_generator: sha256 # <- Overrides the library default. | ||
| store: filesystem | ||
| store_config: {} | ||
| ``` |
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
mdambski marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import hashlib | ||
|
|
||
| _default_hash_algorithm: str | ||
|
|
||
|
|
||
| def set_default_hash_algorithm(algorithm: str): | ||
| """ | ||
| Set the default hash algorithm. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| algorithm : str | ||
| The name of the hash algorithm to set as default. | ||
| The available options are: "md5", "sha256". | ||
|
|
||
| Raises | ||
| ------ | ||
| ValueError | ||
| If the provided algorithm is not supported. | ||
| """ | ||
| _supported = {"md5", "sha256"} | ||
|
|
||
| if algorithm not in _supported: | ||
| raise ValueError( | ||
| f"Unsupported value: {algorithm}, " f"use one of {','.join(_supported)}" | ||
| ) | ||
|
|
||
| global _default_hash_algorithm | ||
| _default_hash_algorithm = algorithm | ||
|
|
||
|
|
||
| def get_default_hash_algorithm() -> str: | ||
| """Returns the default hash algorithm based on the system configuration.""" | ||
| return _default_hash_algorithm | ||
|
|
||
|
|
||
| def generate_hash(text: str) -> str: | ||
| """ | ||
| Get the hash of a given text using the default hash function. | ||
|
|
||
| Args: | ||
| text (str): The text to hash. | ||
|
|
||
| Returns: | ||
| str: The hash of the text. | ||
| """ | ||
| hash_func = getattr(hashlib, _default_hash_algorithm) | ||
| return hash_func(text.encode()).hexdigest() | ||
|
|
||
|
|
||
| def _is_md5_available() -> bool: | ||
| """ | ||
| Check if MD5 usage is allowed. In some FIPS-compliant Python builds, the MD5 hashing | ||
| function may be missing or raise an exception when using OpenSSL compiled in FIPS mode. | ||
|
|
||
| When MD5 is not available, AttributeError will be raised for missing hashlib.md5. | ||
| When OpenSSL is compiled in FIPS mode, the _hashlib.UnsupportedDigestmodError(ValueError) | ||
| will be raised. | ||
|
|
||
| Returns | ||
| ------- | ||
| bool | ||
| True if MD5 is available, False otherwise. | ||
| """ | ||
| try: | ||
| hashlib.md5() | ||
| return True | ||
| except (AttributeError, ValueError): | ||
| return False | ||
|
|
||
|
|
||
| def detect_default_hash_algorithm(): | ||
| set_default_hash_algorithm("md5" if _is_md5_available() else "sha256") | ||
|
|
||
|
|
||
| detect_default_hash_algorithm() |
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
mdambski marked this conversation as resolved.
Show resolved
Hide resolved
|
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
mdambski marked this conversation as resolved.
Show resolved
Hide resolved
|
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
mdambski marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| define user ask capabilities | ||
| "What can you do?" | ||
| "What can you help me with?" | ||
| "tell me what you can do" | ||
| "tell me about you" | ||
|
|
||
| define bot inform capabilities | ||
| "I am an AI assistant that helps answer questions." | ||
|
|
||
| define flow | ||
| user ask capabilities | ||
| bot inform capabilities |
mdambski marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| models: | ||
| - type: main | ||
| engine: openai | ||
| model: gpt-3.5-turbo-instruct | ||
|
|
||
| core: | ||
| embedding_search_provider: | ||
| name: default | ||
| parameters: | ||
| embedding_engine: openai | ||
| embedding_model: text-embedding-ada-002 | ||
| cache: | ||
| enabled: True | ||
| key_generator: sha256 | ||
|
|
||
| knowledge_base: | ||
| embedding_search_provider: | ||
| name: default | ||
| parameters: | ||
| embedding_engine: openai | ||
| embedding_model: text-embedding-ada-002 | ||
| cache: | ||
| enabled: True | ||
| key_generator: sha256 |
mdambski marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from unittest.mock import patch | ||
|
|
||
| import pytest | ||
| from _hashlib import UnsupportedDigestmodError | ||
|
|
||
| from nemoguardrails.hashing import detect_default_hash_algorithm as setup_hashing | ||
| from nemoguardrails.hashing import ( | ||
| generate_hash, | ||
| get_default_hash_algorithm, | ||
| set_default_hash_algorithm, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="function") | ||
| def md5_is_missing(): | ||
| """Raise an exception when hashlib.md5 is not available.""" | ||
| with patch("hashlib.md5", side_effect=AttributeError): | ||
| setup_hashing() | ||
| yield | ||
|
|
||
| # cleanup | ||
| setup_hashing() | ||
|
|
||
|
|
||
| @pytest.fixture(scope="function") | ||
| def md5_unsupported_digest(): | ||
| """Raise an exception when hashlib is using OpenSSL compiled in FIPS mode.""" | ||
| with patch("hashlib.md5", side_effect=UnsupportedDigestmodError): | ||
| setup_hashing() | ||
| yield | ||
|
|
||
| # cleanup | ||
| setup_hashing() | ||
|
|
||
|
|
||
| @pytest.fixture(params=["md5_is_missing", "md5_unsupported_digest"]) | ||
| def md5_not_available(request): | ||
| yield request.getfixturevalue(request.param) | ||
|
|
||
|
|
||
| def test_default_without_md5(md5_not_available): | ||
| assert get_default_hash_algorithm() == "sha256" | ||
|
|
||
|
|
||
| def test_default_with_md5(): | ||
| assert get_default_hash_algorithm() == "md5" | ||
|
|
||
|
|
||
| def test_hash_without_md5(md5_not_available): | ||
| hash_value = generate_hash("test") | ||
| assert isinstance(hash_value, str) | ||
| assert len(hash_value) == 64 # SHA256 hash is 64 characters long | ||
|
|
||
|
|
||
| def test_hash_with_md5(): | ||
| hash_value = generate_hash("test") | ||
| assert isinstance(hash_value, str) | ||
| assert len(hash_value) == 32 # MD5 hash is 32 characters long | ||
|
|
||
|
|
||
| def test_invalid_hash_algorithm_not_allowed(): | ||
| with pytest.raises(ValueError): | ||
| set_default_hash_algorithm("invalid") |
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.
Uh oh!
There was an error while loading. Please reload this page.