forked from cloud-custodian/cel-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc7n_to_cel.py
More file actions
1736 lines (1478 loc) · 65.5 KB
/
c7n_to_cel.py
File metadata and controls
1736 lines (1478 loc) · 65.5 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
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
# SPDX-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
"""
C7N to CEL Rewriter -- Examine a policy's filters clause and emit CEL equivalent code.
The intent is to cover **most** policies, not all. Some rarely-used C7N features
may require manual intervention and cleanup.
Specifically, all of the rewrite functions that provide ``logger.error()`` messages
are policies that are known to produce possibly incorrect CEL expressions.
This is the short list of places where manual rewriting is necessary.
- :py:meth:`xlate.c7n_to_cel.C7N_Rewriter.c7type_marked_for_op_rewrite`
- :py:meth:`xlate.c7n_to_cel.C7N_Rewriter.type_image_rewrite`
In other cases the translator may raise an exception and stop because
the C7N filter uses an utterly obscure feature. In that case, manual conversion
is obviously the only recourse.
This makes it slightly more convenient to migrate C7N policies by
converting legacy policies from the YAML-based DSL into CEL.
There are three explicit limitations here.
- Some C7N features are opaque, and it's difficult to be sure
the CEL translation is correct.
- Some actual policy documents have incorrect logic and are tautologically false.
They never worked, and silence is often conflated with success.
- Some policy filters are so rarely used that there's little point in automated
translation of the policy filter.
"""
import collections
import logging
import re
from typing import Any, Callable, DefaultDict, Dict, List, Optional, Tuple, Union, cast
import yaml
logger = logging.getLogger(__name__)
JSON = Union[Dict[str, Any], List[Any], float, int, str, bool, None]
class C7N_Rewriter:
"""
Collection of functions to rewite most C7N policy filter clauses into CEL.
Generally, a C7N ``filters:`` expression consists of a large variety of individual
clauses, connected by boolean logic.
The :meth:`C7N_Rewriter.c7n_rewrite` method does this transformation.
"""
# Global names that *must* be part of the CEL activation namespace.
resource = "resource"
now = "now"
c7n = "C7N"
@staticmethod
def q(text: Optional[str], quote: str = '"') -> str:
"""Force specific quotes on CEL literals."""
if text is None:
return f"{quote}{quote}"
if quote in text:
text = text.replace(quote, f"\\{quote}")
return f"{quote}{text}{quote}"
@staticmethod
def key_to_cel(operation_key: str, context: Optional[str] = None) -> str:
"""
Convert simple key: clause to CEL or key: tag:Name clause to CEL.
The ``resource.key({name})`` function
handles key resolution by looking in the list of ``{Key: name, Value: value}`` mappings
for the first match. A default is available.
Another solution is a gemeric ``first(x, x["Key] = "{name}")`` macro,
which can return ``null`` if no first item is found.
What's in place now for ``key: tag:name`` is rather complicated. It asserts a complex
condition about one of the values in a list of mappings.
::
resource["Tags"].filter(x, x["Key"] == "{name}")[0]["Value"]
This is risky, since a list with no dictionaty that has a Key value of ``name``
will break this expression.
"""
function_map = {
"length": "size",
}
function_arg_pat = re.compile(r"(\w+)\((\w+)\)")
key_context = context or C7N_Rewriter.resource
key: str
function_arg_match = function_arg_pat.match(operation_key)
if function_arg_match:
function, arg = function_arg_match.groups()
cel_name = function_map[function]
key = f"{cel_name}({key_context}[{C7N_Rewriter.q(arg)}])"
elif "." in operation_key:
names = operation_key.split(".")
key = f"{key_context}[{C7N_Rewriter.q(names[0])}]" + "".join(
f"[{C7N_Rewriter.q(n)}]" for n in names[1:]
)
elif operation_key.startswith("tag:"):
prefix, _, name = operation_key.partition(":")
key = f'{key_context}["Tags"].filter(x, x["Key"] == {C7N_Rewriter.q(name)})[0]["Value"]'
else:
key = f"{key_context}[{C7N_Rewriter.q(operation_key)}]"
return key
# Transformations from C7N ``op:`` to CEL.
atomic_op_map = {
"eq": "{0} == {1}",
"equal": "{0} == {1}",
"ne": "{0} != {1}",
"not-equal": "{0} != {1}",
"gt": "{0} > {1}",
"greater-than": "{0} > {1}",
"ge": "{0} >= {1}",
"gte": "{0} >= {1}",
"le": "{0} < {1}",
"lte": "{0} <= {1}",
"lt": "{0} < {1}",
"less-than": "{0} < {1}",
"glob": "{0}.glob({1})",
"regex": "{0}.matches({1})",
"in": "{1}.contains({0})",
"ni": "! {1}.contains({0})",
"not-in": "! {1}.contains({0})",
"contains": "{0}.contains({1})",
"difference": "{0}.difference({1})",
"intersect": "{0}.intersect({1})",
# Special cases for present, anbsent, not-null, and empty
"__present__": "present({0})",
"__absent__": "absent({0})",
}
@staticmethod
def age_to_duration(age: Union[float, str]) -> str:
"""Ages are days. We convert to seconds and then create a duration string."""
return C7N_Rewriter.seconds_to_duration(float(age) * 24 * 60 * 60)
@staticmethod
def seconds_to_duration(period: Union[float, str]) -> str:
"""Integer periods are seconds."""
seconds = int(float(period))
units = [(24 * 60 * 60, "d"), (60 * 60, "h"), (60, "m"), (1, "s")]
duration = []
while seconds != 0 and units:
u_sec, u_name = units.pop(0)
value, seconds = divmod(seconds, u_sec)
if value != 0:
duration.append(f"{value}{u_name}")
return f"{C7N_Rewriter.q(''.join(duration))}"
@staticmethod
def value_to_cel(
key: str, op: str, value: Optional[str], value_type: Optional[str] = None
) -> str:
"""
Convert simple ``value: v, op: op``, and ``value_type: vt`` clauses to CEL.
"""
type_value_map: Dict[str, Callable[[str, str], Tuple[str, str]]] = {
"age": lambda sentinel, value: (
"timestamp({})".format(value),
"{} - duration({})".format(
C7N_Rewriter.now, C7N_Rewriter.age_to_duration(sentinel)
),
),
"integer": lambda sentinel, value: (sentinel, "int({})".format(value)),
"expiration": lambda sentinel, value: (
"{} + duration({})".format(
C7N_Rewriter.now, C7N_Rewriter.age_to_duration(sentinel)
),
"timestamp({})".format(value),
),
"normalize": lambda sentinel, value: (
sentinel,
"normalize({})".format(value),
),
"size": lambda sentinel, value: (sentinel, "size({})".format(value)),
"cidr": lambda sentinel, value: (
"parse_cidr({})".format(sentinel),
"parse_cidr({})".format(value),
),
"cidr_size": lambda sentinel, value: (
sentinel,
"size_parse_cidr({})".format(value),
),
"swap": lambda sentinel, value: (value, sentinel),
"unique_size": lambda sentinel, value: (
sentinel,
"unique_size({})".format(value),
),
"date": lambda sentinel, value: (
"timestamp({})".format(sentinel),
"timestamp({})".format(value),
),
"version": lambda sentinel, value: (
"version({})".format(sentinel),
"version({})".format(value),
),
# expr -- seems to be used only in value_from clauses
# resource_count -- no examples; it's not clear how this is different from size()
}
if (
isinstance(value, str)
and value in ("true", "false")
or isinstance(value, bool) # noqa: W503
):
# Boolean cases
# Rewrite == true, != true, == false, and != false
if op in ("eq", "equal"):
if value in ("true", True):
return f"{key}"
else:
return f"! {key}"
elif op in ("ne", "not-equal"):
if value in ("true", True):
return f"! {key}"
else:
return f"{key}"
else:
raise ValueError(f"Unknown op: {op}, value: {value} combination")
else:
# Ordinary comparisons, including the value_type transformation
cel_value: str
if isinstance(value, str):
cel_value = C7N_Rewriter.q(value)
else:
cel_value = f"{value}"
if value_type:
type_transform = type_value_map[value_type]
cel_value, key = type_transform(cel_value, key)
return C7N_Rewriter.atomic_op_map[op].format(key, cel_value)
@staticmethod
def value_from_to_cel(
key: str,
op: Optional[str],
value_from: Dict[str, Any],
value_type: Optional[str] = None,
) -> str:
"""
Convert ``value_from: ...``, ``op: op`` clauses to CEL.
When the op is either "in" or "ni", this becomes
::
value_from(url[, format])[.jmes_path_map(expr)].contains(key)
or
::
! value_from(url[, format])[.jmes_path_map(expr)].contains(key)
The complete domain of op values is::
Counter({'op: not-in': 943,
'op: ni': 1482,
'op: in': 656,
'op: intersect': 8,
'value_from: op: ni': 32,
'value_from: op: in': 8,
'value_from: op: not-in': 1,
'no op present': 14})
The ``intersect`` option replaces "contains" with "intersect".
The 41 examples with the ``op:`` buried in the
``value_from:`` clause follow a similar pattern.
The remaining 14 have no explicit operation. The default is ``op: in``.
Also.
Note that the JMES path can have a substitution value buried in it.
It works like this
::
config_args = {
'account_id': manager.config.account_id,
'region': manager.config.region
}
self.data = format_string_values(data, **config_args)
This is a separate function to reach into the C7N objects and
gather pieces of data (if needed) to adjust the JMESPath.
"""
filter_op_map = {
"in": "{1}.contains({0})",
"ni": "! {1}.contains({0})",
"not-in": "! {1}.contains({0})",
"intersect": "{1}.intersect({0})",
}
source: str
url = value_from["url"]
if "format" in value_from:
format = value_from["format"].strip()
source = f"value_from({C7N_Rewriter.q(url)}, {C7N_Rewriter.q(format)})"
else:
# Parse URL to get format from path.
source = f"value_from({C7N_Rewriter.q(url)})"
if "expr" in value_from:
# if expr is a string, it's jmespath. Escape embedded apostrophes.
# TODO: The C7N_Rewriter.q() function *should* handle this.
expr_text = value_from["expr"].replace("'", "\\'")
if "{" in expr_text:
expr_text = f"subst('{expr_text}')"
else:
expr_text = f"'{expr_text}'"
cel_value = f"{source}.jmes_path({expr_text})"
# TODO: if expr is an integer, we use ``.map(x, x[integer])``
else:
cel_value = f"{source}"
if op is None:
# Sometimes the op: is inside the value_from clause.
# Sometimes it's omitted, and it seems like "in" could be a default.
op = value_from.get("op", "in")
if value_type is None:
pass
elif value_type == "normalize":
cel_value = f"{cel_value}.map(v, normalize(v))"
# The schema defines numerous value_type options available.
else:
raise ValueError(f"Unknown value_type: {value_type}") # pragma: no cover
return filter_op_map[cast(str, op)].format(key, cel_value)
@staticmethod
def type_value_rewrite(resource: str, operation: Dict[str, Any]) -> str:
"""
Transform one atomic ``type: value`` clause.
Three common subtypes:
- A ``value: v``, ``op: op`` pair. This is the :meth:`value_to_cel` method.
- A ``value: v`` with no ``op:``. This devolves to the present/not-null/absent/empty test.
- Special ``value_from:``. This is the :meth:`value_from_to_cel` method.
Some other things that arrive here:
- A ``tag:name: absent``, shorthand for "key: "tag:name", "value": "absent"
"""
if "key" not in operation:
# The {"tag:...": "absent"} case?
if len(operation.items()) == 1:
key = list(operation)[0]
value = operation[key]
operation = {"key": key, "value": value}
else:
raise ValueError(f"Missing key {operation}") # pragma: no cover
key = C7N_Rewriter.key_to_cel(operation["key"])
if "value" in operation and "op" in operation:
# Literal value supplied in the filter
return C7N_Rewriter.value_to_cel(
key, operation["op"], operation["value"], operation.get("value_type")
)
elif "value" in operation and "op" not in operation:
# C7N has the following implementation...
# if r is None and v == 'absent':
# return True
# elif r is not None and v == 'present':
# return True
# elif v == 'not-null' and r:
# return True
# elif v == 'empty' and not r:
# return True
if operation["value"] in ("present", "not-null"):
return C7N_Rewriter.value_to_cel(key, "__present__", None)
elif operation["value"] in ("absent", "empty"):
return C7N_Rewriter.value_to_cel(key, "__absent__", None)
else:
raise ValueError(f"Missing value without op in {operation}")
elif "value_from" in operation:
# Value fetched from S3 or HTTPS
return C7N_Rewriter.value_from_to_cel(
key, operation.get("op"), operation["value_from"]
)
else:
raise ValueError(f"Missing value/value_type in {operation}")
@staticmethod
def type_marked_for_op_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
filters:
- op: delete
skew: 4
type: marked-for-op
to::
resource["Tags"].marked_key("marked-for-op").action == "delete"
&& now >= (
timestamp(resource["Tags"].marked_key("marked-for-op").action_date)
- duration('4d")
)
There's an optional ``tag:`` attribute to name the Tag's Key (default "custodian_status").
The op has to match the target op (default "stop").
The Tag's Value *should* have the form ``message:op@action_date``.
Otherwise the result is False.
Making this a variant on ``resource["Tags"].filter(x, x["Key"] == {tag})[0]["Value"]``
is awkward because we're checking at least two separate properties of the value.
Relies on :py:func:`celpy.c7nlib.marked_key` to parse the tag value into
a small mapping with ``"message"``, ``"action"``, and ``"action_date"`` keys.
"""
key = f'{C7N_Rewriter.resource}["Tags"]'
tag = c7n_filter.get("tag", "custodian_status")
op = c7n_filter.get("op", "stop")
skew = int(c7n_filter.get("skew", 0))
skew_hours = int(c7n_filter.get("skew_hours", 0))
if "tz" in c7n_filter: # pragma: no cover
# Not widely used.
tz = c7n_filter.get("tz", "utc")
logger.error(
"Cannot convert mark-for-op: with tz: %s in %s", tz, c7n_filter
)
clauses = [
f"{key}.marked_key({C7N_Rewriter.q(tag)}).action == {C7N_Rewriter.q(op)}",
f'{C7N_Rewriter.now} >= {key}.marked_key("{tag}").action_date '
f'- duration("{skew}d{skew_hours}h")',
]
return " && ".join(filter(None, clauses))
@staticmethod
def type_image_age_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
- days: 60
op: gte
type: image-age
to::
now - resource.image().CreationDate >= duration("60d")
Relies on :py:func:`celpy.c7nlib.image` function to implement
``get_instance_image(resource)`` from C7N Filters.
"""
key = f"{C7N_Rewriter.now} - {C7N_Rewriter.resource}.image().CreationDate"
days = C7N_Rewriter.age_to_duration(c7n_filter["days"])
cel_value = f"duration({days})"
op = cast(str, c7n_filter["op"])
return C7N_Rewriter.atomic_op_map[op].format(key, cel_value)
@staticmethod
def type_image_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
- key: Name
op: regex
type: image
value: (?!WIN.*)
to::
resource.image().Name.matches('(?!WIN.*)')
Relies on :py:func:`celpy.c7nlib.image`` function to implement
``get_instance_image(resource)`` from C7N Filters.
There are relatively few examples of this filter.
Both rely on slightly different semantics for the underlying
CEL ``matches()`` function.
Normally, CEL uses ``re.search()``, which doesn't
trivially work with with the ``(?!X.*)`` patterns.
Rather than compromise the CEL run-time with complexities
for this rare case, it seems better to provide a warning that the resulting
CEL code *may* require manual adjustment.
"""
key = f"resource.image().{c7n_filter['key']}"
op = cast(str, c7n_filter["op"])
cel_value = f"{C7N_Rewriter.q(c7n_filter['value'])}"
if "(?!" in cel_value:
logger.error("Image patterns like %r require a manual rewrite.", cel_value)
return C7N_Rewriter.atomic_op_map[op].format(key, cel_value)
@staticmethod
def type_event_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
- key: detail.responseElements.functionName
op: regex
type: event
value: ^(custodian-.*)
to::
event.detail.responseElements.functionName.matches("^(custodian-.*)")
This relies on ``event`` being a global, like the ``resource``.
"""
key = f"event.{c7n_filter['key']}"
op = cast(str, c7n_filter["op"])
cel_value = c7n_filter["value"]
return C7N_Rewriter.atomic_op_map[op].format(
key, f"{C7N_Rewriter.q(cel_value)}"
)
@staticmethod
def type_metrics_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
- type: metrics
name: CPUUtilization
days: 4
period: 86400
value: 30
op: less-than
or::
- type: metrics
name: RequestCount
statistics: Sum
days: 7
value: 7
missing-value: 0
op: less-than
to::
get_raw_metrics(
{"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
"Dimensions": {"Name": "InstanceId", "Value": resource.InstanceId},
"Statistics": ["Average"],
"StartTime": now - duration("4d"),
"EndTime": now,
"Period": duration("86400s")}
).exists(m, m["AWS/EC2"].CPUUtilization.Average < 30)
get_raw_metrics(
{"Namespace": "AWS/ELB",
"MetricName": "RequestCount",
"Dimensions": {"Name": "InstanceId", "Value": resource.InstanceId},
"Statistics": ["Sum"],
"StartTime": now - duration("7d"),
"EndTime": now,
"Period": duration("7d")}
).map(m: m = null ? 0 : m["AWS/ELB"].RequestCount.Sum < 7)
Note that days computes a default for period as well as start time.
Default days is 14, which becomes a default period of 14 days -> seconds, 1209600.
Default statistics is Average.
Relies on :py:func:`celpy.c7nlib.get_metrics` to fetch the metrics.
C7N uses the parameters to invoke AWS
https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/
API_GetMetricStatistics.html
There are some irksome redundancies for the common case in C7N:
- ``"Namespace": "AWS/EC2"`` is derivable from the resource type, and shouldn't need
to be stated explicitly. C7N hides this by transforming resource type to namespace.
- ``""Dimensions": {"Name": "InstanceId", "Value": resource.InstanceId}`` is
derivable from the resource information and shouldn't necessarily be exposed like this.
- ``"Statistics": ["Average"]`` should *always* be a singleton
to simplify the ``exists()`` macro.
- ``m["AWS/EC2"].CPUUtilization.Average`` can then be eliminated because we get
a simple list of values for the namespace, metric name, and statistic combination.
optimized::
resource.get_metrics(
{"MetricName": "CPUUtilization",
"Statistic": "Average",
"StartTime": now - duration("4d"),
"EndTime": now,
"Period": duration("86400s")})
.exists(m, m < 30)
resource.get_metrics(
{"MetricName": "RequestCount",
"Statistic": "Sum",
"StartTime": now - duration("7d"),
"EndTime": now,
"Period": duration("7d")})
.map(m, m == null ? 0 : m)
.exists(m, m < 7)
.. todo:: The extra fiddling involved with attr-multiplier and percent-attr
in a map() clause.
.map(m, m / (resource["{percent-attr}"] * {attr-multiplier}) * 100)
.exists(m, m op value)
"""
name = c7n_filter["name"]
statistics = c7n_filter.get("statistics", "Average")
C7N_Rewriter.age_to_duration(c7n_filter["days"])
start = c7n_filter.get("days", 14) # Days
period = c7n_filter.get("period", start * 86400)
start_d = C7N_Rewriter.age_to_duration(start)
period_d = C7N_Rewriter.seconds_to_duration(period)
op = c7n_filter["op"]
value = c7n_filter["value"]
macro = C7N_Rewriter.atomic_op_map[op].format("m", f"{value}")
if "missing-value" in c7n_filter:
missing = c7n_filter["missing-value"]
return (
f"resource.get_metrics("
f'{{"MetricName": {C7N_Rewriter.q(name)}, '
f'"Statistic": {C7N_Rewriter.q(statistics)}, '
f'"StartTime": now - duration({start_d}), "EndTime": now, '
f'"Period": duration({period_d})}})'
f".map(m, m == null ? {missing} : m)"
f".exists(m, {macro})"
)
else:
return (
f"resource.get_metrics("
f'{{"MetricName": {C7N_Rewriter.q(name)}, '
f'"Statistic": {C7N_Rewriter.q(statistics)}, '
f'"StartTime": now - duration({start_d}), "EndTime": now, '
f'"Period": duration({period_d})}})'
f".exists(m, {macro})"
)
@staticmethod
def type_age_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
policies:
- name: redshift-old-snapshots
resource: redshift-snapshot
filters:
- type: age
days: 21
op: gt
To::
now - timestamp(resource.SnapshotCreateTime) > duration("21d")
What's important is that each resource type has a distinct attribute name
used for "age".
"""
attribute_map = {
"launch-config": "resource.CreatedTime",
"ebs-snapshot": "resource.StartTime",
"cache-snapshot": "resource.NodeSnaphots.min(x, x.SnapshotCreateTime)",
"rds-snapshot": "SnapshotCreateTime",
"rds-cluster-snapshot": "SnapshotCreateTime",
"redshift-snapshot": "SnapshotCreateTime",
}
attr = attribute_map[resource]
op = c7n_filter["op"]
days = c7n_filter["days"]
return C7N_Rewriter.atomic_op_map[op].format(
f"now - timestamp({attr})", f'duration("{days}d")'
)
@staticmethod
def type_security_group_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
policies:
- name: alb-report
resource: app-elb
filters:
- key: tag:ASSET
op: eq
type: security-group
value: SPECIALASSETNAME
To::
resource.SecurityGroups.map(sg. sg.GroupId.security_group())
.exists(sg, sg["Tags"].filter(x, x["Key"] == "ASSET")[0]["Value"] == 'SPECIALASSETNAME')
The relationship between resource and security group variables by resource type.
Relies on :py:func:`celpy.c7nlib.get_related` function to reach into the filter
to a method of the C7N ``RelatedResourceFilter`` mixin.
Relies on :py:func:`celpy.c7nlib.security_group` function to leverage
the the filter's internal ``get_related()`` method.
For additional information, see the :py:class:`c7n.filters.vpc.NetworkLocation`.
This class reaches into SecurityGroup and Subnet to fetch related objects.
Most cases are relatively simple. There are three very complex cases:
- ASG -- the security group is indirectly associated with config items and launch items.
The filter has ``get_related_ids([resource])`` to be used before ``get_related()``.
- EFS -- the security group is indirectly associated with an MountTargetId.
The filter has ``get_related_ids([resource])`` to be used before ``get_related()``.
- VPC -- The security group seems to have a VpcId that's used.
The filter has ``get_related_ids([resource])`` to be used before ``get_related()``.
"""
attribute_map = {
"app-elb": "resource.SecurityGroups.map(sg, sg.security_group())",
"asg": "resource.get_related_ids().map(sg. sg.security_group())",
"lambda": "VpcConfig.SecurityGroupIds.map(sg, sg.security_group())",
"batch-compute": (
"resource.computeResources.securityGroupIds.map(sg, sg.security_group())"
),
"codecommit": "resource.vpcConfig.securityGroupIds.map(sg, sg.security_group())",
"directory": "resource.VpcSettings.SecurityGroupId.security_group()",
"dms-instance": (
"resource.VpcSecurityGroups.map(sg, sg.VpcSecurityGroupId.security_group())"
),
"dynamodb-table": (
"resource.SecurityGroups.map(sg, sg..SecurityGroupIdentifier.security_group())"
),
"ec2": "resource.SecurityGroups.map(sg, sg.GroupId.security_group())",
"efs": "resource.get_related_ids().map(sg, sg.security_group())",
"eks": "resource.resourcesVpcConfig.securityGroupIds.map(sg, sg.security_group())",
"cache-cluster": "resource.SecurityGroups.map(sg, sg.SecurityGroupId.security_group())",
"elasticsearch": "resource.VPCOptions.SecurityGroupIds.map(sg, sg.security_group())",
"elb": "resource.SecurityGroups.map(sg, sg.security_group())",
"glue-connection": "resource.PhysicalConnectionRequirements.SecurityGroupIdList"
".map(sg, sg.security_group())",
"kafka": "resource.BrokerNodeGroupInfo.SecurityGroups[.map(sg, sg.security_group())",
"message-broker": "resource.SecurityGroups.map(sg, sg.security_group())",
"rds": "resource.VpcSecurityGroups.map(sg, sg.VpcSecurityGroupId.security_group())",
"rds-cluster": (
"resource.VpcSecurityGroups.map(sg, sg.VpcSecurityGroupId.security_group())"
),
"redshift": (
"resource.VpcSecurityGroups.map(sg, sg.VpcSecurityGroupId.security_group())"
),
"sagemaker-notebook": "resource.SecurityGroups.map(sg, sg.security_group())",
"vpc": "resource.get_related_ids().map(sg. sg.security_group())",
"eni": "resource.Groups.map(sg, sg.GroupId.security_group())",
"vpc-endpoint": "resource.Groups.map(sg, sg.GroupId.security_group())",
}
attr = attribute_map[resource]
op = c7n_filter["op"]
value = repr(c7n_filter["value"])
key = C7N_Rewriter.key_to_cel(c7n_filter["key"], context="sg")
exists_expr = C7N_Rewriter.atomic_op_map[op].format(key, value)
return f"{attr}.exists(sg, {exists_expr})"
@staticmethod
def type_subnet_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
policies:
- name: asg-restriction-az1e-notify-weekly
resource: asg
filters:
- key: SubnetId
op: in
type: subnet
value_from:
format: txt
url: s3://path-to-resource/subnets.txt
value_type: normalize
To::
value_from("s3://path-to-resource/subnets.txt").map(x, normalize(x)).contains(
resource.SubnetId.subnet().SubnetID)
For additional information, see the :py:class:`c7n.filters.vpc.NetworkLocation`.
This class reaches into SecurityGroup and Subnet to fetch related objects.
Because there's a key, it's not clear we need an attribute map to locate
the attribute of the resource.
Relies on :py:func:`celpy.c7nlib.subnet` to get subnet details via the C7N Filter.
"""
key = c7n_filter["key"]
full_key = f"{C7N_Rewriter.resource}.{key}.subnet().SubnetID"
return C7N_Rewriter.value_from_to_cel(
full_key,
c7n_filter["op"],
c7n_filter["value_from"],
value_type=c7n_filter.get("value_type"),
)
@staticmethod
def type_flow_log_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
policies:
- name: flow-mis-configured
resource: vpc
filters:
- not:
- type: flow-logs
enabled: true
set-op: or
op: equal
# equality operator applies to following keys
traffic-type: all
status: active
log-group: vpc-logs
To::
size(resource.flow_logs()) != 0
&&
! (
|| resource.flow_logs().exists(x, x.TrafficType == "all")
|| resource.flow_logs().exists(x, x.DeliverLogsStatus == "active")
|| resource.flow_logs().exists(x, x.LogGroupName == "vpc-logs")
)
The default set-op is "or" for the clauses other than enabled.
The default op is "eq", the only other choice is "ne".
The "enabled: true" option is implied by the existence of any data (size(...) != 0)
The "enabled: false" option means there is no data (size(...) == 0)
The enabled is a special case that determines if there's a flow log at all.
In the more common cases, we'd use something like this::
resource.flow_logs().enabled() ?
resource.flow_logs().LogDestinationType != "s3" : false
To express the idea of:
if enabled, check something else, otherwise, it's disabled, ignore it.
Relies on :py:func:`celpy.c7nlib.flow_logs` to get flow_log details via the C7N Filter.
"""
set_op = c7n_filter.get("set-up", "or")
enabled = []
if "enabled" in c7n_filter:
if c7n_filter["enabled"]:
enabled = ["size(resource.flow_logs()) != 0"]
else:
enabled = ["size(resource.flow_logs()) == 0"]
clauses = []
if c7n_filter.get("log-group"):
log_group = c7n_filter.get("log-group")
clauses.append(
f"resource.flow_logs().exists(x, x.LogGroupName == {C7N_Rewriter.q(log_group)})"
)
if c7n_filter.get("log-format"):
log_format = c7n_filter.get("log-format")
clauses.append(
f"resource.flow_logs().exists(x, x.LogFormat == {C7N_Rewriter.q(log_format)})"
)
if c7n_filter.get("traffic-type"):
traffic_type = cast(str, c7n_filter.get("traffic-type"))
clauses.append(
f"resource.flow_logs().exists(x, x.TrafficType == {C7N_Rewriter.q(traffic_type.upper())})"
)
if c7n_filter.get("destination-type"):
destination_type = c7n_filter.get("destination-type")
clauses.append(
f"resource.flow_logs().exists(x, x.LogDestinationType == {C7N_Rewriter.q(destination_type)})"
)
if c7n_filter.get("destination"):
destination = c7n_filter.get("destination")
clauses.append(
f"resource.flow_logs().exists(x, x.LogDestination == {C7N_Rewriter.q(destination)})"
)
if c7n_filter.get("status"):
status = c7n_filter.get("status")
clauses.append(
f"resource.flow_logs().exists(x, x.FlowLogStatus == {C7N_Rewriter.q(status)})"
)
if c7n_filter.get("deliver-status"):
deliver_status = c7n_filter.get("deliver-status")
clauses.append(
f"resource.flow_logs().exists(x, x.DeliverLogsStatus == {C7N_Rewriter.q(deliver_status)})"
)
if len(clauses) > 0:
operator = " && " if set_op == "and" else " || "
details = [f"({operator.join(clauses)})"]
else:
details = []
return " && ".join(enabled + details)
@staticmethod
def type_tag_count_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
policies:
- name: alb-report
resource: app-elb
filters:
- type: tag-count
count: 8
To::
size(resource["Tags"].filter(x, ! matches(x.Key, "^aws:.*"))) >= 8
"""
op = c7n_filter.get("op", "gte")
return C7N_Rewriter.atomic_op_map[op].format(
'size(resource["Tags"].filter(x, ! matches(x.Key, "^aws:.*")))',
c7n_filter.get("count", 10),
)
@staticmethod
def type_vpc_rewrite(resource: str, c7n_filter: Dict[str, Any]) -> str:
"""
Transform::
policies:
- name: ec2-offhours-tagging
resource: ec2
filters:
- key: VpcId
op: not-in
type: vpc
value_from:
expr: not_null(offhours_exceptions."{account_id}"."account", '[]')
format: json
url: s3://c7n-resources/some_list.json
To::
value_from(
"s3://c7n-resources/some_list.json"
).jmes_path_map(
"not_null(offhours_exceptions." + resource.account_id + ".account, '[]')"
).contains(resource.VpcId.vpc().VpcId)
The ``resource.VpcId.vpc().VpcId`` harbors a redundanncy.
This reflects the way C7N works to fetch the related resource, then extracts
an attribute of that resource that happens to be the name used to find the resource.
A :py:func:`celpy.c7nlib.vpc` function, consequently, is not **really** needed.
We provide it, but don't rewrite any filters to use it.
The function relies on the filter's :py:func:`celpy.c7nlib.get_related`
method to locate the related VPC resource.
For additional information, see the :py:class:`c7n.filters.vpc.NetworkLocation`.
This class reaches into SecurityGroup and Subnet to fetch related objects.
For all of the examples seen so far,
Each resource type's ``RelatedIdsExpression`` matches the ``key`` attribute.
"""
attribute_map = {
"app-elb": "resource.VpcId", # resource.VpcId.vpc().{key}
"lambda": "resource.VpcConfig.VpcId", # resource.VpcConfig.VpcId.vpc().{key}
"codecommit": "resource.vpcConfig.vpcId",
"directory": "resource.VpcSettings.VpcId",
"dms-instance": "resource.ReplicationSubnetGroup.VpcId",
"ec2": "resource.VpcId",