Skip to content

Commit

Permalink
Add get call secrets route for service token and jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
maidul98 committed Jan 5, 2023
1 parent 880f4d2 commit d75d9ec
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 23 deletions.
8 changes: 4 additions & 4 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ app.use('/api/v1/integration-auth', v1IntegrationAuthRouter);
// v2 routes
app.use('/api/v2/workspace', v2WorkspaceRouter);
app.use('/api/v2/secret', v2SecretRouter);
app.use('/api/v2/service-token-data', v2ServiceTokenDataRouter);
app.use('/api/v2/service-token', v2ServiceTokenDataRouter);
app.use('/api/v2/api-key-data', v2APIKeyDataRouter);

//* Handle unrouted requests and respond with proper error message as well as status code
app.use((req, res, next)=>{
if(res.headersSent) return next();
next(RouteNotFoundError({message: `The requested source '(${req.method})${req.url}' was not found`}))
app.use((req, res, next) => {
if (res.headersSent) return next();
next(RouteNotFoundError({ message: `The requested source '(${req.method})${req.url}' was not found` }))
})

//* Error Handling Middleware (must be after all routing logic)
Expand Down
30 changes: 30 additions & 0 deletions backend/src/controllers/v2/secretController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { CreateSecretRequestBody, ModifySecretRequestBody, SanitizedSecretForCre
const { ValidationError } = mongoose.Error;
import { BadRequestError, InternalServerError, UnauthorizedRequestError, ValidationError as RouteValidationError } from '../../utils/errors';
import { AnyBulkWriteOperation } from 'mongodb';
import { SECRET_PERSONAL, SECRET_SHARED } from "../../variables";

export const batchCreateSecrets = async (req: Request, res: Response) => {
const secretsToCreate: CreateSecretRequestBody[] = req.body.secrets;
Expand Down Expand Up @@ -135,4 +136,33 @@ export const batchModifySecrets = async (req: Request, res: Response) => {
}

return res.status(200).send()
}

export const fetchAllSecrets = async (req: Request, res: Response) => {
const { environment } = req.query;
const { workspaceId } = req.params;

let userId: string | undefined = undefined // Used for choosing the personal secrets to fetch in
if (req.user) {
userId = req.user._id.toString();
}

if (req.serviceTokenData) {
userId = req.serviceTokenData.user._id
}

const [retriveAllSecretsError, allSecrets] = await to(Secret.find(
{
workspace: workspaceId,
environment,
$or: [{ user: userId }, { user: { $exists: false } }],
type: { $in: [SECRET_SHARED, SECRET_PERSONAL] }
}
).then())

if (retriveAllSecretsError instanceof ValidationError) {
throw RouteValidationError({ message: "Unable to get secrets, please try again", stack: retriveAllSecretsError.stack })
}

return res.json(allSecrets)
}
16 changes: 7 additions & 9 deletions backend/src/controllers/v2/workspaceController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
MembershipOrg,
Integration,
IntegrationAuth,
Key,
Key,
IUser,
ServiceToken,
ServiceTokenData
Expand Down Expand Up @@ -78,7 +78,7 @@ export const pushWorkspaceSecrets = async (req: Request, res: Response) => {
workspaceId,
keys
});

if (postHogClient) {
postHogClient.capture({
event: 'secrets pushed',
Expand Down Expand Up @@ -125,7 +125,7 @@ export const pullSecrets = async (req: Request, res: Response) => {
const environment: string = req.query.environment as string;
const channel: string = req.query.channel as string;
const { workspaceId } = req.params;

let userId;
if (req.user) {
userId = req.user._id.toString();
Expand All @@ -138,7 +138,7 @@ export const pullSecrets = async (req: Request, res: Response) => {
workspaceId,
environment
});

if (channel !== 'cli') {
secrets = reformatPullSecrets({ secrets });
}
Expand Down Expand Up @@ -178,7 +178,7 @@ export const getWorkspaceKey = async (req: Request, res: Response) => {
workspace: workspaceId,
receiver: req.user._id
}).populate('sender', '+publicKey');

if (!key) throw new Error('Failed to find workspace key');
} catch (err) {
Sentry.setUser({ email: req.user.email });
Expand All @@ -188,9 +188,7 @@ export const getWorkspaceKey = async (req: Request, res: Response) => {
});
}

return res.status(200).send({
key
});
return res.status(200).json(key);
}
export const getWorkspaceServiceTokenData = async (
req: Request,
Expand All @@ -213,7 +211,7 @@ export const getWorkspaceServiceTokenData = async (
message: 'Failed to get workspace service token data'
});
}

return res.status(200).send({
serviceTokenData
});
Expand Down
16 changes: 9 additions & 7 deletions backend/src/routes/v2/secret.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import express from 'express';
import express, { Request, Response } from 'express';
import { requireAuth, requireWorkspaceAuth, validateRequest } from '../../middleware';
import { body, param } from 'express-validator';
import { body, param, query } from 'express-validator';
import { ADMIN, MEMBER } from '../../variables';
import { CreateSecretRequestBody, ModifySecretRequestBody } from '../../types/secret/types';
import { secretController } from '../../controllers/v2';
import { fetchAllSecrets } from '../../controllers/v2/secretController';

const router = express.Router();

Expand All @@ -26,19 +27,20 @@ router.post(
);

/**
* Get a single secret by secret id
* Get all secrets for a given environment and workspace id
*/
router.get(
'/:secretId',
'/workspace/:workspaceId',
param('workspaceId').exists().trim(),
query("environment").exists(),
requireAuth({
acceptedAuthModes: ['jwt']
acceptedAuthModes: ['jwt', 'serviceToken']
}),
param('secretId').exists().trim(),
requireWorkspaceAuth({
acceptedRoles: [ADMIN, MEMBER]
}),
validateRequest,
secretController.createSingleSecret
fetchAllSecrets
);

/**
Expand Down
6 changes: 3 additions & 3 deletions backend/src/routes/v2/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ router.get(
);

router.get(
'/:workspaceId/key',
'/:workspaceId/encrypted-key',
requireAuth({
acceptedAuthModes: ['jwt']
}),
requireWorkspaceAuth({
acceptedRoles: [ADMIN, MEMBER]
}),
}),
param('workspaceId').exists().trim(),
validateRequest,
validateRequest,
workspaceController.getWorkspaceKey
);

Expand Down

0 comments on commit d75d9ec

Please sign in to comment.