GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [Stability] Type identity second-factor boundary by Storypapst · Pull Request #882 · OpenResilienceInitiative/ORISO-UserService

Conversation

@Storypapst

@Storypapst Storypapst commented Jul 28, 2026 •
edited by coderabbitai Bot
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Collaborator

Summary

  • introduce the focused, provider-neutral IdentitySecondFactor output port for OTP credential management and email verification
  • keep generated Keycloak DTOs and string-keyed transport maps inside the Keycloak adapter
  • record bounded retries with five fixed low-cardinality operation tags and no user data
  • preserve the existing public API, schemas, configuration, username behavior, and provider-call count
  • add executable architecture, mapping, retry, controller, integration-context, and application tests

Current-state correction

This replacement now contains current pre-dev at 0ea5ba3206ad3a59c8a91e09d8b3d626ded438f4 and only the #793 scope on top. The former documentation-only merge conflict is resolved from fresh suite evidence; no production conflict remained.

The product target remains Matrix-only: the ORISO-owned frontend with the ORISO-controlled Element Call/MatrixRTC fork and LiveKit. Rocket.Chat and Jitsi are not supported runtime paths or fallbacks.

Behavior and measurements

Each of the five second-factor operations performs exactly one provider request on the normal path. An initial unauthorized response can cause at most one token refresh and one repeated provider request, for a maximum of two attempts:

  • otp-fetch
  • otp-setup
  • otp-delete
  • email-verification-start
  • email-verification-finish

The encoded username crosses the application/focused-port boundary unchanged. Provider-specific decoding remains adapter-owned, and the verified email mutation continues to use the decoded username. This refactor deliberately does not reduce calls; it makes ownership, retry bounds, and measurements explicit before later optimization.

Fresh verification on the merged head

  • 3,439 unit tests; 0 failures, 0 errors, 0 skipped
  • 852 integration, contract, and E2E tests across 83 reports; 0 failures, 0 errors, 9 environment-gated skips
  • 51 Python CI and architecture contract tests
  • 8 OpenAPI contract gate tests
  • focused second-factor suite: 183 Java tests
  • Java 21 package and Spotless checks
  • clean diff and direct current pre-dev ancestry

No local database reset was needed.

Delivery truth

Exact head ceee0d87b1b71708a0240d104b952f414df567ba is pushed. Local verification and all exact-head GitHub checks are complete, including required integration, MariaDB, Redis, OpenAPI, package/Docker validation, and the aggregate required PreDev CI gate. This PR is not merged or deployed, and no PreDev runtime claim is made.

Closes #793
Supersedes #794

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added structured results for OTP setup, verification, and credential retrieval.
    • Added support for email- and app-based OTP credential types.
    • Preserved encoded usernames during two-factor authentication operations.
    • Added operation-specific retry tracking for authentication provider requests.
  • Documentation

    • Documented retry limits, metric labels, username handling, and verification guarantees.
  • Tests

    • Expanded coverage for OTP mapping, verification outcomes, retries, and encoded usernames.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@Storypapst @claude
refactor(identity): type second-factor boundary (#793)
eae00bd
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@shazia-k, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 50 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 47cb4b0f-add9-4c4a-bb13-f834876ce7e6

📥 Commits

Reviewing files that changed from the base of the PR and between 89849fb and 8d6742d.

📒 Files selected for processing (4)
  • src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakMapper.java
  • src/main/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingService.java
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java
  • src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java
📝 Walkthrough

Walkthrough

The change isolates OTP and email-verification operations behind IdentitySecondFactor. It replaces generic results and provider DTOs with typed identity models, adds operation-specific retry metrics, preserves encoded usernames, and updates consumers, documentation, and tests.

Changes

Identity second-factor boundary

Layer / File(s) Summary
Typed contracts and manager wiring
src/main/java/de/caritas/cob/userservice/api/identity/*, src/main/java/de/caritas/cob/userservice/api/port/*, src/main/java/de/caritas/cob/userservice/api/IdentityManager.java
Adds typed OTP and email-verification models. Moves second-factor methods from IdentityClient to IdentitySecondFactor.
Keycloak mapping and retry handling
src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/*, src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/*
Maps provider responses to typed results and records bounded retries with operation-specific labels.
Application and web consumers
src/main/java/de/caritas/cob/userservice/api/adapters/web/*, src/main/java/de/caritas/cob/userservice/api/service/*, src/test/java/de/caritas/cob/userservice/api/adapters/web/*, src/test/java/de/caritas/cob/userservice/api/service/*
Updates OTP setup, validation, retrieval, onboarding, handshake checks, and DTO mapping to use the new port and models.
Boundary documentation and integration wiring
documentation/USER_SERVICE_STABILITY.md, src/test/java/de/caritas/cob/userservice/api/*IT.java
Documents call limits, retry tags, encoded usernames, and verification status. Updates mocked identity clients to expose IdentitySecondFactor.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant UserTwoFactorAuthControllerDelegate
  participant IdentityManager
  participant KeycloakService
  participant KeycloakMapper
  User->>UserTwoFactorAuthControllerDelegate: submit OTP operation
  UserTwoFactorAuthControllerDelegate->>IdentityManager: invoke typed second-factor method
  IdentityManager->>KeycloakService: call IdentitySecondFactor
  KeycloakService->>KeycloakMapper: map provider response
  KeycloakMapper-->>KeycloakService: return typed identity result
  KeycloakService-->>IdentityManager: return typed result
  IdentityManager-->>UserTwoFactorAuthControllerDelegate: return verification status
  UserTwoFactorAuthControllerDelegate-->>User: return success or retry response
Loading

Possibly related PRs

  • OpenResilienceInitiative/ORISO-UserService#502: Both changes update HandshakeService and its OTP dependency.
  • OpenResilienceInitiative/ORISO-UserService#728: Both changes cover IdentityManager email/OTP flows and encoded usernames.
  • OpenResilienceInitiative/ORISO-UserService#753: Both changes introduce provider-neutral identity ports and result types.

Suggested labels: coderabbit

Suggested reviewers: hassan9215, shanzaeimran, shazia-k

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive The code objectives align with issue #793, but boundary-contract coverage cannot be verified because tests/ci/test_module_boundaries.py was excluded by path filters. Include the excluded module-boundary test evidence or provide its results before merge.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise, descriptive, and identifies the Stability area and identity second-factor boundary change.
Out of Scope Changes check ✅ Passed The changes remain within issue #793, including the focused port, typed values, adapter migration, consumer updates, retry metrics, documentation, and related tests.
Validation Evidence ✅ Passed Behavior changes include 16 relevant Java test files, including mapper, service, controller, boundary, retry, and encoded-username tests; the PR reports 3,439 unit and 852 integration tests with ze...
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch replay/identity-second-factor-793

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
  • X
  • Mastodon
  • Reddit
  • LinkedIn

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

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Jul 28, 2026
Type and isolate identity second-factor verification #793
Closed
[Stability] Type identity second-factor boundary #794
Closed
@Storypapst
Storypapst marked this pull request as ready for review July 28, 2026 11:56
@Storypapst
Storypapst requested review from Hassan9215, shanzaeimran and shazia-k July 28, 2026 11:56
@cursor

cursor Bot commented Jul 28, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Jul 28, 2026
[Feature Request] Stage the UserService refactor integration (#887) #888
Closed
Make UserService safe when two instances overlap (finish the remaining replica-safety work) #887
Open
Storypapst added a commit that referenced this pull request Jul 28, 2026
@Storypapst @claude
Merge PR #882: type identity second-factor boundary
c4bc75b
Compose the focused second-factor port with the existing authentication, email-owner, role-read, and username-availability seams on the integration branch. Preserve the original delivery commit and keep the combined branch review-only.

Refs #887

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Storypapst @claude
Merge current pre-dev into second-factor boundary
ceee0d8
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Storypapst Storypapst self-assigned this Jul 29, 2026
This was referenced Jul 29, 2026
[Bug]: US-H02 Build ignores test failures completely (testFailureIgnore=true, skipTests) #111
Closed
Stabilize UserService non-blocking CI gates #335
Closed
shazia-k added 3 commits August 7, 2026 11:28
@shazia-k
merge: reconcile PR #882 with pre-dev identity port split
95c80c7
Integrate the focused IdentitySecondFactor port with pre-dev's identity port
split: add IdentitySecondFactor to KeycloakService's implements list and to the
shared @MockitoBean(extraInterfaces = {...}) IdentityClient mocks in every
Spring identity test (replacing the PR's single-item extraInterfaces variant,
which would collide with the same underlying keycloakService bean). Drop the
five OTP methods from IdentityClient (per PR intent) and take pre-dev's
narrowed contract as the base. Preserve pre-dev's dynamically-computed test
count wording in USER_SERVICE_STABILITY.md and fold the second-factor
description into pre-dev's Identity/profile row. Insert the second-factor
boundary test method into pre-dev's larger test_module_boundaries.py.
@shazia-k
fix: migrate pre-dev OTP call sites to IdentitySecondFactor port
89849fb
HandshakeService and TenantAdminOnboardingService (introduced on pre-dev after
PR #882's baseline) still called IdentityClient.getOtpCredential and
IdentityClient.setUpOtpCredential. Those methods no longer exist on
IdentityClient — they moved to the focused IdentitySecondFactor port in this
PR. Inject IdentitySecondFactor into both services, switch the calls, and
migrate the corresponding tests to stub the focused port with typed
IdentityOtpCredential values.
@shazia-k
style: fix spotless formatting in second-factor migration
8d6742d
- Remove unused java.util.Map import from KeycloakMapper (dropped when the
  string-keyed mapOf methods became typed identityEmailVerificationOf).
- Reorder IdentityOtpCredential import in TenantAdminOnboardingServiceTest so
  identity.* precedes model.* alphabetically.
- Collapse a two-line return statement in TenantAdminOnboardingService that
  now fits on one line after switching to IdentityOtpCredential.secret().
- Collapse the wrapped IdentitySecondFactor @mock declaration onto one line
  to match the neighbouring one-line @mock fields in HandshakeServiceTest.
coderabbitai[bot]
coderabbitai Bot requested changes Aug 7, 2026
View reviewed changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java (1)

173-182: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Verify that the fail-closed gate stops OTP verification.

The test verifies only that no session is saved. If execution continues after the OTP lookup fails, the unstubbed keycloakAuthClient.verifyWithOtp(...) returns false and the test still passes. Add verify(keycloakAuthClient, never()).verifyWithOtp(...).

As per path instructions, assertions must be able to fail.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java`
around lines 173 - 182, Strengthen
initiate_Should_Forbid_When_SupportAdminOtpStateIsUnavailable by verifying that
keycloakAuthClient.verifyWithOtp(...) is never invoked when
identitySecondFactor.getOtpCredential(...) throws. Keep the existing
ForbiddenException and handshakeSessionRepository.save(...) assertions.

Source: Path instructions

src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegateTest.java (1)

88-110: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Keep the encoded-username contract executable in all second-factor tests.

The tests either make the transcoder return the raw username or use anyString(). A regression that removes username encoding, or forwards the wrong setup arguments, can therefore pass.

  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegateTest.java#L88-L110: return a distinct encoded username and verify the exact IdentityManager.getOtpCredential(...) argument.
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegateTest.java#L395-L407: use a distinct encoded username instead of returning USERNAME from the transcoder.
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java#L260-L261: match and verify the encoded admin username.
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java#L306-L307: match and verify the encoded admin username.
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java#L357-L358: match and verify the encoded admin username.
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java#L513-L514: match and verify the encoded admin username.
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java#L582-L583: match the encoded username, initial code, and pending secret exactly.
  • src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java#L65-L70: use an exact encoded support-admin username.
  • src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java#L144-L147: use an exact encoded support-admin username.

As per path instructions, tests must be able to fail; flag over-mocking that hides the defect and assertions that cannot break.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegateTest.java`
around lines 88 - 110, Make all second-factor tests enforce the encoded-username
contract rather than allowing raw or arbitrary values. In
UserAccountControllerDelegateTest.java ranges 88-110 and 395-407, configure a
distinct encoded username and verify the exact argument passed to
IdentityManager.getOtpCredential(...); in TenantAdminOnboardingServiceTest.java
ranges 260-261, 306-307, 357-358, 513-514, and 582-583, match and verify the
exact encoded admin username, including initial code and pending secret at
582-583; in HandshakeServiceTest.java ranges 65-70 and 144-147, use exact
encoded support-admin usernames. Remove anyString() or equivalent over-mocking
so each assertion can fail if encoding or setup arguments are incorrect.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java`:
- Around line 275-289: The initiateEmailVerification method must stop exposing
RestClientException.getMessage() and return a stable sanitized application
failure message instead. Update KeycloakService.java lines 275-289 accordingly,
and update KeycloakServiceTest.java lines 1434-1443 to assert the stable message
rather than provider error text.

In
`@src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserTwoFactorAuthControllerDelegate.java`:
- Around line 57-62: In the validationResult.created() branch of
UserTwoFactorAuthControllerDelegate, retain the Optional returned by
accountManager.patchUser(...) and call markTwoFactorActive only when the patch
succeeds; return an appropriate failure response when it is empty instead of
204. Add recovery or an idempotent retry strategy for failures between the patch
and markTwoFactorActive operations, and add a regression test proving
Optional.empty() does not activate 2FA.

In
`@src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakMapperTest.java`:
- Around line 39-47: Add a separate HttpStatus.OK case to
KeycloakMapperTest.identityEmailVerificationOfMapsCreatedResponse using
SuccessWithEmail, and assert the mapped IdentityEmailVerification has
created=false, createdBefore=true, attemptsLeft=false. Keep the existing
HttpStatus.CREATED mapping test unchanged.

In
`@src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java`:
- Around line 312-324: Extend
getOtpCredential_Should_Return_Response_When_RequestWasSuccessful with an OK
ResponseEntity whose body is null, then assert keycloakService.getOtpCredential
returns IdentityOtpCredential.empty() and verify keycloakMapper is not invoked.
Keep the existing successful non-null response assertions intact.

In `@src/test/java/de/caritas/cob/userservice/api/IdentityManagerTest.java`:
- Around line 52-74: The existing tests only cover created email-verification
results; add a test for validateOneTimePassword where finishEmailVerification
returns an IdentityEmailVerification with created == false, then verify
identityClient.changeEmailAddress is never called while preserving the existing
successful cases.

---

Outside diff comments:
In
`@src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegateTest.java`:
- Around line 88-110: Make all second-factor tests enforce the encoded-username
contract rather than allowing raw or arbitrary values. In
UserAccountControllerDelegateTest.java ranges 88-110 and 395-407, configure a
distinct encoded username and verify the exact argument passed to
IdentityManager.getOtpCredential(...); in TenantAdminOnboardingServiceTest.java
ranges 260-261, 306-307, 357-358, 513-514, and 582-583, match and verify the
exact encoded admin username, including initial code and pending secret at
582-583; in HandshakeServiceTest.java ranges 65-70 and 144-147, use exact
encoded support-admin usernames. Remove anyString() or equivalent over-mocking
so each assertion can fail if encoding or setup arguments are incorrect.

In
`@src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java`:
- Around line 173-182: Strengthen
initiate_Should_Forbid_When_SupportAdminOtpStateIsUnavailable by verifying that
keycloakAuthClient.verifyWithOtp(...) is never invoked when
identitySecondFactor.getOtpCredential(...) throws. Keep the existing
ForbiddenException and handshakeSessionRepository.save(...) assertions.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5714173a-ad54-4646-a9fe-0170c25341a0

📥 Commits

Reviewing files that changed from the base of the PR and between 6c62faf and 89849fb.

⛔ Files ignored due to path filters (1)
  • tests/ci/test_module_boundaries.py is excluded by none and included by none
📒 Files selected for processing (32)
  • documentation/USER_SERVICE_STABILITY.md
  • src/main/java/de/caritas/cob/userservice/api/IdentityManager.java
  • src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakMapper.java
  • src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java
  • src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegate.java
  • src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserTwoFactorAuthControllerDelegate.java
  • src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/UserDtoMapper.java
  • src/main/java/de/caritas/cob/userservice/api/identity/IdentityEmailVerification.java
  • src/main/java/de/caritas/cob/userservice/api/identity/IdentityEmailVerificationStart.java
  • src/main/java/de/caritas/cob/userservice/api/identity/IdentityOtpCredential.java
  • src/main/java/de/caritas/cob/userservice/api/identity/IdentityOtpType.java
  • src/main/java/de/caritas/cob/userservice/api/port/in/IdentityManaging.java
  • src/main/java/de/caritas/cob/userservice/api/port/out/IdentityClient.java
  • src/main/java/de/caritas/cob/userservice/api/port/out/IdentitySecondFactor.java
  • src/main/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingService.java
  • src/main/java/de/caritas/cob/userservice/api/service/handshake/HandshakeService.java
  • src/test/java/de/caritas/cob/userservice/api/IdentityManagerTest.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakMapperTest.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAccountControllerDelegateTest.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerMultiTenancyTrueE2EIT.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerAuthorizationIT.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserTwoFactorAuthControllerDelegateTest.java
  • src/test/java/de/caritas/cob/userservice/api/adapters/web/mapping/UserDtoMapperTest.java
  • src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java
  • src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/UpdateAdminServiceIT.java
  • src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java
  • src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceBase.java
  • src/test/java/de/caritas/cob/userservice/api/service/accountinvite/onboarding/TenantAdminOnboardingServiceTest.java
  • src/test/java/de/caritas/cob/userservice/api/service/handshake/HandshakeServiceTest.java
💤 Files with no reviewable changes (1)
  • src/main/java/de/caritas/cob/userservice/api/port/out/IdentityClient.java

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java
Comment on lines +275 to 289
public IdentityEmailVerificationStart initiateEmailVerification(String username, String email) {
var otpSetupDTO = keycloakMapper.otpSetupDtoOf(null, null, email);
var requestUrl = getOtpUrl(ENDPOINT_OTP_VERIFY_EMAIL, username);

try {
withFreshAdminTokenOnUnauthorized(
"email-verification-start",
() ->
keycloakClient.putForEntity(
keycloakClient.getBearerToken(), requestUrl, otpSetupDTO, Success.class));
return Optional.empty();
return IdentityEmailVerificationStart.success();
} catch (RestClientException exception) {
return Optional.of("Keycloak answered: " + exception.getMessage());
return IdentityEmailVerificationStart.failure(
"Identity provider answered: " + exception.getMessage());
}

@coderabbitai coderabbitai Bot Aug 7, 2026

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Remove raw provider error propagation from email-verification initiation.

RestClientException.getMessage() can contain request and provider details. The request URL includes the decoded username. Return a stable application message and update the test.

  • src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java#L275-L289: replace the provider exception message with a stable public failure message.
  • src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java#L1434-L1443: assert the stable sanitized message instead of provider error text.
📍 Affects 2 files
  • src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java#L275-L289 (this comment)
  • src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java#L1434-L1443
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java`
around lines 275 - 289, The initiateEmailVerification method must stop exposing
RestClientException.getMessage() and return a stable sanitized application
failure message instead. Update KeycloakService.java lines 275-289 accordingly,
and update KeycloakServiceTest.java lines 1434-1443 to assert the stable message
rather than provider error text.

Source: Path instructions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread ...caritas/cob/userservice/api/adapters/web/controller/UserTwoFactorAuthControllerDelegate.java
Comment on lines +57 to 62
if (validationResult.created()) {
var patchMap = userDtoMapper.mapOf(validationResult.email(), authenticatedUser);
accountManager.patchUser(patchMap);
accountInviteService.markTwoFactorActive(authenticatedUser.getUserId());
return ResponseEntity.noContent().build();
}

@coderabbitai coderabbitai Bot Aug 7, 2026

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Do not activate 2FA after an unsuccessful email patch.

AccountManaging.patchUser(...) returns Optional<Map<String, Object>>, but this result is discarded. If it returns Optional.empty(), the code still calls markTwoFactorActive(...) and returns 204. The email state and local 2FA state can then become inconsistent.

Check the patch result before activating 2FA. Because the patch and local state transition are separate operations, also define recovery or idempotent retry for a failure between them. Add a regression test for Optional.empty() and verify that markTwoFactorActive(...) is not called.

Suggested guard
-      accountManager.patchUser(patchMap);
+      var patchResponse = accountManager.patchUser(patchMap);
+      if (patchResponse.isEmpty()) {
+        throw new NotFoundException("Authenticated user was not found");
+      }
       accountInviteService.markTwoFactorActive(authenticatedUser.getUserId());

As per path instructions, this main flow must handle missing transaction boundaries and external-call failures.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserTwoFactorAuthControllerDelegate.java`
around lines 57 - 62, In the validationResult.created() branch of
UserTwoFactorAuthControllerDelegate, retain the Optional returned by
accountManager.patchUser(...) and call markTwoFactorActive only when the patch
succeeds; return an appropriate failure response when it is empty instead of
204. Add recovery or an idempotent retry strategy for failures between the patch
and markTwoFactorActive operations, and add a regression test proving
Optional.empty() does not activate 2FA.

Source: Path instructions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakMapperTest.java
Comment on lines +39 to +47
@Test
void identityEmailVerificationOfMapsCreatedResponse() {
var response =
new ResponseEntity<>(
new SuccessWithEmail().email("[email protected]"), HttpStatus.CREATED);

assertThat(mapper.identityEmailVerificationOf(response))
.isEqualTo(new IdentityEmailVerification(true, false, false, "[email protected]"));
}

@coderabbitai coderabbitai Bot Aug 7, 2026

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Test the HttpStatus.OK mapping.

Add a SuccessWithEmail response with HttpStatus.OK. Assert created == false, createdBefore == true, and attemptsLeft == false. The controller uses this result to return PRECONDITION_FAILED.

As per path instructions, tests must cover missing edge cases.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakMapperTest.java`
around lines 39 - 47, Add a separate HttpStatus.OK case to
KeycloakMapperTest.identityEmailVerificationOfMapsCreatedResponse using
SuccessWithEmail, and assert the mapped IdentityEmailVerification has
created=false, createdBefore=true, attemptsLeft=false. Keep the existing
HttpStatus.CREATED mapping test unchanged.

Source: Path instructions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java
Comment on lines 312 to 324
public void getOtpCredential_Should_Return_Response_When_RequestWasSuccessful() {
var outboundHttpMetrics = mock(OutboundHttpMetrics.class);
keycloakService.setOutboundHttpMetrics(outboundHttpMetrics);
var credential = new IdentityOtpCredential(true, "secret", "QrCode", IdentityOtpType.APP);
when(keycloakClient.getBearerToken()).thenReturn(BEARER_TOKEN);
var entity = new ResponseEntity(OTP_INFO_DTO, HttpStatus.OK);
when(this.keycloakClient.get(anyString(), any(), any())).thenReturn(entity);
when(keycloakMapper.identityOtpCredentialOf(OTP_INFO_DTO)).thenReturn(credential);

assertEquals(OTP_INFO_DTO, keycloakService.getOtpCredential(USERNAME));
assertEquals(credential, keycloakService.getOtpCredential(USERNAME));

verify(keycloakClient).get(anyString(), any(), eq(OtpInfoDTO.class));
verifyNoInteractions(outboundHttpMetrics);

@coderabbitai coderabbitai Bot Aug 7, 2026

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Test the empty OTP response body.

Add a response with HttpStatus.OK and a null body. Assert that getOtpCredential returns IdentityOtpCredential.empty() and does not invoke keycloakMapper. This covers the new fallback branch.

As per path instructions, tests must cover missing edge cases.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java`
around lines 312 - 324, Extend
getOtpCredential_Should_Return_Response_When_RequestWasSuccessful with an OK
ResponseEntity whose body is null, then assert keycloakService.getOtpCredential
returns IdentityOtpCredential.empty() and verify keycloakMapper is not invoked.
Keep the existing successful non-null response assertions intact.

Source: Path instructions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/test/java/de/caritas/cob/userservice/api/IdentityManagerTest.java
Comment on lines 52 to 74
void validateOneTimePasswordShouldUseRawUsernameForKeycloakEmailUpdate() {
var encodedUsername = usernameTranscoder.encodeUsername(RAW_USERNAME);
var validationResult = Map.of("created", "true", "email", EMAIL);
when(identityClient.finishEmailVerification(encodedUsername, "123456"))
var validationResult = new IdentityEmailVerification(true, false, false, EMAIL);
when(identitySecondFactor.finishEmailVerification(encodedUsername, "123456"))
.thenReturn(validationResult);

assertThat(identityManager.validateOneTimePassword(encodedUsername, "123456"))
.isEqualTo(validationResult);

verify(identityClient).finishEmailVerification(encodedUsername, "123456");
verify(identitySecondFactor).finishEmailVerification(encodedUsername, "123456");
verify(identityClient).changeEmailAddress(RAW_USERNAME, EMAIL);
}

@Test
void validateOneTimePasswordShouldKeepAlreadyRawUsernameForKeycloakEmailUpdate() {
var validationResult = Map.of("created", "true", "email", EMAIL);
when(identityClient.finishEmailVerification(RAW_USERNAME, "123456"))
var validationResult = new IdentityEmailVerification(true, false, false, EMAIL);
when(identitySecondFactor.finishEmailVerification(RAW_USERNAME, "123456"))
.thenReturn(validationResult);

identityManager.validateOneTimePassword(RAW_USERNAME, "123456");

verify(identityClient).changeEmailAddress(RAW_USERNAME, EMAIL);
}

@coderabbitai coderabbitai Bot Aug 7, 2026

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Test the non-created email-verification result.

Add a test where finishEmailVerification returns created == false. Verify that identityClient.changeEmailAddress is never called. This protects the email-update boundary from invalid or already-created OTP results.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/test/java/de/caritas/cob/userservice/api/IdentityManagerTest.java` around
lines 52 - 74, The existing tests only cover created email-verification results;
add a test for validateOneTimePassword where finishEmailVerification returns an
IdentityEmailVerification with created == false, then verify
identityClient.changeEmailAddress is never called while preserving the existing
successful cases.

Source: Path instructions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
shazia-k
shazia-k approved these changes Aug 7, 2026
View reviewed changes
@shazia-k
shazia-k merged commit dbd7e95 into pre-dev Aug 7, 2026
12 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@shazia-k
shazia-k deleted the replay/identity-second-factor-793 branch August 7, 2026 06:53
@coderabbitai coderabbitai Bot mentioned this pull request Aug 7, 2026
[Stability] Focus identity email address mutations #885
Merged
This was referenced Aug 15, 2026
fix: write onboarding invite fields into a re-read row, never a stale snapshot #1030
Merged
[Stability] Route user identity policy through input port (replay of #778) #1037
Merged
DPA_SIGNED_NOTICE and the onboarding-wizard DPA forward path #1031
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@coderabbitai coderabbitai[bot] coderabbitai[bot] requested changes
@shazia-k shazia-k shazia-k approved these changes
@Hassan9215 Hassan9215 Awaiting requested review from Hassan9215
@shanzaeimran shanzaeimran Awaiting requested review from shanzaeimran

Uh oh!

There was an error while loading. Please reload this page.

Assignees

@Storypapst Storypapst

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@Storypapst @shazia-k
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.