Skip to content

Commit

Permalink
fix: signing request on retry.
Browse files Browse the repository at this point in the history
  • Loading branch information
dblock committed Aug 14, 2024
1 parent 519ff9a commit 398890b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 4 deletions.
49 changes: 47 additions & 2 deletions src/interceptor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ describe("interceptor", () => {
);
});

it("signs url query paremeters in GET requests", async () => {
it("signs url query parameters in GET requests", async () => {
// Arrange
const request: InternalAxiosRequestConfig = {
method: "GET",
Expand Down Expand Up @@ -107,7 +107,7 @@ describe("interceptor", () => {
);
});

it("signs query paremeters in GET requests", async () => {
it("signs query parameters in GET requests", async () => {
// Arrange
const request: InternalAxiosRequestConfig = {
method: "GET",
Expand Down Expand Up @@ -548,4 +548,49 @@ describe("credentials", () => {
},
);
});

it("supports retries", async () => {
// Arrange
const data = { foo: "bar" };

const request: InternalAxiosRequestConfig = {
method: "POST",
url: "https://example.com/foobar",
data,
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};


(sign as jest.Mock).mockImplementation((request) => {
// neither call should contain the previous Authorization header
expect(request).toEqual({
service: "execute-api",
path: "/foobar",
method: "POST",
region: "local",
host: "example.com",
body: '{"foo":"bar"}',
headers: { "Content-Type": "application/json" },
signQuery: undefined
})
request.headers['Authorization'] = 'signed';
return request;
})

const interceptor = aws4Interceptor({
options: {
region: "local",
service: "execute-api",
},
instance: axios,
});

// Act
await interceptor(request);
await interceptor(request);
await interceptor(request);

expect(sign).toBeCalledTimes(3)
});
});
13 changes: 11 additions & 2 deletions src/interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Request as AWS4Request, sign } from "aws4";
import axios, {
AxiosHeaders,
AxiosInstance,
AxiosRequestConfig,
AxiosRequestHeaders,
Expand Down Expand Up @@ -133,12 +134,20 @@ export const aws4Interceptor = <D = any>({

const { host, pathname, search } = new URL(url);
const { data, method } = config;
const headers = config.headers;


const transformRequest = getTransformer(config);

transformRequest.bind(config);

// Save, and reset headers on retry
if (config._originalHeaders) {
config.headers = new AxiosHeaders(config._originalHeaders);
} else {
config._originalHeaders = new AxiosHeaders(config.headers);
}

const headers = config.headers;

// @ts-expect-error we bound the function to the config object
const transformedData = transformRequest(data, headers);

Expand Down

0 comments on commit 398890b

Please sign in to comment.