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

refactor: consume dynamic env vars from SSM rather than env vars [CHI-2897] #801

Open
wants to merge 28 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
36331bc
refactor: consume dynamic env vars from SSM rather than env vars
GPaoloni Dec 30, 2024
498fe9d
fix: lint
GPaoloni Dec 30, 2024
d5a82a6
fix: TS error in resources service
GPaoloni Dec 30, 2024
38f60ce
fix: remove unnecessary TS dep
GPaoloni Jan 2, 2025
31ada77
chore: add type option to lambdas tsconfig
GPaoloni Jan 2, 2025
3d5a281
fix: TS errors in test
GPaoloni Jan 2, 2025
59192c2
fix: added node types to job-complete
GPaoloni Jan 2, 2025
6705de2
fix: tests types
GPaoloni Jan 2, 2025
2b51e79
fix: mock types
GPaoloni Jan 2, 2025
e93a888
fix: docker file runs root npm ci to include common deps
GPaoloni Jan 2, 2025
b2e3ca0
fix: mock open rules
GPaoloni Jan 2, 2025
a06a3c3
fix: add ts as explicit dev dep
GPaoloni Jan 2, 2025
641f4c9
chore: rollback deps
GPaoloni Jan 3, 2025
55aaf15
Revert "chore: rollback deps"
GPaoloni Jan 3, 2025
d80b3fc
chore: revert all deps
GPaoloni Jan 3, 2025
d37dfee
chore: ssm cache defined within each module, removed extra package
GPaoloni Jan 3, 2025
f78d0ac
fix: test mocks type errors
GPaoloni Jan 3, 2025
e218024
fix: more ts errors in tests
GPaoloni Jan 3, 2025
a0e0f61
fix: ssm mocks
GPaoloni Jan 3, 2025
7563f9a
fix: unit tests
GPaoloni Jan 3, 2025
ab41b26
refactor: twilio worker auth package expects lookup functions as para…
GPaoloni Jan 14, 2025
8e8951c
refactor: hrm and resources service provide auth secrets lookup funct…
GPaoloni Jan 14, 2025
36761fb
fix: unit test
GPaoloni Jan 14, 2025
83166d0
fix: rollback unintended change
GPaoloni Jan 14, 2025
e0981a5
fix: service tests
GPaoloni Jan 14, 2025
da91db0
fix: missing lookup function in resources service
GPaoloni Jan 15, 2025
7abede2
Merge remote-tracking branch 'origin/master' into gian_CHI-2897
GPaoloni Jan 15, 2025
6707ee0
fix: missing lookup function in internal hrm service
GPaoloni Jan 15, 2025
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
21 changes: 14 additions & 7 deletions hrm-domain/hrm-core/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,21 @@ import {
adminAuthorizationMiddleware,
staticKeyAuthorizationMiddleware,
} from '@tech-matters/twilio-worker-auth';
import { defaultAuthSecretsLookup } from './config/authSecretsLookup';
import type { AuthSecretsLookup } from '@tech-matters/twilio-worker-auth';
import { adminApiV0, internalApiV0 } from './routes';
import { AccountSID } from '@tech-matters/types';
import { setupPermissions } from './permissions';

type ServiceCreationOptions = Partial<{
permissions: Permissions;
authTokenLookup: (accountSid: AccountSID) => string;
authSecretsLookup: AuthSecretsLookup;
enableProcessContactJobs: boolean;
webServer: Express;
}>;

export function configureService({
permissions = jsonPermissions,
authTokenLookup,
authSecretsLookup = defaultAuthSecretsLookup,
webServer = express(),
}: ServiceCreationOptions = {}) {
webServer.get('/', (req, res) => {
Expand All @@ -47,14 +48,20 @@ export function configureService({
});
});

setUpHrmRoutes(webServer, authTokenLookup, permissions);
setUpHrmRoutes(webServer, authSecretsLookup, permissions);

console.log(`${new Date().toLocaleString()}: app.js has been created`);

return webServer;
}

export const configureInternalService = ({ webServer }: { webServer: Express }) => {
export const configureInternalService = ({
webServer,
authSecretsLookup,
}: {
webServer: Express;
authSecretsLookup: AuthSecretsLookup;
}) => {
webServer.get('/', (req, res) => {
res.json({
Message: 'HRM internal service is up and running!',
Expand All @@ -64,15 +71,15 @@ export const configureInternalService = ({ webServer }: { webServer: Express })
webServer.use(
'/admin/v0/accounts/:accountSid',
addAccountSidMiddleware,
adminAuthorizationMiddleware('ADMIN_HRM'),
adminAuthorizationMiddleware(authSecretsLookup.staticKeyLookup)('ADMIN_HRM'),
setupPermissions(openPermissions),
adminApiV0(),
);

webServer.use(
'/internal/v0/accounts/:accountSid',
addAccountSidMiddleware,
staticKeyAuthorizationMiddleware,
staticKeyAuthorizationMiddleware(authSecretsLookup.staticKeyLookup),
setupPermissions(openPermissions),
internalApiV0(),
);
Expand Down
42 changes: 42 additions & 0 deletions hrm-domain/hrm-core/config/authSecretsLookup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Copyright (C) 2021-2023 Technology Matters
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import type { AuthSecretsLookup } from '@tech-matters/twilio-worker-auth';
import { getFromSSMCache } from './ssm-cache';

const authTokenLookup = async (accountSid: string) => {
if (process.env[`TWILIO_AUTH_TOKEN_${accountSid}`]) {
return process.env[`TWILIO_AUTH_TOKEN_${accountSid}`] || '';
}

const { authToken } = await getFromSSMCache(accountSid);
return authToken;
};

const staticKeyLookup = async (keySuffix: string) => {
const staticSecretKey = `STATIC_KEY_${keySuffix}`;
if (process.env[staticSecretKey]) {
return process.env[staticSecretKey] || '';
}

const { staticKey } = await getFromSSMCache(keySuffix);
return staticKey;
};

export const defaultAuthSecretsLookup: AuthSecretsLookup = {
authTokenLookup,
staticKeyLookup,
};
66 changes: 66 additions & 0 deletions hrm-domain/hrm-core/config/ssm-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we revert this back to the correct file naming convention? i.e. camel case

Copy link
Collaborator

Choose a reason for hiding this comment

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

In fact, given it's specialised nature, perhaps we could call it something like ssmConfigurationCache?

* Copyright (C) 2021-2023 Technology Matters
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import { loadSsmCache as loadSsmCacheRoot, ssmCache } from '@tech-matters/ssm-cache';

import env from 'dotenv';

env.config();

const ssmCacheConfigs = [
{
path: `/${process.env.NODE_ENV}/${
process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION
}/sqs/jobs/contact`,
regex: /queue-url-*/,
},
{
path: `/${process.env.NODE_ENV}/twilio`,
regex: /\/.*\/static_key/,
},
{
path: `/${process.env.NODE_ENV}/twilio`,
regex: /\/.*\/auth_token/,
},
{
path: `/${process.env.NODE_ENV}/config`,
regex: /\/.*\/permission_config/,
},
];

export const loadSsmCache = async () => {
await loadSsmCacheRoot({
configs: ssmCacheConfigs,
cacheDurationMilliseconds: 3600000 * 24, // cache for a day
});
};

export const getFromSSMCache = async (accountSid: string) => {
// does nothing if cache is still valid
await loadSsmCache();

return {
staticKey:
ssmCache.values[`/${process.env.NODE_ENV}/twilio/${accountSid}/static_key`]
?.value || '',
authToken:
ssmCache.values[`/${process.env.NODE_ENV}/twilio/${accountSid}/auth_token`]
?.value || '',
permissionConfig:
ssmCache.values[`/${process.env.NODE_ENV}/config/${accountSid}/permission_config`]
?.value || '',
};
};
32 changes: 0 additions & 32 deletions hrm-domain/hrm-core/config/ssmCache.ts

This file was deleted.

3 changes: 1 addition & 2 deletions hrm-domain/hrm-core/contact-job/client-sqs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@ import {
receiveSqsMessage,
sendSqsMessage,
} from '@tech-matters/sqs-client';
import { getSsmParameter } from '../config/ssmCache';

import type { PublishToContactJobsTopicParams } from '@tech-matters/types';
import { SsmParameterNotFound } from '@tech-matters/ssm-cache';
import { SsmParameterNotFound, getSsmParameter } from '@tech-matters/ssm-cache';

const COMPLETED_QUEUE_SSM_PATH = `/${process.env.NODE_ENV}/${
process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION
Expand Down
3 changes: 1 addition & 2 deletions hrm-domain/hrm-core/contact-job/contact-job-publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ import {
} from './contact-job-data-access';
import { publishToContactJobs } from './client-sqs';
import { assertExhaustive, ContactJobType } from '@tech-matters/types';
import { getSsmParameter } from '../config/ssmCache';
import { SsmParameterNotFound } from '@tech-matters/ssm-cache';
import { SsmParameterNotFound, getSsmParameter } from '@tech-matters/ssm-cache';

export const publishRetrieveContactTranscript = (
contactJob: RetrieveContactTranscriptJob,
Expand Down
1 change: 0 additions & 1 deletion hrm-domain/hrm-core/contact/canPerformContactAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ const canPerformActionOnContact = (
const accountSid = user.accountSid;
const twilioClient = await getClient({
accountSid,
authToken: process.env[`TWILIO_AUTH_TOKEN_${accountSid}`],
});
const isTransferTarget = await isTwilioTaskTransferTarget(
twilioClient,
Expand Down
3 changes: 1 addition & 2 deletions hrm-domain/hrm-core/notifications/entityChangeNotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@
*/

import { sendSqsMessage } from '@tech-matters/sqs-client';
import { getSsmParameter } from '../config/ssmCache';
import { SsmParameterNotFound, getSsmParameter } from '@tech-matters/ssm-cache';
import { IndexMessage } from '@tech-matters/hrm-search-config';
import { CaseService, Contact } from '@tech-matters/hrm-types';
import { AccountSID, HrmAccountId } from '@tech-matters/types';
import { publishSns, PublishSnsParams } from '@tech-matters/sns-client';
import { SsmParameterNotFound } from '@tech-matters/ssm-cache';
import { NotificationOperation } from '@tech-matters/hrm-types';

type DeleteNotificationPayload = {
Expand Down
6 changes: 3 additions & 3 deletions hrm-domain/hrm-core/permissions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ declare global {
const canCache: Record<string, InitializedCan> = {};

export type Permissions = {
rules: (accountSid: AccountSID) => RulesFile;
rules: (accountSid: AccountSID) => Promise<RulesFile>;
cachePermissions: boolean;
};

Expand All @@ -54,10 +54,10 @@ export const applyPermissions = (req: Request, initializedCan: InitializedCan) =
};

export const setupPermissions =
(lookup: Permissions) => (req: Request, res: Response, next: NextFunction) => {
(lookup: Permissions) => async (req: Request, res: Response, next: NextFunction) => {
const { accountSid } = <TwilioUser>(<any>req).user;

const accountRules = lookup.rules(accountSid);
const accountRules = await lookup.rules(accountSid);
if (lookup.cachePermissions) {
canCache[accountSid] = canCache[accountSid] ?? initializeCanForRules(accountRules);
const initializedCan = canCache[accountSid];
Expand Down
37 changes: 25 additions & 12 deletions hrm-domain/hrm-core/permissions/json-permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,41 +14,54 @@
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import { getFromSSMCache } from '../config/ssm-cache';
import { rulesMap } from './rulesMap';
import { Permissions } from './index';
import { AccountSID } from '@tech-matters/types';

export const getPermissionsConfigName = (accountSid: AccountSID) => {
export const getPermissionsConfigName = async (accountSid: AccountSID) => {
const permissionsKey = `PERMISSIONS_${accountSid}`;

const permissionsConfigName = process.env[permissionsKey];
if (process.env[permissionsKey]) {
const permissionConfig = process.env[permissionsKey];

if (!permissionsConfigName)
throw new Error(`No permissions set for account ${accountSid}.`);
if (!rulesMap[permissionConfig])
throw new Error(
`Permissions rules with name ${permissionConfig} missing in rules map.`,
);

if (!rulesMap[permissionsConfigName])
return permissionConfig;
}

const { permissionConfig } = await getFromSSMCache(accountSid);

if (!permissionConfig) throw new Error(`No permissions set for account ${accountSid}.`);

if (!rulesMap[permissionConfig])
throw new Error(
`Permissions rules with name ${permissionsConfigName} missing in rules map.`,
`Permissions rules with name ${permissionConfig} missing in rules map.`,
);

return permissionsConfigName;
return permissionConfig;
};

/**
* @throws Will throw if there is no env var set for PERMISSIONS_${accountSid} or if it's an invalid key in rulesMap
*/
export const jsonPermissions: Permissions = {
rules: (accountSid: AccountSID) => {
const permissionsConfigName = getPermissionsConfigName(accountSid);
rules: async (accountSid: AccountSID) => {
const permissionConfig = await getPermissionsConfigName(accountSid);

const rules = rulesMap[permissionsConfigName];
if (!rules) throw new Error(`Cannot find rules for ${permissionsConfigName}`);
const rules = rulesMap[permissionConfig];
if (!rules) throw new Error(`Cannot find rules for ${permissionConfig}`);
return rules;
},
cachePermissions: true,
};

export const openPermissions: Permissions = {
rules: () => rulesMap.open,
rules: () => Promise.resolve(rulesMap.open),
cachePermissions: true,
};

export const openRules = rulesMap.open;
38 changes: 21 additions & 17 deletions hrm-domain/hrm-core/permissions/permissions-routes-v0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,28 @@ import { TResult, newErr, isErr, newOk, mapHTTPError } from '@tech-matters/types

export default (permissions: Permissions) => {
const permissionsRouter = SafeRouter();
permissionsRouter.get('/', publicEndpoint, (req: Request, res: Response, next) => {
try {
const { accountSid } = req.user;
if (!permissions.rules) {
return next(
createError(
400,
'Reading rules is not supported by the permissions implementation being used by this instance of the HRM service.',
),
);
}
const rules = permissions.rules(accountSid);
permissionsRouter.get(
'/',
publicEndpoint,
async (req: Request, res: Response, next) => {
try {
const { accountSid } = req.user;
if (!permissions.rules) {
return next(
createError(
400,
'Reading rules is not supported by the permissions implementation being used by this instance of the HRM service.',
),
);
}
const rules = await permissions.rules(accountSid);

res.json(rules);
} catch (error) {
return next(createError(500, error.message));
}
});
res.json(rules);
} catch (error) {
return next(createError(500, error.message));
}
},
);

const parseActionGetPayload = ({
objectType,
Expand Down
Loading
Loading