Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /microsoft_agent-governance-toolkit /scripts /check_dependency_confusion.py
| #!/usr/bin/env python3 | |
| # Copyright (c) Microsoft Corporation. | |
| # Licensed under the MIT License. | |
| """Pre-commit hook: detect unregistered PyPI package names in pip install commands. | |
| Scans staged files for `pip install <name>` where <name> is not a known | |
| registered package. Prevents dependency confusion attacks. | |
| Usage: | |
| # Install as pre-commit hook | |
| cp scripts/check_dependency_confusion.py .git/hooks/pre-commit | |
| chmod +x .git/hooks/pre-commit | |
| # Or run manually | |
| python scripts/check_dependency_confusion.py [files...] | |
| """ | |
| import argparse | |
| import glob | |
| import json | |
| import re | |
| import subprocess | |
| import sys | |
| from typing import Any | |
| try: | |
| import tomllib | |
| except ModuleNotFoundError: # pragma: no cover - Python <3.11 fallback | |
| try: | |
| import tomli as tomllib | |
| except ModuleNotFoundError: # pragma: no cover - tomllib unavailable | |
| tomllib = None # type: ignore[assignment] | |
| # Known registered PyPI package names for this project | |
| REGISTERED_PACKAGES = { | |
| # Consolidated packages (v4.0.0+) | |
| "agent-governance-toolkit-core", "agent_governance_toolkit_core", | |
| "agent-governance-toolkit-integrations", "agent_governance_toolkit_integrations", | |
| "agent-governance-toolkit-cli", "agent_governance_toolkit_cli", | |
| "agent-governance-toolkit-protocols", "agent_governance_toolkit_protocols", | |
| # Core packages (on PyPI) — both hyphen and underscore variants | |
| "agent-os-kernel", "agent_os_kernel", | |
| "agentmesh-platform", "agentmesh_platform", | |
| "agent-hypervisor", "agent_hypervisor", | |
| "agentmesh-runtime", "agentmesh_runtime", | |
| "agent-sre", "agent_sre", | |
| "agent-governance-toolkit", "agent_governance_toolkit", | |
| "agent-governance-toolkit-core", "agent_governance_toolkit_core", | |
| "agent-governance-toolkit-cli", "agent_governance_toolkit_cli", | |
| "agent-governance-toolkit-integrations", "agent_governance_toolkit_integrations", | |
| "agent-governance-toolkit-protocols", "agent_governance_toolkit_protocols", | |
| # First-party agent-os module packages from the package rename (#2779/#2935). | |
| # Referenced as cross-module deps in agent-os/modules/*/pyproject.toml. | |
| # MUST be reserved/published on PyPI to prevent dependency-confusion takeover. | |
| "agent-governance-toolkit-tool-registry", "agent_governance_toolkit_tool_registry", | |
| "agent-governance-toolkit-trust-protocol", "agent_governance_toolkit_trust_protocol", | |
| "agent-governance-toolkit-control-plane", "agent_governance_toolkit_control_plane", | |
| "agent-governance-toolkit-drift", "agent_governance_toolkit_drift", | |
| "agentmesh-lightning", "agentmesh_lightning", | |
| "agentmesh-marketplace", "agentmesh_marketplace", | |
| "agent-discovery", "agent_discovery", | |
| "agentmesh-discovery", "agentmesh_discovery", | |
| "agt-sandbox", "agt_sandbox", | |
| "agt-policies", "agt_policies", | |
| "agent-control-specification", "agent_control_specification", | |
| "acs-generator", "acs_generator", | |
| # Common dependencies | |
| "pydantic", "pyyaml", "cryptography", "pynacl", "httpx", "aiohttp", | |
| "fastapi", "uvicorn", "requests", "packaging", "structlog", "click", "rich", "numpy", "scipy", | |
| "pytest", "pytest-asyncio", "pytest-cov", "ruff", "mypy", "build", | |
| "openai", "openai-agents", "anthropic", "langchain", "langchain-core", "crewai", | |
| "croniter", | |
| "redis", "sqlalchemy", "asyncpg", "chromadb", "pinecone-client", | |
| "sentence-transformers", "prometheus-client", "opentelemetry-api", | |
| "opentelemetry-sdk", "fhir.resources", "hl7apy", "zenpy", "freshdesk", | |
| "google-adk", "safety", "jupyter", "vitest", "tsup", "typescript", | |
| "requests", | |
| "twine", | |
| # PyJWT — required by agent-mesh/identity/entra_verifier.py for | |
| # Entra-signed JWT verification (PR #2659). Real package, on PyPI. | |
| "pyjwt", "PyJWT", | |
| # Dashboard / visualization (used in examples) | |
| "streamlit", "plotly", "pandas", "networkx", "matplotlib", "pyvis", | |
| # Async / caching (used in examples) | |
| "aioredis", "aiofiles", "aiosqlite", | |
| # Document processing / NLP (used in examples) | |
| "pypdf", "python-docx", "pdfplumber", "beautifulsoup4", "lxml", | |
| "spacy", "nltk", "tiktoken", "scikit-learn", | |
| # Dev tools | |
| "black", "flake8", "types-PyYAML", | |
| # Infrastructure / runtime (used in examples) | |
| "docker", "huggingface-hub", "python-dotenv", "python-dateutil", | |
| "python-multipart", "python-json-logger", "langchain-openai", | |
| # Slack / messaging | |
| "slack-sdk", "slack-bolt", | |
| # Telemetry / monitoring | |
| "sentry-sdk", | |
| "opentelemetry-instrumentation-fastapi", "opentelemetry-exporter-otlp", | |
| "opentelemetry-exporter-otlp-proto-grpc", "opentelemetry-exporter-otlp-proto-http", | |
| "opentelemetry-instrumentation-httpx", "opentelemetry-instrumentation-asyncio", | |
| # pyproject.toml optional-dependency group names (not real packages) | |
| "dev", "cli", "all", "server", "storage", "observability", | |
| "django", "websocket", "websockets", "grpc", "grpcio", "grpcio-tools", | |
| "agent-os", "test", "docs", "full", "api", "otel", "protocols", | |
| "runtime", "sandbox", "sre", "hypervisor", "iatp", "keywords", | |
| "llm", "mcp", "hf", "huggingface", "blockchain", "web3", | |
| "multi-agent", "broker-agnostic", "pubsub", "kafka", "rabbitmq", | |
| "sql", "async", "nexus", "caas-core", "message-bus", | |
| "ai-agents", "amb", "eval_type_backport", | |
| # Integration packages / real PyPI packages used as deps | |
| # Optional integration backend deps (all real PyPI packages): | |
| # flowise (Flowise SDK), boto3 (AWS, for AVP), nostr-sdk (Nostr WoT), oso (Oso authz). | |
| "flowise", "boto3", "nostr-sdk", "oso", | |
| # fastembed: Qdrant's embedding library, optional dep for the default-off | |
| # embedding evidence signal (agent-os embedding extra, PR #2974). | |
| "fastembed", | |
| "hypothesis", "fakeredis", "langflow", "langgraph", | |
| "agentmesh", "pydantic-ai", "haystack", "haystack-ai", "respx", | |
| "langfuse", "arize", "arize-phoenix", "llamaindex", "braintrust", "helicone", | |
| "datadog", "langsmith", "wandb", "mlflow", "agentops", | |
| "typer", "jsonschema", "anyio", "pre-commit", "import-linter", | |
| "mkdocs", "mkdocs-material", "mkdocs-minify-plugin", "mkdocstrings", "datasets", "sqlglot", | |
| "aio-pika", "aiokafka", | |
| # Cedar/OPA policy backends | |
| "cedarpy", "llama-index-core", "ddtrace", | |
| # Internal module references | |
| "inter-agent-trust-protocol", "agent-control-plane", "cmvk", | |
| "agentmesh-trust-protocol", "agentmesh_trust_protocol", | |
| "agentmesh-control-plane", "agentmesh_control_plane", | |
| "agentmesh-observability", "agentmesh_observability", | |
| "agent-tool-registry", "cedar", "opa", "huggingface_hub", | |
| "agentmesh-tool-registry", "agentmesh_tool_registry", | |
| # APS adapter optional deps | |
| "aps", "agent-passport-system", | |
| # Hyperlight micro-VM SDK (CNCF Sandbox project, on PyPI) | |
| "hyperlight-sandbox", "hyperlight_sandbox", "hyperlight", | |
| # Microsoft Agent Framework (MAF) — not yet on PyPI, used in examples | |
| "agent-framework", "agent_framework", | |
| "agent-framework-openai", "agent_framework_openai", | |
| # Azure Functions Python worker (used in foundry-ai-gateway-pdp example) | |
| "azure-functions", "azure_functions", | |
| # Azure SDK core libs (used by agent-sandbox ACASandboxProvider) | |
| "azure-identity", "azure_identity", | |
| "azure-core", "azure_core", | |
| # Azure AI Foundry Agents SDK (real PyPI package, used by the | |
| # examples/real_packages/foundry_agents.py integration reference) | |
| "azure-ai-agents", "azure_ai_agents", | |
| # SpendGuard SDK (real PyPI package, used in examples) | |
| "spendguard-sdk", "spendguard_sdk", | |
| # Cedarling Python bindings (real PyPI package, optional dep) | |
| "cedarling-python", "cedarling_python", | |
| # Cedarling-AgentMesh integration (internal cross-package, local-only) | |
| "cedarling-agentmesh", "cedarling_agentmesh", | |
| # Internal cross-package references (local-only, NOT on PyPI) | |
| # These are flagged as HIGH RISK if found in requirements.txt with version pins | |
| # instead of path references. See dependency confusion attack vector. | |
| "agent-primitives", "agent-mcp-governance", "agent_mcp_governance", "emk", | |
| "agentmesh-primitives", "agentmesh_primitives", | |
| # Vendored ACS policy-engine SDK/generator deps (all real PyPI packages) | |
| "litellm", "semantic-kernel", "semantic_kernel", | |
| "autogen-agentchat", "autogen_agentchat", | |
| "autogen-core", "autogen_core", "autogen-ext", "autogen_ext", | |
| "agentdojo", | |
| # IANA timezone database for Python (real PyPI package, optional dep for Windows tz support) | |
| "tzdata", | |
| # AGT Audit Trail Record library (real PyPI package, pre-1.0; used in acs-atr-annotator example) | |
| "pyatr", | |
| # agentrust-trace: TRACE v0.2 Trust Record library (real PyPI package; runtime dep for TRACE emission) | |
| "agentrust-trace", "agentrust_trace", | |
| # flowise-agentmesh: AGT governance nodes for Flowise (first-party package in this repo) | |
| "flowise-agentmesh", "flowise_agentmesh", | |
| # OS-native (Landlock / Seatbelt) capability sandbox (real PyPI package, Alpha; agt-sandbox[nono]) | |
| "nono-py", "nono_py", | |
| # With extras (base name is what matters) | |
| # ACS annotator example dependency (real PyPI package) | |
| "pyatr", "pyatr_core", | |
| # Timezone data package (real PyPI package, used on Windows/Alpine) | |
| "tzdata", | |
| } | |
| # Local-only packages that should NEVER appear with version pins in | |
| # requirements.txt (they must use path references like -e ../primitives) | |
| LOCAL_ONLY_PACKAGES = { | |
| "agent-primitives", | |
| "emk", | |
| } | |
| # Known npm packages for this project | |
| REGISTERED_NPM_PACKAGES = { | |
| "@microsoft/agent-os-kernel", "@microsoft/agentmesh-mcp-proxy", | |
| "@microsoft/agentmesh-api", "@microsoft/agent-os-cursor", | |
| "@microsoft/agentmesh-mastra", "@microsoft/agentmesh-copilot-governance", | |
| "@microsoft/agent-governance-sdk", "@microsoft/agent-governance-copilot-cli", | |
| "@microsoft/agent-governance-claude-code", | |
| "@microsoft/agent-governance-opencode", | |
| "@microsoft/agent-governance-antigravity-cli", | |
| "@microsoft/agent-os-copilot-extension", "@microsoft/agentos-mcp-server", | |
| "@microsoft/agent-os-vscode", | |
| "agent-control-specification", | |
| "agent-control-specification-linux-x64-gnu", | |
| "agent-control-specification-linux-arm64-gnu", | |
| "agent-control-specification-darwin-x64", | |
| "agent-control-specification-darwin-arm64", | |
| "agent-control-specification-win32-x64-msvc", | |
| "agent-control-specification-opa-linux-x64", | |
| "agent-control-specification-opa-linux-arm64", | |
| "agent-control-specification-opa-darwin-x64", | |
| "agent-control-specification-opa-darwin-arm64", | |
| "agent-control-specification-opa-win32-x64", | |
| # Common deps | |
| "typescript", "tsup", "vitest", "express", "zod", "@mastra/core", | |
| "@modelcontextprotocol/sdk", "ws", "commander", "chalk", | |
| "@anthropic-ai/sdk", "@types/node", "@types/ws", "@types/express", | |
| # Common npm dev dependencies | |
| "eslint", "@typescript-eslint/parser", "@typescript-eslint/eslint-plugin", | |
| "ts-jest", "@types/jest", "jest", "rimraf", "prettier", | |
| "axios", "@types/vscode", "@vscode/vsce", "webpack", "webpack-cli", | |
| "ts-node", "nodemon", "concurrently", "dotenv", | |
| "esbuild", "@esbuild/linux-x64", "@esbuild/darwin-arm64", | |
| # npm deps from extensions/copilot | |
| "@octokit/webhooks", "path-to-regexp", "winston", | |
| # npm deps from extensions/chrome | |
| "react", "react-dom", "webextension-polyfill", | |
| "@types/chrome", "@types/react", "@types/react-dom", | |
| "copy-webpack-plugin", "css-loader", "eslint-plugin-react", | |
| "eslint-plugin-react-hooks", "html-webpack-plugin", "style-loader", | |
| "ts-loader", | |
| # npm deps from extensions/mcp-server | |
| "uuid", "yaml", "zod", "@types/uuid", "@vitest/coverage-v8", | |
| # npm deps from mcp-proxy | |
| "crypto-js", | |
| # npm deps from agent-governance-typescript | |
| "js-yaml", "@noble/ed25519", "@noble/ciphers", "@noble/curves", "@noble/hashes", | |
| # npm deps from agent-os-vscode | |
| "@types/glob", "@types/mocha", "@vscode/test-electron", | |
| "autoprefixer", "glob", "mocha", "postcss", "tailwindcss", | |
| # Vendored ACS policy-engine node SDK deps (all real npm packages) | |
| "@langchain/core", "langchain", "@openai/agents", | |
| "@napi-rs/cli", | |
| } | |
| # Known Cargo crate names | |
| REGISTERED_CARGO_PACKAGES = { | |
| "serde", "serde_json", "serde_yaml", "sha2", "ed25519-dalek", | |
| "rand", "thiserror", "tempfile", "agentmesh", | |
| "agentmesh-mcp", "base64", "cedar-policy", "clap", "hmac", | |
| "opentelemetry", "regex", "regorus", | |
| "assert_cmd", "predicates", | |
| # Vendored ACS policy-engine crate deps (all real crates.io crates) | |
| "url", "ureq", "jsonschema", "criterion", "tokio", "rmcp", | |
| "async-openai", "rig-core", "napi", "napi-derive", "napi-build", | |
| "pyo3", "pyo3-build-config", | |
| # Vendored ACS workspace crates (internal, path-referenced) | |
| "agent_control_specification", "agent_control_specification_core", | |
| } | |
| # Patterns that are always safe (not package names) | |
| SAFE_PATTERNS = { | |
| "-e", "--editable", "-r", "--requirement", "--upgrade", "--no-cache-dir", | |
| "--quiet", "--require-hashes", "--hash", ".", "..", "../..", | |
| "pip", "install", "%pip", | |
| # Dockerfile / shell tokens that appear alongside pip install | |
| "RUN", "run", "if", "then", "fi", "&&", "||", ";", | |
| } | |
| PIP_INSTALL_RE = re.compile( | |
| r'(?:%?pip)\s+install\s+(.+?)(?:\s*\\?\s*$|(?=\s*&&|\s*\||\s*;|\s*#))', | |
| re.MULTILINE, | |
| ) | |
| def extract_package_names(install_args: str) -> list[str]: | |
| """Extract package names from a pip install argument string.""" | |
| packages = [] | |
| tokens = install_args.split() | |
| skip_next = False | |
| for token in tokens: | |
| if skip_next: | |
| skip_next = False | |
| continue | |
| # Skip flags | |
| if token.startswith("-") or token in SAFE_PATTERNS: | |
| # -e/--editable and -r/--requirement take a path as the next argument. | |
| if token in ("-e", "--editable", "-r", "--requirement", "-c", "--constraint"): | |
| skip_next = True | |
| continue | |
| if token.startswith((".", "/", "\\", "http", "git+")) or "/" in token or "\\" in token: | |
| continue | |
| # Skip tokens that look like code, not package names | |
| if any(c in token for c in ('(', ')', '=', '"', "'", ":", "[", "]")): | |
| continue | |
| # Skip tokens that look like filenames or shell keywords | |
| if any(token.rstrip(";") == kw for kw in ("if", "then", "else", "fi", "do", "done")): | |
| continue | |
| if re.search(r'\.\w{1,4}$', token.rstrip(";")): | |
| continue | |
| # Strip extras: package[extra] -> package | |
| base = re.sub(r'\[.*\]', '', token) | |
| # Strip version specifiers: package>=1.0 -> package | |
| base = re.split(r'[><=!~]', base)[0] | |
| # Strip markdown/quote artifacts | |
| base = base.strip('`"\'(){}%') | |
| if base and base not in SAFE_PATTERNS: | |
| packages.append(base) | |
| return packages | |
| def check_file(filepath: str) -> list[str]: | |
| """Check a file for potentially unregistered pip install targets.""" | |
| findings = [] | |
| try: | |
| with open(filepath, encoding="utf-8", errors="ignore") as f: | |
| content = f.read() | |
| except (OSError, UnicodeDecodeError): | |
| return findings | |
| is_shell = filepath.endswith((".sh", ".bash")) | |
| for match in PIP_INSTALL_RE.finditer(content): | |
| line_num = content[:match.start()].count("\n") + 1 | |
| line_start = content.rfind("\n", 0, match.start()) + 1 | |
| before_pip = content[line_start:match.start()] | |
| if re.search(r'\bprint\s*\(', before_pip): | |
| continue | |
| # For shell scripts, filter out matches that are inside a comment | |
| # or an echo/printf invocation. Only the current shell command | |
| # segment (split on ;, &&, ||, |) is examined so that | |
| # `echo done; pip install foo` is still flagged. | |
| if is_shell: | |
| # Take the last command segment on this line. | |
| segment = re.split(r';|&&|\|\||(?<!\|)\|(?!\|)', before_pip)[-1] | |
| if "#" in segment: | |
| continue | |
| stripped = segment.lstrip() | |
| if re.match(r'(?:sudo\s+)?(?:echo|printf)\b', stripped): | |
| continue | |
| packages = extract_package_names(match.group(1)) | |
| for pkg in packages: | |
| if pkg.lower() not in {p.lower() for p in REGISTERED_PACKAGES}: | |
| findings.append( | |
| f" {filepath}:{line_num}: " | |
| f"'{pkg}' may not be registered on PyPI" | |
| ) | |
| return findings | |
| def check_requirements_file(filepath: str) -> list[str]: | |
| """Check a requirements*.txt file for unregistered package names.""" | |
| findings = [] | |
| try: | |
| with open(filepath, encoding="utf-8", errors="ignore") as f: | |
| lines = f.readlines() | |
| except (OSError, UnicodeDecodeError): | |
| return findings | |
| registered_lower = {p.lower() for p in REGISTERED_PACKAGES} | |
| for line_num, line in enumerate(lines, 1): | |
| line = line.strip() | |
| if not line or line.startswith("#") or line.startswith("-"): | |
| continue | |
| if line.startswith((".", "/", "\\", "http", "git+")): | |
| continue | |
| # Strip extras and version specifiers | |
| base = re.sub(r'\[.*\]', '', line) | |
| base = re.split(r'[><=!~;@\s]', base)[0].strip() | |
| if base and base.lower() not in registered_lower: | |
| findings.append( | |
| f" {filepath}:{line_num}: " | |
| f"'{base}' may not be registered on PyPI" | |
| ) | |
| return findings | |
| def check_notebook(filepath: str) -> list[str]: | |
| """Check a Jupyter notebook for pip install of unregistered packages.""" | |
| findings = [] | |
| try: | |
| with open(filepath, encoding="utf-8", errors="ignore") as f: | |
| nb = json.load(f) | |
| except (OSError, json.JSONDecodeError, UnicodeDecodeError): | |
| return findings | |
| registered_lower = {p.lower() for p in REGISTERED_PACKAGES} | |
| for cell in nb.get("cells", []): | |
| if cell.get("cell_type") != "code": | |
| continue | |
| for line in cell.get("source", []): | |
| if not line.strip().startswith("#"): | |
| for match in PIP_INSTALL_RE.finditer(line): | |
| packages = extract_package_names(match.group(1)) | |
| for pkg in packages: | |
| if pkg.lower() not in registered_lower: | |
| findings.append( | |
| f" {filepath}: " | |
| f"'{pkg}' may not be registered on PyPI" | |
| ) | |
| return findings | |
| def check_pyproject_toml(filepath: str) -> list[str]: | |
| """Check a pyproject.toml for unregistered package dependencies.""" | |
| findings = [] | |
| try: | |
| with open(filepath, encoding="utf-8", errors="ignore") as f: | |
| content = f.read() | |
| except (OSError, UnicodeDecodeError): | |
| return findings | |
| # Keep legacy behavior as a compatibility fallback for malformed TOML. | |
| def _legacy_scan() -> list[str]: | |
| legacy_findings = [] | |
| registered_lower = {p.lower() for p in REGISTERED_PACKAGES} | |
| dep_re = re.compile(r'^[\s"]*([a-zA-Z0-9_-]+)', re.MULTILINE) | |
| in_deps = False | |
| in_optional = False | |
| for line_num, line in enumerate(content.splitlines(), 1): | |
| stripped = line.strip() | |
| if stripped.startswith("[project.dependencies]"): | |
| in_deps = True | |
| in_optional = False | |
| continue | |
| if stripped.startswith("[project.optional-dependencies"): | |
| in_deps = True | |
| in_optional = True | |
| continue | |
| if stripped.startswith("[") and in_deps: | |
| in_deps = False | |
| in_optional = False | |
| continue | |
| if not in_deps: | |
| continue | |
| if not stripped or stripped.startswith("#"): | |
| continue | |
| if in_optional and re.match(r'^[a-zA-Z0-9_-]+\s*=\s*\[', stripped): | |
| bracket_content = stripped.split("[", 1)[1].rstrip("]").strip() | |
| for item in bracket_content.split(","): | |
| item = item.strip().strip('"').strip("'") | |
| if item: | |
| base = re.split(r'[><=!~;@\s]', item)[0].strip() | |
| if base and base.lower() not in registered_lower: | |
| legacy_findings.append( | |
| f" {filepath}:{line_num}: '{base}' may not be registered on PyPI" | |
| ) | |
| continue | |
| m = dep_re.match(stripped.strip('"').strip("'").strip(",")) | |
| if m: | |
| pkg = m.group(1) | |
| if pkg.lower() not in registered_lower and pkg.lower() not in { | |
| "python", "requires-python", | |
| }: | |
| severity = "HIGH RISK" if pkg.lower() in { | |
| p.lower() for p in LOCAL_ONLY_PACKAGES | |
| } else "" | |
| msg = f" {filepath}:{line_num}: '{pkg}' may not be registered on PyPI" | |
| if severity: | |
| msg += f" [{severity}: local-only package]" | |
| legacy_findings.append(msg) | |
| return legacy_findings | |
| def _extract_package_name(requirement: str) -> str: | |
| req = requirement.strip() | |
| if not req: | |
| return "" | |
| req = req.split(";", 1)[0].strip() | |
| req = req.split("@", 1)[0].strip() | |
| req = re.sub(r'\[.*?\]', '', req) | |
| m = re.match(r'^([A-Za-z0-9_.-]+)', req) | |
| return m.group(1) if m else "" | |
| def _safe_line_number_for_requirement(requirement: str) -> int: | |
| needle = requirement.strip().strip('"').strip("'") | |
| if not needle: | |
| return 1 | |
| for line_num, line in enumerate(content.splitlines(), 1): | |
| if needle in line: | |
| return line_num | |
| return 1 | |
| def _extract_pep621_dependency_entries(parsed: dict[str, Any]) -> tuple[list[tuple[str, int]], bool]: | |
| entries: list[tuple[str, int]] = [] | |
| project = parsed.get("project") | |
| if project is None: | |
| return entries, False | |
| if not isinstance(project, dict): | |
| return entries, True | |
| dependencies = project.get("dependencies", []) | |
| if dependencies is not None: | |
| if not isinstance(dependencies, list): | |
| return entries, True | |
| else: | |
| for item in dependencies: | |
| if not isinstance(item, str): | |
| return entries, True | |
| entries.append((item, _safe_line_number_for_requirement(item))) | |
| optional = project.get("optional-dependencies", {}) | |
| if optional is not None: | |
| if not isinstance(optional, dict): | |
| return entries, True | |
| else: | |
| for group, deps in optional.items(): | |
| if not isinstance(deps, list): | |
| return entries, True | |
| for item in deps: | |
| if not isinstance(item, str): | |
| return entries, True | |
| entries.append((item, _safe_line_number_for_requirement(item))) | |
| return entries, False | |
| if tomllib is None: | |
| return _legacy_scan() | |
| try: | |
| parsed = tomllib.loads(content) | |
| except Exception: | |
| return _legacy_scan() | |
| registered_lower = {p.lower() for p in REGISTERED_PACKAGES} | |
| entries, should_fallback = _extract_pep621_dependency_entries(parsed) | |
| if should_fallback: | |
| return _legacy_scan() | |
| for requirement, line_num in entries: | |
| pkg = _extract_package_name(requirement) | |
| if not pkg: | |
| continue | |
| if pkg.lower() not in registered_lower and pkg.lower() not in { | |
| "python", "requires-python", | |
| }: | |
| severity = "HIGH RISK" if pkg.lower() in { | |
| p.lower() for p in LOCAL_ONLY_PACKAGES | |
| } else "" | |
| msg = f" {filepath}:{line_num}: '{pkg}' may not be registered on PyPI" | |
| if severity: | |
| msg += f" [{severity}: local-only package]" | |
| findings.append(msg) | |
| return findings | |
| def check_package_json(filepath: str) -> list[str]: | |
| """Check a package.json for unregistered npm package dependencies.""" | |
| findings = [] | |
| try: | |
| with open(filepath, encoding="utf-8", errors="ignore") as f: | |
| data = json.load(f) | |
| except (OSError, json.JSONDecodeError, UnicodeDecodeError): | |
| return findings | |
| registered_lower = {p.lower() for p in REGISTERED_NPM_PACKAGES} | |
| for section in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"): | |
| for pkg in data.get(section, {}): | |
| if pkg.lower() not in registered_lower: | |
| findings.append( | |
| f" {filepath}: npm '{pkg}' ({section}) may not be registered" | |
| ) | |
| return findings | |
| def check_cargo_toml(filepath: str) -> list[str]: | |
| """Check a Cargo.toml for unregistered crate dependencies.""" | |
| findings = [] | |
| try: | |
| with open(filepath, encoding="utf-8", errors="ignore") as f: | |
| content = f.read() | |
| except (OSError, UnicodeDecodeError): | |
| return findings | |
| registered_lower = {p.lower() for p in REGISTERED_CARGO_PACKAGES} | |
| in_deps = False | |
| for line_num, line in enumerate(content.splitlines(), 1): | |
| stripped = line.strip() | |
| if stripped in ("[dependencies]", "[dev-dependencies]", | |
| "[build-dependencies]"): | |
| in_deps = True | |
| continue | |
| if stripped.startswith("[") and in_deps: | |
| in_deps = False | |
| continue | |
| if not in_deps or not stripped or stripped.startswith("#"): | |
| continue | |
| m = re.match(r'^([a-zA-Z0-9_-]+)\s*=', stripped) | |
| if m: | |
| crate = m.group(1) | |
| if crate.lower() not in registered_lower: | |
| findings.append( | |
| f" {filepath}:{line_num}: crate '{crate}' " | |
| f"may not be registered on crates.io" | |
| ) | |
| return findings | |
| def main() -> int: | |
| parser = argparse.ArgumentParser( | |
| description="Detect unregistered PyPI package names in pip install commands.", | |
| ) | |
| parser.add_argument( | |
| "--strict", action="store_true", | |
| help="Also scan notebooks and requirements*.txt files; exit 1 on any violation", | |
| ) | |
| parser.add_argument("files", nargs="*", help="Files to check") | |
| args = parser.parse_args() | |
| # Get files to check | |
| if args.files: | |
| files = args.files | |
| else: | |
| # Pre-commit mode: check staged files | |
| result = subprocess.run( | |
| ["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"], | |
| capture_output=True, text=True, | |
| ) | |
| files = [ | |
| f for f in result.stdout.strip().split("\n") | |
| if f.endswith((".md", ".py", ".ts", ".txt", ".yaml", ".yml", ".ipynb", ".svg", ".sh", ".bash")) | |
| ] | |
| all_findings = [] | |
| for f in files: | |
| all_findings.extend(check_file(f)) | |
| # --strict: additionally scan all notebooks, requirements, and manifest files | |
| if args.strict: | |
| for nb in glob.glob("**/*.ipynb", recursive=True): | |
| if "node_modules" in nb or ".ipynb_checkpoints" in nb: | |
| continue | |
| all_findings.extend(check_notebook(nb)) | |
| for req in glob.glob("**/requirements*.txt", recursive=True): | |
| if "node_modules" in req: | |
| continue | |
| all_findings.extend(check_requirements_file(req)) | |
| for pyproj in glob.glob("**/pyproject.toml", recursive=True): | |
| if "node_modules" in pyproj: | |
| continue | |
| all_findings.extend(check_pyproject_toml(pyproj)) | |
| for pkgjson in glob.glob("**/package.json", recursive=True): | |
| if "node_modules" in pkgjson: | |
| continue | |
| all_findings.extend(check_package_json(pkgjson)) | |
| for cargo in glob.glob("**/Cargo.toml", recursive=True): | |
| if "node_modules" in cargo: | |
| continue | |
| all_findings.extend(check_cargo_toml(cargo)) | |
| if all_findings: | |
| print("⚠️ Potential dependency confusion detected:") | |
| print() | |
| for finding in all_findings: | |
| print(finding) | |
| print() | |
| print("If the package IS registered on PyPI, add it to REGISTERED_PACKAGES") | |
| print("in scripts/check_dependency_confusion.py") | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |
Xet Storage Details
- Size:
- 28.7 kB
- Xet hash:
- 36a951d16a338098b39df3e94149edbd892fc08c2143ffc71d8e3486e86c291c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.