Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

aws4-axios

Package Overview
Dependencies
Maintainers
1
Versions
102
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

aws4-axios - npm Package Compare versions

Comparing version 2.2.1 to 2.3.0

dist/__tests__/setup.d.ts

252

dist/__tests__/apiGateway.it.js

@@ -38,2 +38,9 @@ "use strict";

};
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -45,28 +52,90 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

var __1 = require("..");
var __2 = require("..");
var client_sts_1 = require("@aws-sdk/client-sts");
var methods = ["GET", "DELETE"];
var dataMethods = ["POST", "PATCH", "PUT"];
var region = process.env.AWS_REGION;
var apiGateway = process.env.API_GATEWAY_URL;
var clientRoleArn = process.env.CLIENT_ROLE_ARN;
var service = "execute-api";
var clientCredentials;
beforeAll(function () { return __awaiter(void 0, void 0, void 0, function () {
var sts, credentials;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
sts = new client_sts_1.STSClient({ region: region });
return [4 /*yield*/, sts.send(new client_sts_1.AssumeRoleCommand({
RoleArn: clientRoleArn,
RoleSessionName: "integration-tests",
}))];
case 1:
credentials = (_a.sent()).Credentials;
clientCredentials = {
accessKeyId: (credentials === null || credentials === void 0 ? void 0 : credentials.AccessKeyId) || "",
secretAccessKey: (credentials === null || credentials === void 0 ? void 0 : credentials.SecretAccessKey) || "",
sessionToken: (credentials === null || credentials === void 0 ? void 0 : credentials.SessionToken) || "",
};
cleanEnvCredentials();
return [2 /*return*/];
}
});
}); });
var setEnvCredentials = function () {
process.env.AWS_ACCESS_KEY_ID = clientCredentials === null || clientCredentials === void 0 ? void 0 : clientCredentials.accessKeyId;
process.env.AWS_SECRET_ACCESS_KEY = clientCredentials === null || clientCredentials === void 0 ? void 0 : clientCredentials.secretAccessKey;
process.env.AWS_SESSION_TOKEN = clientCredentials === null || clientCredentials === void 0 ? void 0 : clientCredentials.sessionToken;
};
var cleanEnvCredentials = function () {
delete process.env.AWS_PROFILE;
delete process.env.AWS_ACCESS_KEY_ID;
delete process.env.AWS_SECRET_ACCESS_KEY;
delete process.env.AWS_SESSION_TOKEN;
};
describe("check that API is actually protected", function () {
it.each(__spreadArrays(methods, dataMethods))("checks that HTTP %s is protected", function (method) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, expect(axios_1.default.request({ url: apiGateway, method: method })).rejects.toMatchObject({
response: {
status: 403,
},
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
});
describe("API Gateway integration", function () {
var client;
var data = {
foo: "bar",
};
beforeAll(function () {
setEnvCredentials();
});
beforeEach(function () {
client = axios_1.default.create();
client.interceptors.request.use(__1.aws4Interceptor({ region: region, service: service }));
});
it.each(methods)("HTTP %s", function (method) { return __awaiter(void 0, void 0, void 0, function () {
var client, message, result, err_1;
var error, result, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
client = axios_1.default.create();
client.interceptors.request.use(__1.aws4Interceptor({ region: "eu-west-2", service: "execute-api" }));
_a.label = 1;
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({ url: apiGateway, method: method })];
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, client.request({ url: apiGateway, method: method })];
result = _a.sent();
return [3 /*break*/, 3];
case 2:
result = _a.sent();
return [3 /*break*/, 4];
err_1 = _a.sent();
error = __1.getAuthErrorMessage(err_1);
return [3 /*break*/, 3];
case 3:
err_1 = _a.sent();
message = __2.getAuthErrorMessage(err_1);
return [3 /*break*/, 4];
case 4:
expect(message).toBe(undefined);
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.requestContext.http.method).toBe(method);
expect(result && result.data.requestContext.http.path).toBe("/");
return [2 /*return*/];

@@ -77,14 +146,7 @@ }

it.each(dataMethods)("HTTP %s", function (method) { return __awaiter(void 0, void 0, void 0, function () {
var client, data, message, result, err_2;
var error, result, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
client = axios_1.default.create();
data = {
foo: "bar",
};
client.interceptors.request.use(__1.aws4Interceptor({ region: "eu-west-2", service: "execute-api" }));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({

@@ -95,12 +157,39 @@ url: apiGateway,

})];
case 1:
result = _a.sent();
return [3 /*break*/, 3];
case 2:
err_2 = _a.sent();
error = __1.getAuthErrorMessage(err_2);
return [3 /*break*/, 3];
case 3:
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.requestContext.http.method).toBe(method);
expect(result && result.data.requestContext.http.path).toBe("/");
expect(result && JSON.parse(result.data.body)).toStrictEqual(data);
return [2 /*return*/];
}
});
}); });
it("handles path", function () { return __awaiter(void 0, void 0, void 0, function () {
var error, result, err_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({
url: apiGateway + "/some/path",
})];
case 1:
result = _a.sent();
return [3 /*break*/, 4];
return [3 /*break*/, 3];
case 2:
err_3 = _a.sent();
error = __1.getAuthErrorMessage(err_3);
return [3 /*break*/, 3];
case 3:
err_2 = _a.sent();
message = __2.getAuthErrorMessage(err_2);
return [3 /*break*/, 4];
case 4:
expect(message).toBe(undefined);
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.requestContext.http.path).toBe("/some/path");
return [2 /*return*/];

@@ -110,15 +199,35 @@ }

}); });
it("handles query parameters", function () { return __awaiter(void 0, void 0, void 0, function () {
var error, result, err_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({
url: apiGateway,
params: {
lorem: 42,
},
})];
case 1:
result = _a.sent();
return [3 /*break*/, 3];
case 2:
err_4 = _a.sent();
error = __1.getAuthErrorMessage(err_4);
return [3 /*break*/, 3];
case 3:
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.rawQueryString).toBe("lorem=42");
return [2 /*return*/];
}
});
}); });
it("handles custom headers", function () { return __awaiter(void 0, void 0, void 0, function () {
var client, data, message, result, err_3;
var error, result, err_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
client = axios_1.default.create();
data = {
foo: "bar",
};
client.interceptors.request.use(__1.aws4Interceptor({ region: "eu-west-2", service: "execute-api" }));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({

@@ -130,12 +239,13 @@ url: apiGateway,

})];
case 1:
result = _a.sent();
return [3 /*break*/, 3];
case 2:
result = _a.sent();
return [3 /*break*/, 4];
err_5 = _a.sent();
error = __1.getAuthErrorMessage(err_5);
return [3 /*break*/, 3];
case 3:
err_3 = _a.sent();
message = __2.getAuthErrorMessage(err_3);
return [3 /*break*/, 4];
case 4:
expect(message).toBe(undefined);
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.headers["x-custom-header"]).toBe("Baz");
return [2 /*return*/];

@@ -146,14 +256,7 @@ }

it("handles custom Content-Type header", function () { return __awaiter(void 0, void 0, void 0, function () {
var client, data, message, result, err_4;
var error, result, err_6;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
client = axios_1.default.create();
data = {
foo: "bar",
};
client.interceptors.request.use(__1.aws4Interceptor({ region: "eu-west-2", service: "execute-api" }));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({

@@ -165,12 +268,13 @@ url: apiGateway,

})];
case 1:
result = _a.sent();
return [3 /*break*/, 3];
case 2:
result = _a.sent();
return [3 /*break*/, 4];
err_6 = _a.sent();
error = __1.getAuthErrorMessage(err_6);
return [3 /*break*/, 3];
case 3:
err_4 = _a.sent();
message = __2.getAuthErrorMessage(err_4);
return [3 /*break*/, 4];
case 4:
expect(message).toBe(undefined);
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.headers["content-type"]).toBe("application/xml");
return [2 /*return*/];

@@ -181,14 +285,7 @@ }

it("sets content type as application/json when the body is an object", function () { return __awaiter(void 0, void 0, void 0, function () {
var client, data, message, result, err_5;
var error, result, err_7;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
client = axios_1.default.create();
data = {
foo: "bar",
};
client.interceptors.request.use(__1.aws4Interceptor({ region: "eu-west-2", service: "execute-api" }));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, client.request({

@@ -199,12 +296,13 @@ url: apiGateway,

})];
case 1:
result = _a.sent();
return [3 /*break*/, 3];
case 2:
result = _a.sent();
return [3 /*break*/, 4];
err_7 = _a.sent();
error = __1.getAuthErrorMessage(err_7);
return [3 /*break*/, 3];
case 3:
err_5 = _a.sent();
message = __2.getAuthErrorMessage(err_5);
return [3 /*break*/, 4];
case 4:
expect(message).toBe(undefined);
expect(error).toBe(undefined);
expect(result && result.status).toEqual(200);
expect(result && result.data.headers["content-type"]).toBe("application/json;charset=utf-8");
return [2 /*return*/];

@@ -211,0 +309,0 @@ }

@@ -6,4 +6,4 @@ import { aws4Interceptor, Credentials, InterceptorOptions } from "./interceptor";

*/
export declare const interceptor: (options?: InterceptorOptions | undefined, credentials?: Credentials | undefined) => (config: import("axios").AxiosRequestConfig) => import("axios").AxiosRequestConfig;
export declare const interceptor: (options?: InterceptorOptions | undefined, credentials?: Credentials | undefined) => (config: import("axios").AxiosRequestConfig) => Promise<import("axios").AxiosRequestConfig>;
export default aws4Interceptor;
export { getAuthErrorMessage, aws4Interceptor, Credentials, InterceptorOptions, };
import { AxiosRequestConfig } from "axios";
export interface InterceptorOptions {
/**
* Target service. Will use default aws4 behavior if not given.
*/
service?: string;
/**
* AWS region name. Will use default aws4 behavior if not given.
*/
region?: string;
/**
* Whether to sign query instead of adding Authorization header. Default to false.
*/
signQuery?: boolean;
/**
* ARN of the IAM Role to be assumed to get the credentials from.
* The credentials will be cached and automatically refreshed as needed.
* Will not be used if credentials are provided.
*/
assumeRoleArn?: string;
/**
* Number of seconds before the assumed Role expiration
* to invalidate the cache.
* Used only if assumeRoleArn is provided.
*/
assumedRoleExpirationMarginSec?: number;
}

@@ -32,3 +53,4 @@ export interface SigningOptions {

* @param options The options to be used when signing a request
* @param credentials Credentials to be used to sign the request
*/
export declare const aws4Interceptor: (options?: InterceptorOptions | undefined, credentials?: Credentials | undefined) => (config: AxiosRequestConfig) => AxiosRequestConfig;
export declare const aws4Interceptor: (options?: InterceptorOptions | undefined, credentials?: Credentials | undefined) => (config: AxiosRequestConfig) => Promise<AxiosRequestConfig>;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {

@@ -33,2 +58,4 @@ var t = {};

var isAbsoluteURL_1 = __importDefault(require("axios/lib/helpers/isAbsoluteURL"));
var simpleCredentialsProvider_1 = require("./credentials/simpleCredentialsProvider");
var assumeRoleCredentialsProvider_1 = require("./credentials/assumeRoleCredentialsProvider");
/**

@@ -44,34 +71,53 @@ * Create an interceptor to add to the Axios request chain. This interceptor

* @param options The options to be used when signing a request
* @param credentials Credentials to be used to sign the request
*/
exports.aws4Interceptor = function (options, credentials) { return function (config) {
if (!config.url) {
throw new Error("No URL present in request config, unable to sign request");
}
if (config.params) {
config.url = buildURL_1.default(config.url, config.params, config.paramsSerializer);
delete config.params;
}
var url = config.url;
if (config.baseURL && !isAbsoluteURL_1.default(config.url)) {
url = combineURLs_1.default(config.baseURL, config.url);
}
var _a = new URL(url), host = _a.host, pathname = _a.pathname, search = _a.search;
var data = config.data, headers = config.headers, method = config.method;
var region;
var service;
var signQuery;
if (options) {
(region = options.region, service = options.service);
}
var transformRequest = getTransformer(config);
var transformedData = transformRequest(data, headers);
// Remove all the default Axios headers
var common = headers.common, _delete = headers.delete, // 'delete' is a reserved word
get = headers.get, head = headers.head, post = headers.post, put = headers.put, patch = headers.patch, headersToSign = __rest(headers, ["common", "delete", "get", "head", "post", "put", "patch"]);
var signingOptions = __assign(__assign({ method: method && method.toUpperCase(), host: host, path: pathname + search, region: region,
service: service }, (signQuery !== undefined ? { signQuery: signQuery } : {})), { body: transformedData, headers: headersToSign });
aws4_1.sign(signingOptions, credentials);
config.headers = signingOptions.headers;
return config;
}; };
exports.aws4Interceptor = function (options, credentials) {
var credentialsProvider = (options === null || options === void 0 ? void 0 : options.assumeRoleArn) && !credentials
? new assumeRoleCredentialsProvider_1.AssumeRoleCredentialsProvider({
roleArn: options.assumeRoleArn,
region: options.region,
expirationMarginSec: options.assumedRoleExpirationMarginSec,
})
: new simpleCredentialsProvider_1.SimpleCredentialsProvider(credentials);
return function (config) { return __awaiter(void 0, void 0, void 0, function () {
var url, _a, host, pathname, search, data, headers, method, transformRequest, transformedData, common, _delete, get, head, post, put, patch, headersToSign, signingOptions, resolvedCredentials;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!config.url) {
throw new Error("No URL present in request config, unable to sign request");
}
if (config.params) {
config.url = buildURL_1.default(config.url, config.params, config.paramsSerializer);
delete config.params;
}
url = config.url;
if (config.baseURL && !isAbsoluteURL_1.default(config.url)) {
url = combineURLs_1.default(config.baseURL, config.url);
}
_a = new URL(url), host = _a.host, pathname = _a.pathname, search = _a.search;
data = config.data, headers = config.headers, method = config.method;
transformRequest = getTransformer(config);
transformedData = transformRequest(data, headers);
common = headers.common, _delete = headers.delete, get = headers.get, head = headers.head, post = headers.post, put = headers.put, patch = headers.patch, headersToSign = __rest(headers, ["common", "delete", "get", "head", "post", "put", "patch"]);
signingOptions = {
method: method && method.toUpperCase(),
host: host,
path: pathname + search,
region: options === null || options === void 0 ? void 0 : options.region,
service: options === null || options === void 0 ? void 0 : options.service,
signQuery: options === null || options === void 0 ? void 0 : options.signQuery,
body: transformedData,
headers: headersToSign,
};
return [4 /*yield*/, credentialsProvider.getCredentials()];
case 1:
resolvedCredentials = _b.sent();
aws4_1.sign(signingOptions, resolvedCredentials);
config.headers = signingOptions.headers;
return [2 /*return*/, config];
}
});
}); };
};
var getTransformer = function (config) {

@@ -78,0 +124,0 @@ var transformRequest = config.transformRequest;

@@ -13,2 +13,38 @@ "use strict";

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -22,230 +58,428 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

jest.mock("aws4");
jest.mock("./credentials/assumeRoleCredentialsProvider", function () { return ({
AssumeRoleCredentialsProvider: jest.fn(function () { return ({
getCredentials: jest.fn().mockResolvedValue({
accessKeyId: "assumed-access-key-id",
secretAccessKey: "assumed-secret-access-key",
sessionToken: "assumed-session-token",
}),
}); }),
}); });
var getDefaultHeaders = function () { return ({
common: { Accept: "application/json, text/plain, */*" },
delete: {},
get: {},
head: {},
post: { "Content-Type": "application/x-www-form-urlencoded" },
put: { "Content-Type": "application/x-www-form-urlencoded" },
patch: { "Content-Type": "application/x-www-form-urlencoded" },
}); };
var getDefaultTransformRequest = function () { return axios_1.default.defaults.transformRequest; };
beforeEach(function () {
aws4_1.sign.mockReset();
});
describe("interceptor", function () {
var getDefaultHeaders = function () { return ({
common: { Accept: "application/json, text/plain, */*" },
delete: {},
get: {},
head: {},
post: { "Content-Type": "application/x-www-form-urlencoded" },
put: { "Content-Type": "application/x-www-form-urlencoded" },
patch: { "Content-Type": "application/x-www-form-urlencoded" },
}); };
var getDefaultTransformRequest = function () { return axios_1.default.defaults.transformRequest; };
beforeEach(function () {
aws4_1.sign.mockReset();
});
it("signs GET requests", function () {
// Arrange
var request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
it("signs GET requests", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, undefined);
});
it("signs url query paremeters in GET requests", function () {
// Arrange
var request = {
method: "GET",
url: "https://example.com/foobar?foo=bar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}); });
it("signs url query paremeters in GET requests", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar?foo=bar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar?foo=bar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar?foo=bar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, undefined);
});
it("signs query paremeters in GET requests", function () {
// Arrange
var request = {
method: "GET",
url: "https://example.com/foobar",
params: { foo: "bar" },
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}); });
it("signs query paremeters in GET requests", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar",
params: { foo: "bar" },
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar?foo=bar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar?foo=bar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, undefined);
});
it("signs POST requests with an object payload", function () {
// Arrange
var data = { foo: "bar" };
var request = {
method: "POST",
url: "https://example.com/foobar",
data: data,
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}); });
it("signs POST requests with an object payload", function () { return __awaiter(void 0, void 0, void 0, function () {
var data, request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
data = { foo: "bar" };
request = {
method: "POST",
url: "https://example.com/foobar",
data: data,
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "POST",
region: "local",
host: "example.com",
body: '{"foo":"bar"}',
headers: { "Content-Type": "application/json;charset=utf-8" },
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "POST",
region: "local",
host: "example.com",
body: '{"foo":"bar"}',
headers: { "Content-Type": "application/json;charset=utf-8" },
}, undefined);
});
it("signs POST requests with a string payload", function () {
// Arrange
var data = "foobar";
var request = {
method: "POST",
url: "https://example.com/foobar",
data: data,
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}); });
it("signs POST requests with a string payload", function () { return __awaiter(void 0, void 0, void 0, function () {
var data, request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
data = "foobar";
request = {
method: "POST",
url: "https://example.com/foobar",
data: data,
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "POST",
path: "/foobar",
region: "local",
host: "example.com",
body: "foobar",
headers: {},
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "POST",
path: "/foobar",
region: "local",
host: "example.com",
body: "foobar",
headers: {},
}, undefined);
});
it("passes Content-Type header to be signed", function () {
// Arrange
var data = "foobar";
var request = {
method: "POST",
url: "https://example.com/foobar",
data: data,
headers: __assign(__assign({}, getDefaultHeaders()), { "Content-Type": "application/xml" }),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}); });
it("passes Content-Type header to be signed", function () { return __awaiter(void 0, void 0, void 0, function () {
var data, request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
data = "foobar";
request = {
method: "POST",
url: "https://example.com/foobar",
data: data,
headers: __assign(__assign({}, getDefaultHeaders()), { "Content-Type": "application/xml" }),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "POST",
path: "/foobar",
region: "local",
host: "example.com",
body: "foobar",
headers: { "Content-Type": "application/xml" },
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "POST",
path: "/foobar",
region: "local",
host: "example.com",
body: "foobar",
headers: { "Content-Type": "application/xml" },
}, undefined);
});
it("works with baseURL config", function () {
// Arrange
var data = "foobar";
var request = {
method: "POST",
baseURL: "https://example.com/foo",
url: "bar",
data: data,
headers: __assign(__assign({}, getDefaultHeaders()), { "Content-Type": "application/xml" }),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}); });
it("works with baseURL config", function () { return __awaiter(void 0, void 0, void 0, function () {
var data, request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
data = "foobar";
request = {
method: "POST",
baseURL: "https://example.com/foo",
url: "bar",
data: data,
headers: __assign(__assign({}, getDefaultHeaders()), { "Content-Type": "application/xml" }),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "POST",
path: "/foo/bar",
region: "local",
host: "example.com",
body: "foobar",
headers: { "Content-Type": "application/xml" },
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "POST",
path: "/foo/bar",
region: "local",
host: "example.com",
body: "foobar",
headers: { "Content-Type": "application/xml" },
}, undefined);
});
it("passes the credentials", function () {
// Arrange
var request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
var interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}, {
accessKeyId: "access-key-id",
secretAccessKey: "secret-access-key",
sessionToken: "session-token",
}); });
it("passes option to sign the query instead of adding header", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
signQuery: true,
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
method: "GET",
path: "/foobar",
region: "local",
host: "example.com",
headers: {},
signQuery: true,
}, undefined);
return [2 /*return*/];
}
});
// Act
interceptor(request);
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, {
accessKeyId: "access-key-id",
secretAccessKey: "secret-access-key",
sessionToken: "session-token",
}); });
});
describe("credentials", function () {
it("passes provided credentials", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
}, {
accessKeyId: "access-key-id",
secretAccessKey: "secret-access-key",
sessionToken: "session-token",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, {
accessKeyId: "access-key-id",
secretAccessKey: "secret-access-key",
sessionToken: "session-token",
});
return [2 /*return*/];
}
});
});
}); });
it("gets credentials for given role", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
assumeRoleArn: "arn:aws:iam::111111111111:role/MockRole",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, {
accessKeyId: "assumed-access-key-id",
secretAccessKey: "assumed-secret-access-key",
sessionToken: "assumed-session-token",
});
return [2 /*return*/];
}
});
}); });
it("prioritizes provided credentials over the role", function () { return __awaiter(void 0, void 0, void 0, function () {
var request, interceptor;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
request = {
method: "GET",
url: "https://example.com/foobar",
headers: getDefaultHeaders(),
transformRequest: getDefaultTransformRequest(),
};
interceptor = _1.aws4Interceptor({
region: "local",
service: "execute-api",
assumeRoleArn: "arn:aws:iam::111111111111:role/MockRole",
}, {
accessKeyId: "access-key-id",
secretAccessKey: "secret-access-key",
sessionToken: "session-token",
});
// Act
return [4 /*yield*/, interceptor(request)];
case 1:
// Act
_a.sent();
// Assert
expect(aws4_1.sign).toBeCalledWith({
service: "execute-api",
path: "/foobar",
method: "GET",
region: "local",
host: "example.com",
headers: {},
}, {
accessKeyId: "access-key-id",
secretAccessKey: "secret-access-key",
sessionToken: "session-token",
});
return [2 /*return*/];
}
});
}); });
});
module.exports = {
...require("./jest.config"),
testMatch: ["**/__tests__/**/*.[jt]s?(x)"],
testMatch: ["**/__tests__/**/*.it.[jt]s?(x)"],
globalSetup: "./src/__tests__/setup.ts",
};
{
"name": "aws4-axios",
"version": "2.2.1",
"version": "2.3.0",
"description": "Axios request interceptor for signing requests with AWSv4",

@@ -34,2 +34,3 @@ "author": "James Bourne",

"test-it": "jest --config jest.config.it.js",
"test-it:deploy": "cd src/__tests__ && serverless deploy",
"prepublishOnly": "npm run build",

@@ -42,2 +43,4 @@ "semantic-release": "semantic-release",

"devDependencies": {
"@aws-sdk/client-cloudformation": "^3.4.1",
"@aws-sdk/client-sts": "^3.4.1",
"@types/jest": "^26.0.20",

@@ -52,3 +55,3 @@ "@types/moxios": "^0.4.9",

"husky": "^4.3.8",
"jest": "^25.4.0",
"jest": "^26.6.3",
"lint-staged": "^10.5.3",

@@ -59,6 +62,8 @@ "moxios": "^0.4.0",

"semantic-release": "^17.3.3",
"ts-jest": "^25.4.0",
"ts-jest": "^26.5.0",
"serverless": "^2.22.0",
"typescript": "^3.8.3"
},
"dependencies": {
"@aws-sdk/client-sts": "^3.4.1",
"@types/aws4": "^1.5.1",

@@ -65,0 +70,0 @@ "aws4": "^1.9.1"

@@ -72,1 +72,23 @@ # aws4-axios

```
## Assuming the IAM Role
You can pass a parameter to assume the IAM Role with AWS STS
and use the assumed role credentials to sign the request.
This is useful when doing cross-account requests.
```typescript
const interceptor = aws4Interceptor(
{
region: "eu-west-2",
service: "execute-api",
assumeRoleArn: "arn:aws:iam::111111111111:role/MyRole",
}
);
```
Obtained credentials are cached and refreshed as needed after they expire.
You can use `expirationMarginSec` parameter to set the number of seconds
before the received credentials expiration time to invalidate the cache.
This allows setting a safety margin. Default to 5 seconds.

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc