Skip to content

MaaS Admin List All API Keys#6908

Open
katieperry4 wants to merge 3 commits intoopendatahub-io:mainfrom
katieperry4:51807/admin-list-api-keys
Open

MaaS Admin List All API Keys#6908
katieperry4 wants to merge 3 commits intoopendatahub-io:mainfrom
katieperry4:51807/admin-list-api-keys

Conversation

@katieperry4
Copy link
Contributor

@katieperry4 katieperry4 commented Mar 26, 2026

Closes RHOAIENG-51807

Description

The MaaS API already handled this 🤷‍♀️ the ticket was just to double check

On the dashboard-maas cluster I had the cluster admin make some keys and the user make some keys

cluster admin view:
Screenshot 2026-03-26 at 9 46 55 AM

user view:
Screenshot 2026-03-26 at 9 47 11 AM


and hiding the username search input for non-maas-admins:
(this uses impersonate so that's why all the keys are still showing just ignore that, that call isn't hooked up to the is-maas-admin check)

Screen.Recording.2026-03-26.at.9.47.54.AM.mov

Small fix for list subscriptions, had some required fields that aren't actually required so I was getting some invalid response format issues
@Griffin-Sullivan mentioned he did the same in his PR, doesn't matter which goes first

How Has This Been Tested?

Tested locally

Test Impact

no tests changed

Request review criteria:

Self checklist (all need to be checked):

  • The developer has manually tested the changes and verified that the changes work
  • Testing instructions have been added in the PR body (for PRs involving changes that are not immediately obvious).
  • The developer has added tests or explained why testing cannot be added (unit or cypress tests for related changes)
  • The code follows our Best Practices (React coding standards, PatternFly usage, performance considerations)

If you have UI changes:

  • Included any necessary screenshots or gifs if it was a UI change.
  • Included tags to the UX team if it was a UI/UX change.

After the PR is posted & before it merges:

  • The developer has tested their solution on a cluster by using the image produced by the PR to main

Summary by CodeRabbit

  • New Features

    • Role-based controls on the API Keys page: admins see the username filter; non-admins see a simplified toolbar.
  • Improvements

    • Subscription data handling made more tolerant of missing fields, reducing validation errors from backend responses.
  • Tests

    • End-to-end tests updated and a mocked admin check added to cover admin vs. non-admin UI behavior.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 26, 2026

📝 Walkthrough

Walkthrough

This PR makes subscription-related fields optional: tokenRateLimits on ModelSubscriptionRef, and phase and creationTimestamp on MaaSSubscription, and updates runtime type-guards to accept these as optional. The API keys page now obtains isMaasAdmin from useIsMaasAdmin() and passes it to ApiKeysToolbar, which conditionally renders the "Username" filter only for Maas admins. Cypress test and typings were added/updated to stub GET /maas/api/v1/is-maas-admin and exercise the admin/non-admin UI paths.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Security considerations

CWE-602: Client-Side Enforcement of Server-Side Security
The conditional rendering of the username filter in ApiKeysToolbar based on isMaasAdmin must be enforced server-side. Client-side UI filtering provides no security boundary. Verify that the backend validates admin authorization before processing requests that depend on username-level filtering. Hiding UI elements is insufficient protection.

Type-guard validation alignment (CWE-20: Improper Input Validation)
Confirm that the optional field changes in both type definitions and runtime type-guards (isMaaSSubscriptionRef, isMaaSSubscription) match actual API responses. Loosening validation without backend alignment risks accepting malformed or incomplete data that downstream code may not handle safely.

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: enabling MaaS admins to list all API keys. It directly relates to the core functionality implemented.
Description check ✅ Passed The description includes issue reference, testing evidence with screenshots, manual verification, and test rationale. All required template sections are addressed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
packages/maas/frontend/src/app/api/subscriptions.ts (1)

13-32: ⚠️ Potential issue | 🟠 Major

Harden nested object guards to prevent malformed payload acceptance (CWE-20, Major).

Line [20], Line [28], and Line [31] only check typeof ... === 'object', which accepts null and arrays and does not enforce shape. A malformed BFF response can pass the guard and break downstream consumers when fields are dereferenced.

Proposed fix
 const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object';

+const isBillingRate = (v: unknown): v is { perToken: string } =>
+  isRecord(v) && typeof v.perToken === 'string';
+
+const isGroupReference = (v: unknown): v is { name: string } =>
+  isRecord(v) && typeof v.name === 'string';
+
+const isOwnerSpec = (v: unknown): v is { groups: { name: string }[] } =>
+  isRecord(v) && Array.isArray(v.groups) && v.groups.every(isGroupReference);
+
+const isTokenMetadata = (
+  v: unknown,
+): v is { organizationId: string; costCenter: string; labels?: Record<string, string> } =>
+  isRecord(v) &&
+  typeof v.organizationId === 'string' &&
+  typeof v.costCenter === 'string' &&
+  (v.labels === undefined ||
+    (isRecord(v.labels) && Object.values(v.labels).every((value) => typeof value === 'string')));
+
 const isMaaSSubscriptionRef = (v: unknown): v is ModelSubscriptionRef =>
   isRecord(v) &&
   typeof v.name === 'string' &&
   typeof v.namespace === 'string' &&
   (v.tokenRateLimits === undefined ||
     (Array.isArray(v.tokenRateLimits) && v.tokenRateLimits.every(isTokenRateLimit))) &&
   (v.tokenRateLimitRef === undefined || typeof v.tokenRateLimitRef === 'string') &&
-  (v.billingRate === undefined || typeof v.billingRate === 'object');
+  (v.billingRate === undefined || isBillingRate(v.billingRate));

 const isMaaSSubscription = (v: unknown): v is MaaSSubscription =>
   isRecord(v) &&
   typeof v.name === 'string' &&
   typeof v.namespace === 'string' &&
   (v.phase === undefined || typeof v.phase === 'string') &&
   (v.priority === undefined || typeof v.priority === 'number') &&
-  typeof v.owner === 'object' &&
+  isOwnerSpec(v.owner) &&
   Array.isArray(v.modelRefs) &&
   v.modelRefs.every(isMaaSSubscriptionRef) &&
-  (v.tokenMetadata === undefined || typeof v.tokenMetadata === 'object') &&
+  (v.tokenMetadata === undefined || isTokenMetadata(v.tokenMetadata)) &&
   (v.creationTimestamp === undefined || typeof v.creationTimestamp === 'string');

As per coding guidelines, **/*.{ts,tsx,js,jsx}: WEB SECURITY (XSS, CSRF Prevention) — “Validate all API responses before rendering”.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/maas/frontend/src/app/api/subscriptions.ts` around lines 13 - 32,
The type guards isMaaSSubscriptionRef and isMaaSSubscription currently use
typeof ... === 'object' which allows nulls and arrays; update these checks to
use the existing isRecord predicate (or equivalent explicit null/array checks)
so nested objects are validated as plain records: replace (v.billingRate ===
undefined || typeof v.billingRate === 'object') with (v.billingRate ===
undefined || isRecord(v.billingRate)), replace typeof v.owner === 'object' with
isRecord(v.owner), and replace (v.tokenMetadata === undefined || typeof
v.tokenMetadata === 'object') with (v.tokenMetadata === undefined ||
isRecord(v.tokenMetadata)); ensure you import/retain the isRecord helper and
keep the rest of the guard logic intact (functions: isMaaSSubscriptionRef,
isMaaSSubscription).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/maas/frontend/src/app/pages/api-keys/allKeys/ApiKeysToolbar.tsx`:
- Around line 114-143: When the username filter UI unmounts the hidden state can
persist; add a useEffect inside ApiKeysToolbar that watches isMaasAdmin and on
unmount or when isMaasAdmin becomes false calls setLocalUsername('') and
onUsernameChange('') to clear any lingering filter state (use a cleanup function
or effect branch). This ensures the username filter (localUsername,
setLocalUsername, onUsernameChange) is reset whenever the ToolbarFilter block is
removed so invisible filtering cannot persist.

---

Outside diff comments:
In `@packages/maas/frontend/src/app/api/subscriptions.ts`:
- Around line 13-32: The type guards isMaaSSubscriptionRef and
isMaaSSubscription currently use typeof ... === 'object' which allows nulls and
arrays; update these checks to use the existing isRecord predicate (or
equivalent explicit null/array checks) so nested objects are validated as plain
records: replace (v.billingRate === undefined || typeof v.billingRate ===
'object') with (v.billingRate === undefined || isRecord(v.billingRate)), replace
typeof v.owner === 'object' with isRecord(v.owner), and replace (v.tokenMetadata
=== undefined || typeof v.tokenMetadata === 'object') with (v.tokenMetadata ===
undefined || isRecord(v.tokenMetadata)); ensure you import/retain the isRecord
helper and keep the rest of the guard logic intact (functions:
isMaaSSubscriptionRef, isMaaSSubscription).
🪄 Autofix (Beta)

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: Repository YAML (base), Central YAML (inherited), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: dbabbb1d-1129-48d7-8e44-19b2109157ba

📥 Commits

Reviewing files that changed from the base of the PR and between f7025bd and 6b3a907.

📒 Files selected for processing (4)
  • packages/maas/frontend/src/app/api/subscriptions.ts
  • packages/maas/frontend/src/app/pages/api-keys/AllApiKeysPage.tsx
  • packages/maas/frontend/src/app/pages/api-keys/allKeys/ApiKeysToolbar.tsx
  • packages/maas/frontend/src/app/types/subscriptions.ts

Comment on lines +114 to +143
{isMaasAdmin && (
<ToolbarFilter
labels={filterData.username ? [filterData.username] : []}
deleteLabel={() => {
setLocalUsername('');
onUsernameChange('');
}}
categoryName="Username"
>
<SearchInput
aria-label="Filter by username"
placeholder="Filter by username"
data-testid="username-filter-input"
value={localUsername}
onChange={(_event, value) => {
setLocalUsername(value);
}}
onSearch={(_event, value) => onUsernameChange(value)}
onClear={() => {
setLocalUsername('');
onUsernameChange('');
}}
/>
</Tooltip>
</ToolbarFilter>
<Tooltip
content="Please enter the full username"
data-testid="username-filter-tooltip"
>
<SearchInput
aria-label="Filter by username"
placeholder="Filter by username"
data-testid="username-filter-input"
value={localUsername}
onChange={(_event, value) => {
setLocalUsername(value);
}}
onSearch={(_event, value) => onUsernameChange(value)}
onClear={() => {
setLocalUsername('');
onUsernameChange('');
}}
/>
</Tooltip>
</ToolbarFilter>
)}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Hidden username filter state can persist after role downgrade.

When this block unmounts, a previously set username filter can still affect requests (see packages/maas/frontend/src/app/pages/api-keys/AllApiKeysPage.tsx, Line 41), leaving users with invisible filtering and no direct clear control.

Proposed fix
 const ApiKeysToolbar: React.FC<ApiKeysToolbarProps> = ({
   setIsModalOpen,
   filterData,
   localUsername,
   setLocalUsername,
   onUsernameChange,
   onStatusToggle,
   onStatusClear,
   activeApiKeys,
   refresh,
   onClearFilters,
   isMaasAdmin,
 }) => {
   const [isStatusSelectOpen, setIsStatusSelectOpen] = React.useState(false);
+
+  React.useEffect(() => {
+    if (!isMaasAdmin && localUsername) {
+      setLocalUsername('');
+      onUsernameChange('');
+    }
+  }, [isMaasAdmin, localUsername, onUsernameChange, setLocalUsername]);

   return (
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/maas/frontend/src/app/pages/api-keys/allKeys/ApiKeysToolbar.tsx`
around lines 114 - 143, When the username filter UI unmounts the hidden state
can persist; add a useEffect inside ApiKeysToolbar that watches isMaasAdmin and
on unmount or when isMaasAdmin becomes false calls setLocalUsername('') and
onUsernameChange('') to clear any lingering filter state (use a cleanup function
or effect branch). This ensures the username filter (localUsername,
setLocalUsername, onUsernameChange) is reset whenever the ToolbarFilter block is
removed so invisible filtering cannot persist.

@openshift-ci
Copy link
Contributor

openshift-ci bot commented Mar 26, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign manaswinidas for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/cypress/cypress/tests/mocked/modelsAsAService/maasApiKeys.cy.ts`:
- Around line 96-101: The test "should not display the username filter for
non-MaaS admins" currently inherits the global beforeEach stub that returns
{allowed: true}; override that by intercepting GET /maas/api/v1/is-maas-admin to
return {allowed: false} (use cy.intercept and give it an alias), call
asProjectAdminUser(), then call apiKeysPage.visit() and cy.wait on the alias to
ensure the frontend has received the response before asserting
apiKeysPage.findFilterInput().should('not.exist') and
apiKeysPage.findUsernameFilterTooltip().should('not.exist').
🪄 Autofix (Beta)

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: Repository YAML (base), Central YAML (inherited), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: c0020bde-19e9-4e2b-84cb-916eec8991f9

📥 Commits

Reviewing files that changed from the base of the PR and between 6b3a907 and fb614bd.

📒 Files selected for processing (2)
  • packages/cypress/cypress/support/commands/odh.ts
  • packages/cypress/cypress/tests/mocked/modelsAsAService/maasApiKeys.cy.ts

@codecov
Copy link

codecov bot commented Mar 26, 2026

Codecov Report

❌ Patch coverage is 62.50000% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.46%. Comparing base (ca13601) to head (fb614bd).
⚠️ Report is 14 commits behind head on main.

Files with missing lines Patch % Lines
.../src/app/pages/api-keys/allKeys/ApiKeysToolbar.tsx 50.00% 6 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #6908      +/-   ##
==========================================
+ Coverage   64.09%   64.46%   +0.36%     
==========================================
  Files        2530     2497      -33     
  Lines       76695    76945     +250     
  Branches    19202    19106      -96     
==========================================
+ Hits        49161    49603     +442     
+ Misses      27534    27342     -192     
Files with missing lines Coverage Δ
...ackages/maas/frontend/src/app/api/subscriptions.ts 95.00% <100.00%> (ø)
...frontend/src/app/pages/api-keys/AllApiKeysPage.tsx 76.00% <ø> (ø)
.../src/app/pages/api-keys/allKeys/ApiKeysToolbar.tsx 56.25% <50.00%> (+2.91%) ⬆️

... and 102 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ca13601...fb614bd. Read the comment docs.

🚀 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.

@katieperry4
Copy link
Contributor Author

/retest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant