Beispiel #1
0
 def _get_valid_cert_data(self, manage_api, request_case):
     cert_data = manage_api.get_cert(request_case.cert_ca_label,
                                     request_case.cert_serial_number)
     cert_data.ensure_cert_verified()
     if cert_data.revoked_on is not None:
         raise HTTPGone('The requested certificate has been revoked.')
     if cert_data.expires_on < datetime.datetime.utcnow():
         raise HTTPGone('The requested certificate already expired.')
     return cert_data
Beispiel #2
0
 def __call__(self, model, req):
     if model == Language:
         # responses for no longer supported legacy codes
         legacy = req.db.query(
             models.LegacyCode).filter_by(id=req.matchdict['id'])
         if req.db.query(legacy.exists()).scalar():
             raise HTTPGone()
     elif model == Source:
         legacy = req.db.query(
             models.LegacyRef).filter_by(id=req.matchdict['id'])
         if req.db.query(legacy.exists()).scalar():
             raise HTTPGone()
     return super(GLCtxFactoryQuery, self).__call__(model, req)
Beispiel #3
0
 def __call__(self, model, req):
     if model == Language:
         # responses for no longer supported legacy codes
         if not models.Languoid.get(req.matchdict['id'], default=None):
             legacy = models.LegacyCode.get(req.matchdict['id'],
                                            default=None)
             if legacy:
                 raise HTTPMovedPermanently(location=legacy.url(req))
         #
         # FIXME: how to serve HTTP 410 for legacy codes?
         #
     elif model == Source:
         if ':' in req.matchdict['id']:
             ref = req.db.query(models.Source)\
                 .join(models.Refprovider)\
                 .filter(models.Refprovider.id == req.matchdict['id'])\
                 .first()
             if ref:
                 raise HTTPMovedPermanently(
                     location=req.route_url('source', id=ref.id))
         legacy = req.db.query(
             models.LegacyRef).filter_by(id=req.matchdict['id'])
         if req.db.query(legacy.exists()).scalar():
             raise HTTPGone()
     return super(GLCtxFactoryQuery, self).__call__(model, req)
Beispiel #4
0
def ctx_factory(model, type_, req):
    """The context of a request is either a single model instance or an instance of
    DataTable incorporating all information to retrieve an appropriately filtered list
    of model instances.
    """
    def replacement(id_):
        raise HTTPMovedPermanently(
            location=req.route_url(model.mapper_name().lower(), id=id_))

    if type_ == 'index':
        datatable = req.registry.getUtility(interfaces.IDataTable,
                                            name=req.matched_route.name)
        return datatable(req, model)

    try:
        if model == common.Dataset:
            ctx = req.db.query(model).one()
        elif model == common.Combination:
            ctx = common.Combination.get(req.matchdict['id'])
        else:
            ctx = req.registry.getUtility(interfaces.ICtxFactoryQuery)(model,
                                                                       req)
            if ctx.replacement_id:
                return replacement(ctx.replacement_id)
        ctx.metadata = get_adapters(interfaces.IMetadata, ctx, req)
        return ctx
    except NoResultFound:
        if req.matchdict.get('id'):
            replacement_id = common.Config.get_replacement_id(
                model, req.matchdict['id'])
            if replacement_id:
                if replacement_id == common.Config.gone:
                    raise HTTPGone()
                return replacement(replacement_id)
        raise HTTPNotFound()
Beispiel #5
0
def dropbox_post_factory(request):
    """receives a UUID via the request and returns either a fresh or an existing dropbox
    for it"""
    try:
        drop_id = parse_post_token(
            token=request.matchdict['token'],
            secret=request.registry.settings['post_secret'])
    except SignatureExpired:
        raise HTTPGone('dropbox expired')
    except Exception:  # don't be too specific on the reason for the error
        raise HTTPNotFound('no such dropbox')
    dropbox = request.registry.settings['dropbox_container'].get_dropbox(
        drop_id)
    if dropbox.status_int >= 20:
        raise HTTPGone('dropbox already in processing, no longer accepts data')
    return dropbox
Beispiel #6
0
def decrypt(ciphertext, settings):
    """
    Calculate and return the plaintext key from the given ciphertext.

    Args:
        ciphertext (str): The encrypted secret for a captcha image.
        settings (bodhi.server.config.BodhiConfig): Bodhi's settings.
    Returns:
        unicode: The plaintext secret for a captcha image.
    Raises:
        pyramid.httpexceptions.HTTPNotFound: If the ciphertext can not be decoded as base64.
        pyramid.httpexceptions.HTTPGone: If the captcha token has expired.
    """
    ttl = settings['captcha.ttl']
    secret = settings['captcha.secret']
    engine = cryptography.fernet.Fernet(secret)

    if isinstance(ciphertext, str):
        ciphertext = ciphertext.encode('utf-8')

    try:
        ciphertext = base64.urlsafe_b64decode(ciphertext)
    except (TypeError, binascii.Error):
        raise HTTPNotFound("%s is garbage" % ciphertext.decode('utf-8'))

    try:
        plaintext = engine.decrypt(ciphertext, ttl=ttl)
    except cryptography.fernet.InvalidToken:
        raise HTTPGone('captcha token is no longer valid')

    return plaintext.decode('utf-8')
Beispiel #7
0
def invitation_claim(request):
    """ Action that awards a person a badge after scanning a qrcode. """

    settings = request.registry.settings

    if request.context.expires_on < datetime.now():
        return HTTPGone("That invitation is expired.")

    if not authenticated_userid(request):
        request.session['came_from'] = request.resource_url(
            request.context, 'claim')
        return HTTPFound(location=request.route_url('login'))

    person = request.db.get_person(person_email=authenticated_userid(request))

    # Check to see if the user already has the badge.
    if request.context.badge in [a.badge for a in person.assertions]:
        # TODO: Flash a message explaining that they already have the badge
        return HTTPFound(location=request.route_url('home'))

    result = request.db.add_assertion(request.context.badge_id, person.email,
                                      datetime.now())

    # TODO -- return them to a page that auto-exports their badges.
    # TODO -- flash and tell them they got the badge
    return HTTPFound(location=request.route_url('home'))
Beispiel #8
0
 def _check_request_case_expiry(self, request_case):
     assert request_case.status == 'finalized'
     request_case_expiry_days = self.view_config_section[
         'finalized_request_case_expiry_days']
     if request_case_expiry_days > 0 and (
             datetime.datetime.utcnow() - request_case.status_changed_on
             > datetime.timedelta(days=request_case_expiry_days)):
         raise HTTPGone(
             'The specified remote certificate request case expired.')
Beispiel #9
0
def respond_if_blocked(context, request):
    """
    Set 410 Gone and construct response if resource is deleted or hidden.

    Otherwise or it request method is 'options' or 'put' return None
    """
    from adhocracy_core.utils import get_reason_if_blocked
    if request.method not in ['HEAD', 'GET', 'POST']:
        return
    block_reason = get_reason_if_blocked(context)
    if block_reason is not None:
        raise HTTPGone(detail=block_reason)
Beispiel #10
0
def get_authorized_file(file_id, auth_token, container=None):
    # type: (AnyUUID, str, Optional[AnySettingsContainer]) -> VaultFile
    """
    Obtain the requested file if access is granted.

    :param file_id: Vault storage reference file UUID.
    :param auth_token: Token to obtain access to the file.
    :param container: Application settings.
    :return: Authorized file.
    :raises: Appropriate HTTP exception according to use case.
    """
    vault_token = parse_vault_token(auth_token, unique=True)
    token = vault_token.get(None, vault_token.get(file_id))
    if not token:
        # note:
        #   401 not applicable since no no Authentication endpoint for the Vault
        #   RFC 2616 requires that a 401 response be accompanied by an RFC 2617 WWW-Authenticate
        msg = "Missing authorization token to obtain access to vault file."
        if auth_token:  # if header provided but parsed as invalid
            msg = "Incorrectly formed authorization token to obtain access to vault file."
        if vault_token and list(vault_token)[0] not in [None, file_id]:
            msg = "Mismatching Vault UUID specified in authorization header."
        raise HTTPForbidden(
            json={
                "code": "InvalidHeaderValue",
                "name": sd.XAuthVaultFileHeader.name,
                "description": msg,
                "value": repr_json(auth_token, force_string=False),
            })

    db = get_db(container)
    vault = db.get_store(StoreVault)
    file = vault.get_file(
        file_id, nothrow=True)  # don't indicate if not found if unauthorized
    if not VaultFile.authorized(file, token):
        raise HTTPForbidden(
            json={
                "code": "InvalidHeaderValue",
                "name": sd.XAuthVaultFileHeader.name,
                "description":
                sd.ForbiddenVaultFileDownloadResponse.description,
            })

    file_path = get_vault_path(file, container)
    if not os.path.isfile(file_path):
        raise HTTPGone(
            json={
                "code": "VaultFileGone",
                "value": str(file.id),
                "description": sd.GoneVaultFileDownloadResponse.description,
            })
    return file
Beispiel #11
0
def invitation_qrcode(request):
    """ Returns a raw dummy qrcode through to the user. """

    if request.context.expires_on < datetime.now():
        return HTTPGone("That invitation is expired.")

    target = request.resource_url(request.context, 'claim')
    img = qrcode_module.make(target)
    stringstream = StringIO.StringIO()
    img.save(stringstream)
    return Response(
        body=stringstream.getvalue(),
        content_type='image/png',
    )
Beispiel #12
0
def diff_document_versions(request):
    """Compara duas versões do documento. Se o argumento `to_when` não for
    fornecido, será assumido como alvo a versão mais recente.
    """
    from_when = request.GET.get("from_when", None)
    if from_when is None:
        raise HTTPBadRequest("cannot fetch diff: missing attribute from_when")
    try:
        return request.services["diff_document_versions"](
            id=request.matchdict["document_id"],
            from_version_at=from_when,
            to_version_at=request.GET.get("to_when", None),
        )
    except (exceptions.DoesNotExist, ValueError) as exc:
        raise HTTPNotFound(exc)
    except exceptions.DeletedVersion as exc:
        raise HTTPGone(exc)
def fetch_document_data(request):
    """Obtém o conteúdo do documento representado em XML com todos os
    apontamentos para seus ativos digitais contextualizados de acordo com a
    versão do documento. Produzirá uma resposta com o código HTTP 404 caso o
    documento solicitado não seja conhecido pela aplicação.
    """
    when = request.GET.get("when", None)
    if when:
        version = {"version_at": when}
    else:
        version = {}
    try:
        return request.services["fetch_document_data"](
            id=request.matchdict["document_id"], **version)
    except (exceptions.DoesNotExist, ValueError) as exc:
        raise HTTPNotFound(exc)
    except exceptions.DeletedVersion as exc:
        raise HTTPGone(exc)
Beispiel #14
0
    def eos_tween(request):
        eos_date = registry.settings["eos"]
        eos_url = registry.settings["eos_url"]
        eos_message = registry.settings["eos_message"]
        if not eos_date:
            return handler(request)

        eos_date = dateparser.parse(eos_date)
        if eos_date > datetime.now():
            code = "soft-eol"
            request.response = handler(request)
        else:
            code = "hard-eol"
            request.response = errors.http_error(
                HTTPGone(), errno=errors.ERRORS.SERVICE_DEPRECATED, message=deprecation_msg
            )

        errors.send_alert(request, eos_message, url=eos_url, code=code)
        return request.response
Beispiel #15
0
def decrypt(ciphertext, settings):
    ttl = int(settings['captcha.ttl'])
    secret = settings['captcha.secret']
    engine = cryptography.fernet.Fernet(secret)

    if isinstance(ciphertext, six.text_type):
        ciphertext = ciphertext.encode('utf-8')

    try:
        ciphertext = base64.urlsafe_b64decode(ciphertext)
    except TypeError:
        raise HTTPNotFound("%s is garbage" % ciphertext)

    try:
        plaintext = engine.decrypt(ciphertext, ttl=ttl)
    except cryptography.fernet.InvalidToken:
        raise HTTPGone('captcha token is no longer valid')

    return plaintext.decode('utf-8')
Beispiel #16
0
 def make_response(self):
     request_id = self.request.matchdict['request_id']
     with self.manage_api as manage_api:
         request_case = self._get_request_case(manage_api, request_id)
         if request_case.status in ('new', 'registered'):
             body = ''
             status_code = 202
         elif request_case.status == 'finalized':
             self._check_request_case_expiry(request_case)
             cert_data = self._get_valid_cert_data(
                 manage_api, request_case)
             body = cert_data.cert_pem
             status_code = 200
         else:
             assert request_case.status == 'cancelled'
             raise HTTPGone(
                 'The specified remote certificate request case is cancelled.'
             )
     return Response(body,
                     status_code=status_code,
                     content_type='text/plain')
Beispiel #17
0
def invitation_claim(request):
    """ Action that awards a person a badge after scanning a qrcode. """

    settings = request.registry.settings

    if request.context.expires_on < datetime.now():
        return HTTPGone("That invitation is expired.")

    if not authenticated_userid(request):
        request.session['came_from'] = request.resource_url(
            request.context, 'claim')
        return HTTPFound(location=request.route_url('login'))

    person = request.db.get_person(person_email=authenticated_userid(request))

    # Check to see if the user already has the badge.
    if request.context.badge in [a.badge for a in person.assertions]:
        # TODO: Flash a message explaining that they already have the badge
        return HTTPFound(location=request.route_url('home'))

    result = request.db.add_assertion(request.context.badge_id, person.email,
                                      datetime.now())

    if fedmsg and settings.get('tahrir.use_fedmsg', False):
        badge = request.context.badge
        fedmsg.publish(modname="fedbadges",
                       topic="badge.award",
                       msg=dict(
                           badge=dict(
                               name=badge.name,
                               description=badge.description,
                               image_url=badge.image,
                           ),
                           user=dict(username=person.nickname,
                                     badges_user_id=person.id),
                       ))

    # TODO -- return them to a page that auto-exports their badges.
    # TODO -- flash and tell them they got the badge
    return HTTPFound(location=request.route_url('home'))
Beispiel #18
0
 def error(self):
     from pyramid.httpexceptions import HTTPGone
     return HTTPGone()
Beispiel #19
0
 def __call__(self, model, req):
     if model == Language:
         # responses for no longer supported legacy codes
         if req.matchdict['id'] in req.registry.settings['legacy_codes']:
             raise HTTPGone()
     return super(GLCtxFactoryQuery, self).__call__(model, req)
Beispiel #20
0
def _validate_visibility(context: IResource, request: IRequest):
    if request.method not in ['HEAD', 'GET', 'POST']:
        return
    block_reason = get_reason_if_blocked(context)
    if block_reason is not None:
        raise HTTPGone(detail=block_reason)