Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ResponseOps][Cases] Get reporters and tags by aggregation #123362

Merged
merged 7 commits into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
56 changes: 10 additions & 46 deletions x-pack/plugins/cases/server/client/cases/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,34 +329,18 @@ export async function getTags(
fold(throwErrors(Boom.badRequest), identity)
);

const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } =
await authorization.getAuthorizationFilter(Operations.findCases);
const { filter: authorizationFilter } = await authorization.getAuthorizationFilter(
Operations.findCases
);

const filter = combineAuthorizedAndOwnerFilter(queryParams.owner, authorizationFilter);

const cases = await caseService.getTags({
const tags = await caseService.getTags({
unsecuredSavedObjectsClient,
filter,
});

const tags = new Set<string>();
const mappedCases: Array<{
owner: string;
id: string;
}> = [];

// Gather all necessary information in one pass
cases.saved_objects.forEach((theCase) => {
theCase.attributes.tags.forEach((tag) => tags.add(tag));
mappedCases.push({
id: theCase.id,
owner: theCase.attributes.owner,
});
});

ensureSavedObjectsAreAuthorized(mappedCases);

return [...tags.values()];
return tags;
} catch (error) {
throw createCaseError({ message: `Failed to get tags: ${error}`, error, logger });
}
Expand All @@ -377,38 +361,18 @@ export async function getReporters(
fold(throwErrors(Boom.badRequest), identity)
);

const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } =
await authorization.getAuthorizationFilter(Operations.getReporters);
const { filter: authorizationFilter } = await authorization.getAuthorizationFilter(
Operations.getReporters
);

const filter = combineAuthorizedAndOwnerFilter(queryParams.owner, authorizationFilter);

const cases = await caseService.getReporters({
const reporters = await caseService.getReporters({
unsecuredSavedObjectsClient,
filter,
});

const reporters = new Map<string, User>();
const mappedCases: Array<{
owner: string;
id: string;
}> = [];

// Gather all necessary information in one pass
cases.saved_objects.forEach((theCase) => {
const user = theCase.attributes.created_by;
if (user.username != null) {
reporters.set(user.username, user);
}

mappedCases.push({
id: theCase.id,
owner: theCase.attributes.owner,
});
});

ensureSavedObjectsAreAuthorized(mappedCases);

return UsersRt.encode([...reporters.values()]);
return reporters;
} catch (error) {
throw createCaseError({ message: `Failed to get reporters: ${error}`, error, logger });
}
Expand Down
67 changes: 56 additions & 11 deletions x-pack/plugins/cases/server/services/cases/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1021,37 +1021,82 @@ export class CasesService {
public async getReporters({
unsecuredSavedObjectsClient,
filter,
}: GetReportersArgs): Promise<SavedObjectsFindResponse<ESCaseAttributes>> {
}: GetReportersArgs): Promise<User[]> {
try {
this.log.debug(`Attempting to GET all reporters`);

return await unsecuredSavedObjectsClient.find<ESCaseAttributes>({
const results = await unsecuredSavedObjectsClient.find<
ESCaseAttributes,
{
reporters: {
buckets: Array<{
key: string;
top_docs: { hits: { hits: Array<{ _source: { cases: { created_by: User } } }> } };
}>;
};
}
>({
type: CASE_SAVED_OBJECT,
fields: ['created_by', OWNER_FIELD],
page: 1,
perPage: MAX_DOCS_PER_PAGE,
perPage: 1,
filter,
aggs: {
reporters: {
terms: {
field: `${CASE_SAVED_OBJECT}.attributes.created_by.username`,
size: MAX_DOCS_PER_PAGE,
},
aggs: {
top_docs: {
top_hits: {
size: 1,
cnasikas marked this conversation as resolved.
Show resolved Hide resolved
},
},
},
},
},
});

return (
// eslint-disable-next-line @typescript-eslint/naming-convention
results?.aggregations?.reporters?.buckets.map(({ key, top_docs }) => {
const user = top_docs?.hits?.hits?.[0]?._source?.cases?.created_by ?? {};
return {
username: key,
full_name: user.full_name ?? null,
email: user.email ?? null,
};
}) ?? []
);
} catch (error) {
this.log.error(`Error on GET all reporters: ${error}`);
throw error;
}
}

public async getTags({
unsecuredSavedObjectsClient,
filter,
}: GetTagsArgs): Promise<SavedObjectsFindResponse<ESCaseAttributes>> {
public async getTags({ unsecuredSavedObjectsClient, filter }: GetTagsArgs): Promise<string[]> {
try {
this.log.debug(`Attempting to GET all cases`);

return await unsecuredSavedObjectsClient.find<ESCaseAttributes>({
const results = await unsecuredSavedObjectsClient.find<
ESCaseAttributes,
{ tags: { buckets: Array<{ key: string }> } }
>({
type: CASE_SAVED_OBJECT,
fields: ['tags', OWNER_FIELD],
page: 1,
perPage: MAX_DOCS_PER_PAGE,
perPage: 1,
filter,
aggs: {
tags: {
terms: {
field: `${CASE_SAVED_OBJECT}.attributes.tags`,
size: MAX_DOCS_PER_PAGE,
},
},
},
});

return results?.aggregations?.tags?.buckets.map(({ key }) => key) ?? [];
} catch (error) {
this.log.error(`Error on GET tags: ${error}`);
throw error;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,17 @@ export default ({ getService }: FtrProviderContext): void => {
for (const scenario of [
{
user: globalRead,
expectedReporters: [getUserInfo(secOnly), getUserInfo(obsOnly)],
expectedReporters: [getUserInfo(obsOnly), getUserInfo(secOnly)],
},
{
user: superUser,
expectedReporters: [getUserInfo(secOnly), getUserInfo(obsOnly)],
expectedReporters: [getUserInfo(obsOnly), getUserInfo(secOnly)],
},
{ user: secOnlyRead, expectedReporters: [getUserInfo(secOnly)] },
{ user: obsOnlyRead, expectedReporters: [getUserInfo(obsOnly)] },
{
user: obsSecRead,
expectedReporters: [getUserInfo(secOnly), getUserInfo(obsOnly)],
expectedReporters: [getUserInfo(obsOnly), getUserInfo(secOnly)],
},
]) {
const reporters = await getReporters({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,17 @@ export default ({ getService }: FtrProviderContext): void => {
for (const scenario of [
{
user: globalRead,
expectedTags: ['sec', 'obs'],
expectedTags: ['obs', 'sec'],
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's try adding a sort to the aggregation to see if we can get the sorting consistent:

"order": { "_key": "asc" }

Copy link
Member Author

Choose a reason for hiding this comment

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

I added the _key. I am gonna leave the change of order of values in the tests as obs preceding sec alphabetically.

},
{
user: superUser,
expectedTags: ['sec', 'obs'],
expectedTags: ['obs', 'sec'],
},
{ user: secOnlyRead, expectedTags: ['sec'] },
{ user: obsOnlyRead, expectedTags: ['obs'] },
{
user: obsSecRead,
expectedTags: ['sec', 'obs'],
expectedTags: ['obs', 'sec'],
},
]) {
const tags = await getTags({
Expand Down