Exemplo n.º 1
0
    def test_ui_oauth2_refresh_token(self):
        actor_identity_obj = ActorIdentity(name="John Doe")
        actor_id = self.idm_client.create_actor_identity(actor_identity_obj)
        actor_name = "jdoe"
        actor_password = "******"
        self.idm_client.set_actor_credentials(actor_id, actor_name,
                                              actor_password)

        actor_details = UserIdentityDetails()
        actor_details.contact.individual_names_given = "John"
        actor_details.contact.individual_name_family = "Doe"
        self.idm_client.define_identity_details(actor_id, actor_details)

        client_obj = ActorIdentity(
            name="UI Client",
            details=OAuthClientIdentityDetails(default_scopes="scioncc"))
        client_actor_id = self.idm_client.create_actor_identity(client_obj)
        client_id = "ui"
        self.idm_client.set_actor_credentials(client_actor_id,
                                              "client:" + client_id,
                                              "client_secret")

        session = requests.session()

        log.info("------------ Get token")
        auth_params = {
            "client_id": client_id,
            "grant_type": "password",
            "username": actor_name,
            "password": actor_password
        }
        resp = session.post(self.ui_base_url + "/oauth/token",
                            data=auth_params)
        access_token = resp.json()

        log.info("------------ Refresh token")
        auth_params = {
            "client_id": client_id,
            "grant_type": "refresh_token",
            "refresh_token": access_token["refresh_token"]
        }
        resp = session.post(self.ui_base_url + "/oauth/token",
                            data=auth_params)
        updated_token = resp.json()

        self.assertIsNotNone(updated_token)
        self.assertNotIn("error", updated_token)
        for item in [
                "access_token", "token_type", "expires_in", "refresh_token",
                "scope"
        ]:
            self.assertIn(item, updated_token)
Exemplo n.º 2
0
    def on_initial_bootstrap(self, process, config, **kwargs):
        # Detect if system has been started before by the presence of the ION system actor
        system_actor, _ = process.container.resource_registry.find_resources(
            restype=RT.ActorIdentity, id_only=True)
        if system_actor:
            raise AbortBootstrap("System already initialized. Start with bootmode=restart or force_clean (-fc)!")

        # Possibly start the event persister here


        # Create ION actor
        actor_name = get_safe(config, "system.system_actor", "ionsystem")
        sys_actor = ActorIdentity(name=actor_name, description="ION System Agent")
        process.container.resource_registry.create(sys_actor)

        webauth_actor_name = get_safe(config, "system.web_authentication_actor", "web_authentication")
        web_auth_actor = ActorIdentity(name=webauth_actor_name, description="Web Authentication Actor")
        process.container.resource_registry.create(web_auth_actor)
Exemplo n.º 3
0
    def on_initial_bootstrap(self, process, config, **kwargs):
        # Detect if system has been started before by the presence of the ION system actor
        system_actor = get_system_actor()
        if system_actor:
            raise AbortBootstrap("System already initialized. Start with bootmode=restart or force_clean (-fc)!")

        # Create ION actor
        actor_name = get_safe(config, "system.system_actor", "ionsystem")
        sys_actor = ActorIdentity(name=actor_name, description="ION System Agent")
        process.container.resource_registry.create(sys_actor)
Exemplo n.º 4
0
    def test_ui_server(self):
        actor_identity_obj = ActorIdentity(name="John Doe")
        actor_id = self.idm_client.create_actor_identity(actor_identity_obj)
        self.idm_client.set_actor_credentials(actor_id, "jdoe", "mypasswd")

        actor_details = UserIdentityDetails()
        actor_details.contact.individual_names_given = "John"
        actor_details.contact.individual_name_family = "Doe"
        self.idm_client.define_identity_details(actor_id, actor_details)

        # TEST: Authentication
        self._do_test_authentication()

        # TEST: Service gateway
        self._do_test_service_gateway(actor_id)

        self.idm_client.delete_actor_identity(actor_id)
Exemplo n.º 5
0
    def test_actor_identity(self):
        # TEST: Create, Update, Read
        actor_identity_obj = ActorIdentity(name="John Doe")
        actor_id = self.identity_management_service.create_actor_identity(
            actor_identity_obj)

        actor_identity = self.identity_management_service.read_actor_identity(
            actor_id)
        self.assertEquals(actor_identity_obj.name, actor_identity.name)

        actor_identity.name = 'Updated name'
        self.identity_management_service.update_actor_identity(actor_identity)

        ai = self.identity_management_service.find_actor_identity_by_name(
            actor_identity.name)
        self.assertEquals(ai.name, actor_identity.name)
        with self.assertRaises(NotFound):
            ai = self.identity_management_service.find_actor_identity_by_name(
                "##FOO USER##")

        self.assertEquals(ai.name, actor_identity.name)

        # TEST: Actor credentials
        self._do_test_credentials(actor_id)

        # TEST: Identity details (user profile)
        self._do_test_profile(actor_id)

        # TEST: Password reset
        self._do_test_password_reset(actor_id)

        # TEST: Auth tokens
        self._do_test_auth_tokens(actor_id)

        # TEST: Delete
        self.identity_management_service.delete_actor_identity(actor_id)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.read_actor_identity(actor_id)
        self.assertTrue("does not exist" in cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.delete_actor_identity(actor_id)
        self.assertTrue("does not exist" in cm.exception.message)
    def _do_test_membership(self, org_id):
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        actor_obj = ActorIdentity(name="Test user")
        actor_id, _ = self.resource_registry.create(actor_obj)

        self.assertTrue(self.org_management_service.is_registered(actor_id))
        self.assertFalse(
            self.org_management_service.is_enrolled(org_id, actor_id))

        self.assertFalse(self.org_management_service.is_registered(org_id))
        self.assertFalse(self.org_management_service.is_registered("FOOBAR"))
        self.assertTrue(
            self.org_management_service.is_enrolled(root_org._id, actor_id))
        actor_objs = self.org_management_service.list_enrolled_actors(org_id)
        self.assertEquals(0, len(actor_objs))
        org_objs = self.org_management_service.list_orgs_for_actor(actor_id)
        self.assertEquals(1, len(org_objs))

        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(0, len(role_objs))
        self.assertFalse(
            self.org_management_service.has_role(org_id, actor_id,
                                                 MEMBER_ROLE))

        self.org_management_service.enroll_member(org_id, actor_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasMember,
                                                         RT.ActorIdentity,
                                                         id_only=True)
        self.assertEquals(1, len(res_ids))

        self.assertTrue(
            self.org_management_service.is_enrolled(org_id, actor_id))
        self.assertTrue(
            self.org_management_service.has_role(org_id, actor_id,
                                                 MEMBER_ROLE))
        self.assertFalse(
            self.org_management_service.has_role(org_id, actor_id,
                                                 OPERATOR_ROLE))

        actor_objs = self.org_management_service.list_enrolled_actors(org_id)
        self.assertEquals(1, len(actor_objs))
        org_objs = self.org_management_service.list_orgs_for_actor(actor_id)
        self.assertEquals(2, len(org_objs))

        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(1, len(role_objs))

        self.org_management_service.grant_role(org_id, actor_id, OPERATOR_ROLE)

        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(2, len(role_objs))
        self.assertTrue(
            self.org_management_service.has_role(org_id, actor_id,
                                                 OPERATOR_ROLE))

        self.org_management_service.revoke_role(org_id, actor_id,
                                                OPERATOR_ROLE)
        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(1, len(role_objs))

        self.org_management_service.cancel_member_enrollment(org_id, actor_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasMember,
                                                         RT.ActorIdentity,
                                                         id_only=True)
        self.assertEquals(0, len(res_ids))

        self.assertFalse(
            self.org_management_service.is_enrolled(org_id, actor_id))

        self.resource_registry.delete(actor_id)
    def _do_test_share_and_commitments(self, org_id):
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        actor_obj = ActorIdentity(name="Test user")
        actor_id, _ = self.resource_registry.create(actor_obj)

        self.org_management_service.enroll_member(org_id, actor_id)

        inst_obj = TestInstrument(name="Test instrument")
        inst_id, _ = self.resource_registry.create(inst_obj)

        self.assertFalse(
            self.org_management_service.is_resource_acquired(
                resource_id=inst_id))

        self.org_management_service.share_resource(org_id, inst_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasResource,
                                                         id_only=True)
        self.assertEquals(1, len(res_ids))

        cmt_id = self.org_management_service.create_resource_commitment(
            org_id, actor_id, inst_id)

        self.assertTrue(
            self.org_management_service.is_resource_acquired(
                resource_id=inst_id))
        self.assertFalse(
            self.org_management_service.is_resource_acquired_exclusively(
                resource_id=inst_id))

        cmt_objs = self.org_management_service.find_commitments(org_id=org_id)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            resource_id=inst_id)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            actor_id=actor_id)
        self.assertEquals(1, len(cmt_objs))

        res_objs = self.org_management_service.find_acquired_resources(
            org_id=org_id)
        self.assertEquals(1, len(res_objs))
        res_objs = self.org_management_service.find_acquired_resources(
            actor_id=actor_id)
        self.assertEquals(1, len(res_objs))

        cmt_id = self.org_management_service.create_resource_commitment(
            org_id,
            actor_id,
            inst_id,
            exclusive=True,
            expiration=get_ion_ts_millis() + 1000)

        self.assertTrue(
            self.org_management_service.is_resource_acquired(
                resource_id=inst_id))
        self.assertTrue(
            self.org_management_service.is_resource_acquired_exclusively(
                resource_id=inst_id))

        cmt_objs = self.org_management_service.find_commitments(org_id=org_id,
                                                                exclusive=True)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            resource_id=inst_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            actor_id=actor_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))

        self.org_management_service.unshare_resource(org_id, inst_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasResource,
                                                         id_only=True)
        self.assertEquals(0, len(res_ids))

        self.resource_registry.delete(inst_id)
        self.resource_registry.delete(actor_id)
Exemplo n.º 8
0
    def _do_test_service_gateway(self, actor_id):
        # We don't want to modify import order during testing, so import here
        from ion.services.service_gateway import SG_IDENTIFICATION

        session = requests.session()

        # TEST: Service gateway available
        resp = session.get(self.sg_base_url + "/")
        self._assert_json_response(resp, SG_IDENTIFICATION)

        # TEST: Login
        resp = session.post(self.ui_base_url + "/auth/login", data=dict(username="******", password="******"))
        resp_json = self._assert_json_response(resp, None)
        self.assertEquals("jdoe", resp_json["result"]["username"])

        # TEST: Service access
        resp = session.get(self.sg_base_url + "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True")
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        # Request as POST with JSON data
        payload = dict(data=json.dumps(dict(params=dict(restype="ActorIdentity", id_only=True))))
        resp = session.post(self.sg_base_url + "/request/resource_registry/find_resources", data=payload)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        # Request as POST with JSON data and no params
        payload = dict(data=json.dumps(dict(restype="ActorIdentity", id_only=True)))
        resp = session.post(self.sg_base_url + "/request/resource_registry/find_resources", data=payload)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        # Request as POST with params directly as form data
        payload = dict(restype="ActorIdentity", id_only=True)
        resp = session.post(self.sg_base_url + "/request/resource_registry/find_resources", data=payload)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        resp = session.get(self.sg_base_url + "/request/resource_registry/read/" + actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])

        # TEST: REST API
        resp = session.get(self.sg_base_url + "/rest/identity_management/actor_identity")
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, [o["_id"] for o in resp_json["result"]])
        num_actors = len(resp_json["result"])

        resp = session.get(self.sg_base_url + "/rest/identity_management/actor_identity/" + actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])

        # Form encoded create request
        other_actor_obj = ActorIdentity(name="Jane Foo")
        other_actor_obj.details = None
        other_actor_obj_dict = other_actor_obj.__dict__.copy()
        # Remove unseralizable attributes.
        del other_actor_obj_dict['passwd_reset_token']
        payload = dict(data=json.dumps(other_actor_obj_dict))
        resp = session.post(self.sg_base_url + "/rest/identity_management/actor_identity", data=payload)
        resp_json = self._assert_json_response(resp, None)
        other_actor_id = resp_json["result"]

        resp = session.get(self.sg_base_url + "/rest/identity_management/actor_identity")
        resp_json = self._assert_json_response(resp, None)
        self.assertEquals(len(resp_json["result"]), num_actors + 1)

        resp = session.get(self.sg_base_url + "/rest/identity_management/actor_identity/" + other_actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])
        self.assertEquals(other_actor_id, resp_json["result"]["_id"])

        # Form encoded update request
        resp_json["result"]["name"] = "Jane Long"
        payload = dict(data=json.dumps(resp_json["result"]))
        resp = session.put(self.sg_base_url + "/rest/identity_management/actor_identity/" + other_actor_id, data=payload)
        resp_json = self._assert_json_response(resp, None)

        resp = session.get(self.sg_base_url + "/rest/identity_management/actor_identity/" + other_actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])
        self.assertEquals("Jane Long", resp_json["result"]["name"])

        # JSON enconded request
        resp_json["result"]["name"] = "Jane Dunn"
        payload = json.dumps(resp_json["result"])
        resp = session.put(self.sg_base_url + "/rest/identity_management/actor_identity/" + other_actor_id, data=payload,
                           headers={'Content-Type': CONT_TYPE_JSON})
        resp_json = self._assert_json_response(resp, None)

        resp = session.get(self.sg_base_url + "/rest/identity_management/actor_identity/" + other_actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])
        self.assertEquals("Jane Dunn", resp_json["result"]["name"])
Exemplo n.º 9
0
    def _do_test_service_gateway(self, actor_id):
        # We don't want to modify import order during testing, so import here
        from ion.service.service_gateway import SG_IDENTIFICATION

        session = requests.session()

        # TEST: Service gateway available
        resp = session.get(self.sg_base_url + "/")
        self._assert_json_response(resp, SG_IDENTIFICATION)

        # TEST: Login
        resp = session.post(self.ui_base_url + "/auth/login",
                            data=dict(username="******", password="******"))
        resp_json = self._assert_json_response(resp, None)
        self.assertEquals("jdoe", resp_json["result"]["username"])

        # TEST: Service access
        resp = session.get(
            self.sg_base_url +
            "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True"
        )
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        # Request as POST with JSON data
        payload = dict(data=json.dumps(
            dict(params=dict(restype="ActorIdentity", id_only=True))))
        resp = session.post(self.sg_base_url +
                            "/request/resource_registry/find_resources",
                            data=payload)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        # Request as POST with JSON data and no params
        payload = dict(
            data=json.dumps(dict(restype="ActorIdentity", id_only=True)))
        resp = session.post(self.sg_base_url +
                            "/request/resource_registry/find_resources",
                            data=payload)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        # Request as POST with params directly as form data
        payload = dict(restype="ActorIdentity", id_only=True)
        resp = session.post(self.sg_base_url +
                            "/request/resource_registry/find_resources",
                            data=payload)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        resp = session.get(self.sg_base_url +
                           "/request/resource_registry/read/" + actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])

        # Request as POST with params directly as form data with files content
        payload = dict(id_only=True)
        files = dict(restype=("restype", "ActorIdentity"))
        resp = session.post(self.sg_base_url +
                            "/request/resource_registry/find_resources",
                            data=payload,
                            files=files)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, resp_json["result"][0])

        resp = session.get(self.sg_base_url +
                           "/request/resource_registry/read/" + actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])

        # TEST: REST API
        resp = session.get(self.sg_base_url +
                           "/rest/identity_management/actor_identity")
        resp_json = self._assert_json_response(resp, None)
        self.assertIn(actor_id, [o["_id"] for o in resp_json["result"]])
        num_actors = len(resp_json["result"])

        resp = session.get(self.sg_base_url +
                           "/rest/identity_management/actor_identity/" +
                           actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])

        # Form encoded create request
        other_actor_obj = ActorIdentity(name="Jane Foo")
        other_actor_obj.details = None
        other_actor_obj_dict = other_actor_obj.__dict__.copy()
        # Remove unseralizable attributes.
        del other_actor_obj_dict['passwd_reset_token']
        payload = dict(data=json.dumps(other_actor_obj_dict))
        resp = session.post(self.sg_base_url +
                            "/rest/identity_management/actor_identity",
                            data=payload)
        resp_json = self._assert_json_response(resp, None)
        other_actor_id = resp_json["result"]

        resp = session.get(self.sg_base_url +
                           "/rest/identity_management/actor_identity")
        resp_json = self._assert_json_response(resp, None)
        self.assertEquals(len(resp_json["result"]), num_actors + 1)

        resp = session.get(self.sg_base_url +
                           "/rest/identity_management/actor_identity/" +
                           other_actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])
        self.assertEquals(other_actor_id, resp_json["result"]["_id"])

        # Form encoded update request
        resp_json["result"]["name"] = "Jane Long"
        payload = dict(data=json.dumps(resp_json["result"]))
        resp = session.put(self.sg_base_url +
                           "/rest/identity_management/actor_identity/" +
                           other_actor_id,
                           data=payload)
        resp_json = self._assert_json_response(resp, None)

        resp = session.get(self.sg_base_url +
                           "/rest/identity_management/actor_identity/" +
                           other_actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])
        self.assertEquals("Jane Long", resp_json["result"]["name"])

        # JSON enconded request
        resp_json["result"]["name"] = "Jane Dunn"
        payload = json.dumps(resp_json["result"])
        resp = session.put(self.sg_base_url +
                           "/rest/identity_management/actor_identity/" +
                           other_actor_id,
                           data=payload,
                           headers={'Content-Type': CONT_TYPE_JSON})
        resp_json = self._assert_json_response(resp, None)

        resp = session.get(self.sg_base_url +
                           "/rest/identity_management/actor_identity/" +
                           other_actor_id)
        resp_json = self._assert_json_response(resp, None)
        self.assertIn("type_", resp_json["result"])
        self.assertEquals("Jane Dunn", resp_json["result"]["name"])
Exemplo n.º 10
0
    def test_ui_oauth2(self):
        actor_identity_obj = ActorIdentity(name="John Doe")
        actor_id = self.idm_client.create_actor_identity(actor_identity_obj)
        self.idm_client.set_actor_credentials(actor_id, "jdoe", "mypasswd")

        actor_details = UserIdentityDetails()
        actor_details.contact.individual_names_given = "John"
        actor_details.contact.individual_name_family = "Doe"
        self.idm_client.define_identity_details(actor_id, actor_details)

        client_obj = ActorIdentity(
            name="UI Client",
            details=OAuthClientIdentityDetails(default_scopes="scioncc"))
        client_actor_id = self.idm_client.create_actor_identity(client_obj)
        client_id = "ui"
        self.idm_client.set_actor_credentials(client_actor_id,
                                              "client:" + client_id,
                                              "client_secret")

        session = requests.session()

        # TEST: OAuth2 authorize
        log.info("------------ Get token #1")
        auth_params = {
            "client_id": client_id,
            "grant_type": "password",
            "username": "******",
            "password": "******"
        }
        resp = session.post(self.ui_base_url + "/oauth/token",
                            data=auth_params)
        access_token = resp.json()

        # TEST: Service access
        log.info("------------ Access with token")
        resp = session.get(
            self.sg_base_url +
            "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
            headers={
                "Authorization": "Bearer %s" % access_token["access_token"]
            })
        resp_json = self._assert_json_response(resp, None)
        #self.assertIn(actor_id, resp_json["result"][0])

        log.info("------------ Access with bad token")
        resp = session.get(
            self.sg_base_url +
            "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
            headers={"Authorization": "Bearer FOOBAR"})
        resp_json = self._assert_json_response(resp, None, status=401)

        # TEST: Get session using token
        log.info("------------ Get session using token")
        resp = session.get(self.ui_base_url + "/auth/session",
                           headers={
                               "Authorization":
                               "Bearer %s" % access_token["access_token"]
                           })
        resp_json = self._assert_json_response(resp, None)
        self.assertEqual(actor_id, resp_json["result"]["actor_id"])

        # TEST: Get new access token
        log.info("------------ Refresh token")
        auth_params = {
            "client_id": client_id,
            "grant_type": "refresh_token",
            "refresh_token": access_token["refresh_token"]
        }
        resp = session.post(self.ui_base_url + "/oauth/token",
                            data=auth_params)
        access_token1 = resp.json()

        with patch('ion.process.ui.server.ui_instance.session_timeout', 2):
            log.info("Patched server.session_timeout to %s",
                     self.ui_server_proc.session_timeout)

            session = requests.session()

            log.info("------------ Get token #2 (with short expiration)")
            auth_params = {
                "client_id": client_id,
                "grant_type": "password",
                "username": "******",
                "password": "******"
            }
            resp = session.post(self.ui_base_url + "/oauth/token",
                                data=auth_params)
            access_token = resp.json()

            # TEST: Service access
            log.info("------------ Access before expired")
            resp = session.get(
                self.sg_base_url +
                "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
                headers={
                    "Authorization": "Bearer %s" % access_token["access_token"]
                })
            resp_json = self._assert_json_response(resp, None)

            gevent.sleep(2)

            # TEST: Service access fails after expiration
            log.info("------------ Access after token expiration")
            resp = session.get(
                self.sg_base_url +
                "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
                headers={
                    "Authorization": "Bearer %s" % access_token["access_token"]
                })
            resp_json = self._assert_json_response(resp, None, status=401)


        with patch('ion.process.ui.server.ui_instance.session_timeout', 2), \
             patch('ion.process.ui.server.ui_instance.extend_session_timeout', True), \
             patch('ion.process.ui.server.ui_instance.max_session_validity', 3):

            session = requests.session()

            log.info("------------ Get token #3 (with short expiration)")
            auth_params = {
                "client_id": client_id,
                "grant_type": "password",
                "username": "******",
                "password": "******"
            }
            resp = session.post(self.ui_base_url + "/oauth/token",
                                data=auth_params)
            access_token = resp.json()

            gevent.sleep(1)

            # TEST: Service access extends expiration
            log.info(
                "------------ Access before expired should extend expiration")
            resp = session.get(
                self.sg_base_url +
                "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
                headers={
                    "Authorization": "Bearer %s" % access_token["access_token"]
                })
            resp_json = self._assert_json_response(resp, None)

            gevent.sleep(1.1)

            # TEST: Service access will fail unless was extended
            log.info("------------ Access before expired after extension")
            resp = session.get(
                self.sg_base_url +
                "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
                headers={
                    "Authorization": "Bearer %s" % access_token["access_token"]
                })
            resp_json = self._assert_json_response(resp, None)

            gevent.sleep(1.5)

            # TEST: Service access fails after max validity
            log.info("------------ Access after token expiration")
            resp = session.get(
                self.sg_base_url +
                "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
                headers={
                    "Authorization": "Bearer %s" % access_token["access_token"]
                })
            resp_json = self._assert_json_response(resp, None, status=401)

        # TEST: Remember user from within session
        session = requests.session()
        log.info("------------ Get token #4")
        auth_params = {
            "client_id": client_id,
            "grant_type": "password",
            "username": "******",
            "password": "******"
        }
        resp = session.post(self.ui_base_url + "/oauth/token",
                            data=auth_params)
        access_token = resp.json()

        # TEST: Get session without token tests remember user
        log.info("------------ Get session without token")
        resp = session.get(self.ui_base_url + "/auth/session")
        resp_json = self._assert_json_response(resp, None)
        self.assertEqual(actor_id, resp_json["result"]["actor_id"])

        # TEST: Logout
        log.info("------------ Logout")
        resp = session.get(self.ui_base_url + "/auth/logout",
                           headers={
                               "Authorization":
                               "Bearer %s" % access_token["access_token"]
                           })
        resp_json = self._assert_json_response(resp, None)
        self.assertEqual(resp_json["result"], "OK")

        # TEST: Get session without token after logout
        log.info("------------ Get session without token")
        resp = session.get(self.ui_base_url + "/auth/session")
        resp_json = self._assert_json_response(resp, None)
        self.assertEqual(resp_json["result"]["actor_id"], "")

        # TEST: Service access after logout
        log.info("------------ Access with token after logout")
        resp = session.get(
            self.sg_base_url +
            "/request/resource_registry/find_resources?restype=ActorIdentity&id_only=True",
            headers={
                "Authorization": "Bearer %s" % access_token["access_token"]
            })
        resp_json = self._assert_json_response(resp, None, 401)

        with patch('ion.process.ui.server.ui_instance.remember_user', False):
            session = requests.session()
            log.info("------------ Get token #5")
            auth_params = {
                "client_id": client_id,
                "grant_type": "password",
                "username": "******",
                "password": "******"
            }
            resp = session.post(self.ui_base_url + "/oauth/token",
                                data=auth_params)
            access_token = resp.json()

            # TEST: Get session without token fails if remember user is False
            log.info("------------ Get session without token")
            resp = session.get(self.ui_base_url + "/auth/session")
            resp_json = self._assert_json_response(resp, None)
            self.assertEqual(resp_json["result"]["actor_id"], "")
Exemplo n.º 11
0
 def on_init(self):
     res_obj = ActorIdentity(name="user1")
     rid,_ = self.clients.resource_registry.create(res_obj)
     agent_resources[self.id] = rid
     self.resource_id = rid
     agent_instances[self._proc_name] = self.id
Exemplo n.º 12
0
    def define_user(self,
                    user_id='',
                    first_name='',
                    last_name='',
                    username='',
                    password='',
                    email='',
                    attributes=None):
        if user_id:
            raise NotImplementedError("Update not supported: user_id=%s" %
                                      user_id)
        if not email:
            raise BadRequest('Email is required')
        username = username or email

        user = self._get_user_by_email(email)
        if user:
            raise BadRequest("Email already taken")

        if not username or not is_valid_identifier(username,
                                                   valid_chars=EMAIL_VALID):
            raise BadRequest("Argument username invalid: %s" % username)
        if attributes and type(attributes) is not dict:
            raise BadRequest("Argument attributes invalid type")
        if not first_name:
            first_name = username
        attributes = attributes or {}

        full_name = ("%s %s" %
                     (first_name, last_name)) if last_name else first_name

        IdentityUtils.check_password_policy(password)

        contact = ContactInformation(individual_names_given=first_name,
                                     individual_name_family=last_name,
                                     email=email)
        user_profile = UserIdentityDetails(contact=contact, profile=attributes)
        actor_obj = ActorIdentity(name=full_name, details=user_profile)

        # Support fast setting of credentials without expensive compute of bcrypt hash, for quick preload
        pwd_salt, pwd_hash = None, None
        if attributes and "scion_init_pwdsalt" in attributes and "scion_init_pwdhash" in attributes:
            pwd_salt, pwd_hash = attributes.pop(
                "scion_init_pwdsalt"), attributes.pop("scion_init_pwdhash")

        user_exists = self.idm_client.is_user_existing(username)
        if user_exists:
            raise BadRequest("Username already taken")

        actor_id = self.idm_client.create_actor_identity(actor_obj)

        if pwd_salt and pwd_hash:
            # Add to credentials
            actor_obj1 = self.rr.read(actor_id)
            cred_obj = None
            for cred in actor_obj1.credentials:
                if cred.username == username:
                    cred_obj = cred
                    break
            if not cred_obj:
                cred_obj = Credentials()
                cred_obj.username = username
                actor_obj1.credentials.append(cred_obj)
                actor_obj1.alt_ids.append("UNAME:" + username)
            cred_obj.identity_provider = "SciON"
            cred_obj.authentication_service = "SciON IdM"
            cred_obj.password_salt = pwd_salt
            cred_obj.password_hash = pwd_hash
            self.rr.update(actor_obj1)
        else:
            self.idm_client.set_actor_credentials(actor_id, username, password)

        return actor_id