Skip to content
Open
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 apps/meteor/client/providers/AuthorizationProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ const AuthorizationProvider = ({ children }: AuthorizationProviderProps) => {
],
getRoles: () => Roles.state.records,
subscribeToRoles: (callback) => Roles.use.subscribe(callback),
getPermission: (permissionId: string) => Permissions.state.get(permissionId),
}),
[auth, userId],
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import {
FieldRow,
FieldHint,
} from '@rocket.chat/fuselage';
import { useAbsoluteUrl } from '@rocket.chat/ui-contexts';
import { UserAutoComplete } from '@rocket.chat/ui-client';
import { useAbsoluteUrl, useGetPermission } from '@rocket.chat/ui-contexts';
import DOMPurify from 'dompurify';
import { useId, useMemo } from 'react';
import { Controller, useFormContext } from 'react-hook-form';
Expand All @@ -33,6 +34,7 @@ export type IncomingWebhookFormProps = { webhookData?: Serialized<IIncomingInteg
const IncomingWebhookForm = ({ webhookData }: IncomingWebhookFormProps) => {
const { t } = useTranslation();
const absoluteUrl = useAbsoluteUrl();
const permission = useGetPermission('message-impersonate');

const {
control,
Expand Down Expand Up @@ -202,10 +204,10 @@ const IncomingWebhookForm = ({ webhookData }: IncomingWebhookFormProps) => {
control={control}
rules={{ required: t('Required_field', { field: t('Post_as') }) }}
render={({ field }) => (
<TextInput
<UserAutoComplete
id={usernameField}
{...field}
endAddon={<Icon name='user' size='x20' />}
conditions={permission?.roles ? { roles: { $in: permission.roles } } : undefined}
Comment on lines +207 to +210

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Fail closed when the permission lookup is unavailable.

When permission is undefined, conditions is also undefined; UserAutoComplete then sends an empty conditions object and returns an unrestricted user list. That defeats the message-impersonate filter and can expose/select users who should not be eligible. Use an empty role set or gate the field until permission metadata is available, and keep server-side authorization authoritative.

🤖 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 `@apps/meteor/client/views/admin/integrations/incoming/IncomingWebhookForm.tsx`
around lines 207 - 210, Update the UserAutoComplete conditions in the incoming
webhook form to fail closed when permission metadata is unavailable: provide an
empty roles filter instead of undefined, or disable/gate the field until
permission is loaded. Preserve the existing permission.roles filter when
available, with server-side authorization remaining authoritative.

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.

P1: Users granted only incoming-integration management get a 400 from users.autocomplete, leaving “Post as” with no suggestions, because roles is not an allowed autocomplete condition without view-full-other-user-info. Use a server-supported filtered lookup/allow this condition for this authorized workflow rather than issuing this selector from the generic endpoint.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/admin/integrations/incoming/IncomingWebhookForm.tsx, line 210:

<comment>Users granted only incoming-integration management get a 400 from `users.autocomplete`, leaving “Post as” with no suggestions, because `roles` is not an allowed autocomplete condition without `view-full-other-user-info`. Use a server-supported filtered lookup/allow this condition for this authorized workflow rather than issuing this selector from the generic endpoint.</comment>

<file context>
@@ -202,10 +204,10 @@ const IncomingWebhookForm = ({ webhookData }: IncomingWebhookFormProps) => {
 											id={usernameField}
 											{...field}
-											endAddon={<Icon name='user' size='x20' />}
+											conditions={permission?.roles ? { roles: { $in: permission.roles } } : undefined}
 											aria-describedby={`${usernameField}-hint-1 ${usernameField}-hint-2 ${usernameField}-error`}
 											aria-required={true}
</file context>

aria-describedby={`${usernameField}-hint-1 ${usernameField}-hint-2 ${usernameField}-error`}
aria-required={true}
aria-invalid={Boolean(errors?.username)}
Expand Down
7 changes: 6 additions & 1 deletion apps/meteor/server/api/lib/isValidQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ const verifyQuery = (query: Query, allowedAttributes: string[], allowedOperation
}

if (Array.isArray(value)) {
return value.every((v) => verifyQuery(v, allowedAttributes, allowedOperations));
return value.every((v) => {
if (isRecord(v)) {
return verifyQuery(v, allowedAttributes, allowedOperations);
}
return true;
});
}

if (isRecord(value)) {
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/api/v1/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1699,7 +1699,7 @@ API.v1.get(
const canViewFullInfo = await hasPermissionAsync(this.userId, 'view-full-other-user-info');
const allowedFields = canViewFullInfo ? [...Object.keys(defaultFields), ...Object.keys(fullFields)] : Object.keys(defaultFields);

if (!isValidQuery(selector.conditions, allowedFields, ['$and', '$ne', '$exists'])) {
if (!isValidQuery(selector.conditions, allowedFields, ['$and', '$ne', '$exists', '$in'])) {
throw new Error('error-invalid-query');
}
}
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/tests/e2e/administration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ test.describe.parallel('administration', () => {
await poAdminIntegrations.btnNew.click();
await poAdminIntegrations.inputName.fill(incomingIntegrationName);
await poAdminIntegrations.inputPostToChannel.fill('#general');
await poAdminIntegrations.inputPostAs.fill('rocket.cat');
await poAdminIntegrations.selectPostAs('rocket.cat');
await poAdminIntegrations.btnSave.click();

await expect(poAdminIntegrations.inputWebhookUrl).not.toHaveValue('Will be available here after saving.');
Expand Down
10 changes: 10 additions & 0 deletions apps/meteor/tests/e2e/page-objects/admin-integrations.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import type { Locator, Page } from '@playwright/test';

import { Admin } from './admin';
import { Listbox } from './fragments/listbox';

export class AdminIntegrations extends Admin {
readonly listbox: Listbox;

constructor(page: Page) {
super(page);
this.listbox = new Listbox(page);
}

get btnInstructions(): Locator {
Expand All @@ -27,6 +31,12 @@ export class AdminIntegrations extends Admin {
return this.page.getByRole('textbox', { name: 'Post as' });
}

async selectPostAs(name: string) {
await this.inputPostAs.click();
await this.inputPostAs.fill(name);
await this.listbox.selectOption(name);
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
getIntegrationByName(name: string): Locator {
return this.page.getByRole('table', { name: 'Integrations table' }).locator('tr', { hasText: name });
}
Expand Down
24 changes: 24 additions & 0 deletions apps/meteor/tests/end-to-end/api/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5642,6 +5642,30 @@ describe('[Users]', () => {
expect(res.body).to.have.property('status', 'error');
});
});

it('should filter results when using allowed $in operator', (done) => {
void request
.get(api('users.autocomplete'))
.set(credentials)
.query({
selector: JSON.stringify({
conditions: {
roles: {
$in: ['bot'],
},
},
}),
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);

expect(res.body).to.have.property('items').and.to.be.an('array').with.lengthOf(1);
expect(res.body.items[0]).to.have.property('username', 'rocket.cat');
})
.end(done);
});
});

describe('[/users.getStatus]', () => {
Expand Down
12 changes: 12 additions & 0 deletions apps/meteor/tests/unit/server/api/lib/isValidQuery.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,16 @@ describe('isValidQuery', () => {
expect(isValidQuery.errors.length).to.be.equals(1);
});
});

describe('primitive values in query array', () => {
it('should return true if the query contains primitive array', () => {
const props = ['roles'];
const allowedOps = ['$in'];
const query = {
roles: { $in: ['admin', 'user'] },
};
expect(isValidQuery(query, props, allowedOps)).to.be.true;
expect(isValidQuery.errors.length).to.be.equals(0);
});
});
});
1 change: 1 addition & 0 deletions packages/mock-providers/src/MockedAppRootBuilder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ export class MockedAppRootBuilder {
queryRole: () => [() => () => undefined, () => false],
getRoles: () => dummyRolesMap,
subscribeToRoles: () => () => undefined,
getPermission: () => undefined,
};
})();

Expand Down
1 change: 1 addition & 0 deletions packages/mock-providers/src/MockedAuthorizationContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const MockedAuthorizationContext = ({
queryRole: (id: string) => [() => (): void => undefined, (): boolean => roles.includes(id)],
getRoles: () => dummyRolesMap,
subscribeToRoles: (): (() => void) => (): void => undefined,
getPermission: () => undefined,
}}
>
{children}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,14 @@ const UserAutoComplete = ({ value, onChange, ...props }: UserAutoCompleteProps)
queryFn: async () => usersAutoCompleteEndpoint(query(debouncedFilter, conditions)),
});

const options = useMemo(() => data?.items.map((user) => ({ value: user.username, label: user.name || user.username })) || [], [data]);
const options = useMemo(() => {
const items = data?.items.map((user) => ({ value: user.username, label: user.name || user.username })) ?? [];

const selectedValues = ([] as string[]).concat(value ?? []);
const missing = selectedValues.filter((v) => !items.some((item) => item.value === v)).map((v) => ({ value: v, label: v }));

return [...items, ...missing];
}, [data, value]);

return (
<AutoComplete
Expand Down
4 changes: 3 additions & 1 deletion packages/ui-contexts/src/AuthorizationContext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IRole, IRoom } from '@rocket.chat/core-typings';
import type { IRole, IRoom, IPermission } from '@rocket.chat/core-typings';
import type { ObjectId } from 'mongodb';
import { createContext } from 'react';

Expand All @@ -24,6 +24,7 @@ export type AuthorizationContextValue = {
): [subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => boolean];
getRoles(): ReadonlyMap<IRole['_id'], IRole>;
subscribeToRoles(callback: () => void): () => void;
getPermission(permissionId: string): IPermission | undefined;
};

const dummyRolesMap: ReadonlyMap<IRole['_id'], IRole> = new Map();
Expand All @@ -35,4 +36,5 @@ export const AuthorizationContext = createContext<AuthorizationContextValue>({
queryRole: () => [() => (): void => undefined, (): boolean => false],
getRoles: (): ReadonlyMap<IRole['_id'], IRole> => dummyRolesMap,
subscribeToRoles: (): (() => void) => (): void => undefined,
getPermission: (): IPermission | undefined => undefined,
});
10 changes: 10 additions & 0 deletions packages/ui-contexts/src/hooks/useGetPermission.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { IPermission } from '@rocket.chat/core-typings';
import { useContext } from 'react';

import { AuthorizationContext } from '../AuthorizationContext';

export const useGetPermission = (permission: string): IPermission | undefined => {
const { getPermission } = useContext(AuthorizationContext);

return getPermission(permission);
};
1 change: 1 addition & 0 deletions packages/ui-contexts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,4 @@ export { useMediaDeviceMicrophonePermission } from './hooks/useMediaDevicePermis
export { useWriteStream } from './hooks/useWriteStream';
export { useUserCard } from './hooks/useUserCard';
export type { SubscriptionWithRoom } from './types/SubscriptionWithRoom';
export { useGetPermission } from './hooks/useGetPermission';
Loading