diff --git a/.github/workflows/codeql-extended-scan.yml b/.github/workflows/codeql-extended-scan.yml deleted file mode 100644 index 5708e02ee0e..00000000000 --- a/.github/workflows/codeql-extended-scan.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: Scan with CodeQL extended security - -on: - workflow_call: - inputs: - publish: - description: Upload SARIF to GitHub Security - type: boolean - required: true - -jobs: - analyze: - name: CodeQL extended (${{ matrix.language }}) - runs-on: ubuntu-24.04 - timeout-minutes: 45 - strategy: - fail-fast: false - matrix: - language: [python, javascript-typescript] - steps: - - name: Require normal logging for CodeQL - if: runner.debug == '1' - shell: bash - run: | - echo "Turn off step debugging so detailed analysis stays in GitHub Security." - exit 1 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 - with: - languages: ${{ matrix.language }} - build-mode: none - dependency-caching: false - queries: security-extended - config: | - paths: - - server/ - - sdk/typescript/src/ - - frontend/src/ - paths-ignore: - - "**/tests/**" - - "**/*.test.ts" - - "**/*.test.tsx" - - "**/*.test-d.ts" - - frontend/src/test/** - - id: scan - uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 - with: - category: /suite:security-extended/language:${{ matrix.language }} - upload: ${{ inputs.publish && 'always' || 'never' }} - upload-database: false - - name: Report findings by rule - shell: bash - env: - SARIF_DIR: ${{ steps.scan.outputs.sarif-output }} - run: | - test -d "$SARIF_DIR" - shopt -s nullglob - reports=("$SARIF_DIR"/*.sarif) - test "${#reports[@]}" -gt 0 - for report in "${reports[@]}"; do - jq -s -e ' - length == 1 and - (.[0].runs | type == "array" and length > 0 and all(.[]; - type == "object" and - ((has("results") | not) or (.results | type == "array" and - all(.[]; type == "object" and (.ruleId | type) == "string"))) - )) - ' "$report" >/dev/null - done - jq -s -r ' - [.[].runs[].results[]?] as $results - | "Findings: \($results | length)", "", - ($results | group_by(.ruleId)[] | "- \(.[0].ruleId): \(length)") - ' "${reports[@]}" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/codeql-extended.yml b/.github/workflows/codeql-extended.yml index fe69455779b..a24fb28adf1 100644 --- a/.github/workflows/codeql-extended.yml +++ b/.github/workflows/codeql-extended.yml @@ -5,7 +5,6 @@ on: branches: [main] paths: - .github/workflows/codeql-extended.yml - - .github/workflows/codeql-extended-scan.yml schedule: - cron: "37 4 * * 3" workflow_dispatch: @@ -19,20 +18,85 @@ concurrency: jobs: scan_pr: - name: Scan the pull request + name: Scan the pull request (${{ matrix.language }}) if: github.event_name == 'pull_request' permissions: contents: read - uses: ./.github/workflows/codeql-extended-scan.yml - with: - publish: false + env: + CODEQL_UPLOAD_MODE: never + runs-on: ubuntu-24.04 + timeout-minutes: 45 + strategy: &scan_strategy + fail-fast: false + matrix: + language: [python, javascript-typescript] + steps: &scan_steps + - name: Require normal logging for CodeQL + if: runner.debug == '1' + shell: bash + run: | + echo "Turn off step debugging so detailed analysis stays in GitHub Security." + exit 1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + languages: ${{ matrix.language }} + build-mode: none + dependency-caching: false + queries: security-extended + config: | + paths: + - server/ + - sdk/typescript/src/ + - frontend/src/ + paths-ignore: + - "**/tests/**" + - "**/*.test.ts" + - "**/*.test.tsx" + - "**/*.test-d.ts" + - frontend/src/test/** + - id: scan + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + category: /suite:security-extended/language:${{ matrix.language }} + upload: ${{ env.CODEQL_UPLOAD_MODE }} + upload-database: false + - name: Report findings by rule + shell: bash + env: + SARIF_DIR: ${{ steps.scan.outputs.sarif-output }} + run: | + test -d "$SARIF_DIR" + shopt -s nullglob + reports=("$SARIF_DIR"/*.sarif) + test "${#reports[@]}" -gt 0 + for report in "${reports[@]}"; do + jq -s -e ' + length == 1 and + (.[0].runs | type == "array" and length > 0 and all(.[]; + type == "object" and + ((has("results") | not) or (.results | type == "array" and + all(.[]; type == "object" and (.ruleId | type) == "string"))) + )) + ' "$report" >/dev/null + done + jq -s -r ' + [.[].runs[].results[]?] as $results + | "Findings: \($results | length)", "", + ($results | group_by(.ruleId)[] | "- \(.[0].ruleId): \(length)") + ' "${reports[@]}" >> "$GITHUB_STEP_SUMMARY" publish: - name: Publish default-branch findings + name: Publish default-branch findings (${{ matrix.language }}) if: github.repository == 'ClickHouse/loom' && github.ref == 'refs/heads/main' && github.event_name != 'pull_request' permissions: contents: read security-events: write # Upload default-branch SARIF to GitHub Security. - uses: ./.github/workflows/codeql-extended-scan.yml - with: - publish: true + env: + CODEQL_UPLOAD_MODE: always + runs-on: ubuntu-24.04 + timeout-minutes: 45 + strategy: *scan_strategy + steps: *scan_steps diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 43eab9d3836..3bb5868a892 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -41,7 +41,23 @@ jobs: MAX_CHANGES = 1000 MAX_BYTES = 1024 * 1024 MAX_FINDINGS = 20 + # The Compare API returns at most 300 files, even with commit pagination. + COMPARE_FILE_LIMIT = 300 + MAX_COMPARE_BYTES = 8 * 1024 * 1024 SEVERITIES = {"low", "moderate", "high", "critical"} + SNAPSHOT_WORKFLOWS = { + ".github/workflows/maven-dependency-graph.yml", + ".github/workflows/rust-dependency-graph.yml", + } + EXPRESSION = "$" + "{{ " + PR_EVENT = "github.event_name == 'pull_request'" + CONCURRENCY_LINES = [ + "+concurrency:", + "+ group: " + EXPRESSION + "github.workflow }}-" + EXPRESSION + + PR_EVENT + " && github.ref || github.sha }}", + "+ cancel-in-progress: " + EXPRESSION + PR_EVENT + " }}", + "+", + ] class ReviewError(ValueError): @@ -53,17 +69,20 @@ jobs: return None - def snapshot_complete(value): + def missing_head_snapshot(value, head): if not value: - return + return False + if len(value) > 8192: + raise ReviewError("Snapshot warning header exceeds its limit") try: - if len(value) > 8192: - raise ReviewError("Snapshot warning header exceeds its limit") - warnings = json.loads(base64.b64decode(value, validate=True)) - except (ValueError, binascii.Error) as error: + warning = base64.b64decode(value, validate=True) + except binascii.Error as error: raise ReviewError("Invalid dependency snapshot warning header") from error - if warnings != []: - raise ReviewError("Dependency snapshots are incomplete") + if warning == b"[]": + return False + if warning == f"No snapshots were found for the head SHA {head}.".encode(): + return True + raise ReviewError("Dependency snapshots are incomplete") def next_page(value, endpoint, canonical_endpoint, page): @@ -87,7 +106,7 @@ jobs: return True - def read_page(opener, url, token): + def read_response(opener, url, token, max_bytes=MAX_BYTES): request = urllib.request.Request( url, headers={ @@ -100,21 +119,72 @@ jobs: with opener.open(request, timeout=20) as response: if response.status != 200: raise ReviewError("Dependency review API did not return HTTP 200") - snapshot_complete( - response.headers.get("x-github-dependency-graph-snapshot-warnings", "") - ) - body = response.read(MAX_BYTES + 1) - link = response.headers.get("Link", "") + body = response.read(max_bytes + 1) + headers = response.headers except urllib.error.HTTPError as error: raise ReviewError(f"Dependency review API returned HTTP {error.code}") from error except (urllib.error.URLError, TimeoutError, http.client.HTTPException) as error: raise ReviewError("Dependency review API request failed") from error - if len(body) > MAX_BYTES: + if len(body) > max_bytes: raise ReviewError("Dependency review response exceeds its limit") - changes = json.loads(body) + return json.loads(body), headers + + + def read_page(opener, url, token, head): + changes, headers = read_response(opener, url, token) if not isinstance(changes, list): raise ReviewError("Invalid dependency review response") - return changes, link + missing = missing_head_snapshot( + headers.get("x-github-dependency-graph-snapshot-warnings", ""), head + ) + return changes, headers.get("Link", ""), missing + + + def scheduler_only(file): + if file["status"] != "modified" or file.get("deletions") != 0: + return False + patch = file.get("patch") + if not isinstance(patch, str) or file.get("additions") != len(CONCURRENCY_LINES): + return False + added = [line for line in patch.splitlines() if line.startswith("+")] + return added == CONCURRENCY_LINES and "\n".join(added + [" permissions:"]) in patch + + + def affects_snapshot(path, file): + parts = path.split("/") + if path in SNAPSHOT_WORKFLOWS: + return not scheduler_only(file) + if ".cargo" in parts or ".mvn" in parts or parts[-1] in {"Cargo.toml", "Cargo.lock", "pom.xml"}: + return True + if path.startswith("sdk/java/"): + # Maven resolves these graphs from the POMs and build configuration. + return not ("src" in parts and path.endswith(".java")) + # Python loads the Rust workflow's modules from the checkout root as well. + module = parts[0].partition(".")[0] + if module in sys.stdlib_module_names or module in {"sitecustomize", "usercustomize"}: + return True + # Rust runs the converter and its tests before publishing the resolved graph. + return path.startswith(("sdk/rust/", ".github/scripts/")) + + + def check_snapshot_inputs(repository_url, base, head, token, opener): + data, _ = read_response( + opener, f"{repository_url}/compare/{base}...{head}?per_page=1", token, MAX_COMPARE_BYTES + ) + if not isinstance(data, dict) or not isinstance(data.get("files"), list): + raise ReviewError("Cannot verify the dependency snapshot inputs") + if len(data["files"]) >= COMPARE_FILE_LIMIT: + raise ReviewError("Too many changed files to verify the dependency snapshot inputs") + merge_base = data["merge_base_commit"]["sha"] + if not isinstance(merge_base, str) or not re.fullmatch(r"[0-9a-f]{40}", merge_base): + raise ReviewError("Invalid merge base for dependency snapshot comparison") + for file in data["files"]: + paths = [file["filename"]] + if file["status"] == "renamed": + paths.append(file["previous_filename"]) + if any(affects_snapshot(path, file) for path in paths): + raise ReviewError("Dependency snapshots are incomplete and snapshot inputs changed") + return merge_base def blocked_changes(change): @@ -154,11 +224,16 @@ jobs: if not all(re.fullmatch(r"[0-9a-f]{40}", sha) for sha in (base, head)) or not token: raise ReviewError("Missing token or invalid commit identities") comparison = f"/dependency-graph/compare/{base}...{head}" - endpoint = f"https://api.github.com/repos/{repository}{comparison}" + repository_url = f"https://api.github.com/repos/{repository}" + endpoint = repository_url + comparison canonical_endpoint = f"https://api.github.com/repositories/{repository_id}{comparison}" findings, blocked, total = [], 0, 0 + head_snapshot_missing = False for page in range(1, MAX_PAGES + 1): - changes, link = read_page(opener, f"{endpoint}?per_page={PAGE_SIZE}&page={page}", token) + changes, link, missing = read_page( + opener, f"{endpoint}?per_page={PAGE_SIZE}&page={page}", token, head + ) + head_snapshot_missing = head_snapshot_missing or missing total += len(changes) if total > MAX_CHANGES: raise ReviewError( @@ -169,7 +244,13 @@ jobs: blocked += len(matches) findings.extend(matches[: MAX_FINDINGS - len(findings)]) if not next_page(link, endpoint, canonical_endpoint, page): - return {"changes": total, "blocked_advisories": blocked, "findings": findings} + result = {"changes": total, "blocked_advisories": blocked, "findings": findings} + if head_snapshot_missing: + merge_base = check_snapshot_inputs(repository_url, base, head, token, opener) + if merge_base != base: + check_snapshot_inputs(repository_url, merge_base, base, token, opener) + result["snapshot_inputs"] = "unchanged" + return result raise ReviewError("Dependency changes exceed the page limit; review is incomplete") diff --git a/.github/workflows/external-links.yml b/.github/workflows/external-links.yml index 5b228dd81fd..0e6d03637ca 100644 --- a/.github/workflows/external-links.yml +++ b/.github/workflows/external-links.yml @@ -12,6 +12,10 @@ on: schedule: - cron: "23 7 * * 3" +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read @@ -79,7 +83,7 @@ jobs: raise SystemExit(f"Install redirect returned the wrong status or destination: {link}") PYTHON - name: Check public documentation URLs - working-directory: ${{ github.event_name == 'pull_request' && 'link-baseline' || '.' }} + if: github.event_name != 'pull_request' run: | "$RUNNER_TEMP/lychee" --scheme https --scheme http --exclude-all-private \ --exclude '^https?://([^/]+\.)?example\.(com|org|net)([:/]|$)' \ @@ -90,7 +94,7 @@ jobs: --output "$RUNNER_TEMP/external-links.md" \ README.md CONTRIBUTING.md 'docs/getting-started/**/*.md' 'sdk/*/README.md' - name: Report the checked links - if: "!cancelled()" + if: "!cancelled() && github.event_name != 'pull_request'" run: | if [ -f "$RUNNER_TEMP/external-links.md" ]; then cat "$RUNNER_TEMP/external-links.md" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/go-api.yml b/.github/workflows/go-api.yml index 46731e596ba..25d0d828cbf 100644 --- a/.github/workflows/go-api.yml +++ b/.github/workflows/go-api.yml @@ -12,6 +12,10 @@ on: - "sdk/go/**" - ".github/workflows/go-api.yml" +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read diff --git a/.github/workflows/maven-dependency-graph.yml b/.github/workflows/maven-dependency-graph.yml index ad7dd034aa8..d47422b5214 100644 --- a/.github/workflows/maven-dependency-graph.yml +++ b/.github/workflows/maven-dependency-graph.yml @@ -14,6 +14,10 @@ on: schedule: - cron: "36 5 * * 2" +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read # Verification checks out the repository. diff --git a/.github/workflows/rust-advisories.yml b/.github/workflows/rust-advisories.yml index 9d782afe0c6..145f33ee8cd 100644 --- a/.github/workflows/rust-advisories.yml +++ b/.github/workflows/rust-advisories.yml @@ -14,11 +14,16 @@ on: schedule: - cron: "37 6 * * 2" +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read jobs: rust-advisories: + name: Check Rust dependency advisories and sources runs-on: ubuntu-24.04 timeout-minutes: 10 env: diff --git a/.github/workflows/rust-api.yml b/.github/workflows/rust-api.yml index 12b100bab1c..b1898e58306 100644 --- a/.github/workflows/rust-api.yml +++ b/.github/workflows/rust-api.yml @@ -12,6 +12,10 @@ on: - "sdk/rust/**" - ".github/workflows/rust-api.yml" +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read diff --git a/.github/workflows/rust-dependency-graph.yml b/.github/workflows/rust-dependency-graph.yml index 9772b635ea2..4073c41b218 100644 --- a/.github/workflows/rust-dependency-graph.yml +++ b/.github/workflows/rust-dependency-graph.yml @@ -18,6 +18,10 @@ on: schedule: - cron: "43 5 * * 2" +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read # Resolution checks out the repository. diff --git a/.github/workflows/typescript-api-report.yml b/.github/workflows/typescript-api-report.yml index dda337da5fc..9386f2bb486 100644 --- a/.github/workflows/typescript-api-report.yml +++ b/.github/workflows/typescript-api-report.yml @@ -23,6 +23,7 @@ concurrency: jobs: api-report: + name: Compare the TypeScript SDK with the release baseline runs-on: ubuntu-24.04 timeout-minutes: 12 env: diff --git a/tests/unit/test_dependency_review_workflow.py b/tests/unit/test_dependency_review_workflow.py index dcb4731d1c3..0c93f8d0a41 100644 --- a/tests/unit/test_dependency_review_workflow.py +++ b/tests/unit/test_dependency_review_workflow.py @@ -80,6 +80,23 @@ def review(*responses): return POLICY.review(REPOSITORY, BASE, HEAD, "test-token", Opener(*responses), REPOSITORY_ID) +def missing_head(data): + warning = f"No snapshots were found for the head SHA {HEAD}.".encode() + return Response( + data, + headers={"x-github-dependency-graph-snapshot-warnings": base64.b64encode(warning).decode()}, + ) + + +def comparison(paths, *, merge_base=BASE): + return Response( + { + "merge_base_commit": {"sha": merge_base}, + "files": [{"filename": path, "status": "modified"} for path in paths], + } + ) + + class DependencyReviewTests(unittest.TestCase): def test_added_high_and_critical_fail_but_lower_and_removed_pass(self): result = review( @@ -149,6 +166,88 @@ def test_incomplete_or_malformed_snapshots_fail(self): with self.assertRaises(POLICY.ReviewError): review(Response([], headers={"x-github-dependency-graph-snapshot-warnings": "%%%"})) + def test_missing_head_snapshot_checks_advisories_when_inputs_are_unchanged(self): + opener = Opener( + missing_head([change()]), + comparison(["frontend/src/example.ts", "sdk/java/src/main/java/example.java"]), + ) + result = POLICY.review(REPOSITORY, BASE, HEAD, "test-token", opener, REPOSITORY_ID) + self.assertEqual(result["blocked_advisories"], 1) + self.assertEqual( + opener.requests[1][0].full_url, + f"https://api.github.com/repos/{REPOSITORY}/compare/{BASE}...{HEAD}?per_page=1", + ) + + def test_missing_snapshot_requires_a_complete_diff_on_both_sides(self): + with self.assertRaises(POLICY.ReviewError): + review(missing_head([]), comparison(["docs/example.md"] * 300)) + with self.assertRaises(POLICY.ReviewError): + review( + missing_head([]), + comparison(["docs/example.md"], merge_base="c" * 40), + comparison(["sdk/rust/Cargo.toml"], merge_base="c" * 40), + ) + self.assertEqual( + review( + missing_head([]), + comparison(["docs/example.md"], merge_base="c" * 40), + comparison(["README.md"], merge_base="c" * 40), + )["blocked_advisories"], + 0, + ) + + def test_missing_snapshot_refuses_modified_build_inputs(self): + for path in ( + "sdk/java/pom.xml", + ".mvn/maven.config", + ".cargo/config.toml", + "sdk/rust/src/lib.rs", + ".github/scripts/rust-dependency-snapshot.py", + ".github/scripts/test_rust_dependency_snapshot.py", + ".github/workflows/maven-dependency-graph.yml", + "unittest/__init__.py", + "pathlib.py", + "sitecustomize.py", + ): + with self.subTest(path=path), self.assertRaises(POLICY.ReviewError): + review(missing_head([]), comparison([path])) + + def test_missing_snapshot_accepts_only_the_scheduler_change_in_submission_workflows(self): + expression = "$" + "{{ " + condition = expression + "github.event_name == 'pull_request'" + patch = ( + "@@ -1,2 +1,6 @@\n+concurrency:\n" + f"+ group: {expression}github.workflow }}}}-{condition} && github.ref || github.sha }}}}\n" + f"+ cancel-in-progress: {condition} }}}}\n+\n permissions:\n contents: read" + ) + file = { + "filename": ".github/workflows/rust-dependency-graph.yml", + "status": "modified", + "additions": 4, + "deletions": 0, + "patch": patch, + } + data = {"merge_base_commit": {"sha": BASE}, "files": [file]} + self.assertEqual(review(missing_head([]), Response(data))["snapshot_inputs"], "unchanged") + for changes in ( + {"patch": None}, + {"deletions": 1}, + {"patch": patch.replace(" permissions:", " jobs:")}, + {"status": "renamed", "previous_filename": "sdk/rust/Cargo.toml"}, + ): + with self.subTest(changes=changes), self.assertRaises(POLICY.ReviewError): + review(missing_head([]), Response({**data, "files": [{**file, **changes}]})) + + def test_missing_snapshot_checks_the_old_name_of_a_renamed_input(self): + data = { + "merge_base_commit": {"sha": BASE}, + "files": [ + {"filename": "example.txt", "status": "renamed", "previous_filename": "pom.xml"} + ], + } + with self.assertRaises(POLICY.ReviewError): + review(missing_head([]), Response(data)) + def test_http_and_timeout_fail_without_retry(self): for code in (403, 404, 429, 503): opener = Opener(urllib.error.HTTPError(ENDPOINT, code, "failure", {}, None))