
    Iiz              	          % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
rSSKrSSKJr  SSKJr  SSKJr  SSKJrJrJrJrJrJrJrJrJr  SSKrSSKrSSK J!r!J"r"  SSK#J$r$  SS	K%J&r&J'r'J(r(  \RR                  " \*5      r+ " S
 S5      r,\" SS5      q-S\"R\                  S\"R^                  S\"R`                  4S jr1S\"R^                  S\"R^                  S\"Rd                  4S jr3S\"R\                  S\"R\                  S\"Rd                  4S jr4S\"R\                  S\"R\                  S\"Rd                  4S jr5S\"R^                  S\"R^                  4S jr6S\"R\                  S\"Rn                  4S jr8 " S S\Rr                  5      r9\S\9\Rt                  4   r;\\\9   \S\Rt                  4   4   r<S r=S\"R^                  S\\"Rn                     4S  jr> " S! S"\R~                  5      r@S\"R^                  S\"R`                  4S# jrS\"R^                  S\"R`                  4S$ jrAS\"R^                  S\"R`                  4S% jrBS&\"R^                  S\"R`                  4S' jrCS(\"R^                  S)\"R^                  S\"R`                  4S* jrD SS&\"R^                  S)\\"R^                     S\"R`                  4S+ jjrES,\"R`                  S-\"R^                  S\"R`                  4S. jrFS,\"R\                  S-\"R^                  S\"R\                  4S/ jrGS\"R\                  S\"R^                  S\"R`                  4S0 jrHS1\"R                  S\"R`                  4S2 jrJS3\"R                  S\"R`                  4S4 jrKS1\"R                  S3\"R                  S\"R`                  4S5 jrLS3\"R                  S\"R`                  4S6 jrM SS1\"R                  S7\\\"R`                        S\"R`                  4S8 jjrNS1\"R                  S\"R`                  4S9 jrOS1\"R                  S\"R`                  4S: jrPS1\"R                  S\"R`                  4S; jrQS1\"R                  S\"R`                  4S< jrRS1\"R                  S\"R`                  4S= jrSS1\"R                  S\"R`                  4S> jrTS1\"R                  S\"R`                  4S? jrUS1\"R                  S\"R`                  4S@ jrVSA\"R                  S\"R`                  4SB jrWSC\"R`                  S\"R`                  4SD jrXS1\"R                  S\"R`                  4SE jrYSF\"R`                  S\"R`                  4SG jrZSH\"R^                  S\"R^                  4SI jr[S1\"R                  S\"R`                  4SJ jr\SF\"R`                  S\"R`                  4SK jr]SL\"R`                  S\"R`                  4SM jr^SN\"R`                  S\"R`                  4SO jr_S1\"R                  S\"R`                  4SP jr`S1\"R                  S\"R`                  4SQ jraS1\"R                  S\"R`                  4SR jrbS1\"R                  S\"R`                  4SS jrcS1\"R                  S\"R`                  4ST jrdS1\"R                  S\"R`                  4SU jreS1\"R                  S\"R`                  4SV jrfS1\"R                  S\"R`                  4SW jrgS1\"R                  S\"R`                  4SX jrhS1\"R                  S\"R`                  4SY jriSZ\"R^                  S[\"R^                  S\"R`                  4S\ jrjS\"R`                  4S] jrkS\"R`                  4S^ jrlS\"R`                  4S_ jrmS\"R`                  4S` jrnS\"R`                  4Sa jroS\"R`                  4Sb jrpS\"R`                  4Sc jrqS1\"R                  S\"R`                  4Sd jrrS1\"R                  S\"R`                  4Se jrsS1\"R                  S\"R`                  4Sf jrtS1\"R                  S\"R`                  4Sg jruS1\"R                  S\"R`                  4Sh jrv0 Si\"R                  _Sj\"R                  _Sk\"R                  _Sl\"R                  _Sm\"R                  _Sn\"R                  _So\"R                  _Sp\"R                  _Sq\"R                  _Sr\"R                  _Ss\"R                  _St\"R                  _SH\"R                  _Su\"R                  _Sv\"R                  _Sw\"R                  _Sx\"R                  _0 Sy\"R                  _Sz\"R                  _S{\"R                  _S|\"R                  _S}\"R                  _S~\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _E0 S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _S\"R                  _E\"R                  \"R                  \"R                  \"R                  \"R                  \"R                  \"R                  S.Erx\\y\&4   \zS'   \S\"R`                  4   r{/ \3P\4P\5P\6P\=P\>P\8P\P\AP\BP\CP\EP\FP\GP\1P\HP\JP\LP\OP\WP\XP\YP\ZP\[P\\P\]P\^P\_P\`P\PP\QP\RP\SP\TP\UP\VP\aP\bP\cP\dP\eP\fP\gP\hP\iP\jP\kP\lP\mP\nP\oP\pP\qP\rP\sP\tP\uP\vP7 V s0 s H  o RT                  \" \{U 5      _M     sn r|\\y\{4   \zS'    " S S\!5      r}gs  sn f )a$  
Functions for C7N features when evaluating CEL expressions.

These functions provide a mapping between C7N features and CEL.

These functions are exposed by the global ``FUNCTIONS`` dictionary that is provided
to the CEL evaluation run-time to provide necessary C7N features.

The functions rely on implementation details in the ``CELFilter`` class.

The API
=======

C7N uses CEL and the :py:mod:`c7nlib` module as follows::

    class CELFilter(c7n.filters.core.Filter):  # See below for the long list of mixins.
        decls = {
            "resource": celpy.celtypes.MapType,
            "now": celpy.celtypes.TimestampType,
            "event": celpy.celtypes.MapType,
        }
        decls.update(celpy.c7nlib.DECLARATIONS)

        def __init__(self, expr: str) -> None:
            self.expr = expr

        def validate(self) -> None:
            cel_env = celpy.Environment(
                annotations=self.decls,
                runner_class=c7nlib.C7N_Interpreted_Runner)
            cel_ast = cel_env.compile(self.expr)
            self.pgm = cel_env.program(cel_ast, functions=celpy.c7nlib.FUNCTIONS)

        def process(self,
            resources: Iterable[celpy.celtypes.MapType]) -> Iterator[celpy.celtypes.MapType]:
            now = datetime.datetime.utcnow()
            for resource in resources:
                with C7NContext(filter=the_filter):
                    cel_activation = {
                        "resource": celpy.json_to_cel(resource),
                        "now": celpy.celtypes.TimestampType(now),
                    }
                    if self.pgm.evaluate(cel_activation):
                        yield resource

This isn't the whole story, this is the starting point.

This library of functions is bound into the program that's built from the AST.

Several objects are required in activation for use by the CEL expression

-   ``resource``. The JSON document describing the cloud resource.

-   ``now.`` The current timestamp.

-   Optionally, ``event`` may have an AWS CloudWatch Event.


The type: value Features
========================

The core value features of C7N require a number of CEL extensions.

-   :func:`glob(string, pattern)` uses Python fnmatch rules. This implements ``op: glob``.

-   :func:`difference(list, list)` creates intermediate sets and computes the difference
    as a boolean value. Any difference is True.  This implements ``op: difference``.

-   :func:`intersect(list, list)` creats intermediate sets and computes the intersection
    as a boolean value. Any interection is True.  This implements ``op: intersect``.

-   :func:`normalize(string)` supports normalized comparison between strings.
    In this case, it means lower cased and trimmed. This implements ``value_type: normalize``.

-   :func:`net.cidr_contains` checks to see if a given CIDR block contains a specific
    address.  See https://www.openpolicyagent.org/docs/latest/policy-reference/#net.

-   :func:`net.cidr_size` extracts the prefix length of a parsed CIDR block.

-   :func:`version` uses ``disutils.version.LooseVersion`` to compare version strings.

-   :func:`resource_count` function. This is TBD.

The type: value_from features
==============================

This relies on  ``value_from()`` and ``jmes_path_map()`` functions

In context, it looks like this::

    value_from("s3://c7n-resources/exemptions.json", "json")
    .jmes_path_map('exemptions.ec2.rehydration.["IamInstanceProfile.Arn"][].*[].*[]')
    .contains(resource["IamInstanceProfile"]["Arn"])

The ``value_from()`` function reads values from a given URI.

-   A full URI for an S3 bucket.

-   A full URI for a server that supports HTTPS GET requests.

If a format is given, this is used, otherwise it's based on the
suffix of the path.

The ``jmes_path_map()`` function compiles and applies a JMESPath
expression against each item in the collection to create a
new collection.  To an extent, this repeats functionality
from the ``map()`` macro.

Additional Functions
====================

A number of C7N subclasses of ``Filter`` provide additional features. There are
at least 70-odd functions that are expressed or implied by these filters.

Because the CEL expressions are always part of a ``CELFilter``, all of these
additional C7N features need to be transformed into "mixins" that are implemented
in two places. The function is part of the legacy subclass of ``Filter``,
and the function is also part of ``CELFilter``.

::

    class InstanceImageMixin:
        # from :py:class:`InstanceImageBase` refactoring
        def get_instance_image(self):
            pass

    class RelatedResourceMixin:
        # from :py:class:`RelatedResourceFilter` mixin
        def get_related_ids(self):
            pass

        def get_related(self):
            pass

    class CredentialReportMixin:
        # from :py:class:`c7n.resources.iam.CredentialReport` filter.
        def get_credential_report(self):
            pass

    class ResourceKmsKeyAliasMixin:
        # from :py:class:`c7n.resources.kms.ResourceKmsKeyAlias`
        def get_matching_aliases(self, resource):
            pass

    class CrossAccountAccessMixin:
        # from :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
        def get_accounts(self, resource):
            pass
        def get_vpcs(self, resource):
            pass
        def get_vpces(self, resource):
            pass
        def get_orgids(self, resource):
            pass
        # from :py:class:`c7n.resources.secretsmanager.CrossAccountAccessFilter`
        def get_resource_policy(self, resource):
            pass

    class SNSCrossAccountMixin:
        # from :py:class:`c7n.resources.sns.SNSCrossAccount`
        def get_endpoints(self, resource):
            pass
        def get_protocols(self, resource):
            pass

    class ImagesUnusedMixin:
        # from :py:class:`c7n.resources.ami.ImageUnusedFilter`
        def _pull_ec2_images(self, resource):
            pass
        def _pull_asg_images(self, resource):
            pass

    class SnapshotUnusedMixin:
        # from :py:class:`c7n.resources.ebs.SnapshotUnusedFilter`
        def _pull_asg_snapshots(self, resource):
            pass
        def _pull_ami_snapshots(self, resource):
            pass

    class IamRoleUsageMixin:
        # from :py:class:`c7n.resources.iam.IamRoleUsage`
        def service_role_usage(self, resource):
            pass
        def instance_profile_usage(self, resource):
            pass

    class SGUsageMixin:
        # from :py:class:`c7n.resources.vpc.SGUsage`
        def scan_groups(self, resource):
            pass

    class IsShieldProtectedMixin:
        # from :py:mod:`c7n.resources.shield`
        def get_type_protections(self, resource):
            pass

    class ShieldEnabledMixin:
        # from :py:class:`c7n.resources.account.ShieldEnabled`
        def account_shield_subscriptions(self, resource):
            pass

    class CELFilter(
        InstanceImageMixin, RelatedResourceMixin, CredentialReportMixin,
        ResourceKmsKeyAliasMixin, CrossAccountAccessMixin, SNSCrossAccountMixin,
        ImagesUnusedMixin, SnapshotUnusedMixin, IamRoleUsageMixin, SGUsageMixin,
        Filter,
    ):
        '''Container for functions used by c7nlib to expose data to CEL'''
        def __init__(self, data, manager) -> None:
            super().__init__(data, manager)
            assert data["type"].lower() == "cel"
            self.expr = data["expr"]
            self.parser = c7n.filters.offhours.ScheduleParser()

        def validate(self):
            pass  # See above example

        def process(self, resources):
            pass  # See above example

This is not the complete list. See the ``tests/test_c7nlib.py`` for the ``celfilter_instance``
fixture which contains **all** of the functions required.

C7N Context Object
==================

A number of the functions require access to C7N features that are not simply part
of the resource being filtered. There are two alternative ways to handle this dependency:

-   A global C7N context object that has the current ``CELFilter`` providing
    access to C7N internals.

-   A ``C7N`` argument to the functions that need C7N access.
    This would be provided in the activation context for CEL.

To keep the library functions looking simple, the module global ``C7N`` is used.
This avoids introducing a non-CEL parameter to the c7nlib functions.

The ``C7N`` context object contains the following attributes:

-   ``filter``. The original C7N ``Filter`` object. This provides access to the
    resource manager. It can be used to manage supplemental
    queries using C7N caches and other resource management.

This is set by the :py:class:`C7NContext` prior to CEL evaluation.

Name Resolution
===============

Note that names are **not** resolved via a lookup in the program object,
an instance of the :py:class:`celpy.Runner` class. To keep these functions
simple, the runner is not part of the run-time, and name resolution
will appear to be "hard-wrired" among these functions.

This is rarely an issue, since most of these functions are independent.
The :func:`value_from` function relies on :func:`text_from` and :func:`parse_text`.
Changing either of these functions with an override won't modify the behavior
of :func:`value_from`.
    N)closing)version)TracebackType)	AnyCallableDictIteratorListOptionalTypeUnioncast)InterpretedRunnerceltypes)json_to_cel)
AnnotationContext	Evaluatorc                   t    \ rS rSrSrS\SS4S jrS\4S jrSS jr	S	\
\\      S
\
\   S\
\   SS4S jrSrg)
C7NContexti-  z
Saves current C7N filter for use by functions in this module.

This is essential for making C7N filter available to *some* of these functions.

::

    with C7NContext(filter):
        cel_prgm.evaluate(cel_activation)
filterreturnNc                     Xl         g Nr   )selfr   s     2/venv/lib/python3.13/site-packages/celpy/c7nlib.py__init__C7NContext.__init__9  s        c                 P    U R                   R                   SU R                  < S3$ )Nz(filter=))	__class____name__r   r   s    r   __repr__C7NContext.__repr__<  s$    ..))*(4;;/CCr    c                     U q g r   )C7Nr%   s    r   	__enter__C7NContext.__enter__?  s    r    exc_type	exc_value	tracebackc                     [        SS 5      qg )Nr   )r   r)   )r   r,   r-   r.   s       r   __exit__C7NContext.__exit__C  s     <&r    r   )r   N)r$   
__module____qualname____firstlineno____doc__r   r   strr&   r*   r   r   BaseExceptionr   r0   __static_attributes__ r    r   r   r   -  sl    	s t D# D4./ M* M*	
 
r    r   sourcetargetr   c                    ^^ [         R                  " S5      m[         R                  " S5      nUU4S jU  5       n [        [         R                  [	        U5      5      R                  U5      $ ! [         a     gf = f)a^  
The C7N shorthand ``tag:Name`` doesn't translate well to CEL. It extracts a single value
from a sequence of objects with a ``{"Key": x, "Value": y}`` structure; specifically,
the value for ``y`` when ``x == "Name"``.

This function locate a particular "Key": target within a list of {"Key": x, "Value", y} items,
returning the y value if one is found, null otherwise.

In effect, the ``key()``    function::

    resource["Tags"].key("Name")["Value"]

is somewhat like::

    resource["Tags"].filter(x, x["Key"] == "Name")[0]

But the ``key()`` function doesn't raise an exception if the key is not found,
instead it returns None.

We might want to generalize this into a ``first()`` reduction macro.
``resource["Tags"].first(x, x["Key"] == "Name" ? x["Value"] : null, null)``
This macro returns the first non-null value or the default (which can be ``null``.)
KeyValuec              3      >#    U  HN  n[        [        R                  [        [        R                  U5      R	                  T5      5      T:X  d  MJ  Uv   MP     g 7fr   )r   r   
StringTypeMapTypeget).0itemkeyr;   s     r   	<genexpr>key.<locals>.<genexpr>n  sJ      )D##T(*:*:D%A%E%Ec%JK 	s   A	A	AN)r   r@   r   rA   nextrB   StopIteration)r:   r;   valuematchesrE   s    `  @r   rE   rE   T  sm    0 

e
$C(E))GH$$d7m488?? s   1A/ /
A<;A<textpatternc                 V    [         R                  " [        R                  " X5      5      $ )aA  Compare a string with a pattern.

While ``"*.py".glob(some_string)`` seems logical because the pattern the more persistent object,
this seems to cause confusion.

We use ``some_string.glob("*.py")`` to express a regex-like rule. This parallels the CEL
`.matches()` method.

We also support ``glob(some_string, "*.py")``.
)r   BoolTypefnmatch)rL   rM   s     r   globrQ   z  s     W__T;<<r    leftrightc                 j    [         R                  " [        [        U 5      [        U5      -
  5      5      $ )z
Compute the difference between two lists. This is ordered set difference: left - right.
It's true if the result is non-empty: there is an item in the left, not present in the right.
It's false if the result is empty: the lists are the same.
r   rO   boolsetrR   rS   s     r   
differencerY     '     T#d)c%j"89::r    c                 j    [         R                  " [        [        U 5      [        U5      -  5      5      $ )z
Compute the intersection between two lists.
It's true if the result is non-empty: there is an item in both lists.
It's false if the result is empty: there is no common item between the lists.
rU   rX   s     r   	intersectr\     rZ   r    stringc                 f    [         R                  " U R                  5       R                  5       5      $ )z
Normalize a string.
)r   r@   lowerstrip)r]   s    r   	normalizera     s$     v||~33566r    
collectionc                 R    [         R                  " [        [        U 5      5      5      $ )z
Unique size of a list
)r   IntTypelenrW   )rb   s    r   unique_sizerf     s     CJ011r    c                      ^  \ rS rSrU 4S jr\R                  R                  S:X  a1  \R                  R                  S::  a  \	S 5       r
S rSrU =r$ SrU =r$ SrU =r$ )IPv4Networki  c                    > Uc  g[        U[        R                  5      (       a  U R                  U5      $ [        [
        U ]  U5      $ NF)
isinstance	ipaddress_BaseNetworksupernet_ofsuperrh   __contains__r   otherr#   s     r   rp   IPv4Network.__contains__  sA    =eY3344##E**[$4U;;r          c                 
    U R                   UR                   :w  a  [        U  SU S35      eUR                  U R                  :*  =(       a    UR                  U R                  :  $ ! [         a    [        SU  SU 35      ef = f)Nz and z are not of the same versionz*Unable to test subnet containment between )_version	TypeErrornetwork_addressbroadcast_addressAttributeError)abs     r   _is_subnet_ofIPv4Network._is_subnet_of  s    ::+#qcqc1M$NOO%%):):: C++q/B/BB " DQCuQCP s   A#A& &Bc                 $    U R                  X5      $ )z3Return True if this network is a supernet of other.)r~   )r   rr   s     r   rn   IPv4Network.supernet_of  s    %%e22r    r9   )r$   r2   r3   r4   rp   sysversion_infomajorminorstaticmethodr~   rn   r8   __classcell__r#   s   @r   rh   rh     sV    < "s'7'7'='='B		 
		3 	3# (C"r    rh   .c                     [         nSU ;  a  [        R                  n U" U 5      nU$ ! [        R                  [        4 a    Sn U$ f = f)z
Process cidr ranges.

This is a union of types outside CEL.

It appears to be Union[None, IPv4Network, ipaddress.IPv4Address]
/N)rh   rl   
ip_addressAddressValueError
ValueError)rJ   klassvs      r   
parse_cidrr     sW     $E
%$$%L H ''4 Hs   ( AArJ   c                 h    [        U 5      nU(       a   [        R                  " UR                  5      $ g)zCIDR prefixlen valueN)r   r   rd   	prefixlen)rJ   cidrs     r   size_parse_cidrr     s'    eD//r    c                   8   ^  \ rS rSrSrS\S\4U 4S jjrSrU =r	$ )ComparableVersioni  zv
The default LooseVersion will fail on comparing present strings, used
in the value as shorthand for certain options.
rr   r   c                 L   >  [         [        U ]  U5      $ ! [         a     gf = frj   )ro   r   __eq__rx   rq   s     r   r   ComparableVersion.__eq__  s-    	*D8?? 		s    
##r9   )
r$   r2   r3   r4   r5   objectrV   r   r8   r   r   s   @r   r   r     s     
F t  r    r   c                 H    [        [        R                  [        U 5      5      $ r   )r   r   r>   r   rJ   s    r   r   r     s      1% 899r    c                 H    [        [        R                  [        U 5      5      $ r   r   r   r>   rV   r   s    r   presentr     s    U,,r    c                 R    [        [        R                  [        U 5      (       + 5      $ r   r   r   s    r   absentr     s    DK00r    urlc                    [         R                  R                  U SS0S9n[        [         R                  R	                  U5      5       nUR                  5       R                  S5      S:X  aF  [        R                  " UR                  5       [        R                  S-  5      R                  S5      nOUR                  5       R                  S5      nSSS5        [        R                  " W5      $ ! , (       d  f       N$= f)	zM
Read raw text from a URL. This can be expanded to accept S3 or other URL's.
zAccept-Encodinggzip)headerszContent-Encoding    utf8zutf-8N)urllibrequestRequestr   urlopeninforB   zlib
decompressread	MAX_WBITSdecoder   r@   )r   reqresponseraw_datas       r   	text_fromr     s     ..
 
 /@&.I
 
JC	'',	-==?12f<x}}8KLSSH  }}--g6H 
. x(( 
.	-s   	B	C00
C>source_textformatc           
      t   US:X  a  [        [        R                  " U 5      5      $ US:X  aW  [        R                  " U R                  5        Vs/ s H'  n[        R                  " UR                  5       5      PM)     sn5      $ US;   aR  [        R                  " U R                  5        Vs/ s H"  n[        [        R                  " U5      5      PM$     sn5      $ US:X  aX  [        R                  " [        R                  " [        R                  " U 5      5       Vs/ s H  n[        U5      PM     sn5      $ US:X  aX  [        R                  " [        R                  " [        R                  " U 5      5       Vs/ s H  n[        U5      PM     sn5      $ [        SU< 35      es  snf s  snf s  snf s  snf )z&
Parse raw text using a given format.
jsontxt)ldjsonndjsonjsonlcsvcsv2dictUnsupported format: )r   r   loadsr   ListType
splitlinesr@   rstripr   readerioStringIO
DictReaderr   )r   r   srows       r   
parse_textr     sl    4::k233	5  6A6L6L6NO6NX  ,6NO
 	
 
0	0  1<1G1G1IJ1IA[A'1IJ
 	
 
5  ),BKK4L)MN)M#[)MN
 	
 
:	  ),K8P)QR)Q#[)QR
 	
 /z:;; P K O Ss   .F&+)F+F0;F5c                    SnU(       d:  [         R                  R                  U 5      u  p4[        R                  " USS 5      nX;  a  [        SU< 35      e[        [        R                  [        U 5      5      n[        XQ5      $ )aN  
Read values from a URL.

First, do :func:`text_from` to read the source.
Then, do :func:`parse_text` to parse the source, if needed.

This makes the format optional, and deduces it from the URL's path information.

C7N will generally replace this with a function
that leverages a more sophisticated :class:`c7n.resolver.ValuesFrom`.
)r   r   r   r   r   r   r      Nr   )	ospathsplitextr   r@   r   r   r   r   )r   r   supported_formats_suffixr   s         r   
value_fromr   /  sz     X GG$$S)	$$VABZ0&/z:;;
 H''38H h''r    source_datapath_sourcec                 b    [         R                  " U5      n[        UR                  U 5      5      $ )z3
Apply JMESPath to an object read from from a URL.
)jmespathcompiler   search)r   r   
expressions      r   	jmes_pathr   O  s*     !!+.Jz((566r    c           
          [         R                  " U5      n[        R                  " U  Vs/ s H  n[	        UR                  U5      5      PM     sn5      $ s  snf )zc
Apply JMESPath to a each object read from from a URL.
This is for ndjson, nljson and jsonl files.
)r   r   r   r   r   r   )r   r   r   r   s       r   jmes_path_mapr   Y  sL     !!+.J8CDZ&&s+	,D Ds   $Ac           
         [        X5      nUc  g [        [        R                  U5      R	                  SS5      u  p4UR                  5       R                  SS5      u  pV[        R                  " [        R                  " S5      [        R                  " U5      [        R                  " S5      [        R                  " U5      [        R                  " S5      [        R                  " U5      05      $ ! [         a     gf = f)a1  
Examines a list of {"Key": text, "Value": text} mappings
looking for the given Key value.

Parses a ``message:action@action_date`` value into a mapping
{"message": message, "action": action, "action_date": action_date}

If no Key or no Value or the Value isn't the right structure,
the result is a null.
N:r   @messageactionaction_date)
rE   r   r   r@   rsplitr`   splitr   rA   TimestampType)r:   r;   rJ   msgtgtr   action_date_strs          r   
marked_keyr   f  s     E}++U3::3B"%))+"3"3C"; 	*H,?,?,D)8+>+>v+F.0F0F0W	
   s   AC3 3
D ?D resourcec                     [         R                  R                  U 5      nU(       a  US   nUS   nOSnSn[        [        R
                  R                  U5      US.5      $ )av  
Reach into C7N to get the image details for this EC2 or ASG resource.

Minimally, the creation date is transformed into a CEL timestamp.
We may want to slightly generalize this to json_to_cell() the entire Image object.

The following may be usable, but it seems too complex:

::

    C7N.filter.prefetch_instance_images(C7N.policy.resources)
    image = C7N.filter.get_instance_image(resource["ImageId"])
    return json_to_cel(image)

..  todo:: Refactor C7N

    Provide the :py:class:`InstanceImageBase` mixin in a :py:class:`CELFilter` class.
    We want to have the image details in the new :py:class:`CELFilter` instance.
CreationDateNamez2000-01-01T01:01:01.000Z )r   r   )r)   r   get_instance_imager   dateutilparserisoparse)r   imagecreation_date
image_names       r   r   r     s\    0 JJ))(3En-6]
2
!11-@*U r    r   c           
          [         R                  R                  R                  5       R	                  S5      nUR                  U S   U S   U S   U S   U S   U S   U S   S	9S
   n[        U5      $ )a  
Reach into C7N and make a statistics request using the current C7N filter object.

The ``request`` parameter is the request object that is passed through to AWS via
the current C7N filter's manager. The request is a Mapping with the following keys and values:

::

    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")
    })

The request is passed through to AWS more-or-less directly. The result is a CEL
list of values for then requested statistic. A ``.map()`` macro
can be used to compute additional details. An ``.exists()`` macro can filter the
data to look for actionable values.

We would prefer to refactor C7N and implement this with code something like this:

::

    C7N.filter.prepare_query(C7N.policy.resources)
    data = C7N.filter.get_resource_statistics(client, resource)
    return json_to_cel(data)

..  todo:: Refactor C7N

    Provide a :py:class:`MetricsAccess` mixin in a :py:class:`CELFilter` class.
    We want to have the metrics processing in the new :py:class:`CELFilter` instance.


cloudwatch	Namespace
MetricName
Statistics	StartTimeEndTimePeriod
Dimensions)r   r   r   r   r   r   r   
Datapoints)r)   r   managersession_factoryclientget_metric_statisticsr   r   r  datas      r   get_raw_metricsr    s    L ZZ//188FF''+&<(<(+&	"x <( (  D tr    c                 L   [         R                  R                  R                  5       R                  n[         R                  R                  R
                  nX R                  U5      S./n[        [        [        R                  [        UUS   UUS   /US   US   US   S.5      5      5      n[        [        [        [        R                     U5       Vs/ s H<  n[        [        [        [        R                  4   U5      R                  US   5      PM>     sn5      $ s  snf )a  
Reach into C7N and make a statistics request using the current C7N filter.

This builds a request object that is passed through to AWS via the :func:`get_raw_metrics`
function.

The ``request`` parameter is a Mapping with the following keys and values:

::

    resource.get_metrics({"MetricName": "CPUUtilization", "Statistic": "Average",
        "StartTime": now - duration("4d"), "EndTime": now, "Period": duration("86400s")}
        ).exists(m, m < 30)

The namespace is derived from the ``C7N.policy``. The dimensions are derived from
the ``C7N.fiter.model``.

..  todo:: Refactor C7N

    Provide a :py:class:`MetricsAccess` mixin in a :py:class:`CELFilter` class.
    We want to have the metrics processing in the new :py:class:`CELFilter` instance.

)r   r>   r   	Statisticr   r   r   )r   r   r   r   r   r   r   )r)   r   r  	get_model	dimensionresource_typerB   r  r   r   rA   r   r
   r>   r   r6   )r   r   r  	namespace
dimensionsraw_metricsrD   s          r   get_metricsr    s   4 

"",,.88I

""00I$||I/FGHJ!$x'7'7"!,/$";/0 -y)h'	

: 
# 
K  T(..1;?	
? c8>>)*D155gk6JK?	
 	
s   AD!c                     [         R                  R                  R                  5       R	                  SSS9nUR                  U S9S   n[        U5      $ )a  
Reach into C7N and make a health-events request using the current C7N filter.

The ``request`` parameter is the filter object that is passed through to AWS via
the current C7N filter's manager. The request is a List of AWS health events.

::

    get_raw_health_events({
        "services": ["ELASTICFILESYSTEM"],
        "regions": ["us-east-1", "global"],
        "eventStatusCodes": ['open', 'upcoming'],
    })
health	us-east-1region_namer   events)r)   r   r  r  r  describe_eventsr   r  s      r   get_raw_health_eventsr    sT     ZZ//188k 9 +F!!!1(;Dtr    statusesc                    U(       d,  [         R                  " S5      [         R                  " S5      /nSSSSSS.n[        R                  R                  nUR                  UR                  S   UR                  5       R                  R                  5       5      n[        [        [         R                  [        U/UR                  R                  S	/US
.5      5      5      nU$ )z
Reach into C7N and make a health-event request using the current C7N filter.

This builds a request object that is passed through to AWS via the :func:`get_raw_health_events`
function.

..  todo:: Handle optional list of event types.
openupcomingELASTICLOADBALANCINGEBSELASTICFILESYSTEMELASTICMAPREDUCE)zapp-elbebsefselbemrr   global)servicesregionseventStatusCodes)r   r@   r)   r   r  rB   r  r  serviceupperr  r   rA   r   configregion)r   r  phd_svc_name_mapmr*  
raw_eventss         r   get_health_eventsr1  $  s     ''/1D1DZ1PQ)"%! 	

A""166*#5q{{}7L7L7R7R7TUG&tH,<,<k 	2 (	
? ( J r    c                 V    [         R                  R                  U 5      n[        U5      $ )a  
Reach into C7N and make a get_related_ids() request using the current C7N filter.

..  todo:: Refactor C7N

    Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
    We want to have the related id's details in the new :py:class:`CELFilter` instance.
)r)   r   get_related_idsr   )r   related_idss     r   r3  r3  E  s#     **,,X6K{##r    c                 V    [         R                  R                  U 5      n[        U5      $ )zS
Reach into C7N and make a get_related_sgs() request using the current C7N filter.
)r)   r   get_related_sgsr   )r   security_groupss     r   r6  r6  T  s#     jj00:O''r    c                 V    [         R                  R                  U 5      n[        U5      $ )zW
Reach into C7N and make a get_related_subnets() request using the current C7N filter.
)r)   r   get_related_subnetsr   )r   subnetss     r   r9  r9  \  s#     jj,,X6Gwr    c                 V    [         R                  R                  U 5      n[        U5      $ )z\
Reach into C7N and make a get_related_nat_gateways() request using the current C7N filter.
)r)   r   get_related_nat_gatewaysr   )r   nat_gatewayss     r   r<  r<  d  s#     ::66x@L|$$r    c                 V    [         R                  R                  U 5      n[        U5      $ )zT
Reach into C7N and make a get_related_igws() request using the current C7N filter.
)r)   r   get_related_igwsr   )r   igwss     r   r?  r?  l  s#     ::&&x0Dtr    c                 V    [         R                  R                  U 5      n[        U5      $ )z`
Reach into C7N and make a get_related_security_configs() request using the current C7N filter.
)r)   r   get_related_security_configsr   )r   security_configss     r   rB  rB  t  s%     zz>>xH'((r    c                 V    [         R                  R                  U 5      n[        U5      $ )zS
Reach into C7N and make a get_related_vpc() request using the current C7N filter.
)r)   r   get_related_vpcr   r   vpcs     r   rE  rE  |  s#     **
$
$X
.Csr    c                 V    [         R                  R                  U 5      n[        U5      $ )zX
Reach into C7N and make a get_related_kms_keys() request using the current C7N filter.
)r)   r   get_related_kms_keysr   rF  s     r   rI  rI    s#     **
)
)(
3Csr    security_group_idc                 X    [         R                  R                  U /5      n[        U5      $ )a  
Reach into C7N and make a get_related() request using the current C7N filter to get
the security group.

..  todo:: Refactor C7N

    Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
    We want to have the related id's details in the new :py:class:`CELFilter` instance.
    See :py:class:`VpcSecurityGroupFilter` subclass of :py:class:`RelatedResourceFilter`.
r)   r   get_relatedr   )rJ  r7  s     r   security_grouprN    s'     jj,,.?-@AO''r    	subnet_idc                 X    [         R                  R                  U /5      n[        U5      $ )a  
Reach into C7N and make a get_related() request using the current C7N filter to get
the subnet.

..  todo:: Refactor C7N

    Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
    We want to have the related id's details in the new :py:class:`CELFilter` instance.
    See :py:class:`VpcSubnetFilter` subclass of :py:class:`RelatedResourceFilter`.
rL  )rO  r:  s     r   subnetrQ    s%     jj$$i[1Gwr    c                     [         R                  R                  R                  5       R	                  S5      nUR                  5       R                  SS5      n[         R                  R                  R                  5       n0 nU H'  nUR                  US   / 5      R                  U5        M)     U R                  UR                  5      U;   a7  U[        [        U R                  UR                  5      5         n[        U5      $ [        / 5      $ )a!  
Reach into C7N and locate the flow logs using the current C7N filter.

..  todo:: Refactor C7N

    Provide a separate function to get the flow logs, separate from the
    the filter processing.

..  todo:: Refactor :func:`c7nlib.flow_logs` -- it exposes too much implementation detail.

ec2FlowLogsr9   
ResourceId)r)   r   r  r  r  describe_flow_logsrB   r  
setdefaultappendidr   r6   r   )r   r  logsr/  resource_mapflflogss          r   	flow_logsr^    s     ZZ//188?F$$&**:r:D

$$&A46L< 0"5<<R@ ||ADD\)T#x||ADD'9:;5!!r?r    vpc_idc                 X    [         R                  R                  U /5      n[        U5      $ )a  
Reach into C7N and make a ``get_related()`` request using the current C7N filter to get
the VPC details.

..  todo:: Refactor C7N

    Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
    We want to have the related id's details in the new :py:class:`CELFilter` instance.
    See :py:class:`VpcFilter` subclass of :py:class:`RelatedResourceFilter`.
rL  )r_  rG  s     r   rG  rG    s%     **
 
 &
*Csr    r   c                    [         R                  R                  R                  R                  [         R                  R                  R                  R
                  S.n[        R                  " U R                  " S0 UD65      $ )a  
Reach into C7N and build a set of substitutions to replace text in a JMES path.

This is based on how :py:class:`c7n.resolver.ValuesFrom` works. There are
two possible substitution values:

-   account_id
-   region

:param jmes_path: the source
:return: A JMES with values replaced.
)
account_idr-  r9   )	r)   r   r  r,  rb  r-  r   r@   r   )r   config_argss     r   substrd    s^     jj((//::**$$++22K y//>+>??r    c                 R    [        [        R                  R                  U 5      5      $ )a  
Reach into C7N and make a get_related() request using the current C7N filter to get
the IAM-role credential details.

See :py:class:`c7n.resources.iam.CredentialReport` filter.
The `get_credential_report()` function does what we need.

..  todo:: Refactor C7N

    Refactor the :py:class:`c7n.resources.iam.CredentialReport` filter into a
    ``CredentialReportMixin`` mixin to the :py:class:`CELFilter` class.
    The ``get_credential_report()`` function does what we need.
)r   r)   r   get_credential_reportr   s    r   credentialsrh    s     szz77ABBr    c                 P    [        [        R                  R                  5       5      $ )a  
Reach into C7N and make a get_matching_aliases() request using the current C7N filter to get
the alias.

See :py:class:`c7n.resources.kms.ResourceKmsKeyAlias`.
The `get_matching_aliases()` function does what we need.

..  todo:: Refactor C7N

    Refactor the :py:class:`c7n.resources.kms.ResourceKmsKeyAlias` filter into a
    ``ResourceKmsKeyAliasMixin`` mixin to the :py:class:`CELFilter` class.
    The ``get_matching_aliases()`` dfunction does what we need.
)r   r)   r   get_matching_aliases)r_  s    r   	kms_aliasrk    s     szz66899r    key_idc                 X    [         R                  R                  U /5      n[        U5      $ )a+  
Reach into C7N and make a ``get_related()`` request using the current C7N filter to get
the key. We're looking for the c7n.resources.kms.Key resource manager to get the related key.

..  todo:: Refactor C7N

    Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
rL  )rl  rE   s     r   kms_keyrn    s%     **
 
 &
*Csr    	tag_valuec                 (   [         R                  R                  R                  U 5      nUR	                  SS5      nUR                  5        VVVs0 s H"  u  p4UU Vs/ s H  oUS   US   US.PM     sn_M$     nnnn[        U5      $ s  snf s  snnnf )a  
Reach into C7N and use the the :py:class:`c7n.filters.offhours.ScheduleParser` class
to examine the tag's value, the current time, and return a True/False.
This parser is the `parser` value of the :py:class:`c7n.filters.offhours.Time` filter class.
Using the filter's `parser.parse(value)` provides needed structure.

The `filter.parser.parse(value)` will transform text of the Tag value
into a dictionary. This is further transformed to something we can use in CEL.

From this
::

    off=[(M-F,21),(U,18)];on=[(M-F,6),(U,10)];tz=pt

C7N ScheduleParser produces this
::

    {
      off: [
        { days: [1, 2, 3, 4, 5], hour: 21 },
        { days: [0], hour: 18 }
      ],
      on: [
        { days: [1, 2, 3, 4, 5], hour: 6 },
        { days: [0], hour: 10 }
      ],
      tz: "pt"
    }

For CEL, we need this
::

    {
      off: [
        { days: [1, 2, 3, 4, 5], hour: 21, tz: "pt" },
        { days: [0], hour: 18, tz: "pt" }
      ],
      on: [
        { days: [1, 2, 3, 4, 5], hour: 6, tz: "pt" },
        { days: [0], hour: 10, tz: "pt" }
      ],
    }

This lets a CEL expression use
::

    key("maid_offhours").resource_schedule().off.exists(s,
        now.getDayOfWeek(s.tz) in s.days && now.getHour(s.tz) == s.hour)
tzetdayshour)rs  rt  rq  )r)   r   r   parsepopitemsr   )ro  c7n_sched_docrq  state	time_listtimecel_sched_docs          r   resource_scheduler}    s    h JJ%%++I6M			4	&B
 !. 3 3 5	 !6E 	OX
OXt&\4<rBy
 	
 !6	   }%%
s   BB2BBc                 P    [        [        R                  R                  5       5      $ )a  
Reach into C7N filter and get accounts for a given resource.
Used by resources like AMI's, log-groups, ebs-snapshot, etc.

..  todo:: Refactor C7N

    Provide the :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
    as a mixin to ``CELFilter``.
)r   r)   r   get_accountsrg  s    r   r  r  Y  s     szz..011r    c                 P    [        [        R                  R                  5       5      $ )a  
Reach into C7N filter and get vpcs for a given resource.
Used by resources like AMI's, log-groups, ebs-snapshot, etc.

..  todo:: Refactor C7N

    Provide the :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
    as a mixin to ``CELFilter``.
)r   r)   r   get_vpcsrg  s    r   r  r  f  s     szz**,--r    c                 P    [        [        R                  R                  5       5      $ )a  
Reach into C7N filter and get vpces for a given resource.
Used by resources like AMI's, log-groups, ebs-snapshot, etc.

..  todo:: Refactor C7N

    Provide the :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
    as a mixin to ``CELFilter``.

)r   r)   r   	get_vpcesrg  s    r   r  r  s  s     szz++-..r    c                 P    [        [        R                  R                  5       5      $ )a  
Reach into C7N filter and get orgids for a given resource.
Used by resources like AMI's, log-groups, ebs-snapshot, etc.

..  todo:: Refactor C7N

    Provide the :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
    as a mixin to ``CELFilter``.
)r   r)   r   
get_orgidsrg  s    r   r  r    s     szz,,.//r    c                 P    [        [        R                  R                  5       5      $ )zFor sns resources

..  todo:: Refactor C7N

    Provide the :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
    as a mixin to ``CELFilter``.
)r   r)   r   get_endpointsrg  s    r   r  r    s     szz//122r    c                 P    [        [        R                  R                  5       5      $ )z+For sns resources

..  todo:: Refactor C7N
)r   r)   r   get_protocolsrg  s    r   r  r    s    
 szz//122r    c                 :   U R                  [        R                  " S5      U R                  [        R                  " S5      5      5      n[        R                  R
                  R                  5       R                  S5      n[        UR                  USS9S   5      $ )z+For kms resources

..  todo:: Refactor C7N
TargetKeyIdKeyIdkmsdefault)r  
PolicyNamePolicy)
rB   r   r@   r)   r   r  r  r  r   get_key_policy)r   rl  r  s      r   r  r    s    
 \\M*X((124F ZZ//188?F  	 	""*	, r    c                 P    [        [        R                  R                  5       5      $ )z
Reach into C7N filter and get the resource policy for a given resource.
Used by resources like AMI's, log-groups, ebs-snapshot, etc.

..  todo:: Refactor C7N
)r   r)   r   get_resource_policyrg  s    r   r  r    s     szz55788r    c                    [         R                  R                  R                  5       R	                  S5      n[        [         R                  R                  R                  UR                  U S   S9R                  SS5      5      $ )zi
For log-groups resources.

..  todo:: Refactor C7N

    this should be directly available in CELFilter.
rZ  logGroupName)r  subscriptionFiltersr9   )	r)   r   r  r  r  r   retrydescribe_subscription_filtersrB   r   r  s     r   r  r    sq     ZZ//188@F

  00!.1 	! 	
 ##R
(	 r    c                     [         R                  R                  R                  5       R	                  S5      n[        [         R                  R                  R                  UR                  U S   SS95      $ )z{
For rds-snapshot and ebs-snapshot resources

..  todo:: Refactor C7N

    this should be directly available in CELFilter.
rS  
SnapshotIdcreateVolumePermission)r  	Attribute)r)   r   r  r  r  r   r  describe_snapshot_attributer  s     r   describe_db_snapshot_attributesr    se     ZZ//188?F

  ..-. 	! 	
 r    arnfieldc                     S Vs0 s H  n[        U5      U_M     nnU R                  S5      tpEUS:w  a  [        SU  35      e[        [	        U[        U5         U5      5      n[        Xa   5      $ s  snf )a  
Parse an ARN, removing a partivular field.
The field name must one one of
"partition", "service", "region", "account-id", "resource-type", "resource-id"
In the case of a ``resource-type/resource-id`` path, this will be a "resource-id" value,
and there will be no "resource-type".

Examples formats

    ``arn:partition:service:region:account-id:resource-id``

    ``arn:partition:service:region:account-id:resource-type/resource-id``

    ``arn:partition:service:region:account-id:resource-type:resource-id``
))	partitionr*  r-  
account-idresource-id)r  r*  r-  r  zresource-typer  r   r  zNot an ARN: )re   r   r   dictzipr   )r  r  namesfield_namesprefixfieldsmappings          r   	arn_splitr    s    $

E 	E
E
   iinOF<u-..3{3v;/89Gw~&&s   A1c                      [        [        [        R                  R	                  5       [        R                  R                  5       -  5      5      $ )z
Depends on :py:meth:`CELFilter._pull_ec2_images` and :py:meth:`CELFilter._pull_asg_images`

See :py:class:`c7n.resources.ami.ImageUnusedFilter`
)r   listr)   r   _pull_ec2_images_pull_asg_imagesr9   r    r   
all_imagesr    s;     JJ'')CJJ,G,G,II	
 r    c                      [        [        [        R                  R	                  5       [        R                  R                  5       -  5      5      $ )z
Depends on :py:meth:`CELFilter._pull_asg_snapshots`
and :py:meth:`CELFilter._pull_ami_snapshots`

See :py:class:`c7n.resources.ebs.SnapshotUnusedFilter`
)r   r  r)   r   _pull_asg_snapshots_pull_ami_snapshotsr9   r    r   all_snapshotsr  	  s;     JJ**,szz/M/M/OO	
 r    c            
      .   [         R                  R                  R                  S5      R	                  5       n [        U  Vs/ s H/  oR                  S5      (       a  M  UR                  SUS   5      PM1     sn5      n[        [        U5      5      $ s  snf )z~
Depends on :py:meth:`CELFilter.manager.get_launch_configuration_names`

See :py:class:`c7n.resources.asg.UnusedLaunchConfig`
asgLaunchTemplateLaunchConfigurationNameAutoScalingGroupName	r)   r   r  get_resource_manager	resourcesrW   rB   r   r  )asgsr|   useds      r   all_launch_configuration_namesr    s     ::2259CCED6AUU#34 	D'+A)BC6 7D tDz""6s   BBc                  P    [        [        R                  R                  5       5      $ )ze
Depends on :py:meth:`CELFilter.service_role_usage`

See :py:class:`c7n.resources.iam.UnusedIamRole`
)r   r)   r   service_role_usager9   r    r   all_service_rolesr  $  s     szz44677r    c                  P    [        [        R                  R                  5       5      $ )zr
Depends on :py:meth:`CELFilter.instance_profile_usage`

See :py:class:`c7n.resources.iam.UnusedInstanceProfiles`
)r   r)   r   instance_profile_usager9   r    r   all_instance_profilesr  -  s     szz88:;;r    c            
          [         R                  R                  R                  S5      R	                  5       n [        U  Vs/ s H  nUR                  SUS   5      PM     sn5      n[        [        U5      5      $ s  snf )zq
Depends on :py:meth:`CELFilter.get_dbsubnet_group_used`

See :py:class:`c7n.resources.rds.UnusedRDSSubnetGroup`
rdsDBSubnetGroupNameDBInstanceIdentifierr  )r  rr  s      r   all_dbsubenet_groupsr  6  st     **


1
1%
8
B
B
DCA 	
!1%;#<= D tDz""s   A;c                  P    [        [        R                  R                  5       5      $ )zd
Depends on :py:meth:`CELFilter.scan_groups`

See :py:class:`c7n.resources.vpc.UnusedSecurityGroup`
)r   r)   r   scan_groupsr9   r    r   all_scan_groupsr  C  s     szz--/00r    c                     [         R                  R                  R                  5       R	                  S5      nUR                  U S   S9n[        US   5      $ )z
Depends on :py:meth:`CELFilter.resources`

See :py:class:`c7n.resources.elb.IsNotLoggingFilter` and
:py:class:`c7n.resources.elb.IsLoggingFilter`.
r$  LoadBalancerName)r  LoadBalancerAttributes)r)   r   r  r  r  !describe_load_balancer_attributesr   )r   r  resultss      r   get_access_logr  L  sV     ZZ//188?F66!"45 7 7Gw7899r    c                 4  ^ S[         S[        [        [        [         4   4S jm[        R
                  R                  R                  5       R                  S5      nUR                  U S   S9n[        U5        [        [        U4S jUS    5       5      5      $ )	z
Depends on :py:meth:`CELFilter.resources`

See :py:class:`c7n.resources.appelb.IsNotLoggingFilter` and
:py:class:`c7n.resources.appelb.IsLoggingFilter`.
r   r   c                 b    U R                  5       (       a  [        U 5      $ U S:X  a  gU S:X  a  gU $ )z:Lightweight JSON atomic value convertion to native Python.trueTfalseF)isdigitint)r   s    r   parse_attribute_value0get_load_balancer.<locals>.parse_attribute_value`  s/    99;;q6M&['\r    elbv2LoadBalancerArn)r  c              3   D   >#    U  H  nUS    T" US   5      4v   M     g7f)r=   r>   Nr9   )rC   rD   r  s     r   rF   $get_load_balancer.<locals>.<genexpr>o  s+      
- %[/W>?-s    
Attributes)r6   r   r  rV   r)   r   r  r  r  r  printr   r  )r   r  r  r  s      @r   get_load_balancerr  Y  s     sD#~)>  ZZ//188AF66 !23 7 5G	'N 
-
 	
 r    c                 B   [         R                  R                  R                  5       R	                  SSS9n[         R                  R                  U[         R                  R                  R                  5       5      nU Vs/ s H  o3S   PM	     nn[        U5      $ s  snf )z
Depends on the :py:meth:`c7n.resources.shield.IsShieldProtected.process` method.
This needs to be refactored and renamed to avoid collisions with other ``process()`` variants.

Applies to most resource types.
shieldr  r  ResourceArn)r)   r   r  r  r  get_type_protectionsr  r   )r   r  protectionspprotected_resourcess        r   shield_protectionr  v  s     ZZ//188{8[F**11&#**:L:L:V:V:XYK5@A[]+[A*++ Bs   Bc                 V    [         R                  R                  U 5      n[        U5      $ )z
Depends on :py:meth:`c7n.resources.account.ShieldEnabled.process` method.
This needs to be refactored and renamed to avoid collisions with other ``process()`` variants.

Applies to account resources only.
)r)   r   account_shield_subscriptionsr   )r   subscriptionss     r   shield_subscriptionr    s#     JJ;;HEM}%%r    c                     [         R                  R                  R                  S5      R	                  5       nU Vs0 s H  o"S   US   _M     nn[        U5      $ s  snf )z
Depends on :py:meth:`c7n.resources.cloudfront.IsWafEnabled.process` method.
This needs to be refactored and renamed to avoid collisions with other ``process()`` variants.
wafr   WebACLId)r)   r   r  r  r  r   )r   wafswwaf_name_id_maps       r   web_aclsr    sV    
 ::2259CCED9=>Ay!J-/O>'' ?s   ArQ   rY   r\   ra   r   r   rf   r   r   r   r   r   r   rE   r   r   r  r3  rN  rQ  r^  rG  rd  rh  rk  rn  r}  r  r6  r9  r<  r?  rB  rE  rI  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  )r  r  r  r  r  r  r  DECLARATIONS	FUNCTIONSc                   L    \ rS rSrSrS	S\S\\   S\R                  4S jjr
Srg)
C7N_Interpreted_Runneri  aZ  
Extends the Evaluation to introduce the C7N CELFilter instance into the exvaluation.

The variable is global to allow the functions to have the simple-looking argument
values that CEL expects. This allows a function in this module to reach outside CEL for
access to C7N's caches.

..  todo: Refactor to be a mixin to the Runner class hierarchy.
Ncontextr   r   c                     [        U R                  U R                  U5      U R                  S9n[	        US9   UR                  5       nS S S 5        U$ ! , (       d  f       W$ = f)N)ast
activation	functionsr   )r   r  new_activationr  r   evaluate)r   r  r   erJ   s        r   r  C7N_Interpreted_Runner.evaluate$  sU    **73nn

 v&JJLE ' '&s   A
A"r9   r   )r$   r2   r3   r4   r5   r   r   r   r   r>   r  r8   r9   r    r   r  r    s.     # (..  r    r  r   )~r5   r   rP   r   rl   r   loggingos.pathr   r   urllib.requestr   r   
contextlibr   	distutilsr   version_libtypesr   typingr   r   r   r	   r
   r   r   r   r   r   r   celpyr   r   celpy.adapterr   celpy.evaluationr   r   r   	getLoggerr$   loggerr   r)   r   r@   r>   rE   rO   rQ   rY   r\   ra   rd   rf   rh   IPv4AddressCIDR
CIDR_Classr   r   LooseVersionr   r   r   r   r   r   r   r   r   rA   r   r  r  r  r1  r3  r6  r9  r<  r?  rB  rE  rI  rN  rQ  r^  rG  rd  rh  rk  rn  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  FunctionTyper  r6   __annotations__ExtFunctionr  r  )fs   0r   <module>r     sT   BF   	     
    ,      - % ; ;			8	$ H <#!! #8+>+> #8>> #L=x"" =X-@-@ =XEVEV =;X&& ;x/@/@ ;XEVEV ;;H%% ;h.?.? ;HDUDU ;7h)) 7h.A.A 72H-- 2(2B2B 23)'' 3@ T;	 5 5564$hsI4I4I/I&JJK
&8.. HX=M=M4N 
00 
::^^:-8&& -HNN -1(%% 18>> 1)8&& )HNN ) <$$<.6.A.A<^^<: GK(			(&.x/B/B&C(^^(@77.6.A.A7^^7
""
191D1D

'/':':^^<#H$$ # #L1X-- 1(.. 1h..)1)9)9.^^.b8#3#3  . 48""4/0 ^^B$h.. $HNN $(h.. (HNN ( ("2"2    %x'7'7 %X^^ %x// X^^ )8+;+; ) )h.. HNN 8#3#3  (h&6&6 (HNN (" hnn  (..   (( hnn 2 HNN  @X(( @h.A.A @*C(** Cx~~ C":hnn :(.. :"
HNN 
 
<&>><&^^<&~
28++ 
2 
2
.x'' 
.X^^ 
./(( /hnn /
0)) 
0x~~ 
03H,, 3(.. 33H,, 3(.. 3X-- 8>>  9("2"2 9 9H,<,< (.. "h.>.> HNN $'8&& 'x/B/B 'x~~ '<
HNN 
x~~ 
# 
#88>> 8<x~~ <
#hnn 
#1 1
:X-- 
:(.. 
: 0 0 X^^ :
, 0 0 
,X^^ 
,&("2"2 &x~~ &(x'' (HNN (<'
H!!<'(''<' &&<' &&	<'
 (''<' x,,<' 8((<' x$$<' x$$<' h##<' &&<' (''<' &&<' X**<' 
8  <'  (''!<'" X""#<'$ 8((%<'& x,,'<'( h++)<'* h##+<', &&-<'. 
8  /<'0 X""1<'2 8((3<'4 &&5<'6 x$$7<'8 ..9<': H));<'< x,,=<'> 800?<'@  5 5A<'B --C<'D #H$9$9E<'F x,,G<'H H11I<'J %%K<'L &&M<'N (''O<'P X**Q<'R X**S<'T h++U<'V 800W<'X $X%:%:Y<'Z &x'<'<[<'\ &&]<'^ (''_<'` X**a<'b %h&;&;c<'d ..e<'f X22g<'h %11,,++!..!..#00%%u<'d3
?# <| sHNN*+</</</ 	</ 		</
 	</ 	</ 	</ 	</ 	</ 	</ 	</ 	</ 	</ 	</ 	</  	!</" 	#</$ 	%</& 	'</( 	)</* 	+</, 	-</. 	/</0 	1</2 	3</4 	5</6 	7</8 	9</: 	;</< 	=</> 	?</@ 	!A</B 	C</D 	%E</F 	G</H 	I</J 	K</L 	M</N 	O</P 	Q</R 	S</T 	U</V 	W</X 	&Y</Z 	([</\ 	]</^ 	_</` 	a</b 	'c</d 	e</f 	g</h 	i</j 	k</l 	m</n 	o</p 	q</r 	s</t 	u</>%</JJ[!$$ </>%	4[ ! >B. C>%s   )o