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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ python -m pip check
openshield --version
```

Before PyPI publication, install a wheel downloaded from the signed GitHub Release or built from the reviewed source. Verify its SHA-256 against the release manifest before installing it. A PR build is not a PyPI release.
Before PyPI publication, build a wheel from a reviewed checkout and install it locally. A PR build is not a PyPI release.

The CLI uses Azure's `DefaultAzureCredential` chain. For local use, `az login` is one supported option. In automation, use an appropriate workload identity or service principal. Grant the identity read access to the subscription and to the specific resource APIs needed by the rules. Some identity and DevOps rules need additional Microsoft Graph or Azure DevOps permissions; a subscription Reader role alone does not prove their coverage. The CLI first acquires an Azure Resource Manager token and checks that the subscription is readable. It does not modify Azure resources.

Expand Down Expand Up @@ -57,7 +57,7 @@ Failed rules: none
- `authentication_failed`: renew the credential used by `DefaultAzureCredential`. For an Azure CLI login, run `az login`, then verify ARM token acquisition with `az account get-access-token --resource https://management.azure.com/ --subscription <id> --query expiresOn -o tsv`. This displays only the expiry. Never paste the token into an issue or PR.
- `subscription_unavailable`: verify the subscription ID, selected tenant, and read access with `az account show --subscription <id>`. Subscription Reader access alone may not cover Graph or Azure DevOps rules.
- `incomplete`: inspect `failed_rule_ids` in the result. If a packaged rule is missing or fails to import, reinstall a verified wheel. If a rule cannot query an Azure API, check the identity's service-specific permissions. Do not interpret the remaining findings as complete coverage.
- Package not found on PyPI: the first signed release has not published yet, or publishing was skipped by the protected setup gate. Use a verified GitHub Release wheel when one exists. Installing the unrelated `openshield` distribution will not provide this CLI.
- Package not found on PyPI: the first signed release has not published yet, or publishing was skipped by the protected setup gate. Build a wheel from a reviewed checkout. Installing the unrelated `openshield` distribution will not provide this CLI.

**Coverage limit:** Most legacy rules have not yet migrated to per-resource `evaluate()` results. Their `UNKNOWN` evaluation placeholders mean that a zero-finding completed scan is not proof that every resource was inspected or compliant. See the [evaluation contract](../scanner/evaluation.py) and [rule migration epic](https://github.com/OWASP/openshield/issues/380). Some Azure SDK helpers handle service failures internally; the CLI's subscription preflight cannot prove that every downstream API call succeeded. Review `evaluations` and rule logs before making assurance claims.

Expand All @@ -75,15 +75,14 @@ Failed rules: none
flowchart LR
Tag[Signed release tag] --> Build[Build wheel and sdist]
Build --> Verify[Fresh installs on Linux, macOS, Windows]
Verify --> GitHub[GitHub Release, checksums and attestations]
GitHub --> PyPI[PyPI publication - follow-up once publisher is registered]
Verify --> PyPI[Future PyPI publication]
PyPI --> Consumer[pip install owasp-openshield]
Consumer --> CLI[openshield scan]
CLI --> Azure[Azure Resource Manager and rule APIs]
```

The package contains `openshield`, the standalone `scanner` modules and all `scanner.rules` modules, `contracts/severity.v1.json`, and referenced `playbooks/cli` scripts. It excludes the API, worker entry points, database, frontend, website, tests, and deployment files. `scanner/engine.py` imports scanner metrics from `openshield.metrics`; `api.observability` re-exports the same collectors for the hosted services.

The release job verifies that the signed tag points to `main`, builds and installs both Python artifacts, and adds their hashes and provenance attestations to the existing GitHub Release. PyPI publishing is not yet wired up in `release.yml`; it will be added in a follow-up once the pending publisher is registered on PyPI. Recheck name availability immediately before tagging. Pending publisher registration does not reserve a name.
Package CI builds and installs both Python artifacts. The signed release workflow publishes a source archive and SBOM with checksums and provenance attestations. PyPI publishing is not yet wired up in `release.yml`; it will be added in a follow-up once the pending publisher is registered on PyPI. Recheck name availability immediately before tagging. Pending publisher registration does not reserve a name.

Release evidence must be reported separately: local tests, clean artifact installs, three-platform CI, human review, signed tag, GitHub Release assets, PyPI publication, and an installation from the public PyPI index. None implies the next gate occurred.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Issues = "https://github.com/OWASP/openshield/issues"
include-package-data = false

[tool.setuptools.packages.find]
include = ["openshield*", "scanner*", "playbooks*", "contracts*"]
include = ["openshield", "openshield.*", "scanner*", "playbooks*", "contracts*"]
exclude = ["api*", "tests*", "website*", "frontend*"]

[tool.setuptools.package-data]
Expand Down
13 changes: 12 additions & 1 deletion scanner/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ class ScanEngine:
only; its findings come from its FAIL evaluations.
"""

rule_load_failures: tuple[str, ...] = ()

def __init__(self, subscription_id: str) -> None:
self.subscription_id = subscription_id
self.client = AzureClient(subscription_id)
Expand All @@ -82,7 +84,10 @@ def load_rules(self) -> None:
# Keep runtime discovery identical to CI validation and documentation
# counts. A misnamed scratch module must never execute against a real
# subscription without first passing the rule checks.
manifest = RULES_DIR / "manifest.txt"
unavailable = set(manifest.read_text(encoding="utf-8").split()) if manifest.is_file() else set()
for rule_path in sorted(RULES_DIR.glob("az_*.py")):
unavailable.add(rule_path.stem)
try:
spec = importlib.util.spec_from_file_location(rule_path.stem, rule_path)
module = importlib.util.module_from_spec(spec) # type: ignore[arg-type]
Expand All @@ -93,6 +98,7 @@ def load_rules(self) -> None:
if normalize_severity(declared_severity) != declared_severity:
raise SeverityContractError(f"rule {rule_id} must declare a canonical severity")
self.rules.append(module)
unavailable.discard(rule_path.stem)
logger.info("Loaded rule: %s", rule_id)
else:
logger.warning("Rule file %s has no scan() function or RULE_ID — skipped", rule_path.name)
Expand All @@ -103,6 +109,7 @@ def load_rules(self) -> None:
raise
except Exception as exc:
logger.error("Failed to load rule %s: %s", rule_path.name, exc)
self.rule_load_failures = tuple(name.upper().replace("_", "-") for name in sorted(unavailable))

# ------------------------------------------------------------------ #
# Scan execution #
Expand Down Expand Up @@ -149,7 +156,11 @@ def run_scan(self, scan_id: Optional[str] = None) -> Dict[str, Any]:
# is ERROR, the rule supplied no usable coverage and is failed. This
# also covers inventory-wide failures, while preserving valid results
# from other inventories/resources.
failed_rule_ids: List[str] = []
failed_rule_ids = list(self.rule_load_failures)
evaluations.extend(
self._evaluator_error(rule_id, "RULE_LOAD_FAILED", "Expected rule could not be loaded.")
for rule_id in self.rule_load_failures
)

for rule in self.rules:
rule_id = getattr(rule, "RULE_ID", "UNKNOWN")
Expand Down
16 changes: 16 additions & 0 deletions tests/test_engine_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ def test_engine_discovery_matches_ci_and_ignores_misnamed_modules(monkeypatch, t
assert [rule.RULE_ID for rule in eng.rules] == ["AZ-VALID-001"]


def test_engine_reports_missing_and_unloadable_packaged_rules(monkeypatch, tmp_path):
(tmp_path / "manifest.txt").write_text("az_load_001\naz_load_002\n", encoding="utf-8")
(tmp_path / "az_load_001.py").write_text('raise ImportError("rule dependency unavailable")\n', encoding="utf-8")
monkeypatch.setattr(engine_mod, "RULES_DIR", tmp_path)
_patch_engine_client(monkeypatch, _offline_mock())

result = ScanEngine(_SUB).run_scan()

assert result["failed_rule_ids"] == ["AZ-LOAD-001", "AZ-LOAD-002"]
assert result["findings"] == []
assert [(row["status"], row["reason_code"]) for row in result["evaluations"]] == [
("ERROR", "RULE_LOAD_FAILED"),
("ERROR", "RULE_LOAD_FAILED"),
]


@pytest.mark.parametrize("severity", ["INFORMATIONAL", "URGENT"])
def test_engine_rejects_noncanonical_rule_declarations(monkeypatch, tmp_path, severity):
(tmp_path / "az_invalid_001.py").write_text(
Expand Down
Loading