Skip to content

[NAE-2118] Implement OpenID Connector Auth for Admin node #317

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

Open
wants to merge 6 commits into
base: release/7.0.0-rev4
Choose a base branch
from

Conversation

Retoocs
Copy link
Contributor

@Retoocs Retoocs commented Jun 16, 2025

Description

Optimized RealmServiceImpl.addProvider method and updated some logging.

Implements NAE-2118

Dependencies

No new dependencies were introduced

Third party dependencies

  • No new dependencies were introduced

Blocking Pull requests

There are no dependencies on other PR

How Has Been This Tested?

Manually

Test Configuration

Name Tested on
OS Ubuntu 24.04.1 LTS
Runtime Java 21
Dependency Manager Maven 3.6.3
Framework version Spring Boot 3.4.4
Run parameters
Other configuration

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • My changes have been checked, personally or remotely, with @...
  • I have commented my code, particularly in hard-to-understand areas
  • I have resolved all conflicts with the target branch of the PR
  • I have updated and synced my code with the target branch
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing tests pass locally with my changes:
    • Lint test
    • Unit tests
    • Integration tests
  • I have checked my contribution with code analysis tools:
  • I have made corresponding changes to the documentation:
    • Developer documentation
    • User Guides
    • Migration Guides

Summary by CodeRabbit

  • Bug Fixes

    • Improved log messages to display the correct realm identifier when searching for users.
  • Refactor

    • Simplified authentication provider management, resulting in updated behavior when adding providers to a realm.
    • Enhanced thread safety in provider registry operations.
  • Documentation

    • Added clarifying comments to provider registration methods.

Retoocs added 4 commits June 2, 2025 09:04
- change registry collection type in ProviderRegistry
- add doc for ProviderRegistry.registerProvider
- optimize RealmServiceImpl.addProvider
- remove unused AuthMethodProvider.createAuthMethod
@Retoocs Retoocs self-assigned this Jun 16, 2025
@Retoocs Retoocs added improvement A change that improves on an existing feature Extra Small labels Jun 16, 2025
Copy link

coderabbitai bot commented Jun 16, 2025

Walkthrough

The changes update authentication provider management by modifying the method signatures and return types for adding providers, removing the creation of AuthMethod instances, and instead returning updated Realm objects. Additional updates include improved logging, enhanced thread safety in provider registries, and removal of unused interface methods.

Changes

File(s) Change Summary
.../auth/service/RealmServiceImpl.java
.../auth/service/RealmService.java
Changed addProvider method signature and return type to return Realm instead of AuthMethod; removed generic type parameter for AuthMethod.
.../auth/provider/AuthMethodProvider.java Removed createAuthMethod method from interface and related import.
.../auth/provider/ProviderRegistry.java Switched internal maps to ConcurrentHashMap for thread safety; improved logging; added Javadoc to registerProvider.
.../auth/service/UserServiceImpl.java Updated log statements in findUserByUsername to use realmId instead of collection name.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RealmService
    participant ProviderRegistry
    participant RealmRepository

    Client->>RealmService: addProvider(realmId, config)
    RealmService->>ProviderRegistry: getProvider(config.type)
    ProviderRegistry-->>RealmService: provider
    RealmService->>RealmRepository: findById(realmId)
    RealmRepository-->>RealmService: realm
    RealmService->>Realm: addAuthMethodConfig(config)
    RealmService->>RealmRepository: save(realm)
    RealmRepository-->>RealmService: updatedRealm
    RealmService-->>Client: updatedRealm
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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

@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: 2

🧹 Nitpick comments (2)
nae-user-common/src/main/java/com/netgrif/application/engine/auth/provider/ProviderRegistry.java (1)

17-23: Minor Javadoc polish

Nit: the description sentences are missing a terminating period and start with a lowercase character. Tightening this keeps generated docs clean.

nae-user-ce/src/main/java/com/netgrif/application/engine/auth/service/UserServiceImpl.java (1)

132-135: Log level reconsideration

A missing user is currently logged with WARN. Given that look-ups for non-existent users can be part of normal control flow (e.g. login attempts), consider downgrading to DEBUG to avoid log noise and alert fatigue.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb581e3 and e4999c6.

📒 Files selected for processing (5)
  • nae-user-ce/src/main/java/com/netgrif/application/engine/auth/service/RealmServiceImpl.java (1 hunks)
  • nae-user-ce/src/main/java/com/netgrif/application/engine/auth/service/UserServiceImpl.java (1 hunks)
  • nae-user-common/src/main/java/com/netgrif/application/engine/auth/provider/AuthMethodProvider.java (0 hunks)
  • nae-user-common/src/main/java/com/netgrif/application/engine/auth/provider/ProviderRegistry.java (1 hunks)
  • nae-user-common/src/main/java/com/netgrif/application/engine/auth/service/RealmService.java (1 hunks)
💤 Files with no reviewable changes (1)
  • nae-user-common/src/main/java/com/netgrif/application/engine/auth/provider/AuthMethodProvider.java
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: task-list-completed
  • GitHub Check: task-list-completed
  • GitHub Check: task-list-completed
  • GitHub Check: task-list-completed
  • GitHub Check: task-list-completed
  • GitHub Check: Build
🔇 Additional comments (1)
nae-user-common/src/main/java/com/netgrif/application/engine/auth/service/RealmService.java (1)

35-35: Adjust downstream callers

The return type change from AuthMethod to Realm is a breaking API modification. Ensure every call-site (services, controllers, tests) has been updated; otherwise compilation errors or silent misbehaviour (ignored return value) will surface.

Comment on lines +13 to 16
protected final Map<String, Class<? extends AbstractAuthConfig>> configClasses = new ConcurrentHashMap<>();

protected final Map<String, AuthMethodProvider<?>> providers = new HashMap<>();
protected final Map<String, AuthMethodProvider<?>> providers = new ConcurrentHashMap<>();

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Locale-safe keys & duplicate-registration guard

type.toLowerCase() depends on the default JVM locale (e.g. Turkish “İ”), which may lead to subtle look-ups mismatches.
A ConcurrentHashMap already offers putIfAbsent; using it makes accidental double registration explicit.

-    protected final Map<String, Class<? extends AbstractAuthConfig>> configClasses = new ConcurrentHashMap<>();
-    protected final Map<String, AuthMethodProvider<?>> providers = new ConcurrentHashMap<>();
+    protected final ConcurrentMap<String, Class<? extends AbstractAuthConfig>> configClasses = new ConcurrentHashMap<>();
+    protected final ConcurrentMap<String, AuthMethodProvider<?>> providers = new ConcurrentHashMap<>();
-        providers.put(type.toLowerCase(), provider);
-        configClasses.put(type.toLowerCase(), provider.getConfigClass());
+        String key = type.toLowerCase(Locale.ROOT);
+        if (providers.putIfAbsent(key, provider) != null) {
+            log.warn("Provider for type [{}] was already registered – overriding", key);
+        }
+        configClasses.put(key, provider.getConfigClass());
📝 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
protected final Map<String, Class<? extends AbstractAuthConfig>> configClasses = new ConcurrentHashMap<>();
protected final Map<String, AuthMethodProvider<?>> providers = new HashMap<>();
protected final Map<String, AuthMethodProvider<?>> providers = new ConcurrentHashMap<>();
// switch from general Map to ConcurrentMap to expose atomic operations
protected final ConcurrentMap<String, Class<? extends AbstractAuthConfig>> configClasses = new ConcurrentHashMap<>();
protected final ConcurrentMap<String, AuthMethodProvider<?>> providers = new ConcurrentHashMap<>();
// … inside your registration method …
// use a locale-neutral lowercase key
String key = type.toLowerCase(Locale.ROOT);
// guard against double-registration
if (providers.putIfAbsent(key, provider) != null) {
log.warn("Provider for type [{}] was already registered – overriding", key);
}
// still update the configClass map
configClasses.put(key, provider.getConfigClass());
🤖 Prompt for AI Agents
In
nae-user-common/src/main/java/com/netgrif/application/engine/auth/provider/ProviderRegistry.java
around lines 13 to 16, avoid using type.toLowerCase() for keys to prevent
locale-dependent issues. Instead, normalize keys in a locale-safe way, such as
using Locale.ROOT with toLowerCase. Also, replace any manual checks for
duplicate registrations with the ConcurrentHashMap's putIfAbsent method to
explicitly handle and prevent accidental double registrations.

Comment on lines +101 to 110
public <C extends AbstractAuthConfig> Realm addProvider(String realmId, AuthMethodConfig<C> config) {
AuthMethodProvider<C> provider = (AuthMethodProvider<C>) providerRegistry.getProvider(config.getType());
if (provider == null) {
throw new IllegalArgumentException("Provider type " + config.getType() + " not found");
}

AuthMethod<C> authMethod = provider.createAuthMethod(config);
Realm realm = getRealmById(realmId).orElseThrow(() -> new IllegalArgumentException("Realm with id " + realmId + " not found"));
realm.addAuthMethod(config);
realmRepository.save(realm);

return (T) authMethod;
return realmRepository.save(realm);
}
Copy link

@coderabbitai coderabbitai bot Jun 16, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Unchecked cast & missing config-provider compatibility check

  1. AuthMethodProvider<C> cast is unchecked and the variable is not used any further – it can be safely dropped.
  2. Nothing verifies that the supplied config matches the provider’s expected configuration class; a typo in type would pass until runtime errors occur elsewhere.
-        AuthMethodProvider<C> provider = (AuthMethodProvider<C>) providerRegistry.getProvider(config.getType());
-        if (provider == null) {
-            throw new IllegalArgumentException("Provider type " + config.getType() + " not found");
-        }
+        AuthMethodProvider<?> provider = providerRegistry.getProvider(config.getType());
+        if (provider == null) {
+            throw new IllegalArgumentException("Provider type %s not found".formatted(config.getType()));
+        }
+        if (!provider.getConfigClass().isAssignableFrom(config.getClass())) {
+            throw new IllegalArgumentException("Config class %s is not compatible with provider %s"
+                    .formatted(config.getClass().getSimpleName(), config.getType()));
+        }

Also remove the now-unused AuthMethod import to avoid compiler warnings.

📝 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
public <C extends AbstractAuthConfig> Realm addProvider(String realmId, AuthMethodConfig<C> config) {
AuthMethodProvider<C> provider = (AuthMethodProvider<C>) providerRegistry.getProvider(config.getType());
if (provider == null) {
throw new IllegalArgumentException("Provider type " + config.getType() + " not found");
}
AuthMethod<C> authMethod = provider.createAuthMethod(config);
Realm realm = getRealmById(realmId).orElseThrow(() -> new IllegalArgumentException("Realm with id " + realmId + " not found"));
realm.addAuthMethod(config);
realmRepository.save(realm);
return (T) authMethod;
return realmRepository.save(realm);
}
public <C extends AbstractAuthConfig> Realm addProvider(String realmId, AuthMethodConfig<C> config) {
AuthMethodProvider<?> provider = providerRegistry.getProvider(config.getType());
if (provider == null) {
throw new IllegalArgumentException("Provider type %s not found"
.formatted(config.getType()));
}
if (!provider.getConfigClass().isAssignableFrom(config.getClass())) {
throw new IllegalArgumentException("Config class %s is not compatible with provider %s"
.formatted(config.getClass().getSimpleName(), config.getType()));
}
Realm realm = getRealmById(realmId)
.orElseThrow(() -> new IllegalArgumentException("Realm with id " + realmId + " not found"));
realm.addAuthMethod(config);
return realmRepository.save(realm);
}
🤖 Prompt for AI Agents
In
nae-user-ce/src/main/java/com/netgrif/application/engine/auth/service/RealmServiceImpl.java
around lines 101 to 110, remove the unchecked cast to AuthMethodProvider<C> and
the unused provider variable entirely. Instead, add a check to verify that the
config's class matches the expected configuration class for the provider type
before proceeding. If the types do not match, throw an IllegalArgumentException
with a clear message. Also, remove the unused AuthMethod import to prevent
compiler warnings.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Odpisujem ti po slovensky. Existuje predpoklad, ze ak najde provider cez config.getType() tak pre provider je automaticky splnena podmienka provider.getConfigClass().isAssignableFrom(config.getClass())

Copy link

Choose a reason for hiding this comment

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

@Retoocs Ďakujem za vysvetlenie! Máš pravdu - ak je systém navrhnutý tak, že provider registry garantuje kompatibilitu medzi config.getType() a príslušným providerom, tak dodatočná validácia isAssignableFrom je skutočne zbytočná.

V takom prípade by sa mohol kód zjednodušiť len odstránením nepoužitej premennej provider, keďže sa už nepoužíva po odstránení createAuthMethod volania:

@Override
public <C extends AbstractAuthConfig> Realm addProvider(String realmId, AuthMethodConfig<C> config) {
    if (providerRegistry.getProvider(config.getType()) == null) {
        throw new IllegalArgumentException("Provider type %s not found".formatted(config.getType()));
    }

    Realm realm = getRealmById(realmId)
            .orElseThrow(() -> new IllegalArgumentException("Realm with id " + realmId + " not found"));
    realm.addAuthMethod(config);
    return realmRepository.save(realm);
}

Toto by eliminovalo unchecked cast a zároveň zachovalo validáciu existencie providera.

(\   /)

( ^.^ )
o_(")(")
curious about the architecture


✏️ Learnings added
Learnt from: Retoocs
PR: netgrif/application-engine#317
File: nae-user-ce/src/main/java/com/netgrif/application/engine/auth/service/RealmServiceImpl.java:101-110
Timestamp: 2025-07-18T08:42:08.397Z
Learning: In the authentication provider system, when a provider is found via `config.getType()` through the provider registry, the condition `provider.getConfigClass().isAssignableFrom(config.getClass())` is automatically satisfied due to the system's design. The provider registry guarantees type compatibility between config types and their corresponding providers, making additional validation checks unnecessary.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@Retoocs Retoocs changed the base branch from release/7.0.0-rev3 to release/7.0.0-rev4 July 3, 2025 09:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Extra Small improvement A change that improves on an existing feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant