Skip to content

[PM-40870] fido2 v4 model migration - #7941

Closed
ike-kottlowski wants to merge 45 commits into
renovate/fido2.aspnet-4.xfrom
auth/renovate/fido2-v4-migration
Closed

ike-kottlowski wants to merge 45 commits into
renovate/fido2.aspnet-4.xfrom
auth/renovate/fido2-v4-migration

Conversation

@ike-kottlowski

@ike-kottlowski ike-kottlowski commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

🎟️ Tracking

🟥 Blocking Client PR: bitwarden/clients#22006

this client PR needs to be merged prior to this one.

JIRA: https://bitwarden.atlassian.net/browse/PM-40870

Parent Ticket: https://bitwarden.atlassian.net/browse/PM-25806

📔 Objective

Modifications need to be made to the surfer project in order to be compliant with the V4 upgrade of the FIDO 2 library. Before the changes were made integration tests and unit tests were generated to verify functionality after classes were modified.

Out of scope modifications include using the FakeWebAuthnAuthenticator to complete the attestation flow which before used mocks. Now it uses or robust fake which then forces the Fido 2 library to actually execute instead of justice returning a mock. This gives us better end to end testing of this feature.

📸 Screenshots

@ike-kottlowski
ike-kottlowski requested a review from enmande July 8, 2026 11:57
@codecov

codecov Bot commented Jul 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.50000% with 18 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (renovate/fido2.aspnet-4.x@bd3b91d). Learn more about missing BASE report.

Files with missing lines Patch % Lines
...h/Identity/TokenProviders/WebAuthnTokenProvider.cs 0.00% 17 Missing ⚠️
...ns/CompleteTwoFactorWebAuthnRegistrationCommand.cs 93.33% 1 Missing ⚠️
Additional details and impacted files
@@                     Coverage Diff                      @@
##             renovate/fido2.aspnet-4.x    #7941   +/-   ##
============================================================
  Coverage                             ?   59.88%           
============================================================
  Files                                ?     2121           
  Lines                                ?    93581           
  Branches                             ?     8298           
============================================================
  Hits                                 ?    56039           
  Misses                               ?    35564           
  Partials                             ?     1978           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@renovate
renovate Bot force-pushed the renovate/fido2.aspnet-4.x branch from bd3b91d to 0928ee7 Compare July 12, 2026 15:00
@renovate
renovate Bot force-pushed the renovate/fido2.aspnet-4.x branch 2 times, most recently from acc4bc0 to d6e824d Compare July 20, 2026 14:37
JaredScar and others added 19 commits July 20, 2026 11:02
…rter 2023 (#8000)

* Enhance PreviewOrganizationTaxCommand to improve error handling and logging for subscription discrepancies. Added a logger for better traceability and refined quantity determination logic for password manager plans.

* Add regression tests for organization plan changes in PreviewOrganizationTaxCommandTests

- Implemented tests to ensure correct handling of plan upgrades from non-seat-based to seat-based plans, utilizing the organization's seat count.
- Added a test to verify that a missing price line item for the current plan results in a BadRequest instead of an exception.
- Enhanced error handling for subscription discrepancies during plan changes.
feat:  Improve ProfileService handling of claims

Created an allow list of claims that are maintained between token refreshes. 

Testing was moved into its own functional area for testing token issuance. Moving the tests into a more functional space allows for more specific areas of test rather than having a large monolith of a test class.
Updated the InviteUsersPasswordManagerValidator to include seat count in validation results. Modified ProviderResellerSeatLimitError to accept seat count and adjusted related validation logic in InvitingUserOrganizationProviderValidator. Updated OrganizationService to reflect seat limits in error messages and adjusted corresponding tests for consistency.
test: Add WebAuthnProvider testing for model updates.
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
* Add google favicon API to icon service lookups

* lint fixes

* off for self host
)

* [PM-40216] Data-protect OrganizationInviteLink.Code at rest

Stores invite link Code as IDataProtector-encrypted NVARCHAR(300) with a
"P|" prefix, replacing the plaintext UNIQUEIDENTIFIER. All anonymous
endpoints now require OrganizationId + Code; lookup by Code is replaced
with lookup-by-org + constant-time FixedTimeEquals comparison, eliminating
the Code as a DB lookup key and closing the DB-read bearer-secret exposure.

Includes SQL Server migration (coordinated deploy), EF Core migrations for
MySQL/PostgreSQL/SQLite, SSDT schema update, and the InviteLinkCodeValidator
helper for constant-time comparisons.

* [PM-40216] fix: Rename SQL migration to sort after main's latest migration

CI's migration order check failed because main gained
2026-07-14_00_AddCreationDateToOrganizationUserUserDetailsView.sql
after this branch's migration was authored.

* [PM-40216] refactor: Use CoreHelpers.FixedTimeEquals in InviteLinkCodeValidator

Delegates to the codebase's existing constant-time comparison helper instead of duplicating the raw CryptographicOperations call.

* [PM-40216] refactor: Move invite link code comparison onto OrganizationInviteLink

Replaces the standalone InviteLinkCodeValidator with an instance method on
OrganizationInviteLink, matching the AuthRequest.IsValidForAuthentication
pattern of entities comparing their own fields against external input.

* [PM-40216] refactor: Drop unnecessary Code lowercasing from migration

The table has zero rows in every environment, so there's no existing
data to normalize before the column type change.

* Revert unrelated packages.lock.json drift picked up by local restore

* Bump invite link code protection migration script date to 2026-07-21

* Remove comments from test methods added/modified by this branch

* Regenerate EF migrations to include Event.SendId

The OrganizationInviteLinkCodeProtection migration's own Designer.cs
snapshot was stale for MySQL, Postgres, and SQLite, missing
Event.SendId and the X_Event_OrganizationIdSendIdDate index added by
#7690, even though the branch was already up to date with main.
Removed and regenerated the migration for all three providers against
the current model.

* Simplify invite link code protection migration comment

Drop the "coordinated deploy" instruction, there's no tooling to gate
migration timing on rollout completion, so it implied a mechanism we
don't have.
…nizations (#8035)

UpdateOrganizationSubscriptionCommand treated every active Stripe
subscription schedule as one of Bitwarden's own plan-migration schedules
and rewrote its phases. A schedule Finance hand-builds in the Stripe
Dashboard (negotiated renewal seats + coupon, end_behavior=release) is
indistinguishable to that code, so a routine change (e.g. adding a seat)
silently clobbered the negotiated future-phase seats and stripped its
discount, returning success while corrupting the terms.

Gate the schedule-rewrite path on whether the org is actually in a plan
migration, using the presence of a migration cohort assignment as the
discriminator (ResolvePhasePlansAsync now returns null for non-migration).
Non-migration orgs fall through to the existing direct subscription
update; Stripe self-manages the current phase and leaves the negotiated
downstream phases intact. Migration code paths are unchanged.

Scoped to the existing PM32581_UseUpdateOrganizationSubscriptionCommand
flag path. No API contract change.
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
…7966)

Premium enable/disable only bumped RevisionDate, but clients gate their
catch-up syncs on GET /accounts/revision-date, which returns
AccountRevisionDate. When the one-time PremiumStatusChanged push was
missed (e.g. an MV3 service worker suspension), every revision-gated
sync concluded nothing had changed and the client kept stale premium
state until a manual sync. Bumping AccountRevisionDate alongside
RevisionDate lets the clients' existing revision-gated syncs detect the
change. No SQL migration needed: User_Update already persists the
AccountRevisionDate column.
…dmins (#8006)

* [PM-40523] feat: Add endpoint to return organization private key to admins

Adds GET /organizations/{orgId}/private-key so admin-level users
(owners, admins, providers, and the "Manage Users" custom permission)
can fetch an organization's encrypted private key.

Supports KM's fix for the account-recovery-enrollment vulnerability
(PM-40307): admins generating an invite link need to derive the org's
public-key fingerprint from a source that can't be silently swapped by
a malicious server. Fetching the encrypted, tamper-evident private key
and deriving the public key/fingerprint from it client-side achieves
that, instead of trusting a bare public key fetched from the server.

Gated by ManageUsersRequirement per the ticket's authorization spec
(deliberately widens "Manage Users" access to the org private key,
pending AppSec sign-off) and by the GenerateInviteLink feature flag,
matching the rest of this epic's admin-side invite-link endpoints.

* fix: make OrganizationPrivateKeyResponseModel null-safe

Removes the leftover FIXME/#nullable disable that was copy-pasted from
an older sibling model. This file is new on this branch, so it should
be nullable-clean from the start rather than carrying forward debt.
…x preview (#7995)

* [PM-40440] fix: Include Secrets Manager and storage in plan-change tax preview

The plan-change tax preview rebuilt line items from the current subscription but looked up Secrets Manager seats, service accounts, and storage by the target plan's price IDs. Those IDs change across a tier boundary (and the service-account 2024 bump), and Families storage uses a distinct personal-storage ID, so the lookups missed and the preview omitted SM and storage cost, under-quoting the upgrade. Match existing items by the current plan's price IDs and re-price at the target plan, following the password-manager-seat pattern already in the command.

* [PM-40440] fix: Flag schedule-derived coupon on customer discount

When an org has an active price-migration schedule, its Phase 2 coupon is
surfaced as the org's CustomerDiscount for the subscription page. The web
change-plan dialog couldn't tell that schedule-derived coupon apart from a
genuine customer/SM discount, causing it to mis-render Enterprise upgrades.
Add an additive IsFromSchedule flag, serialized to the API response, so the
client can make that distinction. No server behavior changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* [PM-40440] fix: Include subscription-level discounts in plan-change tax preview

The organization plan-change and update tax previews applied only the customer-level discount (subscription.Customer.Discount), never subscription-level coupons (subscription.Discounts). Genuine org coupons — complimentary Password Manager, SM-standalone/trial — attach at the subscription level, so they were dropped from the preview and the displayed upgrade total over-quoted (e.g. full Enterprise PM price shown even when PM is comped). Resolve the discount as customer-level first, else the first subscription-level one (mirroring StripePaymentService.GetSubscriptionAsync), expanding discounts.coupon accordingly. The schedule-derived Phase 2 migration coupon lives on the subscription schedule, not the live subscription, so it remains excluded from the preview.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* [PM-40751] fix: Show tier-specific feature bullets in sales-assisted trial emails

The Features and SpotImageUrl switches in SalesAssistedTrialInvitationEmailView
only special-cased Families, so Free, Teams, and Enterprise all fell through to
a shared default written for Teams. Fixes PM-40751 (Enterprise showed Teams
bullets) and PM-40752 (Free showed Teams bullets).

Enterprise now gets distinct copy (SSO/security-policy focused) per the
design-approved mockup, reaffirmed after the ticket's own review caught a
later mockup revision that had accidentally reused Teams' copy for Enterprise.
Free gets the single bullet shared by every other tier, rather than no bullets
at all, per product direction that every trial email should list at least one
feature.

* Refine sales-assisted trial email tier handling

- Free gets no feature bullets or supporting copy (templates guard on
  empty Features)
- TeamsStarter is rejected at the command layer (BadRequestException),
  not just the admin form, and removed from the view model's switches
- ProductName/SpotImageUrl/Features are now exhaustive over
  Free/Families/Teams/Enterprise with no default fallback; any
  unmatched tier throws instead of silently defaulting
- Two-line hero title wrap for the trial-length variant

* Add more spacing above the trial details intro line
Co-authored-by: rkac-bw <148072202+rkac-bw@users.noreply.github.com>
@ike-kottlowski ike-kottlowski changed the title Auth/renovate/fido2 v4 migration [PM-40870] fido2 v4 model migration Jul 23, 2026
patriksvensson and others added 7 commits July 23, 2026 18:26
* Fix date of migration files that broke main
* Update EF migration attribute
* feat(rustsdk): add WrapSymmetricKey for wrapping symmetric keys

Expose the existing crypto_util::wrap_key helper via a new
wrap_symmetric_key FFI function that encrypts the raw key bytes (not the
base64 text), so the result unwraps back into a SymmetricCryptoKey. Add
RustSdkService.WrapSymmetricKey mirroring EncryptString. This is intended
for ProviderOrganization.Key (an organization key wrapped with the
provider's symmetric key) so clients can unwrap it via
unwrap_symmetric_key. Adds a Rust roundtrip test proving the wrapped key
recovers the original organization key.

* feat(core): track Provider creation on PlayItem

Add ProviderId tracking to PlayItem so Providers created during a Play
session are cleaned up with it. Adds PlayItem.ProviderId and a
Create(Provider, playId) overload, IPlayItemService.Record(Provider) with
its implementation, EF configuration (index, cascade FK, and a three-way
exactly-one CK_PlayItem_UserOrOrganizationOrProvider check constraint),
the EF Provider navigation, and the SSDT table/stored-procedure changes.
Adds Dapper and EF provider-tracking repository decorators and registers
them in the Play DI extensions.

* feat(core): add PlayItem ProviderId migrations

Add the schema migration for PlayItem.ProviderId across all four
databases. The MSSQL DbScript idempotently adds the ProviderId column,
FK_PlayItem_Provider (cascade), IX_PlayItem_ProviderId, drops the old
CK_PlayItem_UserOrOrganization check constraint in favor of the three-way
CK_PlayItem_UserOrOrganizationOrProvider, and recreates PlayItem_Create
and PlayItem_ReadByPlayId. The EF migrations (MySQL, PostgreSQL, SQLite)
add the column, index, cascade FK, and the renamed check constraint,
generated via dotnet ef.

* feat(seeder): add provider seed factories

Extract billing-email derivation into a shared SeederBilling helper and
refactor OrganizationSeeder to use it (no behavior change). Add
ProviderSeeder (Create + ApplyBilling), ProviderPlanSeeder (configured
ProviderPlan), and ProviderUserSeeder (role/status-aware ProviderUser
linking, with a confirmed-admin convenience) for seeding providers.

* feat(seeder): add SingleProviderScene

Add a composable SingleProviderScene that links an existing owner user
(as a confirmed ProviderAdmin) and existing client organizations to a new
provider, with an explicit list of billing plans and optional Stripe
gateway identifiers. ProviderOrganization keys wrap the organization key
under the provider key via WrapSymmetricKey so clients unwrap them back
into the organization key. Adds ProviderSceneHelpers.ResolveDomain.

* feat(seeder): destroy providers on scene teardown

Collect distinct provider IDs from the play items and delete providers
before users and organizations. ProviderUser/ProviderOrganization/
ProviderPlan cascade from the Provider, but FK_ProviderUser_User and
FK_ProviderOrganization_Organization do not, so the provider link rows
must be gone before the linked users and organizations can be deleted.
Per-provider delete errors accumulate into an AggregateException surfaced
as a SceneExecutionException, and the organizations query is materialized
before iterating.

* test(seeder): cover provider factories and SingleProviderScene

Add unit tests for the provider seed factories (ProviderSeeder defaults +
ApplyBilling non-null overwrite, ProviderPlanSeeder IsConfigured,
ProviderUserSeeder role/status matrix) and SeederBilling determinism /
non-deliverability. Cover PlayItemService.Record(Provider) for the
in-play and not-in-play paths. Add an InPlaySeederApiApplicationFactory
and an end-to-end SeedControllerProviderTests that seeds a provider-admin
user, a separate org-owner user, a client organization, then a provider
linking them, asserts the ProviderOrganization key is a wrapped type-2
EncString, and verifies DELETE /seed/{playId} tears everything down
(providers first).

* refactor(seeder): use CombGuid.Generate over obsolete GenerateComb

Replace the obsolete CoreHelpers.GenerateComb() calls in the new provider
seed factories and tests with CombGuid.Generate(), the replacement named in
the [Obsolete] attribute. Behavior is identical since GenerateComb delegates
to CombGuid.Generate(); this clears the github-code-quality obsolete-usage
findings on the changed lines.

* refactor(seeder): address review feedback on provider scenes

- Collapse the inline ProviderUser block in SingleProviderScene to
  ProviderUserSeeder.CreateConfirmedAdmin so the recipe lives in one place.
- Inline the single-use ProviderSceneHelpers.ResolveDomain into the scene and
  remove the helper class.
- Rename SeederBilling to BillingEmailSeeder for consistency with sibling
  factories (and the matching tests).
- Move wrap_symmetric_key out of cipher.rs into a dedicated provider.rs module
  (key wrapping is not cipher encryption); register it in build.rs and lib.rs.
- Move the provider scene integration test to
  Scenes/SingleProviderSceneTests.cs.

* fix(migrator): bump PlayItem ProviderId migration sequence to _01

The MSSQL DbScript shared the 2026-07-21_00 date+sequence prefix with the
base migration 2026-07-21_00_OrganizationInviteLinkCodeProtection.sql, so it
did not sort strictly after it and failed the migration-order validation.
Rename to _01 so it orders correctly.
#8031)

* feat(plan-migration): add RenewalNotificationSentDate to cohort assignment entity

* feat(plan-migration): add RenewalNotificationSentDate to database schema

* feat(plan-migration): add GetSendInvoiceCandidatesInWindow to repository

* chore(migrations): generate database migration scripts for plan migration

* test(plan-migration): add integration tests for invoice candidates

* fix(billing): run dotnet format

* feat(plan-migration): Refresh view and simplify tests for migration column

* style(format): remove byte order mark from C# file

* refactor(billing): rename organization plan migration cohort assignment stored procedure

* fix: run dotnet format

* feat(billing): add min/max days validation for invoice candidates

* docs(billing): document ArgumentException for invoice candidates

* test(billing): add integration test for min/max days validation

* fix(billing): update dbscript date

* fix(billing): update designer files and migration scripts

* fix: run dotnet format

* fix(billing): DRY up date call in stored procedure

* fix(Billing): optimize EF query

* fix(billing): update stored proc and sql formatting

* fix(billing): re-sequence RenewalNotificationSentDate migration after AddPamOrganizationUser

* fix: formatting fix
…eld. test: add testing around webauthn parsing of raw JSON
Using IResult (intended for Minimal APIs) with MVC controllers means
the openapi spec can't detect the actual response model. For now,
add annotations to fix this; we will eventually migrate to Minimal APIs
properly.
Swashbuckle reflected over the members of JsonNode/JsonValue and emitted a
bogus, self-referential "JsonValue" component (options/parent/root). The SDK
code generator then materialized that as a made-up type, breaking the generated
bindings for ConfigResponseModel.FeatureStates.

Register MapType mappings so these opaque JSON types render as free-form schemas,
restoring the free-form 'object' behavior these bindings previously relied on.
ike-kottlowski and others added 14 commits July 24, 2026 12:11
…x feature flag (#7989)

* [PM-37599] refactor: Remove PM37597 always-enable-Stripe-automatic-tax feature flag

The pm-37597-always-enable-stripe-automatic-tax flag has been at 100% in
production since 2026.6.0, so its flag-OFF path is dead code. Remove the flag
and delete the legacy branches that programmatically wrote Stripe tax_exempt,
making the flag-ON behavior unconditional: Stripe is the source of truth for
taxability (customers default to tax_exempt = "none") and the tax-ID banner is
gated on Stripe's view rather than a hardcoded country list.

No end-user behavior change. Relocates the postal-code country check off the
now-deleted TaxHelpers onto OrganizationCreateRequestModel.

Final story of epic PM-36315.

* Split postal-code validation theory into true/false tests per review feedback

* Delete AdjustSubscription tax-exempt tests for removed flag-OFF logic (fixes CI)
* improve user collection details performance

* chnage indentation

* bump timestamp

* fix sql

* fix migration

* bump sql file
…implify provider validation logic (#8055)

- Removed the unused 'seats' parameter from the Validate method in InvitingUserOrganizationProviderValidator.
- Updated the ProviderResellerSeatLimitError to streamline error handling by removing the unnecessary constructor overload.
- Adjusted error messages in OrganizationService and corresponding tests for consistency and clarity.
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
…te (#8061)

Complete the mechanical migration deferred by the fixed-GUID backout
(#8060). CoreHelpers.GenerateComb() is [Obsolete] and delegates to
CombGuid.Generate(), so this is behavior-neutral: runtime GUID
generation is unchanged; it only removes obsolete-API (CS0618) usage
from the Seeder.

Swaps all 13 call sites in util/Seeder to CombGuid.Generate(). No
using edits (every site already imports Bit.Core.Utilities), no test
or behavior changes.
…flag (#7883)

* [PM-36062] refactor: Remove defer-price-migration-to-renewal feature flag

Removes the PM32645_DeferPriceMigrationToRenewal flag and its now-dead immediate-migration (OFF-branch) logic, making the deferred schedule-based price migration the unconditional behavior. Collapses the three PM32645-or-PM35215 gates to PM35215 only (still in flight) and deletes the orphaned legacy cancel/reinstate methods left behind.

* Remove unused usings orphaned by the flag removal (IDE0005)

* Make cancel/reinstate schedule handling unconditional

Removing PM32645 had collapsed the PM32645-or-PM35215 schedule gates to PM35215-only, but PM35215 isn't enabled in production, which would drop the schedule release/recreate that PM32645-on currently provides for personal subscribers. Gate on schedule/metadata presence instead (matching PriceIncreaseScheduler.Release, which never checked a flag) and drop the now-unused IFeatureService from both types.

* Explain why upcoming-invoice handlers return true when scheduling is skipped
…lation validation (#7919)

* added Org User Action Validator to handle logic for org users performing actions.

* Updated to match feedback.

* [PM-38923] feat: Add v2 UpdateOrganizationUser command with role-escalation validation

Refactor the OrganizationUsersController.Put flow into a v2 command + validator
(returning CommandResult / ValidationResult<T>), gated behind the
pm-28365-change-member-email-no-mp feature flag. The validator ports v1's request
validation and adds the escalating-role guard by delegating to the shared
IOrganizationUserValidationService.CanManage rules (PM-38927), while preserving
v1's specific error messages. The controller supplies the acting user's membership
(role + permissions) as a plain field so Core stays free of ICurrentContext.

* Fix Put collection-auth mocks to match bulk ModifyUserAccess check

* chore: Remove v1 command references from v2 UpdateOrganizationUser comments

* refactor: Fetch collections once and reject default collections in v2 UpdateOrganizationUser

Pass the API-loaded collections into the v2 validation request so the validator
validates existence without re-querying. The validator now rejects default user
collections with a new CannotAssignDefaultCollection error instead of silently
filtering them, and the controller excludes current-access defaults from the
preserved read-only set.

* Simplified tests around user role validation in update org user validator tests. Made sure self hosted couldn't increase seat count on SM.

* refactor: Simplify v2 UpdateOrganizationUser request object

Fold UpdateOrganizationUserValidationRequest into UpdateOrganizationUserRequest so
the validator consumes the command request directly. Rename request properties for
clarity (OrganizationUserToUpdate, New* for requested changes, ReferencedCollections)
and group them logically, and trim verbose comments across the request, command, and
validator.

* fix: Enforce custom-permission grant-subset check in v2 UpdateOrganizationUser

Port the v1 grant-subset guard into the v2 validator so a Custom member with
only ManageUsers cannot grant a target member custom permissions the actor
does not themselves hold. Owners, admins, providers (no membership), and
system users remain exempt. Add the CustomUsersCanOnlyGrantOwnPermissions
error and validator coverage, and trim redundant comments across the v2
update files.

* removed unnecessary using.

* removed unnecessary comment

* removed unnecessary comment.

* test: Cover escalation-error branch mapping in v2 UpdateOrganizationUser validator

Assert the specific denial error type and add cases where the target's
current role and the requested role are Owner, exercising both branches of
the OnlyOwnersCanManageOwners vs CustomUsersCannotManageAdminsOrOwners mapping.

* test: Assert defaultUserCollectionName in v1 UpdateUser routing test

* [PM-38923] Create default collection on demotion in v2 UpdateOrganizationUser command

Port the v1 behavior of creating a personal DefaultUserCollection when a member
is demoted from a privileged role (Owner/Admin) into the v2 command, so enabling
the ChangeMemberEmailNoMp flag does not regress the feature.

* Fixed querying policy after user is demoted. Improved readability and organization.

* cleaned up comments

* comment clean up

* comment clean up

* Added private methods with state capture fields to capture if we're enabling secrets manager for the user and if we're demoting from a privileged role.

* Added update user method to entity.

* Added method to requirement and moved common code to private method for related methods.

* Added xml docs

* We need org for secrets manager update so we'll just use it instead of org ability

* We're fetching organization already. No need to use the org ability.

* Moved org user values into the IActingUser.

* cleaned up some comments

* fixed up tests

* Updated tests to not need org ability (and removed unused org ability in controller).

* Add default message to NotFoundError

* Clarify custom permissions comment

* Move collection access validity check onto the model

* Move role and permission checks into ManageOrganizationUserValidationService

* Move free org admin limit check into the validation service

* Remove unused role fields from IActingUser interface

* Swapping Arg.Any to Arg.Is<T>

* Rename test to match its assertions

* Corrected SM related tests.  added new positive case.

* Add PUT integration test suite for both feature flag states

Move the PUT tests into a dedicated OrganizationUserControllerPutTests file, run each under the flag off (v1) and on (v2), and branch assertions where v1 and v2 differ.

* Switched to SDK feature Service.

* Checked all clients and didn't see anyone consuming. Removing obsolete endpoint.

* Renamed manage org user service back to update org user validation service.
Moved addselftocollection check to controller. Cleaned up unnecessary request prop.
renamed NewCollections to CollectionsToSave

* Combined the target's new type and permissions into a IOrgUserRole param.

* I combined collections and access into a tuple so i didn't have to do the extra db call.

* Returing specific error

* added comment

* Cut sharing of full collection from controller to validator. Validator will requery to draw line between authz and validation. This matches v1 functionality.
* fix: Extract CreateHostBuilder in Api/Program.cs

* fix: Disable OTel OTLP exporters in all test factories

* style: Simplify OTel disable comment in WebApplicationFactoryBase
…onUser command (#7964)

* added Org User Action Validator to handle logic for org users performing actions.

* Updated to match feedback.

* [PM-38923] feat: Add v2 UpdateOrganizationUser command with role-escalation validation

Refactor the OrganizationUsersController.Put flow into a v2 command + validator
(returning CommandResult / ValidationResult<T>), gated behind the
pm-28365-change-member-email-no-mp feature flag. The validator ports v1's request
validation and adds the escalating-role guard by delegating to the shared
IOrganizationUserValidationService.CanManage rules (PM-38927), while preserving
v1's specific error messages. The controller supplies the acting user's membership
(role + permissions) as a plain field so Core stays free of ICurrentContext.

* Fix Put collection-auth mocks to match bulk ModifyUserAccess check

* chore: Remove v1 command references from v2 UpdateOrganizationUser comments

* refactor: Fetch collections once and reject default collections in v2 UpdateOrganizationUser

Pass the API-loaded collections into the v2 validation request so the validator
validates existence without re-querying. The validator now rejects default user
collections with a new CannotAssignDefaultCollection error instead of silently
filtering them, and the controller excludes current-access defaults from the
preserved read-only set.

* Simplified tests around user role validation in update org user validator tests. Made sure self hosted couldn't increase seat count on SM.

* refactor: Simplify v2 UpdateOrganizationUser request object

Fold UpdateOrganizationUserValidationRequest into UpdateOrganizationUserRequest so
the validator consumes the command request directly. Rename request properties for
clarity (OrganizationUserToUpdate, New* for requested changes, ReferencedCollections)
and group them logically, and trim verbose comments across the request, command, and
validator.

* fix: Enforce custom-permission grant-subset check in v2 UpdateOrganizationUser

Port the v1 grant-subset guard into the v2 validator so a Custom member with
only ManageUsers cannot grant a target member custom permissions the actor
does not themselves hold. Owners, admins, providers (no membership), and
system users remain exempt. Add the CustomUsersCanOnlyGrantOwnPermissions
error and validator coverage, and trim redundant comments across the v2
update files.

* removed unnecessary using.

* removed unnecessary comment

* removed unnecessary comment.

* test: Cover escalation-error branch mapping in v2 UpdateOrganizationUser validator

Assert the specific denial error type and add cases where the target's
current role and the requested role are Owner, exercising both branches of
the OnlyOwnersCanManageOwners vs CustomUsersCannotManageAdminsOrOwners mapping.

* test: Assert defaultUserCollectionName in v1 UpdateUser routing test

* [PM-38923] Create default collection on demotion in v2 UpdateOrganizationUser command

Port the v1 behavior of creating a personal DefaultUserCollection when a member
is demoted from a privileged role (Owner/Admin) into the v2 command, so enabling
the ChangeMemberEmailNoMp flag does not regress the feature.

* Fixed querying policy after user is demoted. Improved readability and organization.

* cleaned up comments

* comment clean up

* comment clean up

* Added private methods with state capture fields to capture if we're enabling secrets manager for the user and if we're demoting from a privileged role.

* Added update user method to entity.

* Added method to requirement and moved common code to private method for related methods.

* Added xml docs

* We need org for secrets manager update so we'll just use it instead of org ability

* We're fetching organization already. No need to use the org ability.

* Moved org user values into the IActingUser.

* cleaned up some comments

* fixed up tests

* Updated tests to not need org ability (and removed unused org ability in controller).

* Add default message to NotFoundError

* Clarify custom permissions comment

* Move collection access validity check onto the model

* Move role and permission checks into ManageOrganizationUserValidationService

* Move free org admin limit check into the validation service

* Remove unused role fields from IActingUser interface

* Swapping Arg.Any to Arg.Is<T>

* Rename test to match its assertions

* Corrected SM related tests.  added new positive case.

* Add PUT integration test suite for both feature flag states

Move the PUT tests into a dedicated OrganizationUserControllerPutTests file, run each under the flag off (v1) and on (v2), and branch assertions where v1 and v2 differ.

* Switched to SDK feature Service.

* Checked all clients and didn't see anyone consuming. Removing obsolete endpoint.

* Renamed manage org user service back to update org user validation service.
Moved addselftocollection check to controller. Cleaned up unnecessary request prop.
renamed NewCollections to CollectionsToSave

* Combined the target's new type and permissions into a IOrgUserRole param.

* I combined collections and access into a tuple so i didn't have to do the extra db call.

* Returing specific error

* added comment

* Cut sharing of full collection from controller to validator. Validator will requery to draw line between authz and validation. This matches v1 functionality.

* [PM-38926] feat: Add admin change member email to v2 UpdateOrganizationUser command

Allow an admin to change a claimed member's email via the v2 update flow when
the member has no master password and the new email is on an org-verified
domain. The validator enforces these rules and surfaces RFC 7807 problems
keyed on "email"; the command loads the account and delegates the change to
the Auth IChangeEmailCommand, mapping its BadRequestExceptions to typed errors.

* Add sync push on email change and reorder autoscale first

* Add admin change member name to v2 UpdateOrganizationUser command

* fixed name bug and cleaned up some command code

* normalized name

* fixed up tests

* Applied reqeusts from base branch to this one. Cleaned up some rebase issues.

* Added more integration tests for email

* Fixed test change from base branch.

* Consolidated to 1 file.

* Added claimed user gate to name change. Cleaned up validator code. Added new error. Updated integration test.

* Cleaned up some error assertions

* Normalized name when creating record.
@ike-kottlowski
ike-kottlowski deleted the auth/renovate/fido2-v4-migration branch July 28, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.