Skip to content

Commit

Permalink
Begin service token data refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
dangtony98 committed Dec 30, 2022
1 parent addf04d commit 01d9691
Show file tree
Hide file tree
Showing 14 changed files with 226 additions and 165 deletions.
4 changes: 2 additions & 2 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
stripe as stripeRouter,
integration as integrationRouter,
integrationAuth as integrationAuthRouter,
apiKey as apiKeyRouter
serviceTokenData as serviceTokenDataRouter
} from './routes';

import { getLogger } from './utils/logger';
Expand Down Expand Up @@ -86,7 +86,7 @@ app.use('/api/v1/password', passwordRouter);
app.use('/api/v1/stripe', stripeRouter);
app.use('/api/v1/integration', integrationRouter);
app.use('/api/v1/integration-auth', integrationAuthRouter);
app.use('/api/v1/api-key', apiKeyRouter);
app.use('/api/v1/service-token-data', serviceTokenDataRouter);

//* Handle unrouted requests and respond with proper error message as well as status code
app.use((req, res, next)=>{
Expand Down
2 changes: 2 additions & 0 deletions backend/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const PORT = process.env.PORT || 4000;
const EMAIL_TOKEN_LIFETIME = process.env.EMAIL_TOKEN_LIFETIME! || '86400';
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY!;
const SALT_ROUNDS = parseInt(process.env.SALT_ROUNDS!) || 10;
const JWT_AUTH_LIFETIME = process.env.JWT_AUTH_LIFETIME! || '10d';
const JWT_AUTH_SECRET = process.env.JWT_AUTH_SECRET!;
const JWT_REFRESH_LIFETIME = process.env.JWT_REFRESH_LIFETIME! || '90d';
Expand Down Expand Up @@ -47,6 +48,7 @@ export {
PORT,
EMAIL_TOKEN_LIFETIME,
ENCRYPTION_KEY,
SALT_ROUNDS,
JWT_AUTH_LIFETIME,
JWT_AUTH_SECRET,
JWT_REFRESH_LIFETIME,
Expand Down
28 changes: 28 additions & 0 deletions backend/src/controllers/workspaceController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
IntegrationAuth,
IUser,
ServiceToken,
ServiceTokenData,
} from '../models';
import {
createWorkspace as create,
Expand Down Expand Up @@ -334,4 +335,31 @@ export const getWorkspaceServiceTokens = async (
return res.status(200).send({
serviceTokens
});
}

export const getWorkspaceServiceTokenData = async (
req: Request,
res: Response
) => {
let serviceTokenData;
try {
const { workspaceId } = req.query;

serviceTokenData = await ServiceTokenData
.find({
workspace: workspaceId
})
.select('+encryptedKey +iv +tag');

} catch (err) {
Sentry.setUser({ email: req.user.email });
Sentry.captureException(err);
return res.status(400).send({
message: 'Failed to get workspace service token data'
});
}

return res.status(200).send({
serviceTokenData
});
}
2 changes: 2 additions & 0 deletions backend/src/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import requireOrganizationAuth from './requireOrganizationAuth';
import requireIntegrationAuth from './requireIntegrationAuth';
import requireIntegrationAuthorizationAuth from './requireIntegrationAuthorizationAuth';
import requireServiceTokenAuth from './requireServiceTokenAuth';
import requireServiceTokenDataAuth from './requireServiceTokenDataAuth';
import validateRequest from './validateRequest';

export {
Expand All @@ -17,5 +18,6 @@ export {
requireIntegrationAuth,
requireIntegrationAuthorizationAuth,
requireServiceTokenAuth,
requireServiceTokenDataAuth,
validateRequest
};
1 change: 1 addition & 0 deletions backend/src/middleware/requireServiceTokenAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ServiceToken } from '../models';
import { JWT_SERVICE_SECRET } from '../config';
import { BadRequestError, UnauthorizedRequestError } from '../utils/errors';

// TODO: deprecate
declare module 'jsonwebtoken' {
export interface UserIDJwtPayload extends jwt.JwtPayload {
userId: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Request, Response, NextFunction } from 'express';
import { APIKeyData } from '../models';
import { ServiceToken, ServiceTokenData } from '../models';
import { validateMembership } from '../helpers/membership';
import { AccountNotFoundError } from '../utils/errors';

type req = 'params' | 'body' | 'query';

const requireAPIKeyDataAuth = ({
const requireServiceTokenDataAuth = ({
acceptedRoles,
acceptedStatuses,
location = 'params'
Expand All @@ -16,25 +16,25 @@ const requireAPIKeyDataAuth = ({
}) => {
return async (req: Request, res: Response, next: NextFunction) => {

// req.user
const serviceTokenData = await ServiceTokenData
.findById(req[location].serviceTokenDataId)
.select('+encryptedKey +iv +tag');

const apiKeyData = await APIKeyData.findById(req[location].apiKeyDataId);

if (!apiKeyData) {
return next(AccountNotFoundError({message: 'Failed to locate API Key data'}));
if (!serviceTokenData) {
return next(AccountNotFoundError({message: 'Failed to locate service token data'}));
}

await validateMembership({
userId: req.user._id.toString(),
workspaceId: apiKeyData?.workspace.toString(),
workspaceId: serviceTokenData.workspace.toString(),
acceptedRoles,
acceptedStatuses
});

req.apiKeyData = '' // ??
req.serviceTokenData = serviceTokenData;

next();
}
}

export default requireAPIKeyDataAuth;
export default requireServiceTokenDataAuth;
6 changes: 3 additions & 3 deletions backend/src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import Token, { IToken } from './token';
import User, { IUser } from './user';
import UserAction, { IUserAction } from './userAction';
import Workspace, { IWorkspace } from './workspace';
import APIKeyData, { IAPIKeyData } from './apiKeyData';
import ServiceTokenData, { IServiceTokenData } from './serviceTokenData ';

export {
BackupPrivateKey,
Expand Down Expand Up @@ -49,6 +49,6 @@ export {
IUserAction,
Workspace,
IWorkspace,
APIKeyData,
IAPIKeyData,
ServiceTokenData,
IServiceTokenData
};
1 change: 1 addition & 0 deletions backend/src/models/serviceToken.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Schema, model, Types } from 'mongoose';
import { ENV_DEV, ENV_TESTING, ENV_STAGING, ENV_PROD } from '../variables';

// TODO: deprecate
export interface IServiceToken {
_id: Types.ObjectId;
name: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,44 +1,41 @@
import { Schema, model, Types } from 'mongoose';
import { ENV_DEV, ENV_TESTING, ENV_STAGING, ENV_PROD } from '../variables';

export interface IAPIKeyData {
export interface IServiceTokenData {
name: string;
workspaces: {
workspace: Types.ObjectId,
environments: string[]
}[];
workspace: Types.ObjectId;
environment: string; // TODO: adapt to upcoming environment id
expiresAt: Date;
prefix: string;
apiKeyHash: string;
serviceTokenHash: string;
encryptedKey: string;
iv: string;
tag: string;
}

const apiKeyDataSchema = new Schema<IAPIKeyData>(
const serviceTokenDataSchema = new Schema<IServiceTokenData>(
{
name: {
type: String,
required: true
},
workspaces: [{
workspace: {
type: Schema.Types.ObjectId,
ref: 'Workspace'
},
environments: [{
type: String,
enum: [ENV_DEV, ENV_TESTING, ENV_STAGING, ENV_PROD]
}]
}],
workspace: {
type: Schema.Types.ObjectId,
ref: 'Workspace',
required: true
},
environment: { // TODO: adapt to upcoming environment id
type: String,
required: true
},
expiresAt: {
type: Date
},
prefix: {
type: String,
required: true
},
apiKeyHash: {
serviceTokenHash: {
type: String,
unique: true,
required: true
Expand All @@ -61,6 +58,6 @@ const apiKeyDataSchema = new Schema<IAPIKeyData>(
}
);

const APIKeyData = model<IAPIKeyData>('APIKeyData', apiKeyDataSchema);
const ServiceTokenData = model<IServiceTokenData>('ServiceTokenData', serviceTokenDataSchema);

export default APIKeyData;
export default ServiceTokenData;
127 changes: 0 additions & 127 deletions backend/src/routes/apiKey.ts

This file was deleted.

4 changes: 2 additions & 2 deletions backend/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import password from './password';
import stripe from './stripe';
import integration from './integration';
import integrationAuth from './integrationAuth';
import apiKey from './apiKey';
import serviceTokenData from './serviceTokenData';

export {
signup,
Expand All @@ -35,5 +35,5 @@ export {
stripe,
integration,
integrationAuth,
apiKey
serviceTokenData
};
Loading

0 comments on commit 01d9691

Please sign in to comment.