Пример #1
0
def test_add_user_exception_409(web_app, token):
    """User already exists

    """
    with pytest.raises(Exception) as exc_info:
        create_obj = json.loads(open('tests/admin_manager/json/create_obj.json').read())
        web_app.post_json("/add_user", {'data': {'create_obj': create_obj}}, headers={'X-Token': token})
    actual = exc_info.value.args[0]
    expected = httpexc.HTTPConflict().status
    assert expected in actual
Пример #2
0
def error(context, request):
    """Catch server errors and trace them."""
    if isinstance(context, httpexceptions.Response):
        return reapply_cors(request, context)

    if isinstance(context, storage_exceptions.IntegrityError):
        error_msg = 'Integrity constraint violated, please retry.'
        response = http_error(httpexceptions.HTTPConflict(),
                              errno=ERRORS.CONSTRAINT_VIOLATED,
                              message=error_msg)
        retry_after = request.registry.settings['retry_after_seconds']
        response.headers['Retry-After'] = str(retry_after)
        return reapply_cors(request, response)

    # Log some information about current request.
    extra = {
      'path': request.path,
      'method': request.method,
    }
    qs = dict(request_GET(request))
    if qs:
        extra['querystring'] = qs
    # Take errno from original exception, or undefined if unknown/unhandled.
    try:
        extra['errno'] = context.errno.value
    except AttributeError:
        extra['errno'] = ERRORS.UNDEFINED.value

    if isinstance(context, storage_exceptions.BackendError):
        logger.critical(context.original, extra=extra, exc_info=context)
        response = httpexceptions.HTTPServiceUnavailable()
        return service_unavailable(response, request)

    # Within the exception view, sys.exc_info() will return null.
    # see https://github.com/python/cpython/blob/ce9e62544/Lib/logging/__init__.py#L1460-L1462
    logger.error(context, extra=extra, exc_info=context)

    error_msg = 'A programmatic error occured, developers have been informed.'
    info = request.registry.settings['error_info_link']
    response = http_error(httpexceptions.HTTPInternalServerError(),
                          message=error_msg,
                          info=info)

    return reapply_cors(request, response)
Пример #3
0
def admin_page(request, error=None):
    if request.registry.settings.get('auth.block_authoring', False):
        raise http.HTTPNotFound()
    auth = authorizedOnly(None)
    if not auth.login(request):
        return login_page(request)
    tdata = get_all_announcements(request)
    tdata['author'] = request.session['uid']
    tdata['error'] = error
    tdata['settings'] = request.registry.settings
    try:
        if 'javascript' in request.accept_encoding:
            if not error:
                raise http.HTTPOk
            raise http.HTTPConflict(json.dumps(error))
    except AttributeError:
        pass
    template = get_template('main')
    content_type = 'text/html'
    reply = template.render(**tdata)
    response = Response(reply, content_type=content_type)
    return response
Пример #4
0
def _item_patch_tus(request):
    comp = request.env.file_upload

    if request.content_type != 'application/offset+octet-stream':
        raise exc.HTTPUnsupportedMediaType()

    try:
        upload_offset = int(request.headers['Upload-Offset'])
    except (KeyError, ValueError):
        raise exc.HTTPBadRequest()

    fnd, fnm = comp.get_filename(request.matchdict['id'])

    if not isfile(fnm):
        raise exc.HTTPNotFound()

    with open(fnm, 'rb') as fd:
        meta = pickle.loads(fd.read())
        size = meta['size']

    # Don't upload more than declared file size.
    if upload_offset + request.content_length > size:
        raise UploadedFileTooLarge()

    # Check minimum chunk size to prevent misconfiguration
    remain = size - upload_offset
    if request.content_length < min(remain, comp.tus_chunk_size_minimum):
        raise exc.HTTPBadRequest()

    with open(fnd, 'ab') as fd:
        # Check for upload conflict
        if upload_offset != fd.tell():
            raise exc.HTTPConflict()

        # Copy request body to data file. Input streaming is also supported
        # here is some conditions: uwsgi - does, pserve - doesn't.
        src_fd = request.body_file
        while True:
            buf = src_fd.read(BUF_SIZE)
            if buf is None:
                break
            read = len(buf)
            if len(buf) == 0:
                break
            if upload_offset + read > size:
                raise UploadedFileTooLarge()
            fd.write(buf)
            upload_offset += read

    if size == upload_offset:
        # File upload completed
        del meta['incomplete']

        # Detect MIME-type
        if 'mime_type' not in meta:
            meta['mime_type'] = magic.from_file(fnd, mime=True)

        # Save changes to metadata
        with open(fnm, 'wb') as fd:
            fd.write(pickle.dumps(meta))

    return _tus_response(204, upload_offset=upload_offset)
Пример #5
0
    def render(self):
        settings = self.request.registry.settings
        if not self.user:
            raise exc.HTTPForbidden()

        params = self.request.params

        if (asbool(settings['pyshop.upload.sanitize']) and not re.match(
                settings['pyshop.upload.sanitize.regex'], params['version'])):
            raise exc.HTTPForbidden(
                "Provided version ({}) should match "
                "regexp {}".format(params['version'],
                                   settings['pyshop.upload.sanitize.regex']))

        pkg = Package.by_name(self.session, params['name'])
        if pkg and pkg.local:
            auth = [
                user for user in pkg.owners + pkg.maintainers
                if user == self.user
            ]
            if not auth:
                raise exc.HTTPForbidden()
        elif not pkg:
            pkg = Package(name=params['name'], local=True)
            pkg.owners.append(self.user)

        content = self.request.POST['content']
        input_file = content.file

        if asbool(settings.get('pyshop.upload.rewrite_filename', '1')):
            # rewrite the filename, do not use the posted one for security
            filename = self._guess_filename(params, content.filename)
        else:
            filename = content.filename

        dir_ = os.path.join(settings['pyshop.repository'], filename[0].lower())

        if not os.path.exists(dir_):
            os.makedirs(dir_, 0o750)

        filepath = os.path.join(dir_, filename)
        while os.path.exists(filepath):
            if asbool(settings.get('pyshop.upload.never_overwrite', '0')):
                # policy: don't overwrite files that already exist in the repo
                raise exc.HTTPConflict(
                    "Uploading version ({}) would overwrite existing file".
                    format(params['version']))
            log.warning('File %s exists but new upload self.request, deleting',
                        filepath)
            os.unlink(filepath)

        size = 0
        with open(filepath, 'wb') as output_file:
            input_file.seek(0)
            while True:
                data = input_file.read(2 << 16)
                if not data:
                    break
                size += len(data)
                output_file.write(data)

        release = Release.by_version(self.session, pkg.name, params['version'])
        if not release:
            release = Release(
                package=pkg,
                version=params['version'],
                summary=params.get('summary'),
                author=self.user,
                home_page=params.get('home_page'),
                license=params.get('license'),
                description=params.get('description'),
                keywords=params.get('keywords'),
                platform=params.get('platform'),
                download_url=params.get('download_url'),
                docs_url=params.get('docs_url'),
            )

        classifiers = params.getall('classifiers')
        for name in classifiers:
            classifier = Classifier.by_name(self.session,
                                            name,
                                            create_if_not_exists=True)
            while classifier:
                if classifier not in release.classifiers:
                    release.classifiers.append(classifier)
                if classifier not in pkg.classifiers:
                    pkg.classifiers.append(classifier)
                classifier = classifier.parent

        rfile = ReleaseFile.by_filename(self.session, release, filename)
        if not rfile:
            rfile = ReleaseFile(
                release=release,
                filename=filename,
                size=size,
                md5_digest=params.get('md5_digest'),
                package_type=params['filetype'],
                python_version=params.get('pyversion'),
                comment_text=params.get('comment'),
            )

        self.session.add(rfile)
        self.session.add(release)
        pkg.update_at = func.now()
        self.session.add(pkg)
        return {'release_file': rfile}