Compare commits
19 Commits
3841106630
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ff4f6e5c0 | |||
| 7517e16b15 | |||
| 9a0433225e | |||
| fa82d30087 | |||
| 05b00a40c0 | |||
| 3068e74e5c | |||
| febd617c56 | |||
| da20eb2fdb | |||
| cd2ac2f6f8 | |||
| 26c66b7db1 | |||
| 86139100eb | |||
| 38f14deeff | |||
| 82483e693d | |||
| 6fce19cc67 | |||
| 37b3c8f5d0 | |||
| b08cf2112b | |||
| 80761a1f17 | |||
| d6fc6845c4 | |||
| f0d0ab7a08 |
@@ -68,3 +68,109 @@ jobs:
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
|
||||
# ── Catalog signature gate (#61) ─────────────────────────────────────────
|
||||
#
|
||||
# data/catalog.json is a list of command+args entries that BCC writes into
|
||||
# the user's Claude config, which Claude then EXECUTES. The catalog is only
|
||||
# trusted if it carries a valid Ed25519 signature from the maintainer key.
|
||||
#
|
||||
# The threat this gate exists for is NOT an outsider pushing to the repo —
|
||||
# it is the maintainer merging a friendly-looking PR without really reading
|
||||
# it. A contributor can change catalog.json but cannot produce a matching
|
||||
# signature, so a blindly-merged PR lands here as a RED BUILD within a
|
||||
# minute, instead of quietly riding into the next release.
|
||||
#
|
||||
# Public-key verification only. No secret is used or needed.
|
||||
catalog-signature:
|
||||
name: Catalog signature
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install cryptography
|
||||
|
||||
# 🔴 TRUST ANCHOR — issue #68 finding 4.
|
||||
#
|
||||
# This step used to do `import bcc_core as c` FROM THE CHECKED-OUT PR
|
||||
# BRANCH and verify the catalog against c.CATALOG_PUBKEYS — i.e. it
|
||||
# trusted the public key shipped in the very diff it was reviewing. A
|
||||
# PR that changed data/catalog.json AND bcc_core.CATALOG_PUBKEYS (to
|
||||
# an attacker key, with a matching signature produced by the attacker's
|
||||
# matching private key) went green, because there was nothing outside
|
||||
# the PR's own content to check the key against. The gate's whole
|
||||
# point is catching a friendly-looking PR the maintainer merges
|
||||
# without really reading it — and that hole made it a two-file diff.
|
||||
#
|
||||
# EXPECTED_CATALOG_PUBKEY_B64 below is hardcoded HERE, in the workflow
|
||||
# file, independent of whatever bcc_core.py says on the PR branch. It
|
||||
# is intentionally the only line in this step that matters for
|
||||
# security review: changing it changes what this gate is willing to
|
||||
# trust. THIS CONSTANT IS A TRUST ANCHOR. A PR that changes this line
|
||||
# in the same diff as a catalog change is exactly the attack this gate
|
||||
# exists to prevent — review a change to this line on its own,
|
||||
# never bundled with a catalog update.
|
||||
#
|
||||
# NOTE for the next key rotation: update EXPECTED_CATALOG_PUBKEY_B64
|
||||
# below to the new key's base64 form, as its own reviewed change.
|
||||
- name: Verify data/catalog.json.sig
|
||||
env:
|
||||
EXPECTED_CATALOG_PUBKEY_B64: "082NOwVB7uURkvfyS3+knJ+40Fk6C9unsF47+2uPKo4="
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import base64, os, pathlib, sys
|
||||
import bcc_core as c
|
||||
|
||||
expected_pubkey_b64 = os.environ["EXPECTED_CATALOG_PUBKEY_B64"]
|
||||
|
||||
raw = pathlib.Path("data/catalog.json").read_bytes()
|
||||
sig_path = pathlib.Path("data/catalog.json.sig")
|
||||
|
||||
if not sig_path.exists():
|
||||
sys.exit("FAIL: data/catalog.json.sig is missing. The catalog must be "
|
||||
"signed via the Catalog Console (#62) before it can land.")
|
||||
|
||||
if b"\x00" * 32 in c.CATALOG_PUBKEYS:
|
||||
sys.exit("FAIL: CATALOG_PUBKEYS still holds the placeholder key.")
|
||||
|
||||
# Trust anchor check FIRST, before verifying anything against
|
||||
# bcc_core.CATALOG_PUBKEYS: a PR is not allowed to bring its own
|
||||
# key. CATALOG_PUBKEYS on the checked-out branch must be EXACTLY
|
||||
# the key(s) this workflow file itself expects -- no more, no
|
||||
# fewer, no substitutions.
|
||||
actual_pubkeys_b64 = [base64.b64encode(k).decode() for k in c.CATALOG_PUBKEYS]
|
||||
if actual_pubkeys_b64 != [expected_pubkey_b64]:
|
||||
sys.exit(
|
||||
"FAIL: bcc_core.CATALOG_PUBKEYS on this branch does not match the "
|
||||
"trust anchor hardcoded in .github/workflows/ci.yml.\n"
|
||||
f" expected: {[expected_pubkey_b64]}\n"
|
||||
f" actual: {actual_pubkeys_b64}\n"
|
||||
"\n"
|
||||
"This PR is changing (or has changed) the catalog signing key. That "
|
||||
"change must be reviewed on its own, separately from any catalog "
|
||||
"content change, and the workflow's EXPECTED_CATALOG_PUBKEY_B64 "
|
||||
"updated deliberately -- not accepted because it happened to match "
|
||||
"whatever bcc_core.py says on this branch."
|
||||
)
|
||||
|
||||
if not c.verify_catalog_signature(raw, sig_path.read_bytes(), c.CATALOG_PUBKEYS):
|
||||
sys.exit(
|
||||
"FAIL: data/catalog.json does NOT match its signature.\n"
|
||||
"\n"
|
||||
"The catalog changed without being re-signed. Either someone edited\n"
|
||||
"it directly (a PR you merged?), or a signing pass was forgotten.\n"
|
||||
"Re-review and re-sign with the Catalog Console — do not bypass this."
|
||||
)
|
||||
|
||||
problems = c.validate_catalog(c.load_catalog(raw))
|
||||
if problems:
|
||||
sys.exit("FAIL: catalog failed validation:\n " + "\n ".join(problems))
|
||||
|
||||
print("OK: catalog signature verifies, the pubkey matches the CI trust anchor, "
|
||||
"and the catalog validates clean.")
|
||||
PY
|
||||
|
||||
@@ -95,6 +95,92 @@ jobs:
|
||||
name: ${{ matrix.artifact }}
|
||||
path: ${{ matrix.artifact }}
|
||||
|
||||
# ── Signing-key smoke test (workflow_dispatch only) ─────────────────────
|
||||
#
|
||||
# The Publish job is gated on a tag, so a manual run never exercises the
|
||||
# signing step — which means a wrong/missing RELEASE_SIGNING_KEY secret
|
||||
# would only be discovered at the worst possible moment: during a real
|
||||
# release. This job signs a throwaway manifest with the secret and verifies
|
||||
# the result against scripts/sign_checksums.RELEASE_PUBKEYS.
|
||||
#
|
||||
# IMPORTANT (issue #68 finding 5): this must verify against the RELEASE
|
||||
# public key, never bcc_core.CATALOG_PUBKEYS. The catalog key is the
|
||||
# offline, maintainer-held root of trust for what BCC executes; it must
|
||||
# NEVER be compared against a value that lives in a CI secret, because
|
||||
# that comparison is itself a way to smuggle a catalog-trusted key through
|
||||
# CI review ("does this repo secret match the catalog key" is a question
|
||||
# this workflow must never even ask). The release key is a SEPARATE
|
||||
# keypair, generated via `catalog_console.py keygen --release`, that only
|
||||
# ever signs release SHA256SUMS manifests -- a CI/secret compromise burns
|
||||
# this key, not the catalog key.
|
||||
#
|
||||
# It proves the two halves of the RELEASE keypair actually match, without
|
||||
# publishing anything. Run it from the Actions tab after setting or
|
||||
# rotating the secret.
|
||||
signing-smoke-test:
|
||||
name: Signing key smoke test
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install cryptography
|
||||
|
||||
- name: Sign a throwaway manifest and verify against the RELEASE pubkey
|
||||
env:
|
||||
RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_SIGNING_KEY" ]; then
|
||||
echo "FAIL: RELEASE_SIGNING_KEY secret is not set."
|
||||
echo "Generate the RELEASE key (NOT the catalog key) with:"
|
||||
echo " python catalog_console.py keygen --release"
|
||||
echo "then add its seed under Settings -> Actions -> Secrets, via:"
|
||||
echo " python catalog_console.py show-seed-b64 --release"
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p smoke && echo "smoke test payload" > smoke/hello.txt
|
||||
python3 scripts/sign_checksums.py generate smoke --out smoke/SHA256SUMS
|
||||
python3 scripts/sign_checksums.py sign --sums smoke/SHA256SUMS --out smoke/SHA256SUMS.sig
|
||||
python - <<'PY'
|
||||
import pathlib, sys
|
||||
from scripts.sign_checksums import RELEASE_PUBKEYS, verify_checksums_against_any
|
||||
|
||||
# Deliberately does NOT import bcc_core / CATALOG_PUBKEYS at all --
|
||||
# this smoke test must never be able to compare the CI secret
|
||||
# against the catalog's root of trust (issue #68 finding 5). Only
|
||||
# RELEASE_PUBKEYS (scripts/sign_checksums.py) is a legitimate
|
||||
# target for a CI-resident key.
|
||||
if not RELEASE_PUBKEYS:
|
||||
sys.exit(
|
||||
"FAIL: scripts/sign_checksums.RELEASE_PUBKEYS is empty.\n"
|
||||
"\n"
|
||||
"Generate the release keypair with:\n"
|
||||
" python catalog_console.py keygen --release\n"
|
||||
"then paste the printed public key into RELEASE_PUBKEYS in\n"
|
||||
"scripts/sign_checksums.py and commit that change."
|
||||
)
|
||||
|
||||
sums = pathlib.Path("smoke/SHA256SUMS").read_text()
|
||||
sig = pathlib.Path("smoke/SHA256SUMS.sig").read_bytes()
|
||||
|
||||
if not verify_checksums_against_any(RELEASE_PUBKEYS, sums, sig):
|
||||
sys.exit(
|
||||
"FAIL: the signature produced by RELEASE_SIGNING_KEY does NOT verify\n"
|
||||
"against any key in scripts/sign_checksums.RELEASE_PUBKEYS.\n"
|
||||
"\n"
|
||||
"The secret and the shipped release public key are different keypairs.\n"
|
||||
"Downloaders would reject every signature this CI produces. Re-copy the\n"
|
||||
"seed from `catalog_console.py show-seed-b64 --release`, or update\n"
|
||||
"RELEASE_PUBKEYS with the matching public key."
|
||||
)
|
||||
print("OK: RELEASE_SIGNING_KEY matches a key in RELEASE_PUBKEYS.")
|
||||
PY
|
||||
|
||||
# ── Create GitHub Release with all three artifacts ──────────────────────
|
||||
|
||||
release:
|
||||
@@ -143,9 +229,13 @@ jobs:
|
||||
# checks. It does NOT remove Gatekeeper/SmartScreen warnings.
|
||||
#
|
||||
# The private key is a repo secret (RELEASE_SIGNING_KEY, base64 raw
|
||||
# Ed25519 seed) generated via the Catalog Console (#62). If it's not
|
||||
# set, we still publish the release — just without a .sig — rather
|
||||
# than fail the release outright.
|
||||
# Ed25519 seed) for the RELEASE key -- a SEPARATE keypair from the
|
||||
# catalog key, generated via `python catalog_console.py keygen
|
||||
# --release` (issue #68 finding 5; #62). This key is intentionally
|
||||
# CI-resident and signs ONLY this checksum manifest; it is never
|
||||
# trusted to sign data/catalog.json. If it's not set, we still
|
||||
# publish the release — just without a .sig — rather than fail the
|
||||
# release outright.
|
||||
- name: Check for signing key
|
||||
id: signing
|
||||
run: |
|
||||
@@ -171,7 +261,7 @@ jobs:
|
||||
- name: Warn — release will be unsigned
|
||||
if: steps.signing.outputs.has_key != 'true'
|
||||
run: |
|
||||
echo "::warning::RELEASE_SIGNING_KEY secret is not set — this release is being published WITHOUT a signed SHA256SUMS.sig. Add the secret (base64 raw Ed25519 seed, generated via the Catalog Console, #62) before the next tag."
|
||||
echo "::warning::RELEASE_SIGNING_KEY secret is not set — this release is being published WITHOUT a signed SHA256SUMS.sig. Generate the RELEASE key (python catalog_console.py keygen --release) and add its seed (python catalog_console.py show-seed-b64 --release) as this secret before the next tag."
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
|
||||
@@ -36,11 +36,10 @@ are only suppressed by a paid OS-vendor certificate, which this project
|
||||
doesn't have. Verifying checksums is about detecting tampering in transit or
|
||||
on a mirror, not about vouching for the software.
|
||||
|
||||
**Release signing public key** (Ed25519, base64, raw 32 bytes):
|
||||
|
||||
```
|
||||
<PLACEHOLDER — AJ: paste the public key from the Catalog Console (#62) here>
|
||||
```
|
||||
This manifest is signed with BCC's **release key**, which is a different
|
||||
key from the one that signs the MCP server catalog — see
|
||||
[Signing keys](#signing-keys) below for why, and for the public key value
|
||||
to use with `--pubkey-b64` below.
|
||||
|
||||
### macOS / Linux
|
||||
|
||||
@@ -59,7 +58,7 @@ To also verify the manifest's signature (optional, requires Python +
|
||||
```bash
|
||||
python3 scripts/sign_checksums.py verify \
|
||||
--sums SHA256SUMS --sig SHA256SUMS.sig \
|
||||
--pubkey-b64 "<the public key above>"
|
||||
--pubkey-b64 "<the release public key from Signing keys, below>"
|
||||
```
|
||||
|
||||
### Windows (PowerShell)
|
||||
@@ -78,6 +77,45 @@ release is missing the `.sig` file, the checksums themselves are still
|
||||
valid and safe to check against — the release workflow only skips signing,
|
||||
never checksum generation.
|
||||
|
||||
## Signing keys
|
||||
|
||||
BCC uses **two separate Ed25519 keypairs**, deliberately never the same
|
||||
key, because they protect different things and live in different places:
|
||||
|
||||
| | Catalog key | Release key |
|
||||
|---|---|---|
|
||||
| Signs | `data/catalog.json` (the MCP server catalog every user's app trusts) | `SHA256SUMS` (the checksum manifest for release binaries) |
|
||||
| Verified by | `bcc_core.CATALOG_PUBKEYS` | `scripts/sign_checksums.RELEASE_PUBKEYS` |
|
||||
| Lives | Offline, passphrase-encrypted, maintainer's machine only (OS keychain or an encrypted file outside the repo — see the [Catalog Console](#files), issue #62) | A Gitea Actions repo secret, `RELEASE_SIGNING_KEY` — **intentionally CI-resident** |
|
||||
| Generated with | `python catalog_console.py keygen` | `python catalog_console.py keygen --release` |
|
||||
| Exported for CI with | *(never — there is no supported way to export this key)* | `python catalog_console.py show-seed-b64 --release` |
|
||||
|
||||
**Why two keys:** the catalog key is the root of trust for what BCC
|
||||
actually *executes* on a user's machine — every `command`/`args` pair in
|
||||
the shipped catalog is only there because this key signed it. If that key
|
||||
and the release-checksum key were the same (as they briefly were — see
|
||||
[issue #68](../../issues/68)), then anything that can exfiltrate a Gitea
|
||||
Actions secret (a malicious workflow-file PR, a compromised runner, a leaky
|
||||
log) could sign a catalog every user's copy of BCC would trust, not just a
|
||||
checksum manifest. Splitting them means **a CI/secret compromise burns the
|
||||
release key, never the catalog key** — checksums for a future release could
|
||||
be forged, which is bad, but no attacker gains the ability to make BCC run
|
||||
arbitrary commands on installs that trust the catalog. That asymmetry is
|
||||
the entire point of having two keys instead of one.
|
||||
|
||||
The catalog key is **never** meant to leave the maintainer's machine: it's
|
||||
generated, stored, unlocked, and used to sign entirely inside the Catalog
|
||||
Console (`catalog_console.py`), and `catalog_console.py show-seed-b64`
|
||||
refuses to run without `--release` specifically so the catalog seed can't
|
||||
be exported by habit or muscle memory.
|
||||
|
||||
**Release signing public key** (Ed25519, base64, raw 32 bytes) — this is
|
||||
the RELEASE key, not the catalog key:
|
||||
|
||||
```
|
||||
<PLACEHOLDER — AJ: paste the release public key from `catalog_console.py keygen --release` here>
|
||||
```
|
||||
|
||||
## Run from source
|
||||
|
||||
```bash
|
||||
@@ -152,6 +190,7 @@ file is also listed, marked *legacy*, so you can copy them over.
|
||||
- `bcc.spec` — PyInstaller build spec (cross-platform).
|
||||
- `scripts/build_icons.py` — regenerates `icons/app.icns` and `icons/app.ico` from source PNGs.
|
||||
- `scripts/sign_checksums.py` — generates and Ed25519-signs the release `SHA256SUMS` manifest (see [Verifying your download](#verifying-your-download)).
|
||||
- `catalog_console.py` / `catalog_review.py` — **maintainer-only**, never shipped to users (excluded from `bcc.spec`; see `tests/test_catalog_console_packaging.py`). The Catalog Console: review + sign `data/catalog.json`, and generate/manage both signing keys (`keygen`, `keygen --release`) — see [Signing keys](#signing-keys).
|
||||
|
||||
## Building from source
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ Run: python mcp_manager.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -18,6 +19,7 @@ from typing import ClassVar
|
||||
from PySide6.QtCore import QRect, QSettings, QSize, Qt, QThread, QTimer, QUrl, Signal
|
||||
from PySide6.QtGui import (
|
||||
QAction,
|
||||
QActionGroup,
|
||||
QColor,
|
||||
QCursor,
|
||||
QDesktopServices,
|
||||
@@ -25,6 +27,7 @@ from PySide6.QtGui import (
|
||||
QIcon,
|
||||
QKeySequence,
|
||||
QPainter,
|
||||
QPalette,
|
||||
QPixmap,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
@@ -65,85 +68,122 @@ import bcc_core as core
|
||||
# thread during drag-and-drop import, so skip anything larger than this.
|
||||
MAX_DROP_IMPORT_BYTES = 5 * 1024 * 1024 # 5 MB
|
||||
|
||||
# --- One-line rebrand: change this to recolor the whole app --------------- #
|
||||
ACCENT = "#f97316" # warm orange
|
||||
ACCENT_DIM = "#c2570b"
|
||||
BG = "#1b1d23"
|
||||
PANEL = "#23262e"
|
||||
PANEL_2 = "#2b2f39"
|
||||
TEXT = "#e7e9ee"
|
||||
MUTED = "#9aa0ad"
|
||||
BORDER = "#3a3f4b"
|
||||
GOOD = "#4ade80"
|
||||
BAD = "#f87171"
|
||||
WARN = "#fbbf24"
|
||||
# --- Theming (issue #75) -------------------------------------------------- #
|
||||
# The palette lives in bcc_core (testable without a Qt app); these module-level
|
||||
# names are rebound by `apply_palette()` whenever the theme changes.
|
||||
#
|
||||
# Why globals rather than passing a palette around: ~20 inline
|
||||
# `setStyleSheet(f"color: {MUTED}")` calls are scattered through this file, and
|
||||
# an f-string resolves its names when it runs, not when it's compiled. Rebinding
|
||||
# the globals means every one of those call sites picks up the new colour on its
|
||||
# next render, with no change to the call sites themselves.
|
||||
PALETTE = core.DARK_PALETTE
|
||||
ACCENT = ACCENT_DIM = BG = PANEL = PANEL_2 = TEXT = MUTED = BORDER = ""
|
||||
GOOD = BAD = WARN = REMOTE = ON_ACCENT = DISABLED_BG = MONO_BG = SEL_TEXT = ""
|
||||
STATUS_COLORS: dict[str, str] = {}
|
||||
HEALTH_COLORS: dict[str, str] = {}
|
||||
|
||||
STATUS_COLORS = {"ok": GOOD, "missing": BAD, "warn": WARN, "remote": "#60a5fa", "unknown": WARN}
|
||||
STATUS_GLYPH = {"ok": "●", "missing": "●", "warn": "▲", "remote": "◆", "unknown": "○"}
|
||||
STATUS_GLYPH = {
|
||||
"ok": "\u25cf",
|
||||
"missing": "\u25cf",
|
||||
"warn": "\u25b2",
|
||||
"remote": "\u25c6",
|
||||
"unknown": "\u25cb",
|
||||
}
|
||||
|
||||
# Health dot (spawn-test outcome, see core.HealthStatus) shown per row in the
|
||||
# server tables' "Health" column -- distinct from the PATH-dependency Status
|
||||
# column above.
|
||||
HEALTH_COLORS = {"ok": GOOD, "failed": BAD, "untested": MUTED}
|
||||
HEALTH_GLYPH = {"ok": "●", "failed": "●", "untested": "○"}
|
||||
HEALTH_GLYPH = {"ok": "\u25cf", "failed": "\u25cf", "untested": "\u25cb"}
|
||||
|
||||
STYLESHEET = f"""
|
||||
|
||||
def build_stylesheet(p: core.Palette) -> str:
|
||||
"""Render the global QSS for a palette."""
|
||||
return f"""
|
||||
/* No font-family here on purpose: Qt already uses the native system UI font
|
||||
on every platform (San Francisco / Segoe UI / desktop default). Naming
|
||||
web-CSS aliases like -apple-system forces a costly font-alias scan. */
|
||||
* {{ font-size: 13px; color: {TEXT}; }}
|
||||
QMainWindow, QDialog {{ background: {BG}; }}
|
||||
* {{ font-size: 13px; color: {p.text}; }}
|
||||
QMainWindow, QDialog {{ background: {p.bg}; }}
|
||||
QLabel#h1 {{ font-size: 15px; font-weight: 600; }}
|
||||
QLabel#muted {{ color: {MUTED}; }}
|
||||
QFrame#card {{ background: {PANEL}; border: 1px solid {BORDER}; border-radius: 10px; }}
|
||||
QLabel#muted {{ color: {p.muted}; }}
|
||||
QFrame#card {{ background: {p.panel}; border: 1px solid {p.border}; border-radius: 10px; }}
|
||||
QLineEdit, QPlainTextEdit, QComboBox {{
|
||||
background: {PANEL_2}; border: 1px solid {BORDER}; border-radius: 7px;
|
||||
padding: 6px 8px; selection-background-color: {ACCENT}; selection-color: #1a1205;
|
||||
background: {p.panel_2}; border: 1px solid {p.border}; border-radius: 7px;
|
||||
padding: 6px 8px; selection-background-color: {p.accent}; selection-color: {p.on_accent};
|
||||
}}
|
||||
QLineEdit:focus, QPlainTextEdit:focus, QComboBox:focus {{ border: 1px solid {ACCENT}; }}
|
||||
QLineEdit:focus, QPlainTextEdit:focus, QComboBox:focus {{ border: 1px solid {p.accent}; }}
|
||||
QComboBox::drop-down {{ border: none; width: 22px; }}
|
||||
QComboBox QAbstractItemView {{ background: {PANEL_2}; border: 1px solid {BORDER};
|
||||
selection-background-color: {ACCENT}; outline: none; }}
|
||||
QPushButton {{ background: {PANEL_2}; border: 1px solid {BORDER}; border-radius: 7px;
|
||||
QComboBox QAbstractItemView {{ background: {p.panel_2}; border: 1px solid {p.border};
|
||||
selection-background-color: {p.accent}; outline: none; }}
|
||||
QPushButton {{ background: {p.panel_2}; border: 1px solid {p.border}; border-radius: 7px;
|
||||
padding: 7px 13px; }}
|
||||
QPushButton:hover {{ border: 1px solid {ACCENT}; }}
|
||||
QPushButton:disabled {{ color: {MUTED}; background: {PANEL}; }}
|
||||
QPushButton#primary {{ background: {ACCENT}; border: 1px solid {ACCENT}; color: #1a1205; font-weight: 600; }}
|
||||
QPushButton#primary:hover {{ background: {ACCENT_DIM}; }}
|
||||
QPushButton#primary:disabled {{ background: {PANEL}; color: {MUTED}; border: 1px solid {BORDER}; }}
|
||||
QPushButton#danger:hover {{ border: 1px solid {BAD}; color: {BAD}; }}
|
||||
QTableWidget {{ background: {PANEL}; border: 1px solid {BORDER}; border-radius: 10px;
|
||||
QPushButton:hover {{ border: 1px solid {p.accent}; }}
|
||||
QPushButton:disabled {{ color: {p.muted}; background: {p.panel}; }}
|
||||
QPushButton#primary {{ background: {p.accent}; border: 1px solid {p.accent}; color: {p.on_accent}; font-weight: 600; }}
|
||||
QPushButton#primary:hover {{ background: {p.accent_dim}; }}
|
||||
QPushButton#primary:disabled {{ background: {p.panel}; color: {p.muted}; border: 1px solid {p.border}; }}
|
||||
QPushButton#danger:hover {{ border: 1px solid {p.bad}; color: {p.bad}; }}
|
||||
QTableWidget {{ background: {p.panel}; border: 1px solid {p.border}; border-radius: 10px;
|
||||
gridline-color: transparent; outline: none; }}
|
||||
QTableWidget::item {{ padding: 6px 8px; border: none; }}
|
||||
QTableWidget::item:selected {{ background: {ACCENT}; color: #1a1205; }}
|
||||
QTableWidget::item:selected {{ background: {p.accent}; color: {p.on_accent}; }}
|
||||
/* Inline cell editors: the global QLineEdit padding/radius clips the text
|
||||
inside a table row, so give editors a compact, flat style instead. */
|
||||
QTableWidget QLineEdit {{
|
||||
background: {PANEL_2}; color: {TEXT}; border: 1px solid {ACCENT};
|
||||
background: {p.panel_2}; color: {p.text}; border: 1px solid {p.accent};
|
||||
border-radius: 3px; padding: 0px 4px; margin: 0px;
|
||||
selection-background-color: {ACCENT_DIM}; selection-color: #ffffff;
|
||||
selection-background-color: {p.accent_dim}; selection-color: {p.selection_text};
|
||||
}}
|
||||
QHeaderView::section {{ background: {PANEL}; color: {MUTED}; border: none;
|
||||
border-bottom: 1px solid {BORDER}; padding: 8px; font-weight: 600; }}
|
||||
QHeaderView::section {{ background: {p.panel}; color: {p.muted}; border: none;
|
||||
border-bottom: 1px solid {p.border}; padding: 8px; font-weight: 600; }}
|
||||
QScrollBar:vertical {{ background: transparent; width: 10px; margin: 2px; }}
|
||||
QScrollBar::handle:vertical {{ background: {BORDER}; border-radius: 5px; min-height: 24px; }}
|
||||
QScrollBar::handle:vertical {{ background: {p.border}; border-radius: 5px; min-height: 24px; }}
|
||||
QScrollBar::add-line, QScrollBar::sub-line {{ height: 0; }}
|
||||
QLabel#statusbar {{ color: {MUTED}; padding: 4px 2px; }}
|
||||
QLabel#warnBanner {{ color: #1a1205; background: {WARN}; border-radius: 8px; padding: 8px 10px; font-weight: 600; }}
|
||||
QLabel#section {{ color: {MUTED}; font-weight: 600; font-size: 12px; padding: 2px 2px; }}
|
||||
QLabel#sectionDisabled {{ color: {MUTED}; font-weight: 600; font-size: 12px; padding: 2px 2px; }}
|
||||
QLabel#placeholder {{ color: {MUTED}; padding: 12px; background: {PANEL_2}; border: 1px dashed {BORDER}; border-radius: 8px; }}
|
||||
QTableWidget#disabledTable {{ background: #202229; }}
|
||||
QTableWidget#disabledTable::item:selected {{ background: {ACCENT}; color: #1a1205; }}
|
||||
QLabel#statusbar {{ color: {p.muted}; padding: 4px 2px; }}
|
||||
QLabel#warnBanner {{ color: {p.on_accent}; background: {p.warn}; border-radius: 8px; padding: 8px 10px; font-weight: 600; }}
|
||||
QFrame#noticeBanner {{ background: {p.panel_2}; border: 1px solid {p.accent}; border-radius: 8px; }}
|
||||
QLabel#noticeText {{ color: {p.text}; }}
|
||||
QPushButton#noticeClose {{ background: transparent; border: none; color: {p.muted}; font-size: 14px; padding: 2px; }}
|
||||
QPushButton#noticeClose:hover {{ color: {p.text}; }}
|
||||
QLabel#section {{ color: {p.muted}; font-weight: 600; font-size: 12px; padding: 2px 2px; }}
|
||||
QLabel#sectionDisabled {{ color: {p.muted}; font-weight: 600; font-size: 12px; padding: 2px 2px; }}
|
||||
QLabel#placeholder {{ color: {p.muted}; padding: 12px; background: {p.panel_2}; border: 1px dashed {p.border}; border-radius: 8px; }}
|
||||
QTableWidget#disabledTable {{ background: {p.disabled_bg}; }}
|
||||
QTableWidget#disabledTable::item:selected {{ background: {p.accent}; color: {p.on_accent}; }}
|
||||
QPlainTextEdit#diag {{ font-family: "Menlo", "Cascadia Code", "Consolas", "DejaVu Sans Mono", monospace;
|
||||
font-size: 12px; background: #16181d; border: 1px solid {BORDER}; border-radius: 8px; }}
|
||||
font-size: 12px; background: {p.mono_bg}; border: 1px solid {p.border}; border-radius: 8px; }}
|
||||
QFrame#diagCard {{ background: transparent; border: none; }}
|
||||
QSplitter::handle {{ background: transparent; }}
|
||||
QSplitter::handle:hover {{ background: {BORDER}; border-radius: 4px; }}
|
||||
QSplitter::handle:pressed {{ background: {ACCENT}; border-radius: 4px; }}
|
||||
QSplitter::handle:hover {{ background: {p.border}; border-radius: 4px; }}
|
||||
QSplitter::handle:pressed {{ background: {p.accent}; border-radius: 4px; }}
|
||||
"""
|
||||
|
||||
|
||||
def apply_palette(p: core.Palette) -> str:
|
||||
"""Rebind the module-level colour names to `p` and return its stylesheet."""
|
||||
global PALETTE, ACCENT, ACCENT_DIM, BG, PANEL, PANEL_2, TEXT, MUTED, BORDER
|
||||
global GOOD, BAD, WARN, REMOTE, ON_ACCENT, DISABLED_BG, MONO_BG, SEL_TEXT
|
||||
global STATUS_COLORS, HEALTH_COLORS
|
||||
PALETTE = p
|
||||
ACCENT, ACCENT_DIM = p.accent, p.accent_dim
|
||||
BG, PANEL, PANEL_2 = p.bg, p.panel, p.panel_2
|
||||
TEXT, MUTED, BORDER = p.text, p.muted, p.border
|
||||
GOOD, BAD, WARN, REMOTE = p.good, p.bad, p.warn, p.remote
|
||||
ON_ACCENT, DISABLED_BG, MONO_BG, SEL_TEXT = (
|
||||
p.on_accent,
|
||||
p.disabled_bg,
|
||||
p.mono_bg,
|
||||
p.selection_text,
|
||||
)
|
||||
STATUS_COLORS = {"ok": GOOD, "missing": BAD, "warn": WARN, "remote": REMOTE, "unknown": WARN}
|
||||
HEALTH_COLORS = {"ok": GOOD, "failed": BAD, "untested": MUTED}
|
||||
return build_stylesheet(p)
|
||||
|
||||
|
||||
STYLESHEET = apply_palette(core.DARK_PALETTE)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Background reachability tester (keeps the UI responsive during the request)
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -1493,6 +1533,54 @@ class AboutDialog(QDialog):
|
||||
QDesktopServices.openUrl(QUrl(self._release_url or core.RELEASES_URL))
|
||||
|
||||
|
||||
class NoticeBanner(QFrame):
|
||||
"""A persistent, dismissible notice with an optional action button.
|
||||
|
||||
The status bar is the wrong home for anything the user needs to act on --
|
||||
21 call sites rewrite it, so a message posted there is gone by the next
|
||||
click. That wiped the MSIX warning (#35) and then the update notice (#78).
|
||||
This is the shared mechanism so it doesn't happen a third time.
|
||||
"""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setObjectName("noticeBanner")
|
||||
row = QHBoxLayout(self)
|
||||
row.setContentsMargins(10, 8, 8, 8)
|
||||
row.setSpacing(8)
|
||||
self._label = QLabel("")
|
||||
self._label.setObjectName("noticeText")
|
||||
self._label.setWordWrap(True)
|
||||
row.addWidget(self._label, 1)
|
||||
self._action_btn = QPushButton("")
|
||||
self._action_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self._action_btn.hide()
|
||||
row.addWidget(self._action_btn)
|
||||
self._close_btn = QPushButton("\u2715")
|
||||
self._close_btn.setObjectName("noticeClose")
|
||||
self._close_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self._close_btn.setFixedWidth(26)
|
||||
self._close_btn.setToolTip("Dismiss")
|
||||
self._close_btn.clicked.connect(self.hide)
|
||||
row.addWidget(self._close_btn)
|
||||
self.hide()
|
||||
|
||||
def show_notice(self, text: str, action_label: str = "", on_action=None):
|
||||
self._label.setText(text)
|
||||
self._label.setToolTip(text)
|
||||
# Reconnect cleanly: a banner reused for a second notice would
|
||||
# otherwise fire the previous notice's action too.
|
||||
with contextlib.suppress(RuntimeError, TypeError):
|
||||
self._action_btn.clicked.disconnect()
|
||||
if action_label and on_action is not None:
|
||||
self._action_btn.setText(action_label)
|
||||
self._action_btn.clicked.connect(lambda _=False: on_action())
|
||||
self._action_btn.show()
|
||||
else:
|
||||
self._action_btn.hide()
|
||||
self.show()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Restart worker: core.restart_claude_desktop() blocks up to ~5 s on macOS
|
||||
# waiting for the old instance to exit, so it must run off the UI thread.
|
||||
@@ -1550,6 +1638,11 @@ class MainWindow(QMainWindow):
|
||||
self.warn_banner.hide()
|
||||
root.addWidget(self.warn_banner)
|
||||
|
||||
# Update availability gets its own persistent banner rather than a
|
||||
# status-line write, which the next UI action overwrites (#78).
|
||||
self.update_banner = NoticeBanner(self)
|
||||
root.addWidget(self.update_banner)
|
||||
|
||||
# User-draggable divider between the server list and the editor.
|
||||
split = QSplitter(Qt.Orientation.Horizontal)
|
||||
split.setChildrenCollapsible(False)
|
||||
@@ -1585,11 +1678,96 @@ class MainWindow(QMainWindow):
|
||||
|
||||
# --- menu bar ---------------------------------------------------------- #
|
||||
def _build_menu_bar(self):
|
||||
view_menu = self.menuBar().addMenu("&View")
|
||||
theme_menu = view_menu.addMenu("Theme")
|
||||
self._theme_group = QActionGroup(self)
|
||||
self._theme_group.setExclusive(True)
|
||||
current = stored_theme_setting()
|
||||
for setting, label in (
|
||||
(core.THEME_SYSTEM, "Match system"),
|
||||
(core.THEME_LIGHT, "Light"),
|
||||
(core.THEME_DARK, "Dark"),
|
||||
):
|
||||
act = QAction(label, self, checkable=True)
|
||||
act.setChecked(setting == current)
|
||||
act.triggered.connect(lambda _checked=False, s=setting: self._set_theme(s))
|
||||
self._theme_group.addAction(act)
|
||||
theme_menu.addAction(act)
|
||||
|
||||
help_menu = self.menuBar().addMenu("&Help")
|
||||
|
||||
# "Check for updates" used to exist only as a button inside the About
|
||||
# dialog, which is not somewhere anyone looks for it (#79).
|
||||
update_action = QAction("Check for updates…", self)
|
||||
# Explicit role: macOS relocates actions it recognises by text, and
|
||||
# some Qt versions treat "update" as application-menu material. Pin it
|
||||
# so the item stays where the menu says it is on every platform.
|
||||
update_action.setMenuRole(QAction.MenuRole.ApplicationSpecificRole)
|
||||
update_action.triggered.connect(self.check_for_updates)
|
||||
help_menu.addAction(update_action)
|
||||
help_menu.addSeparator()
|
||||
|
||||
about_action = QAction("About Better Claude Config…", self)
|
||||
# Qt auto-assigns AboutRole to actions whose text starts with "About",
|
||||
# which moves this into the application menu on macOS. That is the
|
||||
# right home there -- state it explicitly rather than inheriting it by
|
||||
# accident, since the behaviour is invisible from this call site.
|
||||
about_action.setMenuRole(QAction.MenuRole.AboutRole)
|
||||
about_action.triggered.connect(self._show_about)
|
||||
help_menu.addAction(about_action)
|
||||
|
||||
def _show_update_notice(self, notice: dict):
|
||||
"""Surface an available update where it survives the next click."""
|
||||
url = notice["url"]
|
||||
self.update_banner.show_notice(
|
||||
notice["text"],
|
||||
action_label="Open releases page",
|
||||
on_action=lambda: QDesktopServices.openUrl(QUrl(url)),
|
||||
)
|
||||
|
||||
def check_for_updates(self):
|
||||
"""Menu-driven check. Unlike the startup check this is never throttled
|
||||
and always reports back -- the user asked, so silence would read as a
|
||||
broken button."""
|
||||
self.status.setText("Checking for updates…")
|
||||
self._menu_update_worker = UpdateCheckWorker()
|
||||
self._menu_update_worker.done.connect(self._on_menu_update_checked)
|
||||
self._menu_update_worker.start()
|
||||
|
||||
def _on_menu_update_checked(self, release: dict | None):
|
||||
self._menu_update_worker = None
|
||||
if release is None:
|
||||
self.status.setText("Couldn't check for updates (offline?).")
|
||||
return
|
||||
QSettings("BCC", "BetterClaudeConfig").setValue("update/lastCheck", time.time())
|
||||
notice = core.update_notice(core.__version__, release)
|
||||
if notice:
|
||||
self._show_update_notice(notice)
|
||||
self.status.setText(f"Update available: {notice['version']}")
|
||||
else:
|
||||
self.update_banner.hide()
|
||||
self.status.setText(f"You're up to date ({core.__version__}).")
|
||||
|
||||
def _set_theme(self, setting: str):
|
||||
"""Persist the theme choice and repaint the running window."""
|
||||
QSettings("BCC", "BetterClaudeConfig").setValue("ui/theme", setting)
|
||||
app = QApplication.instance()
|
||||
if app is None: # pragma: no cover - only in a headless test harness
|
||||
return
|
||||
app.setStyleSheet(theme_stylesheet_for(app, setting))
|
||||
# The global stylesheet covers most of the UI, but the inline
|
||||
# setStyleSheet calls (status dots, warning labels, update banner) only
|
||||
# pick up the new palette when their widget next renders -- so re-render
|
||||
# them now rather than leaving dark-on-light text behind.
|
||||
self._repaint_themed_widgets()
|
||||
|
||||
def _repaint_themed_widgets(self):
|
||||
"""Re-run the inline-styled bits after a palette change."""
|
||||
self.status.setStyleSheet(f"color: {MUTED};")
|
||||
idx = self._current_index()
|
||||
self._refresh_tables(select_index=idx if idx >= 0 else -1)
|
||||
self._update_status(saved=False)
|
||||
|
||||
def _show_about(self):
|
||||
AboutDialog(self).exec()
|
||||
|
||||
@@ -1610,10 +1788,9 @@ class MainWindow(QMainWindow):
|
||||
if release is None:
|
||||
return # offline/failed check: don't advance lastCheck, allow retry
|
||||
QSettings("BCC", "BetterClaudeConfig").setValue("update/lastCheck", time.time())
|
||||
if core.is_newer_version(core.__version__, release["version"]):
|
||||
self.status.setText(
|
||||
f"Update available: {release['version']} · Help ▸ About to view it."
|
||||
)
|
||||
notice = core.update_notice(core.__version__, release)
|
||||
if notice:
|
||||
self._show_update_notice(notice)
|
||||
|
||||
# --- layout persistence ---------------------------------------------- #
|
||||
def _restore_layout(self):
|
||||
@@ -1939,9 +2116,21 @@ class MainWindow(QMainWindow):
|
||||
return
|
||||
self.full_config = cfg
|
||||
repaired = True
|
||||
# extract_servers tolerates malformed entries rather than raising (#72),
|
||||
# but keep it inside the guard: a load failure must leave the previously
|
||||
# loaded profile intact instead of half-swapping the window's state.
|
||||
try:
|
||||
servers = core.extract_servers(self.full_config)
|
||||
except Exception as exc: # pragma: no cover - defence in depth
|
||||
QMessageBox.critical(
|
||||
self,
|
||||
"Could not read config",
|
||||
f"{profile.path}\n\nThe server list couldn't be read: {exc}",
|
||||
)
|
||||
return
|
||||
self._loaded_stat = core.config_fingerprint(profile.path)
|
||||
self.current_profile = profile
|
||||
self.servers = core.extract_servers(self.full_config)
|
||||
self.servers = servers
|
||||
self.dirty = False
|
||||
self.restart_btn.hide()
|
||||
self._undo_stack.clear()
|
||||
@@ -2264,7 +2453,7 @@ class MainWindow(QMainWindow):
|
||||
entry = self.servers[idx]
|
||||
old_name = entry.name
|
||||
entry.name = self.editor.current_name()
|
||||
entry.data = self.editor.dump_data()
|
||||
entry.set_data(self.editor.dump_data())
|
||||
# The server stays in its section (enable state unchanged), so update
|
||||
# its existing row in place rather than re-rendering.
|
||||
# An edit invalidates any cached "Test all" result -- the server that
|
||||
@@ -2358,7 +2547,7 @@ class MainWindow(QMainWindow):
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
)
|
||||
if ans == QMessageBox.StandardButton.Yes:
|
||||
self.servers[existing[name]].data = data
|
||||
self.servers[existing[name]].set_data(data)
|
||||
return False, True
|
||||
name = core.resolve_name_collision(name, {s.name for s in self.servers})
|
||||
self.servers.append(core.ServerEntry(name, data, True))
|
||||
@@ -2478,6 +2667,11 @@ class MainWindow(QMainWindow):
|
||||
except Exception as e:
|
||||
QMessageBox.critical(self, "Reload failed", str(e))
|
||||
return
|
||||
# The reload above is the on-disk truth for everything the user
|
||||
# didn't touch -- but it also wipes BCC-authored keys the user
|
||||
# changed in this session (named sets), which apply_servers
|
||||
# doesn't write. Carry them over before saving (#73).
|
||||
contested = core.carry_owned_keys(self.full_config, fresh)
|
||||
core.apply_servers(fresh, self.servers)
|
||||
try:
|
||||
backup = core.write_config(self.current_profile.path, fresh)
|
||||
@@ -2490,8 +2684,13 @@ class MainWindow(QMainWindow):
|
||||
self.dirty = False
|
||||
self.save_btn.setEnabled(False)
|
||||
bnote = f" · backup: {backup.name}" if backup else " · (new file)"
|
||||
cnote = (
|
||||
f" · kept your {', '.join(contested)} (the file on disk had a different copy)"
|
||||
if contested
|
||||
else ""
|
||||
)
|
||||
self.status.setText(
|
||||
f"Merged & saved {self.current_profile.path}{bnote}"
|
||||
f"Merged & saved {self.current_profile.path}{bnote}{cnote}"
|
||||
f" · Restart {self.current_profile.label} to apply."
|
||||
)
|
||||
self._offer_restart_button()
|
||||
@@ -2649,6 +2848,33 @@ class MainWindow(QMainWindow):
|
||||
e.accept()
|
||||
|
||||
|
||||
def system_is_dark(app: QApplication) -> bool:
|
||||
"""Whether the desktop is currently using a dark appearance.
|
||||
|
||||
Read from the style's own window colour rather than per-platform APIs --
|
||||
Qt has already resolved the OS appearance by the time it builds the
|
||||
default palette, so this works the same on all three platforms.
|
||||
"""
|
||||
try:
|
||||
return app.palette().color(QPalette.ColorRole.Window).lightness() < 128
|
||||
except Exception: # pragma: no cover - defensive; never block startup on theming
|
||||
return True
|
||||
|
||||
|
||||
def stored_theme_setting() -> str:
|
||||
"""The user's theme choice, defaulting to following the system."""
|
||||
value = QSettings("BCC", "BetterClaudeConfig").value("ui/theme", core.THEME_SYSTEM)
|
||||
return value if value in core.THEME_CHOICES else core.THEME_SYSTEM
|
||||
|
||||
|
||||
def theme_stylesheet_for(app: QApplication, setting: str | None = None) -> str:
|
||||
"""Resolve setting + OS appearance into a palette, apply it, return the QSS."""
|
||||
if setting is None:
|
||||
setting = stored_theme_setting()
|
||||
theme = core.resolve_theme(setting, system_is_dark(app))
|
||||
return apply_palette(core.palette_for(theme))
|
||||
|
||||
|
||||
def main():
|
||||
if sys.platform == "win32":
|
||||
# Without an explicit AppUserModelID, Windows taskbar groups the app
|
||||
@@ -2667,7 +2893,7 @@ def main():
|
||||
icon = _app_icon()
|
||||
if not icon.isNull():
|
||||
app.setWindowIcon(icon)
|
||||
app.setStyleSheet(STYLESHEET)
|
||||
app.setStyleSheet(theme_stylesheet_for(app))
|
||||
win = MainWindow()
|
||||
win.show()
|
||||
sys.exit(app.exec())
|
||||
|
||||
+583
-47
@@ -13,7 +13,9 @@ in its original position.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import copy
|
||||
import difflib
|
||||
import functools
|
||||
import glob
|
||||
@@ -48,6 +50,12 @@ DISABLED_KEY = "_disabledMcpServers"
|
||||
# parks the rest under DISABLED_KEY.
|
||||
SETS_KEY = "_bccServerSets"
|
||||
|
||||
# Top-level keys BCC itself authors. They live in the client's config file, but
|
||||
# BCC is their owner, so on a stale-file merge the in-memory copy wins over the
|
||||
# on-disk one (see `carry_owned_keys`). Any future BCC-authored key belongs
|
||||
# here -- forgetting to add one is exactly how #73 happened.
|
||||
BCC_OWNED_KEYS = (SETS_KEY,)
|
||||
|
||||
BACKUP_DIRNAME = ".bcc_backups"
|
||||
MAX_BACKUPS = 15
|
||||
|
||||
@@ -162,6 +170,39 @@ def fetch_latest_release(timeout: float = 4.0) -> dict | None:
|
||||
return {"version": tag, "url": payload.get("html_url") or RELEASES_URL}
|
||||
|
||||
|
||||
def update_notice(
|
||||
current: str, release: dict | None, url_fallback: str = RELEASES_URL
|
||||
) -> dict | None:
|
||||
"""Decide whether to tell the user about a release, and what to say.
|
||||
|
||||
Returns {"version", "text", "url"} when `release` is newer than `current`,
|
||||
or None when it isn't, when the check failed, or when the payload is
|
||||
malformed. Kept here rather than in the GUI so the wording and the
|
||||
should-we-notify decision are testable -- bcc.py can't be imported by the
|
||||
test suite, which has no PySide6.
|
||||
|
||||
The text deliberately names no menu path. The old status-line notice read
|
||||
"Help > About to view it", which is wrong on macOS: Qt relocates the About
|
||||
action into the application menu (#79). A notice that carries its own
|
||||
action can't drift out of sync with the platform.
|
||||
"""
|
||||
if not isinstance(release, dict):
|
||||
return None
|
||||
version = release.get("version")
|
||||
if not version or not isinstance(version, str):
|
||||
return None
|
||||
if not is_newer_version(current, version):
|
||||
return None
|
||||
# Tags carry a "v" prefix and __version__ doesn't; render both the same way
|
||||
# so the notice doesn't read "Version v1.3.0 ... you're running 1.2.0".
|
||||
shown = version.lstrip("vV")
|
||||
return {
|
||||
"version": version,
|
||||
"text": f"Version {shown} is available. You're running {current.lstrip('vV')}.",
|
||||
"url": release.get("url") or url_fallback,
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Data model
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -177,16 +218,195 @@ class Profile:
|
||||
self.path = Path(self.path)
|
||||
|
||||
|
||||
class _NoRaw:
|
||||
"""Sentinel for ServerEntry.raw.
|
||||
|
||||
`None` can't do this job: `{"mcpServers": {"foo": null}}` is legal JSON and
|
||||
a real malformed-entry case, so None has to mean "the config said null",
|
||||
not "there was nothing here".
|
||||
"""
|
||||
|
||||
__slots__ = ()
|
||||
|
||||
def __repr__(self) -> str: # keeps ServerEntry reprs readable in test output
|
||||
return "<no raw>"
|
||||
|
||||
|
||||
NO_RAW = _NoRaw()
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerEntry:
|
||||
"""One server definition.
|
||||
|
||||
`data` is always a dict so every consumer can treat it as one. When the
|
||||
config held something that wasn't a JSON object for this server (a string,
|
||||
a number, a list -- all legal JSON, all wrong here), `data` is empty and
|
||||
the original value is preserved verbatim in `raw` so Save round-trips it
|
||||
instead of silently deleting the user's line. `lint_servers` surfaces it.
|
||||
`raw` defaults to the NO_RAW sentinel rather than None, because a config
|
||||
value of literal `null` is itself a malformed entry worth preserving.
|
||||
|
||||
Assigning `data` means the user replaced the definition through the editor,
|
||||
which retires `raw` -- use `set_data` so that can't be forgotten.
|
||||
"""
|
||||
|
||||
name: str
|
||||
data: dict
|
||||
enabled: bool = True
|
||||
raw: object = NO_RAW
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "remote" if "url" in self.data and "command" not in self.data else "stdio"
|
||||
|
||||
@property
|
||||
def malformed(self) -> bool:
|
||||
"""True when the config value for this server wasn't a JSON object."""
|
||||
return self.raw is not NO_RAW
|
||||
|
||||
def set_data(self, data: dict) -> None:
|
||||
"""Replace the definition from the editor, clearing any malformed original."""
|
||||
self.data = data
|
||||
self.raw = NO_RAW
|
||||
|
||||
def config_value(self):
|
||||
"""What to write back to the config: the edited dict, or the untouched
|
||||
malformed original when the user never edited it."""
|
||||
return self.data if self.raw is NO_RAW else self.raw
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Theming (issue #75)
|
||||
# --------------------------------------------------------------------------- #
|
||||
THEME_SYSTEM = "system"
|
||||
THEME_LIGHT = "light"
|
||||
THEME_DARK = "dark"
|
||||
THEME_CHOICES = (THEME_SYSTEM, THEME_LIGHT, THEME_DARK)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Palette:
|
||||
"""Every colour the UI draws with.
|
||||
|
||||
Deliberately exhaustive: the stylesheet used to inline a handful of
|
||||
near-black literals (`#1a1205` for text on the accent, `#202229` for the
|
||||
disabled table, `#16181d` for the diagnostics pane), which is fine while
|
||||
there's one theme and invisible breakage the moment there are two. Each
|
||||
gets a slot here so a light palette can't silently inherit a dark value.
|
||||
"""
|
||||
|
||||
name: str
|
||||
accent: str
|
||||
accent_dim: str
|
||||
bg: str
|
||||
panel: str
|
||||
panel_2: str
|
||||
text: str
|
||||
muted: str
|
||||
border: str
|
||||
good: str
|
||||
bad: str
|
||||
warn: str
|
||||
remote: str
|
||||
on_accent: str # text drawn on top of an accent fill
|
||||
disabled_bg: str # the parked-servers table
|
||||
mono_bg: str # diagnostics / log panes
|
||||
selection_text: str
|
||||
|
||||
|
||||
# The shipping theme through v1.3.0. These values are carried over verbatim --
|
||||
# adding a light theme must not restyle the dark one.
|
||||
DARK_PALETTE = Palette(
|
||||
name="dark",
|
||||
accent="#f97316",
|
||||
accent_dim="#c2570b",
|
||||
bg="#1b1d23",
|
||||
panel="#23262e",
|
||||
panel_2="#2b2f39",
|
||||
text="#e7e9ee",
|
||||
muted="#9aa0ad",
|
||||
border="#3a3f4b",
|
||||
good="#4ade80",
|
||||
bad="#f87171",
|
||||
warn="#fbbf24",
|
||||
remote="#60a5fa",
|
||||
on_accent="#1a1205",
|
||||
disabled_bg="#202229",
|
||||
mono_bg="#16181d",
|
||||
selection_text="#ffffff",
|
||||
)
|
||||
|
||||
# The semantic colours are NOT the dark ones lightened. #4ade80 / #fbbf24 sit
|
||||
# around 1.7:1 against white -- illegible. These are darkened to clear 4.5:1,
|
||||
# which `test_light_palette_meets_contrast` enforces so nobody "tidies" them
|
||||
# back toward the dark hues later.
|
||||
LIGHT_PALETTE = Palette(
|
||||
name="light",
|
||||
accent="#c2410c",
|
||||
accent_dim="#9a3412",
|
||||
bg="#f6f7f9",
|
||||
panel="#ffffff",
|
||||
panel_2="#eef0f4",
|
||||
text="#1b1d23",
|
||||
muted="#5c6270",
|
||||
border="#d3d7de",
|
||||
good="#15803d",
|
||||
bad="#b91c1c",
|
||||
warn="#a16207",
|
||||
remote="#1d4ed8",
|
||||
on_accent="#ffffff",
|
||||
disabled_bg="#e9ebef",
|
||||
mono_bg="#f0f2f5",
|
||||
selection_text="#ffffff",
|
||||
)
|
||||
|
||||
PALETTES = {DARK_PALETTE.name: DARK_PALETTE, LIGHT_PALETTE.name: LIGHT_PALETTE}
|
||||
|
||||
|
||||
def resolve_theme(setting: str, system_is_dark: bool) -> str:
|
||||
"""Map a stored theme setting + the OS appearance onto a concrete palette name.
|
||||
|
||||
Anything unrecognised (a hand-edited QSettings value, a setting written by
|
||||
a future version) falls back to following the system rather than to a
|
||||
fixed theme -- the user's desktop is the better guess.
|
||||
"""
|
||||
if setting == THEME_DARK:
|
||||
return THEME_DARK
|
||||
if setting == THEME_LIGHT:
|
||||
return THEME_LIGHT
|
||||
return THEME_DARK if system_is_dark else THEME_LIGHT
|
||||
|
||||
|
||||
def palette_for(theme: str) -> Palette:
|
||||
"""Concrete palette by name; unknown names fall back to dark (the historical look)."""
|
||||
return PALETTES.get(theme, DARK_PALETTE)
|
||||
|
||||
|
||||
def _hex_to_rgb(value: str) -> tuple[int, int, int]:
|
||||
v = value.lstrip("#")
|
||||
if len(v) == 3:
|
||||
v = "".join(ch * 2 for ch in v)
|
||||
return int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16)
|
||||
|
||||
|
||||
def relative_luminance(color: str) -> float:
|
||||
"""WCAG relative luminance for a #rrggbb colour."""
|
||||
|
||||
def chan(c: int) -> float:
|
||||
srgb = c / 255.0
|
||||
return srgb / 12.92 if srgb <= 0.04045 else ((srgb + 0.055) / 1.055) ** 2.4
|
||||
|
||||
r, g, b = (chan(c) for c in _hex_to_rgb(color))
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
|
||||
|
||||
def contrast_ratio(fg: str, bg: str) -> float:
|
||||
"""WCAG contrast ratio between two #rrggbb colours (1.0 to 21.0)."""
|
||||
a, b = relative_luminance(fg), relative_luminance(bg)
|
||||
lighter, darker = max(a, b), min(a, b)
|
||||
return (lighter + 0.05) / (darker + 0.05)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Discovery
|
||||
@@ -451,13 +671,30 @@ def repair_config_file(path: str | os.PathLike) -> tuple[dict, list[str], str]:
|
||||
return obj, notes, pretty
|
||||
|
||||
|
||||
def _server_entry(name: str, data, enabled: bool) -> ServerEntry:
|
||||
"""Build a ServerEntry, tolerating a value that isn't a JSON object.
|
||||
|
||||
A hand-edited config can legally hold `{"mcpServers": {"foo": "oops"}}` --
|
||||
valid JSON, wrong shape. Calling dict() on that raises, which used to take
|
||||
the whole load down before the linter ever got a look at it (#72). Keep the
|
||||
original instead and let the linter report it.
|
||||
"""
|
||||
if isinstance(data, dict):
|
||||
return ServerEntry(name=name, data=dict(data), enabled=enabled)
|
||||
return ServerEntry(name=name, data={}, enabled=enabled, raw=data)
|
||||
|
||||
|
||||
def extract_servers(cfg: dict) -> list[ServerEntry]:
|
||||
"""Pull enabled (`mcpServers`) and disabled (`_disabledMcpServers`) servers."""
|
||||
"""Pull enabled (`mcpServers`) and disabled (`_disabledMcpServers`) servers.
|
||||
|
||||
Never raises on a structurally-odd config -- malformed entries come back as
|
||||
empty-data entries carrying their original value (see `_server_entry`).
|
||||
"""
|
||||
out: list[ServerEntry] = []
|
||||
for name, data in (cfg.get("mcpServers") or {}).items():
|
||||
out.append(ServerEntry(name=name, data=dict(data), enabled=True))
|
||||
out.append(_server_entry(name, data, True))
|
||||
for name, data in (cfg.get(DISABLED_KEY) or {}).items():
|
||||
out.append(ServerEntry(name=name, data=dict(data), enabled=False))
|
||||
out.append(_server_entry(name, data, False))
|
||||
return out
|
||||
|
||||
|
||||
@@ -549,8 +786,8 @@ def apply_servers(cfg: dict, servers: list[ServerEntry]) -> dict:
|
||||
Write the server list back into `cfg` in place, preserving every other key
|
||||
and the position of `mcpServers`. Returns the same dict for convenience.
|
||||
"""
|
||||
enabled = {s.name: s.data for s in servers if s.enabled}
|
||||
disabled = {s.name: s.data for s in servers if not s.enabled}
|
||||
enabled = {s.name: s.config_value() for s in servers if s.enabled}
|
||||
disabled = {s.name: s.config_value() for s in servers if not s.enabled}
|
||||
|
||||
cfg["mcpServers"] = enabled # replaces value if key existed; appends otherwise
|
||||
if disabled:
|
||||
@@ -563,6 +800,34 @@ def apply_servers(cfg: dict, servers: list[ServerEntry]) -> dict:
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Write (atomic, with rotating backups)
|
||||
# --------------------------------------------------------------------------- #
|
||||
def carry_owned_keys(local_cfg: dict, fresh_cfg: dict) -> list[str]:
|
||||
"""Carry BCC-authored top-level keys from `local_cfg` onto `fresh_cfg`.
|
||||
|
||||
Used by the stale-file "Merge & save" path, which reloads the file from
|
||||
disk and re-applies the user's server edits. That reload used to drop
|
||||
anything BCC owns but `apply_servers` doesn't write -- named server sets
|
||||
vanished without a word (#73). BCC owns these keys, so the in-memory copy
|
||||
wins; mutates `fresh_cfg` in place.
|
||||
|
||||
Returns the keys where the on-disk copy differed and was overwritten, so
|
||||
the caller can tell the user something was actually contested rather than
|
||||
merely carried across.
|
||||
|
||||
Deliberately one-directional: a key absent locally is left alone on disk.
|
||||
We can't tell "user deleted their last set" from "user never had sets and
|
||||
another machine just added some", and silently deleting someone else's
|
||||
data is the worse of the two failures.
|
||||
"""
|
||||
conflicts: list[str] = []
|
||||
for key in BCC_OWNED_KEYS:
|
||||
if key not in local_cfg:
|
||||
continue
|
||||
if key in fresh_cfg and fresh_cfg[key] != local_cfg[key]:
|
||||
conflicts.append(key)
|
||||
fresh_cfg[key] = copy.deepcopy(local_cfg[key])
|
||||
return conflicts
|
||||
|
||||
|
||||
def _make_backup(path: Path) -> Path:
|
||||
bdir = path.parent / BACKUP_DIRNAME
|
||||
bdir.mkdir(exist_ok=True)
|
||||
@@ -1379,9 +1644,21 @@ def lint_server(name: str, data: dict) -> list[str]:
|
||||
|
||||
|
||||
def lint_servers(servers: list[ServerEntry]) -> list[str]:
|
||||
"""Concatenate lint_server warnings across every entry, in order."""
|
||||
"""Concatenate lint_server warnings across every entry, in order.
|
||||
|
||||
Entries whose config value wasn't a JSON object at all are reported here
|
||||
rather than in lint_server, which takes an already-dict `data` (#72).
|
||||
"""
|
||||
out: list[str] = []
|
||||
for s in servers:
|
||||
if s.malformed:
|
||||
nm = s.name.strip() or "(unnamed)"
|
||||
out.append(
|
||||
f"'{nm}': server definition is not an object "
|
||||
f"(found {type(s.raw).__name__}) -- it is preserved as-is; "
|
||||
f"edit it to replace it with a proper definition"
|
||||
)
|
||||
continue
|
||||
out.extend(lint_server(s.name, s.data))
|
||||
return out
|
||||
|
||||
@@ -2163,12 +2440,36 @@ def restart_claude_desktop() -> RestartResult:
|
||||
# is rejected by validate_catalog() regardless of how plausible it looks.
|
||||
CATALOG_ALLOWED_COMMANDS = frozenset({"npx", "uvx", "docker", "node", "python", "python3"})
|
||||
|
||||
# Env var keys a catalog entry's config.env must never set. Every one of
|
||||
# these is a loader/interpreter override that lets a value walk straight
|
||||
# past CATALOG_ALLOWED_COMMANDS and the -e/--eval/-c deny-rule below: e.g.
|
||||
# NODE_OPTIONS="--require /tmp/x.js" turns an allowlisted `npx` entry into
|
||||
# arbitrary code execution without ever touching config.args, which is the
|
||||
# only field the allowlist/deny-rules/ASCII/secret checks used to cover.
|
||||
# Matched case-insensitively -- env keys are case-sensitive on POSIX, but a
|
||||
# `node_options` lookalike is exactly the kind of thing this must catch.
|
||||
CATALOG_DENIED_ENV_KEYS = frozenset(
|
||||
{
|
||||
"NODE_OPTIONS",
|
||||
"PYTHONSTARTUP",
|
||||
"PYTHONPATH",
|
||||
"PYTHONHOME",
|
||||
"LD_PRELOAD",
|
||||
"LD_LIBRARY_PATH",
|
||||
"DYLD_INSERT_LIBRARIES",
|
||||
"DYLD_LIBRARY_PATH",
|
||||
"BROWSER",
|
||||
"PATH",
|
||||
"NODE_REPL_EXTERNAL_MODULE",
|
||||
}
|
||||
)
|
||||
|
||||
# Ed25519 public keys allowed to sign a catalog, raw 32-byte form. A LIST
|
||||
# (not a single key) so keys can be rotated without bricking installs that
|
||||
# still trust an older key: verify_catalog_signature() accepts a match
|
||||
# against ANY key in this list.
|
||||
CATALOG_PUBKEYS: list[bytes] = [
|
||||
b"\x00" * 32, # TODO: real key from Catalog Console (#62)
|
||||
base64.b64decode("082NOwVB7uURkvfyS3+knJ+40Fk6C9unsF47+2uPKo4="),
|
||||
]
|
||||
|
||||
# Domain-separation prefix for the signed message. The signature covers
|
||||
@@ -2188,6 +2489,36 @@ _CATALOG_SECRET_ARG_RE = re.compile(r"(?i)--api[-_]?key=|--token=|--password=")
|
||||
# <PLACEHOLDER>-style tokens the GUI must have the user fill in before Save.
|
||||
_PLACEHOLDER_RE = re.compile(r"<[^<>\s]+>")
|
||||
|
||||
# A catalog entry's id becomes an mcpServers JSON key AND is interpolated
|
||||
# into Qt.AutoText widgets (status bar, QMessageBox) -- an id like
|
||||
# "<b>Verified</b>" renders as markup there. Not RCE, but UI spoofing, so
|
||||
# ids are constrained to a plain lowercase slug.
|
||||
_CATALOG_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
|
||||
|
||||
# Docker flags that consume the next arg as a value (so that value must not
|
||||
# be mistaken for the image reference when locating it in config.args).
|
||||
_DOCKER_VALUE_FLAGS = frozenset(
|
||||
{
|
||||
"-e",
|
||||
"--env",
|
||||
"-v",
|
||||
"--volume",
|
||||
"-p",
|
||||
"--publish",
|
||||
"--name",
|
||||
"-w",
|
||||
"--workdir",
|
||||
"-u",
|
||||
"--user",
|
||||
"--entrypoint",
|
||||
"--network",
|
||||
"--platform",
|
||||
"--add-host",
|
||||
"-l",
|
||||
"--label",
|
||||
}
|
||||
)
|
||||
|
||||
# How many versions a single accepted catalog jump may leap in one go. Bounds
|
||||
# a "freeze" attack: a compromised/leaked signing key claiming an absurd
|
||||
# future version would otherwise permanently outrank every legitimate
|
||||
@@ -2262,6 +2593,121 @@ def _docker_arg_violations(tag: str, args: list[str]) -> list[str]:
|
||||
return problems
|
||||
|
||||
|
||||
def _catalog_package_spec_version(spec: str) -> str | None:
|
||||
"""
|
||||
Extract the version pin from an npm-style package spec, or None if the
|
||||
spec carries no pin.
|
||||
|
||||
Handles unscoped "name@version" and scoped "@scope/name@version" --
|
||||
scoped names have a leading "@" that is NOT the version separator, so a
|
||||
naive split on the first/only "@" misparses "@scope/pkg" (no version)
|
||||
as pinned to "scope/pkg". Splitting from the right side instead is safe
|
||||
for both forms because a package name may contain "@" only as the
|
||||
scope's leading character.
|
||||
"""
|
||||
if spec.startswith("@"):
|
||||
rest = spec[1:]
|
||||
if "@" not in rest:
|
||||
return None
|
||||
_, _, version = rest.rpartition("@")
|
||||
return version or None
|
||||
if "@" not in spec:
|
||||
return None
|
||||
_, _, version = spec.rpartition("@")
|
||||
return version or None
|
||||
|
||||
|
||||
def _catalog_package_spec_pinned(spec: str) -> bool:
|
||||
"""
|
||||
True if `spec` carries an exact version pin. Covers npm's "name@version"
|
||||
/ "@scope/name@version" and uv's documented PyPI pin forms
|
||||
"name@version" and "name==version".
|
||||
"""
|
||||
if "==" in spec:
|
||||
_, _, version = spec.partition("==")
|
||||
return bool(version)
|
||||
return bool(_catalog_package_spec_version(spec))
|
||||
|
||||
|
||||
def _first_catalog_package_spec(args: list[str]) -> str | None:
|
||||
"""
|
||||
The first arg that could plausibly BE a package spec: skip flags
|
||||
(leading "-") and <PLACEHOLDER> tokens (which can't be validated and
|
||||
are filled in by the user later, never shipped by the catalog as the
|
||||
package name itself). Everything after the first hit is ignored --
|
||||
trailing flags, paths, and placeholders are not package specs.
|
||||
"""
|
||||
for a in args:
|
||||
if a.startswith("-"):
|
||||
continue
|
||||
if _PLACEHOLDER_RE.fullmatch(a):
|
||||
continue
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def _catalog_pin_violations(tag: str, command: str, args: list[str]) -> list[str]:
|
||||
"""
|
||||
Version-pinning enforcement (finding #3): a catalog PR can otherwise
|
||||
ship `npx -y @scope/pkg` or `docker run img:latest` and the *next*
|
||||
resolve of that package/image is whatever the registry serves that day
|
||||
-- outside review, outside the signature's meaning. This is the only
|
||||
place that enforces pinning at runtime; catalog_review.py's
|
||||
risk_unpinned_package() is a maintainer-facing hint, not a gate.
|
||||
"""
|
||||
if command in ("npx", "uvx"):
|
||||
spec = _first_catalog_package_spec(args)
|
||||
if spec is None:
|
||||
return [f"{tag}: config.args must include a package spec to pin (e.g. name@1.2.3)."]
|
||||
if not _catalog_package_spec_pinned(spec):
|
||||
return [
|
||||
f"{tag}: config.args package {spec!r} is not version-pinned; use "
|
||||
"name@version, @scope/name@version, or name==version."
|
||||
]
|
||||
return []
|
||||
|
||||
if command == "docker":
|
||||
image = _docker_image_ref(args)
|
||||
if image is None:
|
||||
return [f"{tag}: config.args docker command has no image reference to pin."]
|
||||
_, sep, image_tag = image.rpartition(":")
|
||||
if not sep or "/" in image_tag:
|
||||
return [
|
||||
f"{tag}: config.args docker image {image!r} has no explicit tag; "
|
||||
"pin an exact version (not 'latest', not untagged)."
|
||||
]
|
||||
if image_tag == "latest":
|
||||
return [
|
||||
f"{tag}: config.args docker image {image!r} uses the 'latest' tag, "
|
||||
"which is not allowed; pin an exact version."
|
||||
]
|
||||
return []
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def _docker_image_ref(args: list[str]) -> str | None:
|
||||
"""
|
||||
Locate the image reference in a `docker run ...` args list: skip the
|
||||
"run" subcommand and any flags, including ones that consume the next
|
||||
token as a value (-e, -v, --name, ...) so that value isn't mistaken for
|
||||
the image. The first remaining positional token is the image.
|
||||
"""
|
||||
i = 0
|
||||
if i < len(args) and args[i] == "run":
|
||||
i += 1
|
||||
while i < len(args):
|
||||
a = args[i]
|
||||
if a.startswith("-"):
|
||||
if a in _DOCKER_VALUE_FLAGS and "=" not in a:
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
continue
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def _validate_catalog_config(tag: str, config) -> list[str]:
|
||||
"""Validate the `config` block of a basic-tier catalog entry."""
|
||||
if not isinstance(config, dict):
|
||||
@@ -2282,10 +2728,11 @@ def _validate_catalog_config(tag: str, config) -> list[str]:
|
||||
f"({', '.join(sorted(CATALOG_ALLOWED_COMMANDS))})."
|
||||
)
|
||||
|
||||
args = config.get("args")
|
||||
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
|
||||
raw_args = config.get("args")
|
||||
args_ok = isinstance(raw_args, list) and all(isinstance(a, str) for a in raw_args)
|
||||
args = raw_args if args_ok else []
|
||||
if not args_ok:
|
||||
problems.append(f"{tag}: config.args must be a list of strings.")
|
||||
args = []
|
||||
|
||||
for a in args:
|
||||
if not a.isascii():
|
||||
@@ -2304,11 +2751,55 @@ def _validate_catalog_config(tag: str, config) -> list[str]:
|
||||
if command == "docker":
|
||||
problems.extend(_docker_arg_violations(tag, args))
|
||||
|
||||
# Version pinning (finding #3) -- only meaningful once command/args are
|
||||
# actually well-formed; a malformed args list already got its own
|
||||
# problem above and has nothing left to pin-check.
|
||||
if args_ok and command in ("npx", "uvx", "docker"):
|
||||
problems.extend(_catalog_pin_violations(tag, command, args))
|
||||
|
||||
env = config.get("env")
|
||||
if env is not None and (
|
||||
not isinstance(env, dict) or any(not isinstance(v, str) for v in env.values())
|
||||
):
|
||||
problems.append(f"{tag}: config.env must be an object of string values.")
|
||||
if env is not None:
|
||||
env_ok = isinstance(env, dict) and all(
|
||||
isinstance(k, str) and isinstance(v, str) for k, v in env.items()
|
||||
)
|
||||
if not env_ok:
|
||||
problems.append(f"{tag}: config.env must be an object of string values.")
|
||||
else:
|
||||
# config.env (finding #2): unlike args, env was previously
|
||||
# type-checked ONLY -- no allowlist, no deny-rule, no ASCII
|
||||
# check, no secret check. That made it the single easiest way
|
||||
# to smuggle a payload past every other guard in this
|
||||
# function: an allowlisted `command: npx` plus
|
||||
# NODE_OPTIONS=--require /tmp/x.js in env walks straight past
|
||||
# the command allowlist AND the -e/--eval/-c deny-rule above,
|
||||
# because neither of those ever looks at env.
|
||||
for key, value in env.items():
|
||||
if not key.isascii():
|
||||
problems.append(
|
||||
f"{tag}: config.env key {key!r} must be ASCII "
|
||||
"(non-ASCII code points rejected)."
|
||||
)
|
||||
if key.upper() in CATALOG_DENIED_ENV_KEYS:
|
||||
problems.append(
|
||||
f"{tag}: config.env key {key!r} is on the catalog deny-list "
|
||||
"(interpreter/loader override) and is not allowed."
|
||||
)
|
||||
if not value.isascii():
|
||||
problems.append(
|
||||
f"{tag}: config.env value for {key!r} must be ASCII "
|
||||
"(non-ASCII code points rejected)."
|
||||
)
|
||||
if _is_secret_value(value):
|
||||
problems.append(
|
||||
f"{tag}: config.env[{key!r}] looks like a real secret value; "
|
||||
"catalog entries must never ship secret values."
|
||||
)
|
||||
if value != "" and not _PLACEHOLDER_RE.fullmatch(value):
|
||||
problems.append(
|
||||
f"{tag}: config.env[{key!r}] must be an empty string or a "
|
||||
"single <PLACEHOLDER> token -- the catalog declares which env "
|
||||
"vars a server needs, it never supplies their values."
|
||||
)
|
||||
|
||||
return problems
|
||||
|
||||
@@ -2328,6 +2819,12 @@ def _validate_catalog_entry(idx: int, entry, seen_ids: set[str]) -> list[str]:
|
||||
tag = f"servers[{idx}] ({entry_id!r})"
|
||||
if not entry_id.isascii():
|
||||
problems.append(f"{tag}: 'id' must be ASCII (non-ASCII code points rejected).")
|
||||
elif not _CATALOG_ID_RE.match(entry_id):
|
||||
problems.append(
|
||||
f"{tag}: 'id' must match ^[a-z0-9][a-z0-9._-]{{0,63}}$ "
|
||||
"(it becomes an mcpServers JSON key and is interpolated into "
|
||||
"Qt.AutoText widgets)."
|
||||
)
|
||||
if entry_id in seen_ids:
|
||||
problems.append(f"{tag}: duplicate id.")
|
||||
seen_ids.add(entry_id)
|
||||
@@ -2441,15 +2938,32 @@ def verify_catalog_signature(raw: bytes, sig: bytes, pubkeys: list[bytes]) -> bo
|
||||
return False
|
||||
|
||||
|
||||
def _verify_catalog_candidate(candidate: tuple[bytes, bytes] | None) -> tuple[dict | None, int]:
|
||||
"""Verify+load+validate one (raw, sig) candidate. Returns (None, -1) on any failure."""
|
||||
if not candidate:
|
||||
return None, -1
|
||||
raw, sig = candidate
|
||||
if not verify_catalog_signature(raw, sig, CATALOG_PUBKEYS):
|
||||
return None, -1
|
||||
try:
|
||||
data = load_catalog(raw)
|
||||
except (ValueError, TypeError):
|
||||
return None, -1
|
||||
if validate_catalog(data):
|
||||
return None, -1
|
||||
return data, catalog_version(data)
|
||||
|
||||
|
||||
def resolve_catalog(
|
||||
bundled: tuple[bytes, bytes] | None,
|
||||
cached: tuple[bytes, bytes] | None,
|
||||
remote: tuple[bytes, bytes] | None,
|
||||
floor: int = 0,
|
||||
) -> dict:
|
||||
"""
|
||||
Pick the highest-version catalog among bundled/cached/remote. Each
|
||||
argument is either None (unavailable) or an (raw_bytes, signature_bytes)
|
||||
pair.
|
||||
Pick the highest-version catalog among bundled/cached/remote. Each of
|
||||
bundled/cached/remote is either None (unavailable) or an (raw_bytes,
|
||||
signature_bytes) pair.
|
||||
|
||||
🔴 SECURITY: every candidate — including `bundled`, the copy frozen into
|
||||
this binary — is verified against CATALOG_PUBKEYS and re-validated from
|
||||
@@ -2460,46 +2974,68 @@ def resolve_catalog(
|
||||
by virtue of being local. Signing (and checking the signature at
|
||||
runtime, every time) closes that.
|
||||
|
||||
Anti-rollback: a candidate's version is never accepted if it's lower
|
||||
than the best verified candidate already found in this same resolution
|
||||
pass — an attacker replaying an old, since-superseded signed catalog
|
||||
can't downgrade you.
|
||||
`floor` is a pure, caller-supplied lower bound (e.g. a persisted
|
||||
"last accepted version" the GUI can load from disk and pass in) — this
|
||||
function does no storage of its own.
|
||||
|
||||
Anti-freeze: a candidate whose version leaps more than
|
||||
_CATALOG_MAX_VERSION_JUMP past the current best is also rejected. A
|
||||
compromised/leaked signing key claiming an absurd future version would
|
||||
otherwise permanently outrank every legitimate release from then on,
|
||||
since the resolver always prefers the highest verified version — this
|
||||
caps how far a single accepted jump can go.
|
||||
Anti-rollback / anti-freeze, and WHY they apply to every candidate
|
||||
including the first one evaluated: the previous version of this
|
||||
function only ran these checks `if best_version >= 0`, i.e. once a
|
||||
candidate had already been accepted in this pass. That let the FIRST
|
||||
verified candidate through unconditionally — a signed catalog claiming
|
||||
version=999999999 sailed straight past both guards if it happened to be
|
||||
evaluated first, and rollback protection reset on every call anyway
|
||||
(nothing persisted across restarts). Now both guards are anchored to
|
||||
something that doesn't depend on iteration order:
|
||||
|
||||
- The anti-freeze cap is measured against the BUNDLED catalog's version
|
||||
(verified independently, once), not against "whatever was accepted
|
||||
so far in this loop." Bundled ships inside the binary, so it's the
|
||||
one candidate that isn't attacker-supplied at resolve time — the
|
||||
natural trust anchor. If bundled itself doesn't verify, `floor` is
|
||||
the anchor instead.
|
||||
- The anti-rollback floor is max(floor, bundled's version), so a
|
||||
caller that persists `floor` across restarts gets real rollback
|
||||
protection; a caller that doesn't still gets "never below bundled."
|
||||
|
||||
On a version TIE, the bundled candidate wins over cached/remote (it
|
||||
previously lost ties to whichever candidate happened to be evaluated
|
||||
last, silently preferring remote over bundled at equal version).
|
||||
|
||||
Returns the winning catalog dict, or {} if nothing verified and
|
||||
validated.
|
||||
"""
|
||||
bundled_data, bundled_version = _verify_catalog_candidate(bundled)
|
||||
|
||||
anchor = bundled_version if bundled_version >= 0 else floor
|
||||
min_accepted = max(floor, bundled_version if bundled_version >= 0 else 0)
|
||||
|
||||
candidates = (
|
||||
("bundled", bundled_data, bundled_version),
|
||||
("cached", *_verify_catalog_candidate(cached)),
|
||||
("remote", *_verify_catalog_candidate(remote)),
|
||||
)
|
||||
|
||||
best: dict = {}
|
||||
best_version = -1
|
||||
best_is_bundled = False
|
||||
|
||||
for candidate in (bundled, cached, remote):
|
||||
if not candidate:
|
||||
continue
|
||||
raw, sig = candidate
|
||||
if not verify_catalog_signature(raw, sig, CATALOG_PUBKEYS):
|
||||
continue
|
||||
try:
|
||||
data = load_catalog(raw)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if validate_catalog(data):
|
||||
for source, data, version in candidates:
|
||||
if data is None:
|
||||
continue
|
||||
if version < min_accepted:
|
||||
continue # anti-rollback / below the persisted floor
|
||||
if version > anchor + _CATALOG_MAX_VERSION_JUMP:
|
||||
continue # anti-freeze, capped against the bundled trust anchor
|
||||
|
||||
version = catalog_version(data)
|
||||
if best_version >= 0:
|
||||
if version < best_version:
|
||||
continue # anti-rollback
|
||||
if version > best_version + _CATALOG_MAX_VERSION_JUMP:
|
||||
continue # anti-freeze
|
||||
|
||||
best = data
|
||||
best_version = version
|
||||
is_bundled = source == "bundled"
|
||||
better = version > best_version or (
|
||||
version == best_version and is_bundled and not best_is_bundled
|
||||
)
|
||||
if better:
|
||||
best = data
|
||||
best_version = version
|
||||
best_is_bundled = is_bundled
|
||||
|
||||
return best
|
||||
|
||||
|
||||
+1040
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,818 @@
|
||||
"""
|
||||
catalog_review.py -- pure, GUI-free review/diff/risk/crypto logic for the
|
||||
Catalog Console (issue #62).
|
||||
|
||||
This module is deliberately Qt-free and network-free so every function in it
|
||||
is unit-testable offline, exactly like bcc_core.py. catalog_console.py (the
|
||||
PySide6 GUI) is a thin shell over these functions -- it owns Qt widgets,
|
||||
subprocess/git calls, and HTTP registry lookups; this module owns judgment.
|
||||
|
||||
Nothing here is reimplemented from bcc_core: the command allowlist and the
|
||||
signature domain-separation prefix are imported, not retyped, so the two
|
||||
modules cannot silently drift apart (see bcc_core.validate_catalog /
|
||||
bcc_core.verify_catalog_signature and the project's "the check drifted on a
|
||||
new surface" recurring-bug lesson).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from bcc_core import _CATALOG_SIG_DOMAIN as CATALOG_SIG_DOMAIN
|
||||
from bcc_core import CATALOG_ALLOWED_COMMANDS
|
||||
from bcc_core import verify_catalog_signature as _verify_catalog_signature
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Semantic diff
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# Top-level scalar/simple fields compared directly (not drilled into).
|
||||
_DIFF_FIELDS = (
|
||||
"display",
|
||||
"description",
|
||||
"category",
|
||||
"official",
|
||||
"setup",
|
||||
"homepage",
|
||||
"docs_url",
|
||||
"source",
|
||||
"notes",
|
||||
"stars",
|
||||
"last_release",
|
||||
"env_required",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FieldChange:
|
||||
"""One field that differs between the old and new version of an entry."""
|
||||
|
||||
field: str
|
||||
old: object
|
||||
new: object
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntryChange:
|
||||
"""One catalog entry's change: added, removed, or changed.
|
||||
|
||||
`old`/`new` are the raw entry dicts (or None for added/removed) so risk
|
||||
predicates and the GUI can inspect anything not captured by
|
||||
`field_changes` (which only lists fields that actually differ).
|
||||
"""
|
||||
|
||||
entry_id: str
|
||||
status: str # "added" | "removed" | "changed"
|
||||
old: dict | None
|
||||
new: dict | None
|
||||
field_changes: tuple[FieldChange, ...] = ()
|
||||
|
||||
|
||||
def _config_field_changes(old_cfg: dict | None, new_cfg: dict | None) -> list[FieldChange]:
|
||||
old_cfg = old_cfg or {}
|
||||
new_cfg = new_cfg or {}
|
||||
changes: list[FieldChange] = []
|
||||
for f in ("command", "args", "env"):
|
||||
ov, nv = old_cfg.get(f), new_cfg.get(f)
|
||||
if ov != nv:
|
||||
changes.append(FieldChange(f"config.{f}", ov, nv))
|
||||
return changes
|
||||
|
||||
|
||||
def _entry_field_changes(old_entry: dict, new_entry: dict) -> tuple[FieldChange, ...]:
|
||||
changes: list[FieldChange] = []
|
||||
for f in _DIFF_FIELDS:
|
||||
ov, nv = old_entry.get(f), new_entry.get(f)
|
||||
if ov != nv:
|
||||
changes.append(FieldChange(f, ov, nv))
|
||||
changes.extend(_config_field_changes(old_entry.get("config"), new_entry.get("config")))
|
||||
return tuple(changes)
|
||||
|
||||
|
||||
def diff_catalogs(old: dict | None, new: dict | None) -> list[EntryChange]:
|
||||
"""Semantic (per-entry) diff between two parsed catalog dicts.
|
||||
|
||||
NOT a text diff: entries are matched by `id`, and each changed entry
|
||||
reports exactly which fields differ (with before/after values), which is
|
||||
what lets the Console render "command changed from X to Y" instead of a
|
||||
JSON line diff a reviewer has to mentally reconstruct.
|
||||
|
||||
Entries missing/malformed `id` are ignored here -- that is a
|
||||
validate_catalog() rejection, not a diffing concern, and diffing must not
|
||||
silently invent a match for two differently-broken entries.
|
||||
"""
|
||||
old_servers = {
|
||||
e["id"]: e
|
||||
for e in (old or {}).get("servers", []) or []
|
||||
if isinstance(e, dict) and isinstance(e.get("id"), str) and e.get("id")
|
||||
}
|
||||
new_servers = {
|
||||
e["id"]: e
|
||||
for e in (new or {}).get("servers", []) or []
|
||||
if isinstance(e, dict) and isinstance(e.get("id"), str) and e.get("id")
|
||||
}
|
||||
|
||||
changes: list[EntryChange] = []
|
||||
for entry_id in sorted(set(old_servers) | set(new_servers)):
|
||||
old_e = old_servers.get(entry_id)
|
||||
new_e = new_servers.get(entry_id)
|
||||
if old_e is None:
|
||||
changes.append(EntryChange(entry_id, "added", None, new_e, ()))
|
||||
elif new_e is None:
|
||||
changes.append(EntryChange(entry_id, "removed", old_e, None, ()))
|
||||
elif old_e != new_e:
|
||||
fc = _entry_field_changes(old_e, new_e)
|
||||
if fc:
|
||||
changes.append(EntryChange(entry_id, "changed", old_e, new_e, fc))
|
||||
return changes
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Risk annotations -- each predicate is pure and independently unit-tested.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RiskFinding:
|
||||
severity: str # "blocking" | "warning" | "info"
|
||||
code: str
|
||||
message: str
|
||||
|
||||
|
||||
def _escape_non_ascii(s: str) -> str:
|
||||
"""Render a string with any non-ASCII code point shown as an escape
|
||||
sequence, so a homoglyph/RTL-override character can't visually pass as
|
||||
the real thing in the review UI."""
|
||||
return s.encode("unicode_escape").decode("ascii")
|
||||
|
||||
|
||||
def risk_env_required(change: EntryChange) -> list[RiskFinding]:
|
||||
"""A non-empty env_required value is blocking: catalog entries must ship
|
||||
only the *names* of env vars the user fills in, never values."""
|
||||
entry = change.new or {}
|
||||
env_required = entry.get("env_required")
|
||||
findings: list[RiskFinding] = []
|
||||
if isinstance(env_required, dict):
|
||||
for k, v in env_required.items():
|
||||
if v not in (None, ""):
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"env_required_value",
|
||||
f"env_required[{k!r}] carries a non-empty value -- catalog "
|
||||
"entries must never ship secret values, only placeholder names.",
|
||||
)
|
||||
)
|
||||
return findings
|
||||
|
||||
|
||||
def risk_command_allowlist(change: EntryChange) -> list[RiskFinding]:
|
||||
"""A command outside bcc_core.CATALOG_ALLOWED_COMMANDS is blocking.
|
||||
Imports the allowlist rather than redefining it."""
|
||||
entry = change.new or {}
|
||||
config = entry.get("config") or {}
|
||||
command = config.get("command")
|
||||
if isinstance(command, str) and command and command not in CATALOG_ALLOWED_COMMANDS:
|
||||
return [
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"command_not_allowed",
|
||||
f"command {command!r} is not on the catalog allowlist "
|
||||
f"({', '.join(sorted(CATALOG_ALLOWED_COMMANDS))}).",
|
||||
)
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
def risk_non_ascii(change: EntryChange) -> list[RiskFinding]:
|
||||
"""Non-ASCII code points in id/command/args are blocking -- homoglyph /
|
||||
RTL-override typosquatting can make a malicious package name visually
|
||||
identical to a legitimate one in a naive diff view."""
|
||||
entry = change.new or {}
|
||||
findings: list[RiskFinding] = []
|
||||
|
||||
entry_id = entry.get("id")
|
||||
if isinstance(entry_id, str) and not entry_id.isascii():
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"non_ascii_id",
|
||||
f"id contains non-ASCII code points: {_escape_non_ascii(entry_id)!r}",
|
||||
)
|
||||
)
|
||||
|
||||
config = entry.get("config") or {}
|
||||
command = config.get("command")
|
||||
if isinstance(command, str) and not command.isascii():
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"non_ascii_command",
|
||||
f"command contains non-ASCII code points: {_escape_non_ascii(command)!r}",
|
||||
)
|
||||
)
|
||||
|
||||
for a in config.get("args") or []:
|
||||
if isinstance(a, str) and not a.isascii():
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"non_ascii_arg",
|
||||
f"arg contains non-ASCII code points: {_escape_non_ascii(a)!r}",
|
||||
)
|
||||
)
|
||||
|
||||
return findings
|
||||
|
||||
|
||||
def _npm_candidate_args(command: str | None, args: list[str]) -> list[str]:
|
||||
if command != "npx":
|
||||
return []
|
||||
return [a for a in args if isinstance(a, str) and a and not a.startswith("-")]
|
||||
|
||||
|
||||
def split_npm_spec(spec: str) -> tuple[str, str | None]:
|
||||
"""Split an npm package spec into (name, version). version is None if
|
||||
unpinned. Handles scoped (@scope/name@version) and unscoped
|
||||
(name@version) specs."""
|
||||
if spec.startswith("@"):
|
||||
rest = spec[1:]
|
||||
if "/" not in rest:
|
||||
return spec, None # malformed scope, can't tell -- treat unpinned
|
||||
scope, _, remainder = rest.partition("/")
|
||||
if "@" in remainder:
|
||||
pkg_name, _, version = remainder.partition("@")
|
||||
return f"@{scope}/{pkg_name}", (version or None)
|
||||
return f"@{scope}/{remainder}", None
|
||||
if "@" in spec:
|
||||
name, _, version = spec.partition("@")
|
||||
return name, (version or None)
|
||||
return spec, None
|
||||
|
||||
|
||||
def is_pinned_npm_spec(spec: str) -> bool:
|
||||
_name, version = split_npm_spec(spec)
|
||||
return bool(version)
|
||||
|
||||
|
||||
_DOCKER_VALUE_FLAGS = {
|
||||
"-e",
|
||||
"--env",
|
||||
"-v",
|
||||
"--volume",
|
||||
"-p",
|
||||
"--publish",
|
||||
"-w",
|
||||
"--workdir",
|
||||
"-u",
|
||||
"--user",
|
||||
"--name",
|
||||
"--network",
|
||||
"--entrypoint",
|
||||
}
|
||||
|
||||
|
||||
def docker_image_candidates(args: list[str]) -> list[str]:
|
||||
"""Best-effort extraction of the image reference from a `docker run
|
||||
[OPTIONS] IMAGE [CMD...]` args list: the first positional token after
|
||||
any leading `run` and flag(+value) pairs."""
|
||||
candidates: list[str] = []
|
||||
i = 0
|
||||
while i < len(args):
|
||||
a = args[i]
|
||||
if a == "run":
|
||||
i += 1
|
||||
continue
|
||||
if isinstance(a, str) and a.startswith("-"):
|
||||
if "=" not in a and a in _DOCKER_VALUE_FLAGS:
|
||||
i += 2
|
||||
continue
|
||||
i += 1
|
||||
continue
|
||||
if isinstance(a, str):
|
||||
candidates.append(a)
|
||||
break # first positional token after `run` is the image ref
|
||||
return candidates
|
||||
|
||||
|
||||
def is_pinned_docker_image(image: str) -> bool:
|
||||
if "@sha256:" in image:
|
||||
return True
|
||||
tag_part = image.rsplit("/", 1)[-1]
|
||||
if ":" not in tag_part:
|
||||
return False # no tag => implicit :latest
|
||||
tag = tag_part.rsplit(":", 1)[-1]
|
||||
return bool(tag) and tag != "latest"
|
||||
|
||||
|
||||
def risk_unpinned_package(change: EntryChange) -> list[RiskFinding]:
|
||||
"""Every entry must pin an exact version: an `@scope/pkg` npm arg with
|
||||
no `@version`, or a docker image with no tag / `:latest`, is blocking.
|
||||
A later-compromised package must not be able to auto-upgrade into every
|
||||
user just because the catalog entry never pinned a version."""
|
||||
entry = change.new or {}
|
||||
config = entry.get("config") or {}
|
||||
command = config.get("command")
|
||||
args = config.get("args") or []
|
||||
findings: list[RiskFinding] = []
|
||||
|
||||
if command == "npx":
|
||||
for a in _npm_candidate_args(command, args):
|
||||
if not is_pinned_npm_spec(a):
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"unpinned_npm_package",
|
||||
f"npm package arg {a!r} has no pinned @version.",
|
||||
)
|
||||
)
|
||||
elif command == "docker":
|
||||
for img in docker_image_candidates(args):
|
||||
if not is_pinned_docker_image(img):
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"blocking",
|
||||
"unpinned_docker_image",
|
||||
f"docker image {img!r} is not pinned to an exact tag "
|
||||
"(uses :latest or no tag).",
|
||||
)
|
||||
)
|
||||
|
||||
return findings
|
||||
|
||||
|
||||
_URL_FIELDS = ("homepage", "docs_url", "source")
|
||||
|
||||
|
||||
def _domain(url: str) -> str:
|
||||
try:
|
||||
return urlsplit(url).netloc.lower()
|
||||
except ValueError:
|
||||
return ""
|
||||
|
||||
|
||||
def risk_url_domain_change(change: EntryChange) -> list[RiskFinding]:
|
||||
"""Non-https URLs and, more importantly, a *domain change* on any URL
|
||||
field are surfaced loudly with old-vs-new domains broken out -- the
|
||||
lookalike-domain-swap defence."""
|
||||
findings: list[RiskFinding] = []
|
||||
old_entry = change.old or {}
|
||||
new_entry = change.new or {}
|
||||
|
||||
for f in _URL_FIELDS:
|
||||
new_url = new_entry.get(f)
|
||||
if not isinstance(new_url, str) or not new_url:
|
||||
continue
|
||||
if not new_url.startswith("https://"):
|
||||
findings.append(
|
||||
RiskFinding("warning", "non_https_url", f"{f} is not https://: {new_url!r}")
|
||||
)
|
||||
old_url = old_entry.get(f)
|
||||
if isinstance(old_url, str) and old_url:
|
||||
old_domain, new_domain = _domain(old_url), _domain(new_url)
|
||||
if old_domain and new_domain and old_domain != new_domain:
|
||||
findings.append(
|
||||
RiskFinding(
|
||||
"warning",
|
||||
"domain_changed",
|
||||
f"{f} domain changed from {old_domain!r} to {new_domain!r} -- "
|
||||
"verify this isn't a lookalike-domain swap.",
|
||||
)
|
||||
)
|
||||
return findings
|
||||
|
||||
|
||||
def risk_new_entry(change: EntryChange) -> list[RiskFinding]:
|
||||
"""A brand-new entry is flagged for extra scrutiny -- not blocking on its
|
||||
own, but it's the category of change the registry lookup exists for."""
|
||||
if change.status == "added":
|
||||
return [
|
||||
RiskFinding(
|
||||
"info",
|
||||
"new_entry",
|
||||
"Brand-new catalog entry -- extra scrutiny: check publisher identity "
|
||||
"via the registry lookup before signing.",
|
||||
)
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
_RISK_PREDICATES: tuple[Callable[[EntryChange], list[RiskFinding]], ...] = (
|
||||
risk_env_required,
|
||||
risk_command_allowlist,
|
||||
risk_non_ascii,
|
||||
risk_unpinned_package,
|
||||
risk_url_domain_change,
|
||||
risk_new_entry,
|
||||
)
|
||||
|
||||
|
||||
def entry_risk_findings(change: EntryChange) -> list[RiskFinding]:
|
||||
"""Run every risk predicate against one entry change and return the
|
||||
combined findings (order matches _RISK_PREDICATES)."""
|
||||
findings: list[RiskFinding] = []
|
||||
for predicate in _RISK_PREDICATES:
|
||||
findings.extend(predicate(change))
|
||||
return findings
|
||||
|
||||
|
||||
def has_blocking_risk(change: EntryChange) -> bool:
|
||||
return any(f.severity == "blocking" for f in entry_risk_findings(change))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Review session: acknowledge-gating + TOCTOU blob-SHA pinning
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReviewSession:
|
||||
"""State for one review pass. `pinned_blob_sha` is the git blob SHA of
|
||||
data/catalog.json as it existed the moment review began -- see
|
||||
can_sign()/sign_precondition().
|
||||
|
||||
`loaded_ref` is the exact ref this review was loaded from ("main", or a
|
||||
PR's `refs/pull/<n>/head`) -- see issue #68 finding 1. It exists so the
|
||||
Sign path can re-resolve the TOCTOU blob SHA from *the ref that was
|
||||
actually reviewed*, instead of a hardcoded "main" that silently diverges
|
||||
from the reviewed ref on every PR review (the bug that made the PR path
|
||||
unable to sign at all, and forced everyone onto the vacuous
|
||||
main-vs-itself path instead).
|
||||
"""
|
||||
|
||||
pinned_blob_sha: str
|
||||
old_catalog: dict
|
||||
new_catalog: dict
|
||||
loaded_ref: str = "main"
|
||||
changes: list[EntryChange] = field(default_factory=list)
|
||||
acknowledged: set[str] = field(default_factory=set)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.changes:
|
||||
self.changes = diff_catalogs(self.old_catalog, self.new_catalog)
|
||||
|
||||
|
||||
def start_review(
|
||||
pinned_blob_sha: str,
|
||||
old_catalog: dict,
|
||||
new_catalog: dict,
|
||||
loaded_ref: str = "main",
|
||||
) -> ReviewSession:
|
||||
return ReviewSession(
|
||||
pinned_blob_sha=pinned_blob_sha,
|
||||
old_catalog=old_catalog,
|
||||
new_catalog=new_catalog,
|
||||
loaded_ref=loaded_ref,
|
||||
)
|
||||
|
||||
|
||||
def find_last_signed_catalog_raw(
|
||||
candidates: list[bytes], sig: bytes, pubkeys: list[bytes]
|
||||
) -> bytes | None:
|
||||
"""Given `candidates` (candidate raw catalog.json byte-strings -- e.g.
|
||||
successive historical versions from git log, most-recent-first),
|
||||
return the first one whose signature verifies against `sig`/`pubkeys`,
|
||||
or None if none do.
|
||||
|
||||
This is how source="main" review diffs against "the last catalog a
|
||||
maintainer actually signed" instead of against itself (issue #68
|
||||
finding 1): `catalog_console.last_signed_catalog_raw` walks
|
||||
data/catalog.json's git history on main and hands the candidates here.
|
||||
"""
|
||||
for raw in candidates:
|
||||
if _verify_catalog_signature(raw, sig, pubkeys):
|
||||
return raw
|
||||
return None
|
||||
|
||||
|
||||
def acknowledge_entry(session: ReviewSession, entry_id: str) -> None:
|
||||
ids = {c.entry_id for c in session.changes}
|
||||
if entry_id not in ids:
|
||||
raise ValueError(f"{entry_id!r} is not part of this review session's diff.")
|
||||
session.acknowledged.add(entry_id)
|
||||
|
||||
|
||||
def unacknowledge_entry(session: ReviewSession, entry_id: str) -> None:
|
||||
session.acknowledged.discard(entry_id)
|
||||
|
||||
|
||||
def all_entries_acknowledged(session: ReviewSession) -> bool:
|
||||
return {c.entry_id for c in session.changes} <= session.acknowledged
|
||||
|
||||
|
||||
# NOTE for future editors: do NOT add an "acknowledge all" shortcut here, now
|
||||
# or ever. The friction of individually acknowledging every changed entry is
|
||||
# the entire point of this tool (issue #62) -- a shortcut would let a tired
|
||||
# reviewer rubber-stamp a diff exactly like the "merge PR, run script, push"
|
||||
# reflex this Console exists to replace. If this comment is the only thing
|
||||
# stopping you, that is the point: it is stopping you on purpose.
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SignDecision:
|
||||
ok: bool
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
def can_sign(session: ReviewSession, current_blob_sha: str) -> SignDecision:
|
||||
"""Whether the Sign button may fire right now.
|
||||
|
||||
Four independent gates, all required, checked in this order:
|
||||
|
||||
0. The diff must be non-empty. An empty diff historically meant "Sign
|
||||
unlocks instantly" (`set() <= set()` is vacuously True), which is
|
||||
exactly backwards: a vacuously-satisfied gate is worse than no gate
|
||||
at all, because it *manufactures confidence* -- the signature looks
|
||||
identical to one produced by a real review. "Nothing changed" must
|
||||
mean "nothing to sign", never "sign unlocked". (Issue #68 finding 1;
|
||||
this is what let commit b08cf21 sign all 19 entries with zero of them
|
||||
ever reviewed.)
|
||||
1. TOCTOU: `current_blob_sha` (fetched fresh, immediately before signing,
|
||||
from the ref that was actually reviewed -- see sign_precondition())
|
||||
must match the blob SHA pinned when review began. If the bytes on the
|
||||
remote changed since -- a new commit pushed to the same PR, a
|
||||
force-push, another PR merged in between -- signing is refused and a
|
||||
re-review is forced. This is what makes "signing is the approval act"
|
||||
true rather than aspirational: the signature is bound to the exact
|
||||
reviewed bytes, not to "whatever the file happens to be now".
|
||||
2. No blocking risk finding may be outstanding on ANY changed entry, full
|
||||
stop -- checked here, not just in the GUI. The GUI additionally
|
||||
disables the acknowledge checkbox for a blocking entry, but that is a
|
||||
UI nicety, not the enforcement point: if this pure gate didn't also
|
||||
check it, a blocking risk would only be stopped by the GUI happening
|
||||
to have wired the checkbox correctly, and nothing would catch a
|
||||
regression in that wiring. The GUI must not be the only thing
|
||||
standing between a blocking risk and a signature.
|
||||
3. Every changed entry in the diff must be individually acknowledged.
|
||||
"""
|
||||
if not session.changes:
|
||||
return SignDecision(
|
||||
False,
|
||||
"Nothing to sign: this review's diff is empty. If you expected "
|
||||
"changes here, you may be diffing the wrong source/ref.",
|
||||
)
|
||||
if current_blob_sha != session.pinned_blob_sha:
|
||||
return SignDecision(
|
||||
False,
|
||||
"The reviewed bytes changed since this review began (blob SHA "
|
||||
"mismatch) -- re-review required before signing.",
|
||||
)
|
||||
blocking_ids = sorted({c.entry_id for c in session.changes if has_blocking_risk(c)})
|
||||
if blocking_ids:
|
||||
return SignDecision(
|
||||
False,
|
||||
"Blocking risk finding(s) outstanding on: "
|
||||
f"{', '.join(blocking_ids)} -- fix the underlying change, do not sign around it.",
|
||||
)
|
||||
if not all_entries_acknowledged(session):
|
||||
pending = sorted({c.entry_id for c in session.changes} - session.acknowledged)
|
||||
return SignDecision(
|
||||
False, f"Not every changed entry has been acknowledged yet: {', '.join(pending)}"
|
||||
)
|
||||
return SignDecision(True, None)
|
||||
|
||||
|
||||
def sign_precondition(
|
||||
session: ReviewSession, resolve_blob_sha: Callable[[str], str]
|
||||
) -> SignDecision:
|
||||
"""The real Sign-button gate: resolves the current TOCTOU blob SHA from
|
||||
*the ref this session was actually loaded from* (`session.loaded_ref`),
|
||||
never a hardcoded "main", then delegates to can_sign().
|
||||
|
||||
`resolve_blob_sha` is injected so this stays testable without git/Qt --
|
||||
catalog_console.ReviewWindow._on_sign passes a real resolver
|
||||
(fetch_ref + blob_sha_at against self.repo_dir); tests pass a fake
|
||||
dict-backed lookup. This is the fix for issue #68 finding 1's first bug:
|
||||
`_on_sign` used to hardcode `fetch_ref(self.repo_dir, "main")` as the
|
||||
comparison ref, so for any PR review (where `loaded_ref` is the PR's
|
||||
head, not main) the SHAs differed by definition and Sign could never
|
||||
fire -- and the retry path re-called the same hardcoded resolver, so it
|
||||
re-pinned the same wrong value and looped forever instead of forcing a
|
||||
genuine re-review.
|
||||
"""
|
||||
current_blob_sha = resolve_blob_sha(session.loaded_ref)
|
||||
return can_sign(session, current_blob_sha)
|
||||
|
||||
|
||||
def catalog_signing_message(raw_bytes: bytes) -> bytes:
|
||||
"""The exact bytes that get signed: bcc_core's domain-separation prefix
|
||||
(imported, never retyped) + the raw catalog bytes. Using this function
|
||||
guarantees the Console's signature and bcc_core.verify_catalog_signature
|
||||
can never drift apart on the prefix."""
|
||||
return CATALOG_SIG_DOMAIN + raw_bytes
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Key management: passphrase-encrypted-at-rest Ed25519 seed
|
||||
#
|
||||
# The private key is NEVER stored plaintext, never an env var, never
|
||||
# committed. encrypt_private_key/decrypt_private_key are pure and offline
|
||||
# (scrypt KDF + AES-256-GCM via `cryptography`, already a project
|
||||
# dependency); catalog_console.py decides WHERE the resulting blob lives
|
||||
# (OS keychain if available, else a file outside the repo).
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_KDF_SALT_LEN = 16
|
||||
_KDF_N = 2**15 # scrypt cost parameter, tuned for a one-off interactive unlock
|
||||
_KDF_R = 8
|
||||
_KDF_P = 1
|
||||
_NONCE_LEN = 12
|
||||
_AAD = b"bcc-catalog-console-key-v1"
|
||||
|
||||
|
||||
def _derive_key(passphrase: str, salt: bytes) -> bytes:
|
||||
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||||
|
||||
kdf = Scrypt(salt=salt, length=32, n=_KDF_N, r=_KDF_R, p=_KDF_P)
|
||||
return kdf.derive(passphrase.encode("utf-8"))
|
||||
|
||||
|
||||
def generate_keypair() -> tuple[bytes, bytes]:
|
||||
"""Generate a new Ed25519 keypair. Returns (seed_32_bytes, pubkey_32_bytes)."""
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||
|
||||
private_key = Ed25519PrivateKey.generate()
|
||||
seed = private_key.private_bytes_raw()
|
||||
pubkey = private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
|
||||
return seed, pubkey
|
||||
|
||||
|
||||
def encrypt_private_key(seed: bytes, passphrase: str) -> bytes:
|
||||
"""Encrypt a 32-byte Ed25519 seed at rest with a passphrase. Returns a
|
||||
self-contained blob: salt || nonce || ciphertext+tag."""
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
if len(seed) != 32:
|
||||
raise ValueError(f"expected a 32-byte raw Ed25519 seed, got {len(seed)} bytes")
|
||||
if not passphrase:
|
||||
raise ValueError("a non-empty passphrase is required")
|
||||
salt = os.urandom(_KDF_SALT_LEN)
|
||||
key = _derive_key(passphrase, salt)
|
||||
nonce = os.urandom(_NONCE_LEN)
|
||||
ciphertext = AESGCM(key).encrypt(nonce, seed, _AAD)
|
||||
return salt + nonce + ciphertext
|
||||
|
||||
|
||||
def decrypt_private_key(blob: bytes, passphrase: str) -> bytes:
|
||||
"""Decrypt a blob produced by encrypt_private_key. Raises ValueError on a
|
||||
wrong passphrase or corrupt blob -- never silently returns garbage."""
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
if len(blob) < _KDF_SALT_LEN + _NONCE_LEN:
|
||||
raise ValueError("key blob is too short to be valid")
|
||||
salt = blob[:_KDF_SALT_LEN]
|
||||
nonce = blob[_KDF_SALT_LEN : _KDF_SALT_LEN + _NONCE_LEN]
|
||||
ciphertext = blob[_KDF_SALT_LEN + _NONCE_LEN :]
|
||||
key = _derive_key(passphrase, salt)
|
||||
try:
|
||||
return AESGCM(key).decrypt(nonce, ciphertext, _AAD)
|
||||
except InvalidTag as e:
|
||||
raise ValueError("wrong passphrase or corrupted key file") from e
|
||||
|
||||
|
||||
def sign_catalog_bytes(raw: bytes, seed: bytes) -> bytes:
|
||||
"""Sign `raw` catalog bytes with a 32-byte Ed25519 seed, using the exact
|
||||
domain-separated message bcc_core.verify_catalog_signature expects."""
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
|
||||
if len(seed) != 32:
|
||||
raise ValueError(f"expected a 32-byte raw Ed25519 seed, got {len(seed)} bytes")
|
||||
private_key = Ed25519PrivateKey.from_private_bytes(seed)
|
||||
return private_key.sign(catalog_signing_message(raw))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Registry lookup -- the check a human genuinely can't do.
|
||||
#
|
||||
# The network call itself is injected (a `Fetcher` callable) so this stays
|
||||
# testable offline; catalog_console.py supplies the real npm/PyPI HTTP
|
||||
# fetcher. Fails soft everywhere: a fetcher returning None/raising just
|
||||
# yields RegistryInfo(available=False), never an exception into the caller
|
||||
# and never a block on review.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PackageRef:
|
||||
entry_id: str
|
||||
ecosystem: str # "npm" | "pypi"
|
||||
name: str
|
||||
version: str | None
|
||||
|
||||
|
||||
def split_pypi_spec(spec: str) -> tuple[str, str | None]:
|
||||
for sep in ("==", "@"):
|
||||
if sep in spec:
|
||||
name, _, version = spec.partition(sep)
|
||||
return name, (version or None)
|
||||
return spec, None
|
||||
|
||||
|
||||
def extract_package_refs(entry: dict) -> list[PackageRef]:
|
||||
"""Pull out the package(s) a basic-tier entry's args reference, for the
|
||||
registry lookup. Returns [] for link-only entries or entries whose
|
||||
command isn't npx/uvx (docker images aren't registry-lookup candidates
|
||||
in the npm/PyPI sense used here)."""
|
||||
config = entry.get("config") or {}
|
||||
command = config.get("command")
|
||||
args = config.get("args") or []
|
||||
entry_id = entry.get("id", "") if isinstance(entry.get("id"), str) else ""
|
||||
refs: list[PackageRef] = []
|
||||
|
||||
if command == "npx":
|
||||
for a in _npm_candidate_args(command, args):
|
||||
name, version = split_npm_spec(a)
|
||||
if name:
|
||||
refs.append(PackageRef(entry_id, "npm", name, version))
|
||||
elif command == "uvx":
|
||||
for a in args:
|
||||
if isinstance(a, str) and a and not a.startswith("-"):
|
||||
name, version = split_pypi_spec(a)
|
||||
if name:
|
||||
refs.append(PackageRef(entry_id, "pypi", name, version))
|
||||
break # `uvx <pkg>` -- first positional token is the package
|
||||
|
||||
return refs
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegistryInfo:
|
||||
ref: PackageRef
|
||||
available: bool
|
||||
publisher: str | None = None
|
||||
age_days: int | None = None
|
||||
last_release: str | None = None
|
||||
downloads: int | None = None
|
||||
near_neighbor_ids: tuple[str, ...] = ()
|
||||
|
||||
|
||||
Fetcher = Callable[[PackageRef], dict | None]
|
||||
|
||||
|
||||
def edit_distance(a: str, b: str) -> int:
|
||||
"""Levenshtein distance, iterative DP (no recursion depth concerns)."""
|
||||
if a == b:
|
||||
return 0
|
||||
la, lb = len(a), len(b)
|
||||
if la == 0:
|
||||
return lb
|
||||
if lb == 0:
|
||||
return la
|
||||
prev = list(range(lb + 1))
|
||||
for i, ca in enumerate(a, 1):
|
||||
cur = [i] + [0] * lb
|
||||
for j, cb in enumerate(b, 1):
|
||||
cost = 0 if ca == cb else 1
|
||||
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)
|
||||
prev = cur
|
||||
return prev[lb]
|
||||
|
||||
|
||||
def near_neighbor_ids(name: str, other_ids: list[str], max_distance: int = 2) -> list[str]:
|
||||
"""Catalog ids within `max_distance` edits of `name` (case-insensitive),
|
||||
excluding an exact match -- the dependency-confusion / typosquat
|
||||
near-neighbour warning."""
|
||||
lname = name.lower()
|
||||
return [
|
||||
oid
|
||||
for oid in other_ids
|
||||
if oid != name and edit_distance(lname, oid.lower()) <= max_distance
|
||||
]
|
||||
|
||||
|
||||
def lookup_registry_info(
|
||||
ref: PackageRef, fetcher: Fetcher, all_entry_ids: list[str]
|
||||
) -> RegistryInfo:
|
||||
"""Resolve one package against the live registry via the injected
|
||||
fetcher. Never raises: any fetcher exception or falsy return means
|
||||
`available=False` ("unavailable"), which the GUI renders plainly rather
|
||||
than blocking or erroring the review."""
|
||||
neighbors = tuple(near_neighbor_ids(ref.name, all_entry_ids))
|
||||
try:
|
||||
raw = fetcher(ref)
|
||||
except Exception:
|
||||
raw = None
|
||||
if not raw:
|
||||
return RegistryInfo(ref=ref, available=False, near_neighbor_ids=neighbors)
|
||||
return RegistryInfo(
|
||||
ref=ref,
|
||||
available=True,
|
||||
publisher=raw.get("publisher"),
|
||||
age_days=raw.get("age_days"),
|
||||
last_release=raw.get("last_release"),
|
||||
downloads=raw.get("downloads"),
|
||||
near_neighbor_ids=neighbors,
|
||||
)
|
||||
|
||||
|
||||
_NON_ASCII_RE = re.compile(r"[^\x00-\x7f]")
|
||||
|
||||
|
||||
def contains_non_ascii(s: str) -> bool:
|
||||
return bool(_NON_ASCII_RE.search(s))
|
||||
@@ -0,0 +1,2 @@
|
||||
ы<8¶ђt2ішл„»‰/НЕ0Тjcw&`
|
||||
тrH«MўК›єrBL,0AS€!Х2–иже.SТ°ч–'Agm
|
||||
@@ -42,6 +42,25 @@ from pathlib import Path
|
||||
# message signed by the same key.
|
||||
DOMAIN_PREFIX = b"bcc-release-v1|"
|
||||
|
||||
# Public half of the RELEASE signing key(s) -- a SEPARATE keypair from
|
||||
# bcc_core.CATALOG_PUBKEYS (issue #68 finding 5). The catalog key is the
|
||||
# offline, Console-only root of trust for what BCC executes; this key is
|
||||
# CI-resident and signs ONLY the release SHA256SUMS manifest, never the
|
||||
# catalog. Keeping them apart means a CI/repo-secret compromise burns the
|
||||
# release key -- annoying, but it never lets an attacker sign a catalog a
|
||||
# user's binary would trust. A LIST (not a single key), mirroring
|
||||
# CATALOG_PUBKEYS, so the release key can be rotated without invalidating
|
||||
# the signature on every past release: verification accepts a match against
|
||||
# ANY key here.
|
||||
#
|
||||
# Empty until the maintainer generates the release keypair (separately from
|
||||
# the catalog keypair) and pastes the public half in:
|
||||
# python catalog_console.py keygen --release
|
||||
# This is intentionally NOT pre-populated with a placeholder that looks
|
||||
# like a real key -- release.yml's signing-smoke-test fails closed (loudly)
|
||||
# on an empty list rather than silently verifying against nothing.
|
||||
RELEASE_PUBKEYS: list[bytes] = []
|
||||
|
||||
CHUNK_SIZE = 1024 * 1024
|
||||
|
||||
|
||||
@@ -135,6 +154,19 @@ def public_key_b64_from_seed(seed_b64: str) -> str:
|
||||
return base64.b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def verify_checksums_against_any(pubkeys: list[bytes], sums_text: str, signature: bytes) -> bool:
|
||||
"""Verify `signature` against ANY key in `pubkeys` (each a raw 32-byte
|
||||
Ed25519 public key). Mirrors bcc_core.verify_catalog_signature's
|
||||
rotation-friendly "any currently-trusted key" semantics, applied to
|
||||
RELEASE_PUBKEYS instead of the catalog's key list. Returns False (never
|
||||
raises) for an empty `pubkeys` list -- fails closed rather than
|
||||
vacuously verifying against nothing."""
|
||||
return any(
|
||||
verify_checksums(base64.b64encode(pk).decode("ascii"), sums_text, signature)
|
||||
for pk in pubkeys
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# CLI
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Asserts the maintainer-only Catalog Console (catalog_console.py,
|
||||
catalog_review.py) is never bundled into the release binary.
|
||||
|
||||
A signing/review tool shipping to end users would be an own-goal (issue
|
||||
#62): it has no reason to run on a user's machine, and its presence would
|
||||
be a confusing artefact of a build that's supposed to be a thin GUI over
|
||||
mcpServers config editing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
SPEC_PATH = REPO_ROOT / "bcc.spec"
|
||||
|
||||
_EXCLUDED_FILES = ("catalog_console.py", "catalog_review.py")
|
||||
|
||||
|
||||
def test_spec_file_exists():
|
||||
assert SPEC_PATH.exists()
|
||||
|
||||
|
||||
def test_console_files_not_named_in_spec():
|
||||
"""The spec text must never reference either maintainer-only module --
|
||||
not as the Analysis entry point, not in datas, not anywhere."""
|
||||
spec_text = SPEC_PATH.read_text(encoding="utf-8")
|
||||
for filename in _EXCLUDED_FILES:
|
||||
assert filename not in spec_text, (
|
||||
f"{filename} must never be referenced by bcc.spec -- it is a "
|
||||
"maintainer-only tool and must not ship to users."
|
||||
)
|
||||
|
||||
|
||||
def test_spec_analysis_entry_point_is_bcc_py_only():
|
||||
"""PyInstaller's Analysis(...) call determines the dependency-scanned
|
||||
entry point(s); it must be bcc.py alone."""
|
||||
spec_text = SPEC_PATH.read_text(encoding="utf-8")
|
||||
assert 'Analysis(\n ["bcc.py"],' in spec_text or 'Analysis(["bcc.py"]' in spec_text, (
|
||||
"bcc.spec's Analysis(...) entry point changed shape -- re-verify by hand "
|
||||
"that catalog_console.py / catalog_review.py are still excluded."
|
||||
)
|
||||
|
||||
|
||||
def test_console_modules_exist_but_are_standalone_top_level_files():
|
||||
"""Sanity check the files this test is guarding actually exist as
|
||||
top-level modules (not, say, silently moved into a package PyInstaller's
|
||||
Analysis would still pick up as an implicit import of bcc.py)."""
|
||||
for filename in _EXCLUDED_FILES:
|
||||
assert (REPO_ROOT / filename).exists()
|
||||
# bcc.py must not import them.
|
||||
bcc_text = (REPO_ROOT / "bcc.py").read_text(encoding="utf-8")
|
||||
module_name = filename.removesuffix(".py")
|
||||
assert f"import {module_name}" not in bcc_text
|
||||
assert f"from {module_name}" not in bcc_text
|
||||
|
||||
|
||||
def test_requirements_files_do_not_reference_console_only_needs():
|
||||
"""catalog_console.py's only import beyond the shipped stack is the
|
||||
optional `keyring` package, which is intentionally NOT added as a hard
|
||||
dependency anywhere a user install would pick it up."""
|
||||
for req_file in ("requirements.txt", "requirements-dev.txt"):
|
||||
path = REPO_ROOT / req_file
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8").lower()
|
||||
assert "keyring" not in text
|
||||
@@ -0,0 +1,695 @@
|
||||
"""Tests for catalog_review.py -- semantic diff, risk predicates, review
|
||||
session (acknowledge-gating + TOCTOU blob pinning), key encryption, and
|
||||
registry-lookup logic for the Catalog Console (issue #62)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import bcc_core as c
|
||||
import catalog_review as r
|
||||
|
||||
|
||||
def _entry(**overrides):
|
||||
base = {
|
||||
"id": "filesystem",
|
||||
"display": "Filesystem",
|
||||
"description": "desc",
|
||||
"category": "files",
|
||||
"homepage": "https://github.com/modelcontextprotocol/servers",
|
||||
"stars": 100,
|
||||
"official": True,
|
||||
"setup": "basic",
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem@1.0.0"],
|
||||
},
|
||||
"env_required": {},
|
||||
"docs_url": "https://github.com/modelcontextprotocol/servers",
|
||||
"notes": "",
|
||||
"last_release": "2026-01-01",
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def _catalog(*entries):
|
||||
return {"schema": 1, "version": 1, "servers": list(entries)}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# diff_catalogs
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_diff_detects_added_entry():
|
||||
old = _catalog()
|
||||
new = _catalog(_entry())
|
||||
changes = r.diff_catalogs(old, new)
|
||||
assert len(changes) == 1
|
||||
assert changes[0].status == "added"
|
||||
assert changes[0].entry_id == "filesystem"
|
||||
assert changes[0].old is None
|
||||
|
||||
|
||||
def test_diff_detects_removed_entry():
|
||||
old = _catalog(_entry())
|
||||
new = _catalog()
|
||||
changes = r.diff_catalogs(old, new)
|
||||
assert len(changes) == 1
|
||||
assert changes[0].status == "removed"
|
||||
assert changes[0].new is None
|
||||
|
||||
|
||||
def test_diff_detects_no_change():
|
||||
e = _entry()
|
||||
old = _catalog(e)
|
||||
new = _catalog(dict(e))
|
||||
assert r.diff_catalogs(old, new) == []
|
||||
|
||||
|
||||
def test_diff_detects_changed_command_and_args():
|
||||
old = _catalog(_entry())
|
||||
new = _catalog(_entry(config={"command": "uvx", "args": ["other-pkg@2.0.0"]}))
|
||||
changes = r.diff_catalogs(old, new)
|
||||
assert len(changes) == 1
|
||||
ch = changes[0]
|
||||
assert ch.status == "changed"
|
||||
fields = {fc.field for fc in ch.field_changes}
|
||||
assert "config.command" in fields
|
||||
assert "config.args" in fields
|
||||
|
||||
|
||||
def test_diff_detects_description_change():
|
||||
old = _catalog(_entry())
|
||||
new = _catalog(_entry(description="new description"))
|
||||
changes = r.diff_catalogs(old, new)
|
||||
assert changes[0].field_changes == (r.FieldChange("description", "desc", "new description"),)
|
||||
|
||||
|
||||
def test_diff_ignores_entries_without_id():
|
||||
old = _catalog()
|
||||
new = _catalog({"display": "no id"})
|
||||
assert r.diff_catalogs(old, new) == []
|
||||
|
||||
|
||||
def test_diff_multiple_entries_sorted_by_id():
|
||||
old = _catalog(_entry(id="zeta"), _entry(id="alpha"))
|
||||
new = _catalog(
|
||||
_entry(id="zeta", description="changed"), _entry(id="alpha", description="changed")
|
||||
)
|
||||
changes = r.diff_catalogs(old, new)
|
||||
assert [c_.entry_id for c_ in changes] == ["alpha", "zeta"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# risk_env_required
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_risk_env_required_blocking_on_nonempty_value():
|
||||
change = r.EntryChange("x", "changed", None, _entry(env_required={"API_KEY": "sk-real-value"}))
|
||||
findings = r.risk_env_required(change)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].severity == "blocking"
|
||||
assert findings[0].code == "env_required_value"
|
||||
|
||||
|
||||
def test_risk_env_required_clean_on_empty_value():
|
||||
change = r.EntryChange("x", "changed", None, _entry(env_required={"API_KEY": ""}))
|
||||
assert r.risk_env_required(change) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# risk_command_allowlist
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_risk_command_allowlist_blocks_disallowed_command():
|
||||
change = r.EntryChange(
|
||||
"x", "changed", None, _entry(config={"command": "bash", "args": ["-c", "evil"]})
|
||||
)
|
||||
findings = r.risk_command_allowlist(change)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].severity == "blocking"
|
||||
|
||||
|
||||
def test_risk_command_allowlist_allows_listed_command():
|
||||
for cmd in sorted(c.CATALOG_ALLOWED_COMMANDS):
|
||||
change = r.EntryChange("x", "changed", None, _entry(config={"command": cmd, "args": []}))
|
||||
assert r.risk_command_allowlist(change) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# risk_non_ascii
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_risk_non_ascii_flags_homoglyph_id():
|
||||
# Cyrillic 'а' (U+0430) instead of Latin 'a' -- classic homoglyph swap.
|
||||
evil_id = "filаsystem"
|
||||
change = r.EntryChange(evil_id, "changed", None, _entry(id=evil_id))
|
||||
findings = r.risk_non_ascii(change)
|
||||
assert any(f.code == "non_ascii_id" for f in findings)
|
||||
assert findings[0].severity == "blocking"
|
||||
# the offending string must be rendered with escapes, not raw
|
||||
assert "\\u0430" in findings[0].message
|
||||
|
||||
|
||||
def test_risk_non_ascii_flags_arg():
|
||||
change = r.EntryChange(
|
||||
"x", "changed", None, _entry(config={"command": "npx", "args": ["pаckage@1.0.0"]})
|
||||
)
|
||||
findings = r.risk_non_ascii(change)
|
||||
assert any(f.code == "non_ascii_arg" for f in findings)
|
||||
|
||||
|
||||
def test_risk_non_ascii_clean_for_ascii_entry():
|
||||
change = r.EntryChange("x", "changed", None, _entry())
|
||||
assert r.risk_non_ascii(change) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# risk_unpinned_package
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_risk_unpinned_npm_package_no_version():
|
||||
change = r.EntryChange(
|
||||
"x",
|
||||
"changed",
|
||||
None,
|
||||
_entry(config={"command": "npx", "args": ["-y", "@scope/pkg"]}),
|
||||
)
|
||||
findings = r.risk_unpinned_package(change)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].code == "unpinned_npm_package"
|
||||
assert findings[0].severity == "blocking"
|
||||
|
||||
|
||||
def test_risk_pinned_npm_package_is_clean():
|
||||
change = r.EntryChange(
|
||||
"x",
|
||||
"changed",
|
||||
None,
|
||||
_entry(config={"command": "npx", "args": ["-y", "@scope/pkg@1.2.3"]}),
|
||||
)
|
||||
assert r.risk_unpinned_package(change) == []
|
||||
|
||||
|
||||
def test_risk_unpinned_unscoped_npm_package():
|
||||
change = r.EntryChange(
|
||||
"x", "changed", None, _entry(config={"command": "npx", "args": ["-y", "somepkg"]})
|
||||
)
|
||||
findings = r.risk_unpinned_package(change)
|
||||
assert len(findings) == 1
|
||||
|
||||
|
||||
def test_risk_unpinned_docker_latest_tag():
|
||||
change = r.EntryChange(
|
||||
"x",
|
||||
"changed",
|
||||
None,
|
||||
_entry(config={"command": "docker", "args": ["run", "-i", "--rm", "myimage:latest"]}),
|
||||
)
|
||||
findings = r.risk_unpinned_package(change)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].code == "unpinned_docker_image"
|
||||
|
||||
|
||||
def test_risk_unpinned_docker_no_tag():
|
||||
change = r.EntryChange(
|
||||
"x", "changed", None, _entry(config={"command": "docker", "args": ["run", "myimage"]})
|
||||
)
|
||||
findings = r.risk_unpinned_package(change)
|
||||
assert len(findings) == 1
|
||||
|
||||
|
||||
def test_risk_pinned_docker_image_is_clean():
|
||||
change = r.EntryChange(
|
||||
"x",
|
||||
"changed",
|
||||
None,
|
||||
_entry(config={"command": "docker", "args": ["run", "-i", "--rm", "myimage:1.2.3"]}),
|
||||
)
|
||||
assert r.risk_unpinned_package(change) == []
|
||||
|
||||
|
||||
def test_risk_docker_digest_pin_is_clean():
|
||||
change = r.EntryChange(
|
||||
"x",
|
||||
"changed",
|
||||
None,
|
||||
_entry(
|
||||
config={
|
||||
"command": "docker",
|
||||
"args": ["run", "myimage@sha256:" + "a" * 64],
|
||||
}
|
||||
),
|
||||
)
|
||||
assert r.risk_unpinned_package(change) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# risk_url_domain_change
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_risk_url_domain_change_warns_on_lookalike_swap():
|
||||
old_entry = _entry(homepage="https://github.com/foo/bar")
|
||||
new_entry = _entry(homepage="https://githu6.com/foo/bar")
|
||||
change = r.EntryChange("x", "changed", old_entry, new_entry)
|
||||
findings = r.risk_url_domain_change(change)
|
||||
assert any(f.code == "domain_changed" for f in findings)
|
||||
domain_finding = next(f for f in findings if f.code == "domain_changed")
|
||||
assert "github.com" in domain_finding.message
|
||||
assert "githu6.com" in domain_finding.message
|
||||
assert domain_finding.severity == "warning"
|
||||
|
||||
|
||||
def test_risk_url_domain_change_clean_when_domain_unchanged():
|
||||
old_entry = _entry(homepage="https://github.com/foo/bar")
|
||||
new_entry = _entry(homepage="https://github.com/foo/bar-renamed")
|
||||
change = r.EntryChange("x", "changed", old_entry, new_entry)
|
||||
assert r.risk_url_domain_change(change) == []
|
||||
|
||||
|
||||
def test_risk_url_non_https_warns():
|
||||
new_entry = _entry(homepage="http://example.com")
|
||||
change = r.EntryChange("x", "changed", None, new_entry)
|
||||
findings = r.risk_url_domain_change(change)
|
||||
assert any(f.code == "non_https_url" for f in findings)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# risk_new_entry / entry_risk_findings / has_blocking_risk
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_risk_new_entry_flags_added():
|
||||
change = r.EntryChange("x", "added", None, _entry())
|
||||
findings = r.risk_new_entry(change)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].severity == "info"
|
||||
|
||||
|
||||
def test_risk_new_entry_silent_for_changed():
|
||||
change = r.EntryChange("x", "changed", _entry(), _entry(description="x"))
|
||||
assert r.risk_new_entry(change) == []
|
||||
|
||||
|
||||
def test_has_blocking_risk_true_for_disallowed_command():
|
||||
change = r.EntryChange("x", "changed", None, _entry(config={"command": "bash", "args": []}))
|
||||
assert r.has_blocking_risk(change) is True
|
||||
|
||||
|
||||
def test_has_blocking_risk_false_for_clean_entry():
|
||||
change = r.EntryChange("x", "changed", _entry(), _entry(description="new"))
|
||||
assert r.has_blocking_risk(change) is False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ReviewSession: acknowledge gating
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_start_review_computes_diff():
|
||||
old = _catalog()
|
||||
new = _catalog(_entry())
|
||||
session = r.start_review("sha1", old, new)
|
||||
assert len(session.changes) == 1
|
||||
|
||||
|
||||
def test_all_entries_acknowledged_false_initially():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
assert r.all_entries_acknowledged(session) is False
|
||||
|
||||
|
||||
def test_acknowledge_entry_marks_acknowledged():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
assert r.all_entries_acknowledged(session) is True
|
||||
|
||||
|
||||
def test_acknowledge_unknown_entry_raises():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
with pytest.raises(ValueError):
|
||||
r.acknowledge_entry(session, "not-in-diff")
|
||||
|
||||
|
||||
def test_acknowledge_gating_requires_every_entry():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry(id="a"), _entry(id="b")))
|
||||
r.acknowledge_entry(session, "a")
|
||||
assert r.all_entries_acknowledged(session) is False
|
||||
r.acknowledge_entry(session, "b")
|
||||
assert r.all_entries_acknowledged(session) is True
|
||||
|
||||
|
||||
def test_no_acknowledge_all_shortcut_and_gate_is_real():
|
||||
"""Two things, both load-bearing (issue #68: the original version of
|
||||
this test asserted ONLY the first half, and passed the entire time the
|
||||
gate below it was vacuously satisfiable -- 'no function named
|
||||
acknowledge_all' is worthless if signing doesn't actually require
|
||||
acknowledgement in practice).
|
||||
|
||||
1. No bulk-acknowledge shortcut exists (see the comment in
|
||||
catalog_review.py above SignDecision -- deliberate friction).
|
||||
2. The gate that friction protects is actually enforced: with entries
|
||||
still unacknowledged, can_sign() must refuse, not just "some GUI
|
||||
checkbox happens to be unticked".
|
||||
"""
|
||||
names = [n for n in dir(r) if "acknowledge" in n.lower()]
|
||||
assert "acknowledge_all" not in names
|
||||
assert "acknowledge_all_entries" not in names
|
||||
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry(id="a"), _entry(id="b")))
|
||||
r.acknowledge_entry(session, "a") # only one of two -- not a bulk call
|
||||
decision = r.can_sign(session, "sha1")
|
||||
assert decision.ok is False
|
||||
assert "acknowledged" in decision.reason.lower()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# can_sign: TOCTOU blob pinning + acknowledge gating combined
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_can_sign_false_when_not_all_acknowledged():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
decision = r.can_sign(session, "sha1")
|
||||
assert decision.ok is False
|
||||
assert "acknowledged" in decision.reason
|
||||
|
||||
|
||||
def test_can_sign_true_when_acknowledged_and_blob_matches():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
decision = r.can_sign(session, "sha1")
|
||||
assert decision.ok is True
|
||||
assert decision.reason is None
|
||||
|
||||
|
||||
def test_can_sign_refuses_on_blob_mismatch_even_if_acknowledged():
|
||||
"""The core TOCTOU fix: acknowledging everything is not enough if the
|
||||
bytes on the remote changed underneath the review."""
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
decision = r.can_sign(session, "sha2-a-new-commit-landed")
|
||||
assert decision.ok is False
|
||||
assert "changed" in decision.reason.lower() or "mismatch" in decision.reason.lower()
|
||||
|
||||
|
||||
def test_can_sign_blob_mismatch_takes_priority_message():
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
decision = r.can_sign(session, "sha2")
|
||||
assert decision.ok is False
|
||||
assert "blob" in decision.reason.lower() or "changed" in decision.reason.lower()
|
||||
|
||||
|
||||
def test_can_sign_false_on_empty_changeset():
|
||||
"""The exact bug behind issue #68 finding 1: 'main' loaded against
|
||||
itself diffs to [], and an empty changeset used to leave can_sign()
|
||||
with nothing to refuse on (set() <= set() is vacuously True). Commit
|
||||
b08cf21 signed 19 entries through precisely this path -- zero of them
|
||||
were ever reviewed. An empty diff must mean 'nothing to sign', never
|
||||
'sign unlocked'."""
|
||||
same_catalog = _catalog(_entry())
|
||||
session = r.start_review("sha1", same_catalog, same_catalog)
|
||||
assert session.changes == [] # diff_catalogs(x, x) -> []
|
||||
assert r.all_entries_acknowledged(session) is True # vacuously -- this is the trap
|
||||
decision = r.can_sign(session, "sha1") # blob matches, "everything" acknowledged
|
||||
assert decision.ok is False
|
||||
assert "nothing to sign" in decision.reason.lower()
|
||||
|
||||
|
||||
def test_can_sign_false_with_outstanding_blocking_risk_even_if_acknowledged():
|
||||
"""can_sign() must itself refuse a blocking risk finding -- today a
|
||||
blocking finding only disables the GUI checkbox, so the pure gate must
|
||||
not simply trust that the caller never acknowledged a blocking entry.
|
||||
Acknowledge it directly here (bypassing any GUI checkbox-disable logic
|
||||
entirely) to prove the gate catches it independently of the GUI."""
|
||||
session = r.start_review(
|
||||
"sha1",
|
||||
_catalog(),
|
||||
_catalog(_entry(config={"command": "bash", "args": ["-c", "evil"]})),
|
||||
)
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
assert r.all_entries_acknowledged(session) is True
|
||||
decision = r.can_sign(session, "sha1")
|
||||
assert decision.ok is False
|
||||
assert "blocking" in decision.reason.lower()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# sign_precondition: the ref-resolution seam that used to hardcode "main"
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_sign_precondition_resolves_against_loaded_ref_not_hardcoded_main():
|
||||
"""The regression test for issue #68 finding 1's first bug:
|
||||
ReviewWindow._on_sign used to hardcode fetch_ref(repo, "main") as the
|
||||
TOCTOU comparison ref. For a PR review, _on_load pins the PR HEAD's
|
||||
blob SHA, so comparing against main's SHA differs by definition and
|
||||
Sign could never fire on the PR path.
|
||||
|
||||
The fake resolver below returns a DIFFERENT (deliberately wrong) SHA for
|
||||
"main" than for the PR ref that was actually loaded. If
|
||||
sign_precondition ever resolves against "main" instead of
|
||||
session.loaded_ref, this test fails -- both via the recorded `calls`
|
||||
list and via decision.ok flipping to False.
|
||||
"""
|
||||
pr_ref = "refs/pull/42/head"
|
||||
session = r.start_review("pr-blob-sha", _catalog(), _catalog(_entry()), loaded_ref=pr_ref)
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
def fake_resolver(ref: str) -> str:
|
||||
calls.append(ref)
|
||||
return {"main": "main-blob-sha-WRONG", pr_ref: "pr-blob-sha"}[ref]
|
||||
|
||||
decision = r.sign_precondition(session, fake_resolver)
|
||||
assert calls == [pr_ref] # never asked the resolver for "main"
|
||||
assert decision.ok is True
|
||||
assert decision.reason is None
|
||||
|
||||
|
||||
def test_sign_precondition_refuses_when_loaded_ref_blob_moved():
|
||||
"""Same seam, the negative case: if the loaded ref's blob SHA has moved
|
||||
since review began (a new commit landed on the reviewed PR/branch), the
|
||||
resolver reflects that and sign_precondition must refuse -- proving this
|
||||
isn't just a hardcoded pass-through."""
|
||||
pr_ref = "refs/pull/42/head"
|
||||
session = r.start_review("pr-blob-sha", _catalog(), _catalog(_entry()), loaded_ref=pr_ref)
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
|
||||
def fake_resolver(_ref: str) -> str:
|
||||
return "pr-blob-sha-AFTER-A-NEW-PUSH"
|
||||
|
||||
decision = r.sign_precondition(session, fake_resolver)
|
||||
assert decision.ok is False
|
||||
assert "mismatch" in decision.reason.lower() or "changed" in decision.reason.lower()
|
||||
|
||||
|
||||
def test_sign_precondition_defaults_to_main_when_loaded_ref_unset():
|
||||
"""start_review()'s loaded_ref defaults to 'main' for source=main
|
||||
reviews (and backward-compat with callers that don't pass it)."""
|
||||
session = r.start_review("sha1", _catalog(), _catalog(_entry()))
|
||||
assert session.loaded_ref == "main"
|
||||
r.acknowledge_entry(session, "filesystem")
|
||||
|
||||
def fake_resolver(ref: str) -> str:
|
||||
assert ref == "main"
|
||||
return "sha1"
|
||||
|
||||
decision = r.sign_precondition(session, fake_resolver)
|
||||
assert decision.ok is True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# find_last_signed_catalog_raw: what source=main diffs against
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_find_last_signed_catalog_raw_returns_matching_candidate():
|
||||
"""Simulates walking catalog.json's git history: the CURRENT signature
|
||||
covers an OLDER version of the bytes (a later commit changed
|
||||
catalog.json without re-signing -- the exact bypass that produced
|
||||
commit b08cf21). The first candidate that verifies against that
|
||||
signature is 'the last catalog a maintainer actually signed'."""
|
||||
seed, pubkey = r.generate_keypair()
|
||||
old_raw = b'{"schema":1,"version":1,"servers":[]}'
|
||||
new_raw = b'{"schema":1,"version":2,"servers":[]}'
|
||||
sig = r.sign_catalog_bytes(old_raw, seed) # signature covers the OLD bytes
|
||||
found = r.find_last_signed_catalog_raw([new_raw, old_raw], sig, [pubkey])
|
||||
assert found == old_raw
|
||||
|
||||
|
||||
def test_find_last_signed_catalog_raw_none_when_nothing_verifies():
|
||||
seed, _pubkey = r.generate_keypair()
|
||||
_other_seed, other_pubkey = r.generate_keypair()
|
||||
raw = b'{"schema":1,"version":1,"servers":[]}'
|
||||
sig = r.sign_catalog_bytes(raw, seed)
|
||||
# Check against a pubkey list that does NOT include the signer's key.
|
||||
assert r.find_last_signed_catalog_raw([raw], sig, [other_pubkey]) is None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# catalog_signing_message: domain separation must match bcc_core exactly
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_signing_message_uses_bcc_core_domain_prefix():
|
||||
raw = b'{"schema":1}'
|
||||
msg = r.catalog_signing_message(raw)
|
||||
assert msg == c._CATALOG_SIG_DOMAIN + raw
|
||||
assert msg.startswith(b"bcc-catalog-v1|")
|
||||
|
||||
|
||||
def test_sign_then_verify_round_trips_with_bcc_core():
|
||||
"""End-to-end: a signature produced by the Console's sign_catalog_bytes
|
||||
must verify with bcc_core.verify_catalog_signature -- proves the two
|
||||
modules can never drift on the domain-separation prefix."""
|
||||
seed, pubkey = r.generate_keypair()
|
||||
raw = b'{"schema":1,"version":2,"servers":[]}'
|
||||
sig = r.sign_catalog_bytes(raw, seed)
|
||||
assert c.verify_catalog_signature(raw, sig, [pubkey]) is True
|
||||
|
||||
|
||||
def test_sign_tampered_bytes_fails_verify():
|
||||
seed, pubkey = r.generate_keypair()
|
||||
raw = b'{"schema":1,"version":2,"servers":[]}'
|
||||
sig = r.sign_catalog_bytes(raw, seed)
|
||||
tampered = raw[:-1] + b"0"
|
||||
assert c.verify_catalog_signature(tampered, sig, [pubkey]) is False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Key encryption at rest
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_encrypt_decrypt_round_trip():
|
||||
seed, _pub = r.generate_keypair()
|
||||
blob = r.encrypt_private_key(seed, "correct horse battery staple")
|
||||
decrypted = r.decrypt_private_key(blob, "correct horse battery staple")
|
||||
assert decrypted == seed
|
||||
|
||||
|
||||
def test_decrypt_wrong_passphrase_raises():
|
||||
seed, _pub = r.generate_keypair()
|
||||
blob = r.encrypt_private_key(seed, "right passphrase")
|
||||
with pytest.raises(ValueError):
|
||||
r.decrypt_private_key(blob, "wrong passphrase")
|
||||
|
||||
|
||||
def test_decrypt_corrupted_blob_raises():
|
||||
seed, _pub = r.generate_keypair()
|
||||
blob = r.encrypt_private_key(seed, "pass")
|
||||
corrupted = blob[:-1] + bytes([blob[-1] ^ 0xFF])
|
||||
with pytest.raises(ValueError):
|
||||
r.decrypt_private_key(corrupted, "pass")
|
||||
|
||||
|
||||
def test_encrypt_private_key_rejects_wrong_length_seed():
|
||||
with pytest.raises(ValueError):
|
||||
r.encrypt_private_key(b"too-short", "pass")
|
||||
|
||||
|
||||
def test_encrypt_private_key_rejects_empty_passphrase():
|
||||
seed, _pub = r.generate_keypair()
|
||||
with pytest.raises(ValueError):
|
||||
r.encrypt_private_key(seed, "")
|
||||
|
||||
|
||||
def test_encrypted_blob_never_contains_seed_plaintext():
|
||||
seed, _pub = r.generate_keypair()
|
||||
blob = r.encrypt_private_key(seed, "some passphrase")
|
||||
assert seed not in blob
|
||||
|
||||
|
||||
def test_generate_keypair_produces_valid_ed25519_pair():
|
||||
seed, pubkey = r.generate_keypair()
|
||||
assert len(seed) == 32
|
||||
assert len(pubkey) == 32
|
||||
raw = b"test payload"
|
||||
sig = r.sign_catalog_bytes(raw, seed)
|
||||
assert c.verify_catalog_signature(raw, sig, [pubkey]) is True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Registry lookup / near-neighbour edit distance
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_edit_distance_identical():
|
||||
assert r.edit_distance("abc", "abc") == 0
|
||||
|
||||
|
||||
def test_edit_distance_one_substitution():
|
||||
assert r.edit_distance("firecrawl-mcp", "f1recrawl-mcp") == 1
|
||||
|
||||
|
||||
def test_near_neighbor_ids_finds_close_match():
|
||||
others = ["firecrawl-mcp", "unrelated-server", "totally-different"]
|
||||
neighbors = r.near_neighbor_ids("firecrawl-mcp2", others, max_distance=2)
|
||||
assert "firecrawl-mcp" in neighbors
|
||||
|
||||
|
||||
def test_near_neighbor_ids_excludes_self():
|
||||
others = ["filesystem", "other"]
|
||||
assert "filesystem" not in r.near_neighbor_ids("filesystem", others)
|
||||
|
||||
|
||||
def test_near_neighbor_ids_excludes_far_matches():
|
||||
others = ["completely-unrelated-name"]
|
||||
assert r.near_neighbor_ids("filesystem", others, max_distance=2) == []
|
||||
|
||||
|
||||
def test_extract_package_refs_npm():
|
||||
entry = _entry(config={"command": "npx", "args": ["-y", "@scope/pkg@1.2.3"]})
|
||||
refs = r.extract_package_refs(entry)
|
||||
assert len(refs) == 1
|
||||
assert refs[0].ecosystem == "npm"
|
||||
assert refs[0].name == "@scope/pkg"
|
||||
assert refs[0].version == "1.2.3"
|
||||
|
||||
|
||||
def test_extract_package_refs_uvx():
|
||||
entry = _entry(config={"command": "uvx", "args": ["some-pypi-pkg==1.0.0"]})
|
||||
refs = r.extract_package_refs(entry)
|
||||
assert len(refs) == 1
|
||||
assert refs[0].ecosystem == "pypi"
|
||||
assert refs[0].name == "some-pypi-pkg"
|
||||
assert refs[0].version == "1.0.0"
|
||||
|
||||
|
||||
def test_extract_package_refs_link_only_entry_returns_empty():
|
||||
entry = {"id": "slack", "setup": "link-only", "docs_url": "https://example.com"}
|
||||
assert r.extract_package_refs(entry) == []
|
||||
|
||||
|
||||
def test_lookup_registry_info_fails_soft_on_none():
|
||||
ref = r.PackageRef("x", "npm", "somepkg", "1.0.0")
|
||||
info = r.lookup_registry_info(ref, lambda _ref: None, [])
|
||||
assert info.available is False
|
||||
|
||||
|
||||
def test_lookup_registry_info_fails_soft_on_exception():
|
||||
def boom(_ref):
|
||||
raise RuntimeError("network down")
|
||||
|
||||
ref = r.PackageRef("x", "npm", "somepkg", "1.0.0")
|
||||
info = r.lookup_registry_info(ref, boom, [])
|
||||
assert info.available is False
|
||||
|
||||
|
||||
def test_lookup_registry_info_populates_fields_when_available():
|
||||
ref = r.PackageRef("x", "npm", "somepkg", "1.0.0")
|
||||
|
||||
def fetcher(_ref):
|
||||
return {
|
||||
"publisher": "hello_sideguide",
|
||||
"age_days": 30,
|
||||
"last_release": "2026-01-01",
|
||||
"downloads": 500,
|
||||
}
|
||||
|
||||
info = r.lookup_registry_info(ref, fetcher, [])
|
||||
assert info.available is True
|
||||
assert info.publisher == "hello_sideguide"
|
||||
assert info.downloads == 500
|
||||
|
||||
|
||||
def test_lookup_registry_info_includes_near_neighbors():
|
||||
ref = r.PackageRef("x", "npm", "firecrawl-mcp2", "1.0.0")
|
||||
info = r.lookup_registry_info(ref, lambda _ref: None, ["firecrawl-mcp"])
|
||||
assert "firecrawl-mcp" in info.near_neighbor_ids
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# contains_non_ascii
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_contains_non_ascii_true():
|
||||
assert r.contains_non_ascii("pаckage") is True
|
||||
|
||||
|
||||
def test_contains_non_ascii_false():
|
||||
assert r.contains_non_ascii("package") is False
|
||||
+622
-4
@@ -1,6 +1,7 @@
|
||||
"""Pytest port of the original test_core.py script (same 23 behaviours, now
|
||||
proper test functions with tmp_path/monkeypatch fixtures)."""
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -1690,8 +1691,12 @@ def _minimal_catalog(version: int = 1) -> dict:
|
||||
"official": True,
|
||||
"setup": "basic",
|
||||
"config": {
|
||||
# Pinned on purpose (issue #68 finding 3): an earlier
|
||||
# version of this fixture used an unpinned package and
|
||||
# asserted it validated clean, which enshrined the bug
|
||||
# instead of catching it.
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp"],
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
},
|
||||
"placeholders": {},
|
||||
"env_required": {},
|
||||
@@ -1952,6 +1957,213 @@ def test_validate_catalog_rejects_duplicate_ids():
|
||||
assert any("duplicate id" in p for p in problems)
|
||||
|
||||
|
||||
# --- validate_catalog: config.env (issue #68 finding 2) -------------------- #
|
||||
def test_validate_catalog_rejects_each_denied_env_key():
|
||||
for key in sorted(c.CATALOG_DENIED_ENV_KEYS):
|
||||
data = _catalog_with(
|
||||
{"config": {"command": "npx", "args": ["-y", "widget-mcp@1.0.0"], "env": {key: ""}}}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("deny-list" in p for p in problems), (key, problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_denied_env_key_case_insensitively():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"node_options": ""},
|
||||
}
|
||||
}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("deny-list" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_nonempty_nonplaceholder_env_value():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"FOO_URL": "https://example.com"},
|
||||
}
|
||||
}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("empty string or a single <PLACEHOLDER>" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_accepts_empty_and_placeholder_env_values():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"FOO": "", "BAR_URL": "<BAR_URL>"},
|
||||
}
|
||||
}
|
||||
)
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_non_ascii_env_key():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"FÖO": ""},
|
||||
}
|
||||
}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("config.env key" in p and "ASCII" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_non_ascii_env_value():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"FOO": "<Bäd>"},
|
||||
}
|
||||
}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("config.env value" in p and "ASCII" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_secret_looking_env_value():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"SOME_TOKEN": "ghp_abcdef1234567890"},
|
||||
}
|
||||
}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("real secret value" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_node_options_env_walking_past_allowlist():
|
||||
# The exact reproduction from issue #68 finding 2: an allowlisted
|
||||
# `npx` command carrying NODE_OPTIONS in env, which previously passed
|
||||
# validation and would have flowed straight into the executed
|
||||
# subprocess via catalog_entry_to_paste_json().
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "widget-mcp@1.0.0"],
|
||||
"env": {"NODE_OPTIONS": "--require /tmp/payload.js"},
|
||||
}
|
||||
}
|
||||
)
|
||||
problems = c.validate_catalog(data)
|
||||
assert problems != []
|
||||
|
||||
|
||||
# --- validate_catalog: version pinning (issue #68 finding 3) --------------- #
|
||||
def test_validate_catalog_rejects_unpinned_npx_package():
|
||||
data = _catalog_with({"config": {"command": "npx", "args": ["-y", "widget-mcp"]}})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("not version-pinned" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_unpinned_scoped_npx_package():
|
||||
data = _catalog_with({"config": {"command": "npx", "args": ["-y", "@scope/pkg"]}})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("not version-pinned" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_accepts_pinned_scoped_npx_package():
|
||||
data = _catalog_with({"config": {"command": "npx", "args": ["-y", "@scope/pkg@1.2.3"]}})
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_unpinned_uvx_package():
|
||||
data = _catalog_with({"config": {"command": "uvx", "args": ["some-tool"]}})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("not version-pinned" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_accepts_uvx_at_version_pin():
|
||||
data = _catalog_with({"config": {"command": "uvx", "args": ["some-tool@1.0.0"]}})
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
def test_validate_catalog_accepts_uvx_double_equals_pin():
|
||||
data = _catalog_with({"config": {"command": "uvx", "args": ["some-tool==1.0.0"]}})
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_docker_latest_tag():
|
||||
data = _catalog_with({"config": {"command": "docker", "args": ["run", "some/image:latest"]}})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("'latest'" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_docker_untagged_image():
|
||||
data = _catalog_with({"config": {"command": "docker", "args": ["run", "some/image"]}})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("no explicit tag" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_accepts_pinned_docker_image_with_flags():
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "docker",
|
||||
"args": ["run", "-i", "--rm", "-e", "SOME_TOKEN", "some/image:1.2.3"],
|
||||
}
|
||||
}
|
||||
)
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
def test_validate_catalog_does_not_pin_check_placeholders_flags_or_subcommand():
|
||||
# A pinned uvx spec followed by flags and a <PLACEHOLDER> positional
|
||||
# must not itself get mistaken for an unpinned package.
|
||||
data = _catalog_with(
|
||||
{
|
||||
"config": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-git@2026.7.10", "--repository", "<REPO_PATH>"],
|
||||
}
|
||||
}
|
||||
)
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
# --- validate_catalog: id constraint (issue #68 finding 7) ----------------- #
|
||||
def test_validate_catalog_rejects_id_with_markup():
|
||||
data = _catalog_with({"id": "<b>Verified</b>"})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("must match" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_id_with_uppercase():
|
||||
data = _catalog_with({"id": "Widget"})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("must match" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_rejects_id_starting_with_dash():
|
||||
data = _catalog_with({"id": "-widget"})
|
||||
problems = c.validate_catalog(data)
|
||||
assert any("must match" in p for p in problems)
|
||||
|
||||
|
||||
def test_validate_catalog_accepts_valid_slug_id():
|
||||
data = _catalog_with({"id": "widget-2.thing-ok"})
|
||||
assert c.validate_catalog(data) == []
|
||||
|
||||
|
||||
# --- resolve_catalog -------------------------------------------------------- #
|
||||
def test_resolve_catalog_nothing_available_returns_empty_dict():
|
||||
assert c.resolve_catalog(None, None, None) == {}
|
||||
@@ -2003,13 +2215,93 @@ def test_resolve_catalog_rejects_absurd_version_jump(monkeypatch):
|
||||
pub = priv.public_key().public_bytes_raw()
|
||||
monkeypatch.setattr(c, "CATALOG_PUBKEYS", [pub])
|
||||
|
||||
cached = _signed(_minimal_catalog(version=5), priv)
|
||||
# The freeze attempt goes FIRST (as `cached`), the legitimate catalog
|
||||
# SECOND (as `remote`) -- on purpose. Putting the good catalog first
|
||||
# (as an earlier version of this test did) never exercises the
|
||||
# vulnerable path: the old implementation only guarded a candidate
|
||||
# against "the best accepted so far," so whichever candidate was
|
||||
# evaluated FIRST got in unconditionally, uncapped. Ordering the freeze
|
||||
# attempt first is what actually proves the cap holds regardless of
|
||||
# evaluation order.
|
||||
freeze_attempt = _signed(_minimal_catalog(version=999999), priv)
|
||||
good = _signed(_minimal_catalog(version=5), priv)
|
||||
|
||||
result = c.resolve_catalog(None, cached, freeze_attempt)
|
||||
result = c.resolve_catalog(None, freeze_attempt, good)
|
||||
assert c.catalog_version(result) == 5
|
||||
|
||||
|
||||
def test_resolve_catalog_caps_first_and_only_candidate(monkeypatch):
|
||||
# issue #68 finding 6: with no bundled catalog to anchor against, a
|
||||
# signed catalog claiming an absurd version must still be capped even
|
||||
# when it is the ONLY candidate resolve_catalog() ever sees -- there is
|
||||
# no "best so far" for it to be compared against, so the cap has to
|
||||
# apply unconditionally, not "once something else has already landed."
|
||||
priv = Ed25519PrivateKey.generate()
|
||||
pub = priv.public_key().public_bytes_raw()
|
||||
monkeypatch.setattr(c, "CATALOG_PUBKEYS", [pub])
|
||||
|
||||
freeze_attempt = _signed(_minimal_catalog(version=999999999), priv)
|
||||
|
||||
result = c.resolve_catalog(None, None, freeze_attempt)
|
||||
assert result == {}
|
||||
|
||||
|
||||
def test_resolve_catalog_anchors_cap_to_bundled_not_a_chained_best(monkeypatch):
|
||||
# Anti-freeze must be measured against the BUNDLED version specifically,
|
||||
# not against "whatever the best-so-far happens to be after each
|
||||
# candidate is accepted" -- a chained anchor lets each accepted
|
||||
# candidate ratchet the allowed ceiling upward, so a legitimate
|
||||
# moderate bump (cached) plus a second, much larger jump (remote) can
|
||||
# each individually look "within _CATALOG_MAX_VERSION_JUMP of the
|
||||
# previous one" while remote is nowhere near bundled's version.
|
||||
priv = Ed25519PrivateKey.generate()
|
||||
pub = priv.public_key().public_bytes_raw()
|
||||
monkeypatch.setattr(c, "CATALOG_PUBKEYS", [pub])
|
||||
|
||||
bundled = _signed(_minimal_catalog(version=2), priv)
|
||||
cached = _signed(_minimal_catalog(version=1000), priv) # within 1000 of bundled
|
||||
remote = _signed(_minimal_catalog(version=1900), priv) # within 1000 of cached,
|
||||
# NOT of bundled
|
||||
|
||||
result = c.resolve_catalog(bundled, cached, remote)
|
||||
assert c.catalog_version(result) == 1000
|
||||
|
||||
|
||||
def test_resolve_catalog_prefers_bundled_on_version_tie(monkeypatch):
|
||||
# issue #68 finding 6: on a tie the LAST candidate evaluated used to
|
||||
# win, so remote silently beat bundled at equal version. Bundled --
|
||||
# the copy frozen into the binary -- must win ties.
|
||||
priv = Ed25519PrivateKey.generate()
|
||||
pub = priv.public_key().public_bytes_raw()
|
||||
monkeypatch.setattr(c, "CATALOG_PUBKEYS", [pub])
|
||||
|
||||
bundled_data = _minimal_catalog(version=5)
|
||||
bundled = _signed(bundled_data, priv)
|
||||
|
||||
remote_data = _minimal_catalog(version=5)
|
||||
remote_data["servers"][0]["display"] = "Remote Impostor"
|
||||
remote = _signed(remote_data, priv)
|
||||
|
||||
result = c.resolve_catalog(bundled, None, remote)
|
||||
assert c.catalog_version(result) == 5
|
||||
assert result["servers"][0]["display"] == "Widget"
|
||||
|
||||
|
||||
def test_resolve_catalog_floor_rejects_below_persisted_version(monkeypatch):
|
||||
# `floor` is a pure parameter: the caller (eventually the GUI, from
|
||||
# persisted storage) can pass a previously-accepted version, and
|
||||
# nothing below it may be accepted even with no bundled catalog to
|
||||
# anchor against.
|
||||
priv = Ed25519PrivateKey.generate()
|
||||
pub = priv.public_key().public_bytes_raw()
|
||||
monkeypatch.setattr(c, "CATALOG_PUBKEYS", [pub])
|
||||
|
||||
stale = _signed(_minimal_catalog(version=3), priv)
|
||||
|
||||
result = c.resolve_catalog(None, None, stale, floor=10)
|
||||
assert result == {}
|
||||
|
||||
|
||||
def test_resolve_catalog_malformed_candidate_does_not_raise(monkeypatch):
|
||||
priv = Ed25519PrivateKey.generate()
|
||||
pub = priv.public_key().public_bytes_raw()
|
||||
@@ -2039,15 +2331,32 @@ def test_resolve_catalog_invalid_but_signed_candidate_is_skipped(monkeypatch):
|
||||
def test_catalog_entry_to_paste_json_basic_shape():
|
||||
entry = _minimal_catalog()["servers"][0]
|
||||
result = c.catalog_entry_to_paste_json(entry)
|
||||
assert result == {"widget": {"command": "npx", "args": ["-y", "widget-mcp"]}}
|
||||
assert result == {"widget": {"command": "npx", "args": ["-y", "widget-mcp@1.0.0"]}}
|
||||
|
||||
|
||||
def test_catalog_entry_to_paste_json_includes_env_when_present():
|
||||
# NOTE: catalog_entry_to_paste_json() is a pure shape-converter for an
|
||||
# entry that has ALREADY passed validate_catalog() -- it is correct for
|
||||
# it to carry env through verbatim. The bug (issue #68 finding 2) was
|
||||
# never in this function; it was that validate_catalog() let entries
|
||||
# with dangerous/non-placeholder env values reach this function in the
|
||||
# first place. This test now proves that boundary explicitly: a
|
||||
# validation-legal env value (a <PLACEHOLDER> token) survives the
|
||||
# conversion, and a value validate_catalog() would have rejected is
|
||||
# confirmed rejected before it ever gets here.
|
||||
entry = _minimal_catalog()["servers"][0]
|
||||
entry["config"]["env"] = {"GRAFANA_URL": "<GRAFANA_URL>"}
|
||||
result = c.catalog_entry_to_paste_json(entry)
|
||||
assert result["widget"]["env"] == {"GRAFANA_URL": "<GRAFANA_URL>"}
|
||||
|
||||
catalog = _minimal_catalog()
|
||||
catalog["servers"][0]["config"]["env"] = {"GRAFANA_URL": "<GRAFANA_URL>"}
|
||||
assert c.validate_catalog(catalog) == []
|
||||
|
||||
malicious = _minimal_catalog()
|
||||
malicious["servers"][0]["config"]["env"] = {"NODE_OPTIONS": "--require /tmp/payload.js"}
|
||||
assert c.validate_catalog(malicious) != []
|
||||
|
||||
|
||||
def test_config_has_unfilled_placeholders_true_for_token():
|
||||
cfg = {"command": "npx", "args": ["-y", "server", "<ALLOWED_DIR>"]}
|
||||
@@ -2062,3 +2371,312 @@ def test_config_has_unfilled_placeholders_false_after_fill():
|
||||
def test_config_has_unfilled_placeholders_checks_env_too():
|
||||
cfg = {"command": "uvx", "args": ["mcp-grafana"], "env": {"GRAFANA_URL": "<GRAFANA_URL>"}}
|
||||
assert c.config_has_unfilled_placeholders(cfg) is True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# #72 -- a server value that isn't a JSON object must not take the load down
|
||||
# --------------------------------------------------------------------------- #
|
||||
@pytest.mark.parametrize("bad", ["not-a-dict", 123, ["a", "b"], None, True, 1.5])
|
||||
def test_extract_servers_survives_non_dict_server_value(bad):
|
||||
entries = c.extract_servers({"mcpServers": {"foo": bad}})
|
||||
assert len(entries) == 1
|
||||
assert entries[0].name == "foo"
|
||||
assert entries[0].data == {}
|
||||
assert entries[0].malformed is True
|
||||
assert entries[0].raw == bad
|
||||
|
||||
|
||||
def test_extract_servers_marks_only_the_bad_entry():
|
||||
cfg = {"mcpServers": {"good": {"command": "npx"}, "bad": "oops"}}
|
||||
by_name = {e.name: e for e in c.extract_servers(cfg)}
|
||||
assert by_name["good"].malformed is False
|
||||
assert by_name["good"].data == {"command": "npx"}
|
||||
assert by_name["bad"].malformed is True
|
||||
|
||||
|
||||
def test_extract_servers_handles_malformed_disabled_entry():
|
||||
entries = c.extract_servers({c.DISABLED_KEY: {"parked": ["nope"]}})
|
||||
assert entries[0].enabled is False
|
||||
assert entries[0].malformed is True
|
||||
|
||||
|
||||
def test_malformed_entry_round_trips_through_save_unchanged():
|
||||
"""The cardinal rule: never silently delete what the user had on disk."""
|
||||
cfg = {"mcpServers": {"good": {"command": "npx"}, "bad": "oops"}}
|
||||
servers = c.extract_servers(cfg)
|
||||
out = c.apply_servers(dict(cfg), servers)
|
||||
assert out["mcpServers"]["bad"] == "oops"
|
||||
assert out["mcpServers"]["good"] == {"command": "npx"}
|
||||
|
||||
|
||||
def test_editing_a_malformed_entry_retires_the_raw_value():
|
||||
entry = c.extract_servers({"mcpServers": {"bad": "oops"}})[0]
|
||||
entry.set_data({"command": "npx"})
|
||||
assert entry.malformed is False
|
||||
assert entry.config_value() == {"command": "npx"}
|
||||
assert c.apply_servers({}, [entry])["mcpServers"]["bad"] == {"command": "npx"}
|
||||
|
||||
|
||||
def test_lint_reports_the_malformed_entry_by_name():
|
||||
servers = c.extract_servers({"mcpServers": {"bad": "oops"}})
|
||||
warnings = c.lint_servers(servers)
|
||||
assert len(warnings) == 1
|
||||
assert "'bad'" in warnings[0]
|
||||
assert "not an object" in warnings[0]
|
||||
assert "str" in warnings[0]
|
||||
|
||||
|
||||
def test_lint_still_reports_normal_warnings_alongside_malformed():
|
||||
cfg = {"mcpServers": {"bad": "oops", "sloppy": {"command": "npx", "args": "one two"}}}
|
||||
warnings = c.lint_servers(c.extract_servers(cfg))
|
||||
assert any("not an object" in w for w in warnings)
|
||||
assert any("'args' should be a list" in w for w in warnings)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# #73 -- the stale-file merge must not discard BCC-authored keys
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_carry_owned_keys_moves_sets_onto_the_reloaded_config():
|
||||
local = {"mcpServers": {}, c.SETS_KEY: {"work": ["a", "b"]}}
|
||||
fresh = {"mcpServers": {"external": {"command": "npx"}}}
|
||||
contested = c.carry_owned_keys(local, fresh)
|
||||
assert contested == []
|
||||
assert fresh[c.SETS_KEY] == {"work": ["a", "b"]}
|
||||
assert fresh["mcpServers"] == {"external": {"command": "npx"}}
|
||||
|
||||
|
||||
def test_carry_owned_keys_reports_a_genuine_conflict():
|
||||
local = {c.SETS_KEY: {"work": ["a"]}}
|
||||
fresh = {c.SETS_KEY: {"work": ["a", "b"]}}
|
||||
assert c.carry_owned_keys(local, fresh) == [c.SETS_KEY]
|
||||
assert fresh[c.SETS_KEY] == {"work": ["a"]} # local wins: BCC owns the key
|
||||
|
||||
|
||||
def test_carry_owned_keys_is_quiet_when_both_sides_agree():
|
||||
local = {c.SETS_KEY: {"work": ["a"]}}
|
||||
fresh = {c.SETS_KEY: {"work": ["a"]}}
|
||||
assert c.carry_owned_keys(local, fresh) == []
|
||||
|
||||
|
||||
def test_carry_owned_keys_leaves_disk_alone_when_absent_locally():
|
||||
"""Can't distinguish 'deleted my last set' from 'never had sets'; keep theirs."""
|
||||
fresh = {c.SETS_KEY: {"remote": ["a"]}}
|
||||
assert c.carry_owned_keys({}, fresh) == []
|
||||
assert fresh[c.SETS_KEY] == {"remote": ["a"]}
|
||||
|
||||
|
||||
def test_carry_owned_keys_deep_copies_so_later_edits_do_not_leak():
|
||||
local = {c.SETS_KEY: {"work": ["a"]}}
|
||||
fresh = {}
|
||||
c.carry_owned_keys(local, fresh)
|
||||
local[c.SETS_KEY]["work"].append("b")
|
||||
assert fresh[c.SETS_KEY] == {"work": ["a"]}
|
||||
|
||||
|
||||
def test_merge_flow_preserves_sets_and_external_servers(tmp_path):
|
||||
"""End-to-end shape of the Merge & save path that lost sets in #73."""
|
||||
path = tmp_path / "claude.json"
|
||||
path.write_text(json.dumps({"mcpServers": {"old": {"command": "old"}}}))
|
||||
|
||||
# BCC loads, user saves a named set and edits servers in memory.
|
||||
local = c.load_config(path)
|
||||
servers = c.extract_servers(local)
|
||||
c.save_server_set(local, "work", servers)
|
||||
|
||||
# Something else rewrites the file underneath us.
|
||||
path.write_text(json.dumps({"mcpServers": {"external": {"command": "new"}}, "other": 1}))
|
||||
|
||||
# Merge & save: reload disk, carry BCC keys, re-apply the user's servers.
|
||||
fresh = c.load_config(path)
|
||||
c.carry_owned_keys(local, fresh)
|
||||
c.apply_servers(fresh, servers)
|
||||
c.write_config(path, fresh)
|
||||
|
||||
saved = c.load_config(path)
|
||||
assert saved[c.SETS_KEY] == {"work": ["old"]} # the set survived
|
||||
assert saved["other"] == 1 # unrelated external key preserved
|
||||
assert "old" in saved["mcpServers"] # user's servers re-applied
|
||||
|
||||
|
||||
def test_null_server_value_is_malformed_not_mistaken_for_absent():
|
||||
"""`{"mcpServers": {"foo": null}}` is legal JSON and a real malformed case,
|
||||
so None must not double as the 'nothing here' sentinel."""
|
||||
entry = c.extract_servers({"mcpServers": {"foo": None}})[0]
|
||||
assert entry.malformed is True
|
||||
assert entry.raw is None
|
||||
assert c.apply_servers({}, [entry])["mcpServers"]["foo"] is None
|
||||
|
||||
|
||||
def test_a_normal_entry_is_not_malformed():
|
||||
entry = c.extract_servers({"mcpServers": {"foo": {"command": "npx"}}})[0]
|
||||
assert entry.malformed is False
|
||||
assert entry.raw is c.NO_RAW
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# #75 -- theming
|
||||
# --------------------------------------------------------------------------- #
|
||||
@pytest.mark.parametrize(
|
||||
"setting,system_dark,expected",
|
||||
[
|
||||
(c.THEME_DARK, False, "dark"),
|
||||
(c.THEME_DARK, True, "dark"),
|
||||
(c.THEME_LIGHT, False, "light"),
|
||||
(c.THEME_LIGHT, True, "light"),
|
||||
(c.THEME_SYSTEM, True, "dark"),
|
||||
(c.THEME_SYSTEM, False, "light"),
|
||||
],
|
||||
)
|
||||
def test_resolve_theme_covers_every_setting_and_appearance(setting, system_dark, expected):
|
||||
assert c.resolve_theme(setting, system_dark) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("junk", ["", "solarized", None, "DARK", 3])
|
||||
def test_resolve_theme_falls_back_to_following_the_system(junk):
|
||||
"""A hand-edited or future QSettings value should follow the desktop,
|
||||
not pin a fixed theme."""
|
||||
assert c.resolve_theme(junk, True) == "dark"
|
||||
assert c.resolve_theme(junk, False) == "light"
|
||||
|
||||
|
||||
def test_palette_for_known_names():
|
||||
assert c.palette_for("dark") is c.DARK_PALETTE
|
||||
assert c.palette_for("light") is c.LIGHT_PALETTE
|
||||
|
||||
|
||||
def test_palette_for_unknown_name_falls_back_to_dark():
|
||||
assert c.palette_for("chartreuse") is c.DARK_PALETTE
|
||||
|
||||
|
||||
def test_dark_palette_is_unchanged_from_the_shipped_look():
|
||||
"""v1.3.0 shipped these exact colours; adding a light theme must not
|
||||
quietly restyle the dark one."""
|
||||
p = c.DARK_PALETTE
|
||||
assert (p.accent, p.bg, p.panel, p.panel_2) == ("#f97316", "#1b1d23", "#23262e", "#2b2f39")
|
||||
assert (p.text, p.muted, p.border) == ("#e7e9ee", "#9aa0ad", "#3a3f4b")
|
||||
assert (p.good, p.bad, p.warn, p.remote) == ("#4ade80", "#f87171", "#fbbf24", "#60a5fa")
|
||||
assert (p.on_accent, p.disabled_bg, p.mono_bg) == ("#1a1205", "#202229", "#16181d")
|
||||
|
||||
|
||||
def test_both_palettes_define_every_slot():
|
||||
"""A missing slot should fail here rather than render a broken window."""
|
||||
for pal in (c.DARK_PALETTE, c.LIGHT_PALETTE):
|
||||
for f in dataclasses.fields(c.Palette):
|
||||
value = getattr(pal, f.name)
|
||||
assert value, f"{pal.name}.{f.name} is empty"
|
||||
if f.name != "name":
|
||||
assert re.fullmatch(r"#[0-9a-fA-F]{6}", value), f"{pal.name}.{f.name}={value!r}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pal_name", ["dark", "light"])
|
||||
@pytest.mark.parametrize("slot", ["text", "muted", "good", "bad", "warn", "remote", "accent"])
|
||||
def test_palette_meets_contrast_on_panel(pal_name, slot):
|
||||
"""Every colour drawn as text/glyph must clear WCAG AA (4.5:1) against the
|
||||
surface it sits on. The light palette's semantic colours are NOT the dark
|
||||
ones lightened -- #4ade80 sits near 1.7:1 on white -- so this guards
|
||||
against someone 'harmonising' them back toward the dark hues."""
|
||||
pal = c.palette_for(pal_name)
|
||||
assert c.contrast_ratio(getattr(pal, slot), pal.panel) >= 4.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pal_name", ["dark", "light"])
|
||||
def test_on_accent_is_legible_against_the_accent_fill(pal_name):
|
||||
"""Primary buttons and selected rows draw on_accent on top of accent."""
|
||||
pal = c.palette_for(pal_name)
|
||||
assert c.contrast_ratio(pal.on_accent, pal.accent) >= 4.5
|
||||
|
||||
|
||||
def test_contrast_ratio_endpoints():
|
||||
assert c.contrast_ratio("#000000", "#ffffff") == pytest.approx(21.0, abs=0.01)
|
||||
assert c.contrast_ratio("#123456", "#123456") == pytest.approx(1.0, abs=0.001)
|
||||
assert c.contrast_ratio("#ffffff", "#000000") == pytest.approx(21.0, abs=0.01)
|
||||
|
||||
|
||||
def test_relative_luminance_extremes():
|
||||
assert c.relative_luminance("#000000") == pytest.approx(0.0)
|
||||
assert c.relative_luminance("#ffffff") == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_stylesheet_builder_has_no_hardcoded_colours():
|
||||
"""Every colour in the QSS must come from the palette.
|
||||
|
||||
Three near-black literals used to be inlined here (#1a1205, #202229,
|
||||
#16181d). Harmless with one theme; with two, they silently render dark
|
||||
chrome on a light window. Reads the source rather than importing bcc,
|
||||
which needs PySide6.
|
||||
"""
|
||||
src = (Path(__file__).resolve().parent.parent / "bcc.py").read_text(encoding="utf-8")
|
||||
start = src.index("def build_stylesheet")
|
||||
body = src[start : src.index("def apply_palette")]
|
||||
assert re.findall(r"#[0-9a-fA-F]{6}", body) == []
|
||||
|
||||
|
||||
def test_every_palette_slot_is_consumed():
|
||||
"""A slot added to Palette but never wired up is dead weight.
|
||||
|
||||
Checks for `p.<slot>` anywhere in bcc.py, which covers both the QSS and
|
||||
apply_palette's global bindings -- not every slot belongs in the
|
||||
stylesheet (`good` and `remote` feed the inline status dots via
|
||||
STATUS_COLORS/HEALTH_COLORS, never the QSS). This won't catch a slot bound
|
||||
to a global that nothing then uses; it does catch the common mistake of
|
||||
extending the dataclass and forgetting to plumb it through.
|
||||
"""
|
||||
src = (Path(__file__).resolve().parent.parent / "bcc.py").read_text(encoding="utf-8")
|
||||
for f in dataclasses.fields(c.Palette):
|
||||
if f.name == "name":
|
||||
continue
|
||||
assert f"p.{f.name}" in src, f"palette slot {f.name!r} is never consumed"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# #78/#79 -- update notice: when to show it, and what it says
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_update_notice_when_a_newer_release_exists():
|
||||
n = c.update_notice("1.2.0", {"version": "v1.3.0", "url": "https://example.test/rel"})
|
||||
assert n is not None
|
||||
assert n["version"] == "v1.3.0"
|
||||
assert n["url"] == "https://example.test/rel"
|
||||
assert "1.3.0" in n["text"] and "1.2.0" in n["text"]
|
||||
|
||||
|
||||
def test_update_notice_is_silent_when_current():
|
||||
assert c.update_notice("1.3.0", {"version": "v1.3.0"}) is None
|
||||
assert c.update_notice("1.4.0", {"version": "v1.3.0"}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [None, {}, {"version": ""}, {"version": None}, {"version": 3}, []])
|
||||
def test_update_notice_is_silent_on_a_failed_or_malformed_check(bad):
|
||||
"""fetch_latest_release returns None on any failure; a half-formed payload
|
||||
must not produce a notice pointing at nothing."""
|
||||
assert c.update_notice("1.0.0", bad) is None
|
||||
|
||||
|
||||
def test_update_notice_falls_back_to_the_releases_page_without_a_url():
|
||||
n = c.update_notice("1.0.0", {"version": "v2.0.0"})
|
||||
assert n["url"] == c.RELEASES_URL
|
||||
|
||||
|
||||
def test_update_notice_names_no_menu_path():
|
||||
"""The old status-line text said 'Help > About to view it', which is wrong
|
||||
on macOS -- Qt moves the About action into the application menu (#79). The
|
||||
notice carries its own action, so it must not describe a menu path."""
|
||||
n = c.update_notice("1.0.0", {"version": "v2.0.0"})
|
||||
lowered = n["text"].lower()
|
||||
for phrase in ("help", "about", "menu", "▸", ">"):
|
||||
assert phrase not in lowered, f"notice text should not reference {phrase!r}"
|
||||
|
||||
|
||||
def test_update_notice_handles_the_v_prefix_consistently():
|
||||
assert c.update_notice("1.2.0", {"version": "1.3.0"}) is not None
|
||||
assert c.update_notice("v1.2.0", {"version": "v1.3.0"}) is not None
|
||||
assert c.update_notice("1.3.0", {"version": "v1.3.0"}) is None
|
||||
|
||||
|
||||
def test_update_notice_renders_both_versions_the_same_way():
|
||||
"""Tags carry a 'v' prefix, __version__ doesn't -- don't show both forms
|
||||
in one sentence."""
|
||||
n = c.update_notice("1.2.0", {"version": "v1.3.0"})
|
||||
assert "v1.3.0" not in n["text"]
|
||||
assert "1.3.0" in n["text"] and "1.2.0" in n["text"]
|
||||
# the machine-readable field keeps the real tag
|
||||
assert n["version"] == "v1.3.0"
|
||||
|
||||
Reference in New Issue
Block a user