Skip to content

Commit 2b07b03

Browse files
committed
CLI-1555 Address workflow generation review
1 parent 3bad10a commit 2b07b03

6 files changed

Lines changed: 103 additions & 57 deletions

File tree

‎.github/renovate.json‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,9 @@
2020
}
2121
}
2222
],
23-
"customManagers": [
24-
{
25-
"customType": "regex",
26-
"managerFilePatterns": [
27-
"/^src/commands/admin/onboard-ci/github/templates\\.ts$/"
28-
],
29-
"matchStrings": [
30-
"const (?:CHECKOUT|SCAN)_ACTION\\s*=\\s*'(?<depName>[^'@]+)@(?<currentDigest>[a-f0-9]{40})'; // (?<currentValue>v[0-9.]+)"
31-
],
32-
"datasourceTemplate": "github-tags"
33-
}
34-
]
23+
"github-actions": {
24+
"managerFilePatterns": [
25+
"src/commands/admin/onboard-ci/github/workflow.yml"
26+
]
27+
}
3528
}

‎bun.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@
170170
"istanbul-reports": "3.2.0",
171171
"lint-staged": "16.4.0",
172172
"prettier": "3.10.1",
173+
"string-argv": "0.3.2",
173174
"typescript": "6.0.3",
174175
"typescript-eslint": "8.72.2"
175176
},

‎src/commands/admin/onboard-ci/github/templates.ts‎

Lines changed: 33 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,24 @@ import * as yaml from 'js-yaml';
2323
import { InvalidOptionError } from '@/core/commands/command-error.ts';
2424
import { PROJECT_KEY_SAFE_PATTERN } from '@/core/project-key.ts';
2525

26+
import defaultWorkflow from './workflow.yml';
27+
2628
export const WORKFLOW_PATH = '.github/workflows/sonarqube.yml';
2729
const DEFAULT_SONAR_TOKEN_VAR_NAME = 'SONAR_TOKEN';
28-
export const CHECKOUT_ACTION = 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'; // v7.0.1
29-
export const SCAN_ACTION =
30-
'SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4'; // v8.5.0
3130
const PROJECT_KEY_PLACEHOLDER = '{{SONAR_PROJECT_KEY}}';
3231

32+
interface GeneratedWorkflow {
33+
on: Record<string, unknown>;
34+
jobs: {
35+
sonarqube: {
36+
steps: {
37+
env?: Record<string, string>;
38+
with: Record<string, unknown>;
39+
}[];
40+
};
41+
};
42+
}
43+
3344
export interface WorkflowOptions {
3445
triggerOn?: 'main' | 'pr' | 'both';
3546
sonarTokenVarName?: string;
@@ -111,6 +122,12 @@ function scannerArgument(property: string): string {
111122
if (separator < 1 || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(key) || /[\r\n\0]/.test(property)) {
112123
throw new InvalidOptionError('Scanner properties must be single-line key=value pairs.');
113124
}
125+
// GitHub expands expressions after generation, so resolved values could introduce extra arguments.
126+
if (property.includes('${{')) {
127+
throw new InvalidOptionError(
128+
'Scanner properties cannot contain GitHub expressions. Use --workflow-template for dynamic values.',
129+
);
130+
}
114131
// The scan action parses quoted arguments with string-argv, without executing a shell.
115132
const quote = property.includes('"') ? "'" : '"';
116133
if (property.includes(quote)) {
@@ -137,12 +154,16 @@ export function generateWorkflow(
137154
}
138155
const secret = options.sonarTokenVarName ?? DEFAULT_SONAR_TOKEN_VAR_NAME;
139156
const trigger = options.triggerOn ?? 'both';
140-
const on: Record<string, unknown> = {};
141-
if (trigger === 'main' || trigger === 'both') {
142-
on.push = { branches: [defaultBranch] };
157+
const workflow = structuredClone(defaultWorkflow as GeneratedWorkflow);
158+
if (trigger === 'pr') {
159+
delete workflow.on.push;
160+
} else {
161+
// Git forbids *, ? and [ in branch names, leaving ! and + to escape.
162+
const branchPattern = defaultBranch.replace(/[!+]/g, '\\$&');
163+
workflow.on.push = { branches: [branchPattern] };
143164
}
144-
if (trigger === 'pr' || trigger === 'both') {
145-
on.pull_request = { types: ['opened', 'synchronize', 'reopened'] };
165+
if (trigger === 'main') {
166+
delete workflow.on.pull_request;
146167
}
147168
const args = [
148169
...(options.scannerProperty ?? []),
@@ -151,28 +172,10 @@ export function generateWorkflow(
151172
]
152173
.map(scannerArgument)
153174
.join(' ');
154-
return yaml.dump(
155-
{
156-
name: 'SonarQube analysis',
157-
on,
158-
permissions: { contents: 'read' },
159-
jobs: {
160-
sonarqube: {
161-
'runs-on': 'ubuntu-latest',
162-
steps: [
163-
{ uses: CHECKOUT_ACTION, with: { 'fetch-depth': 0 } },
164-
{
165-
name: 'SonarQube scan',
166-
uses: SCAN_ACTION,
167-
env: { SONAR_HOST_URL: serverUrl, SONAR_TOKEN: `\${{ secrets.${secret} }}` },
168-
with: { args },
169-
},
170-
],
171-
},
172-
},
173-
},
174-
{ lineWidth: -1, noRefs: true },
175-
);
175+
const scan = workflow.jobs.sonarqube.steps[1];
176+
scan.env = { SONAR_HOST_URL: serverUrl, SONAR_TOKEN: `\${{ secrets.${secret} }}` };
177+
scan.with.args = args;
178+
return yaml.dump(workflow, { lineWidth: -1, noRefs: true });
176179
}
177180

178181
export function generatePrContent(
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
name: SonarQube analysis
2+
on:
3+
push:
4+
branches:
5+
- main
6+
pull_request:
7+
types: [opened, synchronize, reopened]
8+
permissions:
9+
contents: read
10+
jobs:
11+
sonarqube:
12+
runs-on: ubuntu-latest
13+
steps:
14+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
15+
with:
16+
fetch-depth: 0
17+
- name: SonarQube scan
18+
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
19+
env:
20+
SONAR_HOST_URL: ''
21+
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
22+
with:
23+
args: ''

‎tests/unit/commands/admin/onboard-ci/github/templates.test.ts‎

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,13 @@
2020

2121
import { describe, expect, it } from 'bun:test';
2222
import * as yaml from 'js-yaml';
23+
import { parseArgsStringToArgv } from 'string-argv';
2324

2425
import {
25-
CHECKOUT_ACTION,
2626
generatePrContent,
2727
generateTemplatePrContent,
2828
generateWorkflow,
2929
renderWorkflowTemplate,
30-
SCAN_ACTION,
3130
validateWorkflowOptions,
3231
validateWorkflowTemplate,
3332
} from '@/commands/admin/onboard-ci/github/templates.ts';
@@ -44,9 +43,9 @@ jobs:
4443
SONAR_HOST_URL: \${{ vars.SERVER_URL }}
4544
`;
4645

47-
function workflow(triggerOn: 'main' | 'pr' | 'both' = 'both') {
46+
function workflow(triggerOn: 'main' | 'pr' | 'both' = 'both', defaultBranch = 'trunk') {
4847
return yaml.load(
49-
generateWorkflow('org:repo', 'https://sonar.example.com/context', 'trunk', { triggerOn }),
48+
generateWorkflow('org:repo', 'https://sonar.example.com/context', defaultBranch, { triggerOn }),
5049
) as {
5150
on: Record<string, unknown>;
5251
jobs: {
@@ -76,16 +75,23 @@ describe('generated GitHub workflow', () => {
7675
},
7776
);
7877

78+
it.each([
79+
['!main', '\\!main'],
80+
['release+stable', 'release\\+stable'],
81+
])('escapes default branch %s for literal matching', (branch, pattern) => {
82+
expect(workflow('main', branch).on.push).toEqual({ branches: [pattern] });
83+
});
84+
7985
it('sets Server attribution, pinned actions, full checkout and a secret reference', () => {
8086
const job = workflow().jobs.sonarqube;
81-
for (const step of job.steps) {
82-
expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
83-
}
8487
expect(job['runs-on']).toBe('ubuntu-latest');
85-
expect(job.steps[0]).toEqual({ uses: CHECKOUT_ACTION, with: { 'fetch-depth': 0 } });
88+
expect(job.steps[0]).toEqual({
89+
uses: expect.stringMatching(/^actions\/checkout@[a-f0-9]{40}$/),
90+
with: { 'fetch-depth': 0 },
91+
});
8692
expect(job.steps[1]).toEqual({
8793
name: 'SonarQube scan',
88-
uses: SCAN_ACTION,
94+
uses: expect.stringMatching(/^SonarSource\/sonarqube-scan-action@[a-f0-9]{40}$/),
8995
env: {
9096
SONAR_HOST_URL: 'https://sonar.example.com/context',
9197
SONAR_TOKEN: '${{ secrets.SONAR_TOKEN }}',
@@ -97,21 +103,40 @@ describe('generated GitHub workflow', () => {
97103
it('preserves YAML-sensitive values and quotes complete scanner arguments', () => {
98104
const result = generateWorkflow('org:repo', 'https://sonar.example.com', 'feature: special', {
99105
sonarTokenVarName: 'ANALYSIS_TOKEN',
100-
scannerProperty: [
101-
"sonar.projectName=Team: Bob's app #1",
102-
'sonar.exclusions=a/**,b/**',
103-
'sonar.projectVersion=${{ github.sha }}',
104-
],
106+
scannerProperty: ["sonar.projectName=Team: Bob's app #1", 'sonar.exclusions=a/**,b/**'],
105107
});
106108
expect(result).toContain('${{ secrets.ANALYSIS_TOKEN }}');
107-
expect(result).toContain('${{ github.sha }}');
108109
const parsed = yaml.load(result) as ReturnType<typeof workflow>;
109110
expect(parsed.on.push).toEqual({ branches: ['feature: special'] });
110111
expect(parsed.jobs.sonarqube.steps[1].with.args).toContain(
111112
'"-Dsonar.projectName=Team: Bob\'s app #1"',
112113
);
113114
});
114115

116+
it('blocks PR title expressions whose resolved quotes could add scanner arguments', () => {
117+
const expression = '${{ github.event.pull_request.title }}';
118+
const resolvedTitle = 'My app" "-Dsonar.host.url=https://other.example';
119+
// GitHub resolves the expression before the scan action parses its arguments.
120+
const args = `"-Dsonar.projectName=${expression}"`.replace(expression, resolvedTitle);
121+
122+
expect(parseArgsStringToArgv(args)).toEqual([
123+
'-Dsonar.projectName=My app',
124+
'-Dsonar.host.url=https://other.example',
125+
]);
126+
expect(() =>
127+
generateWorkflow('org:repo', 'https://sonar.example.com', 'main', {
128+
scannerProperty: [`sonar.projectName=${expression}`],
129+
}),
130+
).toThrow('Scanner properties cannot contain GitHub expressions');
131+
});
132+
133+
it('rejects GitHub SHA expressions in scanner properties', () => {
134+
const property = 'sonar.projectVersion=${{ github.sha }}';
135+
expect(() => validateWorkflowOptions({ scannerProperty: [property] })).toThrow(
136+
'Scanner properties cannot contain GitHub expressions',
137+
);
138+
});
139+
115140
it.each(['bad', '=value', 'sonar.x=a\nb', `sonar.x=both'"`])(
116141
'rejects unsafe property %s before repository processing',
117142
(property) => {

0 commit comments

Comments
 (0)