Skip to content

Commit 2fec559

Browse files
committed
ci: upload security sarif without codeql action
1 parent c2e071c commit 2fec559

2 files changed

Lines changed: 90 additions & 6 deletions

File tree

.github/workflows/ci.yml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,10 @@ jobs:
132132
run: gosec -fmt sarif -out gosec.sarif ./...
133133

134134
- name: Upload gosec results
135-
uses: github/codeql-action/upload-sarif@v4
136135
continue-on-error: true
137-
with:
138-
sarif_file: gosec.sarif
136+
env:
137+
GITHUB_TOKEN: ${{ github.token }}
138+
run: python3 scripts/upload-sarif-to-code-scanning.py --sarif-file gosec.sarif --category gosec
139139

140140
- name: Run Trivy vulnerability scanner
141141
uses: aquasecurity/trivy-action@master
@@ -146,10 +146,10 @@ jobs:
146146
output: 'trivy-results.sarif'
147147

148148
- name: Upload Trivy results
149-
uses: github/codeql-action/upload-sarif@v4
150149
continue-on-error: true
151-
with:
152-
sarif_file: 'trivy-results.sarif'
150+
env:
151+
GITHUB_TOKEN: ${{ github.token }}
152+
run: python3 scripts/upload-sarif-to-code-scanning.py --sarif-file trivy-results.sarif --category trivy
153153

154154
build:
155155
name: Build and Test Docker Images
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#!/usr/bin/env python3
2+
"""Upload a SARIF file to GitHub Code Scanning without the CodeQL action."""
3+
4+
from __future__ import annotations
5+
6+
import argparse
7+
import base64
8+
import gzip
9+
import json
10+
import os
11+
from pathlib import Path
12+
import sys
13+
import urllib.error
14+
import urllib.request
15+
16+
17+
def code_scanning_ref() -> str:
18+
ref = os.environ["GITHUB_REF"]
19+
if os.environ.get("GITHUB_EVENT_NAME") == "merge_group":
20+
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event_file:
21+
event = json.load(event_file)
22+
base_ref = event.get("merge_group", {}).get("base_ref", "")
23+
if base_ref.startswith("refs/heads/"):
24+
return base_ref
25+
if base_ref:
26+
return f"refs/heads/{base_ref}"
27+
if ref.startswith(("refs/heads/", "refs/pull/")):
28+
return ref
29+
raise ValueError(f"unsupported GITHUB_REF for Code Scanning SARIF upload: {ref}")
30+
31+
32+
def parse_args() -> argparse.Namespace:
33+
parser = argparse.ArgumentParser(description=__doc__)
34+
parser.add_argument("--sarif-file", required=True, type=Path)
35+
parser.add_argument("--category")
36+
return parser.parse_args()
37+
38+
39+
def main() -> int:
40+
args = parse_args()
41+
sarif_payload = base64.b64encode(gzip.compress(args.sarif_file.read_bytes())).decode(
42+
"ascii"
43+
)
44+
45+
body = {
46+
"commit_sha": os.environ["GITHUB_SHA"],
47+
"ref": code_scanning_ref(),
48+
"sarif": sarif_payload,
49+
"checkout_uri": f"file://{os.environ['GITHUB_WORKSPACE']}",
50+
}
51+
if args.category:
52+
body["category"] = args.category
53+
54+
request = urllib.request.Request(
55+
f"{os.environ['GITHUB_API_URL']}/repos/{os.environ['GITHUB_REPOSITORY']}/code-scanning/sarifs",
56+
data=json.dumps(body).encode("utf-8"),
57+
method="POST",
58+
headers={
59+
"Accept": "application/vnd.github+json",
60+
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
61+
"Content-Type": "application/json",
62+
"X-GitHub-Api-Version": "2022-11-28",
63+
},
64+
)
65+
try:
66+
with urllib.request.urlopen(request) as response:
67+
print(response.read().decode("utf-8"))
68+
except urllib.error.HTTPError as error:
69+
response_body = error.read().decode("utf-8")
70+
response_body_lower = response_body.lower()
71+
if error.code == 403 and (
72+
"advanced security must be enabled" in response_body_lower
73+
or "code scanning is not enabled" in response_body_lower
74+
or "code security must be enabled" in response_body_lower
75+
):
76+
print("::warning::Code Security is not enabled; skipping SARIF upload.")
77+
return 0
78+
sys.stderr.write(response_body)
79+
raise
80+
return 0
81+
82+
83+
if __name__ == "__main__":
84+
raise SystemExit(main())

0 commit comments

Comments
 (0)