Convert axios auth to basic auth header in the axios util

This commit is contained in:
Christos Nasikas 2024-05-10 19:36:53 +03:00
parent 23aa5af563
commit 94753a7342
2 changed files with 62 additions and 2 deletions

View file

@ -339,6 +339,55 @@ describe('request', () => {
`"Do not use \\"baseURL\\" in the creation of your axios instance because you will mostly break proxy"`
);
});
test('it converts the auth property to basic auth header', async () => {
await request({
axios,
url: '/test',
logger,
configurationUtilities,
auth: { username: 'username', password: 'password' },
});
expect(axiosMock).toHaveBeenCalledWith('/test', {
method: 'get',
httpAgent: undefined,
httpsAgent: expect.any(HttpsAgent),
proxy: false,
maxContentLength: 1000000,
timeout: 360000,
headers: { Authorization: `Basic ${Buffer.from('username:password').toString('base64')}` },
});
});
test('it does not override an authorization header if provided', async () => {
await request({
axios,
url: '/test',
logger,
configurationUtilities,
auth: { username: 'username', password: 'password' },
headers: {
'Content-Type': 'application/json',
'X-Test-Header': 'test',
Authorization: 'Bearer my_token',
},
});
expect(axiosMock).toHaveBeenCalledWith('/test', {
method: 'get',
httpAgent: undefined,
httpsAgent: expect.any(HttpsAgent),
proxy: false,
maxContentLength: 1000000,
timeout: 360000,
headers: {
'Content-Type': 'application/json',
'X-Test-Header': 'test',
Authorization: 'Bearer my_token',
},
});
});
});
describe('patch', () => {

View file

@ -18,6 +18,7 @@ import { Logger } from '@kbn/core/server';
import { getCustomAgents } from './get_custom_agents';
import { ActionsConfigurationUtilities } from '../actions_config';
import { SSLSettings } from '../types';
import { getBasicAuthHeader } from './get_basic_auth_header';
export const request = async <T = unknown>({
axios,
@ -55,10 +56,20 @@ export const request = async <T = unknown>({
const { maxContentLength, timeout: settingsTimeout } =
configurationUtilities.getResponseSettings();
const { auth, ...restConfig } = config;
const headersWithBasicAuth =
auth != null
? {
...getBasicAuthHeader({ username: auth.username, password: auth.password }),
...headers,
}
: headers;
return await axios(url, {
...config,
...restConfig,
method,
headers,
headers: headersWithBasicAuth,
...(data ? { data } : {}),
// use httpAgent and httpsAgent and set axios proxy: false, to be able to handle fail on invalid certs
httpAgent,