-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
agent_service.ts
245 lines (210 loc) · 6.93 KB
/
agent_service.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
* 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.
*/
/* eslint-disable max-classes-per-file */
import type {
ElasticsearchClient,
KibanaRequest,
SavedObjectsClientContract,
} from '@kbn/core/server';
import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SortResults } from '@elastic/elasticsearch/lib/api/types';
import type { AgentStatus, ListWithKuery } from '../../types';
import type { Agent, GetAgentStatusResponse } from '../../../common/types';
import { getAuthzFromRequest } from '../security';
import { appContextService } from '../app_context';
import { FleetUnauthorizedError } from '../../errors';
import { getCurrentNamespace } from '../spaces/get_current_namespace';
import { getAgentsByKuery, getAgentById, getByIds } from './crud';
import { getAgentStatusById, getAgentStatusForAgentPolicy } from './status';
import { getLatestAvailableAgentVersion } from './versions';
/**
* A service for interacting with Agent data. See {@link AgentClient} for more information.
*
* @public
*/
export interface AgentService {
/**
* Should be used for end-user requests to Kibana. APIs will return errors if user does not have appropriate access.
*/
asScoped(req: KibanaRequest): AgentClient;
/**
* Scoped services to a given space
*/
asInternalScopedUser(spaceId: string): AgentClient;
/**
* Only use for server-side usages (eg. telemetry), should not be used for end users unless an explicit authz check is
* done.
*/
asInternalUser: AgentClient;
}
/**
* A client for interacting with data about an Agent
*
* @public
*/
export interface AgentClient {
/**
* Get an Agent by id
*/
getAgent(agentId: string): Promise<Agent>;
/**
* Get multiple agents by id
* @param agentIds
*/
getByIds(agentIds: string[], options?: { ignoreMissing?: boolean }): Promise<Agent[]>;
/**
* Return the status by the Agent's id
*/
getAgentStatusById(agentId: string): Promise<AgentStatus>;
/**
* Return the status by the Agent's Policy id
*/
getAgentStatusForAgentPolicy(
agentPolicyId?: string,
filterKuery?: string
): Promise<GetAgentStatusResponse['results']>;
/**
* List agents
*/
listAgents(
options: ListWithKuery & {
showInactive: boolean;
aggregations?: Record<string, AggregationsAggregationContainer>;
searchAfter?: SortResults;
pitId?: string;
getStatusSummary?: boolean;
}
): Promise<{
agents: Agent[];
total: number;
page: number;
perPage: number;
statusSummary?: Record<AgentStatus, number>;
aggregations?: Record<string, estypes.AggregationsAggregate>;
}>;
/**
* Return the latest agent available version
*/
getLatestAgentAvailableVersion(includeCurrentVersion?: boolean): Promise<string>;
/**
* Return the latest agent available version, not taking into account IAR versions
*/
getLatestAgentAvailableBaseVersion(includeCurrentVersion?: boolean): Promise<string>;
/**
* Return the latest agent available version formatted for the docker image
*/
getLatestAgentAvailableDockerImageVersion(includeCurrentVersion?: boolean): Promise<string>;
}
/**
* @internal
*/
class AgentClientImpl implements AgentClient {
constructor(
private readonly internalEsClient: ElasticsearchClient,
private readonly soClient: SavedObjectsClientContract,
private readonly preflightCheck?: () => void | Promise<void>,
private readonly spaceId?: string
) {}
public async listAgents(
options: ListWithKuery & {
showInactive: boolean;
aggregations?: Record<string, AggregationsAggregationContainer>;
}
) {
await this.#runPreflight();
return getAgentsByKuery(this.internalEsClient, this.soClient, {
...options,
spaceId: this.spaceId,
});
}
public async getAgent(agentId: string) {
await this.#runPreflight();
return getAgentById(this.internalEsClient, this.soClient, agentId);
}
public async getByIds(
agentIds: string[],
options?: Partial<{ ignoreMissing: boolean }>
): Promise<Agent[]> {
await this.#runPreflight();
return getByIds(this.internalEsClient, this.soClient, agentIds, options);
}
public async getAgentStatusById(agentId: string) {
await this.#runPreflight();
return getAgentStatusById(this.internalEsClient, this.soClient, agentId);
}
public async getAgentStatusForAgentPolicy(agentPolicyId?: string, filterKuery?: string) {
await this.#runPreflight();
return getAgentStatusForAgentPolicy(
this.internalEsClient,
this.soClient,
agentPolicyId,
filterKuery,
this.spaceId
);
}
public async getLatestAgentAvailableBaseVersion(includeCurrentVersion?: boolean) {
const fullVersion = await this.getLatestAgentAvailableVersion(includeCurrentVersion);
return fullVersion.split('+')[0];
}
public async getLatestAgentAvailableDockerImageVersion(includeCurrentVersion?: boolean) {
const fullVersion = await this.getLatestAgentAvailableVersion(includeCurrentVersion);
return fullVersion.replace('+', '.');
}
public async getLatestAgentAvailableVersion(includeCurrentVersion?: boolean) {
await this.#runPreflight();
return getLatestAvailableAgentVersion({ includeCurrentVersion });
}
#runPreflight = async () => {
if (this.preflightCheck) {
return this.preflightCheck();
}
};
}
/**
* @internal
*/
export class AgentServiceImpl implements AgentService {
constructor(
private readonly internalEsClient: ElasticsearchClient,
private readonly soClient: SavedObjectsClientContract
) {}
public asScoped(req: KibanaRequest) {
const preflightCheck = async () => {
const authz = await getAuthzFromRequest(req);
if (!authz.fleet.all && !authz.fleet.readAgents) {
throw new FleetUnauthorizedError(
`User does not have adequate permissions to access Fleet agents.`
);
}
};
const soClient = appContextService.getInternalUserSOClientForSpaceId(
appContextService.getSavedObjects().getScopedClient(req).getCurrentNamespace()
);
return new AgentClientImpl(
this.internalEsClient,
soClient,
preflightCheck,
getCurrentNamespace(soClient)
);
}
public asInternalScopedUser(spaceId: string): AgentClient {
if (!spaceId) {
throw new TypeError(`spaceId argument is required!`);
}
const soClient = appContextService.getInternalUserSOClientForSpaceId(spaceId);
return new AgentClientImpl(
this.internalEsClient,
soClient,
undefined,
getCurrentNamespace(soClient)
);
}
public get asInternalUser() {
return new AgentClientImpl(this.internalEsClient, this.soClient);
}
}