Enforcing CodeWhisperer Security Scans in GitHub Actions + SonarQube for Spring Boot CI/CD
Introduction
In earlier posts we set up Amazon ElastiCache for Valkey as an external cache and used Amazon CodeWhisperer (via Amazon Q Developer) inside the IDE for faster Spring Boot development. Now we close the loop: automated, merge-blocking security quality gates in CI/CD.
This article shows how to wire CodeWhisperer security scans and SonarQube analysis into a GitHub Actions pipeline for a Spring Boot repository — with OIDC-authenticated AWS access, quality-gate configuration, a vulnerable-code demo, and enforcement tricks.
Why Two Engines?
CodeWhisperer and SonarQube overlap but are not interchangeable:
| Concern | CodeWhisperer (Amazon Q) | SonarQube |
|---|---|---|
| Focus | AWS-native vulnerabilities, credentials/secrets, SDK misuse (Java-oriented) | General code quality: bugs, code smells, security vulnerabilities (100+ rules) |
| Severity model | Informational / Low / Medium / High / Critical | Blocker / Critical / Major / Minor / Info |
| Best at | S3 bucket misuse, IAM misconfig in Java, hardcoded AWS keys | SQL injection, XSS, null-dereference, complexity, duplication |
| CI gate | Fail job on Critical/High findings; enterprise ignore-policies | Enforceable Quality Gate + branch-level "new code" conditions |
| Cost model | Free tier (Builder ID); Pro (IAM Identity Center, dashboards) | Community / Developer / Enterprise — server or SonarCloud |
Conclusion: run both, gate both. Your PR merge requires the CodeWhisperer job and the SonarQube Quality Gate to pass.
Prerequisites
- A GitHub repository with a Spring Boot project (Maven, JDK 17+)
- An AWS account
- SonarQube Server (Self-managed or SonarCloud) with a project key registered
- AWS OIDC provider already configured for your GitHub org/repo
- Enough IAM privileges to create the roles/policies referenced below
Step 1: Create an IAM Role for CodeWhisperer Scans (OIDC)
Never store long-lived AWS credentials in repository secrets. Use OpenID Connect with the standard role pattern:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::<ACCOUNT>:oidc-provider/token.actions.githubusercontent.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:<ORG>/<REPO>:ref:refs/heads/main"
}
}
}
]
}
Attach a least-privilege session policy plus the managed policy for the Enterprise tier:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CodeWhispererScan",
"Effect": "Allow",
"Action": [
"codewhisperer:StartProjectScan",
"codewhisperer:GetProjectScanTaskCompletionState",
"codewhisperer:GetProjectScan"
],
"Resource": "*"
}
]
}
For Enterprise tier with centralized security policies, also attach the managed policy AmazonQDeveloperFullAccess — it includes policy and scan governance actions.
Step 2: GitHub Actions Workflow — CodeWhisperer Scan Job
name: springboot-security
on:
pull_request:
branches: [main, develop]
push:
branches: [main]
schedule:
- cron: '30 2 * * *' # nightly full scan
workflow_dispatch:
permissions:
contents: read
id-token: write # required for AWS OIDC
security-events: write # needed for SARIF upload
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
codewhisperer-scan:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history for diff-based filtering
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
cache: 'maven'
- name: Configure AWS credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_CODEWHISPERER_SCAN_ROLE_ARN }}
aws-region: us-east-1
role-duration-seconds: 900
- name: Install Amazon Q CLI (CodeWhisperer)
run: |
curl -sL https://d3b6z8w7a5y2v.cloudfront.net/cli/latest/aws/qdeveloper/linux/aws-qdeveloper-amd64-latest.zip -o /tmp/q.zip
unzip -q -o /tmp/q.zip -d /tmp
chmod +x /tmp/aws-qdeveloper
sudo mv /tmp/aws-qdeveloper /usr/local/bin/
- name: Upload source as project scan
id: start_scan
run: |
echo "scanning $(find src/main/java -type f -name '*.java' | wc -l) Java files"
SCAN_ID=$(aws qdeveloper start-project-scan \
--region us-east-1 \
--project-name "springboot-ci-${{ github.repository_id }}" \
--programming-language java \
--workspace-state zip \
--project-path . \
| jq -r '.projectScanId')
echo "scan_id=$SCAN_ID" >> "$GITHUB_OUTPUT"
- name: Wait for scan completion
run: |
aws qdeveloper get-project-scan \
--id "${{ steps.start_scan.outputs.scan_id }}" \
--region us-east-1 --wait
echo "scan completed"
- name: Evaluate findings & fail on critical/high
run: |
aws qdeveloper get-project-scan \
--id "${{ steps.start_scan.outputs.scan_id }}" \
--project-name "springboot-ci-${{ github.repository_id }}" \
--region us-east-1 > scan_results.json
CRIT=$(jq '[.issues[]? | select(.severity=="Critical")] | length' scan_results.json)
HIGH=$(jq '[.issues[]? | select(.severity=="High")] | length' scan_results.json)
MED=$(jq '[.issues[]? | select(.severity=="Medium")] | length' scan_results.json)
echo "::group::CodeWhisperer findings"
jq -r '.issues[]? | "\(.severity): \(.title) [\(.descriptionFileName)]"' scan_results.json
echo "::endgroup::"
if [ "$CRIT" -gt 0 ]; then
echo "::error::CodeWhisperer: $CRIT Critical finding(s) found"
exit 1
fi
if [ "$HIGH" -gt 0 ] && [ "${{ github.ref }}" != "refs/heads/main" ]; then
echo "::error::CodeWhisperer: $HIGH High finding(s) on PR"
exit 1
fi
- name: Upload findings (optional SARIF transform)
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: findings.sarif
if: ${{ false }} # enable after you add the jq convert step
Only Count Findings on Changed Files (PR mode)
CodeWhisperer scans the whole project. On a pull request, restrict failing conditions to newly-touched Java files:
# After running scan, intersect findings with the PR diff:
CHANGED=$(git diff --name-only origin/${{ github.base_ref }}...${{ github.sha }} \
| grep '\.java$')
jq -r '.issues[]? | "\(.startLine),\(.endLine),\(.descriptionFileName)"' scan_results.json |
while IFS=, read -r sl el file; do
if echo "$CHANGED" | grep -Fxq "$file"; then
jq "[.issues[]? | select(.descriptionFileName==\"$file\")]" scan_results.json
fi
done > new_findings.json
CRIT=$(jq '[.[]?|select(.severity=="Critical")] | length' new_findings.json)
HIGH=$(jq '[.[]?|select(.severity=="High")] | length' new_findings.json)
Step 3: SonarQube Job — Analyze & Enforce Quality Gate
sonarqube:
runs-on: ubuntu-latest
needs: codewhisperer-scan # makes the pipeline sequential per PR
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Build & analyze
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: |
mvn -B verify -DskipTests
mvn -B org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \
-Dsonar.projectKey=springboot-ci \
-Dsonar.host.url="$SONAR_HOST_URL" \
-Dsonar.token="$SONAR_TOKEN" \
-Dsonar.java.binaries=target/classes \
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml \
-Dsonar.qualitygate.wait=true
- name: Quality gate check
id: qg
uses: sonarsource/sonarqube-quality-gate-action@v1
with:
projectKey: springboot-ci
token: ${{ secrets.SONAR_TOKEN }}
host: ${{ secrets.SONAR_HOST_URL }}
timeout: 300
fail-on-passed: true # always update the check
continue-on-error: true
Quality Gate Configuration (Self-managed / Enterprise)
{
"name": "SpringBoot-CI-Gate",
"conditions": [
{ "metric": "new_reliability_rating", "op": "LT", "error": "A" },
{ "metric": "new_security_rating", "op": "LT", "error": "A" },
{ "metric": "new_maintainability_rating", "op": "LT", "error": "A" },
{ "metric": "new_coverage", "op": "LT", "warning": true, "error": 80 },
{ "metric": "new_duplicated_lines_density", "op": "GT", "error": 3 },
{ "metric": "new_bugs", "op": "GT", "warning": true, "error": 0 },
{ "metric": "new_vulnerabilities", "op": "GT", "warning": true, "error": 0 },
{ "metric": "new_code_smells", "op": "GT", "warning": true, "error": 100 }
]
}
new_* conditions only apply to new/changed code (SonarQube uses your LeXIK branch baseline — usually Previous analysis or a specific parent)
Step 4: Vulnerable Spring Boot Code That Fails Both Gates
Here is intentionally bad code a developer might ship. Both engines catch it:
@RestController
public class AccountController {
// ✗ CWE-798 hardcoded AWS secret — caught by CodeWhisperer (Security)
private static final String AWS_SECRET = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
@Autowired private JdbcTemplate jdbcTemplate;
// ✗ CWE-89 SQL Injection — caught by SonarQube (java:S3649) and CodeWhisperer (Medium)
@GetMapping("/accounts")
public List<String> accounts(@RequestParam String tenant) {
return jdbcTemplate.queryForList(
"SELECT name FROM accounts WHERE tenant = '" + tenant + "'", String.class);
}
// ✗ Weak crypto — caught by CodeWhisperer (Medium/High) — Sonar may flag too
@PostMapping("/api-keys")
public String createKey(@RequestParam String raw) throws Exception {
byte[] key = "32char-long-static-key-!".getBytes("UTF-8");
SecretKeySpec spec = new SecretKeySpec(key, "AES");
return Base64.getEncoder().encodeToString(spec.getEncoded());
}
}
After push, both jobs run and output findings into the PR checks UI. With branch protection requiring these checks to pass, the merge is blocked.
Step 5: Add Required Status Checks (Merge Enforcement)
- Go to repo: Settings → Branches → Branch protection rules → edit for
main - Enable "Require status checks to pass" and search for:
codewhisperer-scansonarqube(Quality gate action name, e.g.SonarQube Quality Gate)
- Optional: require approval + re-pushing code after review comments for security findings.
Now a PR cannot merge until both the CodeWhisperer scan and the SonarQube gate are green.
Optional: GitHub Advanced Security (GHAS) SARIF Upload
CodeWhisperer returns JSON; GHAS wants SARIF. Add a converter step to surface findings as PR annotations:
# convert_to_sarif.py — lightweight mapper (or use official AWS CLI SARIF flag when available)
import json, sys
src = json.load(open(sys.argv[1]))
rules = {"AWS": []}
results = []
for f in src.get("issues", []):
rules["AWS"].append({"id": f["ruleId"], "shortDescription": {"text": f["title"]}})
results.append({
"ruleId": f["ruleId"],
"level": f["severity"].lower(),
"message": {"text": f["description"]},
"locations": [{
"physicalLocation": {
"artifactLocation": {"uri": f["descriptionFileName"]},
"region": {"startLine": f["startLine"], "endColumn": f["endLine"]}
}
}]
})
sarif = {
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [{"tool": {"driver": {"name": "Amazon Q Developer", "version": "2024.01", "rules": rules["AWS"]}}, "results": results}]
}
json.dump(sarif, open("findings.sarif", "w"))
Add to the workflow:
- name: Convert & upload SARIF
if: always()
run: python convert_to_sarif.py scan_results.json
- uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: findings.sarif
Nightly Scan & Audit Trail
For the schedule trigger (and push to main), relax the "only new code" restriction and enforce on the whole codebase. Keep a dashboard of results:
- Store a JSON artifact per run:
upload-artifactwithscan_results.json+ SARIF. - Feed SonarQube's "Projects" dashboard with trends over time (security rating, coverage on new code).
- Use the nightly run to catch regressions introduced outside of PR-based flow (direct pushes, dependabot merges).
Troubleshooting
| Symptom | Fix |
|---|---|
AccessDeniedException: User is not authorized |
Verify the OIDC role trust + AmazonQDeveloperFullAccess (Enterprise) is attached. |
scan stays in progress |
get-project-scan --wait has a 10-minute CLI default — pass --wait 15 or raise timeout-minutes. |
| Sonar gate "not found" | Check projectKey matches the SonarQube server key exactly and the webhook is reachable. |
| Job passes but gate still fails | Look at "Quality Gate" action logs; SonarQube must compute new_* metrics — enable main-branch analysis baseline. |
| Too many false positives in PR | Switch to the diff-only mode (Step 2, "changed files only") for PRs; keep full-scan for nightly. |
Conclusion
You now have a double gate: AWS-native security scanning for secrets/AWS SDK misuse via CodeWhisperer, and general static analysis/quality management via SonarQube. With OIDC-authenticated AWS access, branch protection, and a nightly full scan, your Spring Boot repository enforces "no Critical/High findings, green Quality Gate" — automatically.
Next: combine this with the ElastiCache Spring Data Valkey integration from the first post, and you'll have a defensible, cache-backed microservice pipeline.
Comments
Post a Comment