This file is indexed.

/usr/lib/python3/dist-packages/plainbox/impl/resource.py is in python3-plainbox 0.5.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# This file is part of Checkbox.
#
# Copyright 2012 Canonical Ltd.
# Written by:
#   Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.

#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.

"""
:mod:`plainbox.impl.resource` -- job resources
==============================================

.. warning::

    THIS MODULE DOES NOT HAVE STABLE PUBLIC API
"""

import ast
import logging

from plainbox.i18n import gettext as _

logger = logging.getLogger("plainbox.resource")


class ExpressionFailedError(Exception):
    """
    Exception raise when a resource expression failed to produce a true value.

    This class is meant to be consumed by the UI layers to provide meaningful
    error messages to the operator. The expression attribute can be used to
    obtain the text of the expression that failed as well as the resource id
    that is used by that expression. The resource id can be used to lookup
    the (resource) job that produces such values.
    """

    def __init__(self, expression):
        self.expression = expression

    def __str__(self):
        return _("expression {!r} evaluated to a non-true result").format(
            self.expression.text)

    def __repr__(self):
        return "<{} expression:{!r}>".format(
            self.__class__.__name__, self.expression)


class ExpressionCannotEvaluateError(ExpressionFailedError):
    """
    Exception raised when a resource could not be evaluated because it requires
    an unavailable resource.

    Unlike the base class, this exception is raised before even running the
    expression. As in the base class the exception object is meant to have
    enough data to provide rich and meaningful error messages to the operator.
    """

    def __str__(self):
        return _("expression {!r} needs unavailable resource {!r}").format(
            self.expression.text, self.expression.resource_id)


class Resource:
    """
    A simple container for key-value data

    Resource objects are used when evaluating expressions as containers for
    data read from resource scripts. Each RFC822 record produced by a resource
    script is converted to a new Resource object
    """

    __slots__ = ('_data')

    def __init__(self, data=None):
        if data is None:
            data = {}
        object.__setattr__(self, '_data', data)

    def __setattr__(self, attr, value):
        if attr.startswith("_"):
            raise AttributeError(attr)
        data = object.__getattribute__(self, '_data')
        data[attr] = value

    def __delattr__(self, attr):
        data = object.__getattribute__(self, '_data')
        if attr in data:
            del data[attr]
        else:
            raise AttributeError(attr)

    def __getattribute__(self, attr):
        if attr.startswith("_"):
            raise AttributeError(attr)
        data = object.__getattribute__(self, '_data')
        if attr in data:
            return data[attr]
        else:
            raise AttributeError(attr)

    def __repr__(self):
        data = object.__getattribute__(self, '_data')
        return "Resource({!r})".format(data)

    def __eq__(self, other):
        if not isinstance(other, Resource):
            return False
        return (
            object.__getattribute__(self, '_data')
            == object.__getattribute__(other, '_data'))

    def __ne__(self, other):
        if not isinstance(other, Resource):
            return True
        return (
            object.__getattribute__(self, '_data')
            != object.__getattribute__(other, '_data'))


class ResourceProgram:
    """
    Class for storing and executing resource programs.

    This is used by job requirement expressions
    """

    def __init__(self, program_text, implicit_namespace=None):
        """
        Analyze the requirement program and prepare it for execution

        The requirement program must be a string (of possibly many lines), each
        of which must be a valid ResourceExpression. Empty lines are ignored.

        May raise ResourceProgramError (including CodeNotAllowed) or a
        SyntaxError
        """
        self._expression_list = []
        for line in program_text.splitlines():
            if line.strip() != "":
                self._expression_list.append(
                    ResourceExpression(line, implicit_namespace))

    @property
    def expression_list(self):
        """
        A list of ResourceExpression instances
        """
        return self._expression_list

    @property
    def required_resources(self):
        """
        A set() of resource ids that are needed to evaluate this program
        """
        return set((expression.resource_id
                    for expression in self._expression_list))

    def evaluate_or_raise(self, resource_map):
        """
        Evaluate the program with the given map of resources.

        Raises a ExpressionFailedError exception if the any of the expressions
        that make up this program cannot be executed or executes but produces a
        non-true value.

        Returns True

        Resources must be a dictionary of mapping resource id to a list of
        Resource objects.
        """
        # First check if we have all required resources
        for expression in self._expression_list:
            if expression.resource_id not in resource_map:
                raise ExpressionCannotEvaluateError(expression)
        # Then evaluate all expressions
        for expression in self._expression_list:
            result = expression.evaluate(
                resource_map[expression.resource_id])
            if not result:
                raise ExpressionFailedError(expression)
        return True


class ResourceProgramError(Exception):
    """
    Base class for errors in requirement programs.

    This class of errors are based on static analysis, not runtime execution.
    Typically they encode unsupported or disallowed python code being used by
    an expression somewhere.
    """


class CodeNotAllowed(ResourceProgramError):
    """
    Exception raised when unsupported computing is detected inside requirement
    expression.
    """

    def __init__(self, node):
        self.node = node

    def __repr__(self):
        return "CodeNotAllowed({!r})".format(self.node)

    def __str__(self):
        return _("this kind of python code is not allowed: {}").format(
            ast.dump(self.node))


class ResourceNodeVisitor(ast.NodeVisitor):
    """
    A NodeVisitor subclass used to analyze requirement expressions.

    .. warning::

        Implementation of this class requires understanding of
        some of the lower levels of python. The general idea is
        to use the ast (abstract syntax tree) module to allow
        the ResourceExpression class to execute safely (by
        not permitting various unsafe operations) and quickly
        (by knowing which resources are required so no O(n)
        operations over all resources are ever needed.

    Resource expressions are written one per line, each line is like a
    separate min-program. This visitor will be applied to the root (module)
    node resulting from parsing each of those lines.

    Each actual expression can only use a small subset of python syntax, most
    stuff is actually disallowed. Only basic expressions are permitted.
    Function calls are also disallowed, with the notable exception of 'bool',
    'int', 'float' and 'len'.

    One very important aspect of each expression is the id of the resource it
    is computing against. This is visible as the 'object' the expressions are
    operating on, such as:

        package.name == 'fwts'

    As a rule of a thumb exactly one such id is allowed per expression. This
    allows the code that evaluates this to know which resource to use. As
    resources are actually lists of records (where record values are available
    as object attribute) only one object/record is exposed to each expression.
    Using more than one object (by intent or simple typo) would lead to
    expression that will never match. This visitor class facilitates detecting
    that by computing the ids_seen set.

    One notable fact is that storing is not allowed so it is (presumably) safe
    to evaluate the code in the context of the current python interpreter.

    How this works:

    Using the ast.NodeVisitor we can visit any node type by defining the
    visit_<class name> method. We care about Name and Call nodes and they have
    custom validation implemented. For all other nodes the generic_visit()
    method is called instead.

    On each visit to ast.Name node we record the referenced 'id' (the id of
    the object being referenced, in simple terms)

    On each visit to ast.Call node we check if the called function is in the
    allowed list of ids. This also takes care of stuff like foo()() which
    would call the return value of foo.

    On each visit to any other ast.Node we check if the class is in the
    white-list.

    All violation cause a CodeNotAllowed exception to be raised with the
    node that was rejected as argument.
    """

    # Allowed function calls
    _allowed_call_func_list = (
        'len',
        'bool',
        'int',
        'float',
    )

    # A tuple of allowed types of ast.Node that are white-listed by
    # _check_node()
    _allowed_node_cls_list = (
        # Allowed statements (ast.stmt sub-classes)
        ast.Expr,  # expressions

        # Allowed 'mod's (ast.mod sub-classes)
        ast.Module,

        # Allowed expressions (ast.expr sub-classes)
        ast.Attribute,  # attribute access
        ast.BinOp,  # binary operators
        ast.BoolOp,  # boolean operations (and/or)
        ast.Compare,  # comparisons
        ast.List,  # lists
        ast.Name,  # name access (top-level name references)
        ast.Num,  # numbers
        ast.Str,  # strings
        ast.Tuple,  # tuples
        ast.UnaryOp,  # unary operators

        # Allow all comparison operators
        ast.cmpop,  # this allows ast.Eq, ast.Gt and so on

        # Allow all boolean operators
        ast.boolop,  # this allows ast.And, ast.Or

        # Allowed expression context (ast.expr_context)
        ast.Load,  # allow all loads
    )

    def __init__(self):
        """
        Initialize a ResourceNodeVisitor with empty set of ids_seen
        """
        self._ids_seen = set()

    @property
    def ids_seen(self):
        """
        set() of ast.Name().id values seen
        """
        return self._ids_seen

    def visit_Name(self, node):
        """
        Internal method of NodeVisitor.

        This method is called whenever generic_visit() looks at an instance of
        ast.Name(). It records the node identifier and calls _check_node()
        """
        self._check_node(node)
        self._ids_seen.add(node.id)

    def visit_Call(self, node):
        """
        Internal method of NodeVisitor.

        This method is called whenever generic_visit() looks at an instance of
        ast.Call(). Since white-listing Call in general would be unsafe only a
        small subset of calls are allowed.
        """
        # XXX: Do not call _check_node() here as Call is not on the whitelist
        if node.func.id not in self._allowed_call_func_list:
            raise CodeNotAllowed(node)

    def generic_visit(self, node):
        """
        Internal method of NodeVisitor.

        Called for all ast.Node() subclasses that don't have a dedicated
        visit_xxx() method here. Only needed to all the _check_node() method.
        """
        self._check_node(node)
        return super(ResourceNodeVisitor, self).generic_visit(node)

    def _check_node(self, node):
        """
        Internal method of ResourceNodeVisitor.

        This method raises CodeNotAllowed() for any node that is outside
        of the set of supported node classes.
        """
        if not isinstance(node, self._allowed_node_cls_list):
            raise CodeNotAllowed(node)


class RequirementNodeVisitor(ast.NodeVisitor):
    """
    A NodeVisitor subclass used to analyze package requirement expressions.
    """

    def __init__(self):
        """
        Initialize a ResourceNodeVisitor with empty list of packages_seen
        """
        self._packages_seen = []

    @property
    def packages_seen(self):
        """
        set() of ast.Str().id values seen joined with the "|" operator for
        use in debian/control files
        """
        return self._packages_seen

    def visit_Str(self, node):
        """
        Internal method of NodeVisitor.

        This method is called whenever generic_visit() looks at an instance of
        ast.Str().
        """
        self._packages_seen.append(node.s)


class NoResourcesReferenced(ResourceProgramError):
    """
    Exception raised when an expression does not reference any resources.
    """

    def __str__(self):
        return _("expression did not reference any resources")


class MultipleResourcesReferenced(ResourceProgramError):
    """
    Exception raised when an expression references multiple resources.
    """

    def __str__(self):
        return _("expression referenced multiple resources")


class ResourceExpression:
    """
    Class representing a single line of an requirement program.

    Each valid expression references exactly one resource. In practical terms
    each resource expression is a valid python expression that has no side
    effects (calls almost no methods, does not assign anything) that can be
    evaluated against a single variable which references a Resource object.
    """

    def __init__(self, text, implicit_namespace=None):
        """
        Analyze the text and prepare it for execution

        May raise ResourceProgramError
        """
        self._implicit_namespace = implicit_namespace
        self._resource_id = self._analyze(text)
        self._text = text
        self._lambda = eval("lambda {}: {}".format(
            self._resource_id, self._text))

    def __str__(self):
        return self._text

    def __repr__(self):
        return "<ResourceExpression text:{!r}>".format(self._text)

    def __eq__(self, other):
        if isinstance(other, ResourceExpression):
            return self._text == other._text
        return NotImplemented

    def __ne__(self, other):
        if isinstance(other, ResourceExpression):
            return self._text != other._text
        return NotImplemented

    @property
    def text(self):
        """
        The text of the original expression
        """
        return self._text

    @property
    def resource_id(self):
        """
        The id of the resource this expression depends on
        """
        if "::" not in self._resource_id and self._implicit_namespace:
            return "{}::{}".format(self._implicit_namespace, self._resource_id)
        else:
            return self._resource_id

    @property
    def implicit_namespace(self):
        """
        implicit namespace for partial identifiers, may be None
        """
        return self._implicit_namespace

    def evaluate(self, resource_list):
        """
        Evaluate the expression against a list of resources

        Each subsequent resource from the list will be bound to the resource
        id in the expression. The return value is True if any of the attempts
        return a true value, otherwise the result is False.
        """
        # Try each resource in sequence.
        for resource in resource_list:
            if not isinstance(resource, Resource):
                raise TypeError("Each resource must be a Resource instance")
            # Attempt to evaluate the code with the current resource
            try:
                result = self._lambda(resource)
            except Exception as exc:
                # Treat any exception as a non-fatal error
                #
                # XXX: it would be interesting to see if we have exceptions and
                # why they happen.  We could do deeper validation this way.
                logger.debug(
                    _("Exception in requirement expression %r (with %s=%r):"
                      " %r"), self._text, self._resource_id, resource, exc)
                continue
            # Treat any true result as a success
            if result:
                return True
        # If we get here then the expression did not match. It's pointless (as
        # python returns None implicitly) but it's more explicit on the
        # documentation side.
        return False

    @classmethod
    def _analyze(cls, text):
        """
        Analyze the expression and return the id of the required resource

        May raise SyntaxError or a ResourceProgramError subclass
        """
        # Use the ast module to build an abstract syntax tree of the expression
        node = ast.parse(text)
        # Use ResourceNodeVisitor to see what kind of ast.Name objects are
        # referenced by the expression. This may also raise CodeNotAllowed
        # which should be captured by the higher layers.
        visitor = ResourceNodeVisitor()
        visitor.visit(node)
        # Bail if the expression is not using exactly one resource id
        if len(visitor.ids_seen) == 0:
            raise NoResourcesReferenced()
        elif len(visitor.ids_seen) == 1:
            return list(visitor.ids_seen)[0]
        else:
            raise MultipleResourcesReferenced()