Exemple #1
0
    def registration_endpoint(self, request, authn=None, **kwargs):
        logger.debug("@registration_endpoint: <<{}>>".format(
            sanitize(request)))

        if isinstance(request, dict):
            request = ClientMetadataStatement(**request)
        else:
            try:
                request = ClientMetadataStatement().deserialize(
                    request, "json")
            except ValueError:
                request = ClientMetadataStatement().deserialize(request)

        logger.info("registration_request:{}".format(
            sanitize(request.to_dict())))

        request_args = self.get_metadata_statement(request)
        request = RegistrationRequest(**request_args)

        result = self.client_registration_setup(request)
        if isinstance(result, Response):
            return result

        return Created(result.to_json(),
                       content="application/json",
                       headers=[("Cache-Control", "no-store")])
Exemple #2
0
    def registration_endpoint(self, request, authn=None, **kwargs):
        logger.debug("@registration_endpoint: <<{}>>".format(
            sanitize(request)))

        if isinstance(request, dict):
            request = ClientMetadataStatement(**request)
        else:
            try:
                request = ClientMetadataStatement().deserialize(
                    request, "json")
            except ValueError:
                request = ClientMetadataStatement().deserialize(request)

        logger.info("registration_request:{}".format(
            sanitize(request.to_dict())))

        res = self.federation_entity.get_metadata_statement(request)

        if res:
            request = self.federation_entity.pick_by_priority(res)
        else:  # Nothing I can use
            return error(error='invalid_request',
                         descr='No signed metadata statement I could use')

        result = self.client_registration_setup(request)
        if isinstance(result, Response):
            return result

        return Created(result.to_json(),
                       content="application/json",
                       headers=[("Cache-Control", "no-store")])
Exemple #3
0
    def store(self, qiss, qtag, info):
        """

        :param qiss: OP issuer qoute_plus converted
        :param qtag: test instance tag quote_plus converted
        :param info: test instance configuration as JSON document
        :return: HTTP Created is successful
        """
        self.write(qiss, qtag, info)
        fname = '{}{}/{}'.format(self.base_url, qiss, qtag)
        return Created(fname)
Exemple #4
0
    def permission_registration_endpoint_(self, entity, **kwargs):
        """
        The endpoint URI at which the resource server registers a
        client-requested permission with the authorization server.
        This is a proposed permission waiting for the user to accept it.
        """
        request = kwargs["request"]
        _ticket = rndstr(24)
        logging.debug("Registering permission request: %s" % request)
        resp = PermissionRegistrationResponse(ticket=_ticket)
        self.permission_requests.add_request(_ticket, request)

        return Created(resp.to_json(), content="application/json")
Exemple #5
0
    def registration_endpoint(self, request, authn=None, **kwargs):
        """

        :param request:
        :param authn:
        :param kwargs:
        :return:
        """
        logger.debug("@registration_endpoint: <<{}>>".format(sanitize(request)))

        if isinstance(request, dict):
            request = ClientMetadataStatement(**request)
        else:
            try:
                request = ClientMetadataStatement().deserialize(request, "json")
            except ValueError:
                request = ClientMetadataStatement().deserialize(request)

        try:
            request.verify()
        except Exception as err:
            return error('Invalid request')

        logger.info(
            "registration_request:{}".format(sanitize(request.to_dict())))

        ms_list = self.federation_entity.get_metadata_statement(request,
                                                                'registration')

        if ms_list:
            ms = self.federation_entity.pick_by_priority(ms_list)
            self.federation = ms.fo
        else:  # Nothing I can use
            return error(error='invalid_request',
                         descr='No signed metadata statement I could use')

        request = RegistrationRequest(**ms.le)
        result = self.client_registration_setup(request)

        if isinstance(result, Response):
            return result

        # TODO This is where the OP should sign the response
        if ms.fo:
            _fo = ms.fo
            sms = self.signer.create_signed_metadata_statement(
                result, 'response', [_fo], single=True)
            self.federation_entity.extend_with_ms(result, {_fo: sms})

        return Created(result.to_json(), content="application/json",
                       headers=[("Cache-Control", "no-store")])
Exemple #6
0
    def permission_registration_endpoint_(self, request, **kwargs):
        """
        The endpoint URI at which the resource server registers a
        client-requested permission with the authorization server.
        This is a proposed permission waiting for the user to accept it.

        :param request: The permission registration request
        :return: HTTP Response
        """

        adb = self.get_adb(kwargs['client_id'])
        prr = self.to_prr(request, kwargs['client_id'])
        if prr:
            _ticket = adb.ticket_factory.pack(aud=[kwargs['client_id']],
                                              type='ticket')
            logging.debug("Registering permission request: %s" % request)
            adb.permission_requests[_ticket] = prr
            resp = PermissionRegistrationResponse(ticket=_ticket)

            return Created(resp.to_json(), content="application/json")
        else:
            return BadRequest("Can't register permission for unknown resource")
Exemple #7
0
    def registration_endpoint(self, request, authn=None, **kwargs):
        """
        Registration endpoint. This is where a registration request should
        be handled.

        :param request: The request, either as a dictionary or as a JSON
            document
        :param authn: Authentication information
        :param kwargs: Extra key work arguments.
        :return: A request response or an error response.
        """
        logger.debug("@registration_endpoint: <<{}>>".format(
            sanitize(request)))

        if isinstance(request, dict):
            request = ClientMetadataStatement(**request)
        else:
            try:
                request = ClientMetadataStatement().deserialize(
                    request, "json")
            except ValueError:
                request = ClientMetadataStatement().deserialize(request)

        if not self.is_federation_request(request):
            return provider.Provider.registration_endpoint(self,
                                                           request.to_json(),
                                                           authn=None,
                                                           **kwargs)

        try:
            request.verify()
        except Exception as err:
            return error('Invalid request')

        logger.info("registration_request:{}".format(
            sanitize(request.to_dict())))

        les = self.federation_entity.get_metadata_statement(
            request, 'registration')

        if les:
            ms = self.federation_entity.pick_by_priority(les)
            self.federation = ms.fo
        else:  # Nothing I can use
            return error(error='invalid_request',
                         descr='No signed metadata statement I could use')

        _pc = ms.protected_claims()
        if _pc:
            request = RegistrationRequest(**_pc)
        else:
            request = RegistrationRequest(
                **ms.unprotected_and_protected_claims())
        result = self.client_registration_setup(request)
        if 'signed_jwks_uri' in _pc:
            _kb = KeyBundle(source=_pc['signed_jwks_uri'],
                            verify_keys=ms.signing_keys,
                            verify_ssl=False)
            _kb.do_remote()
            replace_jwks_key_bundle(self.keyjar, result['client_id'], _kb)
            result['signed_jwks_uri'] = _pc['signed_jwks_uri']

        if isinstance(result, Response):
            return result

        # TODO This is where the OP should sign the response
        if ms.fo:
            _fo = ms.fo
            _sig = self._signer()

            if _sig:
                sms = _sig.create_signed_metadata_statement(result,
                                                            'response', [_fo],
                                                            single=True)
            else:
                raise SigningServiceError('No Signer')

            self.federation_entity.extend_with_ms(result, {_fo: sms})

        return Created(result.to_json(),
                       content="application/json",
                       headers=[("Cache-Control", "no-store")])
Exemple #8
0
    def resource_set_registration_endpoint_(self,
                                            entity,
                                            path,
                                            method,
                                            client_id,
                                            body="",
                                            if_match="",
                                            **kwargs):
        """
        The endpoint at which the resource server handles resource sets
        descriptions.

        :param entity: The entity that controls the resource set
        :param path:
        :param method: HTTP method
        :param body: The resource set registration message
        :paran client_id: Which client I'm talking to
        :param if_match: The HTTP If-Match header if any
        :param kwargs: possible other arguments
        :returns: A Response instance
        """

        # path should be /resource_set/{rsid} or /resource_set
        # Path may or may not start with '/'
        if path.startswith("/"):
            assert path[1:].startswith(RSR_PATH)
            rsid = path[PLEN + 1:]
        else:
            assert path.startswith(RSR_PATH)
            rsid = path[PLEN:]

        if rsid.startswith("/"):
            rsid = rsid[1:]

        _user = safe_name(entity, client_id)
        logger.debug("handling resource set belonging to '%s'" % _user)
        #  self.resource_set.set_collection(_user)
        if method == "POST":  # create
            args = {"oid": _user, "data": body}
            func = self.resource_set.create
        elif method == "PUT":  # update
            args = {
                "oid": _user,
                "data": body,
                "rsid": rsid,
                # "if_match": if_match
            }
            func = self.resource_set.update
        elif method == "GET":
            args = {"oid": _user}
            if not rsid:  # List
                func = self.resource_set.list
            else:  # Read
                func = self.resource_set.read
                args["rsid"] = rsid
        elif method == "DELETE":
            args = {"rsid": rsid, "oid": _user}
            func = self.resource_set.delete
        else:
            return BadRequest("Message error")

        logger.debug("operation: %s" % func)
        logger.debug("operation args: %s" % (args, ))
        try:
            body = func(**args)
        except MessageException as err:
            _err = ErrorResponse(error="invalid_request",
                                 error_description=str(err))
            response = BadRequest(_err.to_json(), content="application/json")
        except UnknownObject:
            _err = ErrorResponse(error="not_found")
            response = NotFound(_err.to_json(), content="application/json")
        else:
            response = None
            if isinstance(body, ErrorResponse):
                pass
            else:
                if func == self.resource_set.delete:
                    # As a side effect all permissions assigned that references
                    # this resource set should be deleted
                    self.permit.delete_permit_by_resource_id(entity, rsid)
                    response = NoContent()
                elif func == self.resource_set.create:
                    _etag = self.resource_set.etag[body["_id"]]
                    response = Created(body.to_json(),
                                       content="application/json",
                                       headers=[("ETag", _etag),
                                                ("Location", "/{}/{}".format(
                                                    RSR_PATH, body["_id"]))])
                elif func == self.resource_set.update:
                    _etag = self.resource_set.etag[body["_id"]]
                    response = NoContent(content="application/json",
                                         headers=[("ETag", _etag)])
                elif func == self.resource_set.list:
                    response = Response(json.dumps(body))

            if not response:
                response = Response(body.to_json(), content="application/json")

        return response