Esempio n. 1
0
    def can_perform_action(self, store, tip_id, filename):
        rtip, _ = db_access_rtip(store, self.current_user.user_id, tip_id)

        enable_rc_to_wb_files = store.find(models.Context.enable_rc_to_wb_files,
                                           models.Context.id == models.InternalTip.context_id,
                                           models.InternalTip.id == rtip.internaltip_id).one()

        if not enable_rc_to_wb_files:
            raise errors.ForbiddenOperation()
Esempio n. 2
0
    def can_perform_action(self, store, tip_id):
        rtip = db_access_rtip(store, self.current_user.user_id, tip_id)
        if not rtip.internaltip.context.enable_rc_to_wb_files:
            return errors.ForbiddenOperation()
        n = store.find(WhistleblowerFile, WhistleblowerFile.receivertip_id == rtip.id).count()
        if n > 100:
            return errors.FailedSanityCheck()

        rtip_dict = serialize_rtip(store, rtip, self.request.language)
        wbfile_names = [f['name'] for f in rtip_dict['wbfiles']]
        # The next line will throw a KeyError if the file is not set
        new_name = self.request.args['file'][0]['filename']
        if new_name in wbfile_names:
            return errors.FailedSanityCheck()

        return None
Esempio n. 3
0
    def render(self, request):
        """
        :param request: `twisted.web.Request`

        :return: empty `str` or `NOT_DONE_YET`
        """
        request_finished = [False]

        def _finish(ret):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        self.preprocess(request)

        if request.tid is None:
            # Tentative domain correction in relation to presence / absence of 'www.' prefix
            if not request.hostname.startswith(b'www.'):
                tentative_hostname = b'www.' + request.hostname
            else:
                tentative_hostname = request.hostname[4:]

            if tentative_hostname in State.tenant_hostname_id_map:
                request.tid = State.tenant_hostname_id_map[tentative_hostname]
                if State.tenant_cache[request.tid].https_enabled:
                    request.redirect(b'https://' + tentative_hostname + b'/')
                else:
                    request.redirect(b'http://' + tentative_hostname + b'/')
            else:
                # Fallback on root tenant with error 400
                request.tid = 1
                request.setResponseCode(400)

            self.set_headers(request)
            return b''

        self.set_headers(request)

        if self.should_redirect_tor(request):
            self.redirect_tor(request)
            return b''

        if self.should_redirect_https(request):
            self.redirect_https(request)
            return b''

        request_path = request.path.decode()

        if request_path in State.tenant_cache[request.tid]['redirects']:
            request.redirect(
                State.tenant_cache[request.tid]['redirects'][request_path])
            return b''

        match = None
        for regexp, handler, args in self._registry:
            try:
                match = regexp.match(request_path)
            except UnicodeDecodeError:
                match = None
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower().decode()

        if method == 'head':
            method = 'get'
        elif method == 'options':
            request.setResponseCode(200)
            return b''

        if method not in self.method_map.keys() or not hasattr(
                handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''

        f = getattr(handler, method)
        groups = match.groups()

        self.handler = handler(State, request, **args)

        request.setResponseCode(self.method_map[method])

        if self.handler.root_tenant_only and request.tid != 1:
            self.handle_exception(errors.ForbiddenOperation(), request)
            return b''

        if self.handler.upload_handler and method == 'post':
            self.handler.process_file_upload()
            if self.handler.uploaded_file is None:
                return b''

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            self.handle_exception(err, request)

            yield self.handler.execution_check()

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """
            Concludes successful execution of a `BaseHandler` instance

            :param ret: A `dict`, `list`, `str`, `None` or something unexpected
            """
            yield self.handler.execution_check()

            if not request_finished[0]:
                if ret is not None:
                    if isinstance(ret, (dict, list)):
                        ret = json.dumps(ret,
                                         cls=JSONEncoder,
                                         separators=(',', ':'))
                        request.setHeader(b'content-type', b'application/json')

                    if isinstance(ret, str):
                        ret = ret.encode()

                    request.write(ret)

                request.finish()

        defer.maybeDeferred(f, self.handler,
                            *groups).addCallbacks(concludeHandlerSuccess,
                                                  concludeHandlerFailure)

        return NOT_DONE_YET
Esempio n. 4
0
    def render(self, request):
        """
        @param request: `twisted.web.Request`

        @return: empty `str` or `NOT_DONE_YET`
        """
        request_finished = [False]

        def _finish(ret):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        self.preprocess(request)

        self.set_headers(request)

        if request.tid is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        if self.should_redirect_tor(request):
            self.redirect_tor(request)
            return b''

        if self.should_redirect_https(request):
            self.redirect_https(request)
            return b''

        request.path = request.path.decode('utf-8')

        if request.tid == 1:
            match = re.match(r'^/t/([0-9]+)(/.*)', request.path)
            if match is not None:
                groups = match.groups()
                request.tid, request.path = int(groups[0]), groups[1]

        match = None
        for regexp, handler, args in self._registry:
            try:
                match = regexp.match(request.path)
            except UnicodeDecodeError:
                match = None
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower().decode('utf-8')

        if method == 'head':
            # HEAD method is not really implemented
            # as trick we use the same approch of Twisted of
            # mapping the HEAD method on the GET method.
            method = 'get'

        if method not in self.method_map.keys() or not hasattr(handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''

        f = getattr(handler, method)
        groups = [text_type(g) for g in match.groups()]

        self.handler = handler(State, request, **args)

        request.setResponseCode(self.method_map[method])

        if self.handler.root_tenant_only and request.tid != 1:
            self.handle_exception(errors.ForbiddenOperation(), request)
            return b''

        if self.handler.upload_handler and method == 'post':
            self.handler.process_file_upload()
            if self.handler.uploaded_file is None:
                return b''

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            yield self.handler.execution_check()

            self.handle_exception(err, request)

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """
            Concludes successful execution of a `BaseHandler` instance

            @param ret: A `dict`, `list`, `str`, `None` or something unexpected
            """
            yield self.handler.execution_check()

            if not request_finished[0]:
                if ret is not None:
                    if isinstance(ret, (dict, list)):
                        ret = json.dumps(ret, separators=(',', ':'))
                        request.setHeader(b'content-type', b'application/json')

                    if isinstance(ret, text_type):
                        ret = ret.encode()

                    request.write(ret)

                request.finish()

        defer.maybeDeferred(f, self.handler, *groups).addCallbacks(concludeHandlerSuccess, concludeHandlerFailure)

        return NOT_DONE_YET
Esempio n. 5
0
    def put(self):
        is_ready = yield can_perform_acme_run(self.request.tid)
        if not is_ready:
            raise errors.ForbiddenOperation()

        yield acme_cert_issuance(self.request.tid)
Esempio n. 6
0
    def put(self):
        is_ready = yield can_perform_acme_run()
        if not is_ready:
            raise errors.ForbiddenOperation()

        yield deferToThread(acme_cert_issuance)
Esempio n. 7
0
    def render(self, request):
        """
        @param request: `twisted.web.Request`

        @return: empty `str` or `NOT_DONE_YET`
        """
        request_finished = [False]

        def _finish(ret):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        self.preprocess(request)

        self.set_headers(request)

        if request.tid is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        if self.should_redirect_tor(request):
            self.redirect_tor(request)
            return b''

        if self.should_redirect_https(request):
            self.redirect_https(request)
            return b''

        match = None
        for regexp, handler, args in self._registry:
            match = regexp.match(request.path)
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower()
        if not method in self.method_map or not hasattr(handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''

        f = getattr(handler, method)
        groups = [unicode(g) for g in match.groups()]

        self.handler = handler(State, request, **args)

        request.setResponseCode(self.method_map[method])

        if (self.handler.root_tenant_only and request.tid != 1):
            self.handle_exception(errors.ForbiddenOperation(), request)
            return b''

        if self.handler.upload_handler and method == 'post':
            self.handler.process_file_upload()
            if self.handler.uploaded_file is None:
               return b''

        d = defer.maybeDeferred(f, self.handler, *groups)

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            yield self.handler.execution_check()

            self.handle_exception(err, request)

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """
            Concludes successful execution of a `BaseHandler` instance

            @param ret: A `dict`, `list`, `str`, `None` or something unexpected
            """
            yield self.handler.execution_check()

            if not request_finished[0]:
                if ret is not None:
                   if isinstance(ret, (types.DictType, types.ListType)):
                       ret = json.dumps(ret, separators=(',', ':'))
                       request.setHeader(b'content-type', b'application/json')

                   request.write(bytes(ret))

                request.finish()

        d.addErrback(concludeHandlerFailure)
        d.addCallback(concludeHandlerSuccess)

        return NOT_DONE_YET