Skip to content

Updated validate no subres#1761

Open
simen-rekkedal wants to merge 3 commits intomainfrom
updated_validate_no_subres
Open

Updated validate no subres#1761
simen-rekkedal wants to merge 3 commits intomainfrom
updated_validate_no_subres

Conversation

@simen-rekkedal
Copy link
Contributor

@simen-rekkedal simen-rekkedal commented Jan 5, 2026

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

  • Bug Fixes

    • Enhanced validation for system rights to enforce strict single-resource matching per right. Requests containing rights with multiple resources are now properly rejected with appropriate error handling.
  • Tests

    • Added validation tests for multi-resource right failure scenarios and updated test suite to align with stricter validation requirements.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 5, 2026

📝 Walkthrough

Walkthrough

The changes introduce validation constraints on multi-resource rights in authentication services. SystemRegisterService and SystemUserService now flag or reject rights containing multiple resources, treating them as invalid. Accompanying test updates replace previously passing sub-resource test cases with negative test scenarios that expect failures when multi-resource rights are provided.

Changes

Cohort / File(s) Summary
Service validation logic
src/Authentication/Services/SystemRegisterService.cs, src/Authentication/Services/SystemUserService.cs
Added pre-validation checks to restrict multi-resource rights. SystemRegisterService flags second resources in multi-resource rights as invalid format in GetInvalidResourceIdsDetailed. SystemUserService rejects rights with resource count != 1 in ValidateRights, returning Problem.Rights_NotFound_Or_NotDelegable before per-resource processing.
Controller tests
test/Altinn.Platform.Authentication.Tests/Controllers/ChangeRequestControllerTest.cs
Added test ChangeRequest_Create_SubResource_ReturnBadrequest that expects BadRequest when creating a ChangeRequest with invalid sub-resource rights.
Request controller tests
test/Altinn.Platform.Authentication.Tests/Controllers/RequestControllerTests.cs
Added Create_Request_WithSubResource_ReturnBadRequest test expecting BadRequest for multi-resource requests. Removed Request_Create_Succeed_SubResource test. Modified Request_Create_Failed_WrongRights to validate invalid resource format errors.
System user controller tests
test/Altinn.Platform.Authentication.Tests/Controllers/SystemUserControllerTest.cs
Removed SystemUser_CreateAndDelegate_2RightsSubresource_ReturnsOk test that previously validated successful multi-resource creation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'Updated validate no subres' is vague and uses abbreviated terminology that lacks sufficient context to convey the specific change being made. Provide a clearer title that specifically describes the validation change, such as 'Reject requests with multiple resources per right' or 'Add validation to prevent multi-resource rights'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch updated_validate_no_subres

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 1

Fix all issues with AI Agents 🤖
In @src/Authentication/Services/SystemRegisterService.cs:
- Around line 161-165: The validation only adds the second resource
(right.Resource[1].Value) to invalidFormatResourceIds when there are multiple
resources, so any additional resources beyond the second are ignored; change the
logic in the SystemRegisterService validation block to iterate over all
resources after the first (e.g., for each resource in right.Resource.Skip(1) or
a for-loop from index 1 to right.Resource.Count-1) and add each resource.Value
to invalidFormatResourceIds so every extra resource is flagged.
🧹 Nitpick comments (2)
test/Altinn.Platform.Authentication.Tests/Controllers/ChangeRequestControllerTest.cs (2)

249-253: Update the doc comment to reflect the test's actual purpose.

The XML doc comment describes creating a ChangeRequest successfully, but this test validates that creating a ChangeRequest with sub-resource rights returns BadRequest. Consider updating the summary to clarify:

 /// <summary>
-/// After having verified that the ChangeRequest is needed, create a ChangeRequest
+/// Verifies that creating a ChangeRequest with multi-resource (sub-resource) rights returns BadRequest
 /// </summary>

349-352: Remove unused variables.

The variables orgno, ext, and sys are declared but never used in this test. Only id is used in the endpoint URL.

🔎 Proposed fix
         Guid id = Guid.NewGuid();
-        string orgno = "910493353";
-        string ext = "external";
-        string sys = "991825827_the_matrix";
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b5e7e3a and d1ee77e.

📒 Files selected for processing (5)
  • src/Authentication/Services/SystemRegisterService.cs
  • src/Authentication/Services/SystemUserService.cs
  • test/Altinn.Platform.Authentication.Tests/Controllers/ChangeRequestControllerTest.cs
  • test/Altinn.Platform.Authentication.Tests/Controllers/RequestControllerTests.cs
  • test/Altinn.Platform.Authentication.Tests/Controllers/SystemUserControllerTest.cs
💤 Files with no reviewable changes (1)
  • test/Altinn.Platform.Authentication.Tests/Controllers/SystemUserControllerTest.cs
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-11-04T17:38:15.650Z
Learnt from: simen-rekkedal
Repo: Altinn/altinn-authentication PR: 1581
File: src/Authentication/Controllers/RequestSystemUserController.cs:459-485
Timestamp: 2025-11-04T17:38:15.650Z
Learning: In the Altinn Authentication codebase (src/Authentication/Controllers/RequestSystemUserController.cs), party parameter validation for system user request operations is handled by the Policy Enforcement Point (PEP) layer, not at the controller level. Controller methods rely on authorization policies like AuthzConstants.POLICY_ACCESS_MANAGEMENT_WRITE to enforce party-level access control.

Applied to files:

  • test/Altinn.Platform.Authentication.Tests/Controllers/RequestControllerTests.cs
🧬 Code graph analysis (2)
src/Authentication/Services/SystemRegisterService.cs (1)
test/Altinn.Platform.Authentication.SystemIntegrationTests/Domain/Right.cs (1)
  • Resource (10-15)
src/Authentication/Services/SystemUserService.cs (2)
test/Altinn.Platform.Authentication.SystemIntegrationTests/Domain/Right.cs (1)
  • Resource (10-15)
src/Core/Problems/Problem.cs (1)
  • Problem (8-410)
🔇 Additional comments (5)
src/Authentication/Services/SystemUserService.cs (1)

642-645: LGTM! Clean enforcement of single-resource policy.

The strict check ensures exactly one resource per right before proceeding with validation. This is a clear and effective guard that aligns with the broader validation policy changes across the PR.

test/Altinn.Platform.Authentication.Tests/Controllers/RequestControllerTests.cs (3)

20-20: LGTM! Import supports validation error checking.

The added import enables the test to verify specific validation error messages.


236-246: LGTM! Test correctly validates early rejection of multi-resource rights.

The refactored test now validates that system register creation fails immediately when rights contain multiple resources, aligning with the new pre-check validation in SystemRegisterService.GetInvalidResourceIdsDetailed.


2115-2159: LGTM! Comprehensive test for multi-resource rejection.

The new test validates that requests with multi-resource rights are properly rejected with BadRequest, ensuring the single-resource policy is enforced at the request creation layer.

test/Altinn.Platform.Authentication.Tests/Controllers/ChangeRequestControllerTest.cs (1)

282-297: Test logic for sub-resource validation looks correct.

The test correctly constructs right2 with two AttributePair entries under the same Resource collection, simulating a multi-resource right. The assertion for HttpStatusCode.BadRequest aligns with the PR objective to reject such rights during ChangeRequest creation.

Consider adding an assertion on the response body to verify the error message or problem details, ensuring the correct validation error is returned:

// Optional: verify error details
var problemDetails = await createdResponseMessage.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problemDetails);
// Assert specific error code or message if applicable

Also applies to: 357-368

Comment on lines +161 to +165
// For now we only support single resource per right, no sub-resources
if (right.Resource.Count > 1)
{
invalidFormatResourceIds.Add(right.Resource[1].Value);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Flag all extra resources beyond the first, not just the second.

If a right contains 3 or more resources, only the second resource (index 1) is added to invalidFormatResourceIds. Resources at indices 2, 3, etc. are silently ignored. Consider flagging all resources beyond the first for complete validation feedback.

🔎 Proposed fix to flag all extra resources
 // For now we only support single resource per right, no sub-resources
 if (right.Resource.Count > 1)
 {
-    invalidFormatResourceIds.Add(right.Resource[1].Value);
+    for (int i = 1; i < right.Resource.Count; i++)
+    {
+        invalidFormatResourceIds.Add(right.Resource[i].Value);
+    }
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For now we only support single resource per right, no sub-resources
if (right.Resource.Count > 1)
{
invalidFormatResourceIds.Add(right.Resource[1].Value);
}
// For now we only support single resource per right, no sub-resources
if (right.Resource.Count > 1)
{
for (int i = 1; i < right.Resource.Count; i++)
{
invalidFormatResourceIds.Add(right.Resource[i].Value);
}
}
🤖 Prompt for AI Agents
In @src/Authentication/Services/SystemRegisterService.cs around lines 161-165,
The validation only adds the second resource (right.Resource[1].Value) to
invalidFormatResourceIds when there are multiple resources, so any additional
resources beyond the second are ignored; change the logic in the
SystemRegisterService validation block to iterate over all resources after the
first (e.g., for each resource in right.Resource.Skip(1) or a for-loop from
index 1 to right.Resource.Count-1) and add each resource.Value to
invalidFormatResourceIds so every extra resource is flagged.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Jan 5, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant