Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Enhancement/mod11 ssn validation #796

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

Conversation

axely123
Copy link
Collaborator

@axely123 axely123 commented Mar 7, 2025

Description

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features

    • Enhanced social security number validation using refined control digit calculations for improved accuracy.
    • Added additional validation checks for recipient national identity numbers.
  • Tests

    • Added new tests verifying the behavior for valid and invalid social security numbers.
    • Updated existing test data to ensure consistency, including modifications to recipient identifiers in various test methods.
  • Refactor

    • Standardized internal constants for social security numbers across tests to align with the new validation logic.

Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

📝 Walkthrough

Walkthrough

This pull request updates the handling of social security numbers within the application’s tests and core helper libraries. It modifies specific test values (reserved SSN and recipient identifiers), introduces a new test class for SSN validation, adds a new helper class for Mod 11 control digit calculation, and enhances the SSN validation method in the core string extensions to incorporate the new helper logic.

Changes

File(s) Change Summary
Test/.../CustomWebApplicationFactory.cs, Test/.../CorrespondenceInitializationTests.cs Updated SSN values: changed the constant ReservedSsn from "12345123451" to "08900499559" and updated recipient identifiers in various test methods.
Test/.../StringExtensionsTests.cs Added a new test class with two unit tests validating the IsSocialSecurityNumber method for both invalid and valid synthetic SSNs.
src/.../Mod11.cs Introduced a new static class Mod11 with a TryCalculateControlDigit method for control digit calculation.
src/.../StringExtensions.cs Updated the IsSocialSecurityNumber method to include mod11 validation and added new weight arrays for control digit calculation.
src/.../InitializeCorrespondencesExt.cs Enhanced validation in the IsValid method of the RecipientListAttribute class to include checks against the IsSocialSecurityNumber method.
Test/.../CorrespondenceRetrievalTests.cs Updated recipient tokens in test methods to reflect new identifiers.

Possibly related PRs

  • Contact Reservation Registry #568: The changes in the main PR, specifically the update of the ReservedSsn constant in the CustomWebApplicationFactory class, are related to the modifications in the CorrespondenceInitializationTests class where the same social security number value is utilized in test scenarios.

Suggested labels

kind/feature-request

Suggested reviewers

  • CelineTrammi

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67f8e7e and dcf3755.

📒 Files selected for processing (2)
  • Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceInitializationTests.cs (4 hunks)
  • Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceRetrievalTests.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceInitializationTests.cs
🧰 Additional context used
🧠 Learnings (1)
Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceRetrievalTests.cs (1)
Learnt from: CelineTrammi
PR: Altinn/altinn-correspondence#533
File: Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceAttachmentTests.cs:103-103
Timestamp: 2024-11-29T09:06:46.947Z
Learning: In the test cases, plain IDs without URN prefixes represent social security numbers (SSNs) and are allowed as recipients in the `WithRecipients` method.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (1)
Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceRetrievalTests.cs (1)

216-216: Test SSN values updated for Mod11 compliance

The test recipient identifier has been changed from the previous value to a new social security number (26818099001) that likely complies with the Mod11 validation algorithm, aligning with the PR's purpose of enhancing SSN validation. The update ensures that both test cases consistently use the same validated identifier.

Also applies to: 238-238

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this 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.

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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/Altinn.Correspondence.Common/Helpers/Mod11.cs (1)

1-53: New Mod11 validation helper implementation

The implementation provides a clean, efficient way to validate numbers using the Mod11 algorithm, which is commonly used for validating identification numbers including social security numbers.

However, consider the following improvements:

  1. Add XML documentation comments explaining the purpose and usage of the Mod11 algorithm.
  2. Add input validation to handle null or empty input numbers.
  3. Add validation to ensure the weights array is non-empty.
 using System.Diagnostics.CodeAnalysis;

 namespace Altinn.Correspondence.Common.Helpers;

+/// <summary>
+/// Helper class for calculating control digits using the Mod11 algorithm.
+/// </summary>
 internal static class Mod11
 {
     private const int Mod11Number = 11;
     private const int InvalidControlDigit = 10;

+    /// <summary>
+    /// Attempts to calculate a control digit for the given number using the Mod11 algorithm.
+    /// </summary>
+    /// <param name="number">The number for which to calculate the control digit.</param>
+    /// <param name="weights">The weights to apply to each digit in the number.</param>
+    /// <param name="controlDigit">When this method returns, contains the calculated control digit, or null if the calculation failed.</param>
+    /// <returns>True if the control digit was successfully calculated; otherwise, false.</returns>
     public static bool TryCalculateControlDigit(ReadOnlySpan<char> number, int[] weights, [NotNullWhen(true)] out int? controlDigit)
     {
+        if (number.IsEmpty || weights.Length == 0)
+        {
+            controlDigit = null;
+            return false;
+        }
+
         var digits = number.ExtractDigits();

         if (digits.Length != number.Length ||
             digits.Length > weights.Length)
         {
             controlDigit = null;
             return false;
         }

         var sum = 0;
         for (var i = 0; i < digits.Length; i++)
         {
             sum += digits[i] * weights[i];
         }
         controlDigit = Mod11Number - (sum % Mod11Number);
         controlDigit = controlDigit switch
         {
             Mod11Number => 0,
             InvalidControlDigit => null,
             _ => controlDigit
         };

         return controlDigit is not null;
     }

     private static int[] ExtractDigits(this ReadOnlySpan<char> number)
     {
         var result = new int[number.Length];
         var index = 0;

         foreach (var character in number)
         {
             if (char.IsDigit(character))
             {
                 result[index++] = character - '0';
             }
         }

         Array.Resize(ref result, index);
         return result;
     }
 }
src/Altinn.Correspondence.Common/Helpers/StringExtensions.cs (1)

44-49: Improve method documentation.

The XML documentation is incomplete. Please enhance it to describe what constitutes a valid social security number (including the Mod11 check) and complete the <returns> tag.

/// <summary>
-/// Checks if a social security number is valid.
+/// Checks if a social security number is valid by verifying it matches the expected
+/// 11-digit format and validating both control digits using the Mod11 algorithm.
/// </summary>
/// <param name="identifier">The string to validate.</param>
-/// <returns></returns>
+/// <returns>True if the string is a valid social security number with correct control digits, false otherwise.</returns>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d78db87 and 3630241.

📒 Files selected for processing (5)
  • Test/Altinn.Correspondence.Tests/Helpers/CustomWebApplicationFactory.cs (1 hunks)
  • Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceInitializationTests.cs (1 hunks)
  • Test/Altinn.Correspondence.Tests/TestingUtility/StringExtensionsTests.cs (1 hunks)
  • src/Altinn.Correspondence.Common/Helpers/Mod11.cs (1 hunks)
  • src/Altinn.Correspondence.Common/Helpers/StringExtensions.cs (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceInitializationTests.cs (1)
Learnt from: CelineTrammi
PR: Altinn/altinn-correspondence#533
File: Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceAttachmentTests.cs:103-103
Timestamp: 2024-11-29T09:06:46.947Z
Learning: In the test cases, plain IDs without URN prefixes represent social security numbers (SSNs) and are allowed as recipients in the `WithRecipients` method.
🔇 Additional comments (7)
Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceInitializationTests.cs (1)

433-433: SSN value has been updated to a valid Mod11 SSN

The personRecipient value has been updated from "01234567890" to "08900499559", which is now a valid social security number that passes Mod11 validation.

Test/Altinn.Correspondence.Tests/TestingUtility/StringExtensionsTests.cs (1)

1-33: Well-structured unit tests for SSN validation

The test class provides clear validation tests for both invalid and valid synthetic social security numbers using the new Mod11 validation. The tests follow the AAA (Arrange-Act-Assert) pattern and have clear naming conventions.

Test/Altinn.Correspondence.Tests/Helpers/CustomWebApplicationFactory.cs (1)

28-28: ReservedSsn constant updated to use valid Mod11 SSN

The ReservedSsn constant has been updated from an invalid value to "08900499559", which is a valid Mod11-compliant social security number. This maintains consistency with the other test cases.

src/Altinn.Correspondence.Common/Helpers/StringExtensions.cs (4)

1-1: Appropriate addition of System.Globalization namespace.

The addition of this namespace is necessary to support the use of CultureInfo.InvariantCulture in the new validation method.


8-9: LGTM: Properly defined weight arrays for Mod11 control digit calculation.

These weight arrays are correctly defined for Norwegian SSN validation using the Mod11 algorithm.


18-18: Good refactoring: Improved validation logic.

The method now properly delegates to the new, more thorough validation logic while maintaining its original interface.


50-56: Well-implemented Mod11 validation for SSN.

The implementation correctly:

  1. Verifies the basic pattern (11 digits)
  2. Validates both control digits using the appropriate weight arrays
  3. Uses efficient string manipulation with Span
  4. Properly handles culture-invariant number parsing

This is a significant improvement over simple regex validation, as it ensures the SSN has valid check digits.

@axely123 axely123 added the kind/enhancement Improving existing feature label Mar 10, 2025
@axely123 axely123 linked an issue Mar 10, 2025 that may be closed by this pull request
Ytterås added 2 commits March 10, 2025 09:59
…cipient in initializeCorrespondenceExt to prevent Internal Server error
Copy link
Collaborator

@Ceredron Ceredron left a comment

Choose a reason for hiding this comment

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

Nice! Great work integrating this with existing code.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
kind/enhancement Improving existing feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Speil Dialogportens personnummervalidering i vår
2 participants