Ejemplo n.º 1
0
    def to_python(cls, data, slim_frames=True, raw=False):
        if not data.get('frames'):
            raise InterfaceValidationError("No 'frames' present")

        if not isinstance(data['frames'], list):
            raise InterfaceValidationError("Invalid value for 'frames'")

        frame_list = [
            # XXX(dcramer): handle PHP sending an empty array for a frame
            Frame.to_python(f or {}, raw=raw) for f in data['frames']
        ]

        kwargs = {
            'frames': frame_list,
        }

        kwargs['registers'] = None
        if data.get('registers') and isinstance(data['registers'], dict):
            kwargs['registers'] = data.get('registers')

        if data.get('frames_omitted'):
            if len(data['frames_omitted']) != 2:
                raise InterfaceValidationError(
                    "Invalid value for 'frames_omitted'")
            kwargs['frames_omitted'] = data['frames_omitted']
        else:
            kwargs['frames_omitted'] = None

        instance = cls(**kwargs)
        if slim_frames:
            slim_frame_data(instance)
        return instance
Ejemplo n.º 2
0
    def to_python(cls, data):
        kwargs = {k: trim(data.get(k, None), 1024) for k in REPORT_KEYS}

        if kwargs['effective_directive'] not in DIRECTIVES:
            raise InterfaceValidationError(
                "Invalid value for 'effective-directive'")

        # Some reports from Chrome report blocked-uri as just 'about'.
        # In this case, this is not actionable and is just noisy.
        # Observed in Chrome 45 and 46.
        if kwargs['blocked_uri'] == 'about':
            raise InterfaceValidationError("Invalid value for 'blocked-uri'")

        # Here, we want to block reports that are coming from browser extensions
        # and other sources that are meaningless
        if kwargs['source_file'] is not None:
            if kwargs['source_file'].startswith(DISALLOWED_SOURCES):
                raise InterfaceValidationError(
                    "Invalid value for 'source-file'")

        # Anything resulting from an "inline" whatever violation is either sent
        # as 'self', or left off. In the case if it missing, we want to noramalize.
        if not kwargs['blocked_uri']:
            kwargs['blocked_uri'] = 'self'

        return cls(**kwargs)
Ejemplo n.º 3
0
    def to_python(cls, data):
        if data and 'values' not in data and 'exc_omitted' not in data:
            data = {"values": [data]}

        values = get_path(data, 'values', default=[])
        if not isinstance(values, list):
            raise InterfaceValidationError("Invalid value for 'values'")

        kwargs = {
            'values': [
                v and SingleException.to_python(v, slim_frames=False)
                for v in values
            ],
        }

        if data.get('exc_omitted'):
            if len(data['exc_omitted']) != 2:
                raise InterfaceValidationError(
                    "Invalid value for 'exc_omitted'")
            kwargs['exc_omitted'] = data['exc_omitted']
        else:
            kwargs['exc_omitted'] = None

        instance = cls(**kwargs)
        # we want to wait to slim things til we've reconciled in_app
        slim_exception_data(instance)
        return instance
Ejemplo n.º 4
0
    def to_python(cls, data):
        result = {}
        for path, config in six.iteritems(data):
            if len(path) > 200:
                raise InterfaceValidationError(
                    "Invalid repository `path` (> 200 characters)")

            name = config.get('name')
            if not name:
                raise InterfaceValidationError(
                    "A repository must provide a value `name`")
            # 200 chars is enforced by db, and while we dont validate if the
            # repo actually exists, we know it could *never* exist if its beyond
            # the schema constraints.
            if len(name) > 200:
                raise InterfaceValidationError("Invalid repository `name`")

            prefix = config.get('prefix')
            if prefix and len(prefix) > 200:
                raise InterfaceValidationError(
                    "Invalid repository `prefix` (> 200 characters)")

            revision = config.get('revision')
            if revision and len(revision) > 40:
                raise InterfaceValidationError(
                    "Invalid repository `revision` (> 40 characters)")

            result[path] = {
                'name': name,
            }
            if prefix:
                result[path]['prefix'] = prefix
            if revision:
                result[path]['revision'] = revision
        return cls(**result)
Ejemplo n.º 5
0
    def to_python(cls, data, has_system_frames=None):
        if not data.get('frames'):
            raise InterfaceValidationError("No 'frames' present")

        slim_frame_data(data)

        if has_system_frames is None:
            has_system_frames = cls.data_has_system_frames(data)

        frame_list = [Frame.to_python(f) for f in data['frames']]

        for frame in frame_list:
            if not has_system_frames:
                frame.in_app = False
            elif frame.in_app is None:
                frame.in_app = False

        kwargs = {
            'frames': frame_list,
        }

        if data.get('frames_omitted'):
            if len(data['frames_omitted']) != 2:
                raise InterfaceValidationError(
                    "Invalid value for 'frames_omitted'")
            kwargs['frames_omitted'] = data['frames_omitted']
        else:
            kwargs['frames_omitted'] = None

        kwargs['has_system_frames'] = has_system_frames

        return cls(**kwargs)
Ejemplo n.º 6
0
    def to_python(cls, data, rust_renormalized=RUST_RENORMALIZED_DEFAULT):
        if rust_renormalized:
            for key in (
                    'name',
                    'version',
                    'integrations',
                    'packages',
            ):
                data.setdefault(key, None)

            return cls(**data)

        name = data.get('name')
        version = data.get('version')

        integrations = data.get('integrations')
        if integrations and not isinstance(integrations, list):
            raise InterfaceValidationError("'integrations' must be a list")

        packages = data.get('packages')
        if packages and not isinstance(packages, list):
            raise InterfaceValidationError("'packages' must be a list")

        kwargs = {
            'name': trim(name, 128),
            'version': trim(version, 128),
            'integrations': integrations,
            'packages': packages,
        }

        return cls(**kwargs)
Ejemplo n.º 7
0
    def to_python(cls, data):
        if 'values' not in data:
            data = {'values': [data]}

        if not data['values']:
            raise InterfaceValidationError("No 'values' present")

        has_system_frames = cls.data_has_system_frames(data)

        kwargs = {
            'values': [
                SingleException.to_python(
                    v,
                    has_system_frames=has_system_frames,
                    slim_frames=False,
                ) for v in data['values']
            ],
        }

        if data.get('exc_omitted'):
            if len(data['exc_omitted']) != 2:
                raise InterfaceValidationError(
                    "Invalid value for 'exc_omitted'")
            kwargs['exc_omitted'] = data['exc_omitted']
        else:
            kwargs['exc_omitted'] = None

        instance = cls(**kwargs)
        # we want to wait to slim things til we've reconciled in_app
        slim_exception_data(instance)
        return instance
Ejemplo n.º 8
0
    def to_python(cls, data):
        if 'values' not in data:
            data = {'values': [data]}

        if not data['values']:
            raise InterfaceValidationError("No 'values' present")

        trim_exceptions(data)

        has_system_frames = cls.data_has_system_frames(data)

        kwargs = {
            'values': [
                SingleException.to_python(
                    v,
                    has_system_frames=has_system_frames,
                )
                for v in data['values']
            ],
        }

        if data.get('exc_omitted'):
            if len(data['exc_omitted']) != 2:
                raise InterfaceValidationError("Invalid value for 'exc_omitted'")
            kwargs['exc_omitted'] = data['exc_omitted']
        else:
            kwargs['exc_omitted'] = None

        return cls(**kwargs)
Ejemplo n.º 9
0
    def to_python(cls, data):
        data = data.copy()

        extra_data = data.pop('data', data)
        if not isinstance(extra_data, dict):
            extra_data = {}

        try:
            name = trim(data.pop('name'), 64)
        except KeyError:
            raise InterfaceValidationError("Missing or invalid value for 'name'")

        try:
            version = trim(data.pop('version'), 64)
        except KeyError:
            raise InterfaceValidationError("Missing or invalid value for 'version'")

        build = trim(data.pop('build', None), 64)

        kwargs = {
            'name': name,
            'version': version,
            'build': build,
            'data': trim_dict(extra_data),
        }
        return cls(**kwargs)
Ejemplo n.º 10
0
    def to_python(cls, data):
        if not data.get('url'):
            raise InterfaceValidationError("No value for 'url'")

        kwargs = {}

        if data.get('method'):
            method = data['method'].upper()
            if method not in HTTP_METHODS:
                raise InterfaceValidationError("Invalid value for 'method'")
            kwargs['method'] = method
        else:
            kwargs['method'] = None

        scheme, netloc, path, query_bit, fragment_bit = urlsplit(data['url'])

        query_string = data.get('query_string') or query_bit
        if query_string:
            # if querystring was a dict, convert it to a string
            if isinstance(query_string, dict):
                query_string = urlencode([(to_bytes(k), to_bytes(v))
                                          for k, v in query_string.items()])
            else:
                query_string = query_string
                if query_string[0] == '?':
                    # remove '?' prefix
                    query_string = query_string[1:]
            kwargs['query_string'] = trim(query_string, 4096)
        else:
            kwargs['query_string'] = ''

        fragment = data.get('fragment') or fragment_bit

        cookies = data.get('cookies')
        # if cookies were [also] included in headers we
        # strip them out
        headers = data.get('headers')
        if headers:
            headers, cookie_header = format_headers(headers)
            if not cookies and cookie_header:
                cookies = cookie_header
        else:
            headers = ()

        body = data.get('data')
        if isinstance(body, dict):
            body = json.dumps(body)

        if body:
            body = trim(body, settings.SENTRY_MAX_HTTP_BODY_SIZE)

        kwargs['cookies'] = trim_pairs(format_cookies(cookies))
        kwargs['env'] = trim_dict(data.get('env') or {})
        kwargs['headers'] = trim_pairs(headers)
        kwargs['data'] = fix_broken_encoding(body)
        kwargs['url'] = urlunsplit((scheme, netloc, path, '', ''))
        kwargs['fragment'] = trim(fragment, 1024)

        return cls(**kwargs)
Ejemplo n.º 11
0
    def to_python(cls, data, slim_frames=True, rust_renormalized=RUST_RENORMALIZED_DEFAULT):
        if not rust_renormalized:
            is_valid, errors = validate_and_default_interface(data, cls.path)
            if not is_valid:
                raise InterfaceValidationError("Invalid exception")

            if not (data.get('type') or data.get('value')):
                raise InterfaceValidationError("No 'type' or 'value' present")

        if get_path(data, 'stacktrace', 'frames', filter=True):
            stacktrace = Stacktrace.to_python(
                data['stacktrace'],
                slim_frames=slim_frames,
                rust_renormalized=rust_renormalized
            )
        else:
            stacktrace = None

        if get_path(data, 'raw_stacktrace', 'frames', filter=True):
            raw_stacktrace = Stacktrace.to_python(
                data['raw_stacktrace'], slim_frames=slim_frames, raw=True,
                rust_renormalized=rust_renormalized
            )
        else:
            raw_stacktrace = None

        type = data.get('type')
        value = data.get('value')

        if not rust_renormalized:
            if isinstance(value, six.string_types):
                if type is None:
                    m = _type_value_re.match(value)
                    if m:
                        type = m.group(1)
                        value = m.group(2).strip()
            elif value is not None:
                value = json.dumps(value)

            value = trim(value, 4096)

        if data.get('mechanism'):
            mechanism = Mechanism.to_python(data['mechanism'],
                                            rust_renormalized=rust_renormalized)
        else:
            mechanism = None

        kwargs = {
            'type': trim(type, 128),
            'value': value,
            'module': trim(data.get('module'), 128),
            'mechanism': mechanism,
            'stacktrace': stacktrace,
            'thread_id': trim(data.get('thread_id'), 40),
            'raw_stacktrace': raw_stacktrace,
        }

        return cls(**kwargs)
Ejemplo n.º 12
0
    def to_python(cls, data):
        if not isinstance(data, dict):
            raise InterfaceValidationError("Invalid interface data")
        if not data.get('query'):
            raise InterfaceValidationError("No 'query' value")

        kwargs = {
            'query': trim(data['query'], 1024),
            'engine': trim(data.get('engine'), 128),
        }
        return cls(**kwargs)
Ejemplo n.º 13
0
 def normalize_image(image):
     ty = image.get('type')
     if not ty:
         raise InterfaceValidationError('Image type not provided')
     func = image_types.get(ty)
     if func is None:
         raise InterfaceValidationError('Unknown image type %r' % image)
     rv = func(image)
     assert 'uuid' in rv or 'id' in rv, 'debug image normalizer did not produce a UUID'
     rv['type'] = ty
     return rv
Ejemplo n.º 14
0
    def to_python(cls, data):
        data = upgrade_legacy_mechanism(data)
        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid mechanism")

        if not data.get('type'):
            raise InterfaceValidationError("No 'type' present")

        mechanism_meta = data.get('meta') or {}
        mach_exception = mechanism_meta.get('mach_exception')
        if mach_exception is not None:
            mach_exception = prune_empty_keys({
                'exception':
                mach_exception['exception'],
                'code':
                mach_exception['code'],
                'subcode':
                mach_exception['subcode'],
                'name':
                mach_exception.get('name'),
            })

        signal = mechanism_meta.get('signal')
        if signal is not None:
            signal = prune_empty_keys({
                'number': signal['number'],
                'code': signal.get('code'),
                'name': signal.get('name'),
                'code_name': signal.get('code_name'),
            })

        errno = mechanism_meta.get('errno')
        if errno is not None:
            errno = prune_empty_keys({
                'number': errno['number'],
                'name': errno.get('name'),
            })

        kwargs = {
            'type': trim(data['type'], 128),
            'synthetic': data.get('synthetic'),
            'description': trim(data.get('description'), 1024),
            'help_link': trim(data.get('help_link'), 1024),
            'handled': data.get('handled'),
            'data': trim(data.get('data'), 4096),
            'meta': {
                'errno': errno,
                'mach_exception': mach_exception,
                'signal': signal,
            },
        }

        return cls(**kwargs)
Ejemplo n.º 15
0
    def to_python(cls, data):
        if not data.get('crash'):
            raise InterfaceValidationError("No 'crash' present")
        if not data.get('binary_images'):
            raise InterfaceValidationError("No 'binary_images' present")

        kwargs = {
            'crash': data['crash'],
            'binary_images': data['binary_images'],
        }

        return cls(**kwargs)
Ejemplo n.º 16
0
    def to_python(cls, data):
        if 'images' not in data:
            raise InterfaceValidationError('Missing key "images"')
        is_debug_build = data.get('is_debug_build')
        if is_debug_build is not None and not isinstance(is_debug_build, bool):
            raise InterfaceValidationError('Invalid value for "is_debug_build"')

        return cls(
            images=[cls.normalize_image(x) for x in data['images']],
            sdk_info=cls.normalize_sdk_info(data.get('sdk_info')),
            is_debug_build=is_debug_build,
        )
Ejemplo n.º 17
0
    def to_python(cls, data, has_system_frames=None, slim_frames=True):
        if not (data.get('type') or data.get('value')):
            raise InterfaceValidationError("No 'type' or 'value' present")

        if data.get('stacktrace') and data['stacktrace'].get('frames'):
            stacktrace = Stacktrace.to_python(
                data['stacktrace'],
                has_system_frames=has_system_frames,
                slim_frames=slim_frames,
            )
        else:
            stacktrace = None

        if data.get('raw_stacktrace') and data['raw_stacktrace'].get('frames'):
            raw_stacktrace = Stacktrace.to_python(
                data['raw_stacktrace'],
                has_system_frames=has_system_frames,
                slim_frames=slim_frames,
                raw=True
            )
        else:
            raw_stacktrace = None

        type = data.get('type')
        value = data.get('value')
        if not type and ':' in value.split(' ', 1)[0]:
            type, value = value.split(':', 1)
            # in case of TypeError: foo (no space)
            value = value.strip()

        if value is not None and not isinstance(value, six.string_types):
            value = json.dumps(value)
        value = trim(value, 4096)

        mechanism = data.get('mechanism')
        if mechanism is not None:
            if not isinstance(mechanism, dict):
                raise InterfaceValidationError('Bad value for mechanism')
            mechanism = trim(data.get('mechanism'), 4096)
            mechanism.setdefault('type', 'generic')

        kwargs = {
            'type': trim(type, 128),
            'value': value,
            'module': trim(data.get('module'), 128),
            'mechanism': mechanism,
            'stacktrace': stacktrace,
            'thread_id': trim(data.get('thread_id'), 40),
            'raw_stacktrace': raw_stacktrace,
        }

        return cls(**kwargs)
    def to_python(cls, data, slim_frames=True):
        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid exception")

        if not (data.get('type') or data.get('value')):
            raise InterfaceValidationError("No 'type' or 'value' present")

        if data.get('stacktrace') and data['stacktrace'].get('frames'):
            stacktrace = Stacktrace.to_python(
                data['stacktrace'],
                slim_frames=slim_frames,
            )
        else:
            stacktrace = None

        if data.get('raw_stacktrace') and data['raw_stacktrace'].get('frames'):
            raw_stacktrace = Stacktrace.to_python(data['raw_stacktrace'],
                                                  slim_frames=slim_frames,
                                                  raw=True)
        else:
            raw_stacktrace = None

        type = data.get('type')
        value = data.get('value')
        if isinstance(value, six.string_types):
            if type is None:
                m = _type_value_re.match(value)
                if m:
                    type = m.group(1)
                    value = m.group(2).strip()
        elif value is not None:
            value = json.dumps(value)

        value = trim(value, 4096)

        mechanism = data.get('mechanism')
        if mechanism is not None:
            mechanism = trim(data.get('mechanism'), 4096)
            mechanism.setdefault('type', 'generic')

        kwargs = {
            'type': trim(type, 128),
            'value': value,
            'module': trim(data.get('module'), 128),
            'mechanism': mechanism,
            'stacktrace': stacktrace,
            'thread_id': trim(data.get('thread_id'), 40),
            'raw_stacktrace': raw_stacktrace,
        }

        return cls(**kwargs)
Ejemplo n.º 19
0
    def to_python(cls, data):
        data = data.copy()

        ident = data.pop('id', None)
        if ident is not None:
            ident = trim(six.text_type(ident), 128)

        try:
            email = trim(validate_email(data.pop('email', None), False),
                         MAX_EMAIL_FIELD_LENGTH)
        except ValueError:
            raise InterfaceValidationError("Invalid value for 'email'")

        username = data.pop('username', None)
        if username is not None:
            username = trim(six.text_type(username), 128)

        name = data.pop('name', None)
        if name is not None:
            name = trim(six.text_type(name), 128)

        try:
            ip_address = validate_ip(data.pop('ip_address', None), False)
        except ValueError:
            raise InterfaceValidationError("Invalid value for 'ip_address'")

        geo = data.pop('geo', None)
        if not geo and ip_address:
            geo = Geo.from_ip_address(ip_address)
        elif geo:
            geo = Geo.to_python(geo)

        extra_data = data.pop('data', None)
        if not isinstance(extra_data, dict):
            extra_data = {}
        extra_data.update(data)

        # TODO(dcramer): patch in fix to deal w/ old data but not allow new
        # if not (ident or email or username or ip_address):
        #     raise ValueError('No identifying value')

        kwargs = {
            'id': ident,
            'email': email,
            'username': username,
            'ip_address': ip_address,
            'name': name,
            'geo': geo,
            'data': trim_dict(extra_data)
        }

        return cls(**kwargs)
Ejemplo n.º 20
0
    def to_python(cls, data):
        name = data.get('name')
        if not name:
            raise InterfaceValidationError("No 'name' value")

        version = data.get('version')
        if not version:
            raise InterfaceValidationError("No 'version' value")

        kwargs = {
            'name': trim(name, 128),
            'version': trim(version, 128),
        }
        return cls(**kwargs)
Ejemplo n.º 21
0
    def to_python(cls, data):
        # TODO(markus): semaphore does not validate security interfaces yet
        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid interface data")

        return cls(**data)
Ejemplo n.º 22
0
    def normalize_crumb(cls, crumb):
        ty = crumb.get('type') or 'default'
        ts = parse_new_timestamp(crumb.get('timestamp'))
        if ts is None:
            raise InterfaceValidationError('Unable to determine timestamp '
                                           'for crumb')

        rv = {
            'type': ty,
            'timestamp': to_timestamp(ts),
        }

        level = crumb.get('level')
        if level not in (None, 'info'):
            rv['level'] = level

        msg = crumb.get('message')
        if msg is not None:
            rv['message'] = trim(unicode(msg), 4096)

        category = crumb.get('category')
        if category is not None:
            rv['category'] = trim(unicode(category), 256)

        event_id = crumb.get('event_id')
        if event_id is not None:
            rv['event_id'] = event_id

        if 'data' in crumb:
            rv['data'] = trim(crumb['data'], 4096)

        return rv
Ejemplo n.º 23
0
def process_apple_image(image):
    try:
        apple_image = {
            'uuid': six.text_type(uuid.UUID(image['uuid'])),
            'cpu_type': image.get('cpu_type'),
            'cpu_subtype': image.get('cpu_subtype'),
            'image_addr': _addr(image.get('image_addr')),
            'image_size': image['image_size'],
            'image_vmaddr': _addr(image.get('image_vmaddr') or 0),
            'name': image.get('name'),
        }

        if image.get('arch') is not None:
            apple_image['arch'] = image.get('arch')
        if image.get('major_version') is not None:
            apple_image['major_version'] = image['major_version']
        if image.get('minor_version') is not None:
            apple_image['minor_version'] = image['minor_version']
        if image.get('revision_version') is not None:
            apple_image['revision_version'] = image['revision_version']

        return apple_image
    except KeyError as e:
        raise InterfaceValidationError('Missing value for apple image: %s' %
                                       e.args[0])
Ejemplo n.º 24
0
    def to_python(cls, data, slim_frames=True, raw=False):
        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid stack frame data.")

        frame_list = [
            # XXX(dcramer): handle PHP sending an empty array for a frame
            Frame.to_python(f or {}, raw=raw) for f in data['frames']
        ]

        kwargs = {
            'frames': frame_list,
        }

        kwargs['registers'] = None
        if data.get('registers') and isinstance(data['registers'], dict):
            kwargs['registers'] = data.get('registers')

        if data.get('frames_omitted'):
            kwargs['frames_omitted'] = data['frames_omitted']
        else:
            kwargs['frames_omitted'] = None

        instance = cls(**kwargs)
        if slim_frames:
            slim_frame_data(instance)
        return instance
Ejemplo n.º 25
0
    def to_python(cls, data):
        formatted = stringify(data.get('formatted'))
        message = stringify(data.get('message'))
        if formatted is None and message is None:
            raise InterfaceValidationError("No message present")

        params = data.get('params')
        if isinstance(params, (list, tuple)):
            params = tuple(p for p in params)
        elif isinstance(params, dict):
            params = {k: v for k, v in six.iteritems(params)}
        else:
            params = ()

        if formatted is None and params:
            try:
                if '%' in message:
                    formatted = message % params
                elif '{}' in message and isinstance(params, tuple):
                    formatted = message.format(*params)
                # NB: Named newstyle arguments were never supported
            except Exception:
                pass

        if formatted is None or message == formatted:
            formatted = message
            message = None

        return cls(
            formatted=trim(formatted, settings.SENTRY_MAX_MESSAGE_LENGTH),
            message=trim(message, settings.SENTRY_MAX_MESSAGE_LENGTH),
            params=trim(params, 1024),
        )
Ejemplo n.º 26
0
    def to_python(cls, data, rust_renormalized=RUST_RENORMALIZED_DEFAULT):
        if rust_renormalized:
            for key in (
                'abs_path',
                'filename',
                'context_line',
                'lineno',
                'pre_context',
                'post_context',
            ):
                data.setdefault(key, None)
            return cls(**data)

        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid template")

        kwargs = {
            'abs_path': trim(data.get('abs_path', None), 256),
            'filename': trim(data.get('filename', None), 256),
            'context_line': trim(data.get('context_line', None), 256),
            'lineno': int(data['lineno']) if data.get('lineno', None) is not None else None,
            # TODO(dcramer): trim pre/post_context
            'pre_context': data.get('pre_context'),
            'post_context': data.get('post_context'),
        }
        return cls(**kwargs)
Ejemplo n.º 27
0
def process_native_image(image):
    # NOTE that this is dead code as soon as Rust renormalization is fully
    # enabled. After that, this code should be deleted. There is a difference
    # TODO(untitaker): Remove with other normalization code.
    try:
        native_image = {
            'code_file':
            image.get('code_file') or image.get('name'),
            'debug_id':
            normalize_debug_id(
                image.get('debug_id') or image.get('id') or image.get('uuid')),
            'image_addr':
            _addr(image.get('image_addr')),
            'image_size':
            _addr(image.get('image_size')),
            'image_vmaddr':
            _addr(image.get('image_vmaddr')),
        }

        if image.get('arch') is not None:
            native_image['arch'] = image.get('arch')
        if image.get('code_id') is not None:
            native_image['code_id'] = image.get('code_id')
        if image.get('debug_file') is not None:
            native_image['debug_file'] = image.get('debug_file')

        return native_image
    except KeyError as e:
        raise InterfaceValidationError('Missing value for symbolic image: %s' %
                                       e.args[0])
Ejemplo n.º 28
0
 def normalize_image(image):
     ty = image.get('type')
     if not ty:
         raise InterfaceValidationError('Image type not provided')
     if ty == 'apple':
         # Legacy alias. The schema is actually slightly different, but
         # process_native_image can deal with this and convert to a valid
         # MachO image payload.
         ty = 'macho'
     func = image_types.get(ty)
     if func is None:
         raise InterfaceValidationError('Unknown image type %r' % image)
     rv = func(image)
     assert 'uuid' in rv or 'debug_id' in rv, 'debug image normalizer did not produce an identifier'
     rv['type'] = ty
     return rv
Ejemplo n.º 29
0
    def to_python(cls, data, has_system_frames=None):
        if not (data.get('type') or data.get('value')):
            raise InterfaceValidationError("No 'type' or 'value' present")

        if data.get('stacktrace') and data['stacktrace'].get('frames'):
            stacktrace = Stacktrace.to_python(
                data['stacktrace'],
                has_system_frames=has_system_frames,
            )
        else:
            stacktrace = None

        type = data.get('type')
        value = data.get('value')
        if not type and ':' in value.split(' ', 1)[0]:
            type, value = value.split(':', 1)
            # in case of TypeError: foo (no space)
            value = value.strip()

        if value is not None and not isinstance(value, basestring):
            value = json.dumps(value)
        value = trim(value, 4096)

        kwargs = {
            'type': trim(type, 128),
            'value': value,
            'module': trim(data.get('module'), 128),
            'stacktrace': stacktrace,
        }

        return cls(**kwargs)
Ejemplo n.º 30
0
    def to_python(cls, data, slim_frames=True, raw=False):
        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid stack frame data.")

        # Trim down the frame list to a hard limit. Leave the last frame in place in case
        # it's useful for debugging.
        frameiter = data.get('frames') or []
        if len(frameiter) > settings.SENTRY_STACKTRACE_FRAMES_HARD_LIMIT:
            frameiter = chain(
                islice(data['frames'], settings.SENTRY_STACKTRACE_FRAMES_HARD_LIMIT - 1), (data['frames'][-1],))

        frame_list = []

        for f in frameiter:
            if f is None:
                continue
            # XXX(dcramer): handle PHP sending an empty array for a frame
            frame_list.append(Frame.to_python(f or {}, raw=raw))

        kwargs = {
            'frames': frame_list,
        }

        kwargs['registers'] = None
        if data.get('registers') and isinstance(data['registers'], dict):
            kwargs['registers'] = data.get('registers')

        kwargs['frames_omitted'] = data.get('frames_omitted') or None

        instance = cls(**kwargs)
        if slim_frames:
            slim_frame_data(instance)
        return instance