Skip to content

Commit

Permalink
chore: adjust the API of request to allow for plain objects as header…
Browse files Browse the repository at this point in the history
…s, undo several changes
  • Loading branch information
delanni committed Aug 14, 2023
1 parent 9b41000 commit 604fb34
Show file tree
Hide file tree
Showing 13 changed files with 44 additions and 34 deletions.
11 changes: 9 additions & 2 deletions x-pack/plugins/actions/server/lib/axios_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
*/

import { isObjectLike, isEmpty } from 'lodash';
import { AxiosInstance, Method, AxiosResponse, AxiosRequestConfig, AxiosHeaders } from 'axios';
import {
AxiosInstance,
Method,
AxiosResponse,
AxiosRequestConfig,
AxiosHeaders,
AxiosHeaderValue,
} from 'axios';
import { Logger } from '@kbn/core/server';
import { getCustomAgents } from './get_custom_agents';
import { ActionsConfigurationUtilities } from '../actions_config';
Expand All @@ -29,7 +36,7 @@ export const request = async <T = unknown>({
method?: Method;
data?: T;
configurationUtilities: ActionsConfigurationUtilities;
headers?: AxiosHeaders;
headers?: Record<string, AxiosHeaderValue>;
sslOverrides?: SSLSettings;
} & AxiosRequestConfig): Promise<AxiosResponse> => {
const { httpAgent, httpsAgent } = getCustomAgents(
Expand Down
6 changes: 3 additions & 3 deletions x-pack/plugins/actions/server/lib/request_oauth_token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import qs from 'query-string';
import axios, { AxiosHeaders } from 'axios';
import axios from 'axios';
import stringify from 'json-stable-stringify';
import { Logger } from '@kbn/core/server';
import { request } from './axios_utils';
Expand Down Expand Up @@ -37,9 +37,9 @@ export async function requestOAuthToken<T>(
...bodyRequest,
grant_type: grantType,
}),
headers: new AxiosHeaders({
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}),
},
configurationUtilities,
validateStatus: () => true,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import axios, {
AxiosError,
AxiosRequestHeaders,
AxiosHeaders,
AxiosHeaderValue,
} from 'axios';
import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { ElasticsearchClient } from '@kbn/core-elasticsearch-server';
Expand Down Expand Up @@ -80,8 +81,8 @@ export abstract class SubActionConnector<Config, Secrets> {
}
}

private getHeaders(headers?: AxiosRequestHeaders) {
return headers?.set('Content-Type', 'application/json');
private getHeaders(headers?: AxiosRequestHeaders): Record<string, AxiosHeaderValue> {
return { ...headers, 'Content-Type': 'application/json' };
}

private validateResponse(responseSchema: Type<unknown>, data: unknown) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ describe('cases_webhook/utils', () => {
config: {
method: 'post',
url: 'https://poster.com',
headers: new AxiosHeaders(),
headers: new AxiosHeaders({}),
},
};
it('Throws error when missing content-type', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/
jest.mock('axios', () => ({
create: jest.fn(),
AxiosHeaders: jest.requireActual('axios').AxiosHeaders,
}));

import axios from 'axios';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

// @ts-expect-error missing type def
import stringify from 'json-stringify-safe';
import axios, { AxiosHeaders, AxiosInstance, AxiosResponse } from 'axios';
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { Logger } from '@kbn/core/server';
import { request } from '@kbn/actions-plugin/server/lib/axios_utils';
import { ActionsConfigurationUtilities } from '@kbn/actions-plugin/server/actions_config';
Expand Down Expand Up @@ -40,7 +40,7 @@ export async function sendEmailGraphApi(
method: 'post',
logger,
data: getMessage(options, messageHTML),
headers: new AxiosHeaders(headers),
headers,
configurationUtilities,
validateStatus: () => true,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { AxiosHeaders, AxiosRequestHeaders, AxiosResponse, ResponseType } from 'axios';
import { AxiosResponse, ResponseType } from 'axios';
import { IncomingMessage } from 'http';
import { OpenAiProviderType } from '../../../../common/gen_ai/constants';
import {
Expand Down Expand Up @@ -77,24 +77,24 @@ export const getAxiosOptions = (
provider: string,
apiKey: string,
stream: boolean
): { headers: AxiosRequestHeaders; responseType?: ResponseType } => {
): { headers: Record<string, string>; responseType?: ResponseType } => {
const responseType = stream ? { responseType: 'stream' as ResponseType } : {};
switch (provider) {
case OpenAiProviderType.OpenAi:
return {
headers: new AxiosHeaders({
headers: {
Authorization: `Bearer ${apiKey}`,
['content-type']: 'application/json',
}),
},
...responseType,
};
case OpenAiProviderType.AzureAi:
return {
headers: new AxiosHeaders({ ['api-key']: apiKey, ['content-type']: 'application/json' }),
headers: { ['api-key']: apiKey, ['content-type']: 'application/json' },
...responseType,
};
default:
return { headers: new AxiosHeaders() };
return { headers: {} };
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jest.mock('@kbn/actions-plugin/server/lib/get_oauth_jwt_access_token', () => ({

jest.mock('axios', () => ({
create: jest.fn(),
AxiosHeaders: jest.requireActual('axios').AxiosHeaders,
}));
const createAxiosInstanceMock = axios.create as jest.Mock;
const axiosInstanceMock = {
Expand Down Expand Up @@ -226,7 +227,7 @@ describe('utils', () => {
const mockRequestCallback = (axiosInstanceMock.interceptors.request.use as jest.Mock).mock
.calls[0][0];
expect(await mockRequestCallback({ headers: {} })).toEqual({
headers: { Authorization: 'Bearer tokentokentoken' },
headers: new axios.AxiosHeaders({ Authorization: 'Bearer tokentokentoken' }),
});

expect(getOAuthJwtAccessToken as jest.Mock).toHaveBeenCalledWith({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import axios, { AxiosHeaders, AxiosResponse } from 'axios';
import axios, { AxiosResponse } from 'axios';
import { Logger } from '@kbn/core/server';
import { Services } from '@kbn/actions-plugin/server/types';
import { ActionsConfigurationUtilities } from '@kbn/actions-plugin/server/actions_config';
Expand Down Expand Up @@ -33,7 +33,7 @@ export async function postPagerduty(
method: 'post',
logger,
data,
headers: new AxiosHeaders(headers),
headers,
configurationUtilities,
validateStatus: () => true,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { Logger } from '@kbn/logging';
import axios, { AxiosHeaders } from 'axios';
import axios from 'axios';

import {
getErrorMessage,
Expand Down Expand Up @@ -88,7 +88,7 @@ export const createExternalService = (
axios: axiosInstance,
configurationUtilities,
data,
headers: new AxiosHeaders(headers),
headers,
logger,
method: 'post',
url: getPostRecordUrl(appId),
Expand Down Expand Up @@ -128,7 +128,7 @@ export const createExternalService = (
axios: axiosInstance,
configurationUtilities,
data,
headers: new AxiosHeaders(headers),
headers,
logger,
method: 'patch',
url: getPostRecordIdUrl(appId, params.incidentId),
Expand Down Expand Up @@ -177,7 +177,7 @@ export const createExternalService = (
axios: axiosInstance,
configurationUtilities,
data,
headers: new AxiosHeaders(headers),
headers,
logger,
method: 'post',
url: getPostCommentUrl(appId, incidentId, fieldId),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { i18n } from '@kbn/i18n';
import { curry } from 'lodash';
import axios, { AxiosError, AxiosHeaders, AxiosResponse } from 'axios';
import axios, { AxiosError, AxiosResponse } from 'axios';
import { schema, TypeOf } from '@kbn/config-schema';
import { pipe } from 'fp-ts/lib/pipeable';
import { map, getOrElse } from 'fp-ts/lib/Option';
Expand Down Expand Up @@ -57,6 +57,7 @@ const ParamsSchema = schema.object({
});

export const ActionTypeId = '.torq';

// action type definition
export function getActionType(): TorqActionType {
return {
Expand Down Expand Up @@ -162,10 +163,10 @@ export async function executor(
axios: axiosInstance,
url: webhookIntegrationUrl,
method: 'post',
headers: new AxiosHeaders({
headers: {
'X-Torq-Token': token || '',
'Content-Type': 'application/json',
}),
},
data: body,
configurationUtilities,
logger: execOptions.logger,
Expand Down Expand Up @@ -366,7 +367,6 @@ function retryResult(actionId: string, serviceMessage: string): ActionTypeExecut
function retryResultSeconds(
actionId: string,
serviceMessage: string,

retryAfter: number
): ActionTypeExecutorResult<void> {
const retryEpoch = Date.now() + retryAfter * 1000;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { i18n } from '@kbn/i18n';
import { isString } from 'lodash';
import axios, { AxiosError, AxiosHeaders, AxiosResponse } from 'axios';
import axios, { AxiosError, AxiosResponse } from 'axios';
import { schema, TypeOf } from '@kbn/config-schema';
import { pipe } from 'fp-ts/lib/pipeable';
import { map, getOrElse } from 'fp-ts/lib/Option';
Expand Down Expand Up @@ -238,7 +238,7 @@ export async function executor(
url,
logger,
...basicAuth,
headers: new AxiosHeaders(headers || {}),
headers: headers!,
data,
configurationUtilities,
sslOverrides,
Expand Down
10 changes: 5 additions & 5 deletions x-pack/test/ui_capabilities/common/services/ui_capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import axios, { AxiosHeaders, AxiosInstance, AxiosRequestHeaders } from 'axios';
import axios, { AxiosInstance } from 'axios';
import type { Capabilities as UICapabilities } from '@kbn/core/types';
import { format as formatUrl } from 'url';
import util from 'util';
Expand Down Expand Up @@ -61,13 +61,13 @@ export class UICapabilitiesService {
this.log.debug(
`requesting ${spaceUrlPrefix}/api/core/capabilities to parse the uiCapabilities`
);
const requestHeaders: AxiosRequestHeaders = credentials
? new AxiosHeaders({
const requestHeaders: Record<string, string> = credentials
? {
Authorization: `Basic ${Buffer.from(
`${credentials.username}:${credentials.password}`
).toString('base64')}`,
})
: new AxiosHeaders({});
}
: {};
const response = await this.axios.post(
`${spaceUrlPrefix}/api/core/capabilities`,
{ applications: [...applications, 'kibana:stack_management'] },
Expand Down

0 comments on commit 604fb34

Please sign in to comment.