Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin' into python-saved-search-endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
chrtorres committed Sep 30, 2024
2 parents 242040e + c82ff3b commit 3e75136
Show file tree
Hide file tree
Showing 72 changed files with 3,314 additions and 2,654 deletions.
1 change: 0 additions & 1 deletion .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
name: UI Testing
on:
deployment_status:
push:
defaults:
run:
working-directory: ./playwright
Expand Down
160 changes: 130 additions & 30 deletions backend/src/api/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import * as search from './search';
import * as vulnerabilities from './vulnerabilities';
import * as organizations from './organizations';
import * as scans from './scans';
import * as logs from './logs';
import * as users from './users';
import * as scanTasks from './scan-tasks';
import * as stats from './stats';
Expand All @@ -22,12 +23,13 @@ import * as reports from './reports';
import * as savedSearches from './saved-searches';
import rateLimit from 'express-rate-limit';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { User, UserType, connectToDatabase } from '../models';
import { Organization, User, UserType, connectToDatabase } from '../models';
import * as assessments from './assessments';
import * as jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';
import fetch from 'node-fetch';
import * as searchOrganizations from './organizationSearch';
import { Logger, RecordMessage } from '../tools/logger';

const sanitizer = require('sanitizer');

Expand All @@ -43,27 +45,41 @@ if (
setInterval(() => scheduler({}, {} as any, () => null), 30000);
}

const handlerToExpress = (handler) => async (req, res) => {
const { statusCode, body } = await handler(
{
pathParameters: req.params,
query: req.query,
requestContext: req.requestContext,
body: JSON.stringify(req.body || '{}'),
headers: req.headers,
path: req.originalUrl
},
{}
);
try {
const parsedBody = JSON.parse(sanitizer.sanitize(body));
res.status(statusCode).json(parsedBody);
} catch (e) {
// Not a JSON body
res.setHeader('content-type', 'text/plain');
res.status(statusCode).send(sanitizer.sanitize(body));
}
};
const handlerToExpress =
(handler, message?: RecordMessage, action?: string) => async (req, res) => {
const logger = new Logger(req);
const { statusCode, body } = await handler(
{
pathParameters: req.params,
query: req.query,
requestContext: req.requestContext,
body: JSON.stringify(req.body || '{}'),
headers: req.headers,
path: req.originalUrl
},
{}
);
// Add additional status codes that we may return for succesfull requests
if (statusCode === 200) {
if (message && action) {
logger.record(action, 'success', message, body);
}
} else {
if (message && action) {
logger.record(action, 'fail', message, body);
}
}

try {
const parsedBody = JSON.parse(sanitizer.sanitize(body));
res.status(200).json(parsedBody);
} catch (e) {
// Not valid JSON - may be a string response.
console.log('Error?', e);
res.setHeader('content-type', 'text/plain');
res.status(statusCode).send(sanitizer.sanitize(body));
}
};

const app = express();

Expand Down Expand Up @@ -234,10 +250,7 @@ app.post('/auth/okta-callback', async (req, res) => {
oktaId: oktaId,
firstName: decodedToken.given_name,
lastName: decodedToken.family_name,
invitePending: true,
// TODO: Replace these default Region/State values with user selection
state: 'Virginia',
regionId: '3'
invitePending: true
});
await user.save();
} else {
Expand Down Expand Up @@ -577,6 +590,7 @@ authenticatedRoute.delete(
handlerToExpress(savedSearches.del)
);
authenticatedRoute.get('/scans', handlerToExpress(scans.list));
authenticatedRoute.post('/logs/search', handlerToExpress(logs.list));
authenticatedRoute.get('/granularScans', handlerToExpress(scans.listGranular));
authenticatedRoute.post('/scans', handlerToExpress(scans.create));
authenticatedRoute.get('/scans/:scanId', handlerToExpress(scans.get));
Expand Down Expand Up @@ -634,12 +648,39 @@ authenticatedRoute.delete(
);
authenticatedRoute.post(
'/v2/organizations/:organizationId/users',
handlerToExpress(organizations.addUserV2)
handlerToExpress(
organizations.addUserV2,
async (req, user) => {
const orgId = req?.params?.organizationId;
const userId = req?.body?.userId;
const role = req?.body?.role;
if (orgId && userId) {
const orgRecord = await Organization.findOne({ where: { id: orgId } });
const userRecord = await User.findOne({ where: { id: userId } });
return {
timestamp: new Date(),
userPerformedAssignment: user?.data?.id,
organization: orgRecord,
role: role,
user: userRecord
};
}
return {
timestamp: new Date(),
userId: user?.data?.id,
updatePayload: req.body
};
},
'USER ASSIGNED'
)
);

authenticatedRoute.post(
'/organizations/:organizationId/roles/:roleId/approve',
handlerToExpress(organizations.approveRole)
);

// TO-DO Add logging => /users => user has an org and you change them to a new organization
authenticatedRoute.post(
'/organizations/:organizationId/roles/:roleId/remove',
handlerToExpress(organizations.removeRole)
Expand All @@ -657,9 +698,58 @@ authenticatedRoute.post(
handlerToExpress(organizations.checkDomainVerification)
);
authenticatedRoute.post('/stats', handlerToExpress(stats.get));
authenticatedRoute.post('/users', handlerToExpress(users.invite));
authenticatedRoute.post(
'/users',
handlerToExpress(
users.invite,
async (req, user, responseBody) => {
const userId = user?.data?.id;
if (userId) {
const userRecord = await User.findOne({ where: { id: userId } });
return {
timestamp: new Date(),
userPerformedInvite: userRecord,
invitePayload: req.body,
createdUserRecord: responseBody
};
}
return {
timestamp: new Date(),
userId: user.data?.id,
invitePayload: req.body,
createdUserRecord: responseBody
};
},
'USER INVITE'
)
);
authenticatedRoute.get('/users', handlerToExpress(users.list));
authenticatedRoute.delete('/users/:userId', handlerToExpress(users.del));
authenticatedRoute.delete(
'/users/:userId',
handlerToExpress(
users.del,
async (req, user, res) => {
const userId = req?.params?.userId;
const userPerformedRemovalId = user?.data?.id;
if (userId && userPerformedRemovalId) {
const userPerformdRemovalRecord = await User.findOne({
where: { id: userPerformedRemovalId }
});
return {
timestamp: new Date(),
userPerformedRemoval: userPerformdRemovalRecord,
userRemoved: userId
};
}
return {
timestamp: new Date(),
userPerformedRemoval: user.data?.id,
userRemoved: req.params.userId
};
},
'USER DENY/REMOVE'
)
);
authenticatedRoute.get(
'/users/state/:state',
handlerToExpress(users.getByState)
Expand All @@ -684,7 +774,17 @@ authenticatedRoute.post(
authenticatedRoute.put(
'/users/:userId/register/approve',
checkGlobalAdminOrRegionAdmin,
handlerToExpress(users.registrationApproval)
handlerToExpress(
users.registrationApproval,
async (req, user) => {
return {
timestamp: new Date(),
userId: user?.data?.id,
userToApprove: req.params.userId
};
},
'USER APPROVE'
)
);

authenticatedRoute.put(
Expand Down
1 change: 0 additions & 1 deletion backend/src/api/domains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,6 @@ class DomainSearch {
* - Domains
*/
export const list = wrapHandler(async (event) => {
console.log('Hello, list handler');
if (!isGlobalViewAdmin(event) && getOrgMemberships(event).length === 0) {
console.log('returning no results');
return {
Expand Down
Loading

0 comments on commit 3e75136

Please sign in to comment.