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
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import {
buildPermissionRule,
createDisposableArchivedDocument,
createMemoryViaApi,
getLoggedInUser,
loginAsUser,
MEMORIES_API,
Expand Down Expand Up @@ -137,6 +138,30 @@ const FULL_PERMISSION_RULE = buildPermissionRule(
['Create', 'EditAll', 'Delete', 'ViewAll']
);

// Edit and delete on contextMemory only through isOwner(), as in #38638.
const OWNER_ONLY_MEMORY_RULES = [
{
name: `cc-permission-owner-only-base-${uuid()}`,
resources: ['contextMemory'],
operations: ['Create', 'ViewBasic'],
effect: 'allow',
},
{
name: `cc-permission-owner-only-own-${uuid()}`,
resources: ['contextMemory'],
operations: ['ViewAll', 'EditAll', 'Delete'],
effect: 'allow',
condition: 'isOwner()',
},
{
name: `cc-permission-owner-only-deny-${uuid()}`,
resources: ['contextMemory'],
operations: ['All'],
effect: 'deny',
condition: '!isOwner() && !noOwner()',
},
];

// ─── Test data ───────────────────────────────────────────────────────────────

let articleEntity: KnowledgeCenterClass;
Expand Down Expand Up @@ -1743,7 +1768,9 @@ test.describe('Context Center Permissions', () => {
).toBeVisible();
});

test('user with view-only permission who owns a memory still cannot edit or delete it', async ({
// OrganizationPolicy-Owner-Rule gives every owner `All` on their memory
// (ADR:2026-10-09-data-consumers-create-context-memories).
test('user with view-only permission who owns a memory can edit and delete it through the owner rule', async ({
viewOnlyPage,
}) => {
await navigateToMemories(viewOnlyPage);
Expand All @@ -1755,22 +1782,139 @@ test.describe('Context Center Permissions', () => {
);
await ownRow.scrollIntoViewIfNeeded();
await expect(ownRow).toBeVisible();
await expect(ownRow.getByTestId('edit-memory-btn')).not.toBeVisible();
await expect(ownRow.getByTestId('edit-memory-btn')).toBeVisible();
await expect(ownRow.getByTestId('manage-button')).toBeVisible();

await ownRow.click();
const dialog = viewOnlyPage.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(
dialog.getByRole('button', { name: /^delete$/i })
).not.toBeVisible();
).toBeVisible();
await expect(
dialog.getByRole('button', { name: /^edit$/i })
).not.toBeVisible();
).toBeVisible();
await expect(
dialog.getByRole('button', { name: /^cancel$/i })
).toBeVisible();
});

test('owner whose memory edit and delete are allowed only by isOwner() rules can edit and delete their memory', async ({
browser,
}) => {
test.slow();
const { apiContext, afterAction } = await getDefaultAdminAPIContext(
browser
);
const ownerOnlyUser = new UserClass();
const memoryTitle = `CC Permission Memory Owner-Only ${uuid()}`;
const editedContent = `Edited by its owner ${uuid()}`;
let memoryId = '';
let ownerPage: Page | undefined;

try {
await ownerOnlyUser.create(apiContext, false);
await ownerOnlyUser.setCustomRulePolicy(
apiContext,
OWNER_ONLY_MEMORY_RULES,
'context-center-permission-owner-only'
);
const memory = await createMemoryViaApi(apiContext, {
name: `cc_permission_memory_owner_only_${uuid()}`,
title: memoryTitle,
question: 'Owned by the owner-only user',
answer: 'Owned by the owner-only user',
shareConfig: { visibility: 'Entity' },
owners: [{ id: ownerOnlyUser.responseData.id, type: 'user' }],
});
memoryId = memory.id;

const page = await loginAsUser(browser, ownerOnlyUser);
ownerPage = page;

await test.step('the resource level reports edit as conditional', async () => {
const { apiContext: ownerApi, afterAction: ownerAfterAction } =
await getApiContext(page);
const res = await ownerApi.get('/api/v1/permissions/contextMemory');
const { permissions } = await res.json();
await ownerAfterAction();

expect(
permissions.find(
(permission: { operation: string }) =>
permission.operation === 'EditAll'
)?.access
).toMatch(/^conditional/);
});

await navigateToMemories(page);
const row = await searchAndGetMemoryRow(page, memoryTitle, memoryId);
await row.scrollIntoViewIfNeeded();

await expect(row.getByTestId('edit-memory-btn')).toBeVisible();
await expect(row.getByTestId('manage-button')).toBeVisible();

await test.step('edits the memory from its detail view', async () => {
await row.click();
const dialog = page.getByRole('dialog');
await expect(
dialog.getByRole('button', { name: /^delete$/i })
).toBeVisible();
await dialog.getByRole('button', { name: /^edit$/i }).click();
await dialog
.getByTestId('memory-content-input')
.locator('textarea')
.fill(editedContent);

const saveResPromise = page.waitForResponse(
(res) =>
res.url().includes(`${MEMORIES_API}/${memoryId}`) &&
res.request().method() === 'PATCH'
);
await dialog.getByRole('button', { name: /^save/i }).click();
const saveRes = await saveResPromise;

expect(saveRes.status()).toBe(200);
await expect(dialog).not.toBeVisible();

const stored = await apiContext.get(`${MEMORIES_API}/${memoryId}`);

expect((await stored.json()).answer).toBe(editedContent);
});

await test.step('deletes the memory from its row', async () => {
await row.getByTestId('manage-button').click();
await page.getByTestId('delete-btn').click();

const deleteResPromise = page.waitForResponse(
(res) =>
res.url().includes(`${MEMORIES_API}/${memoryId}`) &&
res.request().method() === 'DELETE'
);
await page.getByTestId('confirm-button').click();
const deleteRes = await deleteResPromise;

expect(deleteRes.status()).toBe(200);
await expect(row).not.toBeVisible();

const gone = await apiContext.get(`${MEMORIES_API}/${memoryId}`);

expect(gone.status()).toBe(404);
});
} finally {
await ownerPage?.close();
if (memoryId) {
await apiContext
.delete(`${MEMORIES_API}/${memoryId}?hardDelete=true`)
.catch(() => undefined);
}
if (ownerOnlyUser.responseData.id) {
await ownerOnlyUser.delete(apiContext).catch(() => undefined);
}
await afterAction();
}
});

test('user with createAll permission sees Add Memory button but no row edit/delete actions or modal action buttons, and can create a memory', async ({
createAllPage,
browser,
Expand Down Expand Up @@ -1885,9 +2029,10 @@ test.describe('Context Center Permissions', () => {
await ownRow.getByTestId('edit-memory-btn').click();
const dialog = editAllPage.getByRole('dialog');
await expect(dialog).toBeVisible();
// Delete on their own memory comes from OrganizationPolicy-Owner-Rule.
await expect(
dialog.getByRole('button', { name: /^delete$/i })
).not.toBeVisible();
).toBeVisible();
await expect(
dialog.getByRole('button', { name: /^(save|create)/i })
).toBeVisible();
Expand Down Expand Up @@ -1933,14 +2078,15 @@ test.describe('Context Center Permissions', () => {
);
await ownRow.scrollIntoViewIfNeeded();
await expect(ownRow).toBeVisible();
await expect(ownRow.getByTestId('edit-memory-btn')).not.toBeVisible();
// Edit on their own memory comes from OrganizationPolicy-Owner-Rule.
await expect(ownRow.getByTestId('edit-memory-btn')).toBeVisible();

await ownRow.click();
const dialog = deleteAllPage.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(
dialog.getByRole('button', { name: /^edit$/i })
).not.toBeVisible();
).toBeVisible();
await expect(
dialog.getByRole('button', { name: /^delete$/i })
).toBeVisible();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ import {
ContextMemory,
EntityReference,
} from '../../../generated/entity/context/contextMemory';
import {
MemoryActionPermissions,
NO_MEMORY_ACTIONS,
} from '../../../hooks/discovery/context-center/useMemoryActionPermissions';
import { getShortRelativeTime } from '../../../utils/date-time/DateTimeUtils';
import { getEntityName } from '../../../utils/EntityNameUtils';
import { stripMarkdown } from '../../../utils/StringUtils';
Expand Down Expand Up @@ -115,11 +119,8 @@ const MemoryRowSkeleton: FC = () => (
);

interface MemoryRowProps {
currentUserName?: string;
isAdminUser?: boolean;
memory: ContextMemory;
canEdit?: boolean;
canDelete?: boolean;
actions: MemoryActionPermissions;
onDeleteMemory?: (memory: ContextMemory) => void;
onEditMemory?: (memory: ContextMemory) => void;
onTogglePin?: (memory: ContextMemory) => void;
Expand All @@ -128,18 +129,12 @@ interface MemoryRowProps {
}

const MemoryRow: FC<MemoryRowProps> = ({
currentUserName,
isAdminUser,
actions,
memory,
canEdit,
canDelete,
onDeleteMemory,
onEditMemory,
onViewMemory,
}) => {
const isOwner =
memory.owners?.some((owner) => owner.name === currentUserName) ?? false;
const canActOnMemory = isOwner || Boolean(isAdminUser);
const { t } = useTranslation();
const memoryUrl = useMemo(
() =>
Expand Down Expand Up @@ -292,7 +287,7 @@ const MemoryRow: FC<MemoryRowProps> = ({
<CopyLinkButton url={memoryUrl}>
<CopyIcon aria-hidden="true" height={20} width={20} />
</CopyLinkButton>
{canActOnMemory && canEdit && onEditMemory && (
{actions.canEdit && onEditMemory && (
<Tooltip title={t('label.edit')}>
<TooltipTrigger>
<ButtonUtility
Expand All @@ -305,7 +300,7 @@ const MemoryRow: FC<MemoryRowProps> = ({
</TooltipTrigger>
</Tooltip>
)}
{canActOnMemory && canDelete && (
{actions.canDelete && (
<MemoryActions memory={memory} onDeleteMemory={onDeleteMemory} />
)}
</Box>
Expand All @@ -315,14 +310,11 @@ const MemoryRow: FC<MemoryRowProps> = ({
};

const MemoriesView: FC<MemoriesViewProps> = ({
currentUserName,
data,
isAdminUser,
getMemoryActions = () => NO_MEMORY_ACTIONS,
isLoading,
onDeleteMemory,
onEditMemory,
canEdit,
canDelete,
isPinningMemoryId,
onTogglePin,
onViewMemory,
Expand Down Expand Up @@ -384,10 +376,7 @@ const MemoriesView: FC<MemoriesViewProps> = ({
<>
{data.map((memory) => (
<MemoryRow
canDelete={canDelete}
canEdit={canEdit}
currentUserName={currentUserName}
isAdminUser={isAdminUser}
actions={getMemoryActions(memory)}
isPinningMemoryId={isPinningMemoryId}
key={memory.id}
memory={memory}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* limitations under the License.
*/
import { ContextMemory } from '../../../generated/entity/context/contextMemory';
import { MemoryActionPermissions } from '../../../hooks/discovery/context-center/useMemoryActionPermissions';

export type MemoryFilterTab =
| ''
Expand All @@ -24,10 +25,8 @@ export type MemorySortBy = 'updated' | 'created' | 'usage' | 'updatedBy';
export interface MemoriesViewProps {
data: ContextMemory[];
isLoading: boolean;
currentUserName?: string;
isAdminUser?: boolean;
canEdit?: boolean;
canDelete?: boolean;
/** Edit and Delete a row offers; a row without them offers neither. */
getMemoryActions?: (memory: ContextMemory) => MemoryActionPermissions;
onDeleteMemory?: (memory: ContextMemory) => void;
onEditMemory?: (memory: ContextMemory) => void;
onTogglePin?: (memory: ContextMemory) => void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, screen } from '@testing-library/react';
import { render, screen, within } from '@testing-library/react';
import { ContextMemory } from '../../../generated/entity/context/contextMemory';
import MemoriesView from './MemoriesView.component';

Expand Down Expand Up @@ -154,4 +154,43 @@ describe('MemoriesView', () => {
expect(screen.getAllByTestId('skeleton').length).toBeGreaterThan(0);
expect(screen.queryByTestId('error-placeholder')).not.toBeInTheDocument();
});

it('shows edit and delete only on rows getMemoryActions allows', () => {
render(
<MemoriesView
data={mockMemories}
getMemoryActions={(memory) => ({
canEdit: memory.id === 'mem-1',
canDelete: memory.id === 'mem-2',
})}
isLoading={false}
onEditMemory={jest.fn()}
/>
);

const editableRow = within(screen.getByTestId('memory-row-mem-1'));
const deletableRow = within(screen.getByTestId('memory-row-mem-2'));

expect(editableRow.getByTestId('edit-memory-btn')).toBeInTheDocument();
expect(editableRow.queryByTestId('manage-button')).not.toBeInTheDocument();
expect(deletableRow.getByTestId('manage-button')).toBeInTheDocument();
expect(
deletableRow.queryByTestId('edit-memory-btn')
).not.toBeInTheDocument();
});

it('shows no edit or delete without getMemoryActions', () => {
render(
<MemoriesView
data={mockMemories}
isLoading={false}
onEditMemory={jest.fn()}
/>
);

const row = within(screen.getByTestId('memory-row-mem-1'));

expect(row.queryByTestId('edit-memory-btn')).not.toBeInTheDocument();
expect(row.queryByTestId('manage-button')).not.toBeInTheDocument();
});
});
Loading
Loading