-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
package_policy.ts
1403 lines (1234 loc) · 43.8 KB
/
package_policy.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 { omit, partition } from 'lodash';
import { i18n } from '@kbn/i18n';
import semverLt from 'semver/functions/lt';
import { getFlattenedObject } from '@kbn/std';
import type { KibanaRequest } from 'src/core/server';
import type {
ElasticsearchClient,
RequestHandlerContext,
SavedObjectsClientContract,
} from 'src/core/server';
import uuid from 'uuid';
import { safeLoad } from 'js-yaml';
import { DEFAULT_SPACE_ID } from '../../../spaces/common/constants';
import type { AuthenticatedUser } from '../../../security/server';
import {
packageToPackagePolicy,
packageToPackagePolicyInputs,
isPackageLimited,
doesAgentPolicyAlreadyIncludePackage,
validatePackagePolicy,
validationHasErrors,
SO_SEARCH_LIMIT,
getMaxPackageName,
} from '../../common';
import type {
DeletePackagePoliciesResponse,
UpgradePackagePolicyResponse,
PackagePolicyInput,
NewPackagePolicyInput,
PackagePolicyConfigRecordEntry,
PackagePolicyInputStream,
PackageInfo,
ListWithKuery,
ListResult,
UpgradePackagePolicyDryRunResponseItem,
RegistryDataStream,
} from '../../common';
import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../constants';
import {
IngestManagerError,
ingestErrorToResponseOptions,
PackagePolicyIneligibleForUpgradeError,
PackagePolicyValidationError,
} from '../errors';
import { NewPackagePolicySchema, UpdatePackagePolicySchema } from '../types';
import type {
NewPackagePolicy,
UpdatePackagePolicy,
PackagePolicy,
PackagePolicySOAttributes,
RegistryPackage,
DryRunPackagePolicy,
} from '../types';
import type { ExternalCallback } from '..';
import { agentPolicyService } from './agent_policy';
import { outputService } from './output';
import * as Registry from './epm/registry';
import { getPackageInfo, getInstallation, ensureInstalledPackage } from './epm/packages';
import { getAssetsData } from './epm/packages/assets';
import { compileTemplate } from './epm/agent/agent';
import { normalizeKuery } from './saved_object';
import { appContextService } from '.';
import { removeOldAssets } from './epm/packages/cleanup';
import type { PackageUpdateEvent, UpdateEventType } from './upgrade_sender';
import { sendTelemetryEvents } from './upgrade_sender';
export type InputsOverride = Partial<NewPackagePolicyInput> & {
vars?: Array<NewPackagePolicyInput['vars'] & { name: string }>;
};
const SAVED_OBJECT_TYPE = PACKAGE_POLICY_SAVED_OBJECT_TYPE;
export const DATA_STREAM_ALLOWED_INDEX_PRIVILEGES = new Set([
'auto_configure',
'create_doc',
'maintenance',
'monitor',
'read',
'read_cross_cluster',
]);
class PackagePolicyService {
public async create(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
packagePolicy: NewPackagePolicy,
options?: {
spaceId?: string;
id?: string;
user?: AuthenticatedUser;
bumpRevision?: boolean;
force?: boolean;
skipEnsureInstalled?: boolean;
skipUniqueNameVerification?: boolean;
overwrite?: boolean;
}
): Promise<PackagePolicy> {
if (!options?.skipUniqueNameVerification) {
const existingPoliciesWithName = await this.list(soClient, {
perPage: 1,
kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: "${packagePolicy.name}"`,
});
// Check that the name does not exist already
if (existingPoliciesWithName.items.length > 0) {
throw new IngestManagerError(
`There is already an integration policy with the same name: ${packagePolicy.name}`
);
}
}
let elasticsearch: PackagePolicy['elasticsearch'];
// Add ids to stream
const packagePolicyId = options?.id || uuid.v4();
let inputs: PackagePolicyInput[] = packagePolicy.inputs.map((input) =>
assignStreamIdToInput(packagePolicyId, input)
);
// Make sure the associated package is installed
if (packagePolicy.package?.name) {
const pkgInfoPromise = getPackageInfo({
savedObjectsClient: soClient,
pkgName: packagePolicy.package.name,
pkgVersion: packagePolicy.package.version,
});
let pkgInfo;
if (options?.skipEnsureInstalled) pkgInfo = await pkgInfoPromise;
else {
const [, packageInfo] = await Promise.all([
ensureInstalledPackage({
esClient,
spaceId: options?.spaceId || DEFAULT_SPACE_ID,
savedObjectsClient: soClient,
pkgName: packagePolicy.package.name,
pkgVersion: packagePolicy.package.version,
}),
pkgInfoPromise,
]);
pkgInfo = packageInfo;
}
// Check if it is a limited package, and if so, check that the corresponding agent policy does not
// already contain a package policy for this package
if (isPackageLimited(pkgInfo)) {
const agentPolicy = await agentPolicyService.get(soClient, packagePolicy.policy_id, true);
if (agentPolicy && doesAgentPolicyAlreadyIncludePackage(agentPolicy, pkgInfo.name)) {
throw new IngestManagerError(
`Unable to create package policy. Package '${pkgInfo.name}' already exists on this agent policy.`
);
}
}
validatePackagePolicyOrThrow(packagePolicy, pkgInfo);
const registryPkgInfo = await Registry.fetchInfo(pkgInfo.name, pkgInfo.version);
inputs = await this._compilePackagePolicyInputs(
registryPkgInfo,
pkgInfo,
packagePolicy.vars || {},
inputs
);
elasticsearch = registryPkgInfo.elasticsearch;
}
const isoDate = new Date().toISOString();
const newSo = await soClient.create<PackagePolicySOAttributes>(
SAVED_OBJECT_TYPE,
{
...packagePolicy,
inputs,
elasticsearch,
revision: 1,
created_at: isoDate,
created_by: options?.user?.username ?? 'system',
updated_at: isoDate,
updated_by: options?.user?.username ?? 'system',
},
{ ...options, id: packagePolicyId }
);
// Assign it to the given agent policy
await agentPolicyService.assignPackagePolicies(
soClient,
esClient,
packagePolicy.policy_id,
[newSo.id],
{
user: options?.user,
bumpRevision: options?.bumpRevision ?? true,
force: options?.force,
}
);
return {
id: newSo.id,
version: newSo.version,
...newSo.attributes,
};
}
public async bulkCreate(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
packagePolicies: NewPackagePolicy[],
agentPolicyId: string,
options?: { user?: AuthenticatedUser; bumpRevision?: boolean }
): Promise<PackagePolicy[]> {
const isoDate = new Date().toISOString();
// eslint-disable-next-line @typescript-eslint/naming-convention
const { saved_objects } = await soClient.bulkCreate<PackagePolicySOAttributes>(
packagePolicies.map((packagePolicy) => {
const packagePolicyId = uuid.v4();
const inputs = packagePolicy.inputs.map((input) =>
assignStreamIdToInput(packagePolicyId, input)
);
return {
type: SAVED_OBJECT_TYPE,
id: packagePolicyId,
attributes: {
...packagePolicy,
inputs,
policy_id: agentPolicyId,
revision: 1,
created_at: isoDate,
created_by: options?.user?.username ?? 'system',
updated_at: isoDate,
updated_by: options?.user?.username ?? 'system',
},
};
})
);
// Filter out invalid SOs
const newSos = saved_objects.filter((so) => !so.error && so.attributes);
// Assign it to the given agent policy
await agentPolicyService.assignPackagePolicies(
soClient,
esClient,
agentPolicyId,
newSos.map((newSo) => newSo.id),
{
user: options?.user,
bumpRevision: options?.bumpRevision ?? true,
}
);
return newSos.map((newSo) => ({
id: newSo.id,
version: newSo.version,
...newSo.attributes,
}));
}
public async get(
soClient: SavedObjectsClientContract,
id: string
): Promise<PackagePolicy | null> {
const packagePolicySO = await soClient.get<PackagePolicySOAttributes>(SAVED_OBJECT_TYPE, id);
if (!packagePolicySO) {
return null;
}
if (packagePolicySO.error) {
throw new Error(packagePolicySO.error.message);
}
return {
id: packagePolicySO.id,
version: packagePolicySO.version,
...packagePolicySO.attributes,
};
}
public async getByIDs(
soClient: SavedObjectsClientContract,
ids: string[]
): Promise<PackagePolicy[] | null> {
const packagePolicySO = await soClient.bulkGet<PackagePolicySOAttributes>(
ids.map((id) => ({
id,
type: SAVED_OBJECT_TYPE,
}))
);
if (!packagePolicySO) {
return null;
}
return packagePolicySO.saved_objects.map((so) => ({
id: so.id,
version: so.version,
...so.attributes,
}));
}
public async list(
soClient: SavedObjectsClientContract,
options: ListWithKuery
): Promise<ListResult<PackagePolicy>> {
const { page = 1, perPage = 20, sortField = 'updated_at', sortOrder = 'desc', kuery } = options;
const packagePolicies = await soClient.find<PackagePolicySOAttributes>({
type: SAVED_OBJECT_TYPE,
sortField,
sortOrder,
page,
perPage,
filter: kuery ? normalizeKuery(SAVED_OBJECT_TYPE, kuery) : undefined,
});
return {
items: packagePolicies?.saved_objects.map((packagePolicySO) => ({
id: packagePolicySO.id,
version: packagePolicySO.version,
...packagePolicySO.attributes,
})),
total: packagePolicies?.total,
page,
perPage,
};
}
public async listIds(
soClient: SavedObjectsClientContract,
options: ListWithKuery
): Promise<ListResult<string>> {
const { page = 1, perPage = 20, sortField = 'updated_at', sortOrder = 'desc', kuery } = options;
const packagePolicies = await soClient.find<{}>({
type: SAVED_OBJECT_TYPE,
sortField,
sortOrder,
page,
perPage,
fields: [],
filter: kuery ? normalizeKuery(SAVED_OBJECT_TYPE, kuery) : undefined,
});
return {
items: packagePolicies.saved_objects.map((packagePolicySO) => packagePolicySO.id),
total: packagePolicies.total,
page,
perPage,
};
}
public async update(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
id: string,
packagePolicy: UpdatePackagePolicy,
options?: { user?: AuthenticatedUser },
currentVersion?: string
): Promise<PackagePolicy> {
const oldPackagePolicy = await this.get(soClient, id);
const { version, ...restOfPackagePolicy } = packagePolicy;
if (!oldPackagePolicy) {
throw new Error('Package policy not found');
}
// Check that the name does not exist already but exclude the current package policy
const existingPoliciesWithName = await this.list(soClient, {
perPage: 1,
kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: "${packagePolicy.name}"`,
});
const filtered = (existingPoliciesWithName?.items || []).filter((p) => p.id !== id);
if (filtered.length > 0) {
throw new IngestManagerError('There is already an integration policy with the same name');
}
let inputs = restOfPackagePolicy.inputs.map((input) =>
assignStreamIdToInput(oldPackagePolicy.id, input)
);
inputs = enforceFrozenInputs(oldPackagePolicy.inputs, inputs);
let elasticsearch: PackagePolicy['elasticsearch'];
if (packagePolicy.package?.name) {
const pkgInfo = await getPackageInfo({
savedObjectsClient: soClient,
pkgName: packagePolicy.package.name,
pkgVersion: packagePolicy.package.version,
});
validatePackagePolicyOrThrow(packagePolicy, pkgInfo);
const registryPkgInfo = await Registry.fetchInfo(pkgInfo.name, pkgInfo.version);
inputs = await this._compilePackagePolicyInputs(
registryPkgInfo,
pkgInfo,
packagePolicy.vars || {},
inputs
);
elasticsearch = registryPkgInfo.elasticsearch;
}
await soClient.update<PackagePolicySOAttributes>(
SAVED_OBJECT_TYPE,
id,
{
...restOfPackagePolicy,
inputs,
elasticsearch,
revision: oldPackagePolicy.revision + 1,
updated_at: new Date().toISOString(),
updated_by: options?.user?.username ?? 'system',
},
{
version,
}
);
// Bump revision of associated agent policy
await agentPolicyService.bumpRevision(soClient, esClient, packagePolicy.policy_id, {
user: options?.user,
});
const newPolicy = (await this.get(soClient, id)) as PackagePolicy;
if (packagePolicy.package) {
await removeOldAssets({
soClient,
pkgName: packagePolicy.package.name,
currentVersion: packagePolicy.package.version,
});
if (packagePolicy.package.version !== currentVersion) {
const upgradeTelemetry: PackageUpdateEvent = {
packageName: packagePolicy.package.name,
currentVersion: currentVersion || 'unknown',
newVersion: packagePolicy.package.version,
status: 'success',
eventType: 'package-policy-upgrade' as UpdateEventType,
};
sendTelemetryEvents(
appContextService.getLogger(),
appContextService.getTelemetryEventsSender(),
upgradeTelemetry
);
appContextService.getLogger().info(`Package policy upgraded successfully`);
appContextService.getLogger().debug(JSON.stringify(upgradeTelemetry));
}
}
return newPolicy;
}
public async delete(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
ids: string[],
options?: { user?: AuthenticatedUser; skipUnassignFromAgentPolicies?: boolean; force?: boolean }
): Promise<DeletePackagePoliciesResponse> {
const result: DeletePackagePoliciesResponse = [];
for (const id of ids) {
try {
const packagePolicy = await this.get(soClient, id);
if (!packagePolicy) {
throw new Error('Package policy not found');
}
if (!options?.skipUnassignFromAgentPolicies) {
await agentPolicyService.unassignPackagePolicies(
soClient,
esClient,
packagePolicy.policy_id,
[packagePolicy.id],
{
user: options?.user,
force: options?.force,
}
);
}
await soClient.delete(SAVED_OBJECT_TYPE, id);
result.push({
id,
name: packagePolicy.name,
success: true,
package: {
name: packagePolicy.package?.name || '',
title: packagePolicy.package?.title || '',
version: packagePolicy.package?.version || '',
},
policy_id: packagePolicy.policy_id,
});
} catch (error) {
result.push({
id,
success: false,
...ingestErrorToResponseOptions(error),
});
}
}
return result;
}
public async getUpgradePackagePolicyInfo(soClient: SavedObjectsClientContract, id: string) {
const packagePolicy = await this.get(soClient, id);
if (!packagePolicy) {
throw new IngestManagerError(
i18n.translate('xpack.fleet.packagePolicy.policyNotFoundError', {
defaultMessage: 'Package policy with id {id} not found',
values: { id },
})
);
}
if (!packagePolicy.package?.name) {
throw new IngestManagerError(
i18n.translate('xpack.fleet.packagePolicy.packageNotFoundError', {
defaultMessage: 'Package policy with id {id} has no named package',
values: { id },
})
);
}
const installedPackage = await getInstallation({
savedObjectsClient: soClient,
pkgName: packagePolicy.package.name,
});
if (!installedPackage) {
throw new IngestManagerError(
i18n.translate('xpack.fleet.packagePolicy.packageNotInstalledError', {
defaultMessage: 'Package {name} is not installed',
values: {
name: packagePolicy.package.name,
},
})
);
}
const packageInfo = await getPackageInfo({
savedObjectsClient: soClient,
pkgName: packagePolicy.package.name,
pkgVersion: installedPackage?.version ?? '',
});
const isInstalledVersionLessThanPolicyVersion = semverLt(
packageInfo?.version ?? '',
packagePolicy.package.version
);
if (isInstalledVersionLessThanPolicyVersion) {
throw new PackagePolicyIneligibleForUpgradeError(
i18n.translate('xpack.fleet.packagePolicy.ineligibleForUpgradeError', {
defaultMessage:
"Package policy {id}'s package version {version} of package {name} is newer than the installed package version. Please install the latest version of {name}.",
values: {
id: packagePolicy.id,
name: packagePolicy.package.name,
version: packagePolicy.package.version,
},
})
);
}
return {
packagePolicy: packagePolicy as Required<PackagePolicy>,
packageInfo,
};
}
public async upgrade(
soClient: SavedObjectsClientContract,
esClient: ElasticsearchClient,
ids: string[],
options?: { user?: AuthenticatedUser }
): Promise<UpgradePackagePolicyResponse> {
const result: UpgradePackagePolicyResponse = [];
for (const id of ids) {
try {
const { packagePolicy, packageInfo } = await this.getUpgradePackagePolicyInfo(soClient, id);
const updatePackagePolicy = updatePackageInputs(
{
...omit(packagePolicy, 'id'),
inputs: packagePolicy.inputs,
package: {
...packagePolicy.package,
version: packageInfo.version,
},
},
packageInfo,
packageToPackagePolicyInputs(packageInfo) as InputsOverride[]
);
const registryPkgInfo = await Registry.fetchInfo(packageInfo.name, packageInfo.version);
updatePackagePolicy.inputs = await this._compilePackagePolicyInputs(
registryPkgInfo,
packageInfo,
updatePackagePolicy.vars || {},
updatePackagePolicy.inputs as PackagePolicyInput[]
);
updatePackagePolicy.elasticsearch = registryPkgInfo.elasticsearch;
await this.update(
soClient,
esClient,
id,
updatePackagePolicy,
options,
packagePolicy.package.version
);
result.push({
id,
name: packagePolicy.name,
success: true,
});
} catch (error) {
result.push({
id,
success: false,
...ingestErrorToResponseOptions(error),
});
}
}
return result;
}
public async getUpgradeDryRunDiff(
soClient: SavedObjectsClientContract,
id: string
): Promise<UpgradePackagePolicyDryRunResponseItem> {
try {
const { packagePolicy, packageInfo } = await this.getUpgradePackagePolicyInfo(soClient, id);
const updatedPackagePolicy = updatePackageInputs(
{
...omit(packagePolicy, 'id'),
inputs: packagePolicy.inputs,
package: {
...packagePolicy.package,
version: packageInfo.version,
},
},
packageInfo,
packageToPackagePolicyInputs(packageInfo) as InputsOverride[],
true
);
const registryPkgInfo = await Registry.fetchInfo(packageInfo.name, packageInfo.version);
updatedPackagePolicy.inputs = await this._compilePackagePolicyInputs(
registryPkgInfo,
packageInfo,
updatedPackagePolicy.vars || {},
updatedPackagePolicy.inputs as PackagePolicyInput[]
);
updatedPackagePolicy.elasticsearch = registryPkgInfo.elasticsearch;
const hasErrors = 'errors' in updatedPackagePolicy;
if (packagePolicy.package.version !== packageInfo.version) {
const upgradeTelemetry: PackageUpdateEvent = {
packageName: packageInfo.name,
currentVersion: packagePolicy.package.version,
newVersion: packageInfo.version,
status: hasErrors ? 'failure' : 'success',
error: hasErrors ? updatedPackagePolicy.errors : undefined,
dryRun: true,
eventType: 'package-policy-upgrade' as UpdateEventType,
};
sendTelemetryEvents(
appContextService.getLogger(),
appContextService.getTelemetryEventsSender(),
upgradeTelemetry
);
appContextService
.getLogger()
.info(
`Package policy upgrade dry run ${
hasErrors ? 'resulted in errors' : 'ran successfully'
}`
);
appContextService.getLogger().debug(JSON.stringify(upgradeTelemetry));
}
return {
name: updatedPackagePolicy.name,
diff: [packagePolicy, updatedPackagePolicy],
hasErrors,
};
} catch (error) {
return {
hasErrors: true,
...ingestErrorToResponseOptions(error),
};
}
}
public async enrichPolicyWithDefaultsFromPackage(
soClient: SavedObjectsClientContract,
newPolicy: NewPackagePolicy
): Promise<NewPackagePolicy> {
let newPackagePolicy: NewPackagePolicy = newPolicy;
if (newPolicy.package) {
const newPP = await this.buildPackagePolicyFromPackageWithVersion(
soClient,
newPolicy.package.name,
newPolicy.package.version
);
if (newPP) {
const inputs = newPolicy.inputs.map((input) => {
const defaultInput = newPP.inputs.find(
(i) =>
i.type === input.type &&
(!input.policy_template || input.policy_template === i.policy_template)
);
return {
...defaultInput,
enabled: input.enabled,
type: input.type,
// to propagate "enabled: false" to streams
streams: defaultInput?.streams?.map((stream) => ({
...stream,
enabled: input.enabled,
})),
} as NewPackagePolicyInput;
});
let agentPolicyId;
// fallback to first agent policy id in case no policy_id is specified, BWC with 8.0
if (!newPolicy.policy_id) {
const { items: agentPolicies } = await agentPolicyService.list(soClient, {
perPage: 1,
});
if (agentPolicies.length > 0) {
agentPolicyId = agentPolicies[0].id;
}
}
newPackagePolicy = {
...newPP,
name: newPolicy.name,
namespace: newPolicy.namespace ?? 'default',
description: newPolicy.description ?? '',
enabled: newPolicy.enabled ?? true,
policy_id: newPolicy.policy_id ?? agentPolicyId,
output_id: newPolicy.output_id ?? '',
inputs: newPolicy.inputs[0]?.streams ? newPolicy.inputs : inputs,
vars: newPolicy.vars || newPP.vars,
};
}
}
return newPackagePolicy;
}
public async buildPackagePolicyFromPackageWithVersion(
soClient: SavedObjectsClientContract,
pkgName: string,
pkgVersion: string
): Promise<NewPackagePolicy | undefined> {
const packageInfo = await getPackageInfo({
savedObjectsClient: soClient,
pkgName,
pkgVersion,
});
if (packageInfo) {
return packageToPackagePolicy(packageInfo, '', '');
}
}
public async buildPackagePolicyFromPackage(
soClient: SavedObjectsClientContract,
pkgName: string
): Promise<NewPackagePolicy | undefined> {
const pkgInstall = await getInstallation({ savedObjectsClient: soClient, pkgName });
if (pkgInstall) {
const [packageInfo, defaultOutputId] = await Promise.all([
getPackageInfo({
savedObjectsClient: soClient,
pkgName: pkgInstall.name,
pkgVersion: pkgInstall.version,
}),
outputService.getDefaultDataOutputId(soClient),
]);
if (packageInfo) {
if (!defaultOutputId) {
throw new Error('Default output is not set');
}
return packageToPackagePolicy(packageInfo, '', defaultOutputId);
}
}
}
public async _compilePackagePolicyInputs(
registryPkgInfo: RegistryPackage,
pkgInfo: PackageInfo,
vars: PackagePolicy['vars'],
inputs: PackagePolicyInput[]
): Promise<PackagePolicyInput[]> {
const inputsPromises = inputs.map(async (input) => {
const compiledInput = await _compilePackagePolicyInput(registryPkgInfo, pkgInfo, vars, input);
const compiledStreams = await _compilePackageStreams(registryPkgInfo, pkgInfo, vars, input);
return {
...input,
compiled_input: compiledInput,
streams: compiledStreams,
};
});
return Promise.all(inputsPromises);
}
public async runExternalCallbacks<A extends ExternalCallback[0]>(
externalCallbackType: A,
packagePolicy: A extends 'postPackagePolicyDelete'
? DeletePackagePoliciesResponse
: NewPackagePolicy,
context: RequestHandlerContext,
request: KibanaRequest
): Promise<A extends 'postPackagePolicyDelete' ? void : NewPackagePolicy>;
public async runExternalCallbacks(
externalCallbackType: ExternalCallback[0],
packagePolicy: NewPackagePolicy | DeletePackagePoliciesResponse,
context: RequestHandlerContext,
request: KibanaRequest
): Promise<NewPackagePolicy | void> {
if (externalCallbackType === 'postPackagePolicyDelete') {
return await this.runDeleteExternalCallbacks(packagePolicy as DeletePackagePoliciesResponse);
} else {
if (!Array.isArray(packagePolicy)) {
let newData = packagePolicy;
const externalCallbacks = appContextService.getExternalCallbacks(externalCallbackType);
if (externalCallbacks && externalCallbacks.size > 0) {
let updatedNewData = newData;
for (const callback of externalCallbacks) {
const result = await callback(updatedNewData, context, request);
if (externalCallbackType === 'packagePolicyCreate') {
updatedNewData = NewPackagePolicySchema.validate(result);
} else if (externalCallbackType === 'packagePolicyUpdate') {
updatedNewData = UpdatePackagePolicySchema.validate(result);
}
}
newData = updatedNewData;
}
return newData;
}
}
}
public async runDeleteExternalCallbacks(
deletedPackagePolicies: DeletePackagePoliciesResponse
): Promise<void> {
const externalCallbacks = appContextService.getExternalCallbacks('postPackagePolicyDelete');
const errorsThrown: Error[] = [];
if (externalCallbacks && externalCallbacks.size > 0) {
for (const callback of externalCallbacks) {
// Failures from an external callback should not prevent other external callbacks from being
// executed. Errors (if any) will be collected and `throw`n after processing the entire set
try {
await callback(deletedPackagePolicies);
} catch (error) {
errorsThrown.push(error);
}
}
if (errorsThrown.length > 0) {
throw new IngestManagerError(
`${errorsThrown.length} encountered while executing package delete external callbacks`,
errorsThrown
);
}
}
}
}
function validatePackagePolicyOrThrow(packagePolicy: NewPackagePolicy, pkgInfo: PackageInfo) {
const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, safeLoad);
if (validationHasErrors(validationResults)) {
const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults))
.map(([key, value]) => ({
key,
message: value,
}))
.filter(({ message }) => !!message);
if (responseFormattedValidationErrors.length) {
throw new PackagePolicyValidationError(
i18n.translate('xpack.fleet.packagePolicyInvalidError', {
defaultMessage: 'Package policy is invalid: {errors}',
values: {
errors: responseFormattedValidationErrors
.map(({ key, message }) => `${key}: ${message}`)
.join('\n'),
},
})
);
}
}
}
function assignStreamIdToInput(packagePolicyId: string, input: NewPackagePolicyInput) {
return {
...input,
streams: input.streams.map((stream) => {
return { ...stream, id: `${input.type}-${stream.data_stream.dataset}-${packagePolicyId}` };
}),
};
}
async function _compilePackagePolicyInput(
registryPkgInfo: RegistryPackage,
pkgInfo: PackageInfo,
vars: PackagePolicy['vars'],
input: PackagePolicyInput
) {
const packagePolicyTemplate = input.policy_template
? pkgInfo.policy_templates?.find(
(policyTemplate) => policyTemplate.name === input.policy_template
)
: pkgInfo.policy_templates?.[0];
if (!input.enabled || !packagePolicyTemplate || !packagePolicyTemplate.inputs?.length) {
return undefined;
}
const packageInputs = packagePolicyTemplate.inputs;
const packageInput = packageInputs.find((pkgInput) => pkgInput.type === input.type);
if (!packageInput) {
throw new Error(`Input template not found, unable to find input type ${input.type}`);
}
if (!packageInput.template_path) {
return undefined;
}
const [pkgInputTemplate] = await getAssetsData(registryPkgInfo, (path: string) =>
path.endsWith(`/agent/input/${packageInput.template_path!}`)
);
if (!pkgInputTemplate || !pkgInputTemplate.buffer) {
throw new Error(`Unable to load input template at /agent/input/${packageInput.template_path!}`);
}
return compileTemplate(
// Populate template variables from package- and input-level vars
Object.assign({}, vars, input.vars),
pkgInputTemplate.buffer.toString()
);
}
async function _compilePackageStreams(
registryPkgInfo: RegistryPackage,
pkgInfo: PackageInfo,
vars: PackagePolicy['vars'],
input: PackagePolicyInput
) {
const streamsPromises = input.streams.map((stream) =>
_compilePackageStream(registryPkgInfo, pkgInfo, vars, input, stream)
);
return await Promise.all(streamsPromises);
}
// temporary export to enable testing pending refactor https://github.com/elastic/kibana/issues/112386
export function _applyIndexPrivileges(
packageDataStream: RegistryDataStream,
stream: PackagePolicyInputStream
): PackagePolicyInputStream {
const streamOut = { ...stream };
const indexPrivileges = packageDataStream?.elasticsearch?.privileges?.indices;
if (!indexPrivileges?.length) {
return streamOut;
}
const [valid, invalid] = partition(indexPrivileges, (permission) =>
DATA_STREAM_ALLOWED_INDEX_PRIVILEGES.has(permission)
);
if (invalid.length) {
appContextService
.getLogger()
.warn(
`Ignoring invalid or forbidden index privilege(s) in "${stream.id}" data stream: ${invalid}`
);
}
if (valid.length) {
stream.data_stream.elasticsearch = {
privileges: {
indices: valid,