@aikidosec/ci-api-client 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ name: Build and release
2
+ on:
3
+ release:
4
+ types: [published]
5
+
6
+ jobs:
7
+ build:
8
+ runs-on: ubuntu-latest
9
+ permissions:
10
+ contents: read
11
+ id-token: write
12
+ timeout-minutes: 15
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-node@v4
16
+ with:
17
+ node-version: "20.x"
18
+ registry-url: "https://registry.npmjs.org"
19
+ scope: "@aikidosec"
20
+ cache: 'yarn'
21
+
22
+ - name: Install dependencies
23
+ run: yarn install
24
+
25
+ - name: Build the library
26
+ run: yarn build
27
+
28
+ - name: Get the version
29
+ id: get_version
30
+ run: echo "tag=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT
31
+
32
+ - name: Set the version
33
+ run: npm --no-git-tag-version version ${{ steps.get_version.outputs.tag }}
34
+
35
+ - name: Publish to NPM
36
+ run: |
37
+ echo "Publishing version ${{ steps.get_version.outputs.tag }} to NPM"
38
+ npm publish --provenance --access public
39
+ env:
40
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
package/README.md CHANGED
@@ -1,10 +1,11 @@
1
- # Aikido Security CI API client
1
+ # Aikido Security CI client
2
2
 
3
3
  <!-- [![NPM Version](http://img.shields.io/npm/v/aikido-api-client.svg?style=flat)](https://www.npmjs.org/package/aikido-api-client)
4
4
  [![NPM Downloads](https://img.shields.io/npm/dm/aikido-api-client.svg?style=flat)](https://npmcharts.com/compare/aikido-api-client?minimal=true)
5
5
  [![Install Size](https://packagephobia.now.sh/badge?p=aikido-api-client)](https://packagephobia.now.sh/result?p=aikido-api-client) -->
6
6
 
7
- CLI helper for the public [Aikido CI API](https://aikido-dev.notion.site/aikido-dev/Aikido-CI-API-78d318b5f5f7477ab072e12f94b21374). This cli tool can help integrate Aikido into a custom CI pipeline without having to implement the Aikido CI API yourself.
7
+ This CLI tool can help integrate Aikido Security scans into any custom CI pipeline such as Jenkins, CircleCI,...
8
+ If you are looking to add checks to a Github, Azure Repos,.. pull request, you do not need this package and you can use our native plugins.
8
9
 
9
10
  ## Installation and setup
10
11
 
@@ -26,15 +27,67 @@ $ aikido-api-client apikey <your-api-key-here>
26
27
 
27
28
  ⚠️ Your Aikido API key is stored in `~/.config/configstore/aikido-api-client.json`. If you don't want this behaviour (e.g. for security related issues), you can also provide your API key to `aikido-api-client` by adding `--apikey <your-api-key-here>` to every command. However, for the examples below, we'll assume you've used `aikido-api-client apikey <your-api-key-here>` to save your API key. If `--apikey` is provided while a key is set in the configuration file on disk, the key that was provided with `--apikey` will be used.
28
29
 
29
- ## Usage
30
+ ## Use case: release gating
30
31
 
31
- Using the `aikido-api-client` to start new scans is very straightforward.
32
+ The example below shows how to use the `scan-release` command. The use case here is to block a new build or a new release as long as issues are still open.
33
+
34
+ ```sh
35
+ $ aikido-api-client scan-release <repository_id or repository_name> <commit_id>
36
+ ```
37
+ ```
38
+ Usage: Aikido API Client scan-release [options] <repository_id> <commit_id>
39
+ Run a release scan of an Aikido repo.
40
+ Arguments:
41
+ repository_id The internal GitHub/Gitlab/Bitbucket/.. repository id you want to scan.
42
+ commit_id The commit you want to scan
43
+ Options:
44
+ --no-fail-on-dependency-scan Don't fail when scanning depedencies. Default is to fail on new CVE
45
+ --fail-on-sast-scan Let Aikido fail when new static code analysis issues have been detected
46
+ --fail-on-iac-scan Let Aikido fail when new infrastructure as code issues have been detected
47
+ --fail-on-secrets-scan Let Aikido fail when new exposed secrets have been detected
48
+ --minimum-severity-level <level> Set the minimum severity level. Accepted options are: LOW, MEDIUM, HIGH and CRITICAL. (choices: "LOW", "MEDIUM",
49
+ "HIGH", "CRITICAL")
50
+ --poll-interval [interval] The poll interval when checking for an updated scan result (preset: 10)
51
+ -h, --help display help for command
52
+ ```
53
+
54
+ ## Use case: pull request checks & gating
55
+
56
+ The example below shows how to use the 'scan' command. The use case here is to add a red/green check to a pull request based on the difference in files (head vs base commit).
32
57
 
33
58
  ```sh
34
59
  $ aikido-api-client scan <repository_id or repository_name> <base_commit_id> <head_commit_id>
35
60
  ```
61
+ ```
62
+ Usage: Aikido API Client scan [options] <repository_id> <base_commit_id> <head_commit_id> [branch_name]
63
+ Run a scan of an Aikido repo.
64
+ Arguments:
65
+ repository_id The internal GitHub/Gitlab/Bitbucket/.. repository id you want to scan.
66
+ base_commit_id The base commit of the code you want to scan (e.g. the commit where you branched from for your PR or the
67
+ initial commit of your repo)
68
+ head_commit_id The latest commit you want to include in your scan (e.g. the latest commit id of your pull request)
69
+ branch_name The branch name (default: "main")
70
+ Options:
71
+ --pull-request-title <title> Your pull request title
72
+ --pull-request-url <url> Your pull request URL
73
+ --self-managed-scanners <scanners...> Set the minimum severity level. Accepted options are: LOW, MEDIUM, HIGH and CRITICAL. (choices: "checkov",
74
+ "json-sbom")
75
+ --expected-amount-json-sboms <amount> The expected amount of json sbombs
76
+ --no-fail-on-dependency-scan Don't fail when scanning depedencies. Default is to fail on new CVE
77
+ --fail-on-sast-scan Let Aikido fail when new static code analysis issues have been detected
78
+ --fail-on-iac-scan Let Aikido fail when new infrastructure as code issues have been detected
79
+ --fail-on-secrets-scan Let Aikido fail when new exposed secrets have been detected
80
+ --minimum-severity-level <level> Set the minimum severity level. Accepted options are: LOW, MEDIUM, HIGH and CRITICAL. (choices: "LOW",
81
+ "MEDIUM", "HIGH", "CRITICAL")
82
+ --poll-interval [interval] The poll interval when checking for an updated scan result (preset: 5)
83
+ -h, --help display help for command
84
+ ```
85
+
86
+
87
+
88
+ ## How it works
36
89
 
37
- The process will report scan progress and will exit with exitCode `0` if the scan was successfull (`gate_passed: true`). The process will exit with exitCode `10` if the scan was unsuccesfull (`gate_passed: false`). If anything else goes wrong (e.g. API unavailable, scanning unavailable, other unexpected issue) the process will exit with exitCode `1`.
90
+ The CLI will spawn a cloud-based scan and then report scan progress. It will exit with exitCode `0` if the scan was successfull (`gate_passed: true`). The process will exit with exitCode `10` if the scan was unsuccesfull (`gate_passed: false`). If anything else goes wrong (e.g. API unavailable, scanning unavailable, other unexpected issue) the process will exit with exitCode `1`.
38
91
 
39
92
  If you want the scan to run quietly (without output), you can add the `--quiet` option to the command.
40
93
 
@@ -43,9 +96,10 @@ Please note that the repository_id which you need to provide to the CLI is the u
43
96
  ```sh
44
97
  # For more options and combinations, check the help output
45
98
  $ aikido-api-client help scan
99
+ $ aikido-api-client help scan-release
46
100
  ```
47
101
 
48
- Uploading custom test results:
102
+ Uploading custom test results (supported by the `scan` command only):
49
103
 
50
104
  ```sh
51
105
  $ aikido-api-client upload --repository-id <repository_id> --type checkov --file <path_to_payload_file>
@@ -54,7 +108,7 @@ $ aikido-api-client upload --repository-id <repository_id> --type checkov --file
54
108
  $ aikido-api-client help upload
55
109
  ```
56
110
 
57
- For more information about these parameters, please refer to `aikido-api-client help`, `aikido-api-client help scan` or `aikido-api-client help upload`, or [the public ci api page](https://aikido-dev.notion.site/aikido-dev/Aikido-CI-API-78d318b5f5f7477ab072e12f94b21374).
111
+ For more information about these parameters, please refer to `aikido-api-client help`, `aikido-api-client help scan`, `aikido-api-client help scan-release` or `aikido-api-client help upload`, or [the public ci api page](https://aikido-dev.notion.site/aikido-dev/Aikido-CI-API-78d318b5f5f7477ab072e12f94b21374).
58
112
 
59
113
  ## Help & contributing
60
114
 
@@ -75,6 +129,9 @@ If you are missing functionality in this cli tool, please feel free to add it. I
75
129
 
76
130
  - [Aikido Official Website](https://aikido.dev)
77
131
  - [Aikido Github Actions Workflow](https://github.com/AikidoSec/github-actions-workflow)
132
+ - [Aikido GitLab CI Integration](https://gitlab.com/aikido-security/gitlab-ci-integration)
133
+ - [Aikido Bitbucket Pipe](https://bitbucket.org/aikido-production/bitbucket-pipe)
134
+ - [Aikido Azure Pipelines](https://marketplace.visualstudio.com/items?itemName=AikidoSecurity.aikido-security-scanner)
78
135
  - [Aikido on Twitter](https://twitter.com/AikidoSecurity)
79
136
 
80
137
 
@@ -14,6 +14,7 @@ export type TScanApiOptions = {
14
14
  fail_on_secrets_scan?: boolean;
15
15
  minimum_severity?: string;
16
16
  version: string;
17
+ is_release_gating?: boolean;
17
18
  };
18
19
  export type TStartScanResult = {
19
20
  scan_id: number;
@@ -118,7 +118,7 @@ export const scan = async ({ repoId, baseCommitId, headCommitId, branchName, opt
118
118
  pollStatus();
119
119
  };
120
120
  const parseCliOptions = (userCliOptions) => {
121
- const apiOptions = { version: '1.0.5' };
121
+ const apiOptions = { version: '1.0.6' };
122
122
  const cliOptions = { pollInterval: 5 };
123
123
  if (userCliOptions.pullRequestTitle) {
124
124
  apiOptions.pull_request_metadata = {
@@ -185,7 +185,7 @@ export const cliSetup = (program) => program
185
185
  .addOption(new Option('--no-fail-on-dependency-scan', "Don't fail when scanning depedencies..."))
186
186
  .option('--fail-on-sast-scan', 'Let Aikido fail when new static code analysis issues have been detected...')
187
187
  .option('--fail-on-iac-scan', 'Let Aikido fail when new infrastructure as code issues have been detected...')
188
- .option('--fail-on-secrets-scan', 'Let Aikido fail when new leaked secrets have been detected...')
188
+ .option('--fail-on-secrets-scan', 'Let Aikido fail when new exposed secrets have been detected...')
189
189
  .addOption(new Option('--minimum-severity-level <level>', 'Set the minimum severity level. Accepted options are: LOW, MEDIUM, HIGH and CRITICAL.').choices(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']))
190
190
  .addOption(new Option('--poll-interval [interval]', 'The poll interval when checking for an updated scan result')
191
191
  .preset(5)
@@ -0,0 +1,35 @@
1
+ import { Command } from 'commander';
2
+ import { TPollIsScanningResult, TPollScanCompletedDefaultBranchResult, TPollScanFeatureBranchCompletedResult, TScanApiOptions } from '../aikidoApi.js';
3
+ type TScanArguments = {
4
+ repoId: string | number;
5
+ commitId: string;
6
+ options: TScanApiOptions;
7
+ pollInterval: number;
8
+ onStart?: () => void | null;
9
+ onStartComplete?: (startResult: any) => void | null;
10
+ onStartFail?: (error: any) => void | null;
11
+ onScanStart?: (startResult: TPollIsScanningResult | TPollScanFeatureBranchCompletedResult | TPollScanCompletedDefaultBranchResult) => void | null;
12
+ onNextPoll?: (pollResult: TPollIsScanningResult | TPollScanFeatureBranchCompletedResult | TPollScanCompletedDefaultBranchResult) => void | null;
13
+ onScanComplete?: (pollResult: TPollIsScanningResult | TPollScanFeatureBranchCompletedResult | TPollScanCompletedDefaultBranchResult) => void | null;
14
+ onScanFail?: (error: any) => void | null;
15
+ };
16
+ type TScanUserCliOptions = {
17
+ pullRequestTitle?: string;
18
+ pullRequestUrl?: string;
19
+ selfManagedScanners?: string[];
20
+ failOnDependencyScan?: boolean;
21
+ failOnSastScan?: boolean;
22
+ failOnSecretsScan?: boolean;
23
+ failOnIacScan?: boolean;
24
+ minimumSeverityLevel?: string;
25
+ pollInterval?: number;
26
+ };
27
+ declare function cli(repoId: string, commitId: string, options: TScanUserCliOptions, command: string): Promise<void>;
28
+ export declare const scan: ({ repoId, commitId, options, pollInterval, onStart, onStartComplete, onStartFail, onScanStart, onNextPoll, onScanComplete, onScanFail, }: TScanArguments) => Promise<void>;
29
+ export declare const cliSetup: (program: Command) => Command;
30
+ declare const _default: {
31
+ cli: typeof cli;
32
+ cliSetup: (program: Command) => Command;
33
+ scan: ({ repoId, commitId, options, pollInterval, onStart, onStartComplete, onStartFail, onScanStart, onNextPoll, onScanComplete, onScanFail, }: TScanArguments) => Promise<void>;
34
+ };
35
+ export default _default;
@@ -0,0 +1,182 @@
1
+ import chalk from 'chalk';
2
+ import { Argument, InvalidArgumentError, Option } from 'commander';
3
+ import { pollScanStatus, startScan, } from '../aikidoApi.js';
4
+ import { getApiKey } from '../configuration.js';
5
+ import { outputError, outputHttpError, outputLog, startSpinner, } from '../output.js';
6
+ async function cli(repoId, commitId, options, command) {
7
+ const apiKey = getApiKey();
8
+ if (!apiKey) {
9
+ outputError('Please set an api key using: aikido-cli apikey <key>');
10
+ }
11
+ const { apiOptions, cliOptions } = parseCliOptions(options);
12
+ let loader;
13
+ let pollCount = 1;
14
+ const onStart = () => {
15
+ loader = startSpinner('Starting Aikido Security release scan');
16
+ };
17
+ const onStartComplete = (startResult) => {
18
+ loader?.succeed(`Aikido Security scan started (id: ${startResult.scan_id})`);
19
+ };
20
+ const onNextPoll = () => {
21
+ if (loader) {
22
+ loader.text = `Polling for Aikido Security scan to complete (${pollCount})`;
23
+ }
24
+ pollCount += 1;
25
+ };
26
+ const onScanStart = () => {
27
+ loader = startSpinner('Waiting for scan to complete');
28
+ };
29
+ const onScanComplete = (pollResult) => {
30
+ if (pollResult.gate_passed === true) {
31
+ loader?.succeed('Scan completed, no open issues found');
32
+ if (pollResult.diff_url) {
33
+ outputLog(chalk.gray(`* Diff url: ${pollResult.diff_url}`));
34
+ }
35
+ }
36
+ else {
37
+ loader?.fail('Scan completed with issues');
38
+ if (pollResult.new_issues_found) {
39
+ outputLog(chalk.gray(chalk.bold('Open issues found: ') + pollResult.new_issues_found));
40
+ }
41
+ if (pollResult.issue_links) {
42
+ outputLog(chalk.gray(pollResult.issue_links
43
+ .map((issueLink) => '- ' + issueLink)
44
+ .join('\n')));
45
+ }
46
+ if (pollResult.diff_url) {
47
+ outputLog(chalk.gray(`* Diff url: ${pollResult.diff_url}`));
48
+ }
49
+ process.exit(10);
50
+ }
51
+ };
52
+ const onFail = (error) => {
53
+ loader?.fail();
54
+ if (error.response?.status && error.response?.status === 404) {
55
+ outputError('Please verify your commit SHA');
56
+ }
57
+ else {
58
+ outputHttpError(error);
59
+ }
60
+ process.exit(1);
61
+ };
62
+ await scan({
63
+ repoId,
64
+ commitId,
65
+ options: apiOptions,
66
+ pollInterval: cliOptions.pollInterval,
67
+ onStart,
68
+ onStartComplete,
69
+ onStartFail: onFail,
70
+ onNextPoll,
71
+ onScanStart,
72
+ onScanComplete,
73
+ onScanFail: onFail,
74
+ });
75
+ }
76
+ export const scan = async ({ repoId, commitId, options, pollInterval = 10, onStart, onStartComplete, onStartFail, onScanStart, onNextPoll, onScanComplete, onScanFail, }) => {
77
+ onStart?.();
78
+ let result = null;
79
+ try {
80
+ result = await startScan({
81
+ is_release_gating: true,
82
+ head_commit_id: commitId,
83
+ repository_id: repoId,
84
+ ...options,
85
+ });
86
+ if (result.scan_id) {
87
+ onStartComplete?.(result);
88
+ }
89
+ else {
90
+ onStartFail?.(result);
91
+ return;
92
+ }
93
+ }
94
+ catch (error) {
95
+ onStartFail?.(error);
96
+ return;
97
+ }
98
+ onScanStart?.(result);
99
+ let pollResult;
100
+ const pollStatus = async () => {
101
+ try {
102
+ pollResult = await pollScanStatus(result.scan_id);
103
+ if (pollResult.all_scans_completed === false) {
104
+ onNextPoll?.(pollResult);
105
+ setTimeout(pollStatus, pollInterval * 1000);
106
+ }
107
+ else {
108
+ onScanComplete?.(pollResult);
109
+ }
110
+ }
111
+ catch (error) {
112
+ onScanFail?.(error);
113
+ }
114
+ };
115
+ pollStatus();
116
+ };
117
+ const parseCliOptions = (userCliOptions) => {
118
+ const apiOptions = { version: '1.0.6' };
119
+ const cliOptions = { pollInterval: 10 };
120
+ if (userCliOptions.pullRequestTitle) {
121
+ apiOptions.pull_request_metadata = {
122
+ ...(apiOptions.pull_request_metadata ?? {}),
123
+ title: userCliOptions.pullRequestTitle,
124
+ };
125
+ }
126
+ if (userCliOptions.pullRequestUrl) {
127
+ apiOptions.pull_request_metadata = {
128
+ ...(apiOptions.pull_request_metadata ?? {}),
129
+ url: userCliOptions.pullRequestUrl,
130
+ };
131
+ }
132
+ if (userCliOptions.selfManagedScanners) {
133
+ apiOptions.self_managed_scanners = userCliOptions.selfManagedScanners;
134
+ }
135
+ if (userCliOptions.failOnDependencyScan != undefined) {
136
+ apiOptions.fail_on_dependency_scan = userCliOptions.failOnDependencyScan;
137
+ }
138
+ if (userCliOptions.failOnSastScan != undefined) {
139
+ apiOptions.fail_on_sast_scan = userCliOptions.failOnSastScan;
140
+ }
141
+ if (userCliOptions.failOnIacScan != undefined) {
142
+ apiOptions.fail_on_iac_scan = userCliOptions.failOnIacScan;
143
+ }
144
+ if (userCliOptions.failOnSecretsScan != undefined) {
145
+ apiOptions.fail_on_secrets_scan = userCliOptions.failOnSecretsScan;
146
+ }
147
+ if (userCliOptions.minimumSeverityLevel) {
148
+ apiOptions.minimum_severity = userCliOptions.minimumSeverityLevel;
149
+ }
150
+ if (userCliOptions.pollInterval &&
151
+ (isNaN(userCliOptions.pollInterval) || userCliOptions.pollInterval <= 0)) {
152
+ outputError('Please provide a valid poll interval');
153
+ }
154
+ else if (userCliOptions.pollInterval) {
155
+ cliOptions.pollInterval = userCliOptions.pollInterval;
156
+ }
157
+ return { apiOptions, cliOptions };
158
+ };
159
+ const validateCommitId = (value) => {
160
+ const testCommitId = (commitId) => commitId.length === 40 && /^[0-9a-f]{40}$/.test(commitId);
161
+ if (testCommitId(value) === false) {
162
+ throw new InvalidArgumentError('Please provide a valid commit ID');
163
+ }
164
+ return value;
165
+ };
166
+ export const cliSetup = (program) => program
167
+ .command('scan-release')
168
+ .addArgument(new Argument('<repository_id>', 'The internal GitHub/Gitlab/Bitbucket/.. repository id you want to scan.').argRequired())
169
+ .addArgument(new Argument('<commit_id>', 'The commit you want to scan')
170
+ .argRequired()
171
+ .argParser(validateCommitId))
172
+ .addOption(new Option('--no-fail-on-dependency-scan', "Don't fail when scanning depedencies..."))
173
+ .option('--fail-on-sast-scan', 'Let Aikido fail when new static code analysis issues have been detected...')
174
+ .option('--fail-on-iac-scan', 'Let Aikido fail when new infrastructure as code issues have been detected...')
175
+ .option('--fail-on-secrets-scan', 'Let Aikido fail when new exposed secrets have been detected...')
176
+ .addOption(new Option('--minimum-severity-level <level>', 'Set the minimum severity level. Accepted options are: LOW, MEDIUM, HIGH and CRITICAL.').choices(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']))
177
+ .addOption(new Option('--poll-interval [interval]', 'The poll interval when checking for an updated scan result')
178
+ .preset(10)
179
+ .argParser(parseFloat))
180
+ .description('Run a release scan of an Aikido repo.')
181
+ .action(cli);
182
+ export default { cli, cliSetup, scan };
package/lib/index.js CHANGED
@@ -4,15 +4,17 @@ import { Command } from 'commander';
4
4
  import dotenv from 'dotenv';
5
5
  import apiKey from './commands/apiKey.js';
6
6
  import scan from './commands/scan.js';
7
+ import scanRelease from './commands/scanRelease.js';
7
8
  import upload from './commands/upload.js';
8
9
  dotenv.config(process.env.NODE_ENV ? { path: `.env.${process.env.NODE_ENV}` } : {});
9
10
  export const program = new Command();
10
11
  program
11
12
  .name('Aikido API Client')
12
13
  .description('CLI api client to easily integrate the Aikido public CI API into custom deploy scripts')
13
- .version('1.0.4');
14
+ .version('1.0.6');
14
15
  apiKey.cliSetup(program);
15
16
  scan.cliSetup(program);
17
+ scanRelease.cliSetup(program);
16
18
  upload.cliSetup(program);
17
19
  program
18
20
  .option('-q, --quiet', 'Disable console output when executing commands')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikidosec/ci-api-client",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "CLI api client to easily integrate the Aikido public CI API into custom deploy scripts",
5
5
  "license": "MIT",
6
6
  "author": "Bert Devriese <bert@builtinbruges.com>",
@@ -8,11 +8,11 @@
8
8
  "type": "module",
9
9
  "main": "lib/index.js",
10
10
  "bin": {
11
- "aikido-api-client": "./lib/index.js"
11
+ "aikido-api-client": "lib/index.js"
12
12
  },
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "https://github.com/AikidoSec/api-client.git"
15
+ "url": "git+https://github.com/AikidoSec/ci-api-client.git"
16
16
  },
17
17
  "scripts": {
18
18
  "start": "nodemon --watch 'src/**/*.ts' --esm --exec 'ts-node' src/index.ts",
package/src/aikidoApi.ts CHANGED
@@ -25,6 +25,7 @@ export type TScanApiOptions = {
25
25
  fail_on_secrets_scan?: boolean;
26
26
  minimum_severity?: string;
27
27
  version: string;
28
+ is_release_gating?: boolean;
28
29
  };
29
30
 
30
31
  export type TStartScanResult = {
@@ -245,7 +245,7 @@ export const scan = async ({
245
245
  const parseCliOptions = (userCliOptions: TScanUserCliOptions) => {
246
246
  // Version provided to the API corresponds with the version in package.json
247
247
  // of the cli client
248
- const apiOptions: TScanApiOptions = { version: '1.0.5' };
248
+ const apiOptions: TScanApiOptions = { version: '1.0.6' };
249
249
  const cliOptions: TScanCliOptions = { pollInterval: 5 };
250
250
 
251
251
  if (userCliOptions.pullRequestTitle) {
@@ -0,0 +1,349 @@
1
+ import chalk from 'chalk';
2
+ import { Argument, Command, InvalidArgumentError, Option } from 'commander';
3
+ import { Ora } from 'ora';
4
+ import {
5
+ TPollIsScanningResult,
6
+ TPollScanCompletedDefaultBranchResult,
7
+ TPollScanFeatureBranchCompletedResult,
8
+ TScanApiOptions,
9
+ TStartScanResult,
10
+ pollScanStatus,
11
+ startScan,
12
+ } from '../aikidoApi.js';
13
+ import { getApiKey } from '../configuration.js';
14
+ import {
15
+ outputError,
16
+ outputHttpError,
17
+ outputLog,
18
+ startSpinner,
19
+ } from '../output.js';
20
+
21
+ type TScanArguments = {
22
+ repoId: string | number;
23
+ commitId: string;
24
+ options: TScanApiOptions;
25
+ pollInterval: number;
26
+ onStart?: () => void | null;
27
+ onStartComplete?: (startResult: any) => void | null;
28
+ onStartFail?: (error: any) => void | null;
29
+ onScanStart?: (
30
+ startResult:
31
+ | TPollIsScanningResult
32
+ | TPollScanFeatureBranchCompletedResult
33
+ | TPollScanCompletedDefaultBranchResult
34
+ ) => void | null;
35
+ onNextPoll?: (
36
+ pollResult:
37
+ | TPollIsScanningResult
38
+ | TPollScanFeatureBranchCompletedResult
39
+ | TPollScanCompletedDefaultBranchResult
40
+ ) => void | null;
41
+ onScanComplete?: (
42
+ pollResult:
43
+ | TPollIsScanningResult
44
+ | TPollScanFeatureBranchCompletedResult
45
+ | TPollScanCompletedDefaultBranchResult
46
+ ) => void | null;
47
+ onScanFail?: (error: any) => void | null;
48
+ };
49
+
50
+ type TScanCliOptions = {
51
+ pollInterval: number;
52
+ };
53
+
54
+ type TScanUserCliOptions = {
55
+ pullRequestTitle?: string;
56
+ pullRequestUrl?: string;
57
+ selfManagedScanners?: string[];
58
+ failOnDependencyScan?: boolean;
59
+ failOnSastScan?: boolean;
60
+ failOnSecretsScan?: boolean;
61
+ failOnIacScan?: boolean;
62
+ minimumSeverityLevel?: string;
63
+ pollInterval?: number;
64
+ };
65
+
66
+ async function cli(
67
+ repoId: string,
68
+ commitId: string,
69
+ options: TScanUserCliOptions,
70
+ command: string
71
+ ) {
72
+
73
+ const apiKey = getApiKey();
74
+
75
+ if (!apiKey) {
76
+ outputError('Please set an api key using: aikido-cli apikey <key>');
77
+ }
78
+
79
+ // Process command options and group them into apiOptions hash
80
+ const { apiOptions, cliOptions } = parseCliOptions(options);
81
+
82
+ let loader: Ora | null;
83
+ let pollCount: number = 1;
84
+
85
+ // Setup different scan() event handlers
86
+ const onStart = () => {
87
+ loader = startSpinner('Starting Aikido Security release scan');
88
+ };
89
+
90
+ const onStartComplete = (startResult: TStartScanResult) => {
91
+ loader?.succeed(
92
+ `Aikido Security scan started (id: ${startResult.scan_id})`
93
+ );
94
+ };
95
+
96
+ const onNextPoll = () => {
97
+ if (loader) {
98
+ loader.text = `Polling for Aikido Security scan to complete (${pollCount})`;
99
+ }
100
+
101
+ pollCount += 1;
102
+ };
103
+
104
+ const onScanStart = () => {
105
+ loader = startSpinner('Waiting for scan to complete');
106
+ };
107
+
108
+ const onScanComplete = (pollResult: any) => {
109
+ if (pollResult.gate_passed === true) {
110
+ loader?.succeed('Scan completed, no open issues found');
111
+ if (pollResult.diff_url) {
112
+ outputLog(chalk.gray(`* Diff url: ${pollResult.diff_url}`));
113
+ }
114
+ } else {
115
+ loader?.fail('Scan completed with issues');
116
+
117
+ if (pollResult.new_issues_found) {
118
+ outputLog(
119
+ chalk.gray(
120
+ chalk.bold('Open issues found: ') + pollResult.new_issues_found
121
+ )
122
+ );
123
+ }
124
+
125
+ if (pollResult.issue_links) {
126
+ outputLog(
127
+ chalk.gray(
128
+ pollResult.issue_links
129
+ .map((issueLink: string) => '- ' + issueLink)
130
+ .join('\n')
131
+ )
132
+ );
133
+ }
134
+
135
+ if (pollResult.diff_url) {
136
+ outputLog(chalk.gray(`* Diff url: ${pollResult.diff_url}`));
137
+ }
138
+
139
+ process.exit(10);
140
+ }
141
+ };
142
+
143
+ const onFail = (error: any) => {
144
+ loader?.fail();
145
+
146
+ if (error.response?.status && error.response?.status === 404) {
147
+ outputError(
148
+ 'Please verify your commit SHA'
149
+ );
150
+ } else {
151
+ outputHttpError(error);
152
+ }
153
+
154
+ process.exit(1);
155
+ };
156
+
157
+ await scan({
158
+ repoId,
159
+ commitId,
160
+ options: apiOptions,
161
+ pollInterval: cliOptions.pollInterval,
162
+ onStart,
163
+ onStartComplete,
164
+ onStartFail: onFail,
165
+ onNextPoll,
166
+ onScanStart,
167
+ onScanComplete,
168
+ onScanFail: onFail,
169
+ });
170
+ }
171
+
172
+ export const scan = async ({
173
+ repoId,
174
+ commitId,
175
+ options,
176
+ pollInterval = 10,
177
+ onStart,
178
+ onStartComplete,
179
+ onStartFail,
180
+ onScanStart,
181
+ onNextPoll,
182
+ onScanComplete,
183
+ onScanFail,
184
+ }: TScanArguments): Promise<void> => {
185
+ onStart?.();
186
+
187
+ let result: any | null = null;
188
+
189
+ // Initialize a scan and call onStartComplete, onStartFail
190
+ // handlers where needed
191
+ try {
192
+
193
+ result = await startScan({
194
+ is_release_gating: true,
195
+ head_commit_id: commitId,
196
+ repository_id: repoId,
197
+ ...options,
198
+ });
199
+
200
+ if (result.scan_id) {
201
+ onStartComplete?.(result);
202
+ } else {
203
+ onStartFail?.(result);
204
+ return;
205
+ }
206
+ } catch (error) {
207
+ onStartFail?.(error);
208
+ return;
209
+ }
210
+
211
+ onScanStart?.(result);
212
+ let pollResult;
213
+
214
+ // Poll status with a setTimeout
215
+ const pollStatus = async () => {
216
+ try {
217
+ pollResult = await pollScanStatus(result.scan_id);
218
+
219
+ // If "all_scans_completed" returns true, call the onScanComplete
220
+ // handler, if not, re poll with `pollInterval`
221
+ // Note that onScanComplete can return a successfull or
222
+ // unsuccessfull scan result
223
+ if (pollResult.all_scans_completed === false) {
224
+ onNextPoll?.(pollResult);
225
+ setTimeout(pollStatus, pollInterval * 1000);
226
+ } else {
227
+ onScanComplete?.(pollResult);
228
+ }
229
+ } catch (error) {
230
+ onScanFail?.(error);
231
+ }
232
+ };
233
+
234
+ // Start polling
235
+ pollStatus();
236
+ };
237
+
238
+ const parseCliOptions = (userCliOptions: TScanUserCliOptions) => {
239
+ // Version provided to the API corresponds with the version in package.json
240
+ // of the cli client
241
+ const apiOptions: TScanApiOptions = { version: '1.0.6' };
242
+ const cliOptions: TScanCliOptions = { pollInterval: 10 };
243
+
244
+ if (userCliOptions.pullRequestTitle) {
245
+ apiOptions.pull_request_metadata = {
246
+ ...(apiOptions.pull_request_metadata ?? {}),
247
+ title: userCliOptions.pullRequestTitle,
248
+ };
249
+ }
250
+ if (userCliOptions.pullRequestUrl) {
251
+ apiOptions.pull_request_metadata = {
252
+ ...(apiOptions.pull_request_metadata ?? {}),
253
+ url: userCliOptions.pullRequestUrl,
254
+ };
255
+ }
256
+ if (userCliOptions.selfManagedScanners) {
257
+ apiOptions.self_managed_scanners = userCliOptions.selfManagedScanners;
258
+ }
259
+ if (userCliOptions.failOnDependencyScan != undefined) {
260
+ apiOptions.fail_on_dependency_scan = userCliOptions.failOnDependencyScan;
261
+ }
262
+ if (userCliOptions.failOnSastScan != undefined) {
263
+ apiOptions.fail_on_sast_scan = userCliOptions.failOnSastScan;
264
+ }
265
+ if (userCliOptions.failOnIacScan != undefined) {
266
+ apiOptions.fail_on_iac_scan = userCliOptions.failOnIacScan;
267
+ }
268
+ if (userCliOptions.failOnSecretsScan != undefined) {
269
+ apiOptions.fail_on_secrets_scan = userCliOptions.failOnSecretsScan;
270
+ }
271
+ if (userCliOptions.minimumSeverityLevel) {
272
+ apiOptions.minimum_severity = userCliOptions.minimumSeverityLevel;
273
+ }
274
+ if (
275
+ userCliOptions.pollInterval &&
276
+ (isNaN(userCliOptions.pollInterval) || userCliOptions.pollInterval <= 0)
277
+ ) {
278
+ outputError('Please provide a valid poll interval');
279
+ } else if (userCliOptions.pollInterval) {
280
+ cliOptions.pollInterval = userCliOptions.pollInterval;
281
+ }
282
+
283
+ return { apiOptions, cliOptions };
284
+ };
285
+
286
+ const validateCommitId = (value: string) => {
287
+ const testCommitId = (commitId: string): boolean =>
288
+ commitId.length === 40 && /^[0-9a-f]{40}$/.test(commitId);
289
+
290
+ if (testCommitId(value) === false) {
291
+ throw new InvalidArgumentError('Please provide a valid commit ID');
292
+ }
293
+
294
+ return value;
295
+ };
296
+
297
+ export const cliSetup = (program: Command) =>
298
+ program
299
+ .command('scan-release')
300
+ .addArgument(
301
+ new Argument(
302
+ '<repository_id>',
303
+ 'The internal GitHub/Gitlab/Bitbucket/.. repository id you want to scan.'
304
+ ).argRequired()
305
+ )
306
+ .addArgument(
307
+ new Argument(
308
+ '<commit_id>',
309
+ 'The commit you want to scan'
310
+ )
311
+ .argRequired()
312
+ .argParser(validateCommitId)
313
+ )
314
+ .addOption(
315
+ new Option(
316
+ '--no-fail-on-dependency-scan',
317
+ "Don't fail when scanning depedencies..."
318
+ )
319
+ )
320
+ .option(
321
+ '--fail-on-sast-scan',
322
+ 'Let Aikido fail when new static code analysis issues have been detected...'
323
+ )
324
+ .option(
325
+ '--fail-on-iac-scan',
326
+ 'Let Aikido fail when new infrastructure as code issues have been detected...'
327
+ )
328
+ .option(
329
+ '--fail-on-secrets-scan',
330
+ 'Let Aikido fail when new exposed secrets have been detected...'
331
+ )
332
+ .addOption(
333
+ new Option(
334
+ '--minimum-severity-level <level>',
335
+ 'Set the minimum severity level. Accepted options are: LOW, MEDIUM, HIGH and CRITICAL.'
336
+ ).choices(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'])
337
+ )
338
+ .addOption(
339
+ new Option(
340
+ '--poll-interval [interval]',
341
+ 'The poll interval when checking for an updated scan result'
342
+ )
343
+ .preset(10)
344
+ .argParser(parseFloat)
345
+ )
346
+ .description('Run a release scan of an Aikido repo.')
347
+ .action(cli);
348
+
349
+ export default { cli, cliSetup, scan };
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import { Command } from 'commander';
4
4
  import dotenv from 'dotenv';
5
5
  import apiKey from './commands/apiKey.js';
6
6
  import scan from './commands/scan.js';
7
+ import scanRelease from './commands/scanRelease.js';
7
8
  import upload from './commands/upload.js';
8
9
 
9
10
  // Load all .env configuration variables and auto-inject them into process.env
@@ -19,11 +20,12 @@ program
19
20
  .description(
20
21
  'CLI api client to easily integrate the Aikido public CI API into custom deploy scripts'
21
22
  )
22
- .version('1.0.4');
23
+ .version('1.0.6');
23
24
 
24
25
  // Load in all app commands and set them up in the `program` instance
25
26
  apiKey.cliSetup(program);
26
27
  scan.cliSetup(program);
28
+ scanRelease.cliSetup(program);
27
29
  upload.cliSetup(program);
28
30
 
29
31
  // Override global process.env type