Skip to content

Commit

Permalink
Revert "[Security Solution][Endpoint] Allow access to Endpoint Metada…
Browse files Browse the repository at this point in the history
…ta for users that might only have READONLY access (#106328)"

This reverts commit b6e9d8d.
  • Loading branch information
jbudz committed Jul 28, 2021
1 parent 904c370 commit 3d33710
Show file tree
Hide file tree
Showing 23 changed files with 106 additions and 532 deletions.
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/common/types/models/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ interface AgentBase {
export interface Agent extends AgentBase {
id: string;
access_api_key?: string;
status?: AgentStatus;
status?: string;
packages: string[];
}

Expand Down
17 changes: 14 additions & 3 deletions x-pack/plugins/fleet/server/routes/agent/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@ export const getAgentHandler: RequestHandler<
const esClient = context.core.elasticsearch.client.asCurrentUser;

try {
const agent = await AgentService.getAgentById(esClient, request.params.agentId);
const body: GetOneAgentResponse = {
item: await AgentService.getAgentById(esClient, request.params.agentId),
item: {
...agent,
status: AgentService.getAgentStatus(agent),
},
};

return response.ok({ body });
Expand Down Expand Up @@ -87,8 +91,12 @@ export const updateAgentHandler: RequestHandler<
await AgentService.updateAgent(esClient, request.params.agentId, {
user_provided_metadata: request.body.user_provided_metadata,
});
const agent = await AgentService.getAgentById(esClient, request.params.agentId);
const body = {
item: await AgentService.getAgentById(esClient, request.params.agentId),
item: {
...agent,
status: AgentService.getAgentStatus(agent),
},
};

return response.ok({ body });
Expand Down Expand Up @@ -124,7 +132,10 @@ export const getAgentsHandler: RequestHandler<
: 0;

const body: GetAgentsResponse = {
list: agents,
list: agents.map((agent) => ({
...agent,
status: AgentService.getAgentStatus(agent),
})),
total,
totalInactive,
page,
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/fleet/server/services/agents/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,9 @@ export async function getAgentById(esClient: ElasticsearchClient, agentId: strin
if (agentHit.body.found === false) {
throw agentNotFoundError;
}
const agent = searchHitToAgent(agentHit.body);

return searchHitToAgent(agentHit.body);
return agent;
} catch (err) {
if (isESClientError(err) && err.meta.statusCode === 404) {
throw agentNotFoundError;
Expand Down
6 changes: 1 addition & 5 deletions x-pack/plugins/fleet/server/services/agents/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import type { estypes } from '@elastic/elasticsearch';

import type { SearchHit } from '../../../../../../src/core/types/elasticsearch';
import type { Agent, AgentSOAttributes, FleetServerAgent } from '../../types';
import { getAgentStatus } from '../../../common/services/agent_status';

type FleetServerAgentESResponse =
| estypes.MgetHit<FleetServerAgent>
Expand All @@ -18,17 +17,14 @@ type FleetServerAgentESResponse =

export function searchHitToAgent(hit: FleetServerAgentESResponse): Agent {
// @ts-expect-error @elastic/elasticsearch MultiGetHit._source is optional
const agent: Agent = {
return {
id: hit._id,
...hit._source,
policy_revision: hit._source?.policy_revision_idx,
access_api_key: undefined,
status: undefined,
packages: hit._source?.packages ?? [],
};

agent.status = getAgentStatus(agent);
return agent;
}

export function agentSOAttributesToFleetServerAgentDoc(
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/fleet/server/services/agents/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export async function getAgentStatusById(
esClient: ElasticsearchClient,
agentId: string
): Promise<AgentStatus> {
return (await getAgentById(esClient, agentId)).status!;
const agent = await getAgentById(esClient, agentId);
return AgentStatusKueryHelper.getAgentStatus(agent);
}

export const getAgentStatus = AgentStatusKueryHelper.getAgentStatus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class BaseDataGenerator<GeneratedDoc extends {} = {}> {
return [7, ...this.randomNGenerator(20, 2)].map((x) => x.toString()).join('.');
}

protected randomChoice<T>(choices: T[] | readonly T[]): T {
protected randomChoice<T>(choices: T[]): T {
return choices[this.randomN(choices.length)];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,7 @@ import { estypes } from '@elastic/elasticsearch';
import { DeepPartial } from 'utility-types';
import { merge } from 'lodash';
import { BaseDataGenerator } from './base_data_generator';
import { Agent, AGENTS_INDEX, AgentStatus, FleetServerAgent } from '../../../../fleet/common';

const agentStatusList: readonly AgentStatus[] = [
'offline',
'error',
'online',
'inactive',
'warning',
'enrolling',
'unenrolling',
'updating',
'degraded',
];
import { Agent, AGENTS_INDEX, FleetServerAgent } from '../../../../fleet/common';

export class FleetAgentGenerator extends BaseDataGenerator<Agent> {
/**
Expand Down Expand Up @@ -52,7 +40,7 @@ export class FleetAgentGenerator extends BaseDataGenerator<Agent> {
id: hit._id,
policy_revision: hit._source?.policy_revision_idx,
access_api_key: undefined,
status: this.randomAgentStatus(),
status: undefined,
packages: hit._source?.packages ?? [],
},
overrides
Expand Down Expand Up @@ -128,8 +116,4 @@ export class FleetAgentGenerator extends BaseDataGenerator<Agent> {
overrides
);
}

private randomAgentStatus() {
return this.randomChoice(agentStatusList);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2.0.
*/

import { httpServerMock } from '../../../../../src/core/server/mocks';
import { EndpointAppContextService } from './endpoint_app_context_services';

describe('test endpoint app context services', () => {
Expand All @@ -16,4 +17,10 @@ describe('test endpoint app context services', () => {
const endpointAppContextService = new EndpointAppContextService();
expect(endpointAppContextService.getManifestManager()).toEqual(undefined);
});
it('should throw error on getScopedSavedObjectsClient if start is not called', async () => {
const endpointAppContextService = new EndpointAppContextService();
expect(() =>
endpointAppContextService.getScopedSavedObjectsClient(httpServerMock.createKibanaRequest())
).toThrow(Error);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
* 2.0.
*/

import { KibanaRequest, Logger } from 'src/core/server';
import {
KibanaRequest,
Logger,
SavedObjectsServiceStart,
SavedObjectsClientContract,
} from 'src/core/server';
import { ExceptionListClient } from '../../../lists/server';
import {
CasesClient,
Expand All @@ -31,8 +36,6 @@ import {
ExperimentalFeatures,
parseExperimentalConfigValue,
} from '../../common/experimental_features';
import { EndpointMetadataService } from './services/metadata';
import { EndpointAppContentServicesNotStartedError } from './errors';

export type EndpointAppContextServiceStartContract = Partial<
Pick<
Expand All @@ -41,13 +44,13 @@ export type EndpointAppContextServiceStartContract = Partial<
>
> & {
logger: Logger;
endpointMetadataService: EndpointMetadataService;
manifestManager?: ManifestManager;
appClientFactory: AppClientFactory;
security: SecurityPluginStart;
alerting: AlertsPluginStartContract;
config: ConfigType;
registerIngestCallback?: FleetStartContract['registerExternalCallback'];
savedObjectsStart: SavedObjectsServiceStart;
licenseService: LicenseService;
exceptionListsClient: ExceptionListClient | undefined;
cases: CasesPluginStartContract | undefined;
Expand All @@ -62,23 +65,25 @@ export class EndpointAppContextService {
private manifestManager: ManifestManager | undefined;
private packagePolicyService: PackagePolicyServiceInterface | undefined;
private agentPolicyService: AgentPolicyServiceInterface | undefined;
private savedObjectsStart: SavedObjectsServiceStart | undefined;
private config: ConfigType | undefined;
private license: LicenseService | undefined;
public security: SecurityPluginStart | undefined;
private cases: CasesPluginStartContract | undefined;
private endpointMetadataService: EndpointMetadataService | undefined;

private experimentalFeatures: ExperimentalFeatures | undefined;

public start(dependencies: EndpointAppContextServiceStartContract) {
this.agentService = dependencies.agentService;
this.packagePolicyService = dependencies.packagePolicyService;
this.agentPolicyService = dependencies.agentPolicyService;
this.manifestManager = dependencies.manifestManager;
this.savedObjectsStart = dependencies.savedObjectsStart;
this.config = dependencies.config;
this.license = dependencies.licenseService;
this.security = dependencies.security;
this.cases = dependencies.cases;
this.endpointMetadataService = dependencies.endpointMetadataService;

this.experimentalFeatures = parseExperimentalConfigValue(this.config.enableExperimental);

if (this.manifestManager && dependencies.registerIngestCallback) {
Expand Down Expand Up @@ -111,13 +116,6 @@ export class EndpointAppContextService {
return this.experimentalFeatures;
}

public getEndpointMetadataService(): EndpointMetadataService {
if (!this.endpointMetadataService) {
throw new EndpointAppContentServicesNotStartedError();
}
return this.endpointMetadataService;
}

public getAgentService(): AgentService | undefined {
return this.agentService;
}
Expand All @@ -134,16 +132,23 @@ export class EndpointAppContextService {
return this.manifestManager;
}

public getScopedSavedObjectsClient(req: KibanaRequest): SavedObjectsClientContract {
if (!this.savedObjectsStart) {
throw new Error(`must call start on ${EndpointAppContextService.name} to call getter`);
}
return this.savedObjectsStart.getScopedClient(req, { excludedWrappers: ['security'] });
}

public getLicenseService(): LicenseService {
if (!this.license) {
throw new EndpointAppContentServicesNotStartedError();
throw new Error(`must call start on ${EndpointAppContextService.name} to call getter`);
}
return this.license;
}

public async getCasesClient(req: KibanaRequest): Promise<CasesClient> {
if (!this.cases) {
throw new EndpointAppContentServicesNotStartedError();
throw new Error(`must call start on ${EndpointAppContextService.name} to call getter`);
}
return this.cases.getCasesClientWithRequest(req);
}
Expand Down
24 changes: 0 additions & 24 deletions x-pack/plugins/security_solution/server/endpoint/errors.ts

This file was deleted.

15 changes: 3 additions & 12 deletions x-pack/plugins/security_solution/server/endpoint/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import { parseExperimentalConfigValue } from '../../common/experimental_features
// a restricted path.
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { createCasesClientMock } from '../../../cases/server/client/mocks';
import { EndpointMetadataService } from './services/metadata';

/**
* Creates a mocked EndpointAppContext.
Expand Down Expand Up @@ -66,6 +65,7 @@ export const createMockEndpointAppContextService = (
getAgentService: jest.fn(),
getAgentPolicyService: jest.fn(),
getManifestManager: jest.fn().mockReturnValue(mockManifestManager ?? jest.fn()),
getScopedSavedObjectsClient: jest.fn(),
} as unknown) as jest.Mocked<EndpointAppContextService>;
};

Expand All @@ -76,23 +76,14 @@ export const createMockEndpointAppContextServiceStartContract = (): jest.Mocked<
const factory = new AppClientFactory();
const config = createMockConfig();
const casesClientMock = createCasesClientMock();
const savedObjectsStart = savedObjectsServiceMock.createStartContract();
const agentService = createMockAgentService();
const agentPolicyService = createMockAgentPolicyService();
const endpointMetadataService = new EndpointMetadataService(
savedObjectsStart,
agentService,
agentPolicyService
);

factory.setup({ getSpaceId: () => 'mockSpace', config });

return {
agentService,
agentPolicyService,
endpointMetadataService,
agentService: createMockAgentService(),
packageService: createMockPackageService(),
logger: loggingSystemMock.create().get('mock_endpoint_app_context'),
savedObjectsStart: savedObjectsServiceMock.createStartContract(),
manifestManager: getManifestManagerMock(),
appClientFactory: factory,
security: securityMock.createStart(),
Expand Down
Loading

0 comments on commit 3d33710

Please sign in to comment.