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

fix(auth): Allow .noconsent scope in EndUser auth policy #1760

Conversation

oskogstad
Copy link
Collaborator

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)

Documentation

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

@oskogstad oskogstad requested a review from a team as a code owner January 29, 2025 14:47
Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new authorization scope EndUserNoConsent across multiple files in the Dialogporten project. The changes modify authorization policies to allow users with either the EndUser or EndUserNoConsent scopes. The modifications occur in both GraphQL and WebApi authorization-related classes, including changes to policy configuration and the visibility of the ScopeClaim constant. The primary goal appears to be expanding the authorization mechanism to support a new type of end-user access.

Changes

File Change Summary
...Authorization/AuthorizationOptionsSetup.cs (GraphQL/WebApi) Modified EndUser policy to accept either AuthorizationScope.EndUser or AuthorizationScope.EndUserNoConsent scopes
...Authorization/AuthorizationPolicy.cs (GraphQL/WebApi) Added new constant EndUserNoConsent = "digdir:dialogporten.noconsent"
...Authorization/AuthorizationPolicyBuilderExtensions.cs (GraphQL/WebApi) Changed ScopeClaim constant from private to public

Possibly related PRs

Suggested reviewers

  • knuhau

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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 (4)
src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicyBuilderExtensions.cs (1)

8-8: Consider documenting the reason for making ScopeClaim public.

While making the constant public allows for reuse, it's good practice to document why this visibility change was necessary, especially for security-related constants.

Consider adding a code comment explaining the rationale:

+    // Made public to enable consistent scope claim validation across the application
     public const string ScopeClaim = "scope";
src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicy.cs (1)

17-17: LGTM! Consider adding documentation for the new scope.

The EndUserNoConsent scope is correctly implemented and matches the GraphQL version. Consider adding XML documentation to explain its purpose and usage scenarios.

Add documentation to clarify the scope's purpose:

+    /// <summary>
+    /// Scope for end-user access without requiring explicit consent.
+    /// Used in scenarios where consent requirements are waived.
+    /// </summary>
     public const string EndUserNoConsent = "digdir:dialogporten.noconsent";
src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationOptionsSetup.cs (1)

31-40: Optimize scope validation performance and improve code organization.

The current implementation has some minor performance and maintainability considerations:

  1. The ToList() call creates an unnecessary allocation since Contains works with IEnumerable<T>.
  2. The scope validation logic could be extracted to improve reusability.

Consider applying these improvements:

+    private static bool HasValidEndUserScope(AuthorizationHandlerContext context)
+    {
+        var userScopes = context.User
+            .FindAll(AuthorizationPolicyBuilderExtensions.ScopeClaim)
+            .Select(s => s.Value);
+        
+        return userScopes.Contains(AuthorizationScope.EndUser) ||
+               userScopes.Contains(AuthorizationScope.EndUserNoConsent);
+    }

     options.AddPolicy(AuthorizationPolicy.EndUser, builder => builder
         .Combine(options.DefaultPolicy)
-        .RequireAssertion(context =>
-        {
-            var userScopes = context.User
-                .FindAll(AuthorizationPolicyBuilderExtensions.ScopeClaim)
-                .Select(s => s.Value)
-                .ToList();
-
-            return userScopes.Contains(AuthorizationScope.EndUser) ||
-                   userScopes.Contains(AuthorizationScope.EndUserNoConsent);
-        }));
+        .RequireAssertion(HasValidEndUserScope));
src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationOptionsSetup.cs (1)

35-44: Consider extracting shared authorization logic to avoid duplication.

The EndUser authorization logic is duplicated between the WebApi and GraphQL AuthorizationOptionsSetup classes. This could lead to maintenance issues if the logic needs to be updated.

Consider creating a shared authorization helper class that both implementations can use:

+ namespace Digdir.Domain.Dialogporten.Common.Authorization;
+ 
+ public static class AuthorizationHelpers
+ {
+     public static bool HasValidEndUserScope(AuthorizationHandlerContext context)
+     {
+         var userScopes = context.User
+             .FindAll(AuthorizationPolicyBuilderExtensions.ScopeClaim)
+             .Select(s => s.Value);
+         
+         return userScopes.Contains(AuthorizationScope.EndUser) ||
+                userScopes.Contains(AuthorizationScope.EndUserNoConsent);
+     }
+ }

Then use it in both places:

     options.AddPolicy(AuthorizationPolicy.EndUser, builder => builder
         .Combine(options.DefaultPolicy)
-        .RequireAssertion(context =>
-        {
-            var userScopes = context.User
-                .FindAll(AuthorizationPolicyBuilderExtensions.ScopeClaim)
-                .Select(s => s.Value)
-                .ToList();
-
-            return userScopes.Contains(AuthorizationScope.EndUser) ||
-                   userScopes.Contains(AuthorizationScope.EndUserNoConsent);
-        }));
+        .RequireAssertion(AuthorizationHelpers.HasValidEndUserScope));
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67ee75d and d7fe34c.

📒 Files selected for processing (6)
  • src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationOptionsSetup.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationPolicy.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationPolicyBuilderExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationOptionsSetup.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicy.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicyBuilderExtensions.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Dry run deploy apps / Deploy job sync-resource-policy-information-job to test
  • GitHub Check: Dry run deploy apps / Deploy job sync-subject-resource-mappings-job to test
  • GitHub Check: build / build-and-test
🔇 Additional comments (4)
src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationPolicyBuilderExtensions.cs (1)

8-8: LGTM! Maintains consistency with WebApi implementation.

The visibility change matches the WebApi version, ensuring consistent authorization handling across both implementations.

src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationPolicy.cs (1)

17-17: Verify the new scope's integration with existing authorization flows.

The new EndUserNoConsent scope has been added following the correct naming convention. Let's verify its usage across the codebase.

✅ Verification successful

The EndUserNoConsent scope is properly integrated into authorization flows

The scope is correctly configured in both GraphQL and WebApi authorization setups, working as an alternative to the EndUser scope. The implementation is consistent across both projects, ensuring uniform authorization behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of the new scope in authorization policies and tests
echo "Searching for EndUserNoConsent scope usage..."
rg -l "EndUserNoConsent" --type cs

echo -e "\nSearching for related authorization policy configurations..."
ast-grep --pattern 'options.AddPolicy($_, policy => policy.RequireScope($_))' --lang cs

Length of output: 704


Script:

#!/bin/bash
# Check scope configuration and usage
echo "=== GraphQL AuthorizationOptionsSetup ==="
rg -A 5 -B 5 "EndUserNoConsent" src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationOptionsSetup.cs

echo -e "\n=== WebApi AuthorizationOptionsSetup ==="
rg -A 5 -B 5 "EndUserNoConsent" src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationOptionsSetup.cs

echo -e "\n=== Searching for [Authorize] attributes with EndUserNoConsent ==="
ast-grep --pattern '[Authorize(Policy = $_)]' --lang cs | rg -A 2 -B 2 "EndUserNoConsent"

Length of output: 1699

src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationOptionsSetup.cs (1)

31-40: Verify the security implications of allowing EndUserNoConsent scope.

The changes broaden the authorization scope by allowing either EndUser or EndUserNoConsent. Please ensure this aligns with the security requirements and document any limitations or restrictions associated with the EndUserNoConsent scope.

Run this script to analyze the usage and implications:

src/Digdir.Domain.Dialogporten.GraphQL/Common/Authorization/AuthorizationOptionsSetup.cs (1)

35-44: Verify consistent behavior between WebApi and GraphQL implementations.

Since both WebApi and GraphQL implementations now support the EndUserNoConsent scope, ensure they behave consistently across different authentication scenarios.

Run this script to compare the implementations:

✅ Verification successful

Authorization implementations are identical and consistent

The WebApi and GraphQL implementations handle the EndUserNoConsent scope in exactly the same way, with identical scope definitions and authorization logic. Both implementations use the same policy configuration that allows access with either the EndUser or EndUserNoConsent scope.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Compare authorization implementations
echo "Comparing authorization setup..."
rg -l "AuthorizationOptionsSetup" --type cs

echo -e "\nComparing EndUser policy configurations..."
rg "AddPolicy.*EndUser.*RequireAssertion" -A 10 --type cs

echo -e "\nSearching for potential differences in scope handling..."
rg "AuthorizationScope" -A 5 --type cs

Length of output: 30830

@oskogstad oskogstad merged commit d770779 into main Jan 29, 2025
23 checks passed
@oskogstad oskogstad deleted the fix/using-noconsent-scope-on-enduser-api-fails-with-500-internal-server-error branch January 29, 2025 15:31
arealmaas added a commit that referenced this pull request Jan 30, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.47.5](v1.47.4...v1.47.5)
(2025-01-30)


### Bug Fixes

* **auth:** Allow .noconsent scope in EndUser auth policy
([#1760](#1760))
([d770779](d770779))
* **auth:** Split values when checking EndUser scopes
([#1764](#1764))
([5957e7d](5957e7d))


### Miscellaneous Chores

* Add FormSubmitted and FormSaved to ActivityType
([#1742](#1742))
([4b9bad0](4b9bad0))
* **deps:** update dependency ziggycreatures.fusioncache to v2
([#1752](#1752))
([dd24928](dd24928))
* **perfomance:** Fixing github action to run performance tests in k8s
([#1739](#1739))
([166d53d](166d53d))
* Remove old OccuredAt property on DomainEvent
([#1758](#1758))
([67ee75d](67ee75d))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: Are Almaas <[email protected]>
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.

2 participants