Skip to content

Commit

Permalink
Add tests for each auth type
Browse files Browse the repository at this point in the history
Signed-off-by: Derek Ho <[email protected]>
  • Loading branch information
derek-ho committed Feb 19, 2024
1 parent ace02e2 commit 6b76c4c
Show file tree
Hide file tree
Showing 7 changed files with 357 additions and 0 deletions.
78 changes: 78 additions & 0 deletions server/auth/types/basic/basic_auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright OpenSearch Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

import { httpServerMock } from '../../../../../../src/core/server/http/http_server.mocks';

import { SecurityPluginConfigType } from '../../../index';
import { SecuritySessionCookie } from '../../../session/security_cookie';
import {
IRouter,
CoreSetup,
ILegacyClusterClient,
Logger,
SessionStorageFactory,
} from '../../../../../../src/core/server';
import { BasicAuthentication } from './basic_auth';

describe('Basic auth tests', () => {
let router: IRouter;
let core: CoreSetup;
let esClient: ILegacyClusterClient;
let sessionStorageFactory: SessionStorageFactory<SecuritySessionCookie>;
let logger: Logger;

// Consistent with auth_handler_factory.test.ts
beforeEach(() => {});

const config = ({
saml: {
extra_storage: {
cookie_prefix: 'testcookie',
additional_cookies: 5,
},
},
session: {
ttl: 1000,
},
} as unknown) as SecurityPluginConfigType;

test('getKeepAliveExpiry', () => {
const realDateNow = Date.now.bind(global.Date);
const dateNowStub = jest.fn(() => 0);
global.Date.now = dateNowStub;
const proxyAuthentication = new BasicAuthentication(
config,
sessionStorageFactory,
router,
esClient,
core,
logger
);

const cookie: SecuritySessionCookie = {
credentials: {
authHeaderValueExtra: true,
},
expiryTime: 0,
};

const request = httpServerMock.createOpenSearchDashboardsRequest({
path: '/internal/v1',
});

expect(proxyAuthentication.getKeepAliveExpiry(cookie, request)).toBe(1000);
global.Date.now = realDateNow;
});
});
1 change: 1 addition & 0 deletions server/auth/types/jwt/jwt_auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ export class JwtAuthentication extends AuthenticationType {
}

getKeepAliveExpiry(cookie: SecuritySessionCookie, request: OpenSearchDashboardsRequest): number {
console.log(this.buildAuthHeaderFromCookie(cookie, request)[this.authHeaderName]);
return getExpirationDate(
this.buildAuthHeaderFromCookie(cookie, request)[this.authHeaderName],
Date.now() + this.config.session.ttl
Expand Down
66 changes: 66 additions & 0 deletions server/auth/types/jwt/jwt_helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ const JWT_TEST_NO_EXP =
const JWT_TEST_FAR_EXP =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJleGFtcGxlLmNvbSIsInN1YiI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiZXhwIjoxMzAwODE5MzgwMCwibmFtZSI6IkpvaG4gRG9lIiwicm9sZXMiOiJhZG1pbiJ9.ciW9WWtIaA-QJqy0flPSfMNQfGs9GEFqcNFY_LqrdII'; // A test JWT with a far off exp claim

const JWT_TEST_NEAR_EXP =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJleGFtcGxlLmNvbSIsInN1YiI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiZXhwIjo1MCwibmFtZSI6IkpvaG4gRG9lIiwicm9sZXMiOiJhZG1pbiJ9.96_h7V_OrO-bHzhh1DUIOJ2_J2sEI8y--cjBOBonk2o'; // A test JWT with exp claim of 50

const router: Partial<IRouter> = { post: (body) => {} };
const core = {
http: {
Expand Down Expand Up @@ -339,5 +342,68 @@ describe('test jwt auth library', () => {
expect(cookieFromURL.expiryTime!).toBe(1000);
});

test('getKeepAliveExpiry', () => {
const keepAliveConfig = {
multitenancy: {
enabled: false,
},
auth: {
unauthenticated_routes: [] as string[],
},
session: {
keepalive: true,
ttl: 100000,
},
jwt: {
url_param: 'awesome',
header: 'AUTHORIZATION',
extra_storage: {
cookie_prefix: 'testcookie',
additional_cookies: 2,
},
},
} as SecurityPluginConfigType;

const jwtAuth = new JwtAuthentication(
keepAliveConfig,
sessionStorageFactory,
router,
esClient,
coreSetup,
logger
);

const requestWithHeaders = httpServerMock.createOpenSearchDashboardsRequest({
path: '/internal/v1',
headers: {
authorization: `Bearer ${JWT_TEST}`,
},
});

const cookie: SecuritySessionCookie = {
credentials: {},
expiryTime: 1000,
};

// Mock the method with a JWT with far exp
jest.spyOn(jwtAuth, 'buildAuthHeaderFromCookie').mockReturnValue({
authorization: `Bearer ${JWT_TEST_FAR_EXP}`,
});

// getKeepAliveExpiry takes on the value of the ttl, since it is less than the exp claim * 1000
expect(jwtAuth.getKeepAliveExpiry(cookie, requestWithHeaders)).toBe(100000);

// Mock the method with a JWT with near exp
jest.spyOn(jwtAuth, 'buildAuthHeaderFromCookie').mockReturnValue({
authorization: `Bearer ${JWT_TEST_NEAR_EXP}`,
});

// getKeepAliveExpiry takes on the value of the exp claim * 1000, since it is less than the ttl
expect(jwtAuth.getKeepAliveExpiry(cookie, requestWithHeaders)).toBe(50000);

// Restore the original method implementation after the test
jwtAuth.buildAuthHeaderFromCookie.mockRestore();
});

/* eslint-enable no-shadow, @typescript-eslint/no-var-requires */
});
78 changes: 78 additions & 0 deletions server/auth/types/multiple/multi_auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright OpenSearch Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

import { httpServerMock } from '../../../../../../src/core/server/http/http_server.mocks';

import { OpenSearchDashboardsRequest } from '../../../../../../src/core/server/http/router';

import { SecurityPluginConfigType } from '../../../index';
import { SecuritySessionCookie } from '../../../session/security_cookie';
import { deflateValue } from '../../../utils/compression';
import {
IRouter,
CoreSetup,
ILegacyClusterClient,
Logger,
SessionStorageFactory,
} from '../../../../../../src/core/server';
import { MultipleAuthentication } from './multi_auth';

describe('Multi auth tests', () => {
let router: IRouter;
let core: CoreSetup;
let esClient: ILegacyClusterClient;
let sessionStorageFactory: SessionStorageFactory<SecuritySessionCookie>;
let logger: Logger;

// Consistent with auth_handler_factory.test.ts
beforeEach(() => {});

const config = ({
session: {
ttl: 1000,
},
auth: {
type: 'basic',
},
} as unknown) as SecurityPluginConfigType;

test('getKeepAliveExpiry', () => {
const realDateNow = Date.now.bind(global.Date);
const dateNowStub = jest.fn(() => 0);
global.Date.now = dateNowStub;
const proxyAuthentication = new MultipleAuthentication(
config,
sessionStorageFactory,
router,
esClient,
core,
logger
);

const cookie: SecuritySessionCookie = {
credentials: {
authHeaderValueExtra: true,
},
expiryTime: 1000,
};

const request = httpServerMock.createOpenSearchDashboardsRequest({
path: '/internal/v1',
});

expect(proxyAuthentication.getKeepAliveExpiry(cookie, request)).toBe(1000); // Multi auth using basic auth's implementation
global.Date.now = realDateNow;
});
});
32 changes: 32 additions & 0 deletions server/auth/types/openid/openid_auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,36 @@ describe('test OpenId authHeaderValue', () => {
expect(await openIdAuthentication.isValidCookie(testCookie, {})).toBe(true);
global.Date.now = realDateNow;
});

test('getKeepAliveExpiry', () => {
const customConfig = {
openid: {
pfx: 'test/certs/keyStore.p12',
certificate: 'test/certs/cert.pem',
private_key: 'test/certs/private-key.pem',
passphrase: '',
header: 'authorization',
scope: [],
},
};

const openidConfig = (customConfig as unknown) as SecurityPluginConfigType;

const openIdAuthentication = new OpenIdAuthentication(
openidConfig,
sessionStorageFactory,
router,
esClient,
core,
logger
);
const testCookie: SecuritySessionCookie = {
credentials: {
authHeaderValue: 'Bearer eyToken',
},
expiryTime: 1000,
};

expect(openIdAuthentication.getKeepAliveExpiry(testCookie, {})).toBe(1000);
});
});
78 changes: 78 additions & 0 deletions server/auth/types/proxy/proxy_auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright OpenSearch Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

import { httpServerMock } from '../../../../../../src/core/server/http/http_server.mocks';

import { SecurityPluginConfigType } from '../../../index';
import { SecuritySessionCookie } from '../../../session/security_cookie';
import {
IRouter,
CoreSetup,
ILegacyClusterClient,
Logger,
SessionStorageFactory,
} from '../../../../../../src/core/server';
import { ProxyAuthentication } from './proxy_auth';

describe('Proxy auth tests', () => {
let router: IRouter;
let core: CoreSetup;
let esClient: ILegacyClusterClient;
let sessionStorageFactory: SessionStorageFactory<SecuritySessionCookie>;
let logger: Logger;

// Consistent with auth_handler_factory.test.ts
beforeEach(() => {});

const config = ({
saml: {
extra_storage: {
cookie_prefix: 'testcookie',
additional_cookies: 5,
},
},
session: {
ttl: 1000,
},
} as unknown) as SecurityPluginConfigType;

test('getKeepAliveExpiry', () => {
const realDateNow = Date.now.bind(global.Date);
const dateNowStub = jest.fn(() => 0);
global.Date.now = dateNowStub;
const proxyAuthentication = new ProxyAuthentication(
config,
sessionStorageFactory,
router,
esClient,
core,
logger
);

const cookie: SecuritySessionCookie = {
credentials: {
authHeaderValueExtra: true,
},
expiryTime: 1000,
};

const request = httpServerMock.createOpenSearchDashboardsRequest({
path: '/internal/v1',
});

expect(proxyAuthentication.getKeepAliveExpiry(cookie, request)).toBe(1000);
global.Date.now = realDateNow;
});
});
24 changes: 24 additions & 0 deletions server/auth/types/saml/saml_auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,28 @@ describe('test SAML authHeaderValue', () => {

expect(headers).toEqual(expectedHeaders);
});

test('getKeepAliveExpiry', () => {
const samlAuthentication = new SamlAuthentication(
config,
sessionStorageFactory,
router,
esClient,
core,
logger
);

const cookie: SecuritySessionCookie = {
credentials: {
authHeaderValueExtra: true,
},
expiryTime: 1000,
};

const request = httpServerMock.createOpenSearchDashboardsRequest({
path: '/internal/v1',
});

expect(samlAuthentication.getKeepAliveExpiry(cookie, request)).toBe(1000);
});
});

0 comments on commit 6b76c4c

Please sign in to comment.