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
21 changes: 21 additions & 0 deletions .github/workflows/test_macaron_action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -316,13 +316,34 @@ jobs:
deps_depth: '1'
upload_reports: 'false'

- name: Assert the SBOM dependencies were analyzed
run: |
jq -e 'map(.purl) |
index("pkg:maven/io.github.behnazh-w.demo/jackson-databind@1.0?type=jar") != null and
index("pkg:maven/org.apache.logging.log4j/log4j-core@3.0.0-beta2?type=jar") != null' \
macaron_output/detect_malicious_java_dep/reports/maven/io_github_behnazh-w_demo/example-maven-app/dependencies.json

- name: Run Macaron (verify policy - detect-malicious-upload)
id: verify_detect_malicious_upload
# Missing publishing-pipeline evidence is expected for this tutorial's dependencies.
continue-on-error: true
uses: ./
with:
policy_file: ./tests/tutorial_resources/detect_malicious_java_dep/example-maven-app.dl
output_dir: macaron_output/detect_malicious_java_dep
upload_reports: 'false'

- name: Assert expected policy failure for the Java dependency example
run: |
if [ "${{ steps.verify_detect_malicious_upload.outcome }}" != "failure" ]; then
echo "Expected the dependency policy to reject missing publishing-pipeline evidence."
exit 1
fi
jq -e '.failed_policies == [["detect-malicious-upload"]] and
(.component_violates_policy | length > 0)' \
macaron_output/detect_malicious_java_dep/policy_report.json
test ! -e macaron_output/detect_malicious_java_dep/vsa.intoto.jsonl

tutorial-exclude-include-checks:
name: Exclude and include checks in Macaron
runs-on: ubuntu-24.04
Expand Down
10 changes: 9 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,13 @@ requirements.txt: pyproject.toml
# files or untrusted request metadata.
# Temporarily ignore these advisories until Semgrep allows mcp >=1.30.0 and
# opentelemetry-api >=1.45.2. Reassess these exceptions if Macaron's usage changes.
#
# wcmatch GHSA-53pm-wgxf-c6qf (CVE-2026-132276) is fixed in >=11.2, but
# Semgrep 1.185.0 and the latest checked release, 1.186.0 (2026-11-23), require
# wcmatch ~=8.3. Temporarily ignore until Semgrep supports the patched version.
# This remains a denial-of-service risk when matching crafted file names against
# multi-star patterns during scans; this exception does not remediate the issue.
# Advisory: https://github.com/advisories/GHSA-53pm-wgxf-c6qf

.PHONY: audit
audit:
Expand All @@ -321,7 +328,8 @@ audit:
--ignore-vuln GHSA-84m7-p3x7-pcfv --ignore-vuln GHSA-5h93-6whr-6q8j \
--ignore-vuln GHSA-w4fh-qvv9-3v23 --ignore-vuln GHSA-rwrf-2pqf-9j8j \
--ignore-vuln GHSA-qx49-fqc8-xw99 \
--ignore-vuln GHSA-xcq7-p3pf-p88h --ignore-vuln GHSA-mf5v-w3w3-f6cg
--ignore-vuln GHSA-xcq7-p3pf-p88h --ignore-vuln GHSA-mf5v-w3w3-f6cg \
--ignore-vuln GHSA-53pm-wgxf-c6qf

# Run some or all checks over the package code base.
.PHONY: check check-code check-ruff check-lint check-mypy check-go check-actionlint
Expand Down
12 changes: 10 additions & 2 deletions docs/source/pages/tutorials/detect_malicious_java_dep.rst
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,19 @@ As you scroll down in the HTML report, you will see a section for the dependenci
* ``io.github.behnazh-w.demo:jackson-databind:1.0``
* ``org.apache.logging.log4j:log4j-core:2.25.3``

When we open the reports for each dependency, we see that ``mcn_find_artifact_pipeline_1`` is passed for ``org.apache.logging.log4j:log4j-core:2.25.3``
and a GitHub Actions workflow run is found for publishing version ``2.25.3``. However, this check is failing for ``io.github.behnazh-w.demo:jackson-databind:1.0``.
In the reports captured below, ``mcn_find_artifact_pipeline_1`` passed for ``org.apache.logging.log4j:log4j-core:2.25.3``
because a GitHub Actions workflow run was found for publishing version ``2.25.3``. The check failed for ``io.github.behnazh-w.demo:jackson-databind:1.0``.
This means that ``io.github.behnazh-w.demo:jackson-databind:1.0`` could have been built and published manually to Maven Central
and could potentially be malicious.

.. note::

As of November 23, 2026, GitHub no longer returns workflow runs for the Log4j
release commit or its publication window. The pipeline check now fails for
Log4j as well, so both dependencies violate the policy below. Missing historical
workflow data does not by itself establish that an artifact was published
manually or is malicious. The screenshots show the earlier results.

.. _fig_find_artifact_pipeline_log4j:

.. figure:: ../../_static/images/tutorial_log4j_find_pipeline.png
Expand Down
3 changes: 2 additions & 1 deletion scripts/actions/run_macaron_analysis.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ CMD+=(--output "$OUTPUT_DIR" -lr . analyze)

if [ -n "${REPO_PATH:-}" ]; then
CMD+=(-rp "$REPO_PATH")
elif [ -n "${PACKAGE_URL:-}" ]; then
fi
if [ -n "${PACKAGE_URL:-}" ]; then
CMD+=(-purl "$PACKAGE_URL")
fi

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ Policy("test_policy", component_id, "") :-
check_passed(component_id, "mcn_build_as_code_1"),
check_passed(component_id, "mcn_build_script_1"),
check_passed(component_id, "mcn_build_service_1"),
check_passed_with_confidence(component_id, "mcn_find_artifact_pipeline_1", confidence),
confidence = 0.7, // Medium confidence because the pipeline was not found from a provenance.
// GitHub no longer returns workflow runs for this release commit or its
// publication window (checked 2026-11-23). A publishing pipeline cannot be verified.
check_failed(component_id, "mcn_find_artifact_pipeline_1"),
check_passed(component_id, "mcn_version_control_system_1"),
// This revision calls remote reusable workflows through mutable refs.
check_failed(component_id, "mcn_githubactions_vulnerabilities_1"),
Expand Down
20 changes: 12 additions & 8 deletions tests/policy_engine/test_github_actions_lockfile_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from sqlalchemy.orm import Session

from macaron.database.database_manager import DatabaseManager
from macaron.database.table_definitions import CheckFacts, MappedCheckResult, RepoFinderMetadata
from macaron.database.table_definitions import MappedCheckResult, RepoFinderMetadata
from macaron.policy_engine.policy_engine import run_souffle
from macaron.repo_finder.repo_finder_enums import CommitFinderInfo, RepoFinderInfo
from macaron.slsa_analyzer.checks.check_result import CheckResultType, Confidence
Expand Down Expand Up @@ -122,7 +122,10 @@ def test_lockfile_policy_database_and_summary(

@pytest.mark.parametrize("case", ["log4j_purl", "log4j_repo", "coherence"])
@pytest.mark.parametrize("include_finding", [True, False])
def test_integration_github_actions_policies(tmp_path: Path, case: str, include_finding: bool) -> None:
@pytest.mark.parametrize("pipeline_passed", [False, True])
def test_integration_github_actions_policies(
tmp_path: Path, case: str, include_finding: bool, pipeline_passed: bool
) -> None:
"""Integration policies require the intended finding and compile against the current schema."""
coherence = case == "coherence"
purl = (
Expand Down Expand Up @@ -152,7 +155,7 @@ def test_integration_github_actions_policies(tmp_path: Path, case: str, include_
"mcn_build_as_code_1": True,
"mcn_build_script_1": True,
"mcn_build_service_1": True,
"mcn_find_artifact_pipeline_1": True,
"mcn_find_artifact_pipeline_1": pipeline_passed,
"mcn_version_control_system_1": True,
"mcn_provenance_available_1": False,
"mcn_provenance_derived_commit_1": False,
Expand All @@ -161,9 +164,7 @@ def test_integration_github_actions_policies(tmp_path: Path, case: str, include_
"mcn_provenance_witness_level_one_1": False,
"mcn_trusted_builder_level_three_1": False,
}.items():
result = MappedCheckResult(check_id=check_id, passed=passed, component=ctx.component)
if check_id == "mcn_find_artifact_pipeline_1":
CheckFacts(checkresult=result, component=ctx.component, confidence=0.7)
MappedCheckResult(check_id=check_id, passed=passed, component=ctx.component)
if include_finding:
GitHubActionsVulnsFacts(
# Finding identifiers must not accidentally equal the component identifier.
Expand Down Expand Up @@ -201,7 +202,10 @@ def test_integration_github_actions_policies(tmp_path: Path, case: str, include_
filename = "policy.dl" if coherence else "policy_purl.dl" if case == "log4j_purl" else "policy_repo_url.dl"
policy_path = Path(__file__).resolve().parents[1] / "integration/cases" / directory / filename
output = run_souffle(str(tmp_path / "macaron.db"), policy_path.read_text(encoding="utf-8"))
assert bool(output["passed_policies"]) is include_finding
assert bool(output["failed_policies"]) is not include_finding
# Only the Log4j PURL policy requires the pipeline check to fail because
# GitHub no longer returns the release's historical workflow runs.
expected_pass = include_finding and (case != "log4j_purl" or not pipeline_passed)
assert bool(output["passed_policies"]) is expected_pass
assert bool(output["failed_policies"]) is not expected_pass
finally:
manager.engine.dispose()
113 changes: 110 additions & 3 deletions tests/slsa_analyzer/checks/test_infer_artifact_pipeline.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
# Copyright (c) 2023 - 2024, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2023 - 2026, Oracle and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/.

"""This module contains tests for the Infer Artifact Pipeline check."""

from datetime import UTC, datetime
from pathlib import Path
from unittest.mock import Mock

import pytest

from macaron.code_analyzer.dataflow_analysis.core import NodeForest
from macaron.database.table_definitions import Repository
from macaron.slsa_analyzer.checks.check_result import CheckResultType
from macaron.slsa_analyzer.checks.infer_artifact_pipeline_check import ArtifactPipelineCheck
from macaron.slsa_analyzer.checks.check_result import CheckResultType, Confidence
from macaron.slsa_analyzer.checks.infer_artifact_pipeline_check import ArtifactPipelineCheck, ArtifactPipelineFacts
from macaron.slsa_analyzer.ci_service.github_actions.github_actions_ci import GitHubActions
from macaron.slsa_analyzer.package_registry.maven_central_registry import MavenCentralRegistry
from macaron.slsa_analyzer.provenance.intoto import InTotoV01Payload
from macaron.slsa_analyzer.specs.ci_spec import CIInfo
from macaron.slsa_analyzer.specs.inferred_provenance import InferredProvenance
from macaron.slsa_analyzer.specs.package_registry_spec import PackageRegistryInfo
from tests.conftest import MockAnalyzeContext

RESOURCE_PATH = Path(__file__).parent.joinpath("resources")
Expand All @@ -33,3 +42,101 @@ def test_artifact_pipeline_errors(macaron_path: Path, repository: Repository, ex
ctx = MockAnalyzeContext(macaron_path=macaron_path, output_dir="")
ctx.component.repository = repository
assert check.run_check(ctx).result_type == expected


@pytest.mark.parametrize(
("runs_available", "conclusion", "expected"),
[
(True, "success", CheckResultType.PASSED),
(False, "success", CheckResultType.FAILED),
(True, "failure", CheckResultType.FAILED),
],
ids=["successful-run", "missing-run", "failed-deploy"],
)
def test_artifact_pipeline_workflow_history(
macaron_path: Path,
monkeypatch: pytest.MonkeyPatch,
runs_available: bool,
conclusion: str,
expected: CheckResultType,
) -> None:
"""Infer a publishing pipeline only when fixed API responses contain a successful deploy."""
# Synthetic API fixtures preserve success coverage after live workflow history disappears.
# Freeze the retention clock so the missing-run case cannot age into UNKNOWN.
clock = Mock(wraps=datetime)
clock.now.return_value = datetime(2026, 11, 23, tzinfo=UTC)
monkeypatch.setattr("macaron.slsa_analyzer.ci_service.github_actions.github_actions_ci.datetime", clock)
monkeypatch.setattr(
MavenCentralRegistry,
"find_publish_timestamp",
lambda self, purl: datetime(2025, 12, 15, 13, tzinfo=UTC),
)
run_url = "https://github.com/apache/logging-log4j2/actions/runs/123"
responses = {
"https://api.github.com/repos/apache/logging-log4j2/actions/runs?"
"created=2025-12-15T11%3A00%3A00%2B00%3A00..2025-12-15T13%3A00%3A00%2B00%3A00": {
"total_count": int(runs_available),
"workflow_runs": [{"id": 123, "path": ".github/workflows/build.yaml", "html_url": run_url}]
if runs_available
else [],
},
"https://api.github.com/repos/apache/logging-log4j2/actions/runs/123/jobs": {
"total_count": 1,
"jobs": [
{
"name": "deploy / release",
"conclusion": conclusion,
"started_at": "2025-12-15T12:45:00Z",
"steps": [],
}
],
},
}
monkeypatch.setattr(
"macaron.slsa_analyzer.git_service.api_client.send_get_http", lambda url, headers: responses[url]
)
workflow = (
"https://github.com/apache/logging-log4j2/blob/"
"028e9fad03ae7bcbf2e49ab8d32d8cfb900f3587/.github/workflows/build.yaml"
)
provenance = InferredProvenance()
predicate = provenance.payload["predicate"]
assert predicate is not None
predicate["buildType"] = "Custom github_actions"
predicate["invocation"] = {"configSource": {"entryPoint": workflow}}
predicate["buildConfig"] = {"jobID": "deploy", "calleeType": "reusable"}
ctx = MockAnalyzeContext(
macaron_path=macaron_path, output_dir="", purl="pkg:maven/org.apache.logging.log4j/log4j-core@2.25.3"
)
ctx.component.repository = Repository(
complete_name="github.com/apache/logging-log4j2",
full_name="apache/logging-log4j2",
commit_date="2025-12-15T12:41:25+00:00",
)
ctx.dynamic_data["package_registries"] = [PackageRegistryInfo("maven", MavenCentralRegistry())]
ctx.dynamic_data["ci_services"] = [
CIInfo(
service=GitHubActions(),
callgraph=NodeForest([]),
provenance_assets=[],
release={},
provenances=[],
build_info_results=InTotoV01Payload(statement=provenance.payload),
)
]

result = ArtifactPipelineCheck().run_check(ctx)

assert result.result_type == expected
if expected == CheckResultType.FAILED:
assert not result.result_tables
return
assert len(result.result_tables) == 1
facts = result.result_tables[0]
assert isinstance(facts, ArtifactPipelineFacts)
assert facts.run_url == run_url
assert facts.deploy_workflow == workflow
assert facts.deploy_job == "deploy"
assert facts.confidence == Confidence.MEDIUM
assert not facts.from_provenance
assert not facts.run_deleted
66 changes: 66 additions & 0 deletions tests/test_action_scripts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Copyright (c) 2026 - 2026, Oracle and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/.

"""Test argument forwarding by the composite action's shell scripts."""

import os
import subprocess
from pathlib import Path

import pytest


@pytest.mark.parametrize(
("repo_path", "package_url", "target_args"),
[
("https://github.com/example/project", "", ["-rp", "https://github.com/example/project"]),
("", "pkg:maven/example/project@1.0", ["-purl", "pkg:maven/example/project@1.0"]),
(
"https://github.com/example/project",
"pkg:maven/example/project@1.0",
["-rp", "https://github.com/example/project", "-purl", "pkg:maven/example/project@1.0"],
),
],
ids=["repository", "package", "package-with-repository"],
)
def test_action_analysis_target_arguments(
tmp_path: Path, repo_path: str, package_url: str, target_args: list[str]
) -> None:
"""Preserve both the artifact identity and repository override for SBOM analysis."""
capture = tmp_path / "arguments"
macaron = tmp_path / "fake-macaron"
macaron.write_text('#!/usr/bin/env bash\nprintf \'%s\\0\' "$@" > "$CAPTURE_ARGS"\n', encoding="utf-8")
macaron.chmod(0o755)
script = Path(__file__).resolve().parents[1] / "scripts/actions/run_macaron_analysis.sh"

result = subprocess.run( # noqa: S603
["/bin/bash", str(script)],
cwd=tmp_path,
env={
"PATH": os.defpath,
"MACARON": str(macaron),
"CAPTURE_ARGS": str(capture),
"REPO_PATH": repo_path,
"PACKAGE_URL": package_url,
"OUTPUT_DIR": "analysis output",
"DEPS_DEPTH": "1",
"SBOM_PATH": "example sbom.json",
},
capture_output=True,
text=True,
check=False,
)

assert result.returncode == 0, result.stderr
assert capture.read_bytes().decode().split("\0")[:-1] == [
"--output",
"analysis output",
"-lr",
".",
"analyze",
*target_args,
"--deps-depth",
"1",
"--sbom-path",
"example sbom.json",
]
Loading