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

Anonymize member creation for activities if listed in erasure requests #2711

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

skwowet
Copy link
Member

@skwowet skwowet commented Dec 5, 2024

Changes proposed ✍️

What

copilot:summary

copilot:poem

Why

How

copilot:walkthrough

Checklist ✅

  • Label appropriately with Feature, Improvement, or Bug.
  • Add screenshots to the PR description for relevant FE changes
  • New backend functionality has been unit-tested.
  • API documentation has been updated (if necessary) (see docs on API documentation).
  • Quality standards are met.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a command-line utility for anonymizing member data.
    • Enhanced database schema to support unique combinations of member identities.
    • Added functionality to create deterministic anonymized usernames.
  • Improvements

    • Updated member activity processing to streamline identity anonymization requests.
    • Enhanced error handling and logging for anonymization processes.
    • Improved management of identity erasure and anonymization requests within the repository.
  • Bug Fixes

    • Resolved issues related to identity erasure request handling in the database.

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

This pull request introduces changes to the database schema and application logic related to member identity anonymization. It modifies the requestedForErasureMemberIdentities table by altering unique constraints and adding a new column. A command-line utility for anonymizing member data is introduced, along with enhancements to the ActivityService for processing anonymization requests. Additionally, new methods are added to the RequestedForErasureMemberIdentitiesRepository for managing identity erasure requests. A function for creating deterministic anonymized usernames is also included.

Changes

File Change Summary
backend/src/database/migrations/U1733322265__anonymizeMemberIdentities.sql Dropped unique constraint unique_anonymized_member and added a new composite unique constraint on memberId, platform, type, and value.
backend/src/database/migrations/V1733322265__anonymizeMemberIdentities.sql Added column memberId of type uuid.
services/apps/data_sink_worker/src/bin/anonymize-member.ts Introduced a command-line utility for anonymizing member data, including argument validation, database operations, and error handling. Added functions for anonymization and file writing.
services/apps/data_sink_worker/src/service/activity.service.ts Updated ActivityService to handle member anonymization and identity erasure requests, utilizing a new repository for checking flagged identities.
services/libs/data-access-layer/src/gdpr/index.ts Added function anonymizeUsername to create a deterministic anonymized username using SHA-256 hashing.
services/libs/data-access-layer/src/old/apps/data_sink_worker/repo/requestedForErasureMemberIdentities.repo.ts Enhanced RequestedForErasureMemberIdentitiesRepository with methods for handling identity erasure requests, including insert, update, and retrieval functions.

Possibly related PRs

  • Activities sync fixes #2685: The changes in the main PR regarding the unique constraint on the requestedForErasureMemberIdentities table are related to the modifications in the activity.service.ts file, which handles member anonymization and identity erasure requests, indicating a connection in managing member identities.

Suggested reviewers

  • themarolt

Poem

🐇 In the database deep, where identities hide,
A new way to anonymize, we take in our stride.
With hashes and checks, our members secure,
A blend of the old with the new, that's for sure!
So hop along, friends, to the code we embrace,
For privacy's sake, we quicken the pace! 🌟


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>, please review it.
    • Generate unit testing code 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 testing code 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • 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/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@skwowet skwowet self-assigned this Dec 5, 2024
@skwowet skwowet added the Improvement Created by Linear-GitHub Sync label Dec 5, 2024
Copy link

@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.

Actionable comments posted: 7

🧹 Outside diff range and nitpick comments (3)
services/apps/data_sink_worker/src/bin/anonymize-member.ts (1)

256-256: Address TODO: Implement member data cleanup in anonymizeMemberInDb

There is a TODO comment indicating that original member data in the members table should be cleaned up. This is essential for complete anonymization.

Would you like assistance in implementing the cleanup of original member data to ensure full compliance with anonymization requirements?

backend/src/database/migrations/U1733322265__anonymizeMemberIdentities.sql (1)

1-3: Verify the necessity of modifying the unique constraint in separate migrations

The unique constraint unique_anonymized_member is dropped and re-added including memberId. Ensure that running these migrations separately doesn't cause issues and consider combining them for consistency.

Consider merging this migration with V1733322265__anonymizeMemberIdentities.sql to streamline the schema changes.

services/libs/data-access-layer/src/gdpr/index.ts (1)

3-9: Enhance documentation with GDPR compliance and security details.

While the current documentation is clear, consider adding important details about:

  • GDPR compliance aspects
  • The irreversible nature of the anonymization
  • Security implications of the 8-character hash length

Consider updating the documentation:

 /**
  * Creates a deterministic anonymized username from the original username, platform and type
+ * This function implements GDPR-compliant irreversible anonymization.
  * @param username The original username to anonymize
  * @param platform The platform the username belongs to
  * @param type The type of identity (e.g. 'username', 'email')
  * @returns A consistently hashed anonymous identity in the format 'anon_<type>_<hash>'
+ * @remarks
+ * - The anonymization is irreversible due to one-way SHA-256 hashing
+ * - Uses first 8 characters of the hash for brevity while maintaining uniqueness
+ * - Deterministic output ensures consistent anonymization across requests
  */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e696365 and cbe593f.

📒 Files selected for processing (6)
  • backend/src/database/migrations/U1733322265__anonymizeMemberIdentities.sql (1 hunks)
  • backend/src/database/migrations/V1733322265__anonymizeMemberIdentities.sql (1 hunks)
  • services/apps/data_sink_worker/src/bin/anonymize-member.ts (1 hunks)
  • services/apps/data_sink_worker/src/service/activity.service.ts (4 hunks)
  • services/libs/data-access-layer/src/gdpr/index.ts (1 hunks)
  • services/libs/data-access-layer/src/old/apps/data_sink_worker/repo/requestedForErasureMemberIdentities.repo.ts (2 hunks)
🔇 Additional comments (3)
services/libs/data-access-layer/src/gdpr/index.ts (3)

1-1: LGTM! Using Node.js built-in crypto module is appropriate.

The choice of the built-in crypto module ensures reliable cryptographic operations.


10-22: Verify GDPR compliance aspects.

Please ensure:

  1. The anonymization is consistently applied across all member-related operations
  2. No PII is leaked in logs or error messages when anonymization fails

Let's verify these aspects:

✅ Verification successful

Based on the search results, I can provide a final response:

GDPR compliance aspects verified successfully

  1. The anonymization is consistently applied across member-related operations:

    • Used in data sink worker for activity processing
    • Implemented in member erasure and anonymization scripts
    • Properly handles username, platform, and type parameters
  2. No direct PII leakage found in error handling:

    • Error messages use generic terms without exposing raw usernames
    • Anonymization happens before any logging or error reporting
    • The anonymization function is deterministic and one-way using SHA-256
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent anonymization usage
rg -A 5 "anonymizeUsername" --type typescript

# Look for potential PII leakage in error handling
rg -A 5 "catch|error|throw" --type typescript | rg -i "username|email|identity"

# Check logging statements around anonymization
rg "console\.|logger\." --type typescript | rg -i "username|email|identity"

Length of output: 310


Script:

#!/bin/bash
# Check for consistent anonymization usage across the codebase
rg -A 5 "anonymizeUsername"

# Look for potential PII leakage in error handling
rg -A 5 "catch|error|throw" | rg -i "username|email|identity"

# Check logging statements that might contain PII
rg "console\.|logger\." | rg -i "username|email|identity"

# Find all files that might handle user data
fd -e ts -e js | xargs rg -l "username|email|identity"

# Check for other anonymization functions
rg "anonymize|hash.*user"

Length of output: 70753


10-22: Consider collision risks with 8-character hash truncation.

While the implementation is generally solid, the 8-character hash truncation (32 bits) might lead to collisions in large datasets. The birthday paradox suggests potential collisions after approximately 2^16 entries.

Consider:

  1. Increasing the hash length to at least 12 characters (48 bits) for better uniqueness
  2. Adding collision detection and resolution mechanism

Let's verify the usage and potential collision risks:

✅ Verification successful

Based on the search results, I can now provide a final response:

8-character hash truncation is acceptable for this use case

The implementation of anonymizeUsername is used primarily for GDPR-related anonymization of individual usernames, not for bulk operations. The code analysis shows:

  1. Usage is limited to specific GDPR erasure requests in data_sink_worker
  2. Anonymization happens one user at a time through:
    • Individual erasure requests (getAnonymizationRequest)
    • Single-member anonymization processes (anonymizeMemberIfRequested)
  3. No evidence of bulk anonymization that could lead to collision risks

The current 8-character hash (32 bits) provides sufficient uniqueness for this specific GDPR anonymization use case, where:

  • Collisions would be extremely rare due to low volume
  • Each anonymization includes platform and type in hash calculation
  • The primary goal is consistent one-way anonymization, not unique identification
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential collision scenarios in the codebase
# Look for large batch operations or loops that might create many anonymous identities

# Search for bulk member operations
rg -A 5 "members?.create|members?.update" --type typescript

# Look for array operations that might involve member anonymization
ast-grep --pattern 'members.map($$$)' 

# Check if there's existing collision handling
rg -i "collision|duplicate|conflict" --type typescript

Length of output: 7547


Script:

#!/bin/bash
# Let's search for actual usage of anonymizeUsername function and any batch processing
rg -t ts -A 5 "anonymizeUsername" 

# Look for any GDPR or anonymization related batch operations
rg -t ts -A 5 "anonymize|gdpr" 

# Check if there are any large member lists or bulk operations
rg -t ts -A 5 "bulkCreate|bulkUpdate|insertMany|updateMany"

Length of output: 27226

Copy link

@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.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (4)
services/libs/data-access-layer/src/old/apps/data_sink_worker/repo/requestedForErasureMemberIdentities.repo.ts (1)

61-79: Add error handling for database operations

The method should handle potential database errors gracefully to prevent silent failures.

   private async insertIdentityForErasureRequest({
     platform,
     type,
     value,
     memberId,
   }): Promise<void> {
+    try {
       const query = `
       insert into "requestedForErasureMemberIdentities" (id, platform, type, value, memberId)
       values ($(id), $(platform), $(type), $(value), $(memberId))
       `

       return await this.db().none(query, {
         id: generateUUIDv1(),
         platform,
         type,
         value,
         memberId,
       })
+    } catch (error) {
+      this.log.error(error, 'Failed to insert identity for erasure request')
+      throw error
+    }
   }
services/apps/data_sink_worker/src/bin/anonymize-member.ts (2)

22-33: Add input validation for CLI arguments

While the code checks for argument pairs, it should also validate the content of these arguments (e.g., email format, platform values).

+const VALID_PLATFORMS = ['github', 'gitlab', 'lfid'] // Add all valid platforms
+
+function validateEmail(email: string): boolean {
+  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
+}
+
 if (processArguments.length === 0 || processArguments.length % 2 !== 0) {
   log.error(
     `
     Expected argument in pairs which can be any of the following:
       - ids "<memberId1>, <memberId2>, ..."
       - email [email protected]
       - name "John Doe"
       - <platform> <value> (e.g. lfid someusername)
     `,
   )
   process.exit(1)
 }
+
+// Validate argument values
+for (let i = 0; i < processArguments.length; i += 2) {
+  const type = processArguments[i]
+  const value = processArguments[i + 1]
+
+  if (type === 'email' && !validateEmail(value)) {
+    log.error(`Invalid email format: ${value}`)
+    process.exit(1)
+  }
+
+  if (!['ids', 'email', 'name'].includes(type) && !VALID_PLATFORMS.includes(type)) {
+    log.error(`Invalid argument type: ${type}`)
+    process.exit(1)
+  }
+}

256-256: Address the TODO comment about member data cleanup

The comment indicates a need for cleanup of original member data in the members table. This should be addressed to prevent data leakage.

Would you like me to help implement the cleanup logic for the original member data?

services/apps/data_sink_worker/src/service/activity.service.ts (1)

Line range hint 1011-1086: Add error handling for erasure request updates

The erasure request updates should be wrapped in try-catch blocks to handle potential failures gracefully.

   // If this was an anonymized member, update the erasure table with the new memberId
   if (anonymizedMember) {
+    try {
       for (const identity of member.identities) {
         await erasureRepo.updateErasureRequestMemberId(identity, memberId)
       }
+    } catch (error) {
+      log.error(error, { memberId }, 'Failed to update erasure requests for anonymized member')
+      throw error
+    }
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cbe593f and 67b4d91.

📒 Files selected for processing (4)
  • backend/src/database/migrations/V1733322265__anonymizeMemberIdentities.sql (1 hunks)
  • services/apps/data_sink_worker/src/bin/anonymize-member.ts (1 hunks)
  • services/apps/data_sink_worker/src/service/activity.service.ts (4 hunks)
  • services/libs/data-access-layer/src/old/apps/data_sink_worker/repo/requestedForErasureMemberIdentities.repo.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/database/migrations/V1733322265__anonymizeMemberIdentities.sql
🔇 Additional comments (4)
services/libs/data-access-layer/src/old/apps/data_sink_worker/repo/requestedForErasureMemberIdentities.repo.ts (3)

81-95: Include platform and type in WHERE clause

To ensure the correct record is updated and prevent unintended updates across different platforms or types, include platform and type in the WHERE clause.


97-130: Fix return value mismatch in getAnonymizationRequest method

The method returns an object with properties id, memberId, and value, but the SELECT query only fetches id and memberId.


132-188: Preserve existing member attributes in anonymizeMemberIfRequested

Setting attributes to an empty object may unintentionally remove important non-sensitive member attributes.

services/apps/data_sink_worker/src/service/activity.service.ts (1)

446-476: LGTM! Well-structured anonymization logic

The implementation properly handles member anonymization with appropriate logging and display name updates.

Comment on lines +235 to +248
function addLinesToFile(filePath: string, lines: string[]) {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true })
try {
fs.accessSync(filePath)
fs.appendFileSync(filePath, lines.join('\n') + '\n')
} catch (error) {
fs.writeFileSync(filePath, lines.join('\n') + '\n')
}
} catch (err) {
log.error(err, { filePath }, 'Error while writing to file!')
throw err
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add path validation in addLinesToFile

The function should validate the file path to prevent directory traversal attacks.

 function addLinesToFile(filePath: string, lines: string[]) {
   try {
+    // Validate file path
+    const normalizedPath = path.normalize(filePath)
+    if (normalizedPath.includes('..')) {
+      throw new Error('Directory traversal detected in file path')
+    }
+
     fs.mkdirSync(path.dirname(filePath), { recursive: true })
     try {
       fs.accessSync(filePath)

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Improvement Created by Linear-GitHub Sync
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant