Compare commits

..

No commits in common. "8400204d95ad648014fe727363c4d46dd4cd80a7" and "4b76407eddb119a9c06462523f1f0107df799b8b" have entirely different histories.

26 changed files with 372 additions and 549 deletions

View File

@ -6,15 +6,16 @@ import * as constants from '../constants';
* shortid, email, accountDisplayName and IAMdisplayName (if applicable) * shortid, email, accountDisplayName and IAMdisplayName (if applicable)
* @return {AuthInfo} an AuthInfo instance * @return {AuthInfo} an AuthInfo instance
*/ */
export default class AuthInfo {
arn: string;
canonicalID: string;
shortid: string;
email: string;
accountDisplayName: string;
IAMdisplayName: string;
constructor(objectFromVault: any) { export default class AuthInfo {
arn
canonicalID
shortid
email
accountDisplayName
IAMdisplayName
constructor(objectFromVault) {
// amazon resource name for IAM user (if applicable) // amazon resource name for IAM user (if applicable)
this.arn = objectFromVault.arn; this.arn = objectFromVault.arn;
// account canonicalID // account canonicalID
@ -56,8 +57,10 @@ export default class AuthInfo {
isRequesterAServiceAccount() { isRequesterAServiceAccount() {
return this.canonicalID.startsWith(`${constants.zenkoServiceAccount}/`); return this.canonicalID.startsWith(`${constants.zenkoServiceAccount}/`);
} }
isRequesterThisServiceAccount(serviceName: string) { isRequesterThisServiceAccount(serviceName) {
const computedCanonicalID = `${constants.zenkoServiceAccount}/${serviceName}`; return (
return this.canonicalID === computedCanonicalID; this.canonicalID ===
`${constants.zenkoServiceAccount}/${serviceName}`
);
} }
} }

View File

@ -1,22 +1,16 @@
import { Logger } from 'werelogs';
import errors from '../errors'; import errors from '../errors';
import AuthInfo from './AuthInfo'; import AuthInfo from './AuthInfo';
/** vaultSignatureCb parses message from Vault and instantiates /** vaultSignatureCb parses message from Vault and instantiates
* @param err - error from vault * @param {object} err - error from vault
* @param authInfo - info from vault * @param {object} authInfo - info from vault
* @param log - log for request * @param {object} log - log for request
* @param callback - callback to authCheck functions * @param {function} callback - callback to authCheck functions
* @param [streamingV4Params] - present if v4 signature; * @param {object} [streamingV4Params] - present if v4 signature;
* items used to calculate signature on chunks if streaming auth * items used to calculate signature on chunks if streaming auth
* @return {undefined}
*/ */
function vaultSignatureCb( function vaultSignatureCb(err, authInfo, log, callback, streamingV4Params) {
err: Error | null,
authInfo: { message: { body: any } },
log: Logger,
callback: (err: Error | null, data?: any, results?: any, params?: any) => void,
streamingV4Params?: any
) {
// vaultclient API guarantees that it returns: // vaultclient API guarantees that it returns:
// - either `err`, an Error object with `code` and `message` properties set // - either `err`, an Error object with `code` and `message` properties set
// - or `err == null` and `info` is an object with `message.code` and // - or `err == null` and `info` is an object with `message.code` and
@ -30,13 +24,11 @@ function vaultSignatureCb(
const info = authInfo.message.body; const info = authInfo.message.body;
const userInfo = new AuthInfo(info.userInfo); const userInfo = new AuthInfo(info.userInfo);
const authorizationResults = info.authorizationResults; const authorizationResults = info.authorizationResults;
const auditLog: { accountDisplayName: string, IAMdisplayName?: string } = const auditLog = { accountDisplayName: userInfo.getAccountDisplayName() };
{ accountDisplayName: userInfo.getAccountDisplayName() };
const iamDisplayName = userInfo.getIAMdisplayName(); const iamDisplayName = userInfo.getIAMdisplayName();
if (iamDisplayName) { if (iamDisplayName) {
auditLog.IAMdisplayName = iamDisplayName; auditLog.IAMdisplayName = iamDisplayName;
} }
// @ts-ignore
log.addDefaultFields(auditLog); log.addDefaultFields(auditLog);
return callback(null, userInfo, authorizationResults, streamingV4Params); return callback(null, userInfo, authorizationResults, streamingV4Params);
} }
@ -48,62 +40,45 @@ function vaultSignatureCb(
* @class Vault * @class Vault
*/ */
export default class Vault { export default class Vault {
client: any; client
implName: string; implName
/** /**
* @constructor * @constructor
* @param {object} client - authentication backend or vault client * @param {object} client - authentication backend or vault client
* @param {string} implName - implementation name for auth backend * @param {string} implName - implementation name for auth backend
*/ */
constructor(client: any, implName: string) { constructor(client, implName) {
this.client = client; this.client = client;
this.implName = implName; this.implName = implName;
} }
/** /**
* authenticateV2Request * authenticateV2Request
* *
* @param params - the authentication parameters as returned by * @param {string} params - the authentication parameters as returned by
* auth.extractParams * auth.extractParams
* @param params.version - shall equal 2 * @param {number} params.version - shall equal 2
* @param params.data.accessKey - the user's accessKey * @param {string} params.data.accessKey - the user's accessKey
* @param params.data.signatureFromRequest - the signature read * @param {string} params.data.signatureFromRequest - the signature read
* from the request * from the request
* @param params.data.stringToSign - the stringToSign * @param {string} params.data.stringToSign - the stringToSign
* @param params.data.algo - the hashing algorithm used for the * @param {string} params.data.algo - the hashing algorithm used for the
* signature * signature
* @param params.data.authType - the type of authentication (query * @param {string} params.data.authType - the type of authentication (query
* or header) * or header)
* @param params.data.signatureVersion - the version of the * @param {string} params.data.signatureVersion - the version of the
* signature (AWS or AWS4) * signature (AWS or AWS4)
* @param [params.data.signatureAge] - the age of the signature in * @param {number} [params.data.signatureAge] - the age of the signature in
* ms * ms
* @param params.data.log - the logger object * @param {string} params.data.log - the logger object
* @param {RequestContext []} requestContexts - an array of RequestContext * @param {RequestContext []} requestContexts - an array of RequestContext
* instances which contain information for policy authorization check * instances which contain information for policy authorization check
* @param callback - callback with either error or user info * @param {function} callback - callback with either error or user info
* @returns {undefined}
*/ */
authenticateV2Request( authenticateV2Request(params, requestContexts, callback) {
params: {
version: 2;
log: Logger;
data: {
securityToken: string;
accessKey: string;
signatureFromRequest: string;
stringToSign: string;
algo: string;
authType: 'query' | 'header';
signatureVersion: string;
signatureAge?: number;
log: Logger;
};
},
requestContexts: any[],
callback: (err: Error | null, data?: any) => void
) {
params.log.debug('authenticating V2 request'); params.log.debug('authenticating V2 request');
let serializedRCsArr: any; let serializedRCsArr;
if (requestContexts) { if (requestContexts) {
serializedRCsArr = requestContexts.map(rc => rc.serialize()); serializedRCsArr = requestContexts.map(rc => rc.serialize());
} }
@ -113,66 +88,44 @@ export default class Vault {
params.data.accessKey, params.data.accessKey,
{ {
algo: params.data.algo, algo: params.data.algo,
// @ts-ignore
reqUid: params.log.getSerializedUids(), reqUid: params.log.getSerializedUids(),
logger: params.log, logger: params.log,
securityToken: params.data.securityToken, securityToken: params.data.securityToken,
requestContext: serializedRCsArr, requestContext: serializedRCsArr,
}, },
(err: Error | null, userInfo?: any) => vaultSignatureCb(err, userInfo, (err, userInfo) => vaultSignatureCb(err, userInfo,
params.log, callback), params.log, callback),
); );
} }
/** authenticateV4Request /** authenticateV4Request
* @param params - the authentication parameters as returned by * @param {object} params - the authentication parameters as returned by
* auth.extractParams * auth.extractParams
* @param params.version - shall equal 4 * @param {number} params.version - shall equal 4
* @param params.data.log - the logger object * @param {string} params.data.log - the logger object
* @param params.data.accessKey - the user's accessKey * @param {string} params.data.accessKey - the user's accessKey
* @param params.data.signatureFromRequest - the signature read * @param {string} params.data.signatureFromRequest - the signature read
* from the request * from the request
* @param params.data.region - the AWS region * @param {string} params.data.region - the AWS region
* @param params.data.stringToSign - the stringToSign * @param {string} params.data.stringToSign - the stringToSign
* @param params.data.scopeDate - the timespan to allow the request * @param {string} params.data.scopeDate - the timespan to allow the request
* @param params.data.authType - the type of authentication (query * @param {string} params.data.authType - the type of authentication (query
* or header) * or header)
* @param params.data.signatureVersion - the version of the * @param {string} params.data.signatureVersion - the version of the
* signature (AWS or AWS4) * signature (AWS or AWS4)
* @param params.data.signatureAge - the age of the signature in ms * @param {number} params.data.signatureAge - the age of the signature in ms
* @param params.data.timestamp - signaure timestamp * @param {number} params.data.timestamp - signaure timestamp
* @param params.credentialScope - credentialScope for signature * @param {string} params.credentialScope - credentialScope for signature
* @param {RequestContext [] | null} requestContexts - * @param {RequestContext [] | null} requestContexts -
* an array of RequestContext or null if authenticaiton of a chunk * an array of RequestContext or null if authenticaiton of a chunk
* in streamingv4 auth * in streamingv4 auth
* instances which contain information for policy authorization check * instances which contain information for policy authorization check
* @param callback - callback with either error or user info * @param {function} callback - callback with either error or user info
* @return {undefined}
*/ */
authenticateV4Request( authenticateV4Request(params, requestContexts, callback) {
params: {
version: 4;
log: Logger;
data: {
accessKey: string;
signatureFromRequest: string;
region: string;
stringToSign: string;
scopeDate: string;
authType: 'query' | 'header';
signatureVersion: string;
signatureAge?: number;
timestamp: number;
credentialScope: string;
securityToken: string;
algo: string;
log: Logger;
};
},
requestContexts: any[],
callback: (err: Error | null, data?: any) => void
) {
params.log.debug('authenticating V4 request'); params.log.debug('authenticating V4 request');
let serializedRCs: any; let serializedRCs;
if (requestContexts) { if (requestContexts) {
serializedRCs = requestContexts.map(rc => rc.serialize()); serializedRCs = requestContexts.map(rc => rc.serialize());
} }
@ -190,39 +143,31 @@ export default class Vault {
params.data.region, params.data.region,
params.data.scopeDate, params.data.scopeDate,
{ {
// @ts-ignore
reqUid: params.log.getSerializedUids(), reqUid: params.log.getSerializedUids(),
logger: params.log, logger: params.log,
securityToken: params.data.securityToken, securityToken: params.data.securityToken,
requestContext: serializedRCs, requestContext: serializedRCs,
}, },
(err: Error | null, userInfo?: any) => vaultSignatureCb(err, userInfo, (err, userInfo) => vaultSignatureCb(err, userInfo,
params.log, callback, streamingV4Params), params.log, callback, streamingV4Params),
); );
} }
/** getCanonicalIds -- call Vault to get canonicalIDs based on email /** getCanonicalIds -- call Vault to get canonicalIDs based on email
* addresses * addresses
* @param emailAddresses - list of emailAddresses * @param {array} emailAddresses - list of emailAddresses
* @param log - log object * @param {object} log - log object
* @param callback - callback with either error or an array * @param {function} callback - callback with either error or an array
* of objects with each object containing the canonicalID and emailAddress * of objects with each object containing the canonicalID and emailAddress
* of an account as properties * of an account as properties
* @return {undefined}
*/ */
getCanonicalIds( getCanonicalIds(emailAddresses, log, callback) {
emailAddresses: string[],
log: Logger,
callback: (
err: Error | null,
data?: { canonicalID: string; email: string }[]
) => void
) {
log.trace('getting canonicalIDs from Vault based on emailAddresses', log.trace('getting canonicalIDs from Vault based on emailAddresses',
{ emailAddresses }); { emailAddresses });
this.client.getCanonicalIds(emailAddresses, this.client.getCanonicalIds(emailAddresses,
// @ts-ignore
{ reqUid: log.getSerializedUids() }, { reqUid: log.getSerializedUids() },
(err: Error | null, info?: any) => { (err, info) => {
if (err) { if (err) {
log.debug('received error message from auth provider', log.debug('received error message from auth provider',
{ errorMessage: err }); { errorMessage: err });
@ -230,17 +175,17 @@ export default class Vault {
} }
const infoFromVault = info.message.body; const infoFromVault = info.message.body;
log.trace('info received from vault', { infoFromVault }); log.trace('info received from vault', { infoFromVault });
const foundIds: { canonicalID: string; email: string }[] = []; const foundIds = [];
for (let i = 0; i < Object.keys(infoFromVault).length; i++) { for (let i = 0; i < Object.keys(infoFromVault).length; i++) {
const key = Object.keys(infoFromVault)[i]; const key = Object.keys(infoFromVault)[i];
if (infoFromVault[key] === 'WrongFormat' if (infoFromVault[key] === 'WrongFormat'
|| infoFromVault[key] === 'NotFound') { || infoFromVault[key] === 'NotFound') {
return callback(errors.UnresolvableGrantByEmailAddress); return callback(errors.UnresolvableGrantByEmailAddress);
} }
foundIds.push({ const obj = {};
email: key, obj.email = key;
canonicalID: infoFromVault[key], obj.canonicalID = infoFromVault[key];
}) foundIds.push(obj);
} }
return callback(null, foundIds); return callback(null, foundIds);
}); });
@ -248,22 +193,18 @@ export default class Vault {
/** getEmailAddresses -- call Vault to get email addresses based on /** getEmailAddresses -- call Vault to get email addresses based on
* canonicalIDs * canonicalIDs
* @param canonicalIDs - list of canonicalIDs * @param {array} canonicalIDs - list of canonicalIDs
* @param log - log object * @param {object} log - log object
* @param callback - callback with either error or an object * @param {function} callback - callback with either error or an object
* with canonicalID keys and email address values * with canonicalID keys and email address values
* @return {undefined}
*/ */
getEmailAddresses( getEmailAddresses(canonicalIDs, log, callback) {
canonicalIDs: string[],
log: Logger,
callback: (err: Error | null, data?: { [key: string]: any }) => void
) {
log.trace('getting emailAddresses from Vault based on canonicalIDs', log.trace('getting emailAddresses from Vault based on canonicalIDs',
{ canonicalIDs }); { canonicalIDs });
this.client.getEmailAddresses(canonicalIDs, this.client.getEmailAddresses(canonicalIDs,
// @ts-ignore
{ reqUid: log.getSerializedUids() }, { reqUid: log.getSerializedUids() },
(err: Error | null, info?: any) => { (err, info) => {
if (err) { if (err) {
log.debug('received error message from vault', log.debug('received error message from vault',
{ errorMessage: err }); { errorMessage: err });
@ -286,22 +227,18 @@ export default class Vault {
/** getAccountIds -- call Vault to get accountIds based on /** getAccountIds -- call Vault to get accountIds based on
* canonicalIDs * canonicalIDs
* @param canonicalIDs - list of canonicalIDs * @param {array} canonicalIDs - list of canonicalIDs
* @param log - log object * @param {object} log - log object
* @param callback - callback with either error or an object * @param {function} callback - callback with either error or an object
* with canonicalID keys and accountId values * with canonicalID keys and accountId values
* @return {undefined}
*/ */
getAccountIds( getAccountIds(canonicalIDs, log, callback) {
canonicalIDs: string[],
log: Logger,
callback: (err: Error | null, data?: { [key: string]: string }) => void
) {
log.trace('getting accountIds from Vault based on canonicalIDs', log.trace('getting accountIds from Vault based on canonicalIDs',
{ canonicalIDs }); { canonicalIDs });
this.client.getAccountIds(canonicalIDs, this.client.getAccountIds(canonicalIDs,
// @ts-ignore
{ reqUid: log.getSerializedUids() }, { reqUid: log.getSerializedUids() },
(err: Error | null, info?: any) => { (err, info) => {
if (err) { if (err) {
log.debug('received error message from vault', log.debug('received error message from vault',
{ errorMessage: err }); { errorMessage: err });
@ -334,19 +271,14 @@ export default class Vault {
* @param {object} log - log object * @param {object} log - log object
* @param {function} callback - callback with either error or an array * @param {function} callback - callback with either error or an array
* of authorization results * of authorization results
* @return {undefined}
*/ */
checkPolicies( checkPolicies(requestContextParams, userArn, log, callback) {
requestContextParams: any[],
userArn: string,
log: Logger,
callback: (err: Error | null, data?: any[]) => void
) {
log.trace('sending request context params to vault to evaluate' + log.trace('sending request context params to vault to evaluate' +
'policies'); 'policies');
this.client.checkPolicies(requestContextParams, userArn, { this.client.checkPolicies(requestContextParams, userArn, {
// @ts-ignore
reqUid: log.getSerializedUids(), reqUid: log.getSerializedUids(),
}, (err: Error | null, info?: any) => { }, (err, info) => {
if (err) { if (err) {
log.debug('received error message from auth provider', log.debug('received error message from auth provider',
{ error: err }); { error: err });
@ -357,14 +289,13 @@ export default class Vault {
}); });
} }
checkHealth(log: Logger, callback: (err: Error | null, data?: any) => void) { checkHealth(log, callback) {
if (!this.client.healthcheck) { if (!this.client.healthcheck) {
const defResp = {}; const defResp = {};
defResp[this.implName] = { code: 200, message: 'OK' }; defResp[this.implName] = { code: 200, message: 'OK' };
return callback(null, defResp); return callback(null, defResp);
} }
// @ts-ignore return this.client.healthcheck(log.getSerializedUids(), (err, obj) => {
return this.client.healthcheck(log.getSerializedUids(), (err: Error | null, obj?: any) => {
const respBody = {}; const respBody = {};
if (err) { if (err) {
log.debug(`error from ${this.implName}`, { error: err }); log.debug(`error from ${this.implName}`, { error: err });

View File

@ -1,5 +1,4 @@
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import { Logger } from 'werelogs';
import errors from '../errors'; import errors from '../errors';
import * as queryString from 'querystring'; import * as queryString from 'querystring';
import AuthInfo from './AuthInfo'; import AuthInfo from './AuthInfo';
@ -9,15 +8,15 @@ import * as constants from '../constants';
import constructStringToSignV2 from './v2/constructStringToSign'; import constructStringToSignV2 from './v2/constructStringToSign';
import constructStringToSignV4 from './v4/constructStringToSign'; import constructStringToSignV4 from './v4/constructStringToSign';
import { convertUTCtoISO8601 } from './v4/timeUtils'; import { convertUTCtoISO8601 } from './v4/timeUtils';
import * as vaultUtilities from './backends/in_memory/vaultUtilities'; import * as vaultUtilities from './backends/in_memory/vault-utilities';
import * as inMemoryBackend from './backends/in_memory/Backend'; import * as inMemoryBackend from './backends/in_memory/Backend';
import validateAuthConfig from './backends/in_memory/validateAuthConfig'; import validateAuthConfig from './backends/in_memory/validate-auth-config';
import AuthLoader from './backends/in_memory/AuthLoader'; import AuthLoader from './backends/in_memory/AuthLoader';
import Vault from './Vault'; import Vault from './Vault';
import baseBackend from './backends/BaseBackend'; import baseBackend from './backends/BaseBackend';
import chainBackend from './backends/ChainBackend'; import chainBackend from './backends/ChainBackend';
let vault: Vault | null = null; let vault = null;
const auth = {}; const auth = {};
const checkFunctions = { const checkFunctions = {
v2: { v2: {
@ -34,7 +33,7 @@ const checkFunctions = {
// 'All Users Group' so use this group as the canonicalID for the publicUser // 'All Users Group' so use this group as the canonicalID for the publicUser
const publicUserInfo = new AuthInfo({ canonicalID: constants.publicId }); const publicUserInfo = new AuthInfo({ canonicalID: constants.publicId });
function setAuthHandler(handler: Vault) { function setAuthHandler(handler) {
vault = handler; vault = handler;
return auth; return auth;
} }
@ -42,30 +41,25 @@ function setAuthHandler(handler: Vault) {
/** /**
* This function will check validity of request parameters to authenticate * This function will check validity of request parameters to authenticate
* *
* @param request - Http request object * @param {Http.Request} request - Http request object
* @param log - Logger object * @param {object} log - Logger object
* @param awsService - Aws service related * @param {string} awsService - Aws service related
* @param data - Parameters from queryString parsing or body of * @param {object} data - Parameters from queryString parsing or body of
* POST request * POST request
* *
* @return ret * @return {object} ret
* @return ret.err - arsenal.errors object if any error was found * @return {object} ret.err - arsenal.errors object if any error was found
* @return ret.params - auth parameters to use later on for signature * @return {object} ret.params - auth parameters to use later on for signature
* computation and check * computation and check
* @return ret.params.version - the auth scheme version * @return {object} ret.params.version - the auth scheme version
* (undefined, 2, 4) * (undefined, 2, 4)
* @return ret.params.data - the auth scheme's specific data * @return {object} ret.params.data - the auth scheme's specific data
*/ */
function extractParams( function extractParams(request, log, awsService, data) {
request: any,
log: Logger,
awsService: string,
data: { [key: string]: string }
) {
log.trace('entered', { method: 'Arsenal.auth.server.extractParams' }); log.trace('entered', { method: 'Arsenal.auth.server.extractParams' });
const authHeader = request.headers.authorization; const authHeader = request.headers.authorization;
let version: 'v2' |'v4' | null = null; let version = null;
let method: 'query' | 'headers' | null = null; let method = null;
// Identify auth version and method to dispatch to the right check function // Identify auth version and method to dispatch to the right check function
if (authHeader) { if (authHeader) {
@ -111,21 +105,16 @@ function extractParams(
/** /**
* This function will check validity of request parameters to authenticate * This function will check validity of request parameters to authenticate
* *
* @param request - Http request object * @param {Http.Request} request - Http request object
* @param log - Logger object * @param {object} log - Logger object
* @param cb - the callback * @param {function} cb - the callback
* @param awsService - Aws service related * @param {string} awsService - Aws service related
* @param {RequestContext[] | null} requestContexts - array of RequestContext * @param {RequestContext[] | null} requestContexts - array of RequestContext
* or null if no requestContexts to be sent to Vault (for instance, * or null if no requestContexts to be sent to Vault (for instance,
* in multi-object delete request) * in multi-object delete request)
* @return {undefined}
*/ */
function doAuth( function doAuth(request, log, cb, awsService, requestContexts) {
request: any,
log: Logger,
cb: (err: Error | null, data?: any) => void,
awsService: string,
requestContexts: any[] | null
) {
const res = extractParams(request, log, awsService, request.query); const res = extractParams(request, log, awsService, request.query);
if (res.err) { if (res.err) {
return cb(res.err); return cb(res.err);
@ -134,30 +123,27 @@ function doAuth(
} }
if (requestContexts) { if (requestContexts) {
requestContexts.forEach((requestContext) => { requestContexts.forEach((requestContext) => {
const { params } = res requestContext.setAuthType(res.params.data.authType);
if ('data' in params) { requestContext.setSignatureVersion(
const { data } = params res.params.data.signatureVersion
requestContext.setAuthType(data.authType); );
requestContext.setSignatureVersion(data.signatureVersion); requestContext.setSignatureAge(res.params.data.signatureAge);
requestContext.setSecurityToken(data.securityToken); requestContext.setSecurityToken(res.params.data.securityToken);
if ('signatureAge' in data) {
requestContext.setSignatureAge(data.signatureAge);
}
}
}); });
} }
// Corner cases managed, we're left with normal auth // Corner cases managed, we're left with normal auth
// TODO What's happening here?
// @ts-ignore
res.params.log = log; res.params.log = log;
if (res.params.version === 2) { if (res.params.version === 2) {
// @ts-ignore return vault.authenticateV2Request(res.params, requestContexts, cb);
return vault!.authenticateV2Request(res.params, requestContexts, cb);
} }
if (res.params.version === 4) { if (res.params.version === 4) {
// @ts-ignore return vault.authenticateV4Request(
return vault!.authenticateV4Request(res.params, requestContexts, cb); res.params,
requestContexts,
cb,
awsService
);
} }
log.error('authentication method not found', { log.error('authentication method not found', {
@ -169,24 +155,25 @@ function doAuth(
/** /**
* This function will generate a version 4 header * This function will generate a version 4 header
* *
* @param request - Http request object * @param {Http.Request} request - Http request object
* @param data - Parameters from queryString parsing or body of * @param {object} data - Parameters from queryString parsing or body of
* POST request * POST request
* @param accessKey - the accessKey * @param {string} accessKey - the accessKey
* @param secretKeyValue - the secretKey * @param {string} secretKeyValue - the secretKey
* @param awsService - Aws service related * @param {string} awsService - Aws service related
* @param [proxyPath] - path that gets proxied by reverse proxy * @param {sting} [proxyPath] - path that gets proxied by reverse proxy
* @param [sessionToken] - security token if the access/secret keys * @param {string} [sessionToken] - security token if the access/secret keys
* are temporary credentials from STS * are temporary credentials from STS
* @return {undefined}
*/ */
function generateV4Headers( function generateV4Headers(
request: any, request,
data: { [key: string]: string }, data,
accessKey: string, accessKey,
secretKeyValue: string, secretKeyValue,
awsService: string, awsService,
proxyPath: string, proxyPath,
sessionToken: string sessionToken
) { ) {
Object.assign(request, { headers: {} }); Object.assign(request, { headers: {} });
const amzDate = convertUTCtoISO8601(Date.now()); const amzDate = convertUTCtoISO8601(Date.now());
@ -200,7 +187,7 @@ function generateV4Headers(
let payload = ''; let payload = '';
if (request.method === 'POST') { if (request.method === 'POST') {
payload = queryString.stringify(data, undefined, undefined, { payload = queryString.stringify(data, null, null, {
encodeURIComponent, encodeURIComponent,
}); });
} }

View File

@ -1,70 +1,84 @@
import errors from '../../errors'; import errors from '../../errors';
import { Callback } from './in_memory/types';
/** Base backend class */ /**
* Base backend class
*
* @class BaseBackend
*/
export default class BaseBackend { export default class BaseBackend {
service: string; service
constructor(service: string) { /**
* @constructor
* @param {string} service - service identifer for construction arn
*/
constructor(service) {
this.service = service; this.service = service;
} }
verifySignatureV2( /** verifySignatureV2
_stringToSign: string, * @param {string} stringToSign - string to sign built per AWS rules
_signatureFromRequest: string, * @param {string} signatureFromRequest - signature sent with request
_accessKey: string, * @param {string} accessKey - account accessKey
_options: { algo: 'SHA1' | 'SHA256' }, * @param {object} options - contains algorithm (SHA1 or SHA256)
callback: Callback * @param {function} callback - callback with either error or user info
) { * @return {function} calls callback
*/
verifySignatureV2(stringToSign, signatureFromRequest,
accessKey, options, callback) {
return callback(errors.AuthMethodNotImplemented); return callback(errors.AuthMethodNotImplemented);
} }
verifySignatureV4(
_stringToSign: string, /** verifySignatureV4
_signatureFromRequest: string, * @param {string} stringToSign - string to sign built per AWS rules
_accessKey: string, * @param {string} signatureFromRequest - signature sent with request
_region: string, * @param {string} accessKey - account accessKey
_scopeDate: string, * @param {string} region - region specified in request credential
_options: any, * @param {string} scopeDate - date specified in request credential
callback: Callback * @param {object} options - options to send to Vault
) { * (just contains reqUid for logging in Vault)
* @param {function} callback - callback with either error or user info
* @return {function} calls callback
*/
verifySignatureV4(stringToSign, signatureFromRequest, accessKey,
region, scopeDate, options, callback) {
return callback(errors.AuthMethodNotImplemented); return callback(errors.AuthMethodNotImplemented);
} }
/** /**
* Gets canonical ID's for a list of accounts based on email associated * Gets canonical ID's for a list of accounts
* with account. The callback will be called with either error or object * based on email associated with account
* with email addresses as keys and canonical IDs as values. * @param {array} emails - list of email addresses
* @param {object} options - to send log id to vault
* @param {function} callback - callback to calling function
* @returns {function} callback with either error or
* object with email addresses as keys and canonical IDs
* as values
*/ */
getCanonicalIds(_emails: string[], _options: any, callback: Callback) { getCanonicalIds(emails, options, callback) {
return callback(errors.AuthMethodNotImplemented); return callback(errors.AuthMethodNotImplemented);
} }
/** /**
* Gets email addresses (referred to as diplay names for getACL's) for a * Gets email addresses (referred to as diplay names for getACL's)
* list of accounts based on canonical IDs associated with account. * for a list of accounts based on canonical IDs associated with account
* The callback will be called with either error or an object from Vault * @param {array} canonicalIDs - list of canonicalIDs
* containing account canonicalID as each object key and an email address * @param {object} options - to send log id to vault
* as the value (or "NotFound"). * @param {function} callback - callback to calling function
* @returns {function} callback with either error or
* an object from Vault containing account canonicalID
* as each object key and an email address as the value (or "NotFound")
*/ */
getEmailAddresses( getEmailAddresses(canonicalIDs, options, callback) {
_canonicalIDs: string[],
_options: any,
callback: Callback
) {
return callback(errors.AuthMethodNotImplemented); return callback(errors.AuthMethodNotImplemented);
} }
checkPolicies( checkPolicies(requestContextParams, userArn, options, callback) {
_requestContextParams: any,
_userArn: string,
_options: any,
callback: Callback
) {
return callback(null, { message: { body: [] } }); return callback(null, { message: { body: [] } });
} }
healthcheck(_reqUid: string, callback: Callback) { healthcheck(reqUid, callback) {
return callback(null, { code: 200, message: 'OK' }); return callback(null, { code: 200, message: 'OK' });
} }
} }

View File

@ -1,31 +1,25 @@
import assert from 'assert'; import assert from 'assert';
import async from 'async'; import async from 'async';
import { Callback } from './in_memory/types';
import errors from '../../errors'; import errors from '../../errors';
import BaseBackend from './BaseBackend'; import BaseBackend from './BaseBackend';
export type Policy = {
[key: string]: any;
arn?: string;
versionId?: string;
isAllowed: boolean;
}
/** /**
* Class that provides an authentication backend that will verify signatures * Class that provides an authentication backend that will verify signatures
* and retrieve emails and canonical ids associated with an account using a * and retrieve emails and canonical ids associated with an account using a
* given list of authentication backends and vault clients. * given list of authentication backends and vault clients.
*
* @class ChainBackend
*/ */
export default class ChainBackend extends BaseBackend { export default class ChainBackend extends BaseBackend {
#clients: BaseBackend[]; _clients: any[];
/** /**
* @constructor * @constructor
* @param {string} service - service id * @param {string} service - service id
* @param {object[]} clients - list of authentication backends or vault clients * @param {object[]} clients - list of authentication backends or vault clients
*/ */
constructor(service: string, clients: BaseBackend[]) { constructor(service: string, clients: any[]) {
super(service); super(service);
assert(Array.isArray(clients) && clients.length > 0, 'invalid client list'); assert(Array.isArray(clients) && clients.length > 0, 'invalid client list');
@ -37,28 +31,25 @@ export default class ChainBackend extends BaseBackend {
typeof client.checkPolicies === 'function' && typeof client.checkPolicies === 'function' &&
typeof client.healthcheck === 'function' typeof client.healthcheck === 'function'
), 'invalid client: missing required auth backend methods'); ), 'invalid client: missing required auth backend methods');
this.#clients = clients; this._clients = clients;
} }
/** try task against each client for one to be successful */ /*
#tryEachClient(task: (client: BaseBackend, done?: any) => void, cb: Callback) { * try task against each client for one to be successful
// @ts-ignore */
async.tryEach(this.#clients.map(client => (done: any) => task(client, done)), cb); _tryEachClient(task, cb) {
async.tryEach(this._clients.map(client => done => task(client, done)), cb);
} }
/** apply task to all clients */ /*
#forEachClient(task: (client: BaseBackend, done?: any) => void, cb: Callback) { * apply task to all clients
async.map(this.#clients, task, cb); */
_forEachClient(task, cb) {
async.map(this._clients, task, cb);
} }
verifySignatureV2( verifySignatureV2(stringToSign, signatureFromRequest, accessKey, options, callback) {
stringToSign: string, this._tryEachClient((client, done) => client.verifySignatureV2(
signatureFromRequest: string,
accessKey: string,
options: any,
callback: Callback
) {
this.#tryEachClient((client, done) => client.verifySignatureV2(
stringToSign, stringToSign,
signatureFromRequest, signatureFromRequest,
accessKey, accessKey,
@ -67,39 +58,27 @@ export default class ChainBackend extends BaseBackend {
), callback); ), callback);
} }
verifySignatureV4( verifySignatureV4(stringToSign, signatureFromRequest, accessKey, region, scopeDate, options, callback) {
stringToSign: string, this._tryEachClient((client, done) => client.verifySignatureV4(
signatureFromRequest: string,
accessKey: string,
region: string,
scopeDate: string,
options: any,
callback: Callback
) {
this.#tryEachClient((client, done) => client.verifySignatureV4(
stringToSign, stringToSign,
signatureFromRequest, signatureFromRequest,
accessKey, accessKey,
region, region,
scopeDate, scopeDate,
options, options,
done done
), callback); ), callback);
} }
static _mergeObjects(objectResponses: any[]) { static _mergeObjects(objectResponses) {
return objectResponses.reduce( return objectResponses.reduce(
(retObj, resObj) => Object.assign(retObj, resObj.message.body), (retObj, resObj) => Object.assign(retObj, resObj.message.body),
{} {}
); );
} }
getCanonicalIds( getCanonicalIds(emailAddresses, options, callback) {
emailAddresses: string[], this._forEachClient(
options: any,
callback: Callback<{ message: { body: any } }>
) {
this.#forEachClient(
(client, done) => client.getCanonicalIds(emailAddresses, options, done), (client, done) => client.getCanonicalIds(emailAddresses, options, done),
(err, res) => { (err, res) => {
if (err) { if (err) {
@ -115,12 +94,8 @@ export default class ChainBackend extends BaseBackend {
); );
} }
getEmailAddresses( getEmailAddresses(canonicalIDs, options, callback) {
canonicalIDs: string[], this._forEachClient(
options: any,
callback: Callback<{ message: { body: any } }>
) {
this.#forEachClient(
(client, done) => client.getEmailAddresses(canonicalIDs, options, done), (client, done) => client.getEmailAddresses(canonicalIDs, options, done),
(err, res) => { (err, res) => {
if (err) { if (err) {
@ -135,9 +110,11 @@ export default class ChainBackend extends BaseBackend {
); );
} }
/** merge policy responses into a single message */ /*
static _mergePolicies(policyResponses: { message: { body: any[] } }[]) { * merge policy responses into a single message
const policyMap: { [key: string]: Policy } = {}; */
static _mergePolicies(policyResponses) {
const policyMap = {};
policyResponses.forEach(resp => { policyResponses.forEach(resp => {
if (!resp.message || !Array.isArray(resp.message.body)) { if (!resp.message || !Array.isArray(resp.message.body)) {
@ -154,8 +131,8 @@ export default class ChainBackend extends BaseBackend {
}); });
return Object.keys(policyMap).map((key) => { return Object.keys(policyMap).map((key) => {
const policyRes: Policy = { isAllowed: policyMap[key].isAllowed }; const policyRes = { isAllowed: policyMap[key].isAllowed };
if (policyMap[key].arn && policyMap[key].arn !== '') { if (policyMap[key].arn !== '') {
policyRes.arn = policyMap[key].arn; policyRes.arn = policyMap[key].arn;
} }
if (policyMap[key].versionId) { if (policyMap[key].versionId) {
@ -165,7 +142,7 @@ export default class ChainBackend extends BaseBackend {
}); });
} }
/** /*
response format: response format:
{ message: { { message: {
body: [{}], body: [{}],
@ -173,13 +150,8 @@ export default class ChainBackend extends BaseBackend {
message: string, message: string,
} } } }
*/ */
checkPolicies( checkPolicies(requestContextParams, userArn, options, callback) {
requestContextParams: any, this._forEachClient((client, done) => client.checkPolicies(
userArn: string,
options: any,
callback: Callback<{ message: { body: any } }>
) {
this.#forEachClient((client, done) => client.checkPolicies(
requestContextParams, requestContextParams,
userArn, userArn,
options, options,
@ -196,8 +168,8 @@ export default class ChainBackend extends BaseBackend {
}); });
} }
healthcheck(reqUid: string, callback: Callback) { healthcheck(reqUid, callback) {
this.#forEachClient((client, done) => this._forEachClient((client, done) =>
client.healthcheck(reqUid, (err, res) => done(null, { client.healthcheck(reqUid, (err, res) => done(null, {
error: !!err ? err : null, error: !!err ? err : null,
status: res, status: res,
@ -207,7 +179,7 @@ export default class ChainBackend extends BaseBackend {
return callback(err); return callback(err);
} }
const isError = res.some((results: any) => !!results.error); const isError = res.some((results) => !!results.error);
if (isError) { if (isError) {
return callback(errors.InternalError, res); return callback(errors.InternalError, res);
} }

View File

@ -1,11 +1,11 @@
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import errors from '../../../errors'; import errors from '../../../errors';
import { calculateSigningKey, hashSignature } from './vaultUtilities'; import { calculateSigningKey, hashSignature } from './vault-utilities';
import Indexer from './Indexer'; import Indexer from './Indexer';
import BaseBackend from '../BaseBackend'; import BaseBackend from '../BaseBackend';
import { Accounts } from './types'; import { Accounts } from './types';
function _formatResponse(userInfoToSend: any) { function _formatResponse(userInfoToSend) {
return { return {
message: { message: {
body: { userInfo: userInfoToSend }, body: { userInfo: userInfoToSend },
@ -58,7 +58,6 @@ class InMemoryBackend extends BaseBackend {
accountDisplayName: this.indexer.getAcctDisplayName(entity), accountDisplayName: this.indexer.getAcctDisplayName(entity),
canonicalID: entity.canonicalID, canonicalID: entity.canonicalID,
arn: entity.arn, arn: entity.arn,
// @ts-ignore TODO why ?
IAMdisplayName: entity.IAMdisplayName, IAMdisplayName: entity.IAMdisplayName,
}; };
const vaultReturnObject = _formatResponse(userInfoToSend); const vaultReturnObject = _formatResponse(userInfoToSend);
@ -73,7 +72,7 @@ class InMemoryBackend extends BaseBackend {
accessKey: string, accessKey: string,
region: string, region: string,
scopeDate: string, scopeDate: string,
_options: { algo: 'SHA256' | 'SHA1' }, options: { algo: 'SHA256' | 'SHA1' },
callback: ( callback: (
err: Error | null, err: Error | null,
data?: ReturnType<typeof _formatResponse> data?: ReturnType<typeof _formatResponse>
@ -96,7 +95,6 @@ class InMemoryBackend extends BaseBackend {
accountDisplayName: this.indexer.getAcctDisplayName(entity), accountDisplayName: this.indexer.getAcctDisplayName(entity),
canonicalID: entity.canonicalID, canonicalID: entity.canonicalID,
arn: entity.arn, arn: entity.arn,
// @ts-ignore TODO why ?
IAMdisplayName: entity.IAMdisplayName, IAMdisplayName: entity.IAMdisplayName,
}; };
const vaultReturnObject = _formatResponse(userInfoToSend); const vaultReturnObject = _formatResponse(userInfoToSend);
@ -107,7 +105,7 @@ class InMemoryBackend extends BaseBackend {
// CODEQUALITY-TODO-SYNC Should be synchronous // CODEQUALITY-TODO-SYNC Should be synchronous
getCanonicalIds( getCanonicalIds(
emails: string[], emails: string[],
_log: any, log: any,
cb: (err: null, data: { message: { body: any } }) => void cb: (err: null, data: { message: { body: any } }) => void
) { ) {
const results = {}; const results = {};
@ -132,7 +130,7 @@ class InMemoryBackend extends BaseBackend {
// CODEQUALITY-TODO-SYNC Should be synchronous // CODEQUALITY-TODO-SYNC Should be synchronous
getEmailAddresses( getEmailAddresses(
canonicalIDs: string[], canonicalIDs: string[],
_options: any, options: any,
cb: (err: null, data: { message: { body: any } }) => void cb: (err: null, data: { message: { body: any } }) => void
) { ) {
const results = {}; const results = {};
@ -160,14 +158,14 @@ class InMemoryBackend extends BaseBackend {
* @param canonicalIDs - list of canonicalIDs * @param canonicalIDs - list of canonicalIDs
* @param options - to send log id to vault * @param options - to send log id to vault
* @param cb - callback to calling function * @param cb - callback to calling function
* @return The next is wrong. Here to keep archives. * @returns The next is wrong. Here to keep archives.
* callback with either error or * callback with either error or
* an object from Vault containing account canonicalID * an object from Vault containing account canonicalID
* as each object key and an accountId as the value (or "NotFound") * as each object key and an accountId as the value (or "NotFound")
*/ */
getAccountIds( getAccountIds(
canonicalIDs: string[], canonicalIDs: string[],
_options: any, options: any,
cb: (err: null, data: { message: { body: any } }) => void cb: (err: null, data: { message: { body: any } }) => void
) { ) {
const results = {}; const results = {};

View File

@ -1,5 +1,5 @@
export default function algoCheck(signatureLength: number) { export default function algoCheck(signatureLength) {
let algo: 'sha256' | 'sha1'; let algo;
// If the signature sent is 44 characters, // If the signature sent is 44 characters,
// this means that sha256 was used: // this means that sha256 was used:
// 44 characters in base64 // 44 characters in base64
@ -11,6 +11,5 @@ export default function algoCheck(signatureLength: number) {
if (signatureLength === SHA1LEN) { if (signatureLength === SHA1LEN) {
algo = 'sha1'; algo = 'sha1';
} }
// @ts-ignore
return algo; return algo;
} }

View File

@ -1,9 +1,8 @@
import { Logger } from 'werelogs';
import errors from '../../errors'; import errors from '../../errors';
const epochTime = new Date('1970-01-01').getTime(); const epochTime = new Date('1970-01-01').getTime();
export default function checkRequestExpiry(timestamp: number, log: Logger) { export default function checkRequestExpiry(timestamp, log) {
// If timestamp is before epochTime, the request is invalid and return // If timestamp is before epochTime, the request is invalid and return
// errors.AccessDenied // errors.AccessDenied
if (timestamp < epochTime) { if (timestamp < epochTime) {

View File

@ -1,14 +1,8 @@
import { Logger } from 'werelogs';
import utf8 from 'utf8'; import utf8 from 'utf8';
import getCanonicalizedAmzHeaders from './getCanonicalizedAmzHeaders'; import getCanonicalizedAmzHeaders from './getCanonicalizedAmzHeaders';
import getCanonicalizedResource from './getCanonicalizedResource'; import getCanonicalizedResource from './getCanonicalizedResource';
export default function constructStringToSign( export default function constructStringToSign(request, data, log, clientType?: any) {
request: any,
data: { [key: string]: string },
log: Logger,
clientType?: any
) {
/* /*
Build signature per AWS requirements: Build signature per AWS requirements:
StringToSign = HTTP-Verb + '\n' + StringToSign = HTTP-Verb + '\n' +

View File

@ -1,12 +1,12 @@
export default function getCanonicalizedAmzHeaders(headers: Headers, clientType: string) { export default function getCanonicalizedAmzHeaders(headers, clientType) {
/* /*
Iterate through headers and pull any headers that are x-amz headers. Iterate through headers and pull any headers that are x-amz headers.
Need to include 'x-amz-date' here even though AWS docs Need to include 'x-amz-date' here even though AWS docs
ambiguous on this. ambiguous on this.
*/ */
const filterFn = clientType === 'GCP' ? const filterFn = clientType === 'GCP' ?
(val: string) => val.substr(0, 7) === 'x-goog-' : val => val.substr(0, 7) === 'x-goog-' :
(val: string) => val.substr(0, 6) === 'x-amz-'; val => val.substr(0, 6) === 'x-amz-';
const amzHeaders = Object.keys(headers) const amzHeaders = Object.keys(headers)
.filter(filterFn) .filter(filterFn)
.map(val => [val.trim(), headers[val].trim()]); .map(val => [val.trim(), headers[val].trim()]);

View File

@ -39,7 +39,7 @@ const awsSubresources = [
'website', 'website',
]; ];
export default function getCanonicalizedResource(request: any, clientType: string) { export default function getCanonicalizedResource(request, clientType) {
/* /*
This variable is used to determine whether to insert This variable is used to determine whether to insert
a '?' or '&'. Once a query parameter is added to the resourceString, a '?' or '&'. Once a query parameter is added to the resourceString,

View File

@ -1,11 +1,10 @@
import { Logger } from 'werelogs';
import errors from '../../errors'; import errors from '../../errors';
import * as constants from '../../constants'; import * as constants from '../../constants';
import constructStringToSign from './constructStringToSign'; import constructStringToSign from './constructStringToSign';
import checkRequestExpiry from './checkRequestExpiry'; import checkRequestExpiry from './checkRequestExpiry';
import algoCheck from './algoCheck'; import algoCheck from './algoCheck';
export function check(request: any, log: Logger, data: { [key: string]: string }) { export function check(request, log, data) {
log.trace('running header auth check'); log.trace('running header auth check');
const headers = request.headers; const headers = request.headers;
@ -57,7 +56,6 @@ export function check(request: any, log: Logger, data: { [key: string]: string }
log.trace('invalid authorization header', { authInfo }); log.trace('invalid authorization header', { authInfo });
return { err: errors.MissingSecurityHeader }; return { err: errors.MissingSecurityHeader };
} }
// @ts-ignore
log.addDefaultFields({ accessKey }); log.addDefaultFields({ accessKey });
const signatureFromRequest = authInfo.substring(semicolonIndex + 1).trim(); const signatureFromRequest = authInfo.substring(semicolonIndex + 1).trim();

View File

@ -1,10 +1,9 @@
import { Logger } from 'werelogs';
import errors from '../../errors'; import errors from '../../errors';
import * as constants from '../../constants'; import * as constants from '../../constants';
import algoCheck from './algoCheck'; import algoCheck from './algoCheck';
import constructStringToSign from './constructStringToSign'; import constructStringToSign from './constructStringToSign';
export function check(request: any, log: Logger, data: { [key: string]: string }) { export function check(request, log, data) {
log.trace('running query auth check'); log.trace('running query auth check');
if (request.method === 'POST') { if (request.method === 'POST') {
log.debug('query string auth not supported for post requests'); log.debug('query string auth not supported for post requests');
@ -52,7 +51,6 @@ export function check(request: any, log: Logger, data: { [key: string]: string }
return { err: errors.RequestTimeTooSkewed }; return { err: errors.RequestTimeTooSkewed };
} }
const accessKey = data.AWSAccessKeyId; const accessKey = data.AWSAccessKeyId;
// @ts-ignore
log.addDefaultFields({ accessKey }); log.addDefaultFields({ accessKey });
const signatureFromRequest = decodeURIComponent(data.Signature); const signatureFromRequest = decodeURIComponent(data.Signature);

View File

@ -17,7 +17,7 @@ See http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
*/ */
// converts utf8 character to hex and pads "%" before every two hex digits // converts utf8 character to hex and pads "%" before every two hex digits
function _toHexUTF8(char: string) { function _toHexUTF8(char) {
const hexRep = Buffer.from(char, 'utf8').toString('hex').toUpperCase(); const hexRep = Buffer.from(char, 'utf8').toString('hex').toUpperCase();
let res = ''; let res = '';
hexRep.split('').forEach((v, n) => { hexRep.split('').forEach((v, n) => {
@ -30,11 +30,7 @@ function _toHexUTF8(char: string) {
return res; return res;
} }
export default function awsURIencode( export default function awsURIencode(input, encodeSlash?: any, noEncodeStar?: any) {
input: string,
encodeSlash?: boolean,
noEncodeStar?: boolean
) {
const encSlash = encodeSlash === undefined ? true : encodeSlash; const encSlash = encodeSlash === undefined ? true : encodeSlash;
let encoded = ''; let encoded = '';
/** /**

View File

@ -1,5 +1,4 @@
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import { Logger } from 'werelogs';
import createCanonicalRequest from './createCanonicalRequest'; import createCanonicalRequest from './createCanonicalRequest';
/** /**
@ -7,17 +6,7 @@ import createCanonicalRequest from './createCanonicalRequest';
* @param {object} params - params object * @param {object} params - params object
* @returns {string} - stringToSign * @returns {string} - stringToSign
*/ */
export default function constructStringToSign(params: { export default function constructStringToSign(params): string {
request: any;
signedHeaders: any;
payloadChecksum: any;
credentialScope: string;
timestamp: string;
query: { [key: string]: string };
log?: Logger;
proxyPath: string;
awsService: string;
}): string {
const { const {
request, request,
signedHeaders, signedHeaders,
@ -40,8 +29,6 @@ export default function constructStringToSign(params: {
service: params.awsService, service: params.awsService,
}); });
// TODO Why that line?
// @ts-ignore
if (canonicalReqResult instanceof Error) { if (canonicalReqResult instanceof Error) {
if (log) { if (log) {
log.error('error creating canonicalRequest'); log.error('error creating canonicalRequest');

View File

@ -4,30 +4,22 @@ import * as queryString from 'querystring';
/** /**
* createCanonicalRequest - creates V4 canonical request * createCanonicalRequest - creates V4 canonical request
* @param params - contains pHttpVerb (request type), * @param {object} params - contains pHttpVerb (request type),
* pResource (parsed from URL), pQuery (request query), * pResource (parsed from URL), pQuery (request query),
* pHeaders (request headers), pSignedHeaders (signed headers from request), * pHeaders (request headers), pSignedHeaders (signed headers from request),
* payloadChecksum (from request) * payloadChecksum (from request)
* @returns - canonicalRequest * @returns {string} - canonicalRequest
*/ */
export default function createCanonicalRequest( export default function createCanonicalRequest(params) {
params: {
pHttpVerb: string;
pResource: string;
pQuery: { [key: string]: string };
pHeaders: any;
pSignedHeaders: any;
service: string;
payloadChecksum: string;
}
) {
const pHttpVerb = params.pHttpVerb; const pHttpVerb = params.pHttpVerb;
const pResource = params.pResource; const pResource = params.pResource;
const pQuery = params.pQuery; const pQuery = params.pQuery;
const pHeaders = params.pHeaders; const pHeaders = params.pHeaders;
const pSignedHeaders = params.pSignedHeaders; const pSignedHeaders = params.pSignedHeaders;
const service = params.service; const service = params.service;
let payloadChecksum = params.payloadChecksum; let payloadChecksum = params.payloadChecksum;
if (!payloadChecksum) { if (!payloadChecksum) {
if (pHttpVerb === 'GET') { if (pHttpVerb === 'GET') {
payloadChecksum = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b' + payloadChecksum = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b' +
@ -40,7 +32,7 @@ export default function createCanonicalRequest(
if (/aws-sdk-java\/[0-9.]+/.test(pHeaders['user-agent'])) { if (/aws-sdk-java\/[0-9.]+/.test(pHeaders['user-agent'])) {
notEncodeStar = true; notEncodeStar = true;
} }
let payload = queryString.stringify(pQuery, undefined, undefined, { let payload = queryString.stringify(pQuery, null, null, {
encodeURIComponent: input => awsURIencode(input, true, encodeURIComponent: input => awsURIencode(input, true,
notEncodeStar), notEncodeStar),
}); });
@ -67,11 +59,11 @@ export default function createCanonicalRequest(
// signed headers // signed headers
const signedHeadersList = pSignedHeaders.split(';'); const signedHeadersList = pSignedHeaders.split(';');
signedHeadersList.sort((a: any, b: any) => a.localeCompare(b)); signedHeadersList.sort((a, b) => a.localeCompare(b));
const signedHeaders = signedHeadersList.join(';'); const signedHeaders = signedHeadersList.join(';');
// canonical headers // canonical headers
const canonicalHeadersList = signedHeadersList.map((signedHeader: any) => { const canonicalHeadersList = signedHeadersList.map(signedHeader => {
if (pHeaders[signedHeader] !== undefined) { if (pHeaders[signedHeader] !== undefined) {
const trimmedHeader = pHeaders[signedHeader] const trimmedHeader = pHeaders[signedHeader]
.trim().replace(/\s+/g, ' '); .trim().replace(/\s+/g, ' ');

View File

@ -1,4 +1,3 @@
import { Logger } from 'werelogs';
import errors from '../../../lib/errors'; import errors from '../../../lib/errors';
import * as constants from '../../constants'; import * as constants from '../../constants';
import constructStringToSign from './constructStringToSign'; import constructStringToSign from './constructStringToSign';
@ -15,18 +14,14 @@ import {
/** /**
* V4 header auth check * V4 header auth check
* @param request - HTTP request object * @param {object} request - HTTP request object
* @param log - logging object * @param {object} log - logging object
* @param data - Parameters from queryString parsing or body of * @param {object} data - Parameters from queryString parsing or body of
* POST request * POST request
* @param awsService - Aws service ('iam' or 's3') * @param {string} awsService - Aws service ('iam' or 's3')
* @return {callback} calls callback
*/ */
export function check( export function check(request, log, data, awsService) {
request: any,
log: Logger,
data: { [key: string]: string },
awsService: string
) {
log.trace('running header auth check'); log.trace('running header auth check');
const token = request.headers['x-amz-security-token']; const token = request.headers['x-amz-security-token'];
@ -68,16 +63,16 @@ export function check(
log.trace('authorization header from request', { authHeader }); log.trace('authorization header from request', { authHeader });
const signatureFromRequest = authHeaderItems.signatureFromRequest!; const signatureFromRequest = authHeaderItems.signatureFromRequest;
const credentialsArr = authHeaderItems.credentialsArr!; const credentialsArr = authHeaderItems.credentialsArr;
const signedHeaders = authHeaderItems.signedHeaders!; const signedHeaders = authHeaderItems.signedHeaders;
if (!areSignedHeadersComplete(signedHeaders, request.headers)) { if (!areSignedHeadersComplete(signedHeaders, request.headers)) {
log.debug('signedHeaders are incomplete', { signedHeaders }); log.debug('signedHeaders are incomplete', { signedHeaders });
return { err: errors.AccessDenied }; return { err: errors.AccessDenied };
} }
let timestamp: string | undefined; let timestamp;
// check request timestamp // check request timestamp
const xAmzDate = request.headers['x-amz-date']; const xAmzDate = request.headers['x-amz-date'];
if (xAmzDate) { if (xAmzDate) {
@ -145,7 +140,7 @@ export function check(
return { err: errors.RequestTimeTooSkewed }; return { err: errors.RequestTimeTooSkewed };
} }
let proxyPath: string | null = null; let proxyPath = null;
if (request.headers.proxy_path) { if (request.headers.proxy_path) {
try { try {
proxyPath = decodeURIComponent(request.headers.proxy_path); proxyPath = decodeURIComponent(request.headers.proxy_path);
@ -168,11 +163,9 @@ export function check(
timestamp, timestamp,
payloadChecksum, payloadChecksum,
awsService: service, awsService: service,
proxyPath: proxyPath!, proxyPath,
}); });
log.trace('constructed stringToSign', { stringToSign }); log.trace('constructed stringToSign', { stringToSign });
// TODO Why?
// @ts-ignore
if (stringToSign instanceof Error) { if (stringToSign instanceof Error) {
return { err: stringToSign }; return { err: stringToSign };
} }

View File

@ -1,4 +1,3 @@
import { Logger } from 'werelogs';
import * as constants from '../../constants'; import * as constants from '../../constants';
import errors from '../../errors'; import errors from '../../errors';
@ -9,11 +8,12 @@ import { areSignedHeadersComplete } from './validateInputs';
/** /**
* V4 query auth check * V4 query auth check
* @param request - HTTP request object * @param {object} request - HTTP request object
* @param log - logging object * @param {object} log - logging object
* @param data - Contain authentification params (GET or POST data) * @param {object} data - Contain authentification params (GET or POST data)
* @return {callback} calls callback
*/ */
export function check(request: any, log: Logger, data: { [key: string]: string }) { export function check(request, log, data) {
const authParams = extractQueryParams(data, log); const authParams = extractQueryParams(data, log);
if (Object.keys(authParams).length !== 5) { if (Object.keys(authParams).length !== 5) {
@ -28,11 +28,11 @@ export function check(request: any, log: Logger, data: { [key: string]: string }
return { err: errors.InvalidToken }; return { err: errors.InvalidToken };
} }
const signedHeaders = authParams.signedHeaders!; const signedHeaders = authParams.signedHeaders;
const signatureFromRequest = authParams.signatureFromRequest!; const signatureFromRequest = authParams.signatureFromRequest;
const timestamp = authParams.timestamp!; const timestamp = authParams.timestamp;
const expiry = authParams.expiry!; const expiry = authParams.expiry;
const credential = authParams.credential!; const credential = authParams.credential;
if (!areSignedHeadersComplete(signedHeaders, request.headers)) { if (!areSignedHeadersComplete(signedHeaders, request.headers)) {
log.debug('signedHeaders are incomplete', { signedHeaders }); log.debug('signedHeaders are incomplete', { signedHeaders });
@ -59,7 +59,7 @@ export function check(request: any, log: Logger, data: { [key: string]: string }
return { err: errors.RequestTimeTooSkewed }; return { err: errors.RequestTimeTooSkewed };
} }
let proxyPath: string | null = null; let proxyPath = null;
if (request.headers.proxy_path) { if (request.headers.proxy_path) {
try { try {
proxyPath = decodeURIComponent(request.headers.proxy_path); proxyPath = decodeURIComponent(request.headers.proxy_path);
@ -97,10 +97,8 @@ export function check(request: any, log: Logger, data: { [key: string]: string }
timestamp, timestamp,
credentialScope: `${scopeDate}/${region}/${service}/${requestType}`, credentialScope: `${scopeDate}/${region}/${service}/${requestType}`,
awsService: service, awsService: service,
proxyPath: proxyPath!, proxyPath,
}); });
// TODO Why?
// @ts-ignore
if (stringToSign instanceof Error) { if (stringToSign instanceof Error) {
return { err: stringToSign }; return { err: stringToSign };
} }

View File

@ -1,8 +1,5 @@
import { Transform } from 'stream'; import { Transform } from 'stream';
import async from 'async'; import async from 'async';
import { Logger } from 'werelogs';
import { Callback } from '../../backends/in_memory/types';
import Vault from '../../Vault';
import errors from '../../../errors'; import errors from '../../../errors';
import constructChunkStringToSign from './constructChunkStringToSign'; import constructChunkStringToSign from './constructChunkStringToSign';
@ -11,28 +8,26 @@ import constructChunkStringToSign from './constructChunkStringToSign';
* v4 Auth request * v4 Auth request
*/ */
export default class V4Transform extends Transform { export default class V4Transform extends Transform {
log: Logger; log;
cb: Callback; cb;
accessKey: string; accessKey;
region: string; region;
/** Date parsed from headers in ISO8601. */ scopeDate;
scopeDate: string; timestamp;
/** Date parsed from headers in ISO8601. */ credentialScope;
timestamp: string; lastSignature;
/** Items from auth header, plus the string 'aws4_request' joined with '/': timestamp/region/aws-service/aws4_request */ currentSignature;
credentialScope: string; haveMetadata;
lastSignature?: string; seekingDataSize;
currentSignature?: string; currentData;
haveMetadata: boolean; dataCursor;
seekingDataSize: number; currentMetadata;
currentData?: any; lastPieceDone;
dataCursor: number; lastChunk;
currentMetadata: Buffer[]; vault;
lastPieceDone: boolean;
lastChunk: boolean;
vault: Vault;
/** /**
* @constructor
* @param {object} streamingV4Params - info for chunk authentication * @param {object} streamingV4Params - info for chunk authentication
* @param {string} streamingV4Params.accessKey - requester's accessKey * @param {string} streamingV4Params.accessKey - requester's accessKey
* @param {string} streamingV4Params.signatureFromRequest - signature * @param {string} streamingV4Params.signatureFromRequest - signature
@ -48,19 +43,7 @@ export default class V4Transform extends Transform {
* @param {object} log - logger object * @param {object} log - logger object
* @param {function} cb - callback to api * @param {function} cb - callback to api
*/ */
constructor( constructor(streamingV4Params, vault, log, cb) {
streamingV4Params: {
accessKey: string,
signatureFromRequest: string,
region: string,
scopeDate: string,
timestamp: string,
credentialScope: string
},
vault: Vault,
log: Logger,
cb: Callback
) {
const { const {
accessKey, accessKey,
signatureFromRequest, signatureFromRequest,
@ -94,8 +77,8 @@ export default class V4Transform extends Transform {
/** /**
* This function will parse the metadata portion of the chunk * This function will parse the metadata portion of the chunk
* @param remainingChunk - chunk sent from _transform * @param {Buffer} remainingChunk - chunk sent from _transform
* @return response - if error, will return 'err' key with * @return {object} response - if error, will return 'err' key with
* arsenal error value. * arsenal error value.
* if incomplete metadata, will return 'completeMetadata' key with * if incomplete metadata, will return 'completeMetadata' key with
* value false * value false
@ -103,7 +86,7 @@ export default class V4Transform extends Transform {
* value true and the key 'unparsedChunk' with the remaining chunk without * value true and the key 'unparsedChunk' with the remaining chunk without
* the parsed metadata piece * the parsed metadata piece
*/ */
_parseMetadata(remainingChunk: Buffer) { _parseMetadata(remainingChunk) {
let remainingPlusStoredMetadata = remainingChunk; let remainingPlusStoredMetadata = remainingChunk;
// have metadata pieces so need to add to the front of // have metadata pieces so need to add to the front of
// remainingChunk // remainingChunk
@ -144,8 +127,9 @@ export default class V4Transform extends Transform {
); );
return { err: errors.InvalidArgument }; return { err: errors.InvalidArgument };
} }
let dataSize = splitMeta[0];
// chunk-size is sent in hex // chunk-size is sent in hex
let dataSize = Number.parseInt(splitMeta[0], 16); dataSize = Number.parseInt(dataSize, 16);
if (Number.isNaN(dataSize)) { if (Number.isNaN(dataSize)) {
this.log.trace('chunk body did not contain valid size'); this.log.trace('chunk body did not contain valid size');
return { err: errors.InvalidArgument }; return { err: errors.InvalidArgument };
@ -180,17 +164,17 @@ export default class V4Transform extends Transform {
/** /**
* Build the stringToSign and authenticate the chunk * Build the stringToSign and authenticate the chunk
* @param dataToSend - chunk sent from _transform or null * @param {Buffer} dataToSend - chunk sent from _transform or null
* if last chunk without data * if last chunk without data
* @param done - callback to _transform * @param {function} done - callback to _transform
* @return executes callback with err if applicable * @return {function} executes callback with err if applicable
*/ */
_authenticate(dataToSend: Buffer | null, done: (err?: Error) => void) { _authenticate(dataToSend, done) {
// use prior sig to construct new string to sign // use prior sig to construct new string to sign
const stringToSign = constructChunkStringToSign( const stringToSign = constructChunkStringToSign(
this.timestamp, this.timestamp,
this.credentialScope, this.credentialScope,
this.lastSignature!, this.lastSignature,
dataToSend dataToSend
); );
this.log.trace('constructed chunk string to sign', { stringToSign }); this.log.trace('constructed chunk string to sign', { stringToSign });
@ -209,7 +193,7 @@ export default class V4Transform extends Transform {
credentialScope: this.credentialScope, credentialScope: this.credentialScope,
}, },
}; };
return this.vault.authenticateV4Request(vaultParams, null, (err: Error) => { return this.vault.authenticateV4Request(vaultParams, null, (err) => {
if (err) { if (err) {
this.log.trace('err from vault on streaming v4 auth', { this.log.trace('err from vault on streaming v4 auth', {
error: err, error: err,
@ -221,18 +205,17 @@ export default class V4Transform extends Transform {
}); });
} }
// TODO encoding unused. Why?
/** /**
* This function will parse the chunk into metadata and data, * This function will parse the chunk into metadata and data,
* use the metadata to authenticate with vault and send the * use the metadata to authenticate with vault and send the
* data on to be stored if authentication passes * data on to be stored if authentication passes
* *
* @param chunk - chunk from request body * @param {Buffer} chunk - chunk from request body
* @param encoding - Data encoding * @param {string} encoding - Data encoding
* @param callback - Callback(err, justDataChunk, encoding) * @param {function} callback - Callback(err, justDataChunk, encoding)
* @return executes callback with err if applicable * @return {function }executes callback with err if applicable
*/ */
_transform(chunk: Buffer, _encoding: string, callback: (err?: Error) => void) { _transform(chunk, encoding, callback) {
// 'chunk' here is the node streaming chunk // 'chunk' here is the node streaming chunk
// transfer-encoding chunks should be of the format: // transfer-encoding chunks should be of the format:
// string(IntHexBase(chunk-size)) + ";chunk-signature=" + // string(IntHexBase(chunk-size)) + ";chunk-signature=" +
@ -271,7 +254,7 @@ export default class V4Transform extends Transform {
} }
// have metadata so reset unparsedChunk to remaining // have metadata so reset unparsedChunk to remaining
// without metadata piece // without metadata piece
unparsedChunk = parsedMetadataResults.unparsedChunk!; unparsedChunk = parsedMetadataResults.unparsedChunk;
} }
if (this.lastChunk) { if (this.lastChunk) {
this.log.trace('authenticating final chunk with no data'); this.log.trace('authenticating final chunk with no data');
@ -318,7 +301,7 @@ export default class V4Transform extends Transform {
// final callback // final callback
(err) => { (err) => {
if (err) { if (err) {
return this.cb(err as any); return this.cb(err);
} }
// get next chunk // get next chunk
return callback(); return callback();

View File

@ -3,30 +3,30 @@ import * as constants from '../../../constants';
/** /**
* Constructs stringToSign for chunk * Constructs stringToSign for chunk
* @param timestamp - date parsed from headers in ISO 8601 format: YYYYMMDDTHHMMSSZ * @param {string} timestamp - date parsed from headers
* @param credentialScope - items from auth header plus the string * in ISO 8601 format: YYYYMMDDTHHMMSSZ
* 'aws4_request' joined with '/': * @param {string} credentialScope - items from auth
* header plus the string 'aws4_request' joined with '/':
* timestamp/region/aws-service/aws4_request * timestamp/region/aws-service/aws4_request
* @param lastSignature - signature from headers or prior chunk * @param {string} lastSignature - signature from headers or prior chunk
* @param justDataChunk - data portion of chunk * @param {string} justDataChunk - data portion of chunk
* @returns {string} stringToSign
*/ */
export default function constructChunkStringToSign( export default function constructChunkStringToSign(
timestamp: string, timestamp: string,
credentialScope: string, credentialScope: string,
lastSignature: string, lastSignature: string,
justDataChunk: string | Buffer | null justDataChunk: string
): string { ): string {
let currentChunkHash: string; let currentChunkHash;
// for last chunk, there will be no data, so use emptyStringHash // for last chunk, there will be no data, so use emptyStringHash
if (!justDataChunk) { if (!justDataChunk) {
currentChunkHash = constants.emptyStringHash; currentChunkHash = constants.emptyStringHash;
} else { } else {
let hash = crypto.createHash('sha256'); currentChunkHash = crypto.createHash('sha256');
currentChunkHash = ( currentChunkHash = currentChunkHash
typeof justDataChunk === 'string' .update(justDataChunk, 'binary')
? hash.update(justDataChunk, 'binary') .digest('hex');
: hash.update(justDataChunk)
).digest('hex');
} }
return ( return (
`AWS4-HMAC-SHA256-PAYLOAD\n${timestamp}\n` + `AWS4-HMAC-SHA256-PAYLOAD\n${timestamp}\n` +

View File

@ -1,11 +1,10 @@
import { Logger } from 'werelogs';
/** /**
* Convert timestamp to milliseconds since Unix Epoch * Convert timestamp to milliseconds since Unix Epoch
* @param timestamp of ISO8601Timestamp format without * @param {string} timestamp of ISO8601Timestamp format without
* dashes or colons, e.g. 20160202T220410Z * dashes or colons, e.g. 20160202T220410Z
* @return {number} number of milliseconds since Unix Epoch
*/ */
export function convertAmzTimeToMs(timestamp: string) { export function convertAmzTimeToMs(timestamp) {
const arr = timestamp.split(''); const arr = timestamp.split('');
// Convert to YYYY-MM-DDTHH:mm:ss.sssZ // Convert to YYYY-MM-DDTHH:mm:ss.sssZ
const ISO8601time = `${arr.slice(0, 4).join('')}-${arr[4]}${arr[5]}` + const ISO8601time = `${arr.slice(0, 4).join('')}-${arr[4]}${arr[5]}` +
@ -14,12 +13,13 @@ export function convertAmzTimeToMs(timestamp: string) {
return Date.parse(ISO8601time); return Date.parse(ISO8601time);
} }
/** /**
* Convert UTC timestamp to ISO 8601 timestamp * Convert UTC timestamp to ISO 8601 timestamp
* @param timestamp of UTC form: Fri, 10 Feb 2012 21:34:55 GMT * @param {string} timestamp of UTC form: Fri, 10 Feb 2012 21:34:55 GMT
* @return ISO8601 timestamp of form: YYYYMMDDTHHMMSSZ * @return {string} ISO8601 timestamp of form: YYYYMMDDTHHMMSSZ
*/ */
export function convertUTCtoISO8601(timestamp: string | number) { export function convertUTCtoISO8601(timestamp) {
// convert to ISO string: YYYY-MM-DDTHH:mm:ss.sssZ. // convert to ISO string: YYYY-MM-DDTHH:mm:ss.sssZ.
const converted = new Date(timestamp).toISOString(); const converted = new Date(timestamp).toISOString();
// Remove "-"s and "."s and milliseconds // Remove "-"s and "."s and milliseconds
@ -28,13 +28,13 @@ export function convertUTCtoISO8601(timestamp: string | number) {
/** /**
* Check whether timestamp predates request or is too old * Check whether timestamp predates request or is too old
* @param timestamp of ISO8601Timestamp format without * @param {string} timestamp of ISO8601Timestamp format without
* dashes or colons, e.g. 20160202T220410Z * dashes or colons, e.g. 20160202T220410Z
* @param expiry - number of seconds signature should be valid * @param {number} expiry - number of seconds signature should be valid
* @param log - log for request * @param {object} log - log for request
* @return true if there is a time problem * @return {boolean} true if there is a time problem
*/ */
export function checkTimeSkew(timestamp: string, expiry: number, log: Logger) { export function checkTimeSkew(timestamp, expiry, log) {
const currentTime = Date.now(); const currentTime = Date.now();
const fifteenMinutes = (15 * 60 * 1000); const fifteenMinutes = (15 * 60 * 1000);
const parsedTimestamp = convertAmzTimeToMs(timestamp); const parsedTimestamp = convertAmzTimeToMs(timestamp);

View File

@ -1,19 +1,15 @@
import { Logger } from 'werelogs';
import errors from '../../../lib/errors'; import errors from '../../../lib/errors';
/** /**
* Validate Credentials * Validate Credentials
* @param credentials - contains accessKey, scopeDate, * @param {array} credentials - contains accessKey, scopeDate,
* region, service, requestType * region, service, requestType
* @param timestamp - timestamp from request in * @param {string} timestamp - timestamp from request in
* the format of ISO 8601: YYYYMMDDTHHMMSSZ * the format of ISO 8601: YYYYMMDDTHHMMSSZ
* @param log - logging object * @param {object} log - logging object
* @return {boolean} true if credentials are correct format, false if not
*/ */
export function validateCredentials( export function validateCredentials(credentials, timestamp, log) {
credentials: [string, string, string, string, string],
timestamp: string,
log: Logger
): Error | {} {
if (!Array.isArray(credentials) || credentials.length !== 5) { if (!Array.isArray(credentials) || credentials.length !== 5) {
log.warn('credentials in improper format', { credentials }); log.warn('credentials in improper format', { credentials });
return errors.InvalidArgument; return errors.InvalidArgument;
@ -67,21 +63,12 @@ export function validateCredentials(
/** /**
* Extract and validate components from query object * Extract and validate components from query object
* @param queryObj - query object from request * @param {object} queryObj - query object from request
* @param log - logging object * @param {object} log - logging object
* @return object containing extracted query params for authV4 * @return {object} object containing extracted query params for authV4
*/ */
export function extractQueryParams( export function extractQueryParams(queryObj, log) {
queryObj: { [key: string]: string | undefined }, const authParams = {};
log: Logger
) {
const authParams: {
signedHeaders?: string;
signatureFromRequest?: string;
timestamp?: string;
expiry?: number;
credential?: [string, string, string, string, string];
} = {};
// Do not need the algorithm sent back // Do not need the algorithm sent back
if (queryObj['X-Amz-Algorithm'] !== 'AWS4-HMAC-SHA256') { if (queryObj['X-Amz-Algorithm'] !== 'AWS4-HMAC-SHA256') {
@ -118,7 +105,7 @@ export function extractQueryParams(
return authParams; return authParams;
} }
const expiry = Number.parseInt(queryObj['X-Amz-Expires'] ?? 'nope', 10); const expiry = Number.parseInt(queryObj['X-Amz-Expires'], 10);
const sevenDays = 604800; const sevenDays = 604800;
if (expiry && expiry > 0 && expiry <= sevenDays) { if (expiry && expiry > 0 && expiry <= sevenDays) {
authParams.expiry = expiry; authParams.expiry = expiry;
@ -129,7 +116,6 @@ export function extractQueryParams(
const credential = queryObj['X-Amz-Credential']; const credential = queryObj['X-Amz-Credential'];
if (credential && credential.length > 28 && credential.indexOf('/') > -1) { if (credential && credential.length > 28 && credential.indexOf('/') > -1) {
// @ts-ignore
authParams.credential = credential.split('/'); authParams.credential = credential.split('/');
} else { } else {
log.warn('invalid credential param', { credential }); log.warn('invalid credential param', { credential });
@ -140,16 +126,12 @@ export function extractQueryParams(
/** /**
* Extract and validate components from auth header * Extract and validate components from auth header
* @param authHeader - authorization header from request * @param {string} authHeader - authorization header from request
* @param log - logging object * @param {object} log - logging object
* @return object containing extracted auth header items for authV4 * @return {object} object containing extracted auth header items for authV4
*/ */
export function extractAuthItems(authHeader: string, log: Logger) { export function extractAuthItems(authHeader, log) {
const authItems: { const authItems = {};
credentialsArr?: [string, string, string, string, string];
signedHeaders?: string;
signatureFromRequest?: string;
} = {};
const authArray = authHeader.replace('AWS4-HMAC-SHA256 ', '').split(','); const authArray = authHeader.replace('AWS4-HMAC-SHA256 ', '').split(',');
if (authArray.length < 3) { if (authArray.length < 3) {
@ -165,7 +147,6 @@ export function extractAuthItems(authHeader: string, log: Logger) {
credentialStr.trim().startsWith('Credential=') && credentialStr.trim().startsWith('Credential=') &&
credentialStr.indexOf('/') > -1 credentialStr.indexOf('/') > -1
) { ) {
// @ts-ignore
authItems.credentialsArr = credentialStr authItems.credentialsArr = credentialStr
.trim() .trim()
.replace('Credential=', '') .replace('Credential=', '')
@ -198,11 +179,11 @@ export function extractAuthItems(authHeader: string, log: Logger) {
/** /**
* Checks whether the signed headers include the host header * Checks whether the signed headers include the host header
* and all x-amz- and x-scal- headers in request * and all x-amz- and x-scal- headers in request
* @param signedHeaders - signed headers sent with request * @param {string} signedHeaders - signed headers sent with request
* @param allHeaders - request.headers * @param {object} allHeaders - request.headers
* @return true if all x-amz-headers included and false if not * @return {boolean} true if all x-amz-headers included and false if not
*/ */
export function areSignedHeadersComplete(signedHeaders: string, allHeaders: Headers) { export function areSignedHeadersComplete(signedHeaders, allHeaders) {
const signedHeadersList = signedHeaders.split(';'); const signedHeadersList = signedHeaders.split(';');
if (signedHeadersList.indexOf('host') === -1) { if (signedHeadersList.indexOf('host') === -1) {
return false; return false;

View File

@ -5,7 +5,7 @@ const assert = require('assert');
const constructStringToSign = const constructStringToSign =
require('../../../../lib/auth/v2/constructStringToSign').default; require('../../../../lib/auth/v2/constructStringToSign').default;
const hashSignature = const hashSignature =
require('../../../../lib/auth/backends/in_memory/vaultUtilities').hashSignature; require('../../../../lib/auth/backends/in_memory/vault-utilities').hashSignature;
const DummyRequestLogger = require('../../helpers').DummyRequestLogger; const DummyRequestLogger = require('../../helpers').DummyRequestLogger;
const log = new DummyRequestLogger(); const log = new DummyRequestLogger();

View File

@ -3,7 +3,7 @@
const assert = require('assert'); const assert = require('assert');
const calculateSigningKey = const calculateSigningKey =
require('../../../../lib/auth/backends/in_memory/vaultUtilities') require('../../../../lib/auth/backends/in_memory/vault-utilities')
.calculateSigningKey; .calculateSigningKey;
describe('v4 signing key calculation', () => { describe('v4 signing key calculation', () => {