-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathPolicyForm.tsx
More file actions
837 lines (763 loc) · 25.7 KB
/
Copy pathPolicyForm.tsx
File metadata and controls
837 lines (763 loc) · 25.7 KB
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
/* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role */
/* eslint-disable jsx-a11y/interactive-supports-focus */
import React, { useState, useContext, useEffect, useMemo } from "react";
import { useQuery, useQueryClient } from "react-query";
import { Ace } from "ace-builds";
import { useDebouncedCallback } from "use-debounce";
import { size } from "lodash";
import { InjectedRouter } from "react-router";
import { AppContext } from "context/app";
import { NotificationContext } from "context/notification";
import { PolicyContext } from "context/policy";
import usePlatformCompatibility from "hooks/usePlatformCompatibility";
import usePlatformSelector from "hooks/usePlatformSelector";
import PATHS from "router/paths";
import {
getCustomTargetOptions,
LabelScope,
} from "components/TargetLabelSelector/labelScopes";
import { getPathWithQueryParams } from "utilities/url";
import { IPolicy, IPolicyFormData } from "interfaces/policy";
import {
APP_CONTEXT_ALL_TEAMS_SUMMARY,
APP_CONTEXT_NO_TEAM_SUMMARY,
} from "interfaces/team";
import { CommaSeparatedPlatformString } from "interfaces/platform";
import { DEFAULT_POLICIES } from "pages/policies/constants";
import {
DEFAULT_USE_QUERY_OPTIONS,
LEARN_MORE_ABOUT_BASE_LINK,
} from "utilities/constants";
import SQLEditor from "components/SQLEditor";
import {
validateQuery,
EMPTY_QUERY_ERR,
} from "components/forms/validators/validate_query";
import Button from "components/buttons/Button";
import Checkbox from "components/forms/fields/Checkbox";
import TooltipWrapper from "components/TooltipWrapper";
import Spinner from "components/Spinner";
import Icon from "components/Icon/Icon";
// @ts-ignore
import InputField from "components/forms/fields/InputField";
import GitOpsModeTooltipWrapper from "components/GitOpsModeTooltipWrapper";
import CustomLink from "components/CustomLink";
import TargetLabelSelector from "components/TargetLabelSelector";
import labelsAPI, {
getCustomLabels,
ILabelsSummaryResponse,
} from "services/entities/labels";
import teamPoliciesAPI from "services/entities/team_policies";
import SaveNewPolicyModal from "../SaveNewPolicyModal";
import PolicyAutomations from "../PolicyAutomations";
const baseClass = "policy-form";
interface IPolicyFormProps {
router: InjectedRouter;
teamIdForApi?: number;
policyIdForEdit: number | null;
showOpenSchemaActionText: boolean;
storedPolicy: IPolicy | undefined;
isStoredPolicyLoading: boolean;
isTeamObserver: boolean;
isUpdatingPolicy: boolean;
onCreatePolicy: (formData: IPolicyFormData) => void;
onOsqueryTableSelect: (tableName: string) => void;
goToSelectTargets: () => void;
onUpdate: (formData: IPolicyFormData) => void;
onOpenSchemaSidebar: () => void;
renderLiveQueryWarning: () => JSX.Element | null;
backendValidators: { [key: string]: string };
isFetchingAutofillDescription: boolean;
isFetchingAutofillResolution: boolean;
onClickAutofillDescription: () => Promise<void>;
onClickAutofillResolution: () => Promise<void>;
resetAiAutofillData: () => void;
currentAutomatedPolicies: number[];
onCancel?: () => void;
}
const validateQuerySQL = (query: string) => {
const errors: { [key: string]: any } = {};
const { error: queryError, valid: queryValid } = validateQuery(query);
if (!queryValid) {
errors.query = queryError;
}
const valid = !size(errors);
return { valid, errors };
};
const PolicyForm = ({
router,
teamIdForApi,
policyIdForEdit,
showOpenSchemaActionText,
storedPolicy,
isStoredPolicyLoading,
isTeamObserver,
isUpdatingPolicy,
onCreatePolicy,
onOsqueryTableSelect,
goToSelectTargets,
onUpdate,
onOpenSchemaSidebar,
renderLiveQueryWarning,
backendValidators,
isFetchingAutofillDescription,
isFetchingAutofillResolution,
onClickAutofillDescription,
onClickAutofillResolution,
resetAiAutofillData,
currentAutomatedPolicies,
onCancel,
}: IPolicyFormProps): JSX.Element => {
const [errors, setErrors] = useState<{ [key: string]: any }>({}); // string | null | undefined or boolean | undefined
const [isSaveNewPolicyModalOpen, setIsSaveNewPolicyModalOpen] = useState(
false
);
const [showQueryEditor, setShowQueryEditor] = useState(false);
const [selectedTargetType, setSelectedTargetType] = useState("All hosts");
const [selectedCustomTarget, setSelectedCustomTarget] = useState<LabelScope>(
"labelsIncludeAny"
);
const [selectedLabels, setSelectedLabels] = useState({});
const isPatchPolicy = storedPolicy?.type === "patch";
const [isAddingAutomation, setIsAddingAutomation] = useState(false);
// Note: The PolicyContext values should always be used for any mutable policy data such as query name
// The storedPolicy prop should only be used to access immutable metadata such as author id
const {
lastEditedQueryId,
lastEditedQueryName,
lastEditedQueryDescription,
lastEditedQueryBody,
lastEditedQueryResolution,
lastEditedQueryCritical,
lastEditedQueryPlatform,
lastEditedQueryLabelsIncludeAny,
lastEditedQueryLabelsIncludeAll,
lastEditedQueryLabelsExcludeAny,
defaultPolicy,
setLastEditedQueryName,
setLastEditedQueryDescription,
setLastEditedQueryBody,
setLastEditedQueryResolution,
setLastEditedQueryCritical,
setLastEditedQueryPlatform,
} = useContext(PolicyContext);
const onSelectLabel = ({
name: labelName,
value,
}: {
name: string;
value: boolean;
}) => {
setSelectedLabels({
...selectedLabels,
[labelName]: value,
});
};
const { renderFlash } = useContext(NotificationContext);
const queryClient = useQueryClient();
const {
currentTeam,
isGlobalObserver,
isTeamTechnician,
isGlobalTechnician,
isOnGlobalTeam,
isPremiumTier,
config,
isFreeTier,
} = useContext(AppContext);
const customTargetOptions = useMemo(
() => getCustomTargetOptions({ entity: "policy", isPremiumTier }),
[isPremiumTier]
);
const { data: { labels } = { labels: [] } } = useQuery<
ILabelsSummaryResponse,
Error
>(
["custom_labels", currentTeam],
() => labelsAPI.summary(currentTeam?.id, true),
{
...DEFAULT_USE_QUERY_OPTIONS,
// Wait for the current team to load from context before pulling labels, otherwise on a page load
// directly on the policies new/edit page this gets called with currentTeam not set, then again
// with the correct team value. If we don't trigger on currentTeam changes we'll just start with a
// null team ID here and never populate with the correct team unless we navigate from another page
// where team context is already set prior to navigation.
enabled: isPremiumTier && !!currentTeam,
staleTime: 10000,
select: (res) => ({ labels: getCustomLabels(res.labels) }),
}
);
const disabledLiveQuery = config?.server_settings.live_query_disabled;
const aiFeaturesDisabled =
config?.server_settings.ai_features_disabled || false;
const gitOpsModeEnabled = config?.gitops.gitops_mode_enabled;
const debounceSQL = useDebouncedCallback((sql: string) => {
const { errors: newErrors } = validateQuerySQL(sql);
setErrors({
...newErrors,
});
}, 500);
const platformCompatibility = usePlatformCompatibility();
const {
getCompatiblePlatforms,
setCompatiblePlatforms,
} = platformCompatibility;
const platformSelectorDisabled =
isFetchingAutofillDescription ||
isFetchingAutofillResolution ||
gitOpsModeEnabled;
const platformSelector = usePlatformSelector(
lastEditedQueryPlatform,
baseClass,
platformSelectorDisabled,
storedPolicy?.install_software,
currentTeam?.id
);
const {
getSelectedPlatforms,
setSelectedPlatforms,
isAnyPlatformSelected,
} = platformSelector;
policyIdForEdit = policyIdForEdit || 0;
const isEditMode = !!policyIdForEdit && !isTeamObserver && !isGlobalObserver;
const isNewTemplatePolicy =
!policyIdForEdit &&
DEFAULT_POLICIES.find((p) => p.name === lastEditedQueryName);
/* - Observer/Observer+ and Technicians cannot edit existing policies
- Team users cannot edit inherited policies
Reroute edit existing policy page (/:policyId/edit) to policy details page (/:policyId) */
useEffect(() => {
const isInheritedPolicy = isEditMode && storedPolicy?.team_id === null;
const noEditPermissions =
isTeamObserver ||
isGlobalObserver ||
isTeamTechnician ||
isGlobalTechnician ||
(!isOnGlobalTeam && isInheritedPolicy); // Team user viewing inherited policy
if (
!isStoredPolicyLoading && // Confirms teamId for storedQuery before RBAC reroute
policyIdForEdit &&
policyIdForEdit > 0 &&
noEditPermissions
) {
router.push(
getPathWithQueryParams(PATHS.POLICY_DETAILS(policyIdForEdit), {
fleet_id: teamIdForApi,
})
);
}
}, [
policyIdForEdit,
isEditMode,
isStoredPolicyLoading,
isTeamObserver,
isGlobalObserver,
isTeamTechnician,
isGlobalTechnician,
isOnGlobalTeam,
storedPolicy?.team_id,
router,
teamIdForApi,
]);
useEffect(() => {
setSelectedTargetType(
!lastEditedQueryLabelsIncludeAny.length &&
!lastEditedQueryLabelsIncludeAll.length &&
!lastEditedQueryLabelsExcludeAny.length
? "All hosts"
: "Custom"
);
let customTarget: LabelScope | undefined;
let activeLabels: typeof lastEditedQueryLabelsIncludeAny = [];
if (lastEditedQueryLabelsExcludeAny.length) {
customTarget = "labelsExcludeAny";
activeLabels = lastEditedQueryLabelsExcludeAny;
} else if (lastEditedQueryLabelsIncludeAll.length) {
customTarget = "labelsIncludeAll";
activeLabels = lastEditedQueryLabelsIncludeAll;
} else if (lastEditedQueryLabelsIncludeAny.length) {
customTarget = "labelsIncludeAny";
activeLabels = lastEditedQueryLabelsIncludeAny;
}
if (customTarget) {
setSelectedCustomTarget(customTarget);
}
setSelectedLabels(
activeLabels.reduce((acc, label) => {
return {
...acc,
[label.name]: true,
};
}, {})
);
}, [
lastEditedQueryLabelsIncludeAny,
lastEditedQueryLabelsIncludeAll,
lastEditedQueryLabelsExcludeAny,
]);
useEffect(() => {
if (isNewTemplatePolicy) {
setCompatiblePlatforms(lastEditedQueryBody);
}
}, []);
useEffect(() => {
debounceSQL(lastEditedQueryBody);
if (
(policyIdForEdit && policyIdForEdit !== lastEditedQueryId) ||
(isNewTemplatePolicy && !lastEditedQueryBody)
) {
return;
}
setCompatiblePlatforms(lastEditedQueryBody);
}, [lastEditedQueryBody, lastEditedQueryId]);
const onLoad = (editor: Ace.Editor) => {
editor.setOptions({
enableLinking: true,
enableMultiselect: false, // Disables command + click creating multiple cursors
} as any);
// @ts-expect-error
// the string "linkClick" is not officially in the lib but we need it
editor.on("linkClick", (data: EditorSession) => {
const { type, value } = data.token;
if (type === "osquery-token") {
return onOsqueryTableSelect(value);
}
return false;
});
};
const onChangePolicySql = (sqlString: string) => {
setLastEditedQueryBody(sqlString);
resetAiAutofillData(); // Allows retry of AI autofill API if the SQL has changed
};
const onAddPatchAutomation = async () => {
if (
!storedPolicy?.patch_software?.software_title_id ||
storedPolicy?.team_id == null
) {
return;
}
setIsAddingAutomation(true);
try {
await teamPoliciesAPI.update(policyIdForEdit as number, {
team_id: storedPolicy.team_id,
software_title_id: storedPolicy.patch_software.software_title_id,
});
queryClient.invalidateQueries(["policy", policyIdForEdit]);
renderFlash("success", "Automation added.");
} catch {
renderFlash("error", "Couldn't set automation. Please try again.");
} finally {
setIsAddingAutomation(false);
}
};
const promptSavePolicy = () => (evt: React.MouseEvent<HTMLButtonElement>) => {
evt.preventDefault();
if (isEditMode && !lastEditedQueryName) {
return setErrors({
...errors,
name: "Policy name must be present",
});
}
if (isEditMode && !isPatchPolicy && !isAnyPlatformSelected) {
return setErrors({
...errors,
name: "At least one platform must be selected",
});
}
if (isPatchPolicy && isEditMode) {
// Patch policies: only send editable fields, not query/platform
const payload: IPolicyFormData = {
name: lastEditedQueryName,
description: lastEditedQueryDescription,
resolution: lastEditedQueryResolution,
};
if (isPremiumTier) {
payload.critical = lastEditedQueryCritical;
}
onUpdate(payload);
return;
}
// Synchronously block empty queries. The button-level `disableSaveFormErrors`
// relies on the debounced `errors.query`, so a fast click before the debounce
// fires could otherwise submit an empty query. Mirrors the guard in
// EditQueryForm's handleSaveQuery (see #38348).
if (!lastEditedQueryBody?.trim()) {
return setErrors({
...errors,
query: EMPTY_QUERY_ERR,
});
}
let selectedPlatforms = getSelectedPlatforms();
if (selectedPlatforms.length === 0 && !isEditMode && !defaultPolicy) {
// If no platforms are selected, default to all compatible platforms
selectedPlatforms = getCompatiblePlatforms();
setSelectedPlatforms(selectedPlatforms);
}
const newPlatformString = selectedPlatforms.join(
","
) as CommaSeparatedPlatformString;
if (!defaultPolicy) {
setLastEditedQueryPlatform(newPlatformString);
}
if (!isEditMode) {
setIsSaveNewPolicyModalOpen(true);
} else {
const payload: IPolicyFormData = {
name: lastEditedQueryName,
description: lastEditedQueryDescription,
query: lastEditedQueryBody,
resolution: lastEditedQueryResolution,
platform: newPlatformString,
};
if (isPremiumTier) {
const customLabelNames =
selectedTargetType === "Custom"
? Object.entries(selectedLabels)
.filter(([, selected]) => selected)
.map(([labelName]) => labelName)
: [];
payload.labels_include_any =
selectedCustomTarget === "labelsIncludeAny" ? customLabelNames : [];
payload.labels_include_all =
selectedCustomTarget === "labelsIncludeAll" ? customLabelNames : [];
payload.labels_exclude_any =
selectedCustomTarget === "labelsExcludeAny" ? customLabelNames : [];
payload.critical = lastEditedQueryCritical;
}
onUpdate(payload);
}
};
const renderLabelComponent = (): JSX.Element | null => {
return (
<div className={`${baseClass}__sql-editor-label-actions`}>
{showOpenSchemaActionText && (
<Button variant="inverse" onClick={onOpenSchemaSidebar}>
<>
Schema
<Icon name="info" />
</>
</Button>
)}
{!policyIdForEdit && (
// only when creating a new policy
<CustomLink
text="Examples"
url={`${LEARN_MORE_ABOUT_BASE_LINK}/policy-templates`}
newTab
/>
)}
</div>
);
};
const renderName = () => {
if (isEditMode) {
return (
<InputField
name="policy-name"
label="Name"
placeholder="Add name here"
value={lastEditedQueryName}
error={errors && errors.name}
onChange={(value: string) => setLastEditedQueryName(value)}
disabled={gitOpsModeEnabled}
/>
);
}
return (
<h1
className={`${baseClass}__policy-name ${baseClass}__policy-name--new no-hover`}
>
New policy
</h1>
);
};
const renderDescription = () => {
if (isEditMode) {
return (
<InputField
name="policy-description"
label="Description"
placeholder="Add description here."
value={lastEditedQueryDescription}
type="textarea"
helpText="How does this policy's failure put the organization at risk?"
onChange={(value: string) => setLastEditedQueryDescription(value)}
disabled={gitOpsModeEnabled}
/>
);
}
return null;
};
const renderResolution = () => {
if (isEditMode) {
return (
<InputField
name="policy-resolution"
label="Resolution"
placeholder="Add resolution here."
value={lastEditedQueryResolution}
type="textarea"
helpText="If this policy fails, what should the end user expect?"
onChange={(value: string) => setLastEditedQueryResolution(value)}
disabled={gitOpsModeEnabled}
/>
);
}
return null;
};
const renderPlatformCompatibility = () => {
if (
isEditMode &&
(isStoredPolicyLoading || policyIdForEdit !== lastEditedQueryId)
) {
return null;
}
return platformCompatibility.render();
};
const renderCriticalPolicy = () => {
return (
<div className={`${baseClass}__critical-checkbox-wrapper`}>
<Checkbox
name="critical-policy"
className="critical-policy"
onChange={(value: boolean) => setLastEditedQueryCritical(value)}
value={lastEditedQueryCritical}
isLeftLabel
disabled={gitOpsModeEnabled}
>
<TooltipWrapper
tipContent={
<p>
If automations are turned on, this information is included. If
Okta conditional access is configured, end users can never
bypass critical policies.
</p>
}
>
Critical
</TooltipWrapper>
</Checkbox>
</div>
);
};
const renderPolicyFleetName = () => {
if (isFreeTier) return null;
// In edit mode, the displayed Fleet must reflect the policy's actual
// owner, not the URL/navigation context: a user can land here by clicking
// an inherited (global) policy from a team's policy list, in which case
// currentTeam reflects the team URL, not the policy's true Fleet.
let fleetName: string | undefined;
if (isEditMode) {
if (storedPolicy?.team_id === null) {
fleetName = APP_CONTEXT_ALL_TEAMS_SUMMARY.name;
} else if (storedPolicy?.team_id === 0) {
fleetName = APP_CONTEXT_NO_TEAM_SUMMARY.name;
} else {
fleetName = currentTeam?.name;
}
} else {
fleetName = currentTeam?.name;
}
if (!fleetName) return null;
return isEditMode ? (
<p>
Editing policy for <strong>{fleetName}</strong>.
</p>
) : (
<p>
Creating a new policy for <strong>{fleetName}</strong>.
</p>
);
};
const renderPolicyForm = () => {
// Save disabled for no platforms selected, policy name blank on existing policy,
// invalid target selection, or empty query. Syntax errors do not disable Save.
const disableSaveFormErrors =
isAddingAutomation ||
(isEditMode && !isPatchPolicy && !isAnyPlatformSelected) ||
(lastEditedQueryName === "" && !!lastEditedQueryId) ||
(selectedTargetType === "Custom" &&
!Object.entries(selectedLabels).some(([, value]) => {
return value;
})) ||
errors.query === EMPTY_QUERY_ERR;
return (
<>
<form className={`${baseClass}__wrapper`} autoComplete="off">
{isEditMode ? (
<div className={`${baseClass}__page-header`}>
<h1 className={`${baseClass}__page-title`}>Edit policy</h1>
{renderPolicyFleetName()}
</div>
) : (
<div className={`${baseClass}__title-bar`}>
<div className={`${baseClass}__policy-name-fleet-name`}>
{renderName()}
{renderPolicyFleetName()}
</div>
</div>
)}
{isEditMode && renderName()}
{renderDescription()}
{renderResolution()}
{isEditMode && !isPatchPolicy && platformSelector.render()}
{isEditMode && isPremiumTier && !isPatchPolicy && (
<TargetLabelSelector
selectedTargetType={selectedTargetType}
selectedCustomTarget={selectedCustomTarget}
customTargetOptions={customTargetOptions}
onSelectCustomTarget={(val) =>
setSelectedCustomTarget(val as LabelScope)
}
selectedLabels={selectedLabels}
className={`${baseClass}__target`}
onSelectTargetType={setSelectedTargetType}
onSelectLabel={onSelectLabel}
labels={labels || []}
disableOptions={gitOpsModeEnabled}
suppressTitle
/>
)}
{isEditMode && storedPolicy && (
<PolicyAutomations
storedPolicy={storedPolicy}
currentAutomatedPolicies={currentAutomatedPolicies}
canEditPolicy={isEditMode}
onAddAutomation={onAddPatchAutomation}
isAddingAutomation={isAddingAutomation}
/>
)}
{isEditMode &&
isPremiumTier &&
!isPatchPolicy &&
renderCriticalPolicy()}
<SQLEditor
value={lastEditedQueryBody}
error={errors.query}
label="Query"
labelActionComponent={
isPatchPolicy ? (
<TooltipWrapper
tipContent="Query is read-only for patch policies."
position="top"
underline={false}
showArrow
tipOffset={12}
>
<Icon name="info" size="small" />
</TooltipWrapper>
) : (
renderLabelComponent()
)
}
name="query editor"
onLoad={onLoad}
wrapperClassName={`${baseClass}__text-editor-wrapper form-field`}
onChange={onChangePolicySql}
handleSubmit={promptSavePolicy}
wrapEnabled
focus={!isEditMode}
readOnly={isPatchPolicy}
/>
{renderPlatformCompatibility()}
{renderLiveQueryWarning()}
<div className="button-wrap">
{isEditMode && onCancel && (
<Button variant="inverse" onClick={onCancel}>
Cancel
</Button>
)}
<GitOpsModeTooltipWrapper
renderChildren={(disableChildren) => (
<TooltipWrapper
tipContent={
<>
Select the platforms this
<br />
policy will be checked on
<br />
to save or run the policy.
</>
}
tooltipClass={`${baseClass}__button-wrap--tooltip`}
position="top"
disableTooltip={!isEditMode || isAnyPlatformSelected}
underline={false}
>
<span className={`${baseClass}__button-wrap--tooltip`}>
<Button
onClick={promptSavePolicy()}
disabled={disableSaveFormErrors || disableChildren}
className="save-loading"
isLoading={isUpdatingPolicy}
>
Save
</Button>
</span>
</TooltipWrapper>
)}
/>
<TooltipWrapper
tipContent={
disabledLiveQuery ? (
<>
Live reports are disabled <br />
in organization settings.
</>
) : (
<>
Select the platforms this <br />
policy will be checked on <br />
to save or run the policy.
</>
)
}
disableTooltip={
(!isEditMode || isAnyPlatformSelected) && !disabledLiveQuery
}
underline={false}
showArrow
position="top"
>
<span className={`${baseClass}__button-wrap--tooltip`}>
<Button
onClick={goToSelectTargets}
disabled={
isAddingAutomation ||
(isEditMode && !isAnyPlatformSelected) ||
disabledLiveQuery
}
variant="inverse"
>
Run <Icon name="run" />
</Button>
</span>
</TooltipWrapper>
</div>
</form>
{isSaveNewPolicyModalOpen && (
<SaveNewPolicyModal
baseClass={baseClass}
queryValue={lastEditedQueryBody}
onCreatePolicy={onCreatePolicy}
setIsSaveNewPolicyModalOpen={setIsSaveNewPolicyModalOpen}
backendValidators={backendValidators}
platformSelector={platformSelector}
isUpdatingPolicy={isUpdatingPolicy}
aiFeaturesDisabled={aiFeaturesDisabled}
isFetchingAutofillDescription={isFetchingAutofillDescription}
isFetchingAutofillResolution={isFetchingAutofillResolution}
onClickAutofillDescription={onClickAutofillDescription}
onClickAutofillResolution={onClickAutofillResolution}
labels={labels}
/>
)}
</>
);
};
if (isStoredPolicyLoading) {
return <Spinner />;
}
return renderPolicyForm();
};
export default PolicyForm;