Skip to content

Commit

Permalink
fix: 401 for missing cookie or token (#71)
Browse files Browse the repository at this point in the history
* 401 for missing cookie or token

* Linting

* Use newer node version for optional chaining

* Use the same node version in Circle as in Dockerfile

* Replace 'python' with 'python3' in Circle

* Remove audit resolver, it's more trouble than it's worth in this repo

* Remove audit resolve vestige of resolver.
  • Loading branch information
partiallyordered authored May 20, 2021
1 parent 55a4abf commit 36c46a7
Show file tree
Hide file tree
Showing 23 changed files with 2,481 additions and 48,223 deletions.
6 changes: 3 additions & 3 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ defaults_Dependencies: &defaults_Dependencies |
apk --no-cache add ca-certificates
apk --no-cache add curl
apk --no-cache add openssh-client
apk add --no-cache -t build-dependencies make gcc g++ python libtool autoconf automake
apk add --no-cache -t build-dependencies make gcc g++ python3 libtool autoconf automake
npm config set unsafe-perm true
npm install -g node-gyp

Expand Down Expand Up @@ -49,7 +49,7 @@ executors:
default-docker:
working_directory: /home/circleci/project
docker:
- image: node:12.16.1-alpine
- image: node:15-alpine3.13

default-machine:
machine:
Expand Down Expand Up @@ -120,7 +120,7 @@ jobs:
command: mkdir -p /tmp/audit/results
- run:
name: Check for new npm vulnerabilities
command: cd src && npm run audit:check --silent -- --json > /tmp/audit/results/auditResults.json
command: cd src && npm audit --production --json > /tmp/audit/results/auditResults.json
- store_artifacts:
path: /tmp/audit/results
prefix: audit
Expand Down
56 changes: 0 additions & 56 deletions Makefile

This file was deleted.

3 changes: 3 additions & 0 deletions src/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
"env": {
"node": true
},
"parserOptions": {
"ecmaVersion": 2020
},
"rules": {
"indent": [
"error",
Expand Down
43,196 changes: 0 additions & 43,196 deletions src/audit-resolve.json

This file was deleted.

25 changes: 12 additions & 13 deletions src/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ const previousSettlementWindowDataQuery = `
ORDER BY close DESC
`;


// TODO: change the line 'AND sw.createdDate < (...)' to 'AND sw.createdDate = (...)'
// TODO: evaluate what information in this query is not necessary for the UI
// TODO: remove the LIMIT 1 clause at the end of this query
Expand Down Expand Up @@ -659,8 +658,8 @@ module.exports = class Database {
async getHistoricalSettlementWindowData({ participantName, fromDateTime, toDateTime }) {
const windows = await this.connection.query(historicalSettlementWindowDataQuery,
[participantName, participantName, fromDateTime, toDateTime])
.then(d => d[0])
.then(ws => ws.map(w => (
.then((d) => d[0])
.then((ws) => ws.map((w) => (
{ ...w, payments: Number(w.payments), receipts: Number(w.receipts) })));

// Now we need to get the ndc and limit history for each currency present
Expand All @@ -679,7 +678,7 @@ module.exports = class Database {
async getLimitAndPositionHistory({
currencies, participantName, fromDateTime, toDateTime,
}) {
return Promise.all(currencies.map(curr => Promise.all([
return Promise.all(currencies.map((curr) => Promise.all([
curr,
this.connection.query(
historicalParticipantLimitQuery,
Expand All @@ -695,7 +694,7 @@ module.exports = class Database {
participantName,
curr,
],
).then(l => l[0]),
).then((l) => l[0]),
this.connection.query(
historicalParticipantPositionQuery,
[
Expand All @@ -710,20 +709,20 @@ module.exports = class Database {
participantName,
toDateTime,
],
).then(p => p[0]),
).then((p) => p[0]),
]).then(([curr, limits, positions]) => [ // eslint-disable-line no-shadow
// parse numeric values
curr,
limits.map(l => ({ ...l, lim: Number(l.lim) })),
positions.map(p => ({ ...p, value: Number(p.value) })),
limits.map((l) => ({ ...l, lim: Number(l.lim) })),
positions.map((p) => ({ ...p, value: Number(p.value) })),
])));
}

async getPreviousSettlementWindowData({ participantName }) {
const windows = await this
.connection.query(previousSettlementWindowDataQuery, [participantName, participantName])
.then(d => d[0])
.then(ws => ws.map(w => ({
.then((d) => d[0])
.then((ws) => ws.map((w) => ({
...w,
payments: Number(w.payments),
receipts: Number(w.receipts),
Expand Down Expand Up @@ -764,8 +763,8 @@ module.exports = class Database {

// TODO: use const participantAmount = netAmount.map(...) here?
netAmount.forEach((element) => {
const inRecord = inAmount.find(n => n.fspId === element.fspId);
const outRecord = outAmount.find(n => n.fspId === element.fspId);
const inRecord = inAmount.find((n) => n.fspId === element.fspId);
const outRecord = outAmount.find((n) => n.fspId === element.fspId);
const inValue = inRecord ? inRecord.inAmount : 0;
const outValue = outRecord ? outRecord.outAmount : 0;
const obj = {
Expand All @@ -779,7 +778,7 @@ module.exports = class Database {
});
const totalAmounts = sumAllParticipants(participantAmount);
const sumTotalAmount = convertParticipantsAmountsToStrings(totalAmounts);
const result = settlementWindow.filter(n => n.settlementWindowId !== null);
const result = settlementWindow.filter((n) => n.settlementWindowId !== null);
return {
settlementWindow: (result.length === 1 ? result[0] : {}),
participantAmount,
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/accounts.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const handler = (router, routesContext) => {
const accounts = await getParticipantAccounts(
routesContext.config.centralLedgerEndpoint, ctx.params.participantName,
);
ctx.response.body = accounts.filter(a => a.isActive === 1);
ctx.response.body = accounts.filter((a) => a.isActive === 1);
ctx.response.status = 200;
await next();
});
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/emailAddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const handler = (router, routesContext) => {
const emailAddresses = await getParticipantEmailAddresses(
routesContext.config.centralLedgerEndpoint, participantName, routesContext.log,
);
const emailAddress = emailAddresses.filter(a => a.type === emailType);
const emailAddress = emailAddresses.filter((a) => a.type === emailType);
[ctx.response.body] = emailAddress;
ctx.response.status = 200;
await next();
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/historical-window-summary.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,17 @@ const handler = (router, routesContext) => {
// Defaults (RHS of ||) here because it's possible a limit or position did not
// exist before this window
limit: (history[w.curr].limits
.find(l => l.createdDate < w.close) || { lim: 0 }).lim,
.find((l) => l.createdDate < w.close) || { lim: 0 }).lim,
position: (history[w.curr].positions
.find(p => p.createdDate < w.close) || { value: 0 }).value,
.find((p) => p.createdDate < w.close) || { value: 0 }).value,
},
},
}), {});

// Note that windowCount should never be zero when currencies is a non-empty array;
// therefore the following code should never cause a divide by zero
const windowCount = Object.keys(windows).length;
const average = Object.assign(...currencies.map(curr => ({
const average = Object.assign(...currencies.map((curr) => ({
[curr]: {
payments: {
num: windowArr.reduce((pv, w) => pv + w.numPayments, 0) / windowCount,
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const handler = (router, routesContext) => {
};

const oauth2Token = await fetch(routesContext.config.auth.loginEndpoint, opts)
.then(res => res.json());
.then((res) => res.json());
if (oauth2Token.access_token === undefined) {
ctx.response.status = 401; // TODO: Or 403?
return;
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/netdebitcap.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const handler = (router, routesContext) => {
const accounts = await getParticipantAccounts(
routesContext.config.centralLedgerEndpoint, ctx.params.participantName,
);
const positionAccounts = accounts.filter(a => a.ledgerAccountType === 'POSITION'
const positionAccounts = accounts.filter((a) => a.ledgerAccountType === 'POSITION'
&& a.isActive === 1);
const ndc = await Promise.all(positionAccounts.map(async (acc) => {
const limit = await getNDC(
Expand Down Expand Up @@ -36,7 +36,7 @@ const handler = (router, routesContext) => {
routesContext.config.centralLedgerEndpoint, ctx.params.participantName,
);
const positionAccounts = accounts
.filter(a => a.ledgerAccountType === 'POSITION' && a.id === ctx.request.body.accountId);
.filter((a) => a.ledgerAccountType === 'POSITION' && a.id === ctx.request.body.accountId);
const ndc = await Promise.all(positionAccounts.map(async (acc) => {
const limit = await getNDC(
routesContext.config.centralLedgerEndpoint,
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/previous-window.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,19 @@ const handler = (router, routesContext) => {
...acc.limits,
[w.curr]: {
value: (history[w.curr].limits
.find(l => l.createdDate < w.close) || { lim: 0 }).lim,
.find((l) => l.createdDate < w.close) || { lim: 0 }).lim,
},
},
positions: {
...acc.positions,
[w.curr]: {
value: (history[w.curr].positions
.find(p => p.createdDate < w.close) || { value: 0 }).value,
.find((p) => p.createdDate < w.close) || { value: 0 }).value,
},
},
}), {});

const netPositions = Object.keys(result.payments).map(curr => ({
const netPositions = Object.keys(result.payments).map((curr) => ({
[curr]: result.payments[curr].value - result.receipts[curr].value,
}));

Expand Down
21 changes: 11 additions & 10 deletions src/handlers/settlements.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,18 @@ const handler = (router, routesContext) => {
const api = new Model({ endpoint: routesContext.config.centralSettlementsEndpoint });

const filterParticipants = (ps, f) => ps
.filter(p => p.accounts.findIndex(a => f(a.netSettlementAmount.amount)) !== -1)
.map(p => (
{ ...p, accounts: p.accounts.filter(a => f(a.netSettlementAmount.amount)) }));
.filter((p) => p.accounts.findIndex((a) => f(a.netSettlementAmount.amount)) !== -1)
.map((p) => (
{ ...p, accounts: p.accounts.filter((a) => f(a.netSettlementAmount.amount)) }));

// payers settlement amount will be positive and payees will be negative
const getPayers = ps => filterParticipants(ps, x => x > 0);
const getPayees = ps => filterParticipants(ps, x => x < 0);
const getPayers = (ps) => filterParticipants(ps, (x) => x > 0);
const getPayees = (ps) => filterParticipants(ps, (x) => x < 0);
const payers = getPayers(ctx.request.body.participants);
const payees = getPayees(ctx.request.body.participants);
const newParticipantsAccountState = (ps, reason, state) => ps.map(p => ({
const newParticipantsAccountState = (ps, reason, state) => ps.map((p) => ({
...p,
accounts: p.accounts.map(a => ({ id: a.id, reason, state })),
accounts: p.accounts.map((a) => ({ id: a.id, reason, state })),
}));

const payerParticipants = newParticipantsAccountState(payers, 'Payee: SETTLED, settlement: SETTLED', 'SETTLED');
Expand All @@ -49,7 +49,7 @@ const handler = (router, routesContext) => {
} finally {
const settlements = await api.getSettlements({ fromDateTime, toDateTime });
const updatedSettlement = settlements
.filter(a => a.id.toString() === ctx.params.settlementId);
.filter((a) => a.id.toString() === ctx.params.settlementId);
ctx.response.body = updatedSettlement[0] || {};
}
await next();
Expand All @@ -65,8 +65,9 @@ const handler = (router, routesContext) => {
} = qs.parse(ctx.request.querystring);
const api = new Model({ endpoint: routesContext.config.centralSettlementsEndpoint });
const settlements = await api.getSettlements({ fromDateTime, toDateTime });
ctx.response.body = settlements
.filter(s => s.participants.some(p => p.id === parseInt(ctx.params.participantId, 10)));
ctx.response.body = settlements.filter(
(s) => s.participants.some((p) => p.id === parseInt(ctx.params.participantId, 10)),
);
ctx.response.status = 200;
await next();
});
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/validate-transfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ const AzureLog = require('../lib/azureLogUtil');

const dir = './secrets';
const pubKeys = fs.readdirSync(dir)
.filter(fname => !fs.statSync(`${dir}/${fname}`).isDirectory())
.map(fname => fs.readFileSync(`${dir}/${fname}`, 'utf-8'));
.filter((fname) => !fs.statSync(`${dir}/${fname}`).isDirectory())
.map((fname) => fs.readFileSync(`${dir}/${fname}`, 'utf-8'));

const handler = (router, routesContext) => {
router.get('/validate-transfer/:transferId', async (ctx, next) => {
Expand All @@ -30,7 +30,7 @@ const handler = (router, routesContext) => {
const token = `${check.protectedHeader}.${check.body}.${check.signature}`;

try {
isValidTransfer = pubKeys.some(pubKey => JWT.verify(token, pubKey));
isValidTransfer = pubKeys.some((pubKey) => JWT.verify(token, pubKey));
} catch (err) {
routesContext.log(`Error validating JWS token: ${err.stack || util.inspect(err)}`);
}
Expand Down
9 changes: 5 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ const createServer = require('./server');
const Database = require('./db');
const config = require('./config/config');
const log = require('./lib/log');
const { version } = require('./package.json');

// /////////////////////////////////////////////////////////////////////////////
// Config
// /////////////////////////////////////////////////////////////////////////////

// Set up the db
const db = new Database(config.db);

// Log development/production status
log('Running portal version ', version);
log('Running in ', process.env.NODE_ENV);

// Set up the db
const db = new Database(config.db);

// Warnings for certain environment var settings
if (config.cors.reflectOrigin && process.env.NODE_ENV !== 'development') {
log('WARNING: NODE_ENV != \'development\' and CORS origin being reflected in Access-Control-Allow-Origin header. '
Expand All @@ -22,7 +24,6 @@ if (config.auth.bypass) {
log('WARNING: auth bypass enabled- all login requests will be approved');
}


// /////////////////////////////////////////////////////////////////////////////
// Start app
// /////////////////////////////////////////////////////////////////////////////
Expand Down
6 changes: 3 additions & 3 deletions src/lib/dbHelpers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Sum all the amounts for all given currencies into an array of objects.
const sumAllParticipants = participantAmount => participantAmount.filter(a => !a.fspId.includes('DFSP'))
const sumAllParticipants = (participantAmount) => participantAmount.filter((a) => !a.fspId.includes('DFSP'))
.reduce((total, participantAmnt) => {
const amounts = total;
if (Object.keys(total).length === 0) {
Expand All @@ -14,8 +14,8 @@ const sumAllParticipants = participantAmount => participantAmount.filter(a => !a
}, {});

// Convert the result from sumAllParticipants into fixed strings
const convertParticipantsAmountsToStrings = totalAmounts => Object.keys(totalAmounts)
.map(currency => ({ [currency]: totalAmounts[currency].toFixed(4).toString() }));
const convertParticipantsAmountsToStrings = (totalAmounts) => Object.keys(totalAmounts)
.map((currency) => ({ [currency]: totalAmounts[currency].toFixed(4).toString() }));

module.exports = {
sumAllParticipants,
Expand Down
Loading

0 comments on commit 36c46a7

Please sign in to comment.