Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
known_cli_path,
load_config,
)
from th_cli.exceptions import ConfigurationError


# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -231,19 +232,19 @@ def test_falls_back_to_defaults_when_no_files(self, tmp_path):
assert isinstance(result, Config)
assert result.hostname == "localhost"

def test_skips_malformed_config_json(self, tmp_path):
def test_raises_on_malformed_config_json(self, tmp_path):
config_file = tmp_path / "config.json"
config_file.write_text("{this is: not valid json}")

good_dir = tmp_path / "good"
good_dir.mkdir()
good_config = good_dir / "config.json"
good_config.write_text(json.dumps({"hostname": "goodserver"}))
(good_dir / "config.json").write_text(json.dumps({"hostname": "goodserver"}))

with patch("th_cli.config.get_config_search_paths", return_value=[tmp_path, good_dir]):
result = load_config()
with pytest.raises(ConfigurationError) as exc_info:
load_config()

assert isinstance(result, Config)
assert str(config_file) in exc_info.value.message

def test_handles_config_json_with_comments_in_example(self, tmp_path):
"""config.json.example may have comment lines (# ...)."""
Expand Down
13 changes: 9 additions & 4 deletions th_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
# limitations under the License.
#
import json
import sys
from enum import Enum
from pathlib import Path

from pydantic import BaseModel

from th_cli.exceptions import CLIError
from th_cli.exceptions import ConfigurationError


def known_cli_path() -> Path:
Expand Down Expand Up @@ -120,8 +121,7 @@ def load_config():
try:
return Config.model_validate_json(config_path.read_text(encoding="utf-8"))
except Exception as e:
CLIError(f"Could not load config from {config_path}: {e}")
continue
raise ConfigurationError(f"Could not load config from {config_path}: {e}") from e

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Security & Privacy · Quick win

Supported by static analysis

Script executed:

sed -n 1,170p th_cli/config.py
git diff adb4fedd5e86fa4a7b81d4e80ea1ff6331942b69 e213096057383a3fb7852cb318075579bfc697e5 -- th_cli/config.py
rg -n -i 'password|secret|wifi' th_cli/config.py

Repository: project-chip/certification-tool-cli

Length of output: 6729


Script executed:

git diff adb4fedd5e86fa4a7b81d4e80ea1ff6331942b69 e213096057383a3fb7852cb318075579bfc697e5 -- th_cli/exceptions.py pyproject.toml
cat -n th_cli/config.py | sed -n '60,155p'
cat -n th_cli/exceptions.py
rg -n -i -e 'config\.json' -e 'wifi.*password' -e 'password.*wifi' -e 'pydantic' -- th_cli tests README.md pyproject.toml config.json.example || test "$?" -eq 1
rg --files -g '*config*.json*' -g '*lock*' -g 'pyproject.toml' -g 'AGENTS.md' -g 'CLAUDE.md'

Repository: project-chip/certification-tool-cli

Length of output: 13739


Web query:

Pydantic v2 model_validate_json invalid JSON validation error input_value truncation hide_input_in_errors

Result:

Sources consulted:
- Environment variable to show full input value in errors — GitHub issue 12251 in pydantic/pydantic (link omitted to avoid creating a cross-reference)
- Pydantic V2 truncates validation error messages, how to print the full data? · pydantic/pydantic · Discussion #7733 · GitHub — GitHub discussion 7733 in pydantic/pydantic (link omitted to avoid creating a cross-reference)
- Error Handling — https://pydantic.dev/docs/validation/latest/errors/errors
- Model config — https://pydantic.dev/docs/validation/2.2/usage/model_config/
- Configuration — https://pydantic.dev/docs/validation/latest/api/pydantic/config/

Script executed:

cat -n README.md | sed -n '22,45p;95,175p'
cat -n th_cli/default_config.json | sed -n '1,50p'
cat -n tests/test_config.py | sed -n '190,251p'
cat -n pyproject.toml | sed -n '24,45p'
rg -n -F -e 'load_json_config(' -e 'default_config.json' -e '--config' -- th_cli/commands th_cli/test_run th_cli/utils.py
python3 - <<'PY'
import importlib.util
s = importlib.util.find_spec("pydantic")
if s is None:
    print("pydantic unavailable")
else:
    import pydantic
    print("pydantic version:", pydantic.__version__)
    if hasattr(pydantic.BaseModel, "model_validate_json"):
        class Probe(pydantic.BaseModel):
            hostname: str = "localhost"
        try:
            Probe.model_validate_json('{"password":"secret",')
        except pydantic.ValidationError as e:
            print(str(e))
PY

Repository: project-chip/certification-tool-cli

Length of output: 11444


Web query:

Pydantic 2 model_validate_json invalid json validation error input_value json_invalid example string

Result:

Sources consulted:
- Incorrect "raises" documentation for `BaseModel.model_validate_json` — GitHub issue 9944 in pydantic/pydantic (link omitted to avoid creating a cross-reference)
- Models — https://pydantic.dev/docs/validation/2.12/concepts/models/
- Pydantic model_validate_json · Python for AI tutorial — https://www.krishnaik.in/ai-tutorials/python-for-ai/model-validate-json
- Parsing JSON | VizLearn — https://vizlearn.in/pydantic/parsing_json.html
- Handle BOM during JSON validation — GitHub issue 10233 in pydantic/pydantic (link omitted to avoid creating a cross-reference)

Do not include configuration values in the error message.

If a malformed project file is named config.json in the current directory, Pydantic can include part of its contents, including a Wi-Fi password, in the error. The CLI prints that error to stderr, which may be captured in logs.

Report the path and sanitized error details without input values.


# Try to create config from example file
example_locations = []
Expand All @@ -147,7 +147,12 @@ def load_config():


# Load the configuration
config = load_config()
try:
config = load_config()
except ConfigurationError as e:
# Raised at import time, before click is running, so report it like click would
e.show()
sys.exit(e.exit_code)


class PairingMode(str, Enum):
Expand Down
Loading