Skip to content

Commit

Permalink
[Osquery] RBAC (elastic#106669)
Browse files Browse the repository at this point in the history
  • Loading branch information
patrykkopycinski authored Aug 10, 2021
1 parent 5a92a7e commit 9edcf9e
Show file tree
Hide file tree
Showing 79 changed files with 1,135 additions and 356 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export const REMOVED_TYPES: string[] = [
'server',
// https://github.com/elastic/kibana/issues/95617
'tsvb-validation-telemetry',
// replaced by osquery-manager-usage-metric
'osquery-usage-metric',
].sort();

// When migrating from the outdated index we use a read query which excludes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const previouslyRegisteredTypes = [
'monitoring-telemetry',
'osquery-saved-query',
'osquery-usage-metric',
'osquery-manager-usage-metric',
'query',
'sample-data-telemetry',
'search',
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/server/collectors/agent_collectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const getAgentUsage = async (
error,
offline,
updating,
} = await AgentService.getAgentStatusForAgentPolicy(soClient, esClient);
} = await AgentService.getAgentStatusForAgentPolicy(esClient);
return {
total_enrolled: total,
healthy: online,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export const getFleetServerUsage = async (
}

const { total, inactive, online, error, updating, offline } = await getAgentStatusForAgentPolicy(
soClient,
esClient,
undefined,
Array.from(policyIds)
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/fleet/server/mocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export const createMockAgentPolicyService = (): jest.Mocked<AgentPolicyServiceIn
export const createMockAgentService = (): jest.Mocked<AgentService> => {
return {
getAgentStatusById: jest.fn(),
getAgentStatusForAgentPolicy: jest.fn(),
authenticateAgentWithAccessToken: jest.fn(),
getAgent: jest.fn(),
listAgents: jest.fn(),
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/fleet/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ import {
} from './services';
import {
getAgentStatusById,
getAgentStatusForAgentPolicy,
authenticateAgentWithAccessToken,
getAgentsByKuery,
getAgentById,
Expand Down Expand Up @@ -309,6 +310,7 @@ export class FleetPlugin
getAgent: getAgentById,
listAgents: getAgentsByKuery,
getAgentStatusById,
getAgentStatusForAgentPolicy,
authenticateAgentWithAccessToken,
},
agentPolicyService: {
Expand Down
2 changes: 0 additions & 2 deletions x-pack/plugins/fleet/server/routes/agent/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,11 @@ export const getAgentStatusForAgentPolicyHandler: RequestHandler<
undefined,
TypeOf<typeof GetAgentStatusRequestSchema.query>
> = async (context, request, response) => {
const soClient = context.core.savedObjects.client;
const esClient = context.core.elasticsearch.client.asCurrentUser;

try {
// TODO change path
const results = await AgentService.getAgentStatusForAgentPolicy(
soClient,
esClient,
request.query.policyId,
request.query.kuery
Expand Down
3 changes: 1 addition & 2 deletions x-pack/plugins/fleet/server/services/agents/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import type { ElasticsearchClient, SavedObjectsClientContract } from 'src/core/server';
import type { ElasticsearchClient } from 'src/core/server';
import pMap from 'p-map';

import { AGENT_SAVED_OBJECT_TYPE } from '../../constants';
Expand Down Expand Up @@ -49,7 +49,6 @@ function joinKuerys(...kuerys: Array<string | undefined>) {
}

export async function getAgentStatusForAgentPolicy(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
agentPolicyId?: string,
filterKuery?: string
Expand Down
10 changes: 10 additions & 0 deletions x-pack/plugins/fleet/server/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import type { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/ser

import type { AgentStatus, Agent } from '../types';

import type { GetAgentStatusResponse } from '../../common';

import type { getAgentById, getAgentsByKuery } from './agents';
import type { agentPolicyService } from './agent_policy';
import * as settingsService from './settings';
Expand Down Expand Up @@ -56,6 +58,14 @@ export interface AgentService {
* Return the status by the Agent's id
*/
getAgentStatusById(esClient: ElasticsearchClient, agentId: string): Promise<AgentStatus>;
/**
* Return the status by the Agent's Policy id
*/
getAgentStatusForAgentPolicy(
esClient: ElasticsearchClient,
agentPolicyId?: string,
filterKuery?: string
): Promise<GetAgentStatusResponse['results']>;
/**
* List agents
*/
Expand Down
7 changes: 5 additions & 2 deletions x-pack/plugins/osquery/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import { PackagePolicy, PackagePolicyInput, PackagePolicyInputStream } from '../

export const savedQuerySavedObjectType = 'osquery-saved-query';
export const packSavedObjectType = 'osquery-pack';
export const usageMetricSavedObjectType = 'osquery-usage-metric';
export type SavedObjectType = 'osquery-saved-query' | 'osquery-pack' | 'osquery-usage-metric';
export const usageMetricSavedObjectType = 'osquery-manager-usage-metric';
export type SavedObjectType =
| 'osquery-saved-query'
| 'osquery-pack'
| 'osquery-manager-usage-metric';

/**
* This makes any optional property the same as Required<T> would but also has the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { AgentIdToName } from '../agents/agent_id_to_name';
import { useActionResults } from './use_action_results';
import { useAllResults } from '../results/use_all_results';
import { Direction } from '../../common/search_strategy';
import { useActionResultsPrivileges } from './use_action_privileges';

interface ActionResultsSummaryProps {
actionId: string;
Expand All @@ -41,6 +42,7 @@ const ActionResultsSummaryComponent: React.FC<ActionResultsSummaryProps> = ({
expirationDate,
]);
const [isLive, setIsLive] = useState(true);
const { data: hasActionResultsPrivileges } = useActionResultsPrivileges();
const {
// @ts-expect-error update types
data: { aggregations, edges },
Expand All @@ -52,6 +54,7 @@ const ActionResultsSummaryComponent: React.FC<ActionResultsSummaryProps> = ({
direction: Direction.asc,
sortField: '@timestamp',
isLive,
skip: !hasActionResultsPrivileges,
});
if (expired) {
// @ts-expect-error update types
Expand All @@ -77,6 +80,7 @@ const ActionResultsSummaryComponent: React.FC<ActionResultsSummaryProps> = ({
},
],
isLive,
skip: !hasActionResultsPrivileges,
});

const renderAgentIdColumn = useCallback((agentId) => <AgentIdToName agentId={agentId} />, []);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useQuery } from 'react-query';

import { i18n } from '@kbn/i18n';
import { useKibana } from '../common/lib/kibana';
import { useErrorToast } from '../common/hooks/use_error_toast';

export const useActionResultsPrivileges = () => {
const { http } = useKibana().services;
const setErrorToast = useErrorToast();

return useQuery(
['actionResultsPrivileges'],
() => http.get('/internal/osquery/privileges_check'),
{
keepPreviousData: true,
select: (response) => response?.has_all_requested ?? false,
onSuccess: () => setErrorToast(),
onError: (error: Error) =>
setErrorToast(error, {
title: i18n.translate('xpack.osquery.action_results_privileges.fetchError', {
defaultMessage: 'Error while fetching action results privileges',
}),
}),
}
);
};
13 changes: 2 additions & 11 deletions x-pack/plugins/osquery/public/agent_policies/use_agent_policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@ import { useQuery } from 'react-query';

import { i18n } from '@kbn/i18n';
import { useKibana } from '../common/lib/kibana';
import {
agentPolicyRouteService,
GetAgentPoliciesResponse,
GetAgentPoliciesResponseItem,
} from '../../../fleet/common';
import { GetAgentPoliciesResponse, GetAgentPoliciesResponseItem } from '../../../fleet/common';
import { useErrorToast } from '../common/hooks/use_error_toast';

export const useAgentPolicies = () => {
Expand All @@ -22,12 +18,7 @@ export const useAgentPolicies = () => {

return useQuery<GetAgentPoliciesResponse, unknown, GetAgentPoliciesResponseItem[]>(
['agentPolicies'],
() =>
http.get(agentPolicyRouteService.getListPath(), {
query: {
perPage: 100,
},
}),
() => http.get('/internal/osquery/fleet_wrapper/agent_policies/'),
{
initialData: { items: [], total: 0, page: 1, perPage: 100 },
keepPreviousData: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { useQuery } from 'react-query';

import { i18n } from '@kbn/i18n';
import { useKibana } from '../common/lib/kibana';
import { agentPolicyRouteService } from '../../../fleet/common';
import { useErrorToast } from '../common/hooks/use_error_toast';

interface UseAgentPolicy {
Expand All @@ -23,7 +22,7 @@ export const useAgentPolicy = ({ policyId, skip }: UseAgentPolicy) => {

return useQuery(
['agentPolicy', { policyId }],
() => http.get(agentPolicyRouteService.getInfoPath(policyId)),
() => http.get(`/internal/osquery/fleet_wrapper/agent_policies/${policyId}`),
{
enabled: !skip,
keepPreviousData: true,
Expand Down
14 changes: 9 additions & 5 deletions x-pack/plugins/osquery/public/agents/agents_table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,13 @@ const AgentsTableComponent: React.FC<AgentsTableProps> = ({ agentSelection, onCh
osqueryPolicyData
);
const grouper = useMemo(() => new AgentGrouper(), []);
const { agentsLoading, agents } = useAllAgents(osqueryPolicyData, debouncedSearchValue, {
perPage,
});
const { isLoading: agentsLoading, data: agents } = useAllAgents(
osqueryPolicyData,
debouncedSearchValue,
{
perPage,
}
);

// option related
const [options, setOptions] = useState<GroupOption[]>([]);
Expand Down Expand Up @@ -108,8 +112,8 @@ const AgentsTableComponent: React.FC<AgentsTableProps> = ({ agentSelection, onCh
grouper.setTotalAgents(totalNumAgents);
grouper.updateGroup(AGENT_GROUP_KEY.Platform, groups.platforms);
grouper.updateGroup(AGENT_GROUP_KEY.Policy, groups.policies);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
grouper.updateGroup(AGENT_GROUP_KEY.Agent, agents!);
// @ts-expect-error update types
grouper.updateGroup(AGENT_GROUP_KEY.Agent, agents);
const newOptions = grouper.generateOptions();
setOptions(newOptions);
}, [groups.platforms, groups.policies, totalNumAgents, groupsLoading, agents, grouper]);
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/osquery/public/agents/use_agent_details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { i18n } from '@kbn/i18n';
import { useQuery } from 'react-query';

import { GetOneAgentResponse, agentRouteService } from '../../../fleet/common';
import { GetOneAgentResponse } from '../../../fleet/common';
import { useErrorToast } from '../common/hooks/use_error_toast';
import { useKibana } from '../common/lib/kibana';

Expand All @@ -21,7 +21,7 @@ export const useAgentDetails = ({ agentId }: UseAgentDetails) => {
const setErrorToast = useErrorToast();
return useQuery<GetOneAgentResponse>(
['agentDetails', agentId],
() => http.get(agentRouteService.getInfoPath(agentId)),
() => http.get(`/internal/osquery/fleet_wrapper/agents/${agentId}`),
{
enabled: agentId.length > 0,
onSuccess: () => setErrorToast(),
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/osquery/public/agents/use_agent_policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { mapKeys } from 'lodash';
import { useQueries, UseQueryResult } from 'react-query';
import { i18n } from '@kbn/i18n';
import { useKibana } from '../common/lib/kibana';
import { agentPolicyRouteService, GetOneAgentPolicyResponse } from '../../../fleet/common';
import { GetOneAgentPolicyResponse } from '../../../fleet/common';
import { useErrorToast } from '../common/hooks/use_error_toast';

export const useAgentPolicies = (policyIds: string[] = []) => {
Expand All @@ -19,7 +19,7 @@ export const useAgentPolicies = (policyIds: string[] = []) => {
const agentResponse = useQueries(
policyIds.map((policyId) => ({
queryKey: ['agentPolicy', policyId],
queryFn: () => http.get(agentPolicyRouteService.getInfoPath(policyId)),
queryFn: () => http.get(`/internal/osquery/fleet_wrapper/agent_policies/${policyId}`),
enabled: policyIds.length > 0,
onSuccess: () => setErrorToast(),
onError: (error) =>
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/osquery/public/agents/use_agent_status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { i18n } from '@kbn/i18n';
import { useQuery } from 'react-query';

import { GetAgentStatusResponse, agentRouteService } from '../../../fleet/common';
import { GetAgentStatusResponse } from '../../../fleet/common';
import { useErrorToast } from '../common/hooks/use_error_toast';
import { useKibana } from '../common/lib/kibana';

Expand All @@ -25,7 +25,7 @@ export const useAgentStatus = ({ policyId, skip }: UseAgentStatus) => {
['agentStatus', policyId],
() =>
http.get(
agentRouteService.getStatusPath(),
`/internal/osquery/fleet_wrapper/agent-status`,
policyId
? {
query: {
Expand Down
11 changes: 6 additions & 5 deletions x-pack/plugins/osquery/public/agents/use_all_agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { i18n } from '@kbn/i18n';
import { useQuery } from 'react-query';

import { GetAgentsResponse, agentRouteService } from '../../../fleet/common';
import { GetAgentsResponse } from '../../../fleet/common';
import { useErrorToast } from '../common/hooks/use_error_toast';
import { useKibana } from '../common/lib/kibana';

Expand All @@ -31,7 +31,8 @@ export const useAllAgents = (
const { perPage } = opts;
const { http } = useKibana().services;
const setErrorToast = useErrorToast();
const { isLoading: agentsLoading, data: agentData } = useQuery<GetAgentsResponse>(

return useQuery<GetAgentsResponse>(
['agents', osqueryPolicies, searchValue, perPage],
() => {
let kuery = `${osqueryPolicies.map((p) => `policy_id:${p}`).join(' or ')}`;
Expand All @@ -40,14 +41,16 @@ export const useAllAgents = (
kuery += ` and (local_metadata.host.hostname:*${searchValue}* or local_metadata.elastic.agent.id:*${searchValue}*)`;
}

return http.get(agentRouteService.getListPath(), {
return http.get(`/internal/osquery/fleet_wrapper/agents`, {
query: {
kuery,
perPage,
},
});
},
{
// @ts-expect-error update types
select: (data) => data?.agents || [],
enabled: !osqueryPoliciesLoading && osqueryPolicies.length > 0,
onSuccess: () => setErrorToast(),
onError: (error) =>
Expand All @@ -58,6 +61,4 @@ export const useAllAgents = (
}),
}
);

return { agentsLoading, agents: agentData?.list };
};
9 changes: 1 addition & 8 deletions x-pack/plugins/osquery/public/agents/use_osquery_policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import { useQuery } from 'react-query';
import { useMemo } from 'react';
import { i18n } from '@kbn/i18n';
import { useKibana } from '../common/lib/kibana';
import { packagePolicyRouteService, PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../../../fleet/common';
import { OSQUERY_INTEGRATION_NAME } from '../../common';
import { useErrorToast } from '../common/hooks/use_error_toast';

export const useOsqueryPolicies = () => {
Expand All @@ -20,12 +18,7 @@ export const useOsqueryPolicies = () => {

const { isLoading: osqueryPoliciesLoading, data: osqueryPolicies = [] } = useQuery(
['osqueryPolicies'],
() =>
http.get(packagePolicyRouteService.getListPath(), {
query: {
kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${OSQUERY_INTEGRATION_NAME}`,
},
}),
() => http.get('/internal/osquery/fleet_wrapper/package_policies'),
{
select: (response) =>
uniq<string>(response.items.map((p: { policy_id: string }) => p.policy_id)),
Expand Down
Loading

0 comments on commit 9edcf9e

Please sign in to comment.