def test_non_anonymous_resource_registry_operations_with_token(self):
        rr = self.container.resource_registry
        id_client = IdentityManagementServiceClient()

        create_request = {
            "serviceRequest": {
                "serviceName": "resource_registry",
                "serviceOp": "create",
                "params": {
                    "object": {
                        "name": "Instrument1",
                        "type_": "InstrumentDevice"
                    }
                }
            }
        }

        # Create without actor
        response = self.test_app.post(
            '/ion-service/resource_registry/create',
            {'payload': simplejson.dumps(create_request)})
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertGreaterEqual(len(response_data[0]),
                                20)  # This is a resource_id
        inst_id = str(response_data[0])

        inst_obj = rr.read(inst_id)
        self.assertEquals(inst_obj.type_, RT.InstrumentDevice)
        self.assertEquals(inst_obj.name, "Instrument1")
        self.assertEquals(inst_obj.visibility, ResourceVisibilityEnum.PUBLIC)

        act_objs, assocs = rr.find_objects(inst_id,
                                           PRED.hasOwner,
                                           RT.ActorIdentity,
                                           id_only=False)
        self.assertEquals(len(act_objs), 0)

        # Anonymous query shows PUBLIC visibility resource anymore
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True'
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        inst_obj.visibility = ResourceVisibilityEnum.OWNER
        rr.update(inst_obj)

        # Now the anonymous query should not show the resource anymore
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True'
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        rr.delete(inst_id)

        # Create with actor
        actor_id, valid_until, registered = id_client.signon(
            USER1_CERTIFICATE, True)

        create_request = {
            "serviceRequest": {
                "serviceName": "resource_registry",
                "serviceOp": "create",
                "requester": actor_id,
                "params": {
                    "object": {
                        "name": "Instrument1",
                        "type_": "InstrumentDevice",
                        "visibility": ResourceVisibilityEnum.OWNER
                    }
                }
            }
        }

        response = self.test_app.post(
            '/ion-service/resource_registry/create',
            {'payload': simplejson.dumps(create_request)})
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertGreaterEqual(len(response_data[0]),
                                20)  # This is a resource_id
        inst_id = str(response_data[0])

        inst_obj = rr.read(inst_id)
        self.assertEquals(inst_obj.type_, RT.InstrumentDevice)
        self.assertEquals(inst_obj.name, "Instrument1")
        self.assertEquals(inst_obj.visibility, ResourceVisibilityEnum.OWNER)

        act_objs, assocs = rr.find_objects(inst_id,
                                           PRED.hasOwner,
                                           RT.ActorIdentity,
                                           id_only=False)
        self.assertEquals(len(act_objs), 1)
        self.assertEquals(act_objs[0]._id, actor_id)

        # Anonymous query should not show the resource anymore
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True'
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        # Authenticated request with owner shows resource
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&requester='
            + actor_id)
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        token_str = id_client.create_authentication_token(actor_id, validity=2)

        # Request with authentication token for owner shows resource
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken='
            + token_str)
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        gevent.sleep(2.1)

        # Request with expired authentication token for owner does not show resource (no error though)
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken='
            + token_str)
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        # Request with valid authentication token for different user does not show resource
        actor_id2, _ = rr.create(IonObject(RT.ActorIdentity, name="Actor2"))
        token_str2 = id_client.create_authentication_token(actor_id2,
                                                           validity=2)

        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken='
            + token_str2)
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        token_str3 = id_client.create_authentication_token(actor_id,
                                                           validity=2)

        # Request with new authentication token for owner shows resource
        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken='
            + token_str3)
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        id_client.invalidate_authentication_token(token_str3)

        response = self.test_app.get(
            '/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken='
            + token_str3)
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json['data'])
        response_data = response.json['data'][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        # Cleanup
        rr.delete(inst_id)
        rr.delete(actor_id2)
        id_client.delete_actor_identity(actor_id)
    def test_non_anonymous_resource_registry_operations_with_token(self):
        rr = self.container.resource_registry
        id_client = IdentityManagementServiceClient()

        create_request = {
            "serviceRequest": {
                "serviceName": "resource_registry",
                "serviceOp": "create",
                "params": {"object": {"name": "Instrument1", "type_": "InstrumentDevice"}},
            }
        }

        # Create without actor
        response = self.test_app.post(
            "/ion-service/resource_registry/create", {"payload": simplejson.dumps(create_request)}
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertGreaterEqual(len(response_data[0]), 20)  # This is a resource_id
        inst_id = str(response_data[0])

        inst_obj = rr.read(inst_id)
        self.assertEquals(inst_obj.type_, RT.InstrumentDevice)
        self.assertEquals(inst_obj.name, "Instrument1")
        self.assertEquals(inst_obj.visibility, ResourceVisibilityEnum.PUBLIC)

        act_objs, assocs = rr.find_objects(inst_id, PRED.hasOwner, RT.ActorIdentity, id_only=False)
        self.assertEquals(len(act_objs), 0)

        # Anonymous query shows PUBLIC visibility resource anymore
        response = self.test_app.get("/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True")
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        inst_obj.visibility = ResourceVisibilityEnum.OWNER
        rr.update(inst_obj)

        # Now the anonymous query should not show the resource anymore
        response = self.test_app.get("/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True")
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        rr.delete(inst_id)

        # Create with actor
        actor_id, valid_until, registered = id_client.signon(USER1_CERTIFICATE, True)

        create_request = {
            "serviceRequest": {
                "serviceName": "resource_registry",
                "serviceOp": "create",
                "requester": actor_id,
                "params": {
                    "object": {
                        "name": "Instrument1",
                        "type_": "InstrumentDevice",
                        "visibility": ResourceVisibilityEnum.OWNER,
                    }
                },
            }
        }

        response = self.test_app.post(
            "/ion-service/resource_registry/create", {"payload": simplejson.dumps(create_request)}
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertGreaterEqual(len(response_data[0]), 20)  # This is a resource_id
        inst_id = str(response_data[0])

        inst_obj = rr.read(inst_id)
        self.assertEquals(inst_obj.type_, RT.InstrumentDevice)
        self.assertEquals(inst_obj.name, "Instrument1")
        self.assertEquals(inst_obj.visibility, ResourceVisibilityEnum.OWNER)

        act_objs, assocs = rr.find_objects(inst_id, PRED.hasOwner, RT.ActorIdentity, id_only=False)
        self.assertEquals(len(act_objs), 1)
        self.assertEquals(act_objs[0]._id, actor_id)

        # Anonymous query should not show the resource anymore
        response = self.test_app.get("/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True")
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        # Authenticated request with owner shows resource
        response = self.test_app.get(
            "/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&requester=" + actor_id
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        token_str = id_client.create_authentication_token(actor_id, validity=2)

        # Request with authentication token for owner shows resource
        response = self.test_app.get(
            "/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken=" + token_str
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        gevent.sleep(2.1)

        # Request with expired authentication token for owner does not show resource (no error though)
        response = self.test_app.get(
            "/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken=" + token_str
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        # Request with valid authentication token for different user does not show resource
        actor_id2, _ = rr.create(IonObject(RT.ActorIdentity, name="Actor2"))
        token_str2 = id_client.create_authentication_token(actor_id2, validity=2)

        response = self.test_app.get(
            "/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken=" + token_str2
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        token_str3 = id_client.create_authentication_token(actor_id, validity=2)

        # Request with new authentication token for owner shows resource
        response = self.test_app.get(
            "/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken=" + token_str3
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 1)
        self.assertEqual(len(response_data[1]), 1)
        self.assertEqual(response_data[0][0], inst_id)

        id_client.invalidate_authentication_token(token_str3)

        response = self.test_app.get(
            "/ion-service/resource_registry/find_resources?name=Instrument1&id_only=True&authtoken=" + token_str3
        )
        self.check_response_headers(response)
        self.assertIn(GATEWAY_RESPONSE, response.json["data"])
        response_data = response.json["data"][GATEWAY_RESPONSE]
        self.assertEqual(len(response_data), 2)
        self.assertEqual(len(response_data[0]), 0)

        # Cleanup
        rr.delete(inst_id)
        rr.delete(actor_id2)
        id_client.delete_actor_identity(actor_id)
class TestIdentityManagementServiceInt(IonIntegrationTestCase):
    
    def setUp(self):
        self.subject = "/DC=org/DC=cilogon/C=US/O=ProtectNetwork/CN=Roger Unwin A254"

        # Start container
        self._start_container()
        self.container.start_rel_from_url('res/deploy/r2deploy.yml')

        self.resource_registry = ResourceRegistryServiceClient()
        self.identity_management_service = IdentityManagementServiceClient()
        self.org_client = OrgManagementServiceClient()

    def test_actor_identity(self):
        actor_identity_obj = IonObject("ActorIdentity", {"name": self.subject})        
        user_id = self.identity_management_service.create_actor_identity(actor_identity_obj)

        actor_identity = self.identity_management_service.read_actor_identity(user_id)

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

        ai = self.identity_management_service.find_actor_identity_by_name(actor_identity.name)
        self._baseAssertEqual(ai.name, actor_identity.name)
        with self.assertRaises(NotFound):
            ai = self.identity_management_service.find_actor_identity_by_name("Yeah, well, you know, that's just, like, your opinion, man.")

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

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

    def test_user_credentials(self):
        actor_identity_obj = IonObject("ActorIdentity", {"name": self.subject})        
        user_id = self.identity_management_service.create_actor_identity(actor_identity_obj)

        user_credentials_obj = IonObject("UserCredentials", {"name": self.subject})        
        self.identity_management_service.register_user_credentials(user_id, user_credentials_obj)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.unregister_user_credentials("bad", self.subject)
        self.assertTrue("does not exist" in cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.unregister_user_credentials(user_id, "bad")
        self.assertTrue("does not exist" in cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.unregister_user_credentials('bad', 'bad')
        self.assertTrue("does not exist" in cm.exception.message)

        self.identity_management_service.unregister_user_credentials(user_id, self.subject)

        self.identity_management_service.delete_actor_identity(user_id)




    def test_user_info(self):
        actor_identity_obj = IonObject("ActorIdentity", {"name": self.subject})
        user_id = self.identity_management_service.create_actor_identity(actor_identity_obj)

        user_credentials_obj = IonObject("UserCredentials", {"name": self.subject})
        self.identity_management_service.register_user_credentials(user_id, user_credentials_obj)

        user_info_obj = IonObject("UserInfo", {"name": "Foo"})
        user_info = self.identity_management_service.create_user_info(user_id, user_info_obj)

        with self.assertRaises(Conflict) as cm:
            self.identity_management_service.create_user_info(user_id, user_info_obj)
        self.assertTrue("UserInfo already exists for user id" in cm.exception.message)

        user_info_obj = self.identity_management_service.find_user_info_by_id(user_id)

        user_info_obj = self.identity_management_service.find_user_info_by_name("Foo")

        user_info_obj = self.identity_management_service.find_user_info_by_subject(self.subject)

        user_info_obj = self.identity_management_service.read_user_info(user_info)

        user_info_obj.name = 'Jane Doe'

        self.identity_management_service.update_user_info(user_info_obj)

        self.identity_management_service.delete_user_info(user_info)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.read_user_info(user_info)
        self.assertTrue('does not exist' in cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.delete_user_info(user_info)
        self.assertTrue('does not exist' in cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.find_user_info_by_name("John Doe")
        self.assertEqual(cm.exception.message, 'UserInfo with name John Doe does not exist')

        with self.assertRaises(NotFound) as cm:
            self.identity_management_service.find_user_info_by_subject("Bogus subject")
        self.assertEqual(cm.exception.message, "UserCredentials with subject Bogus subject does not exist")

        self.identity_management_service.unregister_user_credentials(user_id, self.subject)

        self.identity_management_service.delete_actor_identity(user_id)


    def test_signon(self):
        certificate =  """-----BEGIN CERTIFICATE-----
MIIEMzCCAxugAwIBAgICBQAwDQYJKoZIhvcNAQEFBQAwajETMBEGCgmSJomT8ixkARkWA29yZzEX
MBUGCgmSJomT8ixkARkWB2NpbG9nb24xCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdDSUxvZ29uMRsw
GQYDVQQDExJDSUxvZ29uIEJhc2ljIENBIDEwHhcNMTAxMTE4MjIyNTA2WhcNMTAxMTE5MTAzMDA2
WjBvMRMwEQYKCZImiZPyLGQBGRMDb3JnMRcwFQYKCZImiZPyLGQBGRMHY2lsb2dvbjELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlByb3RlY3ROZXR3b3JrMRkwFwYDVQQDExBSb2dlciBVbndpbiBBMjU0
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6QhsWxhUXbIxg+1ZyEc7d+hIGvchVmtb
g0kKLmivgoVsA4U7swNDRH6svW242THta0oTf6crkRx7kOKg6jma2lcAC1sjOSddqX7/92ChoUPq
7LWt2T6GVVA10ex5WAeB/o7br/Z4U8/75uCBis+ru7xEDl09PToK20mrkcz9M4HqIv1eSoPkrs3b
2lUtQc6cjuHRDU4NknXaVMXTBHKPM40UxEDHJueFyCiZJFg3lvQuSsAl4JL5Z8pC02T8/bODBuf4
dszsqn2SC8YDw1xrujvW2Bd7Q7BwMQ/gO+dZKM1mLJFpfEsR9WrjMeg6vkD2TMWLMr0/WIkGC8u+
6M6SMQIDAQABo4HdMIHaMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgSwMBMGA1UdJQQMMAoG
CCsGAQUFBwMCMBgGA1UdIAQRMA8wDQYLKwYBBAGCkTYBAgEwagYDVR0fBGMwYTAuoCygKoYoaHR0
cDovL2NybC5jaWxvZ29uLm9yZy9jaWxvZ29uLWJhc2ljLmNybDAvoC2gK4YpaHR0cDovL2NybC5k
b2Vncmlkcy5vcmcvY2lsb2dvbi1iYXNpYy5jcmwwHwYDVR0RBBgwFoEUaXRzYWdyZWVuMUB5YWhv
by5jb20wDQYJKoZIhvcNAQEFBQADggEBAEYHQPMY9Grs19MHxUzMwXp1GzCKhGpgyVKJKW86PJlr
HGruoWvx+DLNX75Oj5FC4t8bOUQVQusZGeGSEGegzzfIeOI/jWP1UtIjzvTFDq3tQMNvsgROSCx5
CkpK4nS0kbwLux+zI7BWON97UpMIzEeE05pd7SmNAETuWRsHMP+x6i7hoUp/uad4DwbzNUGIotdK
f8b270icOVgkOKRdLP/Q4r/x8skKSCRz1ZsRdR+7+B/EgksAJj7Ut3yiWoUekEMxCaTdAHPTMD/g
Mh9xL90hfMJyoGemjJswG5g3fAdTP/Lv0I6/nWeH/cLjwwpQgIEjEAVXl7KHuzX5vPD/wqQ=
-----END CERTIFICATE-----"""
        id, valid_until, registered = self.identity_management_service.signon(certificate, True)

        self.assertFalse(registered)

        id2, valid_until2, registered2 = self.identity_management_service.signon(certificate, True)

        self.assertFalse(registered2)
        self.assertTrue(id == id2)
        self.assertTrue(valid_until == valid_until2)

        user_info_obj = IonObject("UserInfo", {"name": "Foo"})        
        self.identity_management_service.create_user_info(id, user_info_obj)

        id3, valid_until3, registered3 = self.identity_management_service.signon(certificate, True)

        self.assertTrue(registered3)
        self.assertTrue(id == id3)
        self.assertTrue(valid_until == valid_until3)

    @attr('EXT')
    def test_get_extended_user_identity(self):

        actor_identity_obj = IonObject("ActorIdentity", {"name": self.subject})
        actor_id = self.identity_management_service.create_actor_identity(actor_identity_obj)

        user_credentials_obj = IonObject("UserCredentials", {"name": self.subject})
        self.identity_management_service.register_user_credentials(actor_id, user_credentials_obj)

        user_info_obj = IonObject("UserInfo", {"name": "Foo"})
        user_info_id = self.identity_management_service.create_user_info(actor_id, user_info_obj)

        ion_org = self.org_client.find_org()

        #Build the Service Agreement Proposal to to request a role but never close it
        sap = IonObject(OT.RequestRoleProposal,consumer=actor_id, provider=ion_org._id, role_name=ORG_MANAGER_ROLE )
        sap_response = self.org_client.negotiate(sap)

        #Just grant the role anyway
        #self.org_client.grant_role(ion_org._id, actor_id, ORG_MANAGER_ROLE)

        with self.assertRaises(NotFound):
            self.identity_management_service.get_user_info_extension('That rug really tied the room together.')
        with self.assertRaises(BadRequest):
            self.identity_management_service.get_user_info_extension()

        #Check the user without the negotiation role request
        extended_user = self.identity_management_service.get_user_info_extension(user_info_id, org_id=ion_org._id)
        self.assertEqual(user_info_obj.type_,extended_user.resource.type_)
        self.assertEqual(len(extended_user.roles),1)
        self.assertEqual(len(extended_user.open_requests),1)
        self.assertEqual(extended_user.open_requests[0].org_id, ion_org._id)
        self.assertEqual(extended_user.open_requests[0].user_id, user_info_id)
        self.assertEqual(extended_user.open_requests[0].request_type, OT.RequestRoleProposal)
        self.assertEqual(len(extended_user.closed_requests),0)
        self.assertEqual(extended_user.open_requests[0]._id, extended_user.open_requests[0].negotiation_id)

        neg = self.resource_registry.read(object_id=extended_user.open_requests[0].negotiation_id)
        sap_response = Negotiation.create_counter_proposal(neg, ProposalStatusEnum.ACCEPTED, ProposalOriginatorEnum.PROVIDER)
        sap_response2 = self.org_client.negotiate(sap_response)

        #Now check the user after the negotiation has been accepted and the role granted
        extended_user = self.identity_management_service.get_user_info_extension(user_info_id, org_id=ion_org._id)
        self.assertEqual(user_info_obj.type_,extended_user.resource.type_)
        self.assertEqual(len(extended_user.roles),2)
        self.assertEqual(len(extended_user.open_requests),0)
        self.assertEqual(len(extended_user.closed_requests),1)
        self.assertEqual(extended_user.closed_requests[0].org_id, ion_org._id)
        self.assertEqual(extended_user.closed_requests[0].user_id, user_info_id)
        self.assertEqual(extended_user.closed_requests[0].request_type, OT.RequestRoleProposal)

        self.identity_management_service.delete_user_info(user_info_id)

        self.org_client.revoke_role(org_id=ion_org._id, actor_id=actor_id, role_name=ORG_MANAGER_ROLE)

        self.identity_management_service.unregister_user_credentials(actor_id, self.subject)

        self.identity_management_service.delete_actor_identity(actor_id)

    def test_account_merge(self):
        certificate =  """-----BEGIN CERTIFICATE-----
MIIEMzCCAxugAwIBAgICBQAwDQYJKoZIhvcNAQEFBQAwajETMBEGCgmSJomT8ixkARkWA29yZzEX
MBUGCgmSJomT8ixkARkWB2NpbG9nb24xCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdDSUxvZ29uMRsw
GQYDVQQDExJDSUxvZ29uIEJhc2ljIENBIDEwHhcNMTAxMTE4MjIyNTA2WhcNMTAxMTE5MTAzMDA2
WjBvMRMwEQYKCZImiZPyLGQBGRMDb3JnMRcwFQYKCZImiZPyLGQBGRMHY2lsb2dvbjELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlByb3RlY3ROZXR3b3JrMRkwFwYDVQQDExBSb2dlciBVbndpbiBBMjU0
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6QhsWxhUXbIxg+1ZyEc7d+hIGvchVmtb
g0kKLmivgoVsA4U7swNDRH6svW242THta0oTf6crkRx7kOKg6jma2lcAC1sjOSddqX7/92ChoUPq
7LWt2T6GVVA10ex5WAeB/o7br/Z4U8/75uCBis+ru7xEDl09PToK20mrkcz9M4HqIv1eSoPkrs3b
2lUtQc6cjuHRDU4NknXaVMXTBHKPM40UxEDHJueFyCiZJFg3lvQuSsAl4JL5Z8pC02T8/bODBuf4
dszsqn2SC8YDw1xrujvW2Bd7Q7BwMQ/gO+dZKM1mLJFpfEsR9WrjMeg6vkD2TMWLMr0/WIkGC8u+
6M6SMQIDAQABo4HdMIHaMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgSwMBMGA1UdJQQMMAoG
CCsGAQUFBwMCMBgGA1UdIAQRMA8wDQYLKwYBBAGCkTYBAgEwagYDVR0fBGMwYTAuoCygKoYoaHR0
cDovL2NybC5jaWxvZ29uLm9yZy9jaWxvZ29uLWJhc2ljLmNybDAvoC2gK4YpaHR0cDovL2NybC5k
b2Vncmlkcy5vcmcvY2lsb2dvbi1iYXNpYy5jcmwwHwYDVR0RBBgwFoEUaXRzYWdyZWVuMUB5YWhv
by5jb20wDQYJKoZIhvcNAQEFBQADggEBAEYHQPMY9Grs19MHxUzMwXp1GzCKhGpgyVKJKW86PJlr
HGruoWvx+DLNX75Oj5FC4t8bOUQVQusZGeGSEGegzzfIeOI/jWP1UtIjzvTFDq3tQMNvsgROSCx5
CkpK4nS0kbwLux+zI7BWON97UpMIzEeE05pd7SmNAETuWRsHMP+x6i7hoUp/uad4DwbzNUGIotdK
f8b270icOVgkOKRdLP/Q4r/x8skKSCRz1ZsRdR+7+B/EgksAJj7Ut3yiWoUekEMxCaTdAHPTMD/g
Mh9xL90hfMJyoGemjJswG5g3fAdTP/Lv0I6/nWeH/cLjwwpQgIEjEAVXl7KHuzX5vPD/wqQ=
-----END CERTIFICATE-----"""
        subject = "/DC=org/DC=cilogon/C=US/O=ProtectNetwork/CN=Roger Unwin A254"
        certificate_2 = """-----BEGIN CERTIFICATE-----
MIIEMzCCAxugAwIBAgIDAJ/lMA0GCSqGSIb3DQEBCwUAMGsxEzARBgoJkiaJk/IsZAEZFgNvcmcx
FzAVBgoJkiaJk/IsZAEZFgdjaWxvZ29uMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHQ0lMb2dvbjEc
MBoGA1UEAxMTQ0lMb2dvbiBPcGVuSUQgQ0EgMTAeFw0xMjEwMTcwMDE2NDlaFw0xMjEwMTcxMjIx
NDlaMGkxEzARBgoJkiaJk/IsZAEZEwNvcmcxFzAVBgoJkiaJk/IsZAEZEwdjaWxvZ29uMQswCQYD
VQQGEwJVUzEPMA0GA1UEChMGR29vZ2xlMRswGQYDVQQDExJPd2VuIE93bmVycmVwIEE4OTMwggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDYLdpgg88sntivH+af4oamlp7blsUQcCQ5Yc/b
VDP/dwEKfxTcW36tMV3asLO7GcL7z4FESG761LAe86siT9rcwg2ttLkRjI9KeA3sFjC28N8XjKZ1
estCqG3odqw2pjo3VEFaU57219vIYMJhjmHKEgSnlMQeChMYun/sYIO5uNFba9BfiB6/PRS+bgee
cXRsIAm1vkB89AHdEjqdvH0uSN+jGjF6aAPXsESh70DUAHzs14lbFAomig7AZafT+weh0G5pnayC
lutVnhb9SyS3s1+A6kx8z9mkDUwY/NKXisuDeXa+WbRVq51D+Lc7ffOI+Ph+ynyfFGMcCBzbMADX
AgMBAAGjgeEwgd4wDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBLAwEwYDVR0lBAwwCgYIKwYB
BQUHAwIwGAYDVR0gBBEwDzANBgsrBgEEAYKRNgEDAzBsBgNVHR8EZTBjMC+gLaArhilodHRwOi8v
Y3JsLmNpbG9nb24ub3JnL2NpbG9nb24tb3BlbmlkLmNybDAwoC6gLIYqaHR0cDovL2NybC5kb2Vn
cmlkcy5vcmcvY2lsb2dvbi1vcGVuaWQuY3JsMCEGA1UdEQQaMBiBFm93ZW5vd25lcnJlcEBnbWFp
bC5jb20wDQYJKoZIhvcNAQELBQADggEBAHWd6ZOjSmJyOUyyLgZAPJpkSuk7DT5mFRhszJhfTGnu
gANHRIJZMs5e/LCMypE+ftxb8mnhAE+kURA2DmeucazHUDP5oYofU+8KMYqcNKnPpLnuiw+bCJPa
3BDxrYoi+vVislHb0U+QDjVYtUtQ2b1/Xhv8ShH89O9i65bbOq+sqez6z2AD9RWOEwRwpQLc9D65
9lkrsKGmJtuG8q3NTpZ1DSuaLOtn0QqttdmCg3pu5edRtgdpGadaSGR4s222JasV439bSTL8Z0Ug
HtjSclGqi8IBmvRkTZI61zTVbGdOKMP90LV1p8noJVLRkZpWRjLxI5xy9El8daAWMdjfrSc=
-----END CERTIFICATE-----"""
        subject_2 = "/DC=org/DC=cilogon/C=US/O=Google/CN=Owen Ownerrep A893"

        # Try to merge with nonexistent email account
        with self.assertRaises(NotFound):
            self.identity_management_service.initiate_account_merge("*****@*****.**")
        with self.assertRaises(BadRequest):
            self.identity_management_service.initiate_account_merge()

        # Create two users
        id, valid_until, registered = self.identity_management_service.signon(certificate, True)
        self.assertFalse(registered)
        id_2, valid_until_2, registered_2 = self.identity_management_service.signon(certificate_2, True)
        self.assertFalse(registered_2)

        # Validate the two accounts are different
        self.assertNotEqual(id, id_2, "The two accounts should have two different user id")

        # Create UserInfo
        contact_info_obj = IonObject("ContactInformation",{"email": "*****@*****.**"})
        user_info_obj = IonObject("UserInfo", {"name": "Dude", "contact": contact_info_obj})
        user_info_id = self.identity_management_service.create_user_info(id, user_info_obj)

        contact_info_obj_2 = IonObject("ContactInformation",{"email": "*****@*****.**"})
        user_info_obj_2 = IonObject("UserInfo", {"name": "theDude", "contact": contact_info_obj_2})
        user_info_id_2 = self.identity_management_service.create_user_info(id_2, user_info_obj_2)

        # Make sure the two users are registered
        id, valid_until, registered = self.identity_management_service.signon(certificate, True)
        self.assertTrue(registered)
        id_2, valid_until_2, registered_2 = self.identity_management_service.signon(certificate_2, True)
        self.assertTrue(registered_2)

        token = self.identity_management_service.initiate_account_merge("*****@*****.**",  headers={'ion-actor-id':id})

        # Try merging accounts with invalid token string
        with self.assertRaises(NotFound):
            self.identity_management_service.complete_account_merge(token_string="0xBeeF", headers={'ion-actor-id':id})
        with self.assertRaises(BadRequest):
            self.identity_management_service.complete_account_merge()

        # Try merging accounts with a different user
        # Since this user hasn't initiated account merge, the token doesn't exist in his/her UserInfo
        with self.assertRaises(NotFound):
            self.identity_management_service.complete_account_merge(token, headers={'ion-actor-id':id_2})

        self.identity_management_service.complete_account_merge(token, headers={'ion-actor-id':id})

        # Try merging the account again
        with self.assertRaises(BadRequest):
            self.identity_management_service.complete_account_merge(token, headers={'ion-actor-id':id})

        # Signon again and verify the two accounts have been merged
        id, valid_until, registered = self.identity_management_service.signon(certificate, True)
        self.assertTrue(registered)
        id_2, valid_until_2, registered_2 = self.identity_management_service.signon(certificate_2, True)
        self.assertTrue(registered_2)

        # Validate the two accounts are the same
        self.assertEqual(id, id_2, "The two accounts should have the same id")

        # Try to merge to your own account
        with self.assertRaises(BadRequest):
            token = self.identity_management_service.initiate_account_merge("*****@*****.**",  headers={'ion-actor-id':id})

        #  Done testing. Delete user
        self.identity_management_service.delete_user_info(user_info_id)
        self.identity_management_service.unregister_user_credentials(id, subject)
        self.identity_management_service.delete_actor_identity(id)

    def test_auth_tokens(self):
        # Note: test of service gateway token functionality is in SGS test

        rr = self.resource_registry

        actor_identity_obj = IonObject("ActorIdentity", {"name": self.subject})
        actor_id = self.identity_management_service.create_actor_identity(actor_identity_obj)

        user_info_obj = IonObject("UserInfo", {"name": "Foo"})
        user_info_id = self.identity_management_service.create_user_info(actor_id, user_info_obj)

        token_str = self.identity_management_service.create_authentication_token(actor_id, validity=10000)
        self.assertIsInstance(token_str, str)
        self.assertGreaterEqual(len(token_str), 25)

        token_info = self.identity_management_service.check_authentication_token(token_str)
        self.assertEquals(token_info["actor_id"], actor_id)

        token_info = self.identity_management_service.check_authentication_token(token_str)
        self.assertGreaterEqual(int(token_info["expiry"]), get_ion_ts_millis())

        with self.assertRaises(BadRequest):
            self.identity_management_service.create_authentication_token(actor_id="", validity=10000)

        with self.assertRaises(BadRequest):
            self.identity_management_service.create_authentication_token(user_info_id, validity=10000)

        with self.assertRaises(BadRequest):
            self.identity_management_service.create_authentication_token(actor_id, validity="FOO")

        with self.assertRaises(BadRequest):
            self.identity_management_service.create_authentication_token(actor_id, validity=-200)

        cur_time = get_ion_ts_millis()

        with self.assertRaises(BadRequest):
            self.identity_management_service.create_authentication_token(actor_id, start_time=str(cur_time-100000), validity=50)

        with self.assertRaises(BadRequest):
            self.identity_management_service.create_authentication_token(actor_id, validity=35000000)

        with self.assertRaises(NotFound):
            self.identity_management_service.check_authentication_token("UNKNOWN")

        token_str2 = self.identity_management_service.create_authentication_token(actor_id, validity=1)
        token_info = self.identity_management_service.check_authentication_token(token_str2)

        gevent.sleep(1.1)

        with self.assertRaises(Unauthorized):
            self.identity_management_service.check_authentication_token(token_str2)

        token = self.identity_management_service.read_authentication_token(token_str2)

        token.expires = str(cur_time + 5000)
        self.identity_management_service.update_authentication_token(token)
        token_info = self.identity_management_service.check_authentication_token(token_str2)

        token_str3 = self.identity_management_service.create_authentication_token(actor_id, validity=2)
        token_info = self.identity_management_service.check_authentication_token(token_str3)

        self.identity_management_service.invalidate_authentication_token(token_str3)

        with self.assertRaises(Unauthorized):
            self.identity_management_service.check_authentication_token(token_str3)

        token = self.identity_management_service.read_authentication_token(token_str3)
        self.assertEquals(token.token_string, token_str3)
        self.assertIn(token_str3, token._id)

        token.status = "OPEN"
        self.identity_management_service.update_authentication_token(token)

        token_info = self.identity_management_service.check_authentication_token(token_str3)

        # Cleanup
        self.identity_management_service.delete_user_info(user_info_id)
        self.identity_management_service.delete_actor_identity(actor_id)