8000 Correct unique constraints for UserConsent entity by cgeorgilakis · Pull Request #14793 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content

Correct unique constraints for UserConsent entity - #14793

Merged
ahus1 merged 1 commit into
keycloak:mainfrom
eosc-kc:13045-unique-constraints
Mar 19, 2024
Merged

ahus1 merged 1 commit into
keycloak:mainfrom
eosc-kc:13045-unique-constraints

Conversation

@cgeorgilakis
Copy link
Copy Markdown
Contributor

Closes #13045

As we see in the following code (classJpaUserProvider , method addConsent) :

 if (clientStorageId.isLocal()) {
            consentEntity.setClientId(clientId);
        } else {
            consentEntity.setClientStorageProvider(clientStorageId.getProviderId());
            consentEntity.setExternalClientId(clientStorageId.getExternalId());
        }

Unique constraint in a database is not working if one - or more - field is null. So we propose to delete old one and create two appropriate unique constraints.
I also propose to delete the check in the method addConsent of class JpaUserProvider. This check must be done in database, no need for twice check.

@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

Adding unique indexes will be failed for Keycloak instances with already duplicate entries.
We have two possible solution for adding in liquibase before changing unique constraints:

  • Delete all duplicate consents
  • Delete newer consent for duplicate consents

What Keycloak team believe that we should do?

@svenseeberg
Copy link
Copy Markdown

What would happen during a migration if duplicate keys are present? Keycloak would fail to start?

@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

What would happen during a migration if duplicate keys are present? Keycloak would fail to start?

That's why I am asking Keycloak team for the way to solve possible duplicate entries problem:

We have two possible solution for adding in liquibase before changing unique constraints:

  • Delete all duplicate consents
  • Delete newer consent for duplicate consents

I believe the second is the ideal.

@sguilhen
sguilhen requested a review from hmlnarik April 5, 2023 20:49
@sguil
8000
hen
sguilhen commented Apr 5, 2023
Copy link
Copy Markdown
Contributor

@hmlnarik I've requested your review for this - the current constraint is not enough to prevent duplicate consents (see associated issue). The problem is that reworking the constraint as proposed here will cause migration failures for those who already have duplicate records in their DBs, so some previous action must be taken to eliminate duplicates before attempting to change the constraints.

@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

@hmlnarik I've requested your review for this - the current constraint is not enough to prevent duplicate consents (see associated issue). The problem is that reworking the constraint as proposed here will cause migration failures for those who already have duplicate records in their DBs, so some previous action must be taken to eliminate duplicates before attempting to change the constraints.

@sguilhen @hmlnarik any review progress for this bug?
I have already proposed a migration solution (only false duplicate entries in database will be changed).

@keycloak-github-bot keycloak-github-bot Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@keycloak-github-bot
Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.ui.account2.ReferrerTest#badClientUriTest

Keycloak CI - Account Console IT (chrome)

org.openqa.selenium.NoSuchElementException: 
no such element: Unable to locate element: {"method":"css selector","selector":"#username"}
  (Session info: chrome-headless-shell=121.0.6167.184)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
...

Report flaky test

@cgeorgilakis
cgeorgilakis force-pushed the 13045-unique-constraints branch from c6c8b19 to 0c34504 Compare February 27, 2024 09:22
@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

I have rebased in current main.

Moreover based on our discussion in github issue, during migration Keycloak will delete newer consent for duplicate consents.
MySQL is different database. So SQL script need to create temporary table and delete it after.
Oracle seems to work with current unique constraints. If I am not wrong, it is the only SQL database that checks null values in unique contraint. If you add new two unique constraints, tests will be failed in Oracle.
The code has been chacked with postegreSQL database with duplicate instances.
Could you review it now? @sguilhen?

@sguilhen
sguilhen requested a review from vramik March 11, 2024 12:21
@sguilhen sguilhen left a comment
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hi @cgeorgilakis. I've added a couple of points I think are worth revisiting. In addition, we need to ensure this change also works for Microsoft SQL Server.

I've also requested a review from @vramik to see if I'm not missing anything.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I am personally not in favor to remove this check, and the reason is that we have similar checks in many other providers. If we decide to go down this route of relying solely on the DB constraints it would call for a broader change in all the providers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I am personally not in favor to remove this check, and the reason is that we have similar checks in many other providers. If we decide to go down this route of relying solely on the DB constraints it would call for a broader change in all the providers.

I do not like double checks for the same thing. If you think that it is not a performance problem, I will add it back.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In Keycloak we have avoided the explicit SQL statements in the changesets, and instead we use custom changes like the one in this PR - for consistency I would use the same approach here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In Keycloak we have avoided the explicit SQL statements in the changesets, and instead we use custom changes like the one in this PR - for consistency I would use the same approach here.

Ok, I will check it and will make appropriate changes if possible.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I have migrate SQL statements to Java class extends CustomKeycloakTask.

@keycloak-github-bot
Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.ui.account2.ApplicationsTest#navigationTest

Keycloak CI - Account Console IT (chrome)

org.openqa.selenium.NoSuchElementException: 
no such element: Unable to locate element: {"method":"css selector","selector":"#username"}
  (Session info: chrome-headless-shell=122.0.6261.94)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
...

Report flaky test

org.keycloak.testsuite.webauthn.account.WebAuthnSigningInTest#createWebAuthnSameUserLabel

Keycloak CI - WebAuthn IT (chrome)

java.lang.AssertionError: Expected OIDCLogin but was  (https://localhost:8543/auth/realms/test/protocol/openid-connect/auth?client_id=account-console&redirect_uri=https%3A%2F%2Flocalhost%3A8543%2Fauth%2Frealms%2Ftest%2Faccount%2F%23%2Fsecurity%2Fsigningin&state=867860dc-0c7b-4663-8bb6-6af05eaeb227&response_mode=fragment&response_type=code&scope=openid&nonce=33b83b36-e3d8-494c-9959-016fb54a8119&code_challenge=2c-KR3JiJTGDzW6Nxx06rFynFZNl2OkHDoF0ZqS-0LM&code_challenge_method=S256)
	at org.junit.Assert.fail(Assert.java:89)
	at org.junit.Assert.assertTrue(Assert.java:42)
	at org.keycloak.testsuite.page.AbstractPage.assertCurrent(AbstractPage.java:109)
	at jdk.internal.reflect.GeneratedMethodAccessor639.invoke(Unknown Source)
...

Report flaky test

@keycloak-github-bot keycloak-github-bot Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

Hi @cgeorgilakis. I've added a couple of points I think are worth revisiting. In addition, we need to ensure this change also works for Microsoft SQL Server.

I've also requested a review from @vramik to see if I'm not missing anything.

Microsoft SQL Server seems to work as Oracle database supporting NULL values in unique constraints.
One the other hand, unique constraints in PostgreSQL, MariaDB, MySQL take into account only entries with not NULL values.

@keycloak-github-bot
Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.oauth.RefreshTokenTest#refreshTokenWithDifferentIssuer

Keycloak CI - Store IT (mariadb)

java.lang.RuntimeException: java.lang.RuntimeException: java.net.UnknownHostException: proxy.kc.127.0.0.1.nip.io: Temporary failure in name resolution
	at org.keycloak.testsuite.arquillian.undertow.lb.SimpleUndertowLoadBalancer.start(SimpleUndertowLoadBalancer.java:121)
	at org.keycloak.testsuite.oauth.RefreshTokenTest.refreshTokenWithDifferentIssuer(RefreshTokenTest.java:326)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
...
java.lang.RuntimeException: java.lang.RuntimeException: java.net.UnknownHostException: proxy.kc.127.0.0.1.nip.io
	at org.keycloak.testsuite.arquillian.undertow.lb.SimpleUndertowLoadBalancer.start(SimpleUndertowLoadBalancer.java:121)
	at org.keycloak.testsuite.oauth.RefreshTokenTest.refreshTokenWithDifferentIssuer(RefreshTokenTest.java:326)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
...

Report flaky test

@keycloak-github-bot keycloak-github-bot Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@vramik vramik left a comment
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@cgeorgilakis thank you for preparing the PR.

@sguilhen I went through it and the code seems good to me. I didn't test the solution locally with different databases.

I've spotted only a minor thing. New classes JpaUpdate25* don't contain copyright message.

@cgeorgilakis
cgeorgilakis force-pushed the 13045-unique-constraints branch 2 times, most recently from 8ce8809 to 3146d4b Compare March 15, 2024 10:44
@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

@cgeorgilakis thank you for preparing the PR.

@sguilhen I went through it and the code seems good to me. I didn't test the solution locally with different databases.

I've spotted only a minor thing. New classes JpaUpdate25* don't contain copyright message.

I have added them.

@cgeorgilakis
cgeorgilakis requested a review from vramik March 15, 2024 10:45
@sguilhen
Copy link
Copy Markdown
Contributor

@cgeorgilakis one final comment that might simplify the whole thing a little bit for your consideration. Instead of two separate custom changes, you can combine them in a single change and use the database from CustomKeycloakTask to differentiate the sql statements that have to be generated. Something like

    protected void generateStatementsImpl() throws CustomChangeException {
        if (super.database instanceof MariaDBDatabase || super.database instanceof PostgresDatabase) {
            generateStatementsPGMariaDB();
        } else if (super.database instanceof MySQLDatabase) {
            generateStatementsMySQL();
        }
    }
    
    protected void generateStatementsPGMariaDB() throws CustomChangeException {
        // PG / MariaDB statements go here
    }
    
    protected void generateStatementsMySQL() throws CustomChangeException {
        // MySQL statements go here
    }

Then the changeset can be adjusted to no longer have pre conditions that check the DB type, and instead simply call the custom change and then adjusts the index (drop current and add the two new indexes). WDYT?

@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

@cgeorgilakis one final comment that might simplify the whole thing a little bit for your consideration. Instead of two separate custom changes, you can combine them in a single change and use the database from CustomKeycloakTask to differentiate the sql statements that have to be generated. Something like

    protected void generateStatementsImpl() throws CustomChangeException {
        if (super.database instanceof MariaDBDatabase || super.database instanceof PostgresDatabase) {
            generateStatementsPGMariaDB();
        } else if (super.database instanceof MySQLDatabase) {
            generateStatementsMySQL();
        }
    }
    
    protected void generateStatementsPGMariaDB() throws CustomChangeException {
        // PG / MariaDB statements go here
    }
    
    protected void generateStatementsMySQL() throws CustomChangeException {
        // MySQL statements go here
    }

Then the changeset can be adjusted to no longer have pre conditions that check the DB type, and instead simply call the custom change and then adjusts the index (drop current and add the two new indexes). WDYT?

The problem with this is that no changes are needed for Microsoft SQL Server and Oracle. So, add/ drop unique Constraint need to be in JpaUpdate25_0_0_ConsentConstraints . Is this change needed?

@sguilhen
Copy link
Copy Markdown
Contributor

The problem with this is that no changes are needed for Microsoft SQL Server and Oracle. So, add/ drop unique Constraint need to be in JpaUpdate25_0_0_ConsentConstraints . Is this change needed?

Good point. Lets leave it as is then.

@ahus1 The PR looks good to me, @vramik also reviewed. If you could take one final look/merge it would be great.

@ahus1
ahus1 commented Mar 18, 2024
Copy link
Copy Markdown
Member

Unfortunately there are now conflicts for the JPA changelog, please resolve them.

Something I worry about a bit: when creating the SQL statements, I am not sure if they contain a schema name, which might be used for MySQL databases. Please double-check. If you think we are fine, I'm ok to go ahead and merge.

@vramik
vramik commented Mar 18, 2024
Copy link
Copy Markdown
Contributor

@ahus1 thank you for looking into it. As far as I'm aware there is schema correctly handled within

public static String getTable(String table, String defaultSchema) {
return defaultSchema != null ? defaultSchema + "." + table : table;
}

which is called from

return LiquibaseJpaUpdaterProvider.getTable(tableName, correctedSchemaName);

Does that address your concern?

@ahus1
ahus1 commented Mar 18, 2024
Copy link
Copy Markdown
Member

@vramik - thank you, yes, this resolves it for me.

Closes keycloak#13045

Signed-off-by: cgeorgilakis-grnet <cgeorgilakis@admin.grnet.gr>
@cgeorgilakis
cgeorgilakis force-pushed the 13045-unique-constraints branch from 3146d4b to c662402 Compare March 19, 2024 08:20
@cgeorgilakis
Copy link
Copy Markdown
Contributor Author

Unfortunately there are now conflicts for the JPA changelog, please resolve them.

Something I worry about a bit: when creating the SQL statements, I am not sure if they contain a schema name, which might be used for MySQL databases. Please double-check. If you think we are fine, I'm ok to go ahead and merge.

@ahus1 I have resolved them (have rebased PR).

@ahus1 ahus1 left a comment
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving based on @sguilhen's previous review. Thanks!

@ahus1 ahus1 self-assigned this Mar 19, 2024
@ahus1
ahus1 enabled auto-merge (rebase) March 19, 2024 08:35
@ahus1
ahus1 merged commit 4bca804 into keycloak:main Mar 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Duplicated user consents

5 participants

0