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

[Fleet] Expose permissions as part of the agent policy #94591

Merged
merged 21 commits into from
Mar 30, 2021
Merged
Show file tree
Hide file tree
Changes from 13 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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const POLICY_KEYS_ORDER = [
'dataset',
'type',
'outputs',
'output_permissions',
'agent',
'inputs',
'enabled',
Expand Down
10 changes: 10 additions & 0 deletions x-pack/plugins/fleet/common/types/models/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,23 @@ export interface FullAgentPolicyInput {
[key: string]: any;
}

export interface FullAgentPolicyPermission {
names: string[];
privileges: string[];
}

export interface FullAgentPolicy {
id: string;
outputs: {
[key: string]: Pick<Output, 'type' | 'hosts' | 'ca_sha256' | 'api_key'> & {
[key: string]: any;
};
};
output_permissions?: {
[output: string]: {
[role: string]: FullAgentPolicyPermission[];
};
};
fleet?: {
kibana: FullAgentPolicyKibanaConfig;
};
Expand Down
21 changes: 19 additions & 2 deletions x-pack/plugins/fleet/server/services/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ class AgentPolicyService {
id: agentPolicy.id,
outputs: {
// TEMPORARY as we only support a default output
...[defaultOutput].reduce(
...[defaultOutput].reduce<FullAgentPolicy['outputs']>(
// eslint-disable-next-line @typescript-eslint/naming-convention
(outputs, { config_yaml, name, type, hosts, ca_sha256, api_key }) => {
const configJs = config_yaml ? safeLoad(config_yaml) : {};
Expand All @@ -675,7 +675,7 @@ class AgentPolicyService {

return outputs;
},
{} as FullAgentPolicy['outputs']
{}
),
},
inputs: storedPackagePoliciesToAgentInputs(agentPolicy.package_policies as PackagePolicy[]),
Expand All @@ -698,6 +698,23 @@ class AgentPolicyService {
}),
};

// Only add permissions if output.type is "elasticsearch"
afgomez marked this conversation as resolved.
Show resolved Hide resolved
fullAgentPolicy.output_permissions = Object.keys(fullAgentPolicy.outputs).reduce<
NonNullable<FullAgentPolicy['output_permissions']>
>((permissions, outputName) => {
const output = fullAgentPolicy.outputs[outputName];
if (output && output.type === 'elasticsearch') {
permissions[outputName] = {};
permissions[outputName].fallback = [
afgomez marked this conversation as resolved.
Show resolved Hide resolved
{
names: ['logs-*', 'metrics-*', 'traces-*', '.logs-endpoint.diagnostic.collection-*'],
privileges: ['auto_configure', 'create_doc'],
jen-huang marked this conversation as resolved.
Show resolved Hide resolved
},
];
}
return permissions;
}, {});

// only add settings if not in standalone
if (!standalone) {
let settings: Settings;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ describe('test agent checkin new action services', () => {
api_key: undefined,
},
},
output_permissions: {
default: { fallback: [] },
},
inputs: [],
},
},
Expand All @@ -159,6 +162,7 @@ describe('test agent checkin new action services', () => {
id: 'policy1',
inputs: [],
outputs: { default: { api_key: 'MOCK_API_KEY', hosts: [], type: 'elasticsearch' } },
outputPermissions: { default: { fallback: [] } },
},
},
id: 'action1',
Expand Down Expand Up @@ -213,7 +217,7 @@ describe('test agent checkin new action services', () => {
).toEqual(expectedResult);
});

it('should return CONNFIG_CHANGE and data.config for agent version <= 7.9', async () => {
it('should return CONFIG_CHANGE and data.config for agent version <= 7.9', async () => {
const expectedResult = [
{
agent_id: 'agent1',
Expand All @@ -223,6 +227,7 @@ describe('test agent checkin new action services', () => {
id: 'policy1',
inputs: [],
outputs: { default: { api_key: 'MOCK_API_KEY', hosts: [], type: 'elasticsearch' } },
outputPermissions: { default: { fallback: [] } },
},
},
id: 'action1',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
} from '../actions';
import { appContextService } from '../../app_context';
import { getAgentById, updateAgent } from '../crud';
import type { FullAgentPolicyPermission } from '../../../../common';

import { toPromiseAbortable, AbortError, createRateLimiter } from './rxjs_utils';

Expand Down Expand Up @@ -113,14 +114,20 @@ async function getAgentDefaultOutputAPIKey(
async function getOrCreateAgentDefaultOutputAPIKey(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
agent: Agent
agent: Agent,
permissions: { [role: string]: FullAgentPolicyPermission[] }
): Promise<string> {
const defaultAPIKey = await getAgentDefaultOutputAPIKey(soClient, esClient, agent);
if (defaultAPIKey) {
return defaultAPIKey;
}

const outputAPIKey = await APIKeysService.generateOutputApiKey(soClient, 'default', agent.id);
const outputAPIKey = await APIKeysService.generateOutputApiKey(
soClient,
'default',
agent.id,
permissions
);
await updateAgent(esClient, agent.id, {
default_api_key: outputAPIKey.key,
default_api_key_id: outputAPIKey.id,
Expand Down Expand Up @@ -167,8 +174,14 @@ export async function createAgentActionFromPolicyAction(
}
);

const permissions =
'policy' in newAgentAction.data
? newAgentAction.data.policy.outputPermissions.default
: newAgentAction.data.config.outputPermissions.default; // agent <= 7.9
afgomez marked this conversation as resolved.
Show resolved Hide resolved

// Mutate the policy to set the api token for this agent
const apiKey = await getOrCreateAgentDefaultOutputAPIKey(soClient, esClient, agent);
const apiKey = await getOrCreateAgentDefaultOutputAPIKey(soClient, esClient, agent, permissions);

if (newAgentAction.data.policy) {
newAgentAction.data.policy.outputs.default.api_key = apiKey;
}
Expand Down
28 changes: 17 additions & 11 deletions x-pack/plugins/fleet/server/services/api_keys/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import type { KibanaRequest } from 'src/core/server';
import type { SavedObjectsClientContract } from 'src/core/server';

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

import { createAPIKey } from './security';

export { invalidateAPIKeys } from './security';
Expand All @@ -16,20 +18,24 @@ export * from './enrollment_api_key';
export async function generateOutputApiKey(
soClient: SavedObjectsClientContract,
outputId: string,
agentId: string
agentId: string,
permissions: { [role: string]: FullAgentPolicyPermission[] }
): Promise<{ key: string; id: string }> {
const name = `${agentId}:${outputId}`;
const key = await createAPIKey(soClient, name, {
'fleet-output': {
cluster: ['monitor'],
index: [
{
names: ['logs-*', 'metrics-*', 'traces-*', '.logs-endpoint.diagnostic.collection-*'],
privileges: ['auto_configure', 'create_doc'],
},
],

const APIKeyRequest = Object.entries(permissions).reduce<Record<string, any>>(
(request, [role, indices]) => {
request[role] = {
cluster: ['monitor'],
index: indices,
};

return request;
},
});
{}
);

const key = await createAPIKey(soClient, name, APIKeyRequest);

if (!key) {
throw new Error('Unable to create an output api key');
Expand Down