Skip to content

Commit

Permalink
moar
Browse files Browse the repository at this point in the history
  • Loading branch information
pgayvallet committed Oct 14, 2023
1 parent 7ebde8e commit 264c2db
Show file tree
Hide file tree
Showing 15 changed files with 90 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ export async function ensureAuthorized<T extends string>(

// Neither fully nor partially authorized. Bail with error.
const uniqueUnauthorizedPrivileges = [...missingPrivileges.entries()].reduce(
(acc, [, privilegeSet]) => new Set([...acc, ...privilegeSet]),
(acc, [, privilegeSet]) => {
privilegeSet.forEach(acc.add);
return acc;
},
new Set<string>()
);
const targetTypesAndActions = [...uniqueUnauthorizedPrivileges]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,13 @@ export class SecureSpacesClientWrapper implements ISpacesClient {

// Collect all privileges which need to be checked
const allPrivileges = Object.entries(PURPOSE_PRIVILEGE_MAP).reduce(
(acc, [getSpacesPurpose, privilegeFactory]) =>
!includeAuthorizedPurposes && getSpacesPurpose !== purpose
? acc
: { ...acc, [getSpacesPurpose]: privilegeFactory(this.authorization) },
(acc, [getSpacesPurpose, privilegeFactory]) => {
if (!includeAuthorizedPurposes && getSpacesPurpose !== purpose) {
return acc;
}
acc[getSpacesPurpose as GetAllSpacesPurpose] = privilegeFactory(this.authorization);
return acc;
},
{} as Record<GetAllSpacesPurpose, string[]>
);

Expand Down Expand Up @@ -117,7 +120,8 @@ export class SecureSpacesClientWrapper implements ISpacesClient {
const requiredActions = privilegeFactory(this.authorization);
const hasAllRequired = checkHasAllRequired(space, requiredActions);
hasAnyAuthorization = hasAnyAuthorization || hasAllRequired;
return { ...acc, [purposeKey]: hasAllRequired };
acc[purposeKey as GetAllSpacesPurpose] = hasAllRequired;
return acc;
},
{} as Record<GetAllSpacesPurpose, boolean>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,10 @@ export function registerSecurityUsageCollector({ usageCollection, config, licens
const authProviderCount = config.authc.sortedProviders.length;
const enabledAuthProviders = [
...new Set(
config.authc.sortedProviders.reduce(
(acc, provider) => [...acc, provider.type],
[] as string[]
)
config.authc.sortedProviders.reduce((acc, provider) => {
acc.push(provider.type);
return acc;
}, [] as string[])
),
];
const accessAgreementEnabled =
Expand Down
17 changes: 12 additions & 5 deletions x-pack/plugins/security_solution/common/utils/sourcerer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@
*/
export const sortWithExcludesAtEnd = (indices: string[]) => {
const allSorted = indices.reduce(
(acc: { includes: string[]; excludes: string[] }, index) =>
index.trim().startsWith('-')
? { includes: acc.includes, excludes: [...acc.excludes, index] }
: { includes: [...acc.includes, index], excludes: acc.excludes },
(acc: { includes: string[]; excludes: string[] }, index) => {
if (index.trim().startsWith('-')) {
acc.excludes.push(index);
} else {
acc.includes.push(index);
}
return acc;
},
{ includes: [], excludes: [] }
);
return [...allSorted.includes.sort(), ...allSorted.excludes.sort()];
Expand All @@ -18,6 +22,9 @@ export const sortWithExcludesAtEnd = (indices: string[]) => {
export const ensurePatternFormat = (patternList: string[]): string[] =>
sortWithExcludesAtEnd([
...new Set(
patternList.reduce((acc: string[], pattern: string) => [...pattern.split(','), ...acc], [])
patternList.reduce((acc: string[], pattern: string) => {
acc.unshift(...pattern.split(','));
return acc;
}, [])
),
]);
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface OutputError {
message: string;
statusCode: number;
}

export interface BulkError {
// Id can be single id or stringified ids.
id?: string;
Expand Down Expand Up @@ -193,6 +194,7 @@ export const convertToSnakeCase = <T extends Record<string, unknown>>(
}
return Object.keys(obj).reduce((acc, item) => {
const newKey = snakeCase(item);
return { ...acc, [newKey]: obj[item] };
(acc as Record<string, unknown>)[newKey] = obj[item];
return acc;
}, {});
};
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,10 @@ export const formatSortForBucketSort = (sort: estypes.Sort) => {
*/
export const formatSortForTermsSort = (sort: estypes.Sort) => {
return (sort as estypes.SortCombinations[]).map((s) =>
Object.keys(s).reduce(
(acc, curr) => ({ ...acc, [SORT_FIELD_TO_AGG_MAPPING[curr]]: get(s, `${curr}.order`) }),
{}
)
Object.keys(s).reduce((acc, curr) => {
(acc as Record<string, unknown>)[SORT_FIELD_TO_AGG_MAPPING[curr]] = get(s, `${curr}.order`);
return acc;
}, {})
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ export const wrapSequencesFactory =
publicBaseUrl: string | undefined;
}): WrapSequences =>
(sequences, buildReasonMessage) =>
sequences.reduce(
(acc: Array<WrappedFieldsLatest<BaseFieldsLatest>>, sequence) => [
...acc,
sequences.reduce((acc: Array<WrappedFieldsLatest<BaseFieldsLatest>>, sequence) => {
acc.push(
...buildAlertGroupFromSequence(
ruleExecutionLogger,
sequence,
Expand All @@ -49,7 +48,7 @@ export const wrapSequencesFactory =
indicesToQuery,
alertTimestampOverride,
publicBaseUrl
),
],
[]
);
)
);
return acc;
}, []);
Original file line number Diff line number Diff line change
Expand Up @@ -725,10 +725,10 @@ export const getSelectedTimelines = async (

const savedObjects = await Promise.resolve(
savedObjectsClient.bulkGet<SavedObjectTimelineWithoutExternalRefs>(
(exportedIds ?? []).reduce(
(acc, timelineId) => [...acc, { id: timelineId, type: timelineSavedObjectType }],
[] as Array<{ id: string; type: string }>
)
(exportedIds ?? []).reduce((acc, timelineId) => {
acc.push({ id: timelineId, type: timelineSavedObjectType });
return acc;
}, [] as Array<{ id: string; type: string }>)
)
);

Expand All @@ -740,13 +740,12 @@ export const getSelectedTimelines = async (
if (savedObject.error == null) {
const populatedTimeline = timelineFieldsMigrator.populateFieldsFromReferences(savedObject);

return {
errors: acc.errors,
timelines: [...acc.timelines, convertSavedObjectToSavedTimeline(populatedTimeline)],
};
acc.timelines.push(convertSavedObjectToSavedTimeline(populatedTimeline));
return acc;
}

return { errors: [...acc.errors, savedObject.error], timelines: acc.timelines };
acc.errors.push(savedObject.error);
return acc;
},
{
timelines: [] as TimelineSavedObject[],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ export const kpiRiskScore: SecuritySolutionFactory<RiskQueries.kpiRiskScore> = {
const riskBuckets = getOr([], 'aggregations.risk.buckets', response.rawResponse);

const result: Record<RiskSeverity, number> = riskBuckets.reduce(
(cummulative: Record<string, number>, bucket: AggBucket) => ({
...cummulative,
[bucket.key]: getOr(0, 'unique_entries.value', bucket),
}),
(cummulative: Record<string, number>, bucket: AggBucket) => {
cummulative[bucket.key] = getOr(0, 'unique_entries.value', bucket);
return cummulative;
},
{}
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,11 @@ async function enhanceEdges(
isNewRiskScoreModuleInstalled
);
const usersRiskByUserName: Record<string, RiskSeverity> | undefined =
userRiskData?.hits.hits.reduce(
(acc, hit) => ({
...acc,
[hit._source?.user.name ?? '']: hit._source?.user?.risk?.calculated_level,
}),
{}
);
userRiskData?.hits.hits.reduce((acc, hit) => {
(acc as Record<string, unknown>)[hit._source?.user.name ?? ''] =
hit._source?.user?.risk?.calculated_level;
return acc;
}, {});

return usersRiskByUserName
? edges.map(({ name, lastSeen, domain }) => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ export class EndpointMeteringService {
projectId: cloudSetup?.serverless?.projectId,
});

return [...acc, record];
acc.push(record);
return acc;
}, [] as UsageRecord[]);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,19 @@ function toggleDisabledFeatures(
) {
const disabledFeatureKeys = activeSpace.disabledFeatures;

const [enabledFeatures, disabledFeatures] = features.reduce(
const { enabledFeatures, disabledFeatures } = features.reduce(
(acc, feature) => {
if (disabledFeatureKeys.includes(feature.id)) {
return [acc[0], [...acc[1], feature]];
acc.disabledFeatures.push(feature);
} else {
acc.enabledFeatures.push(feature);
}
return [[...acc[0], feature], acc[1]];
return acc;
},
[[], []] as [KibanaFeature[], KibanaFeature[]]
{ enabledFeatures: [], disabledFeatures: [] } as {
enabledFeatures: KibanaFeature[];
disabledFeatures: KibanaFeature[];
}
);

const navLinks = capabilities.navLinks;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,10 +454,10 @@ export const createExternalService = (
});

const fields = res.data.values.reduce(
(acc: { [x: string]: {} }, value: { fieldId: string }) => ({
...acc,
[value.fieldId]: { ...value },
}),
(acc: { [x: string]: {} }, value: { fieldId: string }) => {
(acc as Record<string, unknown>)[value.fieldId] = { ...value };
return acc;
},
{}
);
return normalizeFields(fields);
Expand All @@ -484,13 +484,12 @@ export const createExternalService = (
const currentListOfFields = Object.keys(acc);
return currentListOfFields.length === 0
? fieldTypesByIssue
: currentListOfFields.reduce(
(add: GetCommonFieldsResponse, field) =>
Object.keys(fieldTypesByIssue).includes(field)
? { ...add, [field]: acc[field] }
: add,
{}
);
: currentListOfFields.reduce((add: GetCommonFieldsResponse, field) => {
if (Object.keys(fieldTypesByIssue).includes(field)) {
(add as Record<string, unknown>)[field] = acc[field];
}
return add;
}, {});
}, {});
} catch (error) {
// errors that happen here would be thrown in the contained async calls
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ import * as i18n from './translations';
export const prepareIncident = (useOldApi: boolean, incident: PartialIncident): PartialIncident =>
useOldApi
? incident
: Object.entries(incident).reduce(
(acc, [key, value]) => ({ ...acc, [`${FIELD_PREFIX}${key}`]: value }),
{} as Incident
);
: Object.entries(incident).reduce((acc, [key, value]) => {
(acc as Record<string, unknown>)[`${FIELD_PREFIX}${key}`] = value;
return acc;
}, {} as Incident);

const createErrorMessage = (errorResponse?: ServiceNowError): string => {
if (errorResponse == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,12 @@ const formatTimeOfEvent = (timeOfEvent: string | null): string | undefined => {
const removeNullValues = (
params: ExecutorSubActionAddEventParams
): ExecutorSubActionAddEventParams =>
(Object.keys(params) as Array<keyof ExecutorSubActionAddEventParams>).reduce(
(acc, key) => ({
...acc,
...(params[key] != null ? { [key]: params[key] } : {}),
}),
{} as ExecutorSubActionAddEventParams
);
(Object.keys(params) as Array<keyof ExecutorSubActionAddEventParams>).reduce((acc, key) => {
if (params[key] != null) {
(acc as Record<string, unknown>)[key] = params[key];
}
return acc;
}, {} as ExecutorSubActionAddEventParams);

export const prepareParams = (
params: ExecutorSubActionAddEventParams
Expand Down

0 comments on commit 264c2db

Please sign in to comment.