Esempio n. 1
0
def app_view_manifest(request, addon):
    if addon.is_packaged:
        version = addon.versions.latest()
        content = json.dumps(json.loads(_mini_manifest(addon, version.id)),
                             indent=4)
        return escape_all({'content': content, 'headers': ''})

    else:  # Show the hosted manifest_url.
        content, headers = u'', {}
        if addon.manifest_url:
            try:
                req = requests.get(addon.manifest_url, verify=False)
                content, headers = req.content, req.headers
            except Exception:
                content = u''.join(traceback.format_exception(*sys.exc_info()))

            try:
                # Reindent the JSON.
                content = json.dumps(json.loads(content), indent=4)
            except:
                # If it's not valid JSON, just return the content as is.
                pass
        return escape_all({
            'content': smart_decode(content),
            'headers': headers
        })
Esempio n. 2
0
def app_view_manifest(request, addon):
    if addon.is_packaged:
        version = addon.versions.latest()
        content = json.dumps(json.loads(_mini_manifest(addon, version.id)),
                             indent=4)
        return escape_all({'content': content, 'headers': '', 'success': True})

    else:  # Show the hosted manifest_url.
        content, headers, success = u'', {}, False
        if addon.manifest_url:
            try:
                req = requests.get(addon.manifest_url, verify=False)
                content, headers = req.content, req.headers
                success = True
            except Exception:
                content = u''.join(traceback.format_exception(*sys.exc_info()))

            try:
                # Reindent the JSON.
                content = json.dumps(json.loads(content), indent=4)
            except:
                # If it's not valid JSON, just return the content as is.
                pass
        return escape_all({'content': smart_decode(content),
                           'headers': headers,
                           'success': success})
Esempio n. 3
0
def test_escape_all_linkify_only_full(mock_get_outgoing_url):
    mock_get_outgoing_url.return_value = 'http://outgoing.firefox.com'

    eq_(escape_all('http://firefox.com', linkify_only_full=True),
        '<a href="http://outgoing.firefox.com">http://firefox.com</a>')
    eq_(escape_all('http://firefox.com', linkify_only_full=False),
        '<a href="http://outgoing.firefox.com">http://firefox.com</a>')

    eq_(escape_all('firefox.com', linkify_only_full=True), 'firefox.com')
    eq_(escape_all('firefox.com', linkify_only_full=False),
        '<a href="http://outgoing.firefox.com">firefox.com</a>')
Esempio n. 4
0
def test_escape_all_linkify_only_full(mock_get_outgoing_url):
    mock_get_outgoing_url.return_value = 'http://outgoing.firefox.com'

    eq_(escape_all('http://firefox.com', linkify_only_full=True),
        '<a href="http://outgoing.firefox.com">http://firefox.com</a>')
    eq_(escape_all('http://firefox.com', linkify_only_full=False),
        '<a href="http://outgoing.firefox.com">http://firefox.com</a>')

    eq_(escape_all('firefox.com', linkify_only_full=True), 'firefox.com')
    eq_(escape_all('firefox.com', linkify_only_full=False),
        '<a href="http://outgoing.firefox.com">firefox.com</a>')
Esempio n. 5
0
def ajax(request):
    """Query for a user matching a given email."""

    if 'q' not in request.GET:
        raise http.Http404()

    data = {'status': 0, 'message': ''}

    email = request.GET.get('q', '').strip()
    dev_only = request.GET.get('dev', '1')
    try:
        dev_only = int(dev_only)
    except ValueError:
        dev_only = 1
    dev_only = dev_only and settings.MARKETPLACE

    if not email:
        data.update(message=_('An email address is required.'))
        return data

    user = UserProfile.objects.filter(email=email)
    if dev_only:
        user = user.exclude(read_dev_agreement=None)

    msg = _('A user with that email address does not exist.')
    msg_dev = _('A user with that email address does not exist, or the user '
                'has not yet accepted the developer agreement.')

    if user:
        data.update(status=1, id=user[0].id, name=user[0].name)
    else:
        data['message'] = msg_dev if dev_only else msg

    return escape_all(data)
Esempio n. 6
0
def app_view_manifest(request, addon):
    manifest = {}
    success = False
    headers = ''
    if addon.is_packaged:
        manifest = _get_manifest_json(addon)
        content = json.dumps(manifest, indent=4)
        success = True

    else:  # Show the hosted manifest_url.
        content, headers = u'', {}
        if addon.manifest_url:
            try:
                req = requests.get(addon.manifest_url, verify=False)
                content, headers = req.content, req.headers
                success = True
            except Exception:
                content = u''.join(traceback.format_exception(*sys.exc_info()))
            else:
                success = True

            try:
                # Reindent the JSON.
                manifest = json.loads(content)
                content = json.dumps(manifest, indent=4)
            except:
                # If it's not valid JSON, just return the content as is.
                pass

    return escape_all({'content': smart_decode(content),
                       'headers': dict(headers),
                       'success': success,
                       'permissions': _get_permissions(manifest)})
Esempio n. 7
0
def make_validation_result(data, is_compatibility=False):
    """Safe wrapper around JSON dict containing a validation result.

    Keyword Arguments

    **is_compatibility=False**
        When True, errors will be summarized as if they were in a regular
        validation result.
    """
    if not settings.EXPOSE_VALIDATOR_TRACEBACKS:
        if data['error']:
            # Just expose the message, not the traceback
            data['error'] = data['error'].strip().split('\n')[-1].strip()
    if data['validation']:
        ending_tier = 0
        for msg in data['validation']['messages']:
            if msg['tier'] > ending_tier:
                ending_tier = msg['tier']
            if msg['tier'] == 0:
                # We can't display a message if it's on tier 0.
                # Should get fixed soon in bug 617481
                msg['tier'] = 1
            for k, v in msg.items():
                msg[k] = escape_all(v)
        if is_compatibility:
            compat = data['validation']['compatibility_summary']
            for k in ('errors', 'warnings', 'notices'):
                data['validation'][k] = compat[k]
            for msg in data['validation']['messages']:
                if msg['compatibility_type']:
                    msg['type'] = msg['compatibility_type']
        data['validation']['ending_tier'] = ending_tier
    return data
Esempio n. 8
0
def app_view_manifest(request, addon):
    manifest = {}
    success = False
    headers = ''
    if addon.is_packaged:
        manifest = _get_manifest_json(addon)
        content = json.dumps(manifest, indent=4)
        success = True

    else:  # Show the hosted manifest_url.
        content, headers = u'', {}
        if addon.manifest_url:
            try:
                req = requests.get(addon.manifest_url, verify=False)
                content, headers = req.content, req.headers
                success = True
            except Exception:
                content = u''.join(traceback.format_exception(*sys.exc_info()))
            else:
                success = True

            try:
                # Reindent the JSON.
                manifest = json.loads(content)
                content = json.dumps(manifest, indent=4)
            except:
                # If it's not valid JSON, just return the content as is.
                pass

    return escape_all({
        'content': smart_decode(content),
        'headers': dict(headers),
        'success': success,
        'permissions': _get_permissions(manifest)
    })
Esempio n. 9
0
def ajax(request):
    """Query for a user matching a given email."""

    if 'q' not in request.GET:
        raise http.Http404()

    data = {'status': 0, 'message': ''}

    email = request.GET.get('q', '').strip()
    dev_only = request.GET.get('dev', '1')
    try:
        dev_only = int(dev_only)
    except ValueError:
        dev_only = 1

    if not email:
        data.update(message=_('An email address is required.'))
        return data

    user = UserProfile.objects.filter(email=email)
    if dev_only:
        user = user.exclude(read_dev_agreement=None)

    msg = _('A user with that email address does not exist.')
    msg_dev = _('A user with that email address does not exist, or the user '
                'has not yet accepted the developer agreement.')

    if user:
        data.update(status=1, id=user[0].id, name=user[0].name)
    else:
        data['message'] = msg_dev if dev_only else msg

    return escape_all(data)
Esempio n. 10
0
def make_validation_result(data, is_compatibility=False):
    """Safe wrapper around JSON dict containing a validation result.

    Keyword Arguments

    **is_compatibility=False**
        When True, errors will be summarized as if they were in a regular
        validation result.
    """
    if not settings.EXPOSE_VALIDATOR_TRACEBACKS:
        if data['error']:
            # Just expose the message, not the traceback
            data['error'] = data['error'].strip().split('\n')[-1].strip()
    if data['validation']:
        ending_tier = 0
        for msg in data['validation']['messages']:
            if msg['tier'] > ending_tier:
                ending_tier = msg['tier']
            if msg['tier'] == 0:
                # We can't display a message if it's on tier 0.
                # Should get fixed soon in bug 617481
                msg['tier'] = 1
            for k, v in msg.items():
                msg[k] = escape_all(v)
        if is_compatibility:
            compat = data['validation']['compatibility_summary']
            for k in ('errors', 'warnings', 'notices'):
                data['validation'][k] = compat[k]
            for msg in data['validation']['messages']:
                if msg['compatibility_type']:
                    msg['type'] = msg['compatibility_type']
        data['validation']['ending_tier'] = ending_tier
    return data
Esempio n. 11
0
def ajax(request):
    """Query for a user matching a given email."""

    if "q" not in request.GET:
        raise http.Http404()

    data = {"status": 0, "message": ""}

    email = request.GET.get("q", "").strip()
    dev_only = request.GET.get("dev", "1")
    try:
        dev_only = int(dev_only)
    except ValueError:
        dev_only = 1
    dev_only = dev_only and settings.MARKETPLACE

    if not email:
        data.update(message=_("An email address is required."))
        return data

    user = UserProfile.objects.filter(email=email)
    if dev_only:
        user = user.exclude(read_dev_agreement=None)

    msg = _("A user with that email address does not exist.")
    msg_dev = _(
        "A user with that email address does not exist, or the user " "has not yet accepted the developer agreement."
    )

    if user:
        data.update(status=1, id=user[0].id, name=user[0].name)
    else:
        data["message"] = msg_dev if dev_only else msg

    return escape_all(data)
Esempio n. 12
0
def make_validation_result(data):
    """Safe wrapper around JSON dict containing a validation result."""
    if not settings.EXPOSE_VALIDATOR_TRACEBACKS:
        if data['error']:
            # Just expose the message, not the traceback.
            data['error'] = data['error'].strip().split('\n')[-1].strip()
    if data['validation']:
        for msg in data['validation']['messages']:
            for k, v in msg.items():
                msg[k] = escape_all(v, linkify=k in ('message', 'description'))
    return data
Esempio n. 13
0
    def test_nested(self):
        value = '<script>alert("BALL SO HARD")</script>'
        expected = '&lt;script&gt;alert("BALL SO HARD")&lt;/script&gt;'

        test = {"string": value, "dict": {"x": value}, "list": [value], "bool": True}
        res = escape_all(test)

        eq_(res["string"], expected)
        eq_(res["dict"], {"x": expected})
        eq_(res["list"], [expected])
        eq_(res["bool"], True)
Esempio n. 14
0
    def test_without_linkify(self):
        value = "<button>http://firefox.com</button>"
        expected = "&lt;button&gt;http://firefox.com&lt;/button&gt;"

        test = {"string": value, "dict": {"x": value}, "list": [value], "bool": True}
        res = escape_all(test, linkify=False)

        eq_(res["string"], expected)
        eq_(res["dict"], {"x": expected})
        eq_(res["list"], [expected])
        eq_(res["bool"], True)
Esempio n. 15
0
def make_validation_result(data):
    """Safe wrapper around JSON dict containing a validation result."""
    if not settings.EXPOSE_VALIDATOR_TRACEBACKS:
        if data['error']:
            # Just expose the message, not the traceback.
            data['error'] = data['error'].strip().split('\n')[-1].strip()
    if data['validation']:
        for msg in data['validation']['messages']:
            for k, v in msg.items():
                msg[k] = escape_all(v)
    return data
Esempio n. 16
0
def make_validation_result(data):
    """Safe wrapper around JSON dict containing a validation result."""
    if not settings.EXPOSE_VALIDATOR_TRACEBACKS:
        if data["error"]:
            # Just expose the message, not the traceback.
            data["error"] = data["error"].strip().split("\n")[-1].strip()
    if data["validation"]:
        for msg in data["validation"]["messages"]:
            for k, v in msg.items():
                msg[k] = escape_all(v, linkify=k in ("message", "description"))
    return data
Esempio n. 17
0
def escape_validation(validation):
    ending_tier = validation.get('ending_tier', 0)
    for msg in validation.get('messages', []):
        tier = msg.get('tier', -1)  # Use -1 so we know it isn't 0.
        if tier > ending_tier:
            ending_tier = tier
        if tier == 0:
            # We can't display a message if it's on tier 0.
            # Should get fixed soon in bug 617481
            msg['tier'] = 1
    validation['ending_tier'] = ending_tier
    return escape_all(validation, linkify_only_full=True)
Esempio n. 18
0
def escape_validation(validation):
    ending_tier = validation.get('ending_tier', 0)
    for msg in validation.get('messages', []):
        tier = msg.get('tier', -1)  # Use -1 so we know it isn't 0.
        if tier > ending_tier:
            ending_tier = tier
        if tier == 0:
            # We can't display a message if it's on tier 0.
            # Should get fixed soon in bug 617481
            msg['tier'] = 1
    validation['ending_tier'] = ending_tier
    return escape_all(validation, linkify_only_full=True)
Esempio n. 19
0
def app_view_manifest(request, addon):
    content, headers = u'', {}
    if addon.manifest_url:
        try:
            req = requests.get(addon.manifest_url, verify=False)
            content, headers = req.content, req.headers
        except Exception:
            content = u''.join(traceback.format_exception(*sys.exc_info()))

        try:
            # Reindent the JSON.
            content = json.dumps(json.loads(content), indent=4)
        except:
            # If it's not valid JSON, just return the content as is.
            pass
    return escape_all({'content': smart_decode(content), 'headers': headers})
Esempio n. 20
0
    def test_without_linkify(self):
        value = '<button>http://firefox.com</button>'
        expected = '&lt;button&gt;http://firefox.com&lt;/button&gt;'

        test = {
            'string': value,
            'dict': {'x': value},
            'list': [value],
            'bool': True,
        }
        res = escape_all(test, linkify=False)

        eq_(res['string'], expected)
        eq_(res['dict'], {'x': expected})
        eq_(res['list'], [expected])
        eq_(res['bool'], True)
Esempio n. 21
0
    def test_nested(self):
        value = '<script>alert("BALL SO HARD")</script>'
        expected = '&lt;script&gt;alert("BALL SO HARD")&lt;/script&gt;'

        test = {
            'string': value,
            'dict': {'x': value},
            'list': [value],
            'bool': True,
        }
        res = escape_all(test)

        eq_(res['string'], expected)
        eq_(res['dict'], {'x': expected})
        eq_(res['list'], [expected])
        eq_(res['bool'], True)
Esempio n. 22
0
def app_view_manifest(request, addon):
    content, headers = u'', {}
    if addon.manifest_url:
        try:
            req = requests.get(addon.manifest_url, verify=False)
            content, headers = req.content, req.headers
        except Exception:
            content = u''.join(traceback.format_exception(*sys.exc_info()))

        try:
            # Reindent the JSON.
            content = json.dumps(json.loads(content), indent=4)
        except:
            # If it's not valid JSON, just return the content as is.
            pass
    return escape_all({'content': smart_decode(content), 'headers': headers})
Esempio n. 23
0
def app_view_manifest(request, addon):
    headers = {}
    manifest = {}
    success = False

    if addon.is_packaged:
        manifest = _get_manifest_json(addon)
        content = json.dumps(manifest, indent=4)
        success = True

    else:  # Show the hosted manifest_url.
        content, headers = u'', {}
        if addon.manifest_url:
            try:
                req = requests.get(
                    addon.manifest_url,
                    verify=False,
                    headers={'User-Agent': settings.MARKETPLACE_USER_AGENT})
                content, headers = req.content, req.headers
                success = True
            except Exception:
                content = u''.join(traceback.format_exception(*sys.exc_info()))
            else:
                success = True

            try:
                # Reindent the JSON.
                manifest = json.loads(content)
                content = json.dumps(manifest, indent=4)
            except:
                # If it's not valid JSON, just return the content as is.
                pass

    return {
        'content':
        jinja2.escape(smart_decode(content)),
        'headers':
        dict((jinja2.escape(k), jinja2.escape(v)) for k, v in headers.items()),
        'success':
        success,
        # Note: We're using `escape_all` on the values here since we know the
        # keys of the nested dict don't come from user input (manifest) and are
        # known safe.
        'permissions':
        dict((jinja2.escape(k), escape_all(v))
             for k, v in _get_permissions(manifest).items())
    }
Esempio n. 24
0
    def test_basics(self):
        x = "-".join([u, u])
        y = " - ".join([u, u])

        tests = [
            ('<script>alert("BALL SO HARD")</script>', '&lt;script&gt;alert("BALL SO HARD")&lt;/script&gt;'),
            (u"Bän...g (bang)", u"Bän...g (bang)"),
            (u, u),
            (x, x),
            (y, y),
            (u"x荿", u"x\u837f"),
            (u"ϧ΃蒬蓣", u"\u03e7\u0383\u84ac\u84e3"),
            (u"¿x", u"¿x"),
        ]

        for val, expected in tests:
            eq_(escape_all(val), expected)
Esempio n. 25
0
    def test_without_linkify(self):
        value = '<button>http://firefox.com</button>'
        expected = '&lt;button&gt;http://firefox.com&lt;/button&gt;'

        test = {
            'string': value,
            'dict': {
                'x': value
            },
            'list': [value],
            'bool': True,
        }
        res = escape_all(test, linkify=False)

        eq_(res['string'], expected)
        eq_(res['dict'], {'x': expected})
        eq_(res['list'], [expected])
        eq_(res['bool'], True)
Esempio n. 26
0
    def test_basics(self):
        x = '-'.join([u, u])
        y = ' - '.join([u, u])

        tests = [
            ('<script>alert("BALL SO HARD")</script>',
             '&lt;script&gt;alert("BALL SO HARD")&lt;/script&gt;'),
            (u'Bän...g (bang)', u'Bän...g (bang)'),
            (u, u),
            (x, x),
            (y, y),
            (u'x荿', u'x\u837f'),
            (u'ϧ΃蒬蓣', u'\u03e7\u0383\u84ac\u84e3'),
            (u'¿x', u'¿x'),
        ]

        for val, expected in tests:
            eq_(escape_all(val), expected)
Esempio n. 27
0
    def test_basics(self):
        x = '-'.join([u, u])
        y = ' - '.join([u, u])

        tests = [
            ('<script>alert("BALL SO HARD")</script>',
             '&lt;script&gt;alert("BALL SO HARD")&lt;/script&gt;'),
            (u'Bän...g (bang)', u'Bän...g (bang)'),
            (u, u),
            (x, x),
            (y, y),
            (u'x荿', u'x\u837f'),
            (u'ϧ΃蒬蓣', u'\u03e7\u0383\u84ac\u84e3'),
            (u'¿x', u'¿x'),
        ]

        for val, expected in tests:
            eq_(escape_all(val), expected)
Esempio n. 28
0
    def test_nested(self):
        value = '<script>alert("BALL SO HARD")</script>'
        expected = '&lt;script&gt;alert("BALL SO HARD")&lt;/script&gt;'

        test = {
            'string': value,
            'dict': {
                'x': value
            },
            'list': [value],
            'bool': True,
        }
        res = escape_all(test)

        eq_(res['string'], expected)
        eq_(res['dict'], {'x': expected})
        eq_(res['list'], [expected])
        eq_(res['bool'], True)
Esempio n. 29
0
def app_view_manifest(request, addon):
    headers = {}
    manifest = {}
    success = False

    if addon.is_packaged:
        manifest = _get_manifest_json(addon)
        content = json.dumps(manifest, indent=4)
        success = True

    else:  # Show the hosted manifest_url.
        content, headers = u'', {}
        if addon.manifest_url:
            try:
                req = requests.get(
                    addon.manifest_url, verify=False,
                    headers={'User-Agent': settings.MARKETPLACE_USER_AGENT})
                content, headers = req.content, req.headers
                success = True
            except Exception:
                content = u''.join(traceback.format_exception(*sys.exc_info()))
            else:
                success = True

            try:
                # Reindent the JSON.
                manifest = json.loads(content)
                content = json.dumps(manifest, indent=4)
            except:
                # If it's not valid JSON, just return the content as is.
                pass

    return {
        'content': jinja2.escape(smart_decode(content)),
        'headers': dict((jinja2.escape(k), jinja2.escape(v))
                        for k, v in headers.items()),
        'success': success,
        # Note: We're using `escape_all` on the values here since we know the
        # keys of the nested dict don't come from user input (manifest) and are
        # known safe.
        'permissions': dict((jinja2.escape(k), escape_all(v))
                            for k, v in _get_permissions(manifest).items())
    }
Esempio n. 30
0
def ajax(request):
    """Query for a user matching a given email."""

    if 'q' not in request.GET:
        raise http.Http404()

    data = {'status': 0, 'message': ''}

    email = request.GET.get('q', '').strip()

    if not email:
        data.update(message=_('An email address is required.'))
        return data

    u = UserProfile.objects.filter(email=email)

    if u:
        data.update(status=1, id=u[0].id, name=u[0].name)
    else:
        data['message'] = _('A user with that email address does not exist.')

    return escape_all(data)
Esempio n. 31
0
def ajax(request):
    """Query for a user matching a given email."""

    if 'q' not in request.GET:
        raise http.Http404()

    data = {'status': 0, 'message': ''}

    email = request.GET.get('q', '').strip()

    if not email:
        data.update(message=_('An email address is required.'))
        return data

    u = UserProfile.objects.filter(email=email)

    if u:
        data.update(status=1, id=u[0].id, name=u[0].name)
    else:
        data['message'] = _('A user with that email address does not exist.')

    return escape_all(data)
Esempio n. 32
0
@permission_required('Apps', 'Review')
@addon_view
@json_view
def app_view_manifest(request, addon):
    content, headers = '', {}
    if addon.manifest_url:
        try:
            req = requests.get(addon.manifest_url)
            content, headers = req.content, req.headers
        except Exception, e:
            content = e

        try:
            # Reindent the JSON.
            content = json.dumps(json.loads(content), indent=4)
        except:
            # If it's not valid JSON, just return the content as is.
            pass
    return escape_all({'content': content, 'headers': headers})


@permission_required('Apps', 'Review')
@addon_view
def app_abuse(request, addon):
    reports = AbuseReport.objects.filter(addon=addon).order_by('-created')
    total = reports.count()
    reports = amo.utils.paginate(request, reports, count=total)
    return jingo.render(request, 'reviewers/abuse.html',
                        context(addon=addon, reports=reports, total=total))
Esempio n. 33
0
 def check(x, y):
     eq_(escape_all(x), y)
Esempio n. 34
0
 def check(x, y):
     eq_(escape_all(x), y)