コード例 #1
0
 def create_client(self):
     dataset = DictDBWrap(USERDB)
     client = Client({}, client_authn_methods=CLIENT_AUTHN_METHOD)
     self.rsh = ResourceSetHandler(dataset, client, "hans")
     self.rsh.dataset.scopes2op[
         'https://dirg.org.umu.se/uma/read'] = self.rsh.dataset.get
     self.rsh.client.provider_info = {
         "resource_set_registration_endpoint": 'https://as.example.com/rsr'
     }
     self.rsh.token["PAT"] = 'pat'
コード例 #2
0
ファイル: test_resourceset.py プロジェクト: simudream/pyuma
 def create_client(self):
     dataset = DictDBWrap(USERDB)
     client = Client({}, client_authn_methods=CLIENT_AUTHN_METHOD)
     self.rsh = ResourceSetHandler(dataset, client, "hans")
     self.rsh.dataset.scopes2op[
         'https://dirg.org.umu.se/uma/read'] = self.rsh.dataset.get
     self.rsh.client.provider_info = {
         "resource_set_registration_endpoint": 'https://as.example.com/rsr'}
     self.rsh.token["PAT"] = 'pat'
コード例 #3
0
ファイル: resourcesrv.py プロジェクト: simudream/pyuma
 def __init__(self,
              dataset,
              resource_owner,
              info_store,
              symkey="",
              client_id=None,
              ca_certs=None,
              client_authn_methods=None,
              keyjar=None,
              server_info=None,
              authz_page="",
              flow_type="",
              password=None,
              registration_info=None,
              response_type="",
              scope="",
              **kwargs):
     self.client = Client(client_id=client_id,
                          ca_certs=ca_certs,
                          client_authn_methods=client_authn_methods,
                          keyjar=keyjar,
                          server_info=server_info,
                          authz_page=authz_page,
                          flow_type=flow_type,
                          password=password,
                          registration_info=registration_info,
                          response_type=response_type,
                          scope=scope)
     self.rs_handler = ResourceSetHandler(dataset, self.client,
                                          resource_owner)
     self.info_store = info_store
     self.symkey = symkey
     self.kwargs = kwargs
     self.srv_discovery_url = ""
     self.cookie_handler = http_util.CookieDealer(self)
     self.cookie_name = "resourceserver"
     self.rsd_map = {}
     self.pat = None
コード例 #4
0
ファイル: test_resourceset.py プロジェクト: simudream/pyuma
class TestResourceSetHandler(object):
    @pytest.fixture(autouse=True)
    def create_client(self):
        dataset = DictDBWrap(USERDB)
        client = Client({}, client_authn_methods=CLIENT_AUTHN_METHOD)
        self.rsh = ResourceSetHandler(dataset, client, "hans")
        self.rsh.dataset.scopes2op[
            'https://dirg.org.umu.se/uma/read'] = self.rsh.dataset.get
        self.rsh.client.provider_info = {
            "resource_set_registration_endpoint": 'https://as.example.com/rsr'}
        self.rsh.token["PAT"] = 'pat'

    def test_register_init(self):
        res_set_desc = self.rsh.register_init()
        assert len(res_set_desc) == 5

    def test_create_rsd(self):
        res_set_desc = self.rsh.register_init()
        # http_args = {'headers': {'Authorization': auth}}
        for lid, _desc in res_set_desc.items():
            res = self.rsh.com_args(ResourceSetDescription, "POST",
                                    request_args=_desc,
                                    content_type=JSON_ENCODED)
            assert res["url"] == 'https://as.example.com/rsr/resource_set'
            assert res["http_args"] == {
                'headers': {'Content-Type': 'application/json',
                            'Authorization': 'Bearer pat'}}

    def test_first_args(self):
        # Used by read and delete
        args = self.rsh.first_args("123456")
        assert args["url"] == 'https://as.example.com/rsr/resource_set/123456'
        assert args["http_args"] == {'headers': {'Authorization': 'Bearer pat'}}

        # used by list
        args = self.rsh.first_args()
        assert args["url"] == 'https://as.example.com/rsr/resource_set'
        assert args["http_args"] == {'headers': {'Authorization': 'Bearer pat'}}

    def test_update_rsd(self):
        res_set_desc = self.rsh.register_init()
        _desc = res_set_desc[list(res_set_desc)[0]]
        res = self.rsh.com_args(ResourceSetDescription, "POST",
                                request_args=_desc, rsid="foo",
                                content_type=JSON_ENCODED)
        assert res["url"] == 'https://as.example.com/rsr/resource_set/foo'
        assert res["http_args"] == {
            'headers': {'Content-Type': 'application/json',
                        'Authorization': 'Bearer pat'}}
コード例 #5
0
ファイル: resourcesrv.py プロジェクト: simudream/pyuma
 def __init__(self, dataset, resource_owner, info_store, symkey="",
              client_id=None, ca_certs=None, client_authn_methods=None,
              keyjar=None, server_info=None, authz_page="", flow_type="",
              password=None, registration_info=None, response_type="",
              scope="", **kwargs):
     self.client = Client(client_id=client_id, ca_certs=ca_certs,
                          client_authn_methods=client_authn_methods,
                          keyjar=keyjar, server_info=server_info,
                          authz_page=authz_page,
                          flow_type=flow_type, password=password,
                          registration_info=registration_info,
                          response_type=response_type, scope=scope)
     self.rs_handler = ResourceSetHandler(dataset, self.client,
                                          resource_owner)
     self.info_store = info_store
     self.symkey = symkey
     self.kwargs = kwargs
     self.srv_discovery_url = ""
     self.cookie_handler = http_util.CookieDealer(self)
     self.cookie_name = "resourceserver"
     self.rsd_map = {}
     self.pat = None
コード例 #6
0
ファイル: resourcesrv.py プロジェクト: simudream/pyuma
class ResourceServer(object):
    def __init__(self,
                 dataset,
                 resource_owner,
                 info_store,
                 symkey="",
                 client_id=None,
                 ca_certs=None,
                 client_authn_methods=None,
                 keyjar=None,
                 server_info=None,
                 authz_page="",
                 flow_type="",
                 password=None,
                 registration_info=None,
                 response_type="",
                 scope="",
                 **kwargs):
        self.client = Client(client_id=client_id,
                             ca_certs=ca_certs,
                             client_authn_methods=client_authn_methods,
                             keyjar=keyjar,
                             server_info=server_info,
                             authz_page=authz_page,
                             flow_type=flow_type,
                             password=password,
                             registration_info=registration_info,
                             response_type=response_type,
                             scope=scope)
        self.rs_handler = ResourceSetHandler(dataset, self.client,
                                             resource_owner)
        self.info_store = info_store
        self.symkey = symkey
        self.kwargs = kwargs
        self.srv_discovery_url = ""
        self.cookie_handler = http_util.CookieDealer(self)
        self.cookie_name = "resourceserver"
        self.rsd_map = {}
        self.pat = None

    # def rs_request_info(self, msgtype, method=DEFAULT_METHOD,
    #                     authn_method="bearer_header", request_args=None,
    #                     extra_args=None):
    #
    #     return self.client.request_info(msgtype, method,
    #                                     request_args=request_args,
    #                                     extra_args=extra_args,
    #                                     authn_method=authn_method,
    #                                     content_type=JSON_ENCODED)

    @staticmethod
    def _get_bearer_token(authz):
        try:
            if authz.startswith("Bearer"):
                return authz[len("Bearer "):]
            else:
                return None
        except KeyError:
            return None

    def do_introspection(self, rpt, path=None):
        """
        The resource server doing introspection on a RPT at the AuthzServer

        :param rpt: Resource access token
        :param path: path representing the resource
        :returns:
        """

        pat = self.client.token
        ir = IntrospectionRequest(token=rpt)

        # if path:
        #     fpath = self.rs_handler.dataset.resource_name(path)
        #     ir["resource_id"] = self.rs_handler.path2rsid[fpath]

        request_args = {"access_token": pat}
        ht_args = self.client.client_authn_method["bearer_header"](
            self).construct(ir, request_args=request_args)

        url = list(
            self.client.provider_info.values())[0]["introspection_endpoint"]

        return self.client.request_and_return(url,
                                              IntrospectionResponse,
                                              body=ir.to_json(),
                                              body_type="json",
                                              http_args=ht_args)

    # ========================================================================
    # Below is the client API methods
    # ========================================================================
    def result(self, environ, start_response, result):
        resp = Response(mako_template="opresult.mako",
                        template_lookup=self.kwargs["template_lookup"],
                        headers=[])
        argv = {"result": result}
        return resp(environ, start_response, **argv)

    @staticmethod
    def filter_by_permission(intro, scope=None):
        """
        :param intro: An IntrospectionResponse instance
        :param scope: The scope that access is asked for
        :return: list of resource_set_description ids
        :rtype: list
        """

        rsids = []
        now = utc_time_sans_frac()
        try:
            assert now < intro["exp"]
        except KeyError:
            pass
        except AssertionError:
            return False

        for perm in intro["permissions"]:
            try:
                assert now < perm["exp"]
            except KeyError:
                pass
            except AssertionError:
                continue

            try:
                assert scope in perm["scopes"]
            except AssertionError:
                pass
            else:
                rsids.append(perm["resource_set_id"])

        return rsids

    def collect_info(self, introspection_response, scope):
        """
        :param introspection_response:
        :param scope:
        :return: Dictionary of attributes and values
        :rtype: dict
        """
        rsids = self.filter_by_permission(introspection_response, scope)

        # Collect information
        res = {}
        for rsid in rsids:
            lid = self.rs_handler.rsid2lid[rsid]
            part = lid.split(':')
            if len(part) == 2:  # every value for an attribute
                res[part[1]] = self.rs_handler.get_info(part[0], part[1])
            else:
                try:
                    res[part[1]].append(part[2])
                except KeyError:
                    res[part[1]] = [part[2]]

        return res

    # ----------------------------------------------------------------------
    # ----------------------------------------------------------------------
    def resource_endpoint(self, operation, path, auth=None, query=None):
        """
        This is where the client sends its requests.
        Assumes a HTTP interface.

        Three possible cases:
        - No RPT
        - A RPT that doesn't give the necessary access
        - A valid RPT

        :param auth: Authentication information, HTTP Authorization header
        :param operation: A HTTP operation: "GET","POST", ...
        :param path: The URL path
        :param query: A possible URL query part
        :return: HTTP response
        """

        rpt = self._get_bearer_token(auth)
        if auth is None:  # no RPT
            rssp = self.rs_handler.query2permission_registration_request_primer(
                operation, path, query)
        else:
            self.do_introspection(rpt)

        return Response
コード例 #7
0
ファイル: resourcesrv.py プロジェクト: simudream/pyuma
class ResourceServer(object):
    def __init__(self, dataset, resource_owner, info_store, symkey="",
                 client_id=None, ca_certs=None, client_authn_methods=None,
                 keyjar=None, server_info=None, authz_page="", flow_type="",
                 password=None, registration_info=None, response_type="",
                 scope="", **kwargs):
        self.client = Client(client_id=client_id, ca_certs=ca_certs,
                             client_authn_methods=client_authn_methods,
                             keyjar=keyjar, server_info=server_info,
                             authz_page=authz_page,
                             flow_type=flow_type, password=password,
                             registration_info=registration_info,
                             response_type=response_type, scope=scope)
        self.rs_handler = ResourceSetHandler(dataset, self.client,
                                             resource_owner)
        self.info_store = info_store
        self.symkey = symkey
        self.kwargs = kwargs
        self.srv_discovery_url = ""
        self.cookie_handler = http_util.CookieDealer(self)
        self.cookie_name = "resourceserver"
        self.rsd_map = {}
        self.pat = None

    # def rs_request_info(self, msgtype, method=DEFAULT_METHOD,
    #                     authn_method="bearer_header", request_args=None,
    #                     extra_args=None):
    #
    #     return self.client.request_info(msgtype, method,
    #                                     request_args=request_args,
    #                                     extra_args=extra_args,
    #                                     authn_method=authn_method,
    #                                     content_type=JSON_ENCODED)

    @staticmethod
    def _get_bearer_token(authz):
        try:
            if authz.startswith("Bearer"):
                return authz[len("Bearer "):]
            else:
                return None
        except KeyError:
            return None

    def do_introspection(self, rpt, path=None):
        """
        The resource server doing introspection on a RPT at the AuthzServer

        :param rpt: Resource access token
        :param path: path representing the resource
        :returns:
        """

        pat = self.client.token
        ir = IntrospectionRequest(token=rpt)

        # if path:
        #     fpath = self.rs_handler.dataset.resource_name(path)
        #     ir["resource_id"] = self.rs_handler.path2rsid[fpath]

        request_args = {"access_token": pat}
        ht_args = self.client.client_authn_method[
            "bearer_header"](self).construct(ir, request_args=request_args)

        url = list(self.client.provider_info.values())[0][
            "introspection_endpoint"]

        return self.client.request_and_return(url, IntrospectionResponse,
                                              body=ir.to_json(),
                                              body_type="json",
                                              http_args=ht_args)

    # ========================================================================
    # Below is the client API methods
    # ========================================================================
    def result(self, environ, start_response, result):
        resp = Response(mako_template="opresult.mako",
                        template_lookup=self.kwargs["template_lookup"],
                        headers=[])
        argv = {
            "result": result
        }
        return resp(environ, start_response, **argv)

    @staticmethod
    def filter_by_permission(intro, scope=None):
        """
        :param intro: An IntrospectionResponse instance
        :param scope: The scope that access is asked for
        :return: list of resource_set_description ids
        :rtype: list
        """

        rsids = []
        now = utc_time_sans_frac()
        try:
            assert now < intro["exp"]
        except KeyError:
            pass
        except AssertionError:
            return False

        for perm in intro["permissions"]:
            try:
                assert now < perm["exp"]
            except KeyError:
                pass
            except AssertionError:
                continue

            try:
                assert scope in perm["scopes"]
            except AssertionError:
                pass
            else:
                rsids.append(perm["resource_set_id"])

        return rsids

    def collect_info(self, introspection_response, scope):
        """
        :param introspection_response:
        :param scope:
        :return: Dictionary of attributes and values
        :rtype: dict
        """
        rsids = self.filter_by_permission(introspection_response, scope)

        # Collect information
        res = {}
        for rsid in rsids:
            lid = self.rs_handler.rsid2lid[rsid]
            part = lid.split(':')
            if len(part) == 2:  # every value for an attribute
                res[part[1]] = self.rs_handler.get_info(part[0], part[1])
            else:
                try:
                    res[part[1]].append(part[2])
                except KeyError:
                    res[part[1]] = [part[2]]

        return res

    # ----------------------------------------------------------------------
    # ----------------------------------------------------------------------
    def resource_endpoint(self, operation, path, auth=None, query=None):
        """
        This is where the client sends its requests.
        Assumes a HTTP interface.

        Three possible cases:
        - No RPT
        - A RPT that doesn't give the necessary access
        - A valid RPT

        :param auth: Authentication information, HTTP Authorization header
        :param operation: A HTTP operation: "GET","POST", ...
        :param path: The URL path
        :param query: A possible URL query part
        :return: HTTP response
        """

        rpt = self._get_bearer_token(auth)
        if auth is None:  # no RPT
            rssp = self.rs_handler.query2permission_registration_request_primer(
                operation, path, query)
        else:
            self.do_introspection(rpt)

        return Response
コード例 #8
0
class TestResourceSetHandler(object):
    @pytest.fixture(autouse=True)
    def create_client(self):
        dataset = DictDBWrap(USERDB)
        client = Client({}, client_authn_methods=CLIENT_AUTHN_METHOD)
        self.rsh = ResourceSetHandler(dataset, client, "hans")
        self.rsh.dataset.scopes2op[
            'https://dirg.org.umu.se/uma/read'] = self.rsh.dataset.get
        self.rsh.client.provider_info = {
            "resource_set_registration_endpoint": 'https://as.example.com/rsr'
        }
        self.rsh.token["PAT"] = 'pat'

    def test_register_init(self):
        res_set_desc = self.rsh.register_init()
        assert len(res_set_desc) == 5

    def test_create_rsd(self):
        res_set_desc = self.rsh.register_init()
        # http_args = {'headers': {'Authorization': auth}}
        for lid, _desc in res_set_desc.items():
            res = self.rsh.com_args(ResourceSetDescription,
                                    "POST",
                                    request_args=_desc,
                                    content_type=JSON_ENCODED)
            assert res["url"] == 'https://as.example.com/rsr/resource_set'
            assert res["http_args"] == {
                'headers': {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer pat'
                }
            }

    def test_first_args(self):
        # Used by read and delete
        args = self.rsh.first_args("123456")
        assert args["url"] == 'https://as.example.com/rsr/resource_set/123456'
        assert args["http_args"] == {
            'headers': {
                'Authorization': 'Bearer pat'
            }
        }

        # used by list
        args = self.rsh.first_args()
        assert args["url"] == 'https://as.example.com/rsr/resource_set'
        assert args["http_args"] == {
            'headers': {
                'Authorization': 'Bearer pat'
            }
        }

    def test_update_rsd(self):
        res_set_desc = self.rsh.register_init()
        _desc = res_set_desc[list(res_set_desc)[0]]
        res = self.rsh.com_args(ResourceSetDescription,
                                "POST",
                                request_args=_desc,
                                rsid="foo",
                                content_type=JSON_ENCODED)
        assert res["url"] == 'https://as.example.com/rsr/resource_set/foo'
        assert res["http_args"] == {
            'headers': {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer pat'
            }
        }