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

[OTE-141] implement post /compliance/geoblock #1129

Merged
merged 8 commits into from
Mar 5, 2024
Merged

[OTE-141] implement post /compliance/geoblock #1129

merged 8 commits into from
Mar 5, 2024

Conversation

dydxwill
Copy link
Contributor

@dydxwill dydxwill commented Mar 1, 2024

Changelist

implement POST /compliance/geoblock logic

Test Plan

unit tested.

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Copy link
Contributor

coderabbitai bot commented Mar 1, 2024

Warning

Rate Limit Exceeded

@dydxwill has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 25 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between 9879d1f and 3af5cb8.

Walkthrough

The recent updates focus on enhancing compliance handling within the comlink service, specifically targeting country-based restrictions. New logic and utility functions have been introduced to assess and update compliance statuses such as BLOCKED, FIRST_STRIKE, or COMPLIANT, depending on the user's country and specific conditions. The changes involve adding new imports, reorganizing existing code, and implementing new test cases to ensure robust compliance checks based on geographical restrictions.

Changes

File Path Changes
.../compliance-v2-controller.test.ts
.../compliance-v2-controller.ts
Reordered imports; added CountryHeaders and isRestrictedCountryHeaders imports; implemented compliance logic based on country restrictions; updated compliance status in the database.
.../compliance/compliance-utils.ts Provided a new function getGeoComplianceReason for determining compliance reasons based on country headers.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9850cb4 and 2ae9e5c.
Files selected for processing (3)
  • indexer/services/comlink/tests/controllers/api/v4/compliance-v2-controller.test.ts (4 hunks)
  • indexer/services/comlink/src/controllers/api/v4/compliance-v2-controller.ts (3 hunks)
  • indexer/services/comlink/src/helpers/compliance/compliance-utils.ts (1 hunks)
Additional comments: 2
indexer/services/comlink/src/controllers/api/v4/compliance-v2-controller.ts (1)
  • 1-6: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-20]

The reordering of imports and the addition of new imports for CountryHeaders and isRestrictedCountryHeaders are correctly implemented, ensuring that the necessary modules are available for the new compliance logic.

indexer/services/comlink/__tests__/controllers/api/v4/compliance-v2-controller.test.ts (1)
  • 1-11: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-25]

The reordering of imports and the addition of new imports for ComplianceReason, ComplianceStatusFromDatabase, and ComplianceStatusTable are correctly implemented, ensuring that the necessary modules are available for the new test cases.

Comment on lines +4 to +18
export function getGeoComplianceReason(
headers: CountryHeaders,
): ComplianceReason | undefined {
if (isRestrictedCountryHeaders(headers)) {
const country: string | undefined = headers['cf-ipcountry'];
if (country === 'US') {
return ComplianceReason.US_GEO;
} else if (country === 'CA') {
return ComplianceReason.CA_GEO;
} else {
return ComplianceReason.SANCTIONED_GEO;
}
}
return undefined;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation of getGeoComplianceReason correctly determines the compliance reason based on the country code in the headers. However, consider handling the case where the cf-ipcountry header might not be present or could be an unexpected value. Adding a default case or logging for unexpected country codes could improve maintainability and debugging.

-    } else {
+    } else if (country) {
      return ComplianceReason.SANCTIONED_GEO;
+    }
+    // Consider adding logging or handling for unexpected country codes

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export function getGeoComplianceReason(
headers: CountryHeaders,
): ComplianceReason | undefined {
if (isRestrictedCountryHeaders(headers)) {
const country: string | undefined = headers['cf-ipcountry'];
if (country === 'US') {
return ComplianceReason.US_GEO;
} else if (country === 'CA') {
return ComplianceReason.CA_GEO;
} else {
return ComplianceReason.SANCTIONED_GEO;
}
}
return undefined;
}
export function getGeoComplianceReason(
headers: CountryHeaders,
): ComplianceReason | undefined {
if (isRestrictedCountryHeaders(headers)) {
const country: string | undefined = headers['cf-ipcountry'];
if (country === 'US') {
return ComplianceReason.US_GEO;
} else if (country === 'CA') {
return ComplianceReason.CA_GEO;
} else if (country) {
return ComplianceReason.SANCTIONED_GEO;
}
// Consider adding logging or handling for unexpected country codes
}
return undefined;
}

Comment on lines 214 to 291
/**
* If the address doesn't exist in the compliance table:
* - if the request is from a restricted country:
* - if the action is ONBOARD, set the status to BLOCKED
* - if the action is CONNECT, set the status to FIRST_STRIKE
* - else if the request is not from a non-restricted country:
* - set the status to COMPLIANT
*
* if the address is COMPLIANT:
* - the ONLY action should be CONNECT
* - if the request is from a restricted country:
* - set the status to FIRST_STRIKE
*
* if the address is FIRST_STRIKE:
* - the ONLY action should be CONNECT
* - if the request is from a restricted country:
* - set the status to CLOSE_ONLY
*/
const complianceStatus: ComplianceStatusFromDatabase[] = await
ComplianceStatusTable.findAll(
{ address: [address] },
[],
);
let complianceStatusFromDatabase: ComplianceStatusFromDatabase | undefined;
if (complianceStatus.length === 0) {
if (isRestrictedCountryHeaders(req.headers as CountryHeaders)) {
if (action === ComplianceAction.ONBOARD) {
complianceStatusFromDatabase = await ComplianceStatusTable.upsert({
address,
status: ComplianceStatus.BLOCKED,
reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
updatedAt: DateTime.utc().toISO(),
});
} else if (action === ComplianceAction.CONNECT) {
complianceStatusFromDatabase = await ComplianceStatusTable.upsert({
address,
status: ComplianceStatus.FIRST_STRIKE,
reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
updatedAt: DateTime.utc().toISO(),
});
}
} else {
complianceStatusFromDatabase = await ComplianceStatusTable.upsert({
address,
status: ComplianceStatus.COMPLIANT,
updatedAt: DateTime.utc().toISO(),
});
}
} else {
complianceStatusFromDatabase = complianceStatus[0];
if (
complianceStatus[0].status === ComplianceStatus.FIRST_STRIKE ||
complianceStatus[0].status === ComplianceStatus.COMPLIANT
) {
if (action === ComplianceAction.ONBOARD) {
logger.error({
at: 'ComplianceV2Controller POST /geoblock',
message: 'Invalid action for current compliance status',
address,
action,
complianceStatus: complianceStatus[0],
});
} else if (
isRestrictedCountryHeaders(req.headers as CountryHeaders) &&
action === ComplianceAction.CONNECT
) {
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
[ComplianceStatus.COMPLIANT]: ComplianceStatus.FIRST_STRIKE,
[ComplianceStatus.FIRST_STRIKE]: ComplianceStatus.CLOSE_ONLY,
};

complianceStatusFromDatabase = await ComplianceStatusTable.update({
address,
status: complianceProgression[complianceStatus[0].status],
reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
updatedAt: DateTime.utc().toISO(),
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic implemented in the /geoblock endpoint for handling compliance based on geographical restrictions is comprehensive and covers various scenarios. However, ensure that the complianceProgression mapping in lines 280-282 is exhaustive and correctly maps all possible transitions. Additionally, consider handling the case where complianceProgression[complianceStatus[0].status] might return undefined, which could lead to an invalid status being set.

-              status: complianceProgression[complianceStatus[0].status],
+              status: complianceProgression[complianceStatus[0].status] || ComplianceStatus.COMPLIANT,

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
/**
* If the address doesn't exist in the compliance table:
* - if the request is from a restricted country:
* - if the action is ONBOARD, set the status to BLOCKED
* - if the action is CONNECT, set the status to FIRST_STRIKE
* - else if the request is not from a non-restricted country:
* - set the status to COMPLIANT
*
* if the address is COMPLIANT:
* - the ONLY action should be CONNECT
* - if the request is from a restricted country:
* - set the status to FIRST_STRIKE
*
* if the address is FIRST_STRIKE:
* - the ONLY action should be CONNECT
* - if the request is from a restricted country:
* - set the status to CLOSE_ONLY
*/
const complianceStatus: ComplianceStatusFromDatabase[] = await
ComplianceStatusTable.findAll(
{ address: [address] },
[],
);
let complianceStatusFromDatabase: ComplianceStatusFromDatabase | undefined;
if (complianceStatus.length === 0) {
if (isRestrictedCountryHeaders(req.headers as CountryHeaders)) {
if (action === ComplianceAction.ONBOARD) {
complianceStatusFromDatabase = await ComplianceStatusTable.upsert({
address,
status: ComplianceStatus.BLOCKED,
reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
updatedAt: DateTime.utc().toISO(),
});
} else if (action === ComplianceAction.CONNECT) {
complianceStatusFromDatabase = await ComplianceStatusTable.upsert({
address,
status: ComplianceStatus.FIRST_STRIKE,
reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
updatedAt: DateTime.utc().toISO(),
});
}
} else {
complianceStatusFromDatabase = await ComplianceStatusTable.upsert({
address,
status: ComplianceStatus.COMPLIANT,
updatedAt: DateTime.utc().toISO(),
});
}
} else {
complianceStatusFromDatabase = complianceStatus[0];
if (
complianceStatus[0].status === ComplianceStatus.FIRST_STRIKE ||
complianceStatus[0].status === ComplianceStatus.COMPLIANT
) {
if (action === ComplianceAction.ONBOARD) {
logger.error({
at: 'ComplianceV2Controller POST /geoblock',
message: 'Invalid action for current compliance status',
address,
action,
complianceStatus: complianceStatus[0],
});
} else if (
isRestrictedCountryHeaders(req.headers as CountryHeaders) &&
action === ComplianceAction.CONNECT
) {
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
[ComplianceStatus.COMPLIANT]: ComplianceStatus.FIRST_STRIKE,
[ComplianceStatus.FIRST_STRIKE]: ComplianceStatus.CLOSE_ONLY,
};
complianceStatusFromDatabase = await ComplianceStatusTable.update({
address,
status: complianceProgression[complianceStatus[0].status],
reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
updatedAt: DateTime.utc().toISO(),
});
}
status: complianceProgression[complianceStatus[0].status] || ComplianceStatus.COMPLIANT,

Comment on lines 332 to 497
it('should set status to COMPLIANT for any action from a non-restricted country with no existing compliance status', async () => {
(Secp256k1.verifySignature as jest.Mock).mockResolvedValueOnce(true);
isRestrictedCountryHeadersSpy.mockReturnValue(false);

const response: any = await sendRequest({
type: RequestMethod.POST,
path: '/v4/compliance/geoblock',
body: {
address: testConstants.defaultAddress,
message: 'Test message',
action: ComplianceAction.ONBOARD, // Or CONNECT, should work the same
signedMessage: sha256(Buffer.from('msg')),
pubkey: new Uint8Array([/* public key bytes */]),
timestamp: 1620000000, // Valid timestamp
},
expectedStatus: 200,
});

const data: ComplianceStatusFromDatabase[] = await ComplianceStatusTable.findAll({}, [], {});
expect(data).toHaveLength(1);
expect(data[0]).toEqual(expect.objectContaining({
address: testConstants.defaultAddress,
status: ComplianceStatus.COMPLIANT,
}));

expect(response.body.status).toEqual(ComplianceStatus.COMPLIANT);
});

it('should update status to FIRST_STRIKE for CONNECT action from a restricted country with existing COMPLIANT status', async () => {
await ComplianceStatusTable.create({
address: testConstants.defaultAddress,
status: ComplianceStatus.COMPLIANT,
});
(Secp256k1.verifySignature as jest.Mock).mockResolvedValueOnce(true);
getGeoComplianceReasonSpy.mockReturnValueOnce(ComplianceReason.US_GEO);
isRestrictedCountryHeadersSpy.mockReturnValue(true);

const response: any = await sendRequest({
type: RequestMethod.POST,
path: '/v4/compliance/geoblock',
body: {
address: testConstants.defaultAddress,
message: 'Test message',
action: ComplianceAction.CONNECT,
signedMessage: sha256(Buffer.from('msg')),
pubkey: new Uint8Array([/* public key bytes */]),
timestamp: 1620000000, // Valid timestamp
},
expectedStatus: 200,
});

const data: ComplianceStatusFromDatabase[] = await ComplianceStatusTable.findAll({}, [], {});
expect(data).toHaveLength(1);
expect(data[0]).toEqual(expect.objectContaining({
address: testConstants.defaultAddress,
status: ComplianceStatus.FIRST_STRIKE,
reason: ComplianceReason.US_GEO,
}));

expect(response.body.status).toEqual(ComplianceStatus.FIRST_STRIKE);
expect(response.body.reason).toEqual(ComplianceReason.US_GEO);
});

it('should update status to CLOSE_ONLY for CONNECT action from a restricted country with existing FIRST_STRIKE status', async () => {
await ComplianceStatusTable.create({
address: testConstants.defaultAddress,
status: ComplianceStatus.FIRST_STRIKE,
reason: ComplianceReason.US_GEO,
});
(Secp256k1.verifySignature as jest.Mock).mockResolvedValueOnce(true);
getGeoComplianceReasonSpy.mockReturnValueOnce(ComplianceReason.US_GEO);
isRestrictedCountryHeadersSpy.mockReturnValue(true);

const response: any = await sendRequest({
type: RequestMethod.POST,
path: '/v4/compliance/geoblock',
body: {
address: testConstants.defaultAddress,
message: 'Test message',
action: ComplianceAction.CONNECT,
signedMessage: sha256(Buffer.from('msg')),
pubkey: new Uint8Array([/* public key bytes */]),
timestamp: 1620000000, // Valid timestamp
},
expectedStatus: 200,
});

const data: ComplianceStatusFromDatabase[] = await ComplianceStatusTable.findAll({}, [], {});
expect(data).toHaveLength(1);
expect(data[0]).toEqual(expect.objectContaining({
address: testConstants.defaultAddress,
status: ComplianceStatus.CLOSE_ONLY,
reason: ComplianceReason.US_GEO,
}));

expect(response.body.status).toEqual(ComplianceStatus.CLOSE_ONLY);
expect(response.body.reason).toEqual(ComplianceReason.US_GEO);
});
});
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [239-495]

The new test cases added to cover various compliance scenarios based on country restrictions and actions are well-implemented and comprehensive. They effectively test the application's ability to correctly identify and respond to country-based restrictions. However, ensure that edge cases, such as invalid country codes or missing headers, are also covered in the tests to improve robustness.

Consider adding test cases for edge cases, such as invalid country codes or missing headers, to ensure comprehensive coverage.

@dydxwill dydxwill changed the title implement post /compliance/geoblock [OTE-141] implement post /compliance/geoblock Mar 5, 2024
Copy link

linear bot commented Mar 5, 2024

* - if the request is from a restricted country:
* - if the action is ONBOARD, set the status to BLOCKED
* - if the action is CONNECT, set the status to FIRST_STRIKE
* - else if the request is not from a non-restricted country:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* - else if the request is not from a non-restricted country:
* - else if the request is from a non-restricted country:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

* - set the status to COMPLIANT
*
* if the address is COMPLIANT:
* - the ONLY action should be CONNECT
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Note that if action is ONBOARD it is a no-op.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 280 to 283
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
[ComplianceStatus.COMPLIANT]: ComplianceStatus.FIRST_STRIKE,
[ComplianceStatus.FIRST_STRIKE]: ComplianceStatus.CLOSE_ONLY,
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Pull out this constant.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 375 to 382
body: {
address: testConstants.defaultAddress,
message: 'Test message',
action: ComplianceAction.CONNECT,
signedMessage: sha256(Buffer.from('msg')),
pubkey: new Uint8Array([/* public key bytes */]),
timestamp: 1620000000, // Valid timestamp
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Pull out this body into a separate object so we don't have to repeat this per test-case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@@ -231,7 +236,12 @@ describe('ComplianceV2Controller', () => {
});

describe('POST /geoblock', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Add test case of unexpected ONBOARD action, leading to error-log + no-op?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 2ae9e5c and 9879d1f.
Files selected for processing (2)
  • indexer/services/comlink/tests/controllers/api/v4/compliance-v2-controller.test.ts (5 hunks)
  • indexer/services/comlink/src/controllers/api/v4/compliance-v2-controller.ts (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • indexer/services/comlink/tests/controllers/api/v4/compliance-v2-controller.test.ts
Additional comments: 1
indexer/services/comlink/src/controllers/api/v4/compliance-v2-controller.ts (1)
  • 1-3: The reordering of imports and the addition of CountryHeaders and isRestrictedCountryHeaders are appropriate for the new functionality being introduced. It's good practice to keep imports organized and grouped by their source or functionality, which seems to be followed here.

Comment on lines 39 to 42
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
[ComplianceStatus.COMPLIANT]: ComplianceStatus.FIRST_STRIKE,
[ComplianceStatus.FIRST_STRIKE]: ComplianceStatus.CLOSE_ONLY,
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The complianceProgression object is a partial record mapping from ComplianceStatus to ComplianceStatus. This mapping is used to determine the next compliance status based on the current status. It's a clear and maintainable way to handle status progression, but it's important to ensure that all relevant statuses are covered, especially since it's declared as a Partial record. Consider adding a comment or documentation to explain the choice of included statuses and the handling of any statuses not included in this mapping.

+ // Note: This mapping covers the progression from COMPLIANT to FIRST_STRIKE and from FIRST_STRIKE to CLOSE_ONLY. Other statuses are handled separately.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
[ComplianceStatus.COMPLIANT]: ComplianceStatus.FIRST_STRIKE,
[ComplianceStatus.FIRST_STRIKE]: ComplianceStatus.CLOSE_ONLY,
};
// Note: This mapping covers the progression from COMPLIANT to FIRST_STRIKE and from FIRST_STRIKE to CLOSE_ONLY. Other statuses are handled separately.
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
[ComplianceStatus.COMPLIANT]: ComplianceStatus.FIRST_STRIKE,
[ComplianceStatus.FIRST_STRIKE]: ComplianceStatus.CLOSE_ONLY,
};

Comment on lines +219 to +236
/**
* If the address doesn't exist in the compliance table:
* - if the request is from a restricted country:
* - if the action is ONBOARD, set the status to BLOCKED
* - if the action is CONNECT, set the status to FIRST_STRIKE
* - else if the request is from a non-restricted country:
* - set the status to COMPLIANT
*
* if the address is COMPLIANT:
* - the ONLY action should be CONNECT. ONBOARD is a no-op.
* - if the request is from a restricted country:
* - set the status to FIRST_STRIKE
*
* if the address is FIRST_STRIKE:
* - the ONLY action should be CONNECT. ONBOARD is a no-op.
* - if the request is from a restricted country:
* - set the status to CLOSE_ONLY
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic implemented in the POST /geoblock endpoint for handling compliance based on geographical restrictions and user actions is comprehensive. However, there's a potential issue with the use of ! (non-null assertion operator) in line 249 and 256. While it's clear that getGeoComplianceReason should always return a reason when called with headers from a restricted country, relying on the non-null assertion operator without explicit error handling could lead to runtime errors if unexpected conditions occur. Consider adding explicit error handling for cases where getGeoComplianceReason might return undefined.

- reason: getGeoComplianceReason(req.headers as CountryHeaders)!,
+ const reason = getGeoComplianceReason(req.headers as CountryHeaders);
+ if (!reason) {
+   // Handle the case where no reason is returned, possibly by logging and returning an error response
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
/**
* If the address doesn't exist in the compliance table:
* - if the request is from a restricted country:
* - if the action is ONBOARD, set the status to BLOCKED
* - if the action is CONNECT, set the status to FIRST_STRIKE
* - else if the request is from a non-restricted country:
* - set the status to COMPLIANT
*
* if the address is COMPLIANT:
* - the ONLY action should be CONNECT. ONBOARD is a no-op.
* - if the request is from a restricted country:
* - set the status to FIRST_STRIKE
*
* if the address is FIRST_STRIKE:
* - the ONLY action should be CONNECT. ONBOARD is a no-op.
* - if the request is from a restricted country:
* - set the status to CLOSE_ONLY
*/
/**
* If the address doesn't exist in the compliance table:
* - if the request is from a restricted country:
* - if the action is ONBOARD, set the status to BLOCKED
* - if the action is CONNECT, set the status to FIRST_STRIKE
* - else if the request is from a non-restricted country:
* - set the status to COMPLIANT
*
* if the address is COMPLIANT:
* - the ONLY action should be CONNECT. ONBOARD is a no-op.
* - if the request is from a restricted country:
* - set the status to FIRST_STRIKE
*
* if the address is FIRST_STRIKE:
* - the ONLY action should be CONNECT. ONBOARD is a no-op.
* - if the request is from a restricted country:
* - set the status to CLOSE_ONLY
*/

Comment on lines +1 to 6
import { ExtendedSecp256k1Signature, Secp256k1, sha256 } from '@cosmjs/crypto';
import { logger, stats, TooManyRequestsError } from '@dydxprotocol-indexer/base';
import { CountryHeaders, isRestrictedCountryHeaders } from '@dydxprotocol-indexer/compliance';
import {
ComplianceReason,
ComplianceStatus,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [357-357]

Directly writing to a Response object from user-defined input, as seen in the catch block of the POST /geoblock endpoint, may expose the application to Cross-Site Scripting (XSS) vulnerabilities. It's recommended to sanitize or escape user-defined input before including it in the response or, alternatively, use methods that automatically ensure safe rendering of the content.

- return create4xxResponse(res, error.message);
+ // Ensure error.message is sanitized or escaped to prevent XSS
+ return create4xxResponse(res, sanitize(error.message));

@@ -34,6 +36,11 @@ export enum ComplianceAction {
CONNECT = 'CONNECT',
}

const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: As it's a constant config.

Suggested change
const complianceProgression: Partial<Record<ComplianceStatus, ComplianceStatus>> = {
const COMPLIANCE_PROGRESSION: Partial<Record<ComplianceStatus, ComplianceStatus>> = {

@dydxwill dydxwill merged commit e226a00 into main Mar 5, 2024
11 checks passed
@dydxwill dydxwill deleted the wl/pg1 branch March 5, 2024 20:03
Eric-Warehime pushed a commit to skip-mev/v4-chain that referenced this pull request Mar 12, 2024
Signed-off-by: Eric <eric.warehime@gmail.com>
Eric-Warehime added a commit to skip-mev/v4-chain that referenced this pull request Mar 12, 2024
commit d98f859
Author: Eric <eric.warehime@gmail.com>
Date:   Mon Mar 11 12:46:53 2024 -0700

    Update sample pregenesis

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 7f178fe
Author: Mohammed Affan <affanmd@nyu.edu>
Date:   Mon Mar 11 13:46:08 2024 -0400

    [OTE-209] Emit metrics gated through execution mode (dydxprotocol#1157)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 47e365d
Author: dydxwill <119354122+dydxwill@users.noreply.github.com>
Date:   Mon Mar 11 13:43:16 2024 -0400

    add aggregate comlink response code stats (dydxprotocol#1162)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 7774ad9
Author: shrenujb <98204323+shrenujb@users.noreply.github.com>
Date:   Fri Mar 8 17:30:49 2024 -0500

    [TRA-70] Add state migrations for isolated markets (dydxprotocol#1155)

    Signed-off-by: Shrenuj Bansal <shrenuj@dydx.exchange>
    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 89c7405
Author: Jonathan Fung <121899091+jonfung-dydx@users.noreply.github.com>
Date:   Thu Mar 7 17:28:06 2024 -0500

    [CT-517] E2E tests batch cancel (dydxprotocol#1149)

    * more end to end test

    * extraprint

    * more e2e test

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 41a3a41
Author: Teddy Ding <teddy@dydx.exchange>
Date:   Thu Mar 7 15:42:30 2024 -0500

    [OTE-200] OIMF protos (dydxprotocol#1125)

    * OIMF protos

    * add default genesis value, modify methods interface

    * fix genesis file

    * fix integration test

    * lint

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 2a062b1
Author: Teddy Ding <teddy@dydx.exchange>
Date:   Thu Mar 7 15:24:15 2024 -0500

    Add `v5` upgrade handler and set up container upgrade test (dydxprotocol#1153)

    * wip

    * update preupgrade_genesis

    * fix preupgrade_genesis.json

    * nit

    * setupUpgradeStoreLoaders for v5.0.0

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit b7942b3
Author: jayy04 <103467857+jayy04@users.noreply.github.com>
Date:   Thu Mar 7 13:43:48 2024 -0500

    [CT-647] construct the initial orderbook snapshot (dydxprotocol#1147)

    * [CT-647] construct the initial orderbook snapshot

    * [CT-647] initialize new streams and send orderbook snapshot (dydxprotocol#1152)

    * [CT-647] initialize new streams and send orderbook snapshot

    * use sync once

    * comments

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit c67a3c6
Author: shrenujb <98204323+shrenujb@users.noreply.github.com>
Date:   Thu Mar 7 12:40:37 2024 -0500

    [TRA-84] Move SA module address transfers to use perpetual based SA accounts (dydxprotocol#1146)

    Signed-off-by: Shrenuj Bansal <shrenuj@dydx.exchange
    Signed-off-by: Eric <eric.warehime@gmail.com>

commit dba23e0
Author: Mohammed Affan <affanmd@nyu.edu>
Date:   Thu Mar 7 10:34:11 2024 -0500

    update readme link to point to the right page (dydxprotocol#1151)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit b5870d5
Author: Tian <tian@dydx.exchange>
Date:   Wed Mar 6 16:43:04 2024 -0500

    [TRA-86] scaffold x/vault (dydxprotocol#1148)

    * scaffold x/vault

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 0eca041
Author: jayy04 <103467857+jayy04@users.noreply.github.com>
Date:   Wed Mar 6 10:48:42 2024 -0500

    [CT-652] add command line flag for full node streaming (dydxprotocol#1145)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit b319cb8
Author: jayy04 <103467857+jayy04@users.noreply.github.com>
Date:   Tue Mar 5 21:58:35 2024 -0500

    [CT-646] stream offchain updates through stream manager (dydxprotocol#1138)

    * [CT-646] stream offchain updates through stream manager

    * comments

    * fix lint

    * get rid of finished

    * comments

    * comments

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 1c54620
Author: shrenujb <98204323+shrenujb@users.noreply.github.com>
Date:   Tue Mar 5 16:34:19 2024 -0500

    [TRA-78] Add function to retrieve collateral pool addr for a subaccount (dydxprotocol#1142)

    Signed-off-by: Shrenuj Bansal <shrenuj@dydx.exchange>
    Signed-off-by: Eric <eric.warehime@gmail.com>

commit b8c1d62
Author: dydxwill <119354122+dydxwill@users.noreply.github.com>
Date:   Tue Mar 5 15:03:28 2024 -0500

    [OTE-141] implement post /compliance/geoblock (dydxprotocol#1129)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit ab8c570
Author: Jonathan Fung <121899091+jonfung-dydx@users.noreply.github.com>
Date:   Tue Mar 5 11:19:53 2024 -0500

    Fix mock-gen dydxprotocol#1140

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 12506a1
Author: shrenujb <98204323+shrenujb@users.noreply.github.com>
Date:   Mon Mar 4 21:33:28 2024 -0500

    [TRA-64] Use market specific insurance fund for cross or isolated markets (dydxprotocol#1132)

    Signed-off-by: Shrenuj Bansal <shrenuj@dydx.exchange>
    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 929f09e
Author: Jonathan Fung <121899091+jonfung-dydx@users.noreply.github.com>
Date:   Mon Mar 4 13:48:04 2024 -0800

    [CT-514] Clob `MsgBatchCancel` functionality (dydxprotocol#1110)

    * wip implementation

    * use new cometbft

    * Revert "use new cometbft"

    This reverts commit e5b8a03.

    * go mod tidy

    * basic e2e test

    * more msgBatchCancels in code

    * repeated fixed32 -> uint32

    * remove debug prints

    * update cometbft replace go.mod sha

    * one more debug print

    * typo

    * regen indexer protos

    * update comment on proto

    * proto comment changes

    * extract stateful validation into own fn

    * pr format comments

    * clean up test file

    * new return type with success and failure

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 41de83e
Author: dydxwill <119354122+dydxwill@users.noreply.github.com>
Date:   Mon Mar 4 12:22:16 2024 -0500

    add index to address read replica lag (dydxprotocol#1137)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 735d9a8
Author: dydxwill <119354122+dydxwill@users.noreply.github.com>
Date:   Mon Mar 4 11:56:59 2024 -0500

    rename (dydxprotocol#1136)

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 86617dd
Author: jayy04 <103467857+jayy04@users.noreply.github.com>
Date:   Mon Mar 4 10:43:31 2024 -0500

    [CT-644] instantiate grpc stream manager (dydxprotocol#1134)

    * [CT-644] instantiate grpc stream manager

    * update type

    * update channel type

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit 32afd64
Author: Eric <eric.warehime@gmail.com>
Date:   Mon Mar 11 12:41:06 2024 -0700

    Update go version in Dockerfile

    Signed-off-by: Eric <eric.warehime@gmail.com>

commit ba27204
Author: Eric <eric.warehime@gmail.com>
Date:   Fri Mar 8 09:44:04 2024 -0800

    Add slinky utils, use that to convert between market and currency pair

commit 667a804
Author: Eric <eric.warehime@gmail.com>
Date:   Wed Mar 6 20:43:40 2024 -0800

    Update error messages

commit d53292c
Author: Eric <eric.warehime@gmail.com>
Date:   Wed Mar 6 20:16:01 2024 -0800

    Update docstrings, rename OracleClient

commit daad125
Author: Eric <eric.warehime@gmail.com>
Date:   Mon Mar 4 10:51:23 2024 -0800

    VoteExtension slinky logic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants