Skip to content

feat(tickets): email tickets of linked requesters visible to the device CU-17tkuw66na0 - #3337

Open
andriikachur wants to merge 15 commits into
mainfrom
feature/CU-17tkuw66na0
Open

andriikachur wants to merge 15 commits into
mainfrom
feature/CU-17tkuw66na0

Conversation

@andriikachur

@andriikachur andriikachur commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Email tickets in Fae, backend part 1 of 3 (oss-lib). ClickUp: https://app.clickup.com/t/17tkuw66na0

A device (AGENT) now also sees the email-created tickets whose requester is a directory user linked to that device. Same ticket entity, same reads; only the visibility rule is wider.

  • ClientOwnerScope gets the requester account ids of the calling machine; allows(Ticket) = today's owner rule OR (creationSource = EMAIL and requester.accountId in that set). The email branch ignores the organization and the cut-off. A requester without an account id is never visible.
  • New SPI ClientRequesterAccounts (openframe-data-mongo-common); ClientOwnerScopeResolver uses it when a bean exists (saas-lib registers it behind the email-to-ticket flag), else an empty set, so behaviour is unchanged without it.
  • getTickets: $and: [{$or: [ownerBranch, emailBranch]}]; the search's top-level $or and all filters apply to both branches; the owner branch keeps the cut-off. getTicket / getTicketByNumber filter by allows.
  • New index tenant_requester_account (tenantId, requester.accountId).
  • NatsClientContext carries the device's bearer token and tenant namespace from the websocket upgrade (excluded from toString, never logged), so the tenant gateway can ask ai-agent which dialogs the device may read.

Tests: red spec tests first, then implementation; PIT on changed lines 32/32 killed. TicketAgentVisibilityIT runs against real Mongo.

Change-Set: feature-cu-17tkuw66na0

Change set flamingo-stack/openframe-oss-lib#3337: these pull requests are one change, reviewed together.

Linked work

Linked by the Depends-On / Change-Set lines in these descriptions; this block is maintained by the hub.

@andriikachur andriikachur added the build Run the PR builds and publish snapshots (Java, npm preview); stays on until removed label Dec 3, 2026
@flamingo

flamingo Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

🦩 flamingo Code Review / security

✅ No findings on the current head.

Advisory: findings do not block the merge.

Files Lines 🔴 Action required 🟠 Recommended 🔵 Informational
17 +1052 / -36 0 0 0

Review again. New commits are not reviewed until you ask:

  • Security-check the new commits: only what was pushed since this security review
  • Security-check the whole diff again: everything, including what was already checked

Or comment @flamingo-review security (new commits) or @flamingo-review security full (everything). Add the flamingo-security-review-always label to security-review every push.

Started 2026-12-04 14:02 UTC · updated 2026-12-04 14:03 UTC · workflow run

@flamingo

flamingo Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

🦩 flamingo Code Review

✅ Tests and checks passed on this commit (3 lanes).

9 findings: 🔴 0 action required · 🟠 0 recommended · 🔵 9 informational

Advisory: findings do not block the merge.

Rules cited: OFJAVA-002, OFJAVA-017, OFJAVA-007, OFJAVA-001, OFJAVA-013 · 1 defect outside any rule

Files Lines Languages Tests Checks 🔴 Action required 🟠 Recommended 🔵 Informational
16 +999 / -26 Java (1 Maven lane) ✅ 7410 / 7410 green (443 skipped) ✅ 1 / 1 passed 0 0 9

🔵 Informational (9)

# Where Finding Flagged by
1 CustomTicketRepositoryImpl.java:167 Nested method calls passed as arguments to query.addCriteria in applyOwnerScope (Minor) OFJAVA-002
2 NatsClientContextFactory.java:58 Needless null guard on exchange.getRequest() in upgradeHeaders (Minor) OFJAVA-017
3 CustomTicketRepositoryImpl.java:175 ownerCriteria passes ownerScope.getMachineId() as a call argument (Minor) OFJAVA-002
4 NatsClientContextFactory.java:68 BEARER_PREFIX.length() called inside the substring(...) argument list (Minor) OFJAVA-002
5 NatsClientContextFactory.java:65 Compound Bearer-header condition not extracted into a named predicate (Minor) OFJAVA-007
6 NatsClientContextFactory.java:65 Hand-rolled null check on the Authorization header instead of StringUtils.hasText (Minor) OFJAVA-001
7 ClientOwnerScope.java:37 allows(Ticket) returns a raw || compound condition instead of a named predicate (Minor) OFJAVA-007
8 NatsClientContextFactory.java:63 bearerTokenOf returns null and that null is passed into the NatsClientContext builder (Minor) OFJAVA-013
9 TicketRepository.java:25 findByTicketNumberAndOwnerMachineId has no callers left Tests and mutation

✅ What this change does well

  • ClientOwnerScope keeps its new requesterAccountIds defensive and immutable (Set.copyOf, null-to-empty) and ClientOwnerScopeTest pins exactly that with requesterAccountIds_neverNull_immutable.
  • Ticket.java declares the new tenant_requester_account compound index on the @‍Document itself and TicketIndexesTest pins the full declared index set by name and key order.
  • CustomTicketRepositoryImpl keeps the organization-assignment cutoff on the owner branch only (hasOwnerBranchOnly in createdAtFrom), so the new email branch cannot be silently truncated by the cutoff.
  • NatsClientContext.java marks bearerToken and tenantNamespace with @‍ToString.Exclude so the credential never reaches logs, and NatsClientContextTest.java actually asserts toString() omits it.
  • Visibility stays one rule in one class: ClientOwnerScope.allows(Ticket) for single reads and the same owner-OR-email shape in CustomTicketRepositoryImpl for list/count/cursor, so every existing AGENT caller of the scope picks up the email branch.
  • Without the SPI bean the query and the scope are byte-for-byte today's (buildTicketQuery_emptyAccountSet_identicalToToday), so OSS and flag-off deployments are unaffected.
  • Top-level $or of search is preserved by wrapping the owner/email union in $and, and withCursorBound appends to that $and instead of clobbering it; covered by unit tests and a real-Mongo IT.
  • Bearer token and tenant namespace are excluded from NatsClientContext.toString, with a test asserting they are never printed.

Inline comments: 8 new

Outside the lines this diff changes (no inline comment possible)

  • 🔵 Informational · info · Tests and mutation · openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepository.java:25: findByTicketNumberAndOwnerMachineId has no callers left
    TicketService.getTicketByNumber now reads findByTicketNumber(...).filter(scope::allows); it was the only caller of findByTicketNumberAndOwnerMachineId. No code in oss-lib, saas-lib or saas-tenant of this change set calls it any more (findByIdAndOwnerMachineId is still used by ai-agent TicketReopenService).
2 possible problems checked and ruled out
  • openframe-api-lib/src/main/java/com/openframe/api/service/device/ClientOwnerScopeResolver.java:61 Missing ClientRequesterAccounts bean silently narrows agent ticket visibility with no log: OFJAVA-020 is about log levels per layer, not about logging an absent optional bean; the request is a generic 'log more' wish on a deliberate Set.of() fallback (ClientOwnerScopeResolver.java:62-63).
  • openframe-api-lib/src/main/java/com/openframe/api/service/ticket/TicketService.java:198 findByIdOrNumber is changed and no test references it: The PR adds openframe-data-mongo-sync/.../TicketAgentVisibilityIT.java covering agent ticket visibility; findByIdOrNumber is a thin delegator and a dedicated-name test demand is noise here.

🧪 Tests and mutation

Tests per lane

Language Project Command Status Counts Time
Java (Maven) . mvn -B test -pl openframe-api-lib,openframe-data-mongo-common,openframe-data-mongo-sync,openframe-gateway-service-core -am ✅ passed openframe-api-lib 1891 · openframe-audit 348 · openframe-core 271 · openframe-core-crypto 64 · openframe-data-kafka 52 · openframe-data-loki 96 · openframe-data-mongo-common 115 · openframe-data-mongo-reactive 25 · openframe-data-mongo-sync 3391 (407 skipped) · openframe-data-nats 243 (4 skipped) · openframe-data-pinot 256 · openframe-data-redis 2 · openframe-data-timeentry-aspect 3 · openframe-event-publishing 103 (32 skipped) · openframe-exception 9 · openframe-gateway-service-core 643 · openframe-graphql-relay 73 · openframe-machine-delivery 161 · openframe-security-core 37 · fleetmdm 70 · 0 failures 105.1 s

Checks

Check Kind Language Project Status Time
OpenGrep security Java (OpenGrep) . ✅ passed 13.4 s

Stage 2 lanes: Maven test passed (7853 run, 0 failed, 443 skipped - skipped are ITs gated by -Dintegration.tests, including the new TicketAgentVisibilityIT); PIT mutation passed; OpenGrep security check passed with no places.

Mutation on new lines: openframe-api-lib 6/6 killed, openframe-data-mongo-sync 11/11 killed, openframe-gateway-service-core 6/6 killed.

The 9 NO_COVERAGE mutants on ClientOwnerScope (lines 34, 40, 60, 62, 63) are a tool artefact: ClientOwnerScope lives in openframe-data-mongo-common but its tests (ClientOwnerScopeTest, 17 cases covering null requester, null accountId, non-EMAIL source, unlinked account, other customer, pre-cut-off, empty set, null set) live in openframe-data-mongo-sync, which per-module PIT does not run against mo.

ClientRequesterAccounts.java is an interface with no logic, so 'not mutation-tested' is not a real gap.

Worktree carries uncommitted local pom pins (feature-CU-17tkuw66na0-SNAPSHOT); left untouched. PR head 00c86fd equals the local HEAD.

Mutation testing

This build has no PIT plugin, so each module is mutated from the command line with pit-adhoc.sh, changing nothing in the repository.

Module Classes Whole classes New lines only Time
api-lib ClientOwnerScopeResolver, TicketService 182 mutants, 110 killed (60%), 22 survived, 50 no coverage, test strength 83%, line coverage 76% 6 mutants: 6 killed 56 s
data-mongo-common ClientOwnerScope, Ticket, TicketEmailOrigin, TicketRequester, TicketStatusKind 37 mutants, 0 killed (0%), 37 no coverage, line coverage 0% 9 mutants: 9 no coverage 14 s
data-mongo-sync CustomTicketRepositoryImpl 146 mutants, 87 killed (60%), 18 survived, 41 no coverage, test strength 83%, line coverage 69% 11 mutants: 11 killed 27 s
gateway-service-core NatsClientContext, NatsClientContextFactory 18 mutants, 17 killed (94%), 1 survived, test strength 94%, line coverage 100% 6 mutants: 6 killed 15 s

New code, its covering tests and the result

New code Covering tests Result
forMachine in ClientOwnerScopeResolver, lines 54-58 ClientOwnerScopeResolverTest (3), 3 more killed
requesterAccountIdsOf in ClientOwnerScopeResolver, line 63 ClientOwnerScopeResolverTest (3), 3 more killed
getTicket in TicketService, line 185 TicketServiceClientOwnerScopeTest (3), 5 more killed
getTicketByNumber in TicketService, line 195 TicketServiceClientOwnerScopeTest (3), 2 more killed
init in ClientOwnerScope, line 34 none no coverage (line 34)
allows in ClientOwnerScope, line 40 none no coverage (line 40)
isLinkedRequesterEmailTicket in ClientOwnerScope, lines 60-63 none no coverage (lines 60, 62-63)
createdAtFrom in CustomTicketRepositoryImpl, line 144 CustomTicketRepositoryFilterTest (3), 25 more killed
applyOwnerScope in CustomTicketRepositoryImpl, line 158 CustomTicketRepositoryFilterTest (3), 12 more killed
hasOwnerBranchOnly in CustomTicketRepositoryImpl, line 171 CustomTicketRepositoryFilterTest (3), 25 more killed
ownerCriteria in CustomTicketRepositoryImpl, lines 177-181 CustomTicketRepositoryFilterTest (3), 12 more killed
withCutOff in CustomTicketRepositoryImpl, line 185 CustomTicketRepositoryFilterTest (3), 4 more killed
linkedRequesterEmailCriteria in CustomTicketRepositoryImpl, line 189 CustomTicketRepositoryFilterTest (3), 4 more killed
upgradeHeaders in NatsClientContextFactory, line 60 NatsClientContextFactoryTest (3), 1 more killed
bearerTokenOf in NatsClientContextFactory, lines 65-68 NatsClientContextFactoryTest (3), 1 more killed
The covering tests by name (12 methods)
  • ClientOwnerScopeResolver.forMachine: ClientOwnerScopeResolverTest.scopeOf_agentOfUnknownMachine_scopeWithoutOrganization, ClientOwnerScopeResolverTest.forMachine_unknownMachine_stillAsksSpi, ClientOwnerScopeResolverTest.forMachine_knownMachine_scopeCarriesItsCurrentOrganization, and 3 more
  • ClientOwnerScopeResolver.requesterAccountIdsOf: ClientOwnerScopeResolverTest.scopeOf_agentOfUnknownMachine_scopeWithoutOrganization, ClientOwnerScopeResolverTest.forMachine_unknownMachine_stillAsksSpi, ClientOwnerScopeResolverTest.forMachine_knownMachine_scopeCarriesItsCurrentOrganization, and 3 more
  • TicketService.getTicket: TicketServiceClientOwnerScopeTest.getTicket_agentAndTicketWithoutSnapshot_stillFound, TicketServiceClientOwnerScopeTest.getTicket_agentAndTicketCreatedUnderCurrentOrganization_found, TicketServiceClientOwnerScopeTest.getTicket_agentVisibleEmailTicket_present, and 5 more
  • TicketService.getTicketByNumber: TicketServiceClientOwnerScopeTest.getTicketByNumber_agentVisibleEmailTicket_present, TicketServiceClientOwnerScopeTest.getTicketByNumber_agentAndOtherMachinesTicket_notFound, TicketServiceClientOwnerScopeTest.getTicketByNumber_agentAndTicketCreatedUnderPreviousOrganization_notFound, and 2 more
  • CustomTicketRepositoryImpl.createdAtFrom: CustomTicketRepositoryFilterTest.buildTicketQuery_noOwnerScope_noOwnerClauses, CustomTicketRepositoryFilterTest.buildTicketQuery_escalatedByUserOmitted_noNarrowing, CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithCutOffAndNoFilter_createdAtStartsAtTheCutOff, and 25 more
  • CustomTicketRepositoryImpl.applyOwnerScope: CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithOrganization_machineAndOrganizationSnapshotOrLegacyNull, CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithoutOrganization_machineOnly, CustomTicketRepositoryFilterTest.buildTicketQuery_accountSet_ownerOrEmailBranches, and 12 more
  • CustomTicketRepositoryImpl.hasOwnerBranchOnly: CustomTicketRepositoryFilterTest.buildTicketQuery_noOwnerScope_noOwnerClauses, CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithoutOrganization_machineOnly, CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithOrganization_machineAndOrganizationSnapshotOrLegacyNull, and 25 more
  • CustomTicketRepositoryImpl.ownerCriteria: CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithOrganization_machineAndOrganizationSnapshotOrLegacyNull, CustomTicketRepositoryFilterTest.buildTicketQuery_ownerScopeWithoutOrganization_machineOnly, CustomTicketRepositoryFilterTest.buildTicketQuery_accountSet_ownerOrEmailBranches, and 12 more
  • CustomTicketRepositoryImpl.withCutOff: CustomTicketRepositoryFilterTest.buildTicketQuery_accountSet_ownerOrEmailBranches, CustomTicketRepositoryFilterTest.buildTicketQuery_cutOffOnlyOnOwnerBranch, CustomTicketRepositoryFilterTest.buildTicketQuery_callerCreatedAtTo_appliesToBothBranches, and 4 more
  • CustomTicketRepositoryImpl.linkedRequesterEmailCriteria: CustomTicketRepositoryFilterTest.buildTicketQuery_accountSet_ownerOrEmailBranches, CustomTicketRepositoryFilterTest.buildTicketQuery_cutOffOnlyOnOwnerBranch, CustomTicketRepositoryFilterTest.buildTicketQuery_callerCreatedAtTo_appliesToBothBranches, and 4 more
  • NatsClientContextFactory.upgradeHeaders: NatsClientContextFactoryTest.create_adminToken_userContextScopedToTheUser, NatsClientContextFactoryTest.create_agentTokenWithMachineId_deviceContextScopedToTheMachine, NatsClientContextFactoryTest.create_keepsBearerAndTenantNs, and 1 more
  • NatsClientContextFactory.bearerTokenOf: NatsClientContextFactoryTest.create_noAuthorizationOrNs_nullFields, NatsClientContextFactoryTest.create_adminToken_userContextScopedToTheUser, NatsClientContextFactoryTest.create_agentTokenWithMachineId_deviceContextScopedToTheMachine, and 1 more

What the surviving mutations leave unverified

  • NatsClientContextFactory.java:43-45: The device bearer token and X-Tenant-Ns are taken from the upgrade request and kept for the session's lifetime (the session is closed at JWT expiry by WebSocketServiceSecurityDecorator, and the token is excluded from toString). X-Tenant-Ns is trusted because the shared gateway injects it behind the trust boundary and applyToUri only accepts a DNS-1123 label; whether a client-supplied X-Tenant-Ns on /ws/nats is always overwritten/validated before it reaches this factory is enforced outside this repo (saas gateway TenantContextWebFilter) and was not verified here. Worth a security review.

9 mutants on lines this change added are not caught (0 survived, 9 with no test reaching them): each is annotated on its line in the flamingo Code Review / tests and mutation check.

1 gap (not tested here):

  • Java (Maven) .: ClientRequesterAccounts.java changed but not mutation-tested (outside the mutation targets openframe-data-mongo-common configures)
🤖 Prompt for AI agents: fix every finding
Address these code-review findings on pull request #3337 of flamingo-stack/openframe-oss-lib, most important first.
For each one, make the minimal change that resolves it and do not refactor unrelated code.
If you can show a finding is wrong, skip it and say why.

1. [Informational] openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepositoryImpl.java:167 Nested method calls passed as arguments to query.addCriteria in applyOwnerScope
   OFJAVA-002 forbids calling a method inside another call's argument list; here `Criteria.where(AND_OPERATOR).is(List.of(visible))` is built inline inside `query.addCriteria(...)`, and `List.of(visible)` is itself a call used as an argument. Extract the list and the criteria into named locals first. This is CI-enforced by PMD NoMethodCallAsArgument.
2. [Informational] openframe-gateway-service-core/src/main/java/com/openframe/gateway/config/ws/nats/NatsClientContextFactory.java:58 Needless null guard on exchange.getRequest() in upgradeHeaders
   ServerWebExchange.getRequest() is contractually non-null (it is the request the exchange wraps; both MockServerWebExchange in the new tests and the real DefaultServerWebExchange always return one). The `request == null ? HttpHeaders.EMPTY : ...` branch is a guard for a state that cannot occur, and it hides the fact that a missing Authorization header — not a missing request — is the real absent case handled just below in bearerTokenOf.
3. [Informational] openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepositoryImpl.java:175 ownerCriteria passes ownerScope.getMachineId() as a call argument
   OFJAVA-002 requires each method call to be extracted to a named local before being passed as an argument. The new `ownerCriteria` helper calls `is(ownerScope.getMachineId())` directly; the method already extracts `organizationId` to a local two lines below, so the machineId should follow the same shape.
4. [Informational] openframe-gateway-service-core/src/main/java/com/openframe/gateway/config/ws/nats/NatsClientContextFactory.java:68 BEARER_PREFIX.length() called inside the substring(...) argument list
   OFJAVA-002 forbids calling a method inside another call's argument list (CI-enforced by PMD NoMethodCallAsArgument, priority 1). The added line nests BEARER_PREFIX.length() as substring's argument; it must be extracted to a named local first.
5. [Informational] openframe-gateway-service-core/src/main/java/com/openframe/gateway/config/ws/nats/NatsClientContextFactory.java:65 Compound Bearer-header condition not extracted into a named predicate
   The `authorization == null || !authorization.startsWith(BEARER_PREFIX)` condition mixes a null check with a prefix check inline; the rule requires any condition containing || to be a named private predicate, and OFJAVA-001 asks for Spring's StringUtils.hasText rather than a hand-rolled null check.
6. [Informational] openframe-gateway-service-core/src/main/java/com/openframe/gateway/config/ws/nats/NatsClientContextFactory.java:65 Hand-rolled null check on the Authorization header instead of StringUtils.hasText
   OFJAVA-001 requires reusing Spring/JDK utilities via static import instead of hand-rolled checks; the added guard hand-rolls the null check for a String where org.springframework.util.StringUtils.hasText is the prescribed utility (and would also reject a blank header).
7. [Informational] openframe-data-mongo-common/src/main/java/com/openframe/data/model/ClientOwnerScope.java:37 allows(Ticket) returns a raw || compound condition instead of a named predicate
   OFJAVA-007 makes a named private predicate mandatory for any condition containing `||`. The new `allows(Ticket)` returns `allows(owner, createdAt) || isLinkedRequesterEmailTicket(ticket)` inline; the visibility rule (own-machine ticket OR an email ticket of a linked requester) deserves a named predicate such as `isOwnerTicket`/`isVisibleTo`.
8. [Informational] openframe-gateway-service-core/src/main/java/com/openframe/gateway/config/ws/nats/NatsClientContextFactory.java:63 bearerTokenOf returns null and that null is passed into the NatsClientContext builder
   bearerTokenOf returns a bare null when the Authorization header is missing or not a Bearer header, and create() then passes that null (and the possibly-null TENANT_NS_HEADER value) into NatsClientContext.builder().bearerToken(...). The new test create_noAuthorizationOrNs_nullFields pins this null-field shape, so every future consumer of getBearerToken()/getTenantNamespace() (wired in the sibling pull requests not visible here) has to null-check instead of getting a real value or a failure at the upgrade, where the absence is actually detectable.
9. [Informational] openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepository.java:25 findByTicketNumberAndOwnerMachineId has no callers left
   TicketService.getTicketByNumber now reads findByTicketNumber(...).filter(scope::allows); it was the only caller of findByTicketNumberAndOwnerMachineId. No code in oss-lib, saas-lib or saas-tenant of this change set calls it any more (findByIdAndOwnerMachineId is still used by ai-agent TicketReopenService).

Next: commit a suggestion, or hand a comment's prompt to your coding agent. React 👍 on a finding that helped and 👎 on one that is wrong: the reviewer learns from both.

Review again. New commits are not reviewed until you ask:

  • Review the new commits: only what was pushed since this review
  • Review the whole diff again: everything, including what was already reviewed

Or comment @flamingo-review (new commits) or @flamingo-review full (everything). Add the flamingo-review-always label to review every push.

Updated 2026-12-03 21:02 UTC · reviewed from Andrii Kachur's machine

@yevhenii-flamingo yevhenii-flamingo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A couple of points from the checklist pass.

@andriikachur
andriikachur force-pushed the feature/CU-17tkuw66na0 branch from 6624fee to c8a3d3a Compare December 4, 2026 12:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

build Run the PR builds and publish snapshots (Java, npm preview); stays on until removed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants