def test_file_pathsep(self, sep):
     url = QUrl('glimpse://pdfjs/file')
     query = QUrlQuery()
     query.addQueryItem('filename', 'foo{}bar'.format(sep))
     url.setQuery(query)
     with pytest.raises(glimpsescheme.RequestDeniedError):
         glimpsescheme.data_for_url(url)
    def test_nonexisting_resource(self, caplog):
        """Test with a resource that does not exist."""
        with caplog.at_level(logging.WARNING, 'misc'):
            with pytest.raises(glimpsescheme.NotFoundError):
                glimpsescheme.data_for_url(
                    QUrl('glimpse://pdfjs/no/file.html'))

        expected = 'pdfjs resource requested but not found: /no/file.html'
        assert caplog.messages == [expected]
Пример #3
0
    def requestStarted(self, job):
        """Handle a request for a glimpse: scheme.

        This method must be reimplemented by all custom URL scheme handlers.
        The request is asynchronous and does not need to be handled right away.

        Args:
            job: QWebEngineUrlRequestJob
        """
        url = job.requestUrl()

        if url.scheme() in ['chrome-error', 'chrome-extension']:
            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378
            job.fail(QWebEngineUrlRequestJob.UrlInvalid)
            return

        if not self._check_initiator(job):
            return

        if job.requestMethod() != b'GET':
            job.fail(QWebEngineUrlRequestJob.RequestDenied)
            return

        assert url.scheme() == 'glimpse'

        log.misc.debug("Got request for {}".format(url.toDisplayString()))
        try:
            mimetype, data = glimpsescheme.data_for_url(url)
        except glimpsescheme.Error as e:
            errors = {
                glimpsescheme.NotFoundError:
                QWebEngineUrlRequestJob.UrlNotFound,
                glimpsescheme.UrlInvalidError:
                QWebEngineUrlRequestJob.UrlInvalid,
                glimpsescheme.RequestDeniedError:
                QWebEngineUrlRequestJob.RequestDenied,
                glimpsescheme.SchemeOSError:
                QWebEngineUrlRequestJob.UrlNotFound,
                glimpsescheme.Error: QWebEngineUrlRequestJob.RequestFailed,
            }
            exctype = type(e)
            log.misc.error("{} while handling glimpse://* URL".format(
                exctype.__name__))
            job.fail(errors[exctype])
        except glimpsescheme.Redirect as e:
            qtutils.ensure_valid(e.url)
            job.redirect(e.url)
        else:
            log.misc.debug("Returning {} data".format(mimetype))

            # We can't just use the QBuffer constructor taking a QByteArray,
            # because that somehow segfaults...
            # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
            buf = QBuffer(parent=self)
            buf.open(QIODevice.WriteOnly)
            buf.write(data)
            buf.seek(0)
            buf.close()
            job.reply(mimetype.encode('ascii'), buf)
Пример #4
0
def handler(request, operation, current_url):
    """Scheme handler for glimpse:// URLs.

    Args:
        request: QNetworkRequest to answer to.
        operation: The HTTP operation being done.
        current_url: The page we're on currently.

    Return:
        A QNetworkReply.
    """
    if operation != QNetworkAccessManager.GetOperation:
        return networkreply.ErrorNetworkReply(
            request, "Unsupported request type",
            QNetworkReply.ContentOperationNotPermittedError)

    url = request.url()

    if ((url.scheme(), url.host(), url.path()) ==
            ('glimpse', 'settings', '/set')):
        if current_url != QUrl('glimpse://settings/'):
            log.webview.warning("Blocking malicious request from {} to {}"
                                .format(current_url.toDisplayString(),
                                        url.toDisplayString()))
            return networkreply.ErrorNetworkReply(
                request, "Invalid glimpse://settings request",
                QNetworkReply.ContentAccessDenied)

    try:
        mimetype, data = glimpsescheme.data_for_url(url)
    except glimpsescheme.Error as e:
        errors = {
            glimpsescheme.NotFoundError:
                QNetworkReply.ContentNotFoundError,
            glimpsescheme.UrlInvalidError:
                QNetworkReply.ContentOperationNotPermittedError,
            glimpsescheme.RequestDeniedError:
                QNetworkReply.ContentAccessDenied,
            glimpsescheme.SchemeOSError:
                QNetworkReply.ContentNotFoundError,
            glimpsescheme.Error:
                QNetworkReply.InternalServerError,
        }
        exctype = type(e)
        log.misc.error("{} while handling glimpse://* URL".format(
            exctype.__name__))
        return networkreply.ErrorNetworkReply(request, str(e), errors[exctype])
    except glimpsescheme.Redirect as e:
        qtutils.ensure_valid(e.url)
        return networkreply.RedirectNetworkReply(e.url)

    return networkreply.FixedDataNetworkReply(request, data, mimetype)
    def test_glimpsejavascript_404(self):
        url = QUrl("glimpse://javascript/404.js")

        with pytest.raises(glimpsescheme.SchemeOSError):
            glimpsescheme.data_for_url(url)
 def test_file_no_filename(self):
     with pytest.raises(glimpsescheme.UrlInvalidError):
         glimpsescheme.data_for_url(QUrl('glimpse://pdfjs/file'))
 def test_file(self, download_tmpdir):
     """Load a file via glimpse://pdfjs/file."""
     (download_tmpdir / 'testfile').write_binary(b'foo')
     _mimetype, data = glimpsescheme.data_for_url(
         QUrl('glimpse://pdfjs/file?filename=testfile'))
     assert data == b'foo'
 def test_viewer_no_filename(self):
     with pytest.raises(glimpsescheme.UrlInvalidError):
         glimpsescheme.data_for_url(QUrl('glimpse://pdfjs/web/viewer.html'))
 def test_viewer_page(self, data_tmpdir):
     """Load the /web/viewer.html page."""
     _mimetype, data = glimpsescheme.data_for_url(
         QUrl('glimpse://pdfjs/web/viewer.html?filename=foobar'))
     assert b'PDF.js' in data
 def test_existing_resource(self):
     """Test with a resource that exists."""
     _mimetype, data = glimpsescheme.data_for_url(
         QUrl('glimpse://pdfjs/existing/file.html'))
     assert data == b'foobar'