-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathreassign.ts
171 lines (153 loc) · 5.23 KB
/
reassign.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
* 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 type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SavedObjectsClientContract, ElasticsearchClient } from '@kbn/core/server';
import Boom from '@hapi/boom';
import type { Agent, BulkActionResult } from '../../types';
import { agentPolicyService } from '../agent_policy';
import { AgentReassignmentError, HostedAgentPolicyRestrictionRelatedError } from '../../errors';
import {
getAgentDocuments,
getAgents,
getAgentPolicyForAgent,
updateAgent,
bulkUpdateAgents,
} from './crud';
import type { GetAgentsOptions } from '.';
import { createAgentAction } from './actions';
import { searchHitToAgent } from './helpers';
export async function reassignAgent(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
agentId: string,
newAgentPolicyId: string
) {
const newAgentPolicy = await agentPolicyService.get(soClient, newAgentPolicyId);
if (!newAgentPolicy) {
throw Boom.notFound(`Agent policy not found: ${newAgentPolicyId}`);
}
await reassignAgentIsAllowed(soClient, esClient, agentId, newAgentPolicyId);
await updateAgent(esClient, agentId, {
policy_id: newAgentPolicyId,
policy_revision: null,
});
await createAgentAction(esClient, {
agents: [agentId],
created_at: new Date().toISOString(),
type: 'POLICY_REASSIGN',
});
}
export async function reassignAgentIsAllowed(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
agentId: string,
newAgentPolicyId: string
) {
const agentPolicy = await getAgentPolicyForAgent(soClient, esClient, agentId);
if (agentPolicy?.is_managed) {
throw new HostedAgentPolicyRestrictionRelatedError(
`Cannot reassign an agent from hosted agent policy ${agentPolicy.id}`
);
}
const newAgentPolicy = await agentPolicyService.get(soClient, newAgentPolicyId);
if (newAgentPolicy?.is_managed) {
throw new HostedAgentPolicyRestrictionRelatedError(
`Cannot reassign an agent to hosted agent policy ${newAgentPolicy.id}`
);
}
return true;
}
function isMgetDoc(doc?: estypes.MgetResponseItem<unknown>): doc is estypes.GetGetResult {
return Boolean(doc && 'found' in doc);
}
export async function reassignAgents(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
options: ({ agents: Agent[] } | GetAgentsOptions) & { force?: boolean },
newAgentPolicyId: string
): Promise<{ items: BulkActionResult[] }> {
const agentPolicy = await agentPolicyService.get(soClient, newAgentPolicyId);
if (!agentPolicy) {
throw Boom.notFound(`Agent policy not found: ${newAgentPolicyId}`);
}
const outgoingErrors: Record<Agent['id'], Error> = {};
let givenAgents: Agent[] = [];
if ('agents' in options) {
givenAgents = options.agents;
} else if ('agentIds' in options) {
const givenAgentsResults = await getAgentDocuments(esClient, options.agentIds);
for (const agentResult of givenAgentsResults) {
if (isMgetDoc(agentResult) && agentResult.found === false) {
outgoingErrors[agentResult._id] = new AgentReassignmentError(
`Cannot find agent ${agentResult._id}`
);
} else {
givenAgents.push(searchHitToAgent(agentResult));
}
}
} else if ('kuery' in options) {
givenAgents = await getAgents(esClient, options);
}
const givenOrder =
'agentIds' in options ? options.agentIds : givenAgents.map((agent) => agent.id);
// which are allowed to unenroll
const agentResults = await Promise.allSettled(
givenAgents.map(async (agent, index) => {
if (agent.policy_id === newAgentPolicyId) {
throw new AgentReassignmentError(`${agent.id} is already assigned to ${newAgentPolicyId}`);
}
const isAllowed = await reassignAgentIsAllowed(
soClient,
esClient,
agent.id,
newAgentPolicyId
);
if (isAllowed) {
return agent;
}
throw new AgentReassignmentError(`${agent.id} may not be reassigned to ${newAgentPolicyId}`);
})
);
// Filter to agents that do not already use the new agent policy ID
const agentsToUpdate = agentResults.reduce<Agent[]>((agents, result, index) => {
if (result.status === 'fulfilled') {
agents.push(result.value);
} else {
const id = givenAgents[index].id;
outgoingErrors[id] = result.reason;
}
return agents;
}, []);
await bulkUpdateAgents(
esClient,
agentsToUpdate.map((agent) => ({
agentId: agent.id,
data: {
policy_id: newAgentPolicyId,
policy_revision: null,
},
}))
);
const orderedOut = givenOrder.map((agentId) => {
const hasError = agentId in outgoingErrors;
const result: BulkActionResult = {
id: agentId,
success: !hasError,
};
if (hasError) {
result.error = outgoingErrors[agentId];
}
return result;
});
const now = new Date().toISOString();
await createAgentAction(esClient, {
agents: agentsToUpdate.map((agent) => agent.id),
created_at: now,
type: 'POLICY_REASSIGN',
});
return { items: orderedOut };
}