Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(IAM Authenticator): add support for optional 'scope' property #109

Merged
merged 1 commit into from
Sep 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions auth/authenticators/iam-authenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export interface Options extends BaseOptions {
* authorization header for IAM token requests.
*/
clientSecret?: string;

/**
* The "scope" parameter to use when fetching the bearer token from the IAM token server.
*/
scope?: string;
}

/**
Expand All @@ -52,6 +57,7 @@ export class IamAuthenticator extends TokenRequestBasedAuthenticator {
private apikey: string;
private clientId: string;
private clientSecret: string;
private scope: string;

/**
*
Expand All @@ -68,6 +74,8 @@ export class IamAuthenticator extends TokenRequestBasedAuthenticator {
* authorization header for IAM token requests.
* @param {string} [options.clientSecret] The `clientId` and `clientSecret` fields are used to form a "basic"
* authorization header for IAM token requests.
* @param {string} [options.scope] The "scope" parameter to use when fetching the bearer token from the
* IAM token server.
* @throws {Error} When the configuration options are not valid.
*/
constructor(options: Options) {
Expand All @@ -78,6 +86,7 @@ export class IamAuthenticator extends TokenRequestBasedAuthenticator {
this.apikey = options.apikey;
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.scope = options.scope;

// the param names are shared between the authenticator and the token
// manager so we can just pass along the options object
Expand All @@ -98,4 +107,15 @@ export class IamAuthenticator extends TokenRequestBasedAuthenticator {
// update properties in token manager
this.tokenManager.setClientIdAndSecret(clientId, clientSecret);
}

/**
* Setter for the "scope" parameter to use when fetching the bearer token from the IAM token server.
* @param {string} scope A space seperated string that makes up the scope parameter
*/
public setScope(scope: string): void {
this.scope = scope;

// update properties in token manager
this.tokenManager.setScope(scope);
}
}
22 changes: 22 additions & 0 deletions auth/token-managers/iam-token-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ function onlyOne(a: any, b: any): boolean {
}

const CLIENT_ID_SECRET_WARNING = 'Warning: Client ID and Secret must BOTH be given, or the header will not be included.';
const SCOPE = 'scope';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know that a constant here is really necessary but I also don't have a problem with it. Up to you but I thought I would at least say that. If you find it helpful, I'm fine with it


/** Configuration options for IAM token retrieval. */
interface Options extends JwtTokenManagerOptions {
apikey: string;
clientId?: string;
clientSecret?: string;
scope?: string;
}

/**
Expand All @@ -53,6 +55,7 @@ export class IamTokenManager extends JwtTokenManager {
private apikey: string;
private clientId: string;
private clientSecret: string;
private scope: string;

/**
*
Expand Down Expand Up @@ -87,12 +90,27 @@ export class IamTokenManager extends JwtTokenManager {
if (options.clientSecret) {
this.clientSecret = options.clientSecret;
}
if (options.scope) {
this.scope = options.scope;
}
if (onlyOne(options.clientId, options.clientSecret)) {
// tslint:disable-next-line
logger.warn(CLIENT_ID_SECRET_WARNING);
}
}

/**
* Set the IAM `scope` value.
* This value is the form parameter to use when fetching the bearer token
* from the IAM token server.
*
* @param {string} scope - A space seperated string that makes up the scope parameter.
* @returns {void}
*/
public setScope(scope: string): void {
this.scope = scope;
}

/**
* Set the IAM `clientId` and `clientSecret` values.
* These values are used to compute the Authorization header used
Expand Down Expand Up @@ -143,6 +161,10 @@ export class IamTokenManager extends JwtTokenManager {
}
};

if (this.scope) {
parameters.options.form[SCOPE] = this.scope;
}

return this.requestWrapperInstance.sendRequest(parameters);
}
}
11 changes: 10 additions & 1 deletion test/resources/ibm-credentials.env
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ TEST_SERVICE_AUTH_DISABLE_SSL=true
# service properties
TEST_SERVICE_URL=service.com/api
TEST_SERVICE_DISABLE_SSL=true
TEST_SERVICE_SCOPE=A B C D

# Service1 auth properties configured with IAM and a token containing '='
SERVICE_1_AUTH_TYPE=iam
Expand All @@ -19,4 +20,12 @@ SERVICE_1_AUTH_URL=https://iamhost/iam/api=
SERVICE_1_AUTH_DISABLE_SSL=

# Service1 service properties
SERVICE_1_URL=service1.com/api
SERVICE_1_URL=service1.com/api

# Service2 configured with IAM w/scope
SERVICE_2_AUTH_TYPE=iam
SERVICE_2_APIKEY=V4HXmoUtMjohnsnow=KotN
SERVICE_2_CLIENT_ID=somefake========id
SERVICE_2_CLIENT_SECRET===my-client-secret==
SERVICE_2_AUTH_URL=https://iamhost/iam/api=
SERVICE_2_SCOPE=A B C D
15 changes: 15 additions & 0 deletions test/unit/get-authenticator-from-environment.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ describe('Get Authenticator From Environment Module', () => {
getAuthenticatorFromEnvironment(SERVICE_NAME);
}).toThrow();
});

it('should get iam authenticator and set the scope', () => {
setUpIamPayloadWithScope();
const authenticator = getAuthenticatorFromEnvironment(SERVICE_NAME);
expect(authenticator).toBeInstanceOf(IamAuthenticator);
expect(authenticator.scope).toBe('jon snow');
});
});

// mock payloads for the read-external-sources module
Expand Down Expand Up @@ -120,6 +127,14 @@ function setUpIamPayload() {
}));
}

function setUpIamPayloadWithScope() {
readExternalSourcesMock.mockImplementation(() => ({
authType: 'iam',
apikey: APIKEY,
scope: 'jon snow',
}));
}

function setUpCp4dPayload() {
readExternalSourcesMock.mockImplementation(() => ({
authType: 'cp4d',
Expand Down
17 changes: 17 additions & 0 deletions test/unit/iam-authenticator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe('IAM Authenticator', () => {
headers: {
'X-My-Header': 'some-value',
},
scope: 'A B C D',
};

it('should store all config options on the class', () => {
Expand All @@ -32,6 +33,7 @@ describe('IAM Authenticator', () => {
expect(authenticator.clientSecret).toBe(config.clientSecret);
expect(authenticator.disableSslVerification).toBe(config.disableSslVerification);
expect(authenticator.headers).toEqual(config.headers);
expect(authenticator.scope).toEqual(config.scope);

// should also create a token manager
expect(authenticator.tokenManager).toBeInstanceOf(IamTokenManager);
Expand Down Expand Up @@ -64,6 +66,9 @@ describe('IAM Authenticator', () => {

// verify that the original options are kept intact
expect(options.headers['X-Some-Header']).toBe('user-supplied header');
// verify the scope param wasn't set
expect(authenticator.scope).toBeUndefined();
expect(authenticator.tokenManager.scope).toBeUndefined();
done();
});

Expand Down Expand Up @@ -105,4 +110,16 @@ describe('IAM Authenticator', () => {
// also, verify that the underlying token manager has been updated
expect(authenticator.tokenManager.headers).toEqual(newHeader);
});

it('should re-set the scope using the setter', () => {
const authenticator = new IamAuthenticator(config);
expect(authenticator.headers).toEqual(config.headers);

const newScope = 'john snow';
authenticator.setScope(newScope);
expect(authenticator.scope).toEqual(newScope);

// also, verify that the underlying token manager has been updated
expect(authenticator.tokenManager.scope).toEqual(newScope);
});
});
86 changes: 86 additions & 0 deletions test/unit/iam-token-manager.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBeUndefined();
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

Expand All @@ -149,6 +151,25 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBe('Basic Zm9vOmJhcg==');
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

it('should include scope form param based on scope via ctor', async done => {
const instance = new IamTokenManager({
apikey: 'abcd-1234',
scope: 'john snow',
});

mockSendRequest.mockImplementation(parameters => Promise.resolve(IAM_RESPONSE));

await instance.getToken();
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const form = sendRequestArgs.options.form;
expect(form).not.toBeNull();
const scope = form.scope;
expect(scope).toBe('john snow');
done();
});

Expand All @@ -170,6 +191,8 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBeUndefined();
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

Expand All @@ -190,6 +213,25 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBeUndefined();
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

it('should not include scope form param based on scope via ctor', async done => {
const instance = new IamTokenManager({
apikey: 'abcd-1234',
scope: null,
});

mockSendRequest.mockImplementation(parameters => Promise.resolve(IAM_RESPONSE));

await instance.getToken();
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const form = sendRequestArgs.options.form;
expect(form).not.toBeNull();
const scope = form.scope;
expect(scope).toBeUndefined();
done();
});

Expand All @@ -206,6 +248,44 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBe('Basic Zm9vOmJhcg==');
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

it('should include scope form param based on scope via setter', async done => {
const instance = new IamTokenManager({
apikey: 'abcd-1234',
});

instance.setScope('john snow');

mockSendRequest.mockImplementation(parameters => Promise.resolve(IAM_RESPONSE));

await instance.getToken();
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const form = sendRequestArgs.options.form;
expect(form).not.toBeNull();
const scope = form.scope;
expect(scope).toBe('john snow');
done();
});

it('should not include scope form param based on scope via setter', async done => {
const instance = new IamTokenManager({
apikey: 'abcd-1234',
});

instance.setScope(null);

mockSendRequest.mockImplementation(parameters => Promise.resolve(IAM_RESPONSE));

await instance.getToken();
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const form = sendRequestArgs.options.form;
expect(form).not.toBeNull();
const scope = form.scope;
expect(scope).toBeUndefined();
done();
});

Expand All @@ -228,6 +308,8 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBeUndefined();
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

Expand All @@ -250,6 +332,8 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBeUndefined();
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});

Expand All @@ -266,6 +350,8 @@ describe('iam_token_manager_v1', function() {
const sendRequestArgs = mockSendRequest.mock.calls[0][0];
const authHeader = sendRequestArgs.options.headers.Authorization;
expect(authHeader).toBeUndefined();
const scope = sendRequestArgs.options.form.scope;
expect(scope).toBeUndefined();
done();
});
});
7 changes: 7 additions & 0 deletions test/unit/read-credentials-file.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ describe('read ibm credentials file', () => {
expect(obj.SERVICE_1_CLIENT_SECRET).toBe('==my-client-secret==');
expect(obj.SERVICE_1_AUTH_DISABLE_SSL).toBe('');
expect(obj.SERVICE_1_URL).toBe('service1.com/api');

expect(obj.SERVICE_2_AUTH_TYPE).toBe('iam');
expect(obj.SERVICE_2_APIKEY).toBe('V4HXmoUtMjohnsnow=KotN');
expect(obj.SERVICE_2_AUTH_URL).toBe('https://iamhost/iam/api=');
expect(obj.SERVICE_2_CLIENT_ID).toBe('somefake========id');
expect(obj.SERVICE_2_CLIENT_SECRET).toBe('==my-client-secret==');
expect(obj.SERVICE_2_SCOPE).toBe('A B C D');
});

it('should return credentials as an object for alternate filename', () => {
Expand Down
Loading