Skip to content

Conversation

@sbernauer
Copy link
Member

@sbernauer sbernauer commented Nov 4, 2025

Description

Sometimes more context than the username and/or groups is helpful to make an authorization decision.
This PR adds support to additionally send the users principal to the OPA server.
As this increases the payload size for every OPA request, we made this opt-in using the configuration property opa.include-user-principal

Release notes

( ) This is not user-visible or is docs only, and no release notes are required.
( ) Release notes are required. Please propose a release note for me.
(x) Release notes are required, with the following suggested text:

## Added
* Support sending user principal to open policy agent 

Summary by Sourcery

Add optional support for including the user principal in OPA authorization requests based on a new configuration property.

New Features:

  • Add opa.include-user-principal configuration option to opt in to sending the user principal in OPA requests

Enhancements:

  • Extend TrinoIdentity and TrinoUser to carry an optional Principal when includeUserPrincipal is enabled
  • Update OpaAccessControl and OpaBatchAccessControl to pass the includeUserPrincipal flag when building OPA input

Documentation:

  • Document the new opa.include-user-principal property in the OPA access control documentation

Tests:

  • Add OpaConfig tests for default and explicit includeUserPrincipal mappings
  • Add end-to-end test verifying the OPA request payload includes the user principal when enabled and include a SerializableTestPrincipal helper

Chores:

  • Introduce SerializableTestPrincipal class for testing principal serialization

@cla-bot cla-bot bot added the cla-signed label Nov 4, 2025
@sourcery-ai
Copy link

sourcery-ai bot commented Nov 4, 2025

Reviewer's Guide

Added optional inclusion of the user’s Principal in authorization requests to OPA via a new opa.include-user-principal configuration flag, with corresponding data model, access control, test, and documentation updates.

Entity relationship diagram for TrinoIdentity principal inclusion

erDiagram
    IDENTITY {
        string user
        string[] groups
        principal principal
    }
    TRINO_IDENTITY {
        string user
        string[] groups
        principal principal
    }
    PRINCIPAL {
        string details
    }
    IDENTITY ||--o| PRINCIPAL : has
    TRINO_IDENTITY ||--o| PRINCIPAL : has
Loading

Class diagram for updated TrinoIdentity and TrinoUser

classDiagram
    class Identity {
        +String user
        +Set<String> groups
        +Optional<Principal> principal
    }
    class TrinoIdentity {
        +String user
        +Set<String> groups
        +Optional<Principal> principal
        +static fromTrinoIdentity(identity: Identity, includeUserPrincipal: boolean): TrinoIdentity
    }
    class TrinoUser {
        +TrinoUser(identity: Identity, includeUserPrincipal: boolean)
    }
    Identity <|-- TrinoIdentity
    TrinoIdentity <|-- TrinoUser
Loading

Class diagram for updated OpaConfig and OpaAccessControl

classDiagram
    class OpaConfig {
        -boolean includeUserPrincipal
        +boolean getIncludeUserPrincipal()
        +OpaConfig setIncludeUserPrincipal(boolean)
    }
    class OpaAccessControl {
        -boolean includeUserPrincipal
        +OpaAccessControl(..., OpaConfig config, ...)
    }
    OpaConfig <|-- OpaAccessControl
Loading

File-Level Changes

Change Details Files
Introduce and wire up includeUserPrincipal config property
  • Add includeUserPrincipal field, getter, setter, and annotations in OpaConfig
  • Update TestOpaConfig to cover default and explicit mapping of the new property
  • Document opa.include-user-principal in OPA access control docs
OpaConfig.java
TestOpaConfig.java
opa-access-control.md
Extend identity/resource models to carry optional principal
  • Enhance TrinoIdentity to hold Optional and adjust constructor logic
  • Add new TrinoUser constructor overload to accept principal-inclusion flag
  • Propagate includeUserPrincipal flag from config into TrinoIdentity and TrinoUser in OpaAccessControl and OpaBatchAccessControl
TrinoIdentity.java
TrinoUser.java
OpaAccessControl.java
OpaBatchAccessControl.java
Add tests for principal inclusion
  • Update TestOpaAccessControl to include principal on dummy identity
  • Add testIncludeUserPrincipal to verify serialization of principal in OPA request
  • Introduce SerializableTestPrincipal for Jackson-based test serialization
TestOpaAccessControl.java
SerializableTestPrincipal.java

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions github-actions bot added the docs label Nov 4, 2025
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `plugin/trino-opa/src/test/java/io/trino/plugin/opa/TestOpaAccessControl.java:694-695` </location>
<code_context>
         assertStringRequestsEqual(ImmutableSet.of(expectedRequest), mockClient.getRequests(), "/input");
     }

+    @Test
+    void testIncludeUserPrincipal() {
+        InstrumentedHttpClient mockClient = createMockHttpClient(OPA_SERVER_URI, request -> OK_RESPONSE);
+        OpaAccessControl authorizer = (OpaAccessControl) OpaAccessControlFactory.create(
</code_context>

<issue_to_address>
**suggestion (testing):** Consider adding negative and edge case tests for principal inclusion.

Please add tests for: (1) config set to false, ensuring principal is excluded; (2) principal is null or missing; (3) principal with special characters or large size. This will improve coverage of edge cases.

Suggested implementation:

```java
    @Test
    void testIncludeUserPrincipal() {
        InstrumentedHttpClient mockClient = createMockHttpClient(OPA_SERVER_URI, request -> OK_RESPONSE);
        OpaAccessControl authorizer = (OpaAccessControl) OpaAccessControlFactory.create(
                ImmutableMap.of("opa.policy.uri", OPA_SERVER_URI.toString(), "opa.include-user-principal", "true"),
                Optional.of(mockClient),
                Optional.empty());
        Identity sampleIdentityWithGroupsAndPrincipal = Identity.forUser("test_user").withGroups(ImmutableSet.of("some_group")).withPrincipal(new SerializableTestPrincipal("test_principal")).build();
        authorizer.checkCanExecuteQuery(sampleIdentityWithGroupsAndPrincipal, TEST_QUERY_ID);

        String expectedRequest =
                """
                {
                    "action": {

```

```java
                }
                """;
        assertStringRequestsEqual(ImmutableSet.of(expectedRequest), mockClient.getRequests(), "/input");
    }

    @Test
    void testExcludeUserPrincipalWhenConfigFalse() {
        InstrumentedHttpClient mockClient = createMockHttpClient(OPA_SERVER_URI, request -> OK_RESPONSE);
        OpaAccessControl authorizer = (OpaAccessControl) OpaAccessControlFactory.create(
                ImmutableMap.of("opa.policy.uri", OPA_SERVER_URI.toString(), "opa.include-user-principal", "false"),
                Optional.of(mockClient),
                Optional.empty());
        Identity sampleIdentityWithPrincipal = Identity.forUser("test_user").withGroups(ImmutableSet.of("some_group")).withPrincipal(new SerializableTestPrincipal("test_principal")).build();
        authorizer.checkCanExecuteQuery(sampleIdentityWithPrincipal, TEST_QUERY_ID);

        String expectedRequest =
                """
                {
                    "action": {
                        "type": "EXECUTE_QUERY",
                        "queryId": "test_query_id"
                    },
                    "user": {
                        "user": "test_user",
                        "groups": ["some_group"]
                    }
                }
                """;
        assertStringRequestsEqual(ImmutableSet.of(expectedRequest), mockClient.getRequests(), "/input");
    }

    @Test
    void testPrincipalIsNullOrMissing() {
        InstrumentedHttpClient mockClient = createMockHttpClient(OPA_SERVER_URI, request -> OK_RESPONSE);
        OpaAccessControl authorizer = (OpaAccessControl) OpaAccessControlFactory.create(
                ImmutableMap.of("opa.policy.uri", OPA_SERVER_URI.toString(), "opa.include-user-principal", "true"),
                Optional.of(mockClient),
                Optional.empty());
        Identity sampleIdentityWithoutPrincipal = Identity.forUser("test_user").withGroups(ImmutableSet.of("some_group")).build();
        authorizer.checkCanExecuteQuery(sampleIdentityWithoutPrincipal, TEST_QUERY_ID);

        String expectedRequest =
                """
                {
                    "action": {
                        "type": "EXECUTE_QUERY",
                        "queryId": "test_query_id"
                    },
                    "user": {
                        "user": "test_user",
                        "groups": ["some_group"]
                    }
                }
                """;
        assertStringRequestsEqual(ImmutableSet.of(expectedRequest), mockClient.getRequests(), "/input");
    }

    @Test
    void testPrincipalWithSpecialCharactersAndLargeSize() {
        InstrumentedHttpClient mockClient = createMockHttpClient(OPA_SERVER_URI, request -> OK_RESPONSE);
        OpaAccessControl authorizer = (OpaAccessControl) OpaAccessControlFactory.create(
                ImmutableMap.of("opa.policy.uri", OPA_SERVER_URI.toString(), "opa.include-user-principal", "true"),
                Optional.of(mockClient),
                Optional.empty());
        String specialPrincipal = "user!@#$%^&*()_+-=[]{},.<>?/|~`" + "A".repeat(1000);
        Identity sampleIdentityWithSpecialPrincipal = Identity.forUser("test_user").withGroups(ImmutableSet.of("some_group")).withPrincipal(new SerializableTestPrincipal(specialPrincipal)).build();
        authorizer.checkCanExecuteQuery(sampleIdentityWithSpecialPrincipal, TEST_QUERY_ID);

        String expectedRequest =
                String.format("""
                {
                    "action": {
                        "type": "EXECUTE_QUERY",
                        "queryId": "test_query_id"
                    },
                    "user": {
                        "user": "test_user",
                        "groups": ["some_group"],
                        "principal": "%s"
                    }
                }
                """, specialPrincipal);
        assertStringRequestsEqual(ImmutableSet.of(expectedRequest), mockClient.getRequests(), "/input");
    }

```
</issue_to_address>

### Comment 2
<location> `plugin/trino-opa/src/test/java/io/trino/plugin/opa/SerializableTestPrincipal.java:8-10` </location>
<code_context>
+
+import java.security.Principal;
+
+// A Principal for tests that can be serialized using Jackson
+@JsonSerialize
+public class SerializableTestPrincipal implements Principal {
+    private String name;
+
</code_context>

<issue_to_address>
**suggestion (testing):** Consider adding a test for serialization/deserialization of SerializableTestPrincipal.

Adding a unit test with Jackson will ensure SerializableTestPrincipal's serialization works as expected and prevent future regressions.

Suggested implementation:

```java
package io.trino.plugin.opa;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class SerializableTestPrincipalTest {

    @Test
    public void testSerializationDeserialization() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        SerializableTestPrincipal principal = new SerializableTestPrincipal("test-user");

        // Serialize to JSON
        String json = objectMapper.writeValueAsString(principal);

        // Deserialize from JSON
        SerializableTestPrincipal deserialized = objectMapper.readValue(json, SerializableTestPrincipal.class);

        // Assert that the name is preserved
        assertThat(deserialized.getName()).isEqualTo("test-user");
        assertThat(deserialized.getName()).isEqualTo(principal.getName());
    }
}

```

You may need to ensure that `SerializableTestPrincipal` has a public constructor accepting a `String name` and a public getter for `name` (e.g., `getName()`), as well as any necessary Jackson annotations for proper serialization/deserialization. If these are missing, add them to `SerializableTestPrincipal.java`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 8 to 23
// A Principal for tests that can be serialized using Jackson
@JsonSerialize
public class SerializableTestPrincipal implements Principal {
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Consider adding a test for serialization/deserialization of SerializableTestPrincipal.

Adding a unit test with Jackson will ensure SerializableTestPrincipal's serialization works as expected and prevent future regressions.

Suggested implementation:

package io.trino.plugin.opa;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class SerializableTestPrincipalTest {

    @Test
    public void testSerializationDeserialization() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        SerializableTestPrincipal principal = new SerializableTestPrincipal("test-user");

        // Serialize to JSON
        String json = objectMapper.writeValueAsString(principal);

        // Deserialize from JSON
        SerializableTestPrincipal deserialized = objectMapper.readValue(json, SerializableTestPrincipal.class);

        // Assert that the name is preserved
        assertThat(deserialized.getName()).isEqualTo("test-user");
        assertThat(deserialized.getName()).isEqualTo(principal.getName());
    }
}

You may need to ensure that SerializableTestPrincipal has a public constructor accepting a String name and a public getter for name (e.g., getName()), as well as any necessary Jackson annotations for proper serialization/deserialization. If these are missing, add them to SerializableTestPrincipal.java.

- Configure if permission management operations are allowed. Find more details in
[](opa-permission-management). Defaults to `false`.
* - `opa.include-user-principal`
- Whether to include the users principal when sending authorization requests to OPA. Defaults to `false`.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
- Whether to include the users principal when sending authorization requests to OPA. Defaults to `false`.
- Whether to include the user's principal when sending authorization requests to OPA. Defaults to `false`.

Copy link
Member

Choose a reason for hiding this comment

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

In addition I think this could use a few more details. What exactly is it it's sending? I guess it depends on the authentication method?

Copy link
Member Author

Choose a reason for hiding this comment

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

Picked the suggestion. Honestly, I don't know. I also assume it depends on the authentication method used. I'm no Java expert, this code only sees the java.security.Principal interface.

private final LifeCycleManager lifeCycleManager;
private final OpaHighLevelClient opaHighLevelClient;
private final boolean allowPermissionManagementOperations;
protected final boolean includeUserPrincipal;
Copy link
Member

Choose a reason for hiding this comment

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

Personally I'd prefer if this could be made private and the create an access method.

Copy link
Member Author

Choose a reason for hiding this comment

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

No opinion. Moved it behind this function

    protected boolean allowPermissionManagementOperations()
    {
        return this.allowPermissionManagementOperations;
    }

String user,
Set<String> groups)
Set<String> groups,
Optional<Principal> principal)
Copy link
Member

Choose a reason for hiding this comment

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

I checked how these are sent and it seems the OpaHttpClient serializes everything to JSON. Are we sure that all principals can be serialized properly?

I don't have a really good answer myself for how to test this to be honest.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, we only have the java.security.Principal interface here. In Rust I would simply add a trait bound on Serialize and the compiler would ensure all passed types can be serialized :P
This is the main reason this is opt-in, so only users that really need access to the principal in OPA need to make sure it's serializable.

It would be great to find out what possible concrete types the Trino source code passes to authorizers.

@sbernauer sbernauer force-pushed the feat/opa-send-user-principal branch from 70d3a96 to f2a7e3c Compare November 7, 2025 11:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

2 participants