Skip to content

Commit

Permalink
Use updateContext
Browse files Browse the repository at this point in the history
  • Loading branch information
hansott committed Jul 25, 2024
1 parent cd327ea commit 125c103
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
11 changes: 7 additions & 4 deletions library/ratelimiting/shouldRateLimitRequest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Agent } from "../agent/Agent";
import { Context } from "../agent/Context";
import { Context, updateContext } from "../agent/Context";
import { isLocalhostIP } from "../helpers/isLocalhostIP";

type Result =
Expand All @@ -16,7 +16,10 @@ type Result =
};

// eslint-disable-next-line max-lines-per-function
export function shouldRateLimitRequest(context: Context, agent: Agent): Result {
export function shouldRateLimitRequest(
context: Readonly<Context>,
agent: Agent
): Result {
const match = agent.getConfig().getEndpoint(context);

if (!match) {
Expand Down Expand Up @@ -61,7 +64,7 @@ export function shouldRateLimitRequest(context: Context, agent: Agent): Result {

// This function is executed for every middleware and route handler
// We want to count the request only once
context.consumedRateLimitForIP = true;
updateContext(context, "consumedRateLimitForIP", true);

if (!allowed) {
return { block: true, trigger: "ip" };
Expand All @@ -79,7 +82,7 @@ export function shouldRateLimitRequest(context: Context, agent: Agent): Result {

// This function is executed for every middleware and route handler
// We want to count the request only once
context.consumedRateLimitForUser = true;
updateContext(context, "consumedRateLimitForUser", true);

if (!allowed) {
return { block: true, trigger: "user" };
Expand Down
4 changes: 2 additions & 2 deletions library/sources/Lambda.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Agent } from "../agent/Agent";
import { setInstance } from "../agent/AgentSingleton";
import { ReportingAPIForTesting } from "../agent/api/ReportingAPIForTesting";
import { Token } from "../agent/api/Token";
import { getContext } from "../agent/Context";
import { getContext, updateContext } from "../agent/Context";
import { LoggerNoop } from "../agent/logger/LoggerNoop";
import { createLambdaWrapper, SQSEvent, APIGatewayProxyEvent } from "./Lambda";

Expand Down Expand Up @@ -427,7 +427,7 @@ t.test("it counts attacks", async () => {

const handler = createLambdaWrapper(async (event, context) => {
const ctx = getContext();
ctx.attackDetected = true;
updateContext(ctx, "attackDetected", true);
return ctx;
});

Expand Down

0 comments on commit 125c103

Please sign in to comment.