Files
shields/services/test-helpers.js
T
jNulljandPierre-Yves Bigourdan fcfbf895c1 Improve our approach for testing auth (part 2) - basicAuth (#9983)
* improve stackexchange auth testing

Change auth tests to include all shields of the base class.
The code is formated to be used in more general cases and increases code reuseability.

* Remove dummy auth test

We already test all existing classes, no need for a dummy

* Add getBadgeExampleCall to test-helpers

Add getBadgeExampleCall to extract the first OpenAPI example then reformat it for service invoke function.

* Use getBadgeExampleCall in stackexchange-base tests

* Fix getBadgeExampleCall Errors

* Add testAuth to test-helpers

Add the testAuth function which tests auth of a service (badge) using a provided dummy response.

* Refactor stackexchange-base.spec.js to use testAuth from test-helpers

* Split stackexchange-base.spec into per service test file

* Add all auth methods to testAuth

Add all auth methods used to testAuth to be generic and used by all services.
Add helper functions to make testAuth more readable

* Handle non-default bearer and api headers

* Add discord.spec.js as first attempt for bearer auth

* Fix basic auth user

* Add dynamic authorizedOrigins

* Add header optional argument

* Add obs as basicAuth example

* Use apiHeaderKey and bearerHeaderKey function params

Use apiHeaderKey & bearerHeaderKey as function params rather then extracting them with regex from function strings.

Those options are now part of an options object param joined with the contentType that replaces header.

header was originaly added for setting content type of the reply, so it makes more sense to directly set the content type

* Remove old comment

* Allow any pass & user key for QueryStringAuth

Before this commit the QueryStringAuth would only work for the key of stackexchange.
This commit makes the testAuth function generic and allows passing user and pass keys.

* Add auth test for PepyDownloads

* Fix wrong header for jwt login

Might set wrong header for jwt login request.
This commit fixes that.

* Support multiple authOrigins in testAuth

Some services might have more then one authOrigin.
This commit makes sure we test for redundent authOrigins as well as support requests to them if needed.

* Add docker-automated auth test

* Fix JwtAuth testing by introducing mandatory jwtLoginEndpoint

Prior to this change, JwtAuth testing would lead to erros due to the absence of a specified login endpoint,
Nock would be dumplicated for both login and non login hosts and indicate a missing request.

This commit enforces the requirement for a new jwtLoginEndpoint argument when testing JwtAuth.
The argument seperates the endpoint nock scope from the behavior of the request nock.

* Fix type test in generateFakeConfig

* Add exampleOverride to testAuth

Introduce `exampleOverride` to test authentication scenarios.
Allows providing custom examples for testAuth via an object.
Simulates service requests that trigger desiered condition paths in tests.

* Add authOverride to testAuth

Some classes can change the auth based on badge inputs.
This parameter allows the flexability of overriding the default auth for testing those cases.

* Add configOverride to testAuth

Some tests might require non default config for cases where these are set.
This allows creating tests for those cases.

* Fix example params by split into path and query

Splits testAuth example params into path and query params.
Introduce paramType to getBadgeExampleCall

* Refactor BitbucketPullRequest for testAuth

Refactor to add auth static properties.
for better integration with testAuth.

Refactor bitbucketpullrequest for testAuth

* Refactor: use testAuth for BitbucketPullRequest

* Fix BitbucketPullRequest tests using authOverride

* Add auth testing for jenkins services with testAuth

* Add auth testing for Jira services with testAuth

* Add auth testing for Nexus services with testAuth

* Improve error handling in getServiceClassAuthOrigin

Enhance reliability by throwing a TypeError when a service key definition is missing.
It's common for a key to be missing and might require the developer that writes tests to provide a fake on that fits the examples used.

Key changes:
- Added a check for missing service key definitions in getServiceClassAuthOrigin.
- Throws a TypeError with a clear message if the key is not found.
- Guides devs to use an override if needed which is often.

* Fix edge case in testAuth for user only auth

Addresses a scenario where generateFakeConfig/testAuth would fail for classes using auth.userKey without auth.passKey.
Ensures proper handling of user-specific authentication even if a password key is not present.
Throws a TypeError only when both fakeKey and fakeUser are missing.
Better fit for AuthHelper behivor.

* Add option to not import openApi example in testAuth

Added for services without openApi examples.
Dev can use example override to add example inputs in those cases.

* Add auth testing for Sonar services with testAuth

* Add auth testing for SymfonyInsight services with testAuth

* Refactor TeamCity auth tests for use of testAuth

* Refactor testAuth function to handle defaultToEmptyStringForUser auth option

* Add support for multiple requests in testAuth function

Some services might have more then one request to auth with the server for the same shield.
This commit adds support for those requests in testAuth using the new multipleRequests option.

* Add auth testing for AzureDevOps services with testAuth

* Fix async mocha tests

Missing return for async mocha tests caused the tests to run async and throw errors of one test in another.
This commit makes sure all testAuth tests return a promise to mocha for it to await.

* Remove ignoreOpenApiExample option in testAuth function

The `ignoreOpenApiExample` option in the `testAuth` function is no longer needed and has been removed. This option was used to ignore OpenAPI examples for classes without OpenAPI, but it is no longer necessary as the function now handles this case correctly.
BaseService defines by dafault empty object for openApi so if nothing is set we expect empty obj.
Warn devs about missing openApi as openApi is standard for services now.

* handle extraction of openApi boolean examples

Improve authTest by handeling boolean example extractions.
Remove example override not needed after this change.

* Use static headers in base service classes and remove contentType option from testAuth

Refactor the base service classes (BaseGraphqlService, BaseJsonService, BaseSvgScrapingService, BaseTomlService, BaseXmlService, BaseYamlService) to use static headers for access from other function to header types.
Remove testAuth contentType option and use the new headers veriable to extract headers insted.

* Remove contentType option tests using testAuth

This option is removed

* Update jenkinsCoverage response

Example changed at 62ed7c3a27
The new example schema differ from old one
This caused test to fail
Update example response to fit new schema

* remove BitbucketPullReuqest tests

remove for adding these changes in a later PR.
this test adds the authOverride we try to get rid of.
This blocks testAuth development and is planned for a later time.

* fix: fix wrong exception message & check order

* fix typo

Co-authored-by: Pierre-Yves Bigourdan <10694593+PyvesB@users.noreply.github.com>

* fix typo cleanup -> clean up

Co-authored-by: Pierre-Yves Bigourdan <10694593+PyvesB@users.noreply.github.com>

* fix exception error text 'object' -> 'boolean'

Co-authored-by: Pierre-Yves Bigourdan <10694593+PyvesB@users.noreply.github.com>

* fix: return merged authorizedOrigins in getServiceClassAuthOrigin

* update JenkinsTests origin

Was outdated after merging with master.
This commit fixes origin test to openapi example.

* fix(docs): docstring origins type

* fix typo

* fix(auth): reduce strictness for JwtAuth test

Avoid exact body match requirement.
We are only intrested in username and password values to match, not exact one to one object.

---------

Co-authored-by: Pierre-Yves Bigourdan <10694593+PyvesB@users.noreply.github.com>
2026-01-11 19:32:38 +00:00

441 lines
14 KiB
JavaScript

import _ from 'lodash'
import dayjs from 'dayjs'
import { expect } from 'chai'
import nock from 'nock'
import config from 'config'
import { fetch } from '../core/base-service/got.js'
import BaseService from '../core/base-service/base.js'
const runnerConfig = config.util.toObject()
function cleanUpNockAfterEach() {
afterEach(function () {
nock.restore()
nock.cleanAll()
nock.enableNetConnect()
nock.activate()
})
}
function noToken(serviceClass) {
let hasLogged = false
return () => {
const userKey = serviceClass.auth.userKey
const passKey = serviceClass.auth.passKey
const noToken =
(userKey && !runnerConfig.private[userKey]) ||
(passKey && !runnerConfig.private[passKey])
if (noToken && !hasLogged) {
console.warn(
`${serviceClass.name}: no credentials configured, tests for this service will be skipped. Add credentials in local.yml to run them.`,
)
hasLogged = true
}
return noToken
}
}
/**
* Retrieves an example set of parameters for invoking a service class using OpenAPI example of that class.
*
* @param {BaseService} serviceClass The service class containing OpenAPI specifications.
* @param {'path'|'query'} paramType The type of params to extract, may be path params or query params.
* @returns {object} An object with call params to use with a service invoke of the first OpenAPI example.
* @throws {TypeError} - Throws a TypeError if the input `serviceClass` is not an instance of BaseService,
* or if it lacks the expected structure.
*
* @example
* // Example usage:
* const example = getBadgeExampleCall(StackExchangeReputation)
* console.log(example)
* // Output: { stackexchangesite: 'stackoverflow', query: '123' }
* StackExchangeReputation.invoke(defaultContext, config, example)
*/
function getBadgeExampleCall(serviceClass, paramType) {
if (!(serviceClass.prototype instanceof BaseService)) {
throw new TypeError(
'Invalid serviceClass: Must be an instance of BaseService.',
)
}
if (Object.keys(serviceClass.openApi).length === 0) {
console.warn(
`Missing OpenAPI in service class ${serviceClass.name}. Make sure to use exampleOverride in testAuth.`,
)
return {}
}
if (!['path', 'query'].includes(paramType)) {
throw new TypeError('Invalid paramType: Must be path or query.')
}
const firstOpenapiPath = Object.keys(serviceClass.openApi)[0]
const firstOpenapiExampleParams =
serviceClass.openApi[firstOpenapiPath].get.parameters
if (!Array.isArray(firstOpenapiExampleParams)) {
throw new TypeError(
`Missing or invalid OpenAPI examples in ${serviceClass.name}.`,
)
}
// reformat structure for serviceClass.invoke
const exampleInvokeParams = firstOpenapiExampleParams.reduce((acc, obj) => {
if (obj.in === paramType) {
let example = obj.example
if (obj?.schema?.type === 'boolean') {
example = example || ''
}
acc[obj.name] = example
}
return acc
}, {})
return exampleInvokeParams
}
/**
* Generates a configuration object with a fake key based on the provided class.
* For use in auth tests where a config with a test key is required.
*
* @param {BaseService} serviceClass - The class to generate configuration for.
* @param {string} fakeKey - The fake key to be used in the configuration.
* @param {string} fakeUser - Optional, The fake user to be used in the configuration.
* @param {string[]} fakeauthorizedOrigins - authorizedOrigins to add to config.
* @param {object} authOverride Return result with overrid params.
* @returns {object} - The configuration object.
* @throws {TypeError} - Throws an error if the input is not a class.
*/
function generateFakeConfig(
serviceClass,
fakeKey,
fakeUser,
fakeauthorizedOrigins,
authOverride,
) {
if (
!serviceClass ||
!serviceClass.prototype ||
!(serviceClass.prototype instanceof BaseService)
) {
throw new TypeError(
'Invalid serviceClass: Must be an instance of BaseService.',
)
}
if (!fakeKey && !fakeUser) {
throw new TypeError('Must provide at least one: fakeKey or fakeUser.')
}
if (!fakeauthorizedOrigins || !Array.isArray(fakeauthorizedOrigins)) {
throw new TypeError('Invalid fakeauthorizedOrigins: Must be an array.')
}
const auth = { ...serviceClass.auth, ...authOverride }
if (Object.keys(auth).length === 0) {
throw new Error(`Auth empty for ${serviceClass.name}.`)
}
if (fakeKey && typeof fakeKey !== 'string') {
throw new Error('Invalid fakeKey: Must be a String.')
}
if (fakeKey && !auth.passKey) {
throw new Error(`Missing auth.passKey for ${serviceClass.name}.`)
}
// Extract the passKey property from auth, or use a default if not present
const passKeyProperty = auth.passKey ? auth.passKey : undefined
if (fakeUser && typeof fakeUser !== 'string') {
throw new TypeError('Invalid fakeUser: Must be a String.')
}
if (fakeUser && !auth.userKey) {
throw new Error(`Missing auth.userKey for ${serviceClass.name}.`)
}
const passUserProperty = auth.userKey ? auth.userKey : undefined
// Build and return the configuration object with the fake key
return {
public: {
services: {
[auth.serviceKey]: {
authorizedOrigins: fakeauthorizedOrigins,
},
},
},
private: {
[passKeyProperty]: fakeKey,
[passUserProperty]: fakeUser,
},
}
}
/**
* Returns the first auth origin found for a provided service class.
*
* @param {BaseService} serviceClass The service class to find the authorized origins.
* @param {object} authOverride Return result with overridden params.
* @param {object} configOverride - Override the config.
* @throws {TypeError} - Throws a TypeError if the input `serviceClass` is not an instance of BaseService.
* @returns {string[]} First auth origin found.
*
* @example
* // Example usage:
* getServiceClassAuthOrigin(Obs)
* // outputs ['https://api.opensuse.org']
*/
function getServiceClassAuthOrigin(serviceClass, authOverride, configOverride) {
if (
!serviceClass ||
!serviceClass.prototype ||
!(serviceClass.prototype instanceof BaseService)
) {
throw new TypeError(
`Invalid serviceClass ${serviceClass}: Must be an instance of BaseService.`,
)
}
const auth = { ...serviceClass.auth, ...authOverride }
if (auth.authorizedOrigins) {
return auth.authorizedOrigins
} else {
const mergedConfig = _.merge(runnerConfig, configOverride)
if (!mergedConfig.public.services[auth.serviceKey]) {
throw new TypeError(
`Missing service key definition for ${auth.serviceKey}: Use an override if applicable.`,
)
}
return [mergedConfig.public.services[auth.serviceKey].authorizedOrigins]
}
}
/**
* Generate a fake JWT Token valid for 1 hour for use in testing.
*
* @returns {string} Fake JWT Token valid for 1 hour.
*/
function fakeJwtToken() {
const fakeJwtPayload = { exp: dayjs().add(1, 'hours').unix() }
const fakeJwtPayloadJsonString = JSON.stringify(fakeJwtPayload)
const fakeJwtPayloadBase64 = Buffer.from(fakeJwtPayloadJsonString).toString(
'base64',
)
const jwtToken = `FakeHeader.${fakeJwtPayloadBase64}.fakeSignature`
return jwtToken
}
/**
* Test authentication of a badge for it's first OpenAPI example using a provided dummyResponse and authentication method.
*
* @param {BaseService} serviceClass The service class tested.
* @param {'BasicAuth'|'ApiKeyHeader'|'BearerAuthHeader'|'QueryStringAuth'|'JwtAuth'} authMethod The auth method of the tested service class.
* @param {object} dummyResponse An object containing the dummy response by the server.
* @param {object} options - Additional options for non default keys and content-type of the dummy response.
* @param {string} options.apiHeaderKey - Non default header for ApiKeyHeader auth.
* @param {string} options.bearerHeaderKey - Non default bearer header prefix for BearerAuthHeader.
* @param {string} options.queryUserKey - QueryStringAuth user key.
* @param {string} options.queryPassKey - QueryStringAuth pass key.
* @param {string} options.jwtLoginEndpoint - jwtAuth Login endpoint.
* @param {object} options.exampleOverride - Override example params in test.
* @param {object} options.authOverride - Override class auth params.
* @param {object} options.configOverride - Override the config for this test.
* @param {boolean} options.multipleRequests - For classes that require multiple requests to complete the test.
* @throws {TypeError} - Throws a TypeError if the input `serviceClass` is not an instance of BaseService,
* or if `serviceClass` is missing authorizedOrigins.
*
* @example
* // Example usage:
* testAuth(StackExchangeReputation, QueryStringAuth, { items: [{ reputation: 8 }] })
*/
async function testAuth(serviceClass, authMethod, dummyResponse, options = {}) {
if (!(serviceClass.prototype instanceof BaseService)) {
throw new TypeError(
'Invalid serviceClass: Must be an instance of BaseService.',
)
}
const {
apiHeaderKey = 'x-api-key',
bearerHeaderKey = 'Bearer',
queryUserKey,
queryPassKey,
jwtLoginEndpoint,
exampleOverride = {},
authOverride,
configOverride,
multipleRequests = false,
} = options
const header = serviceClass.headers
? { 'Content-Type': serviceClass.headers.Accept.split(', ')[0] }
: undefined
if (!apiHeaderKey || typeof apiHeaderKey !== 'string') {
throw new TypeError('Invalid apiHeaderKey: Must be a String.')
}
if (!bearerHeaderKey || typeof bearerHeaderKey !== 'string') {
throw new TypeError('Invalid bearerHeaderKey: Must be a String.')
}
if (typeof exampleOverride !== 'object') {
throw new TypeError('Invalid exampleOverride: Must be an Object.')
}
if (authOverride && typeof authOverride !== 'object') {
throw new TypeError('Invalid authOverride: Must be an Object.')
}
if (configOverride && typeof configOverride !== 'object') {
throw new TypeError('Invalid configOverride: Must be an Object.')
}
if (multipleRequests && typeof multipleRequests !== 'boolean') {
throw new TypeError('Invalid multipleRequests: Must be a boolean.')
}
if (!multipleRequests) {
cleanUpNockAfterEach()
}
const auth = { ...serviceClass.auth, ...authOverride }
const fakeUser = auth.userKey
? 'fake-user'
: auth.defaultToEmptyStringForUser
? ''
: undefined
const fakeSecret = auth.passKey ? 'fake-secret' : undefined
if (!fakeUser && !fakeSecret) {
throw new TypeError(
`Missing auth pass/user for ${serviceClass.name}. At least one is required.`,
)
}
const authOrigins = getServiceClassAuthOrigin(
serviceClass,
authOverride,
configOverride,
)
const config = generateFakeConfig(
serviceClass,
fakeSecret,
fakeUser,
authOrigins,
authOverride,
)
const exampleInvokePathParams = getBadgeExampleCall(serviceClass, 'path')
const exampleInvokeQueryParams = getBadgeExampleCall(serviceClass, 'query')
if (options && typeof options !== 'object') {
throw new TypeError('Invalid options: Must be an object.')
}
if (!authOrigins) {
throw new TypeError(`Missing authorizedOrigins for ${serviceClass.name}.`)
}
const jwtToken = authMethod === 'JwtAuth' ? fakeJwtToken() : undefined
const scopeArr = []
authOrigins.forEach(authOrigin => {
const scope = nock(authOrigin)
if (multipleRequests) {
scope.persist()
}
scopeArr.push(scope)
switch (authMethod) {
case 'BasicAuth':
scope
.get(/.*/)
.basicAuth({ user: fakeUser, pass: fakeSecret })
.reply(200, dummyResponse, header)
break
case 'ApiKeyHeader':
scope
.get(/.*/)
.matchHeader(apiHeaderKey, fakeSecret)
.reply(200, dummyResponse, header)
break
case 'BearerAuthHeader':
scope
.get(/.*/)
.matchHeader('Authorization', `${bearerHeaderKey} ${fakeSecret}`)
.reply(200, dummyResponse, header)
break
case 'QueryStringAuth':
if (!queryPassKey || typeof queryPassKey !== 'string') {
throw new TypeError('Invalid queryPassKey: Must be a String.')
}
scope
.get(/.*/)
.query(queryObject => {
if (queryObject[queryPassKey] !== fakeSecret) {
return false
}
if (queryUserKey) {
if (typeof queryUserKey !== 'string') {
throw new TypeError('Invalid queryUserKey: Must be a String.')
}
if (queryObject[queryUserKey] !== fakeUser) {
return false
}
}
return true
})
.reply(200, dummyResponse, header)
break
case 'JwtAuth': {
if (!jwtLoginEndpoint || typeof jwtLoginEndpoint !== 'string') {
throw new TypeError('Invalid jwtLoginEndpoint: Must be a String.')
}
if (jwtLoginEndpoint.startsWith(authOrigin)) {
scope
.post(/.*/, body => {
if (typeof body === 'object') {
return (
body.username === fakeUser && body.password === fakeSecret
)
}
if (typeof body === 'string') {
return (
body.includes(`username=${encodeURIComponent(fakeUser)}`) &&
body.includes(`password=${encodeURIComponent(fakeSecret)}`)
)
}
return false
})
.reply(200, { token: jwtToken })
} else {
scope
.get(/.*/)
.matchHeader('Authorization', `Bearer ${jwtToken}`)
.reply(200, dummyResponse, header)
}
break
}
default:
throw new TypeError(`Unkown auth method for ${serviceClass.name}.`)
}
})
expect(
await serviceClass.invoke(
defaultContext,
_.merge(config, configOverride),
{
...exampleInvokePathParams,
...exampleOverride,
},
{
...exampleInvokeQueryParams,
...exampleOverride,
},
),
).to.not.have.property('isError')
// clean up persistance if we have multiple requests
if (multipleRequests) {
scopeArr.forEach(scope => scope.persist(false))
nock.restore()
nock.cleanAll()
nock.enableNetConnect()
nock.activate()
}
// if we get 'Mocks not yet satisfied' we have redundent authOrigins or we are missing a critical request
scopeArr.forEach(scope => scope.done())
}
const defaultContext = { requestFetcher: fetch }
export {
cleanUpNockAfterEach,
noToken,
getBadgeExampleCall,
testAuth,
defaultContext,
}