Skip to content

[ADS-1632] Handle blank and BOM-prefixed Agent Guard JSON configs - #574

Merged
jakub-kassak merged 2 commits into
mainfrom
fix/ADS-1632-handle-blank-json-configs
Nov 27, 2026
Merged

jakub-kassak merged 2 commits into
mainfrom
fix/ADS-1632-handle-blank-json-configs

Conversation

@jakub-kassak

@jakub-kassak jakub-kassak commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What this does

Agent Guard currently fails to parse blank JSON configs and valid JSON configs that start with a UTF-8 byte-order mark (BOM).

The shared JSON reader now treats empty, whitespace-only, and BOM-only files as {} and accepts BOM-prefixed JSON. Install, status, and uninstall all use that reader.

When Guard rewrites a config, it preserves the file’s BOM convention and uses the existing backup and atomic write flow. An identical reinstall leaves the file untouched.

Notes for the reviewer

The agreed scope for ADS-1632 is blank-file and BOM handling in agent-scan. A revert restores the previous config behavior. The change is limited to Guard’s local JSON config files.

Evidence

  • Before: All five new regression cases failed with JSON parsing errors.
  • After: All five passed, covering blank input, BOM preservation, no-op reinstall, backup behavior, and non-ASCII settings through install and uninstall.
  • All Guard unit tests, a macOS CLI status smoke test, pinned pre-commit checks for the changed files, and the package build passed.
  • Eight API unit tests initially failed because SNYK_TOKEN was unset. The API test module passed on rerun with a dummy token.

More information

ADS-1632


Note

Low Risk
Localized to Guard's local JSON read/write/backup paths for agent hook configs; behavior is additive preservation with regression tests and no auth or network changes.

Overview
Fixes Agent Guard failing on JSON configs that are empty, whitespace-only, or UTF-8 BOM-prefixed (common on Windows editors).

_read_json_or_empty now reads with utf-8-sig and treats blank or whitespace-only files as {}, so install/status/uninstall no longer throw parse errors on those inputs.

Writes preserve encoding conventions: _has_utf8_bom detects an existing BOM; _dump_config_json can re-emit \ufeff; backup, change-detection, uninstall, and reinstall paths pass that through so BOM-only configs, backups, and no-op reinstalls stay byte-stable while non-ASCII user content (e.g. "café") still round-trips.

Unit tests in TestJsonConfigEncoding cover blank/BOM-only files, BOM + user content through install/uninstall, backups, and unchanged reinstalls.

Reviewed by Cursor Bugbot for commit c02896b. Bugbot is set up for automated code reviews on this repo. Configure here.

Treat blank JSON files as empty configs and preserve a UTF-8 BOM when
rewriting an existing file.

Related: ADS-1632
Co-authored-by: FORGE <forge@snyk.io>
@jakub-kassak
jakub-kassak requested review from a team and marcelosousa as code owners November 27, 2026 14:48
@qodo-merge-etso

qodo-merge-etso Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Handle blank and BOM-prefixed Agent Guard JSON configs

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Treat blank JSON configs as empty and accept UTF-8 BOM-prefixed configs across Guard operations.
• Preserve existing BOMs during rewrites and backups without changing identical reinstalls.
• Add regression tests for blank files, BOM preservation, backups, and non-ASCII settings.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed helpers are called by the shared client configuration preparation, installation, status detection, backup, and uninstallation flows.
  • These are one bounded end-to-end integration whose outcome is preserving or modifying a supported client's hook configuration, rather than independent technical layers.
Sources

src/agent_scan/guard.py[3141-3146]

def _has_utf8_bom(path: Path) -> bool:
    try:
        with path.open("rb") as f:
            return f.read(len(codecs.BOM_UTF8)) == codecs.BOM_UTF8
    except FileNotFoundError:
        return False

src/agent_scan/guard.py[3165-3173]

def _json_config_without_guard(path: Path, client: str, *, with_bom: bool) -> str | None:
    """*client*'s JSON config at ``path`` without Agent Guard, or None if it has no Guard hooks."""
    data = _read_json_or_empty(path)
    stripped = _strip_guard_from_json_config(data, client)
    return None if stripped == data else _dump_config_json(stripped, with_bom=with_bom)


def _write_json(path: Path, data: dict) -> None:
    _atomic_write_text(path, _dump_config_json(data, with_bom=_has_utf8_bom(path)))

src/agent_scan/guard.py[3154-3161]

    old_content = path.read_text(encoding="utf-8") if path.exists() else None
    with_bom = old_content is not None and _has_utf8_bom(path)
    new_content = _dump_config_json(data, with_bom=with_bom)
    if old_content is not None:
        if old_content == new_content:
            return False
        _backup_file(path, lambda: _json_config_without_guard(path, client, with_bom=with_bom))
    _atomic_write_text(path, new_content)
Behavioral complexity 🟡 Medium 🧩 Compatibility cases

  • Before: JSON lifecycle code assumed ordinary UTF-8 JSON and serialized without a BOM.
  • After: it accepts blank or BOM-prefixed files, detects the existing BOM, and preserves that encoding through writes and guard-free backups.
  • New correctness condition: parsing must remove only an input BOM while serialization must reproduce it consistently across install, update, backup, and uninstall, without changing user data or idempotence.
  • The behavior spans established client flows but introduces compatibility handling for multiple file encodings and empty-file states.
Sources

src/agent_scan/guard.py[3141-3146]

def _has_utf8_bom(path: Path) -> bool:
    try:
        with path.open("rb") as f:
            return f.read(len(codecs.BOM_UTF8)) == codecs.BOM_UTF8
    except FileNotFoundError:
        return False

src/agent_scan/guard.py[3154-3161]

    old_content = path.read_text(encoding="utf-8") if path.exists() else None
    with_bom = old_content is not None and _has_utf8_bom(path)
    new_content = _dump_config_json(data, with_bom=with_bom)
    if old_content is not None:
        if old_content == new_content:
            return False
        _backup_file(path, lambda: _json_config_without_guard(path, client, with_bom=with_bom))
    _atomic_write_text(path, new_content)

src/agent_scan/guard.py[3165-3173]

def _json_config_without_guard(path: Path, client: str, *, with_bom: bool) -> str | None:
    """*client*'s JSON config at ``path`` without Agent Guard, or None if it has no Guard hooks."""
    data = _read_json_or_empty(path)
    stripped = _strip_guard_from_json_config(data, client)
    return None if stripped == data else _dump_config_json(stripped, with_bom=with_bom)


def _write_json(path: Path, data: dict) -> None:
    _atomic_write_text(path, _dump_config_json(data, with_bom=_has_utf8_bom(path)))
Potential damage 🟡 Medium 🩹 Recoverable

  • If the changed encoding or blank-file handling regresses, installation or removal may fail, leave Agent Guard hooks unavailable, or require restoration of the backed-up user configuration.
  • The shared atomic write and backup paths limit ordinary recovery to rerunning the operation or restoring the backup; reverting code alone would not repair a file already rewritten with incorrect content.
  • Rerun the lifecycle operation or restore the Guard backup; manual repair may be needed if a user configuration was already rewritten.
Sources

src/agent_scan/guard.py[3154-3161]

    old_content = path.read_text(encoding="utf-8") if path.exists() else None
    with_bom = old_content is not None and _has_utf8_bom(path)
    new_content = _dump_config_json(data, with_bom=with_bom)
    if old_content is not None:
        if old_content == new_content:
            return False
        _backup_file(path, lambda: _json_config_without_guard(path, client, with_bom=with_bom))
    _atomic_write_text(path, new_content)

src/agent_scan/guard.py[3165-3173]

def _json_config_without_guard(path: Path, client: str, *, with_bom: bool) -> str | None:
    """*client*'s JSON config at ``path`` without Agent Guard, or None if it has no Guard hooks."""
    data = _read_json_or_empty(path)
    stripped = _strip_guard_from_json_config(data, client)
    return None if stripped == data else _dump_config_json(stripped, with_bom=with_bom)


def _write_json(path: Path, data: dict) -> None:
    _atomic_write_text(path, _dump_config_json(data, with_bom=_has_utf8_bom(path)))
Assessed commit c02896b
Diagram

graph TD
  A["Guard actions"] --> B["JSON reader"] --> C{"Blank after BOM?"}
  C -->|yes| D["Empty object"] --> F["Guard config logic"] --> G["BOM-aware writer"] --> H["Config and backup"]
  C -->|no| E["Parsed JSON"] --> F
Loading
High-Level Assessment

The targeted shared-reader change and BOM-aware serialization fit the existing Guard config flow. Replacing the backup or atomic-write mechanisms would add scope without addressing the parsing issue more directly.

Files changed (2) +59 / -11

Bug fix (1) +17 / -11
guard.pyAccept blank and BOM-prefixed JSON while preserving BOMs on writes +17/-11

Accept blank and BOM-prefixed JSON while preserving BOMs on writes

• The shared reader treats empty and whitespace-only files as empty configs and parses UTF-8 BOM-prefixed JSON. Config rewrites and guard-free backups retain an existing BOM, while unchanged content still skips the write.

src/agent_scan/guard.py

Tests (1) +42 / -0
test_guard.pyCover blank configs and BOM-preserving Guard lifecycle +42/-0

Cover blank configs and BOM-preserving Guard lifecycle

• Regression tests cover empty, whitespace-only, BOM-only, and BOM-plus-whitespace files. They also check install and uninstall with non-ASCII user settings, backup contents, and an identical reinstall that leaves the file untouched.

tests/unit/test_guard.py

@qodo-merge-etso

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can commit Qodo's fix in one click with committable suggestions (GitHub & GitLab)

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@phsommer phsommer left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good to me. Please have a look at the small suggestion below.

Comment thread src/agent_scan/guard.py Outdated
Comment on lines +3165 to +3167
with_bom = False
with contextlib.suppress(FileNotFoundError), path.open("rb") as f:
with_bom = f.read(len(codecs.BOM_UTF8)) == codecs.BOM_UTF8

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we use the same mechanism to check if the file has a BOM?
I suggest to use a a small helper _has_utf8_bom(path) which is then shared by both _write_json() and _write_json_if_changed

@jakub-kassak jakub-kassak changed the title [ADS-1632] Handle blank and BOM-prefixed Agent Guard configs [ADS-1632] Handle blank and BOM-prefixed Agent Guard JSON configs Nov 27, 2026
Related: ADS-1632
Co-authored-by: FORGE <forge@snyk.io>
@jakub-kassak
jakub-kassak merged commit 647bc87 into main Nov 27, 2026
19 of 23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants