Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/custom/permissions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,7 @@ export const createCanShow = (
// Re-export PermissionProvider types and hooks
export {
PermissionProvider,
getPermissionKeys,
isPermissionKeySet,
useHasPermission,
usePermission,
Expand Down
172 changes: 172 additions & 0 deletions src/custom/useAccessibleOrgs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { useLazyGetUserKeysQuery } from '@meshery/schemas/cloudApi';
import { Key } from '@meshery/schemas/permissions';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getPermissionKeys, isPermissionKeySet, PermissionKeySpec } from './PermissionProvider';

/**
* For a given set of user keys (as returned by `getUserKeys`), check whether
* the `permissionKey` spec is satisfied.
*
* Uses case-insensitive comparison on the `function` field, matching the
* `canKey` pattern in host applications.
*/
const orgHasPermission = (
orgKeys: Array<{ id: string; function: string }>,
spec: PermissionKeySpec
): boolean => {
const userHasKey = (key: Key) =>
orgKeys.some(
(k) => k.id === key.id && k.function?.toLowerCase() === key.function?.toLowerCase()
);

if (!isPermissionKeySet(spec)) {
return userHasKey(spec);
}

const keys = getPermissionKeys(spec);
if (keys.length === 0) return false;

const specObj = spec as { anyOf?: Key[] };
if ('anyOf' in specObj) {
return keys.some(userHasKey);
}
return keys.every(userHasKey);
};

/** Type guard: narrows any object with an optional `id` to one with a definite `id`. */
const hasDefiniteId = <T extends { id?: string }>(org: T): org is T & { id: string } =>
Boolean(org.id);

/**
* Configuration for `useAccessibleOrgs`.
*
* The hook does NOT read orgs or the current org from any global store — both
* are supplied by the host application so the hook stays framework-agnostic.
*
* Generic over `T` so the element type of `allOrgs` flows through to
* `accessibleOrgs` — callers keep `org.name`, `org.avatar`, etc. typed.
*/
export interface UseAccessibleOrgsOptions<T extends { id?: string } = { id?: string }> {
/** All organizations the user belongs to (e.g. from `useGetOrgsQuery`). */
allOrgs?: T[];

/** The id of the organization the user is currently in. Excluded from results. */
currentOrgId?: string;

/** Whether the org list has finished loading. */
orgsLoaded: boolean;

/** The permission key (or key set) to check each org against. */
permissionKey?: PermissionKeySpec;
}

/**
* Returns only those organizations where the user holds the permission(s)
* described by `permissionKey`. The current org is excluded from the result
* since the user is already on the 403 page for it.
*
* Queries `/api/identity/orgs/:orgId/users/keys` for each org in parallel
* via `useLazyGetUserKeysQuery`. This is a 403-page-only hook — the N
* parallel requests are acceptable because this page is not a hot path.
*
* @example
* ```tsx
* // In meshery-cloud
* const { data: allOrgs, isSuccess } = useGetActiveOrgs();
* const currentOrg = useSelector(selectCurrentOrg);
* const { accessibleOrgs, isLoading } = useAccessibleOrgs({
* allOrgs,
* currentOrgId: currentOrg?.id,
* orgsLoaded: isSuccess,
* permissionKey,
* });
* ```
*/
export const useAccessibleOrgs = <T extends { id?: string }>({
allOrgs,
currentOrgId,
orgsLoaded,
permissionKey
}: UseAccessibleOrgsOptions<T>) => {
const [triggerGetKeys] = useLazyGetUserKeysQuery();

// Track which orgs have been checked and their results.
// Map<orgId, hasPermission>
const [checkedOrgs, setCheckedOrgs] = useState<Map<string, boolean>>(new Map());
const [isChecking, setIsChecking] = useState(false);

// Stable ref to avoid re-triggering the effect on every state update
const checkedRef = useRef<Set<string>>(new Set());
Comment on lines +95 to +99

@coderabbitai coderabbitai Bot Aug 12, 2026

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Invalidate permission results when the permission requirement changes.

checkedRef and checkedOrgs are keyed only by organization ID. When permissionKey changes, Line 107 suppresses new requests for already checked organizations. The hook can then return access results for the previous permission requirement.

Associate each request batch with its permission requirement. Clear the result cache when that requirement changes. Ignore results from an older batch after a newer requirement becomes active. Keep isChecking scoped to the active batch.

Also applies to: 101-137

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

In `@src/custom/useAccessibleOrgs.ts` around lines 95 - 99, Update the
permission-checking flow in useAccessibleOrgs, including the effect around
checkedRef and the request logic around lines 101-137, to associate cached
results and each request batch with the current permissionKey. Clear checkedRef
and checkedOrgs when permissionKey changes, ignore responses belonging to older
batches, and ensure isChecking is updated only for the active batch.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch in theory, but in practice permissionKey is set once from the 403 page's permission shield and never changes during the component lifecycle. The useCallback dep array already includes permissionKey so if it did change, the effect re-fires. That said, I'll add a reset of checkedRef when permissionKey changes for correctness doesn't hurt.

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.

@rishiraj38, agreed. The 403-page lifecycle makes this low risk in the current caller.

If permissionKey can change, reset both checkedRef and checkedOrgs. Also guard in-flight responses so an older request cannot populate the cache after the new requirement becomes active. Resetting only checkedRef can still expose results from the previous requirement.

🐇


✏️ Learnings added
Learnt from: rishiraj38
Repo: layer5io/sistent PR: 1793
File: src/custom/useAccessibleOrgs.ts:95-99
Timestamp: 2026-08-12T19:55:05.061Z
Learning: In layer5io/sistent, `useAccessibleOrgs` is currently used from the 403-page permission shield, where `permissionKey` is normally fixed for the component lifecycle.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: CR
Repo: layer5io/sistent PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-08-04T18:30:58.858Z
Learning: Applies to src/**/*.{ts,tsx} : Use the `Key` interface from `meshery/schemas/permissions`; do not define local permission keys or use/re-export generated `Keys` or `PermissionKeys` maps.

You are interacting with an AI system.


// Reset caches when the permission requirement changes so stale results
// from a previous key are never served.
useEffect(() => {
checkedRef.current.clear();
setCheckedOrgs(new Map());
}, [permissionKey]);

const checkOrgs = useCallback(async () => {
if (!allOrgs || !orgsLoaded || !permissionKey) return;

// Only check orgs we haven't already checked
const orgsToCheck = allOrgs
.filter(hasDefiniteId)
.filter((org) => org.id !== currentOrgId && !checkedRef.current.has(org.id));

if (orgsToCheck.length === 0) return;

setIsChecking(true);

// Mark these as being checked to prevent duplicate requests
orgsToCheck.forEach((org) => checkedRef.current.add(org.id));

// Fire all queries in parallel
const results = await Promise.allSettled(
orgsToCheck.map(async (org) => {
const result = await triggerGetKeys({ orgId: org.id }).unwrap();
const keys = result?.keys ?? [];
return { orgId: org.id, hasPermission: orgHasPermission(keys, permissionKey) };
})
);

setCheckedOrgs((prev) => {
const next = new Map(prev);
for (const [index, r] of results.entries()) {
const orgId = orgsToCheck[index].id;
if (r.status === 'fulfilled') {
next.set(orgId, r.value.hasPermission);
} else {
// On failure, record as inaccessible so isReady can still resolve
next.set(orgId, false);
}
}
return next;
});

setIsChecking(false);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}, [allOrgs, orgsLoaded, permissionKey, currentOrgId, triggerGetKeys]);

useEffect(() => {
checkOrgs();
}, [checkOrgs]);

const accessibleOrgs = useMemo(() => {
if (!allOrgs) return [];
return allOrgs
.filter(hasDefiniteId)
.filter((org) => org.id !== currentOrgId && checkedOrgs.get(org.id) === true);
}, [allOrgs, currentOrgId, checkedOrgs]);

const otherOrgs = (allOrgs ?? [])
.filter(hasDefiniteId)
.filter((org) => org.id !== currentOrgId);

const isReady = orgsLoaded && !isChecking && otherOrgs.every((org) => checkedOrgs.has(org.id));

return {
accessibleOrgs,
isReady,
isLoading: !orgsLoaded || isChecking,
hasNoAccessibleOrgs: isReady && accessibleOrgs.length === 0
};
};
5 changes: 5 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export {
PermissionProvider,
PermissionSessionContext,
PermissionShield,
getPermissionKeys,
isPermissionKeySet,
useHasPermission,
usePermission,
Expand All @@ -91,6 +92,10 @@ export {
type PermissionUserContext
} from './custom/permissions';

export {
useAccessibleOrgs,
type UseAccessibleOrgsOptions
} from './custom/useAccessibleOrgs';
export { BottomSheet, type BottomSheetProps } from './custom/BottomSheet';

export { ActionButton, type ActionButtonProps, type Option } from './custom/ActionButton';
Expand Down
Loading