diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d8b4eb6b..7b9c5839 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -20,7 +20,7 @@ jobs: name: Lint and test project strategy: matrix: - node: ['18', '20', '24', 'latest'] + node: ['24', 'latest'] env: MAIN_NODE_VER: '24' steps: @@ -88,8 +88,7 @@ jobs: env: TRUSTIFY_DA_PYTHON3_PATH: "${{steps.python-location.outputs.python-bin-location}}/python3" TRUSTIFY_DA_PIP3_PATH: "${{steps.python-location.outputs.python-bin-location}}/pip3" - TRUSTIFY_DA_DEV_MODE: 'true' - DEV_TRUSTIFY_DA_BACKEND_URL: 'https://exhort.stage.devshift.net' + TRUSTIFY_DA_BACKEND_URL: 'https://exhort.stage.devshift.net' run: npm run test - name: Compile project @@ -98,15 +97,13 @@ jobs: - name: Run integration tests run: npm run integration-tests env: - TRUSTIFY_DA_DEV_MODE: 'true' - DEV_TRUSTIFY_DA_BACKEND_URL: 'https://exhort.stage.devshift.net' + TRUSTIFY_DA_BACKEND_URL: 'https://exhort.stage.devshift.net' - name: Run integration tests cli working-directory: integration run: bash ./run_its.sh env: - TRUSTIFY_DA_DEV_MODE: 'true' - DEV_TRUSTIFY_DA_BACKEND_URL: 'https://exhort.stage.devshift.net' + TRUSTIFY_DA_BACKEND_URL: 'https://exhort.stage.devshift.net' - name: Upload coverage reports if: ${{ matrix.node == env.MAIN_NODE_VER }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 835af41f..6cd6389d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -119,7 +119,5 @@ contribution. See the [DCO](DCO) file for details. [0]: https://www.conventionalcommits.org/en/v1.0.0/ -[1]: https://github.com/guacsec/exhort/blob/0.1.x/src/main/resources/META-INF/openapi.yaml - [10]: https://badgen.net/badge/NodeJS%20Version/18/68a063 diff --git a/README.md b/README.md index abd94f41..56e6f5d5 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ -# Exhort JavaScript API
![latest-no-snapshot][0] ![latest-snapshot][1] +# Trustify Dependency Analytics JavaScript Client
![latest-no-snapshot][0] ![latest-snapshot][1] -* Looking for the OpenAPI Spec? Try [Exhort API Spec](https://github.com/trustify-da/trustify-da-api-model) -* Looking for our Java API? Try [Exhort Java API](https://github.com/guacsec/exhort-java-api). -* Looking for our Backend implementation? Try [Exhort](https://github.com/guacsec/exhort). +* Looking for the OpenAPI Spec? Try [Trustify Dependency Analytics API](https://github.com/guacsec/trustify-da-api-spec) +* Looking for our Java API? Try [Trustify Dependency Analytics Java Client](https://github.com/guacsec/trustify-da-java-client). +* Looking for our Backend implementation? Try [Trustify Dependency Analytics](https://github.com/guacsec/trustify-dependency-analytics).

Usage

+Prerequisites: The TRUSTIFY_DA_BACKEND_URL environment variable must be set to the URL of the Trustify Dependency Analytics backend service. You can set it as an environment variable or pass it in the options object (see Customization section). +

@@ -45,16 +52,16 @@ npm install @trustify-da/trustify-da-javascript-client ``` ```javascript -async function loadExhort() +async function loadTrustifyDa() { // dynamic import is the only way to import ESM module into commonJS module - const { default: exhort } = await import('@trustify-da/trustify-da-javascript-client'); - return exhort + const { default: client } = await import('@trustify-da/trustify-da-javascript-client'); + return client } -const runExhort = (manifestPath) => { +const runTrustifyDa = (manifestPath) => { return new Promise(async ( resolve, reject) => { try { - let stackAnalysisReport = await (await loadExhort()).stackAnalysis(manifestPath,false) + let stackAnalysisReport = await (await loadTrustifyDa()).stackAnalysis(manifestPath,false) resolve(stackAnalysisReport) } catch (error) @@ -64,7 +71,7 @@ const runExhort = (manifestPath) => { }); }; -runExhort("./path/to/manifest").then(resp => console.log(JSON.stringify(resp,null,4))) +runTrustifyDa("./path/to/manifest").then(resp => console.log(JSON.stringify(resp,null,4))) ``` @@ -297,17 +304,21 @@ All of the 5 above examples are valid for marking a package to be ignored

Customization

-There are 2 approaches for customizing Exhort JavaScript API. Whether you're using this API as a +There are 2 approaches for customizing Trustify Dependency Analytics JavaScript Client. Whether you're using this API as a Global Module, a Remote Script, or an ESM Module, you can use Environment Variables for various customization. +Note: The TRUSTIFY_DA_BACKEND_URL environment variable is mandatory and must be set to the URL of the Trustify Dependency Analytics backend service. Without this variable, the API will throw an error. + However, ESM Module users, can opt for customizing programmatically: ```javascript -import exhort from '@trustify-da/trustify-da-javascript-client' +import client from '@trustify-da/trustify-da-javascript-client' import fs from 'node:fs' let options = { + // Mandatory: Backend URL for Trustify Dependency Analytics service + 'TRUSTIFY_DA_BACKEND_URL': 'https://api.trustify.dev', 'TRUSTIFY_DA_MVN_PATH': '/path/to/my/mvn', 'TRUSTIFY_DA_NPM_PATH': '/path/to/npm', 'TRUSTIFY_DA_PNPM_PATH': '/path/to/pnpm', @@ -323,19 +334,19 @@ let options = { } // Get stack analysis in JSON format ( all package managers, pom.xml is as an example here) -let stackAnalysis = await exhort.stackAnalysis('/path/to/pom.xml', false, options) +let stackAnalysis = await client.stackAnalysis('/path/to/pom.xml', false, options) // Get stack analysis in HTML format in string ( all package managers, pom.xml is as an example here) -let stackAnalysisHtml = await exhort.stackAnalysis('/path/to/pom.xml', true, options) +let stackAnalysisHtml = await client.stackAnalysis('/path/to/pom.xml', true, options) // Get component analysis in JSON format -let componentAnalysis = await exhort.componentAnalysis('/path/to/pom.xml', options) +let componentAnalysis = await client.componentAnalysis('/path/to/pom.xml', options) // Get image analysis in JSON format -let imageAnalysis = await exhort.imageAnalysis(['docker.io/library/node:18'], false, options) +let imageAnalysis = await client.imageAnalysis(['docker.io/library/node:18'], false, options) // Get image analysis in HTML format in string -let imageAnalysisHtml = await exhort.imageAnalysis(['docker.io/library/node:18'], true, options) +let imageAnalysisHtml = await client.imageAnalysis(['docker.io/library/node:18'], true, options) // Specify architecture using ^^ notation (e.g., httpd:2.4.49^^amd64) -let imageAnalysisWithArch = await exhort.imageAnalysis(['httpd:2.4.49^^amd64'], false, options) +let imageAnalysisWithArch = await client.imageAnalysis(['httpd:2.4.49^^amd64'], false, options) ``` **_Environment variables takes precedence._**

diff --git a/integration/testers/javascript/index.js b/integration/testers/javascript/index.js index 35b278e9..a10b161e 100644 --- a/integration/testers/javascript/index.js +++ b/integration/testers/javascript/index.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -import exhort from '@trustify-da/trustify-da-javascript-client' +import client from '@trustify-da/trustify-da-javascript-client' import process from 'node:process' const [,, ...args] = process.argv @@ -8,13 +8,13 @@ const [,, ...args] = process.argv if ('stack' === args[0]) { // arg[1] = manifest path; arg[2] = is html boolean let html = args[2] === 'true' - let res = await exhort.stackAnalysis(args[1], html) + let res = await client.stackAnalysis(args[1], html) console.log(html ? res : JSON.stringify(res, null, 2)) process.exit(0) } if ('component' === args[0]) { // arg[1] = manifest path - let res = await exhort.componentAnalysis(args[1]) + let res = await client.componentAnalysis(args[1]) console.log(JSON.stringify(res, null, 2)) process.exit(0) } @@ -24,7 +24,7 @@ if ('validateToken' === args[0]) { let tokens = { "TRUSTIFY_DA_SNYK_TOKEN" : args[1] } - let res = await exhort.validateToken(tokens) + let res = await client.validateToken(tokens) console.log(res) process.exit(0) } diff --git a/integration/testers/typescript/index.ts b/integration/testers/typescript/index.ts index 738ddbd2..7d6d8493 100644 --- a/integration/testers/typescript/index.ts +++ b/integration/testers/typescript/index.ts @@ -1,21 +1,21 @@ #!/usr/bin/env node -import exhort from '@guacsec/trustify-da-javascript-client' -import process from 'node:process' -import { AnalysisReport } from '@trustify-da/trustify-da-api-model/model/v5/AnalysisReport' +import client from '@trustify-da/trustify-da-javascript-client'; +import process from 'node:process'; +import type { AnalysisReport } from '@trustify-da/trustify-da-api-model/model/v5/AnalysisReport'; -const [,, ...args] = process.argv +const args = process.argv.slice(2); if ('stack' === args[0]) { // arg[1] = manifest path; arg[2] = is html boolean let html = args[2] === 'true' - let res = await exhort.stackAnalysis(args[1], html) + let res = await client.stackAnalysis(args[1], html) console.log(html ? res as string : JSON.stringify(res as AnalysisReport, null, 2)) process.exit(0) } if ('component' === args[0]) { // arg[1] = manifest path - let res = await exhort.componentAnalysis(args[1]) + let res = await client.componentAnalysis(args[1]) console.log(JSON.stringify(res as AnalysisReport, null, 2)) process.exit(0) } diff --git a/package.json b/package.json index de3902f8..33f758cf 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,9 @@ "exhort", "secure", "supply-chain", - "vulnerability" + "vulnerability", + "trustify", + "dependency analytics" ], "engines": { "node": ">= 20.0.0", diff --git a/src/analysis.js b/src/analysis.js index 8eddf6bf..4e8a98ee 100644 --- a/src/analysis.js +++ b/src/analysis.js @@ -18,7 +18,7 @@ const rhdaPackageManagerHeader = "rhda-pkg-manager" /** * Adds proxy agent configuration to fetch options if a proxy URL is specified * @param {RequestInit} options - The base fetch options - * @param {import("index.js").Options} opts - The exhort options that may contain proxy configuration + * @param {import("index.js").Options} opts - The trustify DA options that may contain proxy configuration * @returns {RequestInit} The fetch options with proxy agent if applicable */ function addProxyAgent(options, opts) { @@ -47,7 +47,7 @@ async function requestStack(provider, manifest, url, html = false, opts = {}) { let startTime = new Date() let endTime if (process.env["TRUSTIFY_DA_DEBUG"] === "true") { - console.log("Starting time of sending stack analysis request to exhort server= " + startTime) + console.log("Starting time of sending stack analysis request to the dependency analytics server= " + startTime) } opts[rhdaPackageManagerHeader.toUpperCase().replaceAll("-", "_")] = provided.ecosystem @@ -80,15 +80,15 @@ async function requestStack(provider, manifest, url, html = false, opts = {}) { console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId) } endTime = new Date() - console.log("Response body received from exhort server : " + EOL + EOL) + console.log("Response body received from Trustify DA backend server : " + EOL + EOL) console.log(console.log(JSON.stringify(result, null, 4))) - console.log("Ending time of sending stack analysis request to exhort server= " + endTime) + console.log("Ending time of sending stack analysis request to Trustify DA backend server= " + endTime) let time = (endTime - startTime) / 1000 console.log("Total Time in seconds: " + time) } } else { - throw new Error(`Got error response from exhort backend - http return code : ${resp.status}, error message => ${await resp.text()}`) + throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, error message => ${await resp.text()}`) } return Promise.resolve(result) @@ -109,7 +109,7 @@ async function requestComponent(provider, manifest, url, opts = {}) { opts["source-manifest"] = "" opts[rhdaOperationTypeHeader.toUpperCase().replaceAll("-", "_")] = "component-analysis" if (process.env["TRUSTIFY_DA_DEBUG"] === "true") { - console.log("Starting time of sending component analysis request to exhort server= " + new Date()) + console.log("Starting time of sending component analysis request to Trustify DA backend server= " + new Date()) } opts[rhdaPackageManagerHeader.toUpperCase().replaceAll("-", "_")] = provided.ecosystem @@ -137,14 +137,14 @@ async function requestComponent(provider, manifest, url, opts = {}) { if (exRequestId) { console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId) } - console.log("Response body received from exhort server : " + EOL + EOL) + console.log("Response body received from Trustify DA backend server : " + EOL + EOL) console.log(JSON.stringify(result, null, 4)) - console.log("Ending time of sending component analysis request to exhort server= " + new Date()) + console.log("Ending time of sending component analysis request to Trustify DA backend server= " + new Date()) } } else { - throw new Error(`Got error response from exhort backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`) + throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`) } return Promise.resolve(result) @@ -191,13 +191,13 @@ async function requestImages(imageRefs, url, html = false, opts = {}) { if (exRequestId) { console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId) } - console.log("Response body received from exhort server : " + EOL + EOL) + console.log("Response body received from Trustify DA backend server : " + EOL + EOL) console.log(JSON.stringify(result, null, 4)) - console.log("Ending time of sending component analysis request to exhort server= " + new Date()) + console.log("Ending time of sending component analysis request to Trustify DA backend server= " + new Date()) } return result } else { - throw new Error(`Got error response from exhort backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`) + throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`) } } @@ -264,7 +264,7 @@ function getTokenHeaders(opts = {}) { setRhdaHeader(rhdaTelemetryId, headers, opts); if (process.env["TRUSTIFY_DA_DEBUG"] === "true") { - console.log("Headers Values to be sent to exhort:" + EOL) + console.log("Headers Values to be sent to Trustify DA backend:" + EOL) for (const headerKey in headers) { if (!headerKey.match(RegexNotToBeLogged)) { console.log(`${headerKey}: ${headers[headerKey]}`) diff --git a/src/cli.js b/src/cli.js index a453bf43..b105773a 100644 --- a/src/cli.js +++ b/src/cli.js @@ -5,7 +5,7 @@ import * as path from "path"; import yargs from 'yargs' import { hideBin } from 'yargs/helpers' -import exhort from './index.js' +import client from './index.js' // command for component analysis take manifest type and content @@ -22,7 +22,7 @@ const component = { ), handler: async args => { let manifestName = args['/path/to/manifest'] - let res = await exhort.componentAnalysis(manifestName) + let res = await client.componentAnalysis(manifestName) console.log(JSON.stringify(res, null, 2)) } } @@ -50,7 +50,7 @@ const validateToken = { let tokenValue = args['tokenValue'].trim() opts[`TRUSTIFY_DA_${tokenProvider}_TOKEN`] = tokenValue } - let res = await exhort.validateToken(opts) + let res = await client.validateToken(opts) console.log(res) } } @@ -87,7 +87,7 @@ const image = { } let html = args['html'] let summary = args['summary'] - let res = await exhort.imageAnalysis(imageRefs, html) + let res = await client.imageAnalysis(imageRefs, html) if(summary && !html) { let summaries = {} for (let [imageRef, report] of Object.entries(res)) { @@ -144,7 +144,7 @@ const stack = { let summary = args['summary'] let theProvidersSummary = new Map(); let theProvidersObject ={} - let res = await exhort.stackAnalysis(manifest, html) + let res = await client.stackAnalysis(manifest, html) if(summary) { for (let provider in res.providers ) { diff --git a/src/index.js b/src/index.js index cb19c279..9cdc0ba2 100644 --- a/src/index.js +++ b/src/index.js @@ -85,35 +85,27 @@ function readAndPrintVersionFromPackageJson() { } /** - * This function is used to determine exhort theUrl backend according to the following logic: - * If TRUSTIFY_DA_DEV_MODE = true, then take the value of the EXHORT BACKEND URL of dev/staging environment in such a way: - * take it as environment variable if exists, otherwise, take it from opts object if exists, otherwise, use the hardcoded default of DEV environment. - * If TRUSTIFY_DA_DEV_MODE = false , then select the production theUrl of EXHORT Backend, which is hardcoded. - * TRUSTIFY_DA_DEV_MODE evaluated in the following order and selected when it finds it first: + * This function is used to determine the Trustify DA backend URL. + * The TRUSTIFY_DA_BACKEND_URL is evaluated in the following order and selected when it finds it first: * 1. Environment Variable * 2. (key,value) from opts object - * 3. Default False ( points to production URL ) + * If TRUSTIFY_DA_BACKEND_URL is not set, the function will throw an error. * @param {{TRUSTIFY_DA_DEBUG?: string | undefined; TRUSTIFY_DA_BACKEND_URL?: string | undefined}} [opts={}] - * @return {string} - The selected exhort backend + * @return {string} - The selected Trustify DA backend URL + * @throws {Error} if TRUSTIFY_DA_BACKEND_URL is unset * @private */ -export function selectExhortBackend(opts = {}) { +export function selectTrustifyDABackend(opts = {}) { if (getCustom("TRUSTIFY_DA_DEBUG", "false", opts) === "true") { readAndPrintVersionFromPackageJson(); } - let url; - if (getCustom('TRUSTIFY_DA_DEV_MODE', 'false', opts) === 'true') { - url = getCustom('DEV_TRUSTIFY_DA_BACKEND_URL', undefined, opts); - } else { - url = getCustom('TRUSTIFY_DA_BACKEND_URL', undefined, opts); - } - + let url = getCustom('TRUSTIFY_DA_BACKEND_URL', null, opts); if (!url) { throw new Error(`TRUSTIFY_DA_BACKEND_URL is unset`) } - logOptionsAndEnvironmentsVariables("Chosen exhort backend URL:", url) + logOptionsAndEnvironmentsVariables("Chosen Trustify DA backend URL:", url) return url; } @@ -147,7 +139,7 @@ export function selectExhortBackend(opts = {}) { * or backend request failed */ async function stackAnalysis(manifest, html = false, opts = {}) { - const theUrl = selectExhortBackend(opts) + const theUrl = selectTrustifyDABackend(opts) fs.accessSync(manifest, fs.constants.R_OK) // throws error if file unreadable let provider = match(manifest, availableProviders) // throws error if no matching provider return await analysis.requestStack(provider, manifest, theUrl, html, opts) // throws error request sending failed @@ -161,7 +153,7 @@ async function stackAnalysis(manifest, html = false, opts = {}) { * @throws {Error} if no matching provider, failed to get create content, or backend request failed */ async function componentAnalysis(manifest, opts = {}) { - const theUrl = selectExhortBackend(opts) + const theUrl = selectTrustifyDABackend(opts) fs.accessSync(manifest, fs.constants.R_OK) opts["manifest-type"] = path.basename(manifest) let provider = match(manifest, availableProviders) // throws error if no matching provider @@ -197,7 +189,7 @@ async function componentAnalysis(manifest, opts = {}) { * or backend request failed */ async function imageAnalysis(imageRefs, html = false, opts = {}) { - const theUrl = selectExhortBackend(opts) + const theUrl = selectTrustifyDABackend(opts) return await analysis.requestImages(imageRefs, theUrl, html, opts) } @@ -208,6 +200,6 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) { * @throws {Error} if the backend request failed. */ async function validateToken(opts = {}) { - const theUrl = selectExhortBackend(opts) + const theUrl = selectTrustifyDABackend(opts) return await analysis.validateToken(theUrl, opts) // throws error request sending failed } diff --git a/src/providers/java_maven.js b/src/providers/java_maven.js index c7f43a9e..4e6d724b 100644 --- a/src/providers/java_maven.js +++ b/src/providers/java_maven.js @@ -88,7 +88,7 @@ export default class Java_maven extends Base_java { } // create dependency graph in a temp file - let tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'exhort_')) + let tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trustify_da_')) let tmpDepTree = path.join(tmpDir, 'mvn_deptree.txt') // build initial command (dot outputType is not available for verbose mode) let depTreeCmdArgs = ['-q', 'org.apache.maven.plugins:maven-dependency-plugin:3.6.0:tree', diff --git a/src/providers/python_controller.js b/src/providers/python_controller.js index 31170129..e89c770f 100644 --- a/src/providers/python_controller.js +++ b/src/providers/python_controller.js @@ -49,7 +49,7 @@ export default class Python_controller { } prepareEnvironment() { if(!this.realEnvironment) { - this.pythonEnvDir = path.join(path.sep, "tmp", "exhort_env_js") + this.pythonEnvDir = path.join(path.sep, "tmp", "trustify_da_env_js") try { invokeCommand(this.pathToPythonBin, ['-m', 'venv', this.pythonEnvDir]) } catch (error) { diff --git a/src/providers/python_pip.js b/src/providers/python_pip.js index 9edf7b6e..08d2a543 100644 --- a/src/providers/python_pip.js +++ b/src/providers/python_pip.js @@ -212,7 +212,7 @@ function createSbomStackAnalysis(manifest, opts = {}) { }) let requirementTxtContent = fs.readFileSync(manifest).toString(); handleIgnoredDependencies(requirementTxtContent, sbom, opts) - // In python there is no root component, then we must remove the dummy root we added, so the sbom json will be accepted by exhort backend + // In python there is no root component, then we must remove the dummy root we added, so the sbom json will be accepted by the DA backend // sbom.removeRootComponent() return sbom.getAsJsonString(opts) } @@ -237,7 +237,7 @@ function getSbomForComponentAnalysis(manifest, opts = {}) { }) let requirementTxtContent = fs.readFileSync(manifest).toString(); handleIgnoredDependencies(requirementTxtContent, sbom, opts) - // In python there is no root component, then we must remove the dummy root we added, so the sbom json will be accepted by exhort backend + // In python there is no root component, then we must remove the dummy root we added, so the sbom json will be accepted by the DA backend // sbom.removeRootComponent() return sbom.getAsJsonString(opts) } diff --git a/test/get-exhort-url.test.js b/test/get-exhort-url.test.js index 9fff03d3..ed850d8d 100644 --- a/test/get-exhort-url.test.js +++ b/test/get-exhort-url.test.js @@ -1,127 +1,65 @@ import { expect } from 'chai' -import { selectExhortBackend } from '../src/index.js' +import { selectTrustifyDABackend } from '../src/index.js' -const testProdUrl = 'https://exhort.example.com'; -const testDevUrl = 'https://dev.exhort.example.com'; +const testUrl = 'https://trustify-da.example.com'; +const testUrl2 = 'https://dev.trustify-da.example.com'; -suite('testing Select Exhort Backend function when TRUSTIFY_DA_DEV_MODE environment variable is True', () => { +suite('testing Select Trustify DA Backend function', () => { - test('When Dev Mode environment Variable= true, default DEV Exhort Backend Selected', () => { - let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'true' - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(testProdUrl) - expect(selectedUrl).to.be.equals(testDevUrl) - }); - - test('When Dev Mode environment Variable= true, and despite option Dev Mode = false, default DEV Exhort Backend Selected', () => { - let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'false' - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(testProdUrl) - expect(selectedUrl).to.be.equals(testDevUrl) + test('When TRUSTIFY_DA_BACKEND_URL is set in environment variable, should return that value', () => { + process.env['TRUSTIFY_DA_BACKEND_URL'] = testUrl; + let selectedUrl = selectTrustifyDABackend({}); + expect(selectedUrl).to.be.equals(testUrl); + delete process.env['TRUSTIFY_DA_BACKEND_URL']; }); - test('When Dev Mode environment Variable= true, And option DEV_TRUSTIFY_DA_BACKEND_URL contains some url route that client set, default DEV Exhort Backend Not Selected', () => { - const dummyRoute = 'http://dummy-exhort-route'; - delete process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] + test('When TRUSTIFY_DA_BACKEND_URL is set in opts (but not in env), should return that value', () => { + delete process.env['TRUSTIFY_DA_BACKEND_URL']; let testOpts = { - 'DEV_TRUSTIFY_DA_BACKEND_URL': dummyRoute - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).to.be.equals(dummyRoute) + 'TRUSTIFY_DA_BACKEND_URL': testUrl + }; + let selectedUrl = selectTrustifyDABackend(testOpts); + expect(selectedUrl).to.be.equals(testUrl); }); -}).beforeAll(() => { - process.env['TRUSTIFY_DA_DEV_MODE'] = 'true' - process.env['TRUSTIFY_DA_BACKEND_URL'] = testProdUrl - process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] = testDevUrl -}).afterAll(() => delete process.env['TRUSTIFY_DA_DEV_MODE']); - -suite('testing Select Exhort Backend function when TRUSTIFY_DA_DEV_MODE environment variable is false', () => { - - test('When Dev Mode environment Variable= true, default DEV Exhort Backend Selected', () => { - + test('When TRUSTIFY_DA_BACKEND_URL is set in both environment and opts, environment variable should take precedence', () => { + process.env['TRUSTIFY_DA_BACKEND_URL'] = testUrl; let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'false' - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(testDevUrl) - expect(selectedUrl).to.be.equals(testProdUrl) + 'TRUSTIFY_DA_BACKEND_URL': testUrl2 + }; + let selectedUrl = selectTrustifyDABackend(testOpts); + expect(selectedUrl).to.be.equals(testUrl); + delete process.env['TRUSTIFY_DA_BACKEND_URL']; }); - test('When Dev Mode environment Variable= false, and despite option Dev Mode = true, default Exhort Backend Selected (production)', () => { - let dummyRoute = 'http://dummy-dev-route-exhort' - let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'true', - 'DEV_TRUSTIFY_DA_BACKEND_URL': dummyRoute - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(dummyRoute) - expect(selectedUrl).to.be.equals(testProdUrl) + test('When TRUSTIFY_DA_BACKEND_URL is not set, should throw error', () => { + delete process.env['TRUSTIFY_DA_BACKEND_URL']; + expect(() => selectTrustifyDABackend({})).to.throw('TRUSTIFY_DA_BACKEND_URL is unset'); }); - test('When Dev Mode environment Variable= false, environment variable DEV_TRUSTIFY_DA_BACKEND_URL=dummy-url, option TRUSTIFY_DA_DEV_MODE=true, default Exhort Backend Selected anyway', () => { - const dummyRoute = 'http://dummy-url' - process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] = dummyRoute - let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'true', - 'DEV_TRUSTIFY_DA_BACKEND_URL': dummyRoute - } - let selectedUrl = selectExhortBackend(testOpts); - delete process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] - expect(selectedUrl).not.to.be.equals(dummyRoute) - expect(selectedUrl).to.be.equals(testProdUrl) - }); - -}).beforeAll(() => { - process.env['TRUSTIFY_DA_DEV_MODE'] = 'false' - process.env['TRUSTIFY_DA_BACKEND_URL'] = testProdUrl - process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] = testDevUrl -}).afterAll(() => delete process.env['TRUSTIFY_DA_DEV_MODE']); - -suite('testing Select Exhort Backend function when TRUSTIFY_DA_DEV_MODE environment variable is not set', () => { - - test('When Dev Mode Option = false, default Exhort Backend Selected (production)', () => { - - let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'false' - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(testDevUrl) - expect(selectedUrl).to.be.equals(testProdUrl) + test('When TRUSTIFY_DA_BACKEND_URL is empty string in environment, should throw error', () => { + process.env['TRUSTIFY_DA_BACKEND_URL'] = ''; + expect(() => selectTrustifyDABackend({})).to.throw('TRUSTIFY_DA_BACKEND_URL is unset'); + delete process.env['TRUSTIFY_DA_BACKEND_URL']; }); - test('When Dev Mode Option Variable= true, default dev Exhort Backend Selected', () => { + test('When TRUSTIFY_DA_BACKEND_URL is empty string in opts, should throw error', () => { + delete process.env['TRUSTIFY_DA_BACKEND_URL']; let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'true' - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(testProdUrl) - expect(selectedUrl).to.be.equals(testDevUrl) + 'TRUSTIFY_DA_BACKEND_URL': '' + }; + expect(() => selectTrustifyDABackend(testOpts)).to.throw('TRUSTIFY_DA_BACKEND_URL is unset'); }); - test('When Dev Mode option = true, option DEV_TRUSTIFY_DA_BACKEND_URL=some dummy-url, then some dummy-url Selected', () => { - let dummyRoute = 'http://dummy-dev-route-exhort' - process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] = dummyRoute + test('When TRUSTIFY_DA_BACKEND_URL is null in opts, should throw error', () => { + delete process.env['TRUSTIFY_DA_BACKEND_URL']; let testOpts = { - 'TRUSTIFY_DA_DEV_MODE': 'true', - 'DEV_TRUSTIFY_DA_BACKEND_URL': dummyRoute - } - let selectedUrl = selectExhortBackend(testOpts); - expect(selectedUrl).not.to.be.equals(testProdUrl) - expect(selectedUrl).to.be.equals(dummyRoute) - delete process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] + 'TRUSTIFY_DA_BACKEND_URL': null + }; + expect(() => selectTrustifyDABackend(testOpts)).to.throw('TRUSTIFY_DA_BACKEND_URL is unset'); }); - test('When Nothing set, throw error', () => { - let selectedUrl = selectExhortBackend({}); - expect(selectedUrl).to.be.equals(testProdUrl) - }) -}).beforeAll(() => { - process.env['TRUSTIFY_DA_BACKEND_URL'] = testProdUrl; - process.env['DEV_TRUSTIFY_DA_BACKEND_URL'] = testDevUrl +}).afterAll(() => { + delete process.env['TRUSTIFY_DA_BACKEND_URL']; }); diff --git a/test/it/end-to-end.js b/test/it/end-to-end.js index 946eb463..8fad6cf7 100644 --- a/test/it/end-to-end.js +++ b/test/it/end-to-end.js @@ -58,7 +58,7 @@ suite('Integration Tests', () => { let providers = ["rhtpa"] providers.forEach(provider => expect(extractTotalsGeneralOrFromProvider(providedDataForStack, provider)).greaterThan(0)) // TODO: if sources doesn't exist, add "scanned" instead - // python transitive count for stack analysis is awaiting fix in exhort backend + // python transitive count for stack analysis is awaiting fix in the DA backend if(packageManager !== "pip") { expect(providedDataForStack.scanned.transitive).greaterThan(0) }