App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-12-08] [$175] Category and tag pickers repeatedly send unauthorized requests for regular workspace members

Open roryabraham opened this issue 1 week ago • 8 comments

Problem

Opening category/tag pickers as a regular workspace member repeatedly sends requests that fail: GetPolicyCategories returns 666 (Auth 401 Unauthorized), and OpenPolicyTagsPage shows the same behavior.

Steps to reproduce

  1. On staging, sign in as a regular member of a workspace with categories.
  2. Go to Troubleshoot → Clear cache and restart.
  3. Open an expense and select Category.
  4. Close and reopen the picker.

Actual: Each opening sends another failing request. Expected: Opening the picker should not repeatedly send requests the member cannot access, and available categories/tags should remain usable.

Reported cause

useLoadPolicyCategories and useLoadPolicyTags load data whenever a picker opens, but the corresponding Auth commands require permissions regular members lack.

The behavior was introduced by #99125 (fixing #98838); #102812 added the same loaders to Edit multiple.

Impact

Low observed user impact: members still see categories pushed at sign-in. However, the report identifies roughly 30–64k failing category requests daily since October 6, versus roughly 10 previously, and approximately 63% failures for tag-page requests.

Lazy-loaded, high-traffic accounts remain unverified.

Suggested investigation

Gate reads by supported permissions or avoid repeatedly retrying authorization failures, while preserving lazy-loaded category/tag access.

Original Slack report

Issue OwnerCurrent Issue Owner: @abzokhattab
Upwork Automation - Do Not Edit

roryabraham avatar Nov 23 '26 19:11 roryabraham

Current assignee @abzokhattab is eligible for the External assigner, not assigning anyone new.

Job added to Upwork: https://www.upwork.com/jobs/~022124995104171206792

Proposal

Confidence: Medium. The App retry mechanism is verified in code; the reported authorization failure and a regression-safe fix remain unverified at runtime.

What is the root cause of that problem?

The category/tag loaders do not check read permissions. They remember successful loads, but not authorization denials.

After a failed request, isLoading becomes false while hasOnceLoaded remains false. A per-instance guard prevents an immediate retry loop, but closing and reopening a picker that remounts creates a new instance—allowing the same request again.

Code evidence and introduction

What changes do you think we should make in order to solve the problem?

Confirm the authorization and data-loading contracts before implementing a permission gate. Specifically:

  1. Verify which roles these commands accept and which response field reliably identifies permission denial.
  2. Verify how lazy-loaded members obtain complete permitted categories and tag lists, not just the selected value.
  3. Then choose permission-aware request gating or separate denial-state tracking, while preserving transient-failure retries and cached options.

Do not use an admin-only check, mark denied requests successfully loaded, or suppress every 666 response.

Why those shortcuts are unsafe, and required coverage

Regression coverage should include member/admin/editor/auditor/approver roles; absent, partial and complete collections; repeated opens; reconnects; role changes; and high-traffic accounts entering inline, full-page and Edit multiple pickers.

What alternative solutions did you explore?

  • Fetch only when collections are absent: reintroduces selected-only lists for partially loaded accounts.
  • Never retry after any failure: prevents recovery from temporary failures.
  • Admin-only gating: excludes other settings readers and does not establish how ordinary members receive missing options.

Verification limitation: VictoriaLogs tools were unavailable. No production logs were queried, and no browser reproduction was performed. The denial reason, reported request volumes and high-traffic member behavior remain unconfirmed.

Related issue: Home “Top tags” insight requests tags for every workspace on each load shares the tag loader but additionally concerns Home’s per-workspace request fan-out.


Next Steps for Contributor+ team: To accept: After resolving the validation gaps above, @MelvinBot implement [this](https://github.com/Expensify/App/issues/107762) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 23 '26 22:11 MelvinBot

Proposal

Reproduced on staging web as a user-role member: after Clear cache and restart, I opened the Category picker, then closed and reopened it 10 times. Every open sent a new GetPolicyCategories request (11 in total), and each one returned jsonCode: 666, "Unauthorized request". The picker itself still showed the categories.

What is the root cause of that problem?

useLoadPolicyCategories and useLoadPolicyTags (added in #99125) fetch whenever a picker mounts and hasOnceLoaded is false. They never check whether the current user is allowed to read the policy's categories or tags:

https://github.com/Expensify/App/blob/main/src/hooks/useLoadPolicyCategories.ts#L50-L56 https://github.com/Expensify/App/blob/main/src/hooks/useLoadPolicyTags.ts#L46-L52

On an authorization failure, failureData only clears isLoading. hasOnceLoaded stays false. The per-instance requestedPolicyIDRef stops a tight loop, but each new picker mount (open, close, open again; inline EditableCell pickers; Edit multiple) is a new instance, so it fires the read again. For a member this request can never succeed.

The App already models who can read these settings. ROLE_PERMISSION_BUNDLES in src/libs/PolicyUtils/permissions.ts gives categories / tags read access to admin, editor and auditor, and not to user, approveOnly, guest or the card/people/payments admin roles. This matches the report: regular members (user) are the ones getting 401s.

What changes do you think we should make in order to solve the problem?

Gate the on-demand read on the existing feature permission, inside the two hooks so every picker surface is covered:

  1. In useLoadPolicyCategories, read the policy and the current user's login, and compute
    const role = policy?.employeeList?.[login]?.role ?? policy?.role;
    const canFetch = !role || canMemberRead(policy, login, CONST.POLICY.POLICY_FEATURE.CATEGORIES);
    
    • If the role is known and has no read access, skip getPolicyCategories and the reconnect retry.
    • If the role is unknown (policy not loaded yet), keep today's behaviour, so a lazy-loaded admin is never left with a selected-only list.
  2. When canFetch is false, return isLoadingPolicyCategories = false and isLoadingCompletePolicyCategories = false, so the picker renders the categories the member already has (the ones pushed at sign-in) instead of a skeleton.
  3. Make the same change in useLoadPolicyTags with POLICY_FEATURE.TAGS (isLoadingPolicyTags = false, hasLoadedPolicyTags unchanged).
  4. Add unit tests for both hooks:
    • user role: no read on mount or on remount, and no skeleton.
    • admin / auditor: the read still fires once.
    • Unknown role: the read still fires.
    • After a reconnect, a gated member still sends nothing.

Why this doesn't regress the lazy-loading fix from #99125: for the gated roles the server already rejects these reads. A member never got the full list from this request, so skipping it removes only the failing traffic. It doesn't change what the member sees. Admins, editors, auditors and users whose role isn't loaded yet keep the on-demand fetch exactly as it is today.

Out of scope, but worth flagging: if lazy-loaded members can end up with an incomplete category or tag list, the fix is a member-readable endpoint or including the data in the sign-in push. That's a backend change; no App request can fix it today.

What alternative solutions did you explore? (Optional)

  • Remember the failure in Onyx (for example failureData: {hasFailed: true}) and stop retrying. failureData can't tell a 401 from a transient server error, so this would also block recovery for admins after a one-off failure.
  • Admin-only check: this would wrongly stop editors and auditors, who are allowed to read these settings. canMemberRead already encodes the role matrix, so it's the right source of truth.
  • Fetch only when the collection is absent: this brings back the selected-only list from #98838, because a partial collection can't be told apart from a complete one.

Xch4rt avatar Nov 23 '26 23:11 Xch4rt

Proposal

Please re-state the problem that we are trying to solve in this issue.

When a regular workspace member (e.g., user role) opens the Category or Tag picker — including after Clear cache and restart, closing/reopening the picker, or opening inline / split-expense pickers — the app repeatedly sends GetPolicyCategories and OpenPolicyTagsPage requests that fail with jsonCode: 666 (Unauthorized request / Auth 401).

What is the root cause of that problem?

Two separate layers dispatch these policy-settings read commands without checking whether the current user has read permission for the workspace's categories or tags:

  1. Shared on-demand loader hooks (src/hooks/useLoadPolicyCategories.ts:26-64 and src/hooks/useLoadPolicyTags.ts:21-60):
    • Both hooks dispatch getPolicyCategories(policyID) / openPolicyTagsPage(policyID) whenever hasOnceLoaded is false, without checking canMemberRead(policy, email, CONST.POLICY.POLICY_FEATURE.CATEGORIES / TAGS) (src/libs/PolicyUtils/permissions.ts:158-175).
    • On a 401 authorization denial, failureData in src/libs/actions/Policy/Category.ts:201-207 and src/libs/actions/Policy/Tag.ts:108-114 only resets isLoading: false and leaves hasOnceLoaded unset. While requestedPolicyIDRef prevents an infinite loop within a single mounted instance, every close/reopen, inline EditableCell mount, or reconnect (onReconnect) starts a fresh attempt and sends another failing 401 request.
    • Additionally, isLoadingCompletePolicyCategories (useLoadPolicyCategories.ts:60) and isLoadingPolicyTags (useLoadPolicyTags.ts:56) treat loadingState === undefined as loading when !hasOnceLoaded, so skipping the fetch without gating those flags would leave skeletons or loading states stuck for gated members.
  2. Direct expense/picker call sites bypassing the shared hooks:
    • src/pages/iou/request/step/DynamicIOURequestStepCategory.tsx:134-149: Calls getPolicyCategories(policyID) directly on mount and on onReconnect whenever !(policy && policyCategories) — with no permission check — and computes isLoading = !isOffline && policyCategories === undefined (line 142). Even if useLoadPolicyCategories is gated, opening an expense's Category step as a regular member before policyCategories is cached still fires GetPolicyCategories (401).
    • src/pages/iou/DynamicSplitExpenseEditPage.tsx:161-176: Unconditionally calls openPolicyCategoriesPage(effectivePolicyID ?? String(CONST.DEFAULT_NUMBER_ID)) and openPolicyTagsPage(effectivePolicyID ?? String(CONST.DEFAULT_NUMBER_ID)) on mount whenever policyCategories or policyTags is absent, with no permission check (and even when effectivePolicyID is undefined).

What changes do you think we should make in order to solve the problem?

Gate category and tag settings fetches consistently on the existing role-permission matrix (canMemberRead from @libs/PolicyUtils, which delegates to hasPolicyFeaturePermission and getPolicyRole in src/libs/PolicyUtils/permissions.ts:158-175, 262-278 — automatically handling policy.role, case-insensitive employeeList lookup, admin/editor/auditor read access, and isControlPolicyOnlyRole checks on downgraded Team workspaces):

  1. src/hooks/useLoadPolicyCategories.ts:
    • Subscribe to the target policy (ONYXKEYS.COLLECTION.POLICY for policyID) and the current user's email (ONYXKEYS.SESSION with an email selector).
    • Compute canFetchCategories = canMemberRead(policy, currentUserEmail ?? '', CONST.POLICY.POLICY_FEATURE.CATEGORIES).
    • Notice why we do not fall back to !role || canMemberRead(...): during initial Onyx hydration right after Clear cache and restart, policy starts as undefined; falling back to !role would immediately fire an unauthorized 401 request on the first render before policy resolves. Gating directly on canMemberRead(...) waits until policy hydrates, then fires immediately in the effect for permitted roles (admin, editor, Control auditor) while sending zero requests for user, approveOnly, guest, card_admin, people_admin, and payments_admin.
    • Include !canFetchCategories in the useEffect guard (with canFetchCategories in the dependency array), in the onReconnect guard (so reconnects never clear loading state or retrigger for unauthorized members), and in isLoadingCompletePolicyCategories (so gated members never see a stuck skeleton and render their cached/pushed categories immediately).
  2. src/hooks/useLoadPolicyTags.ts:
    • Apply the exact same permission gate using canMemberRead(policy, currentUserEmail ?? '', CONST.POLICY.POLICY_FEATURE.TAGS) across the useEffect, onReconnect, and isLoadingPolicyTags return flag.
    • Keep hasLoadedPolicyTags: hasOnceLoaded unchanged so callers like useUpdateTransactionTag.ts:96-109 do not falsely assume a complete tag list was fetched when the request was skipped.
  3. src/pages/iou/request/step/DynamicIOURequestStepCategory.tsx (lines 134–149):
    • Compute canFetchCategories = canMemberRead(policy, currentUserEmailParam, CONST.POLICY.POLICY_FEATURE.CATEGORIES) (currentUserEmailParam is already available in this component).
    • Guard fetchData (both on mount and onReconnect) with !canFetchCategories, add canFetchCategories to the effect dependencies so authorized roles fetch as soon as policy resolves, and gate isLoading (line 142) on canFetchCategories so regular members do not get stuck on a loading indicator if policyCategories is undefined.
  4. src/pages/iou/DynamicSplitExpenseEditPage.tsx (lines 161–176):
    • Guard openPolicyCategoriesPage on !!effectivePolicyID && !policyCategories && canMemberRead(effectivePolicy, login ?? '', CONST.POLICY.POLICY_FEATURE.CATEGORIES) and openPolicyTagsPage on !!effectivePolicyID && !policyTags && canMemberRead(effectivePolicy, login ?? '', CONST.POLICY.POLICY_FEATURE.TAGS) (also avoiding bogus '-1' requests when effectivePolicyID is undefined).
  5. Regression tests:
    • Unit tests for useLoadPolicyCategories and useLoadPolicyTags covering:
      • regular user (and guest / approveOnly / card_admin) sends 0 requests on initial mount, remount, and reconnect, with isLoading* === false;
      • policy === undefined hydrating into a user-role policy sends 0 requests (no hydration-race 401);
      • policy === undefined hydrating into an admin, editor, or Control auditor policy fires the read once;
      • downgraded Team policy with stale auditor role does not fire unauthorized reads;
      • transient failures for authorized roles still retry on remount / reconnect.
    • Component tests for DynamicIOURequestStepCategory and DynamicSplitExpenseEditPage verifying regular members do not dispatch GetPolicyCategories / OpenPolicyCategoriesPage / OpenPolicyTagsPage or get stuck in a loading state.

What alternative solutions did you explore? (Optional)

  1. Gating only useLoadPolicyCategories / useLoadPolicyTags with !role || canMemberRead(...):
    • Leaves two gaps: (a) when policy is briefly undefined during Onyx hydration (especially after Clear cache and restart), !role evaluates to true and still dispatches an unauthorized 401 request; and (b) misses the direct calls in DynamicIOURequestStepCategory.tsx:139 and DynamicSplitExpenseEditPage.tsx:163-166.
  2. Persisting failure state in Onyx (hasFailed: true) on any error:
    • failureData cannot distinguish a permanent 401 authorization denial from a transient network/server 5xx failure, which would break retry recovery for admins and editors after temporary outages.
  3. Restricting fetches to isPolicyAdmin only:
    • Too narrow: ROLE_PERMISSION_BUNDLES grants settings read access to editor and Control auditor as well; reusing canMemberRead keeps the client aligned with the central permission matrix.

danlopes18-ctrl avatar Nov 24 '26 02:11 danlopes18-ctrl

Fix PR is ready

abzokhattab avatar Nov 24 '26 15:11 abzokhattab

@abzokhattab / @thesahindia

The solution for this issue has been :rocket: deployed to production :rocket: in version 9.5.55-6 and is now subject to a 7-day regression period :calendar:. Here is the list of pull requests that resolve this issue:

  • https://github.com/Expensify/App/pull/107839

If no regressions arise, payment will be issued on 2026-12-08. :confetti_ball:

The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

melvin-bot[bot] avatar Dec 01 '26 03:12 melvin-bot[bot]

@abzokhattab / @thesahindia

The solution for this issue has been :rocket: deployed to production :rocket: in version 9.5.56-2 and is now subject to a 7-day regression period :calendar:. Here is the list of pull requests that resolve this issue:

  • https://github.com/Expensify/App/pull/107869

If no regressions arise, payment will be issued on 2026-12-08. :confetti_ball:

The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

melvin-bot[bot] avatar Dec 01 '26 23:12 melvin-bot[bot]