Skip to content

Commit

Permalink
feat: attach to request rhda-token if exists in env/option (#52)
Browse files Browse the repository at this point in the history
* feat: attach to request rhda-token if exists in env/option

* feat: attach to request header rhda-source if set by client

* feat: attached to request header rhda-operation type

* chore: add a lot of useful debug logs

* ci: add no-warnings flag to nodeJS binary , when invoking integration tests


https://issues.redhat.com/browse/APPENG-2000

---------

Signed-off-by: Zvi Grinberg <[email protected]>
  • Loading branch information
zvigrinberg authored Oct 5, 2023
1 parent 2735816 commit 34cb2dd
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 9 deletions.
10 changes: 5 additions & 5 deletions integration/run_its.sh
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ mkdir -p ./responses
#### JAVA MAVEN
echo "RUNNING JavaScript integration test for Stack Analysis report in Html for Java Maven"

node testers/javascript/index.js stack scenarios/maven/pom.xml true &> ./responses/stack.html
node --no-warnings testers/javascript/index.js stack scenarios/maven/pom.xml true &> ./responses/stack.html

if [ "$?" -ne 0 ]; then
echo "- FAILED , return $RC from invocation"
Expand All @@ -113,7 +113,7 @@ fi
echo "- PASSED"

echo "RUNNING JavaScript integration test for Stack Analysis report in Json for Java Maven"
node testers/javascript/index.js stack scenarios/maven/pom.xml false &> ./responses/stack.json
node --no-warnings testers/javascript/index.js stack scenarios/maven/pom.xml false &> ./responses/stack.json

if [ "$?" -ne 0 ]; then
echo "- FAILED , return $RC from invocation"
Expand All @@ -129,7 +129,7 @@ StatusCode=$(jq '.summary.providerStatuses[] | select(.provider== "snyk") ' ./re
matchConstant "200" "$StatusCode"

echo "RUNNING JavaScript integration test for Component Analysis report for Java Maven"
eval "node testers/javascript/index.js component pom.xml '$(<scenarios/maven/pom.xml)'" &> ./responses/component.json
eval "node --no-warnings testers/javascript/index.js component pom.xml '$(<scenarios/maven/pom.xml)'" &> ./responses/component.json

if [ "$?" -ne 0 ]; then
echo "- FAILED , return $RC from invocation"
Expand All @@ -144,11 +144,11 @@ StatusCode=$(jq '.summary.providerStatuses[] | select(.provider== "snyk") ' ./re
matchConstant "200" "$StatusCode"

echo "RUNNING JavaScript integration test for Validate Token Function With wrong token, expecting getting 401 http status code "
answerAboutToken=$(node testers/javascript/index.js validateToken veryBadToken)
answerAboutToken=$(node --no-warnings testers/javascript/index.js validateToken veryBadToken)
matchConstant "401" "$answerAboutToken"

echo "RUNNING JavaScript integration test for Validate Token Function With no token at all, Expecting getting 400 http status code"
answerAboutToken=$(node testers/javascript/index.js validateToken )
answerAboutToken=$(node --no-warnings testers/javascript/index.js validateToken )
matchConstant "400" "$answerAboutToken"

cleanup 0
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,6 @@
"json",
"text"
]
}
},
"eslintIgnore": ["index.js"]
}
30 changes: 29 additions & 1 deletion src/analysis.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import {getCustom} from "./tools.js";
import {EOL} from "os";
import {RegexNotToBeLogged, getCustom} from "./tools.js";

export default { requestComponent, requestStack, validateToken }

const rhdaTokenHeader = "rhda-token";
const rhdaSourceHeader = "rhda-source"
const rhdaOperationTypeHeader = "rhda-operation-type"

/**
* Send a stack analysis request and get the report as 'text/html' or 'application/json'.
* @param {import('./provider').Provider} provider - the provided data for constructing the request
Expand All @@ -13,6 +18,7 @@ export default { requestComponent, requestStack, validateToken }
*/
async function requestStack(provider, manifest, url, html = false, opts = {}) {
let provided = provider.provideStack(manifest, opts) // throws error if content providing failed
opts[rhdaOperationTypeHeader.toUpperCase().replaceAll("-","_")] = "stack-analysis"
let resp = await fetch(`${url}/api/v3/analysis`, {
method: 'POST',
headers: {
Expand All @@ -35,6 +41,7 @@ async function requestStack(provider, manifest, url, html = false, opts = {}) {
*/
async function requestComponent(provider, data, url, opts = {}) {
let provided = provider.provideComponent(data, opts) // throws error if content providing failed
opts[rhdaOperationTypeHeader.toUpperCase().replaceAll("-","_")] = "component-analysis"
let resp = await fetch(`${url}/api/v3/analysis`, {
method: 'POST',
headers: {
Expand Down Expand Up @@ -64,6 +71,14 @@ async function validateToken(url, opts = {}) {
return resp.status
}


function setRhdaHeader(headerName,headers,opts) {
let rhdaHeaderValue = getCustom(headerName.toUpperCase().replaceAll("-", "_"), null, opts);
if (rhdaHeaderValue) {
headers[headerName] = rhdaHeaderValue
}
}

/**
* Utility function for fetching vendor tokens
* @param {{}} [opts={}] - optional various options to pass along the application
Expand All @@ -78,5 +93,18 @@ function getTokenHeaders(opts = {}) {
headers[`ex-${vendor}-token`] = token
}
})
setRhdaHeader(rhdaTokenHeader,headers, opts);
setRhdaHeader(rhdaSourceHeader,headers, opts);
setRhdaHeader(rhdaOperationTypeHeader, headers,opts);
if (process.env["EXHORT_DEBUG"] === "true")
{
console.log("Headers Values to be sent to exhort:" + EOL)
for (const headerKey in headers) {
if(!headerKey.match(RegexNotToBeLogged))
{
console.log(`${headerKey}: ${headers[headerKey]}`)
}
}
}
return headers
}
13 changes: 13 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {EOL} from "os";
import { availableProviders, match } from './provider.js'
import {AnalysisReport} from '../generated/backend/AnalysisReport.js'
import analysis from './analysis.js'
import fs from 'node:fs'
import {getCustom} from "./tools.js";
import PackageJson from '../package.json' assert {type: 'json'};

export default { AnalysisReport, componentAnalysis, stackAnalysis, validateToken }

Expand All @@ -12,6 +14,12 @@ export const exhortDevDefaultUrl = 'http://alpha-exhort.apps.sssc-cl01.appeng.rh
export const exhortDefaultUrl = "https://rhda.rhcloud.com";


function logOptionsAndEnvironmentsVariables(alongsideText,valueToBePrinted) {
if (process.env["EXHORT_DEBUG"] === "true") {
console.log(`${alongsideText}: ${valueToBePrinted} ${EOL}`)
}

}

/** This function is used to determine exhort url backend according to the following logic:
* If EXHORT_DEV_MODE = true, then take the value of the EXHORT BACKEND URL of dev/staging environment in such a way:
Expand All @@ -26,6 +34,8 @@ export const exhortDefaultUrl = "https://rhda.rhcloud.com";
* @private
*/
function selectExhortBackend(opts= {}) {

logOptionsAndEnvironmentsVariables("exhort-javascript-api analysis started, version: ",PackageJson.version)
let result
let exhortDevModeBundled = "false"
let exhortDevMode = getCustom("EXHORT_DEV_MODE",exhortDevModeBundled,opts)
Expand All @@ -36,6 +46,9 @@ function selectExhortBackend(opts= {}) {
{
result = exhortDefaultUrl
}

logOptionsAndEnvironmentsVariables("Chosen exhort backend URL:",result)

return result;
}

Expand Down
32 changes: 32 additions & 0 deletions src/tools.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
import {EOL} from "os";


export const RegexNotToBeLogged = /EXHORT_.*_TOKEN|ex-.*-token/
/**
*
* @param {string} key to log its value from environment variables and from opts, if it exists
* @param {{}} [opts={}] different options of application, if key in it, log it.
* @param {string }defValue default value of key in case there is no option and environment variable values for key
*/
export function logValueFromObjects(key,opts, defValue) {
if(key in opts) {
console.log(`value of option with key ${key} = ${opts[key]} ${EOL}`)
}
else
{
console.log(`key ${key} doesn't exists on opts object ${EOL}`)
}
if(key in process.env) {
console.log(`value of environment variable ${key} = ${process.env[key]} ${EOL}`)
}
else
{
console.log(`environment variable ${key} doesn't exists ${EOL}`)
}
console.log(`default value for ${key} = ${defValue} ${EOL}`)
}

/**
* Utility function will return the value for key from the environment variables,
* if not present will return the value for key from the opts objects only if it's a string,
Expand All @@ -9,6 +37,10 @@
* default supplied
*/
export function getCustom(key, def = null, opts = {}) {
if (process.env["EXHORT_DEBUG"] === "true" && !key.match(RegexNotToBeLogged))
{
logValueFromObjects(key,opts,def)
}
return key in process.env ? process.env[key] : key in opts && typeof opts[key] === 'string' ? opts[key] : def
}

Expand Down
5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"include": ["src/**/*", "generated/backend/**/*"],
"include": ["src/**/*", "generated/backend/**/*","./package.json"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"allowJs": true,
Expand All @@ -17,6 +17,7 @@
"types": ["node"],
"module": "esnext",
"outDir": "dist",
"target": "esnext"
"target": "esnext",
"resolveJsonModule": true
}
}

0 comments on commit 34cb2dd

Please sign in to comment.