-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathcreate_rule.ts
205 lines (184 loc) · 7.07 KB
/
create_rule.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
/*
* 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 Semver from 'semver';
import Boom from '@hapi/boom';
import { SavedObject, SavedObjectsUtils } from '@kbn/core/server';
import { withSpan } from '@kbn/apm-utils';
import { parseDuration } from '../../../../common/parse_duration';
import { WriteOperations, AlertingAuthorizationEntity } from '../../../authorization';
import { validateRuleTypeParams, getRuleNotifyWhenType, getDefaultMonitoring } from '../../../lib';
import { getRuleExecutionStatusPending } from '../../../lib/rule_execution_status';
import {
extractReferences,
validateActions,
addGeneratedActionValues,
} from '../../../rules_client/lib';
import { generateAPIKeyName, apiKeyAsAlertAttributes } from '../../../rules_client/common';
import { ruleAuditEvent, RuleAuditAction } from '../../../rules_client/common/audit_events';
import { RulesClientContext } from '../../../rules_client/types';
import { Rule, RuleDomain, RuleParams } from '../types';
import { SanitizedRule } from '../../../types';
import {
transformRuleAttributesToRuleDomain,
transformRuleDomainToRuleAttributes,
transformRuleDomainToRule,
} from '../transforms';
import { ruleDomainSchema } from '../schemas';
import { RuleAttributes } from '../../../data/rule/types';
import type { CreateRuleData } from './types';
import { createRuleDataSchema } from './schemas';
import { createRuleSavedObject } from '../../../rules_client/lib';
export interface CreateRuleOptions {
id?: string;
}
export interface CreateRuleParams<Params extends RuleParams = never> {
data: CreateRuleData<Params>;
options?: CreateRuleOptions;
allowMissingConnectorSecrets?: boolean;
}
export async function createRule<Params extends RuleParams = never>(
context: RulesClientContext,
createParams: CreateRuleParams<Params>
// TODO (http-versioning): This should be of type Rule, change this when all rule types are fixed
): Promise<SanitizedRule<Params>> {
const { data: initialData, options, allowMissingConnectorSecrets } = createParams;
const data = { ...initialData, actions: addGeneratedActionValues(initialData.actions) };
const id = options?.id || SavedObjectsUtils.generateId();
try {
createRuleDataSchema.validate(data);
} catch (error) {
throw Boom.badRequest(`Error validating create data - ${error.message}`);
}
try {
await withSpan({ name: 'authorization.ensureAuthorized', type: 'rules' }, () =>
context.authorization.ensureAuthorized({
ruleTypeId: data.alertTypeId,
consumer: data.consumer,
operation: WriteOperations.Create,
entity: AlertingAuthorizationEntity.Rule,
})
);
} catch (error) {
context.auditLogger?.log(
ruleAuditEvent({
action: RuleAuditAction.CREATE,
savedObject: { type: 'alert', id },
error,
})
);
throw error;
}
context.ruleTypeRegistry.ensureRuleTypeEnabled(data.alertTypeId);
// Throws an error if alert type isn't registered
const ruleType = context.ruleTypeRegistry.get(data.alertTypeId);
const validatedAlertTypeParams = validateRuleTypeParams(data.params, ruleType.validate.params);
const username = await context.getUserName();
let createdAPIKey = null;
let isAuthTypeApiKey = false;
try {
isAuthTypeApiKey = context.isAuthenticationTypeAPIKey();
const name = generateAPIKeyName(ruleType.id, data.name);
createdAPIKey = data.enabled
? isAuthTypeApiKey
? context.getAuthenticationAPIKey(`${name}-user-created`)
: await withSpan(
{
name: 'createAPIKey',
type: 'rules',
},
() => context.createAPIKey(name)
)
: null;
} catch (error) {
throw Boom.badRequest(`Error creating rule: could not create API key - ${error.message}`);
}
await withSpan({ name: 'validateActions', type: 'rules' }, () =>
validateActions(context, ruleType, data, allowMissingConnectorSecrets)
);
// Throw error if schedule interval is less than the minimum and we are enforcing it
const intervalInMs = parseDuration(data.schedule.interval);
if (
intervalInMs < context.minimumScheduleIntervalInMs &&
context.minimumScheduleInterval.enforce
) {
throw Boom.badRequest(
`Error creating rule: the interval is less than the allowed minimum interval of ${context.minimumScheduleInterval.value}`
);
}
// Extract saved object references for this rule
const {
references,
params: updatedParams,
actions,
} = await withSpan({ name: 'extractReferences', type: 'rules' }, () =>
extractReferences(context, ruleType, data.actions, validatedAlertTypeParams)
);
const createTime = Date.now();
const lastRunTimestamp = new Date();
const legacyId = Semver.lt(context.kibanaVersion, '8.0.0') ? id : null;
const notifyWhen = getRuleNotifyWhenType(data.notifyWhen ?? null, data.throttle ?? null);
const throttle = data.throttle ?? null;
// Convert domain rule object to ES rule attributes
const ruleAttributes = transformRuleDomainToRuleAttributes(
{
...data,
...apiKeyAsAlertAttributes(createdAPIKey, username, isAuthTypeApiKey),
id,
createdBy: username,
updatedBy: username,
createdAt: new Date(createTime),
updatedAt: new Date(createTime),
snoozeSchedule: [],
muteAll: false,
mutedInstanceIds: [],
notifyWhen,
throttle,
executionStatus: getRuleExecutionStatusPending(lastRunTimestamp.toISOString()),
monitoring: getDefaultMonitoring(lastRunTimestamp.toISOString()) as Rule['monitoring'],
revision: 0,
running: false,
},
{
legacyId,
actionsWithRefs: actions as RuleAttributes['actions'],
paramsWithRefs: updatedParams,
}
);
const createdRuleSavedObject: SavedObject<RuleAttributes> = await withSpan(
{ name: 'createRuleSavedObject', type: 'rules' },
() =>
createRuleSavedObject(context, {
intervalInMs,
rawRule: ruleAttributes,
references,
ruleId: id,
options,
returnRuleAttributes: true,
})
);
// Convert ES RuleAttributes back to domain rule object
const ruleDomain: RuleDomain<Params> = transformRuleAttributesToRuleDomain<Params>(
createdRuleSavedObject.attributes,
{
id: createdRuleSavedObject.id,
logger: context.logger,
ruleType: context.ruleTypeRegistry.get(createdRuleSavedObject.attributes.alertTypeId),
references,
}
);
// Try to validate created rule, but don't throw.
try {
ruleDomainSchema.validate(ruleDomain);
} catch (e) {
context.logger.warn(`Error validating rule domain object for id: ${id}, ${e}`);
}
// Convert domain rule to rule (Remove certain properties)
const rule = transformRuleDomainToRule<Params>(ruleDomain, { isPublic: true });
// TODO (http-versioning): Remove this cast, this enables us to move forward
// without fixing all of other solution types
return rule as SanitizedRule<Params>;
}