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

fix(capping): reup capping on connection creation #2674

Merged
merged 3 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 7 additions & 7 deletions packages/frontend/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand Down Expand Up @@ -309,7 +309,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand All @@ -330,7 +330,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand All @@ -351,7 +351,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand All @@ -372,7 +372,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand All @@ -393,7 +393,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand All @@ -414,7 +414,7 @@ export default class Nango {

if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
throw new AuthError(errorResponse.error.message, errorResponse.error.code);
}

return res.json();
Expand Down
20 changes: 9 additions & 11 deletions packages/server/lib/hooks/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,15 @@ export const connectionCreationStartCapCheck = async ({

const scriptConfigs = await getSyncConfigsWithConnections(providerConfigKey, environmentId);

if (scriptConfigs.length > 0) {
for (const script of scriptConfigs) {
const { connections } = script;

if (connections && connections.length >= CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT) {
logger.info(`Reached cap for providerConfigKey: ${providerConfigKey} and environmentId: ${environmentId}`);
const analyticsType =
creationType === 'create' ? AnalyticsTypes.RESOURCE_CAPPED_CONNECTION_CREATED : AnalyticsTypes.RESOURCE_CAPPED_CONNECTION_IMPORTED;
void analytics.trackByEnvironmentId(analyticsType, environmentId);
return true;
}
for (const script of scriptConfigs) {
const { connections } = script;

if (connections && connections.length >= CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT) {
logger.info(`Reached cap for providerConfigKey: ${providerConfigKey} and environmentId: ${environmentId}`);
const analyticsType =
creationType === 'create' ? AnalyticsTypes.RESOURCE_CAPPED_CONNECTION_CREATED : AnalyticsTypes.RESOURCE_CAPPED_CONNECTION_IMPORTED;
void analytics.trackByEnvironmentId(analyticsType, environmentId);
return true;
}
}

Expand Down
29 changes: 15 additions & 14 deletions packages/server/lib/middleware/resource-capping.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import type { Request, Response, NextFunction } from 'express';
import { errorManager } from '@nangohq/shared';
import { connectionCreationStartCapCheck as connectionCreationStartCapCheckHook } from '../hooks/hooks.js';
import { asyncWrapper } from '../utils/asyncWrapper.js';
import type { ApiError, Endpoint } from '@nangohq/types';

export const authCheck = async (req: Request, res: Response, next: NextFunction) => {
const environmentId = res.locals['environment']!.id;
const account = res.locals['account']!.id;
export const resourceCapping = asyncWrapper<Endpoint<{ Method: 'POST'; Path: ''; Success: any; Error: ApiError<'resource_capped'> }>>(
async (req, res, next) => {
const { environment, account } = res.locals;

const { providerConfigKey } = req.params;
const { providerConfigKey } = req.params;

if (account.is_capped && providerConfigKey) {
const isCapped = await connectionCreationStartCapCheckHook({ providerConfigKey, environmentId, creationType: 'create' });
if (isCapped) {
errorManager.errRes(res, 'resource_capped');
return;
if (account.is_capped && providerConfigKey) {
const isCapped = await connectionCreationStartCapCheckHook({ providerConfigKey, environmentId: environment.id, creationType: 'create' });
if (isCapped) {
res.status(400).send({ error: { code: 'resource_capped', message: 'Reached maximum number of connections with scripts enabled' } });
return;
}
}
}

next();
};
next();
}
);
20 changes: 12 additions & 8 deletions packages/server/lib/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import appAuthController from './controllers/appAuth.controller.js';
import onboardingController from './controllers/onboarding.controller.js';
import webhookController from './controllers/webhook.controller.js';
import { rateLimiterMiddleware } from './middleware/ratelimit.middleware.js';
import { authCheck } from './middleware/resource-capping.middleware.js';
import { resourceCapping } from './middleware/resource-capping.middleware.js';
import path from 'path';
import { dirname } from './utils/utils.js';
import express from 'express';
Expand All @@ -26,7 +26,7 @@ import { setupAuth } from './clients/auth.client.js';
import passport from 'passport';
import environmentController from './controllers/environment.controller.js';
import accountController from './controllers/account.controller.js';
import type { Response, Request } from 'express';
import type { Response, Request, RequestHandler } from 'express';
import { isCloud, isEnterprise, isBasicAuthEnabled, isTest, isLocal, basePublicUrl, baseUrl, flagHasAuth, flagHasManagedAuth } from '@nangohq/utils';
import { errorManager } from '@nangohq/shared';
import tracer from 'dd-trace';
Expand Down Expand Up @@ -85,13 +85,17 @@ export const router = express.Router();

router.use(...securityMiddlewares());

const apiAuth = [authMiddleware.secretKeyAuth.bind(authMiddleware), rateLimiterMiddleware];
const adminAuth = [authMiddleware.secretKeyAuth.bind(authMiddleware), authMiddleware.adminKeyAuth.bind(authMiddleware), rateLimiterMiddleware];
const apiPublicAuth = [authMiddleware.publicKeyAuth.bind(authMiddleware), authCheck, rateLimiterMiddleware];
let webAuth = flagHasAuth
? [passport.authenticate('session'), authMiddleware.sessionAuth.bind(authMiddleware), rateLimiterMiddleware]
const apiAuth: RequestHandler[] = [authMiddleware.secretKeyAuth.bind(authMiddleware), rateLimiterMiddleware];
const adminAuth: RequestHandler[] = [
authMiddleware.secretKeyAuth.bind(authMiddleware),
authMiddleware.adminKeyAuth.bind(authMiddleware),
rateLimiterMiddleware
];
const apiPublicAuth: RequestHandler[] = [authMiddleware.publicKeyAuth.bind(authMiddleware), resourceCapping, rateLimiterMiddleware];
let webAuth: RequestHandler[] = flagHasAuth
? [passport.authenticate('session') as RequestHandler, authMiddleware.sessionAuth.bind(authMiddleware), rateLimiterMiddleware]
: isBasicAuthEnabled
? [passport.authenticate('basic', { session: false }), authMiddleware.basicAuth.bind(authMiddleware), rateLimiterMiddleware]
? [passport.authenticate('basic', { session: false }) as RequestHandler, authMiddleware.basicAuth.bind(authMiddleware), rateLimiterMiddleware]
: [authMiddleware.noAuth.bind(authMiddleware), rateLimiterMiddleware];

// For integration test, we want to bypass session auth
Expand Down
2 changes: 1 addition & 1 deletion packages/server/lib/utils/asyncWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function asyncWrapper<TEndpoint extends Endpoint<any>, Locals extends Rec
res: Response<TEndpoint['Reply'], Locals>,
next: NextFunction
) => Promise<void> | void
): RequestHandler<any, TEndpoint['Reply'], TEndpoint['Body'], TEndpoint['Querystring'], Locals> {
): RequestHandler<any, TEndpoint['Reply'], any, any, any> {
bodinsamuel marked this conversation as resolved.
Show resolved Hide resolved
return (req, res, next) => {
const active = tracer.scope().active();
active?.setTag('http.route', req.route?.path || req.originalUrl);
Expand Down
3 changes: 2 additions & 1 deletion packages/types/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export type ResDefaultErrors =
| ApiError<'feature_disabled'>
| ApiError<'missing_auth_header'>
| ApiError<'generic_error_support', undefined, string>
| ApiError<'server_error'>;
| ApiError<'server_error'>
| ApiError<'resource_capped'>;

export type EndpointMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
/**
Expand Down
2 changes: 1 addition & 1 deletion packages/types/lib/flow/http.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export type PostPreBuiltDeploy = Endpoint<{
scriptName: string;
type: ScriptTypeLiteral;
};
Error: ApiError<'unknown_provider'> | ApiError<'resource_capped'> | ApiError<'failed_to_deploy', Error[]> | ApiError<'unknown_flow'>;
Error: ApiError<'unknown_provider'> | ApiError<'failed_to_deploy', Error[]> | ApiError<'unknown_flow'>;
Success: {
data: {
id: number;
Expand Down
1 change: 1 addition & 0 deletions packages/webapp/src/pages/Connection/Create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ export default function IntegrationCreate() {

if (integration != null) {
setIntegration(integration);
setServerErrorMessage('');
setUpConnectionConfigParams(integration);
setAuthMode(integration.authMode);
}
Expand Down
Loading