def test_add_key_POST_adds_key(self): key_string = get_data('data/test_rsa0.pub') response = self.client.post( reverse('prefs-add-sshkey'), {'key': key_string}) self.assertEqual(httplib.FOUND, response.status_code) self.assertTrue(SSHKey.objects.filter(key=key_string).exists())
def test_sshkey_display_with_real_life_key(self): # With a real-life ssh-rsa key, the key_string part is cropped. key_string = get_data('data/test_rsa0.pub') user = factory.make_user() key = SSHKey(key=key_string, user=user) display = key.display_html() self.assertEqual( 'ssh-rsa AAAAB3NzaC1yc2E… ubuntu@server-7476', display)
def test_sshkey_same_key_can_be_used_by_different_users(self): key_string = get_data('data/test_rsa0.pub') user = factory.make_user() key = SSHKey(key=key_string, user=user) key.save() user2 = factory.make_user() key2 = SSHKey(key=key_string, user=user2) key2.full_clean()
def test_sshkey_user_and_key_unique_together(self): key_string = get_data('data/test_rsa0.pub') user = factory.make_user() key = SSHKey(key=key_string, user=user) key.save() key2 = SSHKey(key=key_string, user=user) self.assertRaises( ValidationError, key2.full_clean)
def test_sslkey_display_is_HTML_safe(self): self.patch(sslkey_module, "find_ssl_common_name").return_value = "<escape>" key_string = get_data("data/test_x509_0.pem") user = factory.make_User() key = SSLKey(key=key_string, user=user) display = key.display_html() self.assertThat(display, StartsWith("<escape>")) self.assertNotIn("<", display) self.assertNotIn(">", display)
def test_creates_audit_event_on_save(self): user = factory.make_User() key_string = get_data("data/test_x509_0.pem") form = SSLKeyForm(user=user, data={"key": key_string}) request = HttpRequest() request.user = user form.save(factory.pick_choice(ENDPOINT_CHOICES), request) event = Event.objects.get(type__level=AUDIT) self.assertIsNotNone(event) self.assertEquals(event.description, "Created SSL key.")
def test_adding_does_not_work_with_user_for_non_admin(self): username = factory.make_name('user') factory.make_User(username=username) key_string = get_data('data/test_rsa0.pub') response = self.client.post( reverse('sshkeys_handler'), data=dict( key=key_string, user=username)) self.assertEqual( http.client.BAD_REQUEST, response.status_code, response) self.assertIn(b"Only administrators", response.content)
def test_adding_does_not_work_with_unknown_user(self): self.become_admin() username = factory.make_name('user') key_string = get_data('data/test_rsa0.pub') response = self.client.post( reverse('sshkeys_handler'), data=dict( key=key_string, user=username)) self.assertEqual( http.client.BAD_REQUEST, response.status_code, response) self.assertIn(b"Supplied username", response.content)
def test_import_keys_source_exists_doesnt_remove_keys(self): user = factory.make_User() protocol = random.choice( [KEYS_PROTOCOL_TYPE.LP, KEYS_PROTOCOL_TYPE.GH]) auth_id = factory.make_name('auth_id') keysource = factory.make_KeySource(protocol, auth_id) keys = get_data('data/test_rsa0.pub') + get_data('data/test_rsa1.pub') mock_get_protocol_keys = self.patch(keysource_module, 'get_protocol_keys') mock_get_protocol_keys.return_value = keys.strip().split('\n') returned_sshkeys = keysource.import_keys(user) # only return one key keys = get_data('data/test_rsa0.pub') mock_get_protocol_keys.return_value = keys.strip().split('\n') keysource.import_keys(user) # no key is removed self.assertEqual(2, SSHKey.objects.count()) self.assertCountEqual(returned_sshkeys, SSHKey.objects.filter(keysource=keysource))
def test_adding_works(self): key_string = get_data("data/test_rsa0.pub") response = self.client.post( reverse("sshkeys_handler"), data=dict(key=key_string) ) self.assertEqual(http.client.CREATED, response.status_code) parsed_response = json_load_bytes(response.content) self.assertEqual(key_string, parsed_response["key"]) added_key = get_one(SSHKey.objects.filter(user=self.user)) self.assertEqual(key_string, added_key.key)
def test_adding_works(self): key_string = get_data('data/test_rsa0.pub') response = self.client.post( reverse('sshkeys_handler'), data=dict(op="new", key=key_string)) self.assertEqual(httplib.CREATED, response.status_code) parsed_response = json.loads(response.content) self.assertEqual(key_string, parsed_response["key"]) added_key = get_one(SSHKey.objects.filter(user=self.logged_in_user)) self.assertEqual(key_string, added_key.key)
def test_create_ssl_key_POST(self): user = factory.make_admin() self.client.login(user=user) key_string = get_data('data/test_x509_0.pem') params = {'key': key_string} response = self.client.post(reverse('prefs-add-sslkey'), params) sslkey = SSLKey.objects.get(user=user) self.assertEqual(http.client.FOUND, response.status_code) self.assertIsNotNone(sslkey) self.assertEqual(key_string, sslkey.key)
def test_key_can_be_added_if_same_key_already_setup_for_other_user(self): key_string = get_data('data/test_rsa0.pub') key = SSHKey(user=factory.make_user(), key=key_string) key.save() response = self.client.post( reverse('prefs-add-sshkey'), {'key': key_string}) new_key = SSHKey.objects.get(key=key_string, user=self.logged_in_user) self.assertEqual(httplib.FOUND, response.status_code) self.assertItemsEqual( [key, new_key], SSHKey.objects.filter(key=key_string))
def test_get_protocol_keys_returns_github_keys(self): auth_id = factory.make_name('auth_id') key_string = str([dict(key=get_data('data/test_rsa0.pub'))]) mock_requests = self.patch(requests_module, 'get') mock_requests.return_value.text = key_string keys = get_github_ssh_keys(auth_id) url = 'https://api.github.com/users/%s/keys' % auth_id self.expectThat(mock_requests, MockCalledOnceWith(url, proxies=None)) self.expectThat( keys, Equals([data['key'] for data in key_string if 'key' in data]))
def test_sshkey_user_and_key_unique_together(self): protocol = random.choice( [KEYS_PROTOCOL_TYPE.LP, KEYS_PROTOCOL_TYPE.GH]) auth_id = factory.make_name('auth_id') keysource = factory.make_KeySource(protocol=protocol, auth_id=auth_id) key_string = get_data('data/test_rsa0.pub') user = factory.make_User() key = SSHKey(key=key_string, user=user, keysource=keysource) key.save() key2 = SSHKey(key=key_string, user=user, keysource=keysource) self.assertRaises(ValidationError, key2.full_clean)
def test_creates_audit_event_on_save(self): user = factory.make_User() key_string = get_data('data/test_rsa0.pub') form = SSHKeyForm(user=user, data={'key': key_string}) request = HttpRequest() request.user = user form.save(factory.pick_choice(ENDPOINT_CHOICES), request) event = Event.objects.get(type__level=AUDIT) self.assertIsNotNone(event) self.assertEqual(event.description, "SSH key created by '%(username)s'.")
def test_key_can_be_added_if_same_key_already_setup_for_other_user(self): key_string = get_data('data/test_rsa0.pub') key = SSHKey(user=factory.make_user(), key=key_string) key.save() response = self.client.post(reverse('prefs-add-sshkey'), {'key': key_string}) new_key = SSHKey.objects.get(key=key_string, user=self.logged_in_user) self.assertEqual(httplib.FOUND, response.status_code) self.assertItemsEqual([key, new_key], SSHKey.objects.filter(key=key_string))
def test_add_key_POST_fails_if_key_already_exists_for_the_user(self): key_string = get_data('data/test_rsa0.pub') key = SSHKey(user=self.logged_in_user, key=key_string) key.save() response = self.client.post(reverse('prefs-add-sshkey'), {'key': key_string}) self.assertEqual(httplib.OK, response.status_code) self.assertIn("This key has already been added for this user.", response.content) self.assertItemsEqual([key], SSHKey.objects.filter(key=key_string))
def test_creates_audit_event_for_specified_user_on_save(self): specified_user = factory.make_User() request_user = factory.make_User() key_string = get_data("data/test_rsa0.pub") form = SSHKeyForm(user=specified_user, data={"key": key_string}) request = HttpRequest() request.user = request_user form.save(factory.pick_choice(ENDPOINT_CHOICES), request) event = Event.objects.get(type__level=AUDIT) self.assertIsNotNone(event) self.assertEqual(event.description, "Created SSH key for %s." % specified_user)
def test_adding_works(self): key_string = get_data("data/test_x509_0.pem") response = self.client.post( reverse("sslkeys_handler"), data=dict(key=key_string) ) self.assertEqual(http.client.CREATED, response.status_code) parsed_response = json.loads( response.content.decode(settings.DEFAULT_CHARSET) ) self.assertEqual(key_string, parsed_response["key"]) added_key = get_one(SSLKey.objects.filter(user=self.user)) self.assertEqual(key_string, added_key.key)
def test_create(self): user = factory.make_User() handler = SSLKeyHandler(user, {}, None) key_string = get_data("data/test_x509_0.pem") new_sslkey = handler.create({"key": key_string}) self.assertThat( new_sslkey, ContainsDict({ "user": Equals(user.id), "key": Equals(key_string) }), )
def test_add_key_POST_fails_if_key_already_exists_for_the_user(self): key_string = get_data('data/test_rsa0.pub') key = SSHKey(user=self.logged_in_user, key=key_string) key.save() response = self.client.post( reverse('prefs-add-sshkey'), {'key': key_string}) self.assertEqual(httplib.OK, response.status_code) self.assertIn( "This key has already been added for this user.", response.content) self.assertItemsEqual([key], SSHKey.objects.filter(key=key_string))
def test_adding_works_with_user(self): self.become_admin() username = factory.make_name('user') user = factory.make_User(username=username) key_string = get_data('data/test_rsa0.pub') response = self.client.post(reverse('sshkeys_handler'), data=dict(key=key_string, user=username)) self.assertEqual(http.client.CREATED, response.status_code) parsed_response = json_load_bytes(response.content) self.assertEqual(key_string, parsed_response["key"]) added_key = get_one(SSHKey.objects.filter(user=user)) self.assertEqual(key_string, added_key.key)
def test_sshkey_same_key_can_be_used_by_different_sources(self): auth_id = factory.make_name('auth_id') keysource1 = factory.make_KeySource(protocol=KEYS_PROTOCOL_TYPE.LP, auth_id=auth_id) keysource2 = factory.make_KeySource(protocol=KEYS_PROTOCOL_TYPE.GH, auth_id=auth_id) key_string = get_data('data/test_rsa0.pub') user = factory.make_User() key1 = SSHKey(key=key_string, user=user, keysource=keysource1) key1.save() key2 = SSHKey(key=key_string, user=user, keysource=keysource2) key2.save() self.assertIsNone(key2.full_clean())
def test_create(self): user = factory.make_User() handler = SSHKeyHandler(user, {}, None) key_string = get_data('data/test_rsa0.pub') new_sshkey = handler.create({ 'key': key_string, }) self.assertThat( new_sshkey, ContainsDict({ "user": Equals(user.id), "key": Equals(key_string), }))
def test_sslkey_user_and_key_unique_together_db_level(self): # Even if we hack our way around model-level checks, uniqueness # of the user/key combination is enforced at the database level. key_string = get_data('data/test_x509_0.pem') user = factory.make_User() existing_key = SSLKey(key=key_string, user=user) existing_key.save() # The trick to hack around the model-level checks: create a # duplicate key for another user, then attach it to the same # user as the existing key by updating it directly in the # database. redundant_key = SSLKey(key=key_string, user=factory.make_User()) redundant_key.save() self.assertRaises(IntegrityError, SSLKey.objects.filter(id=redundant_key.id).update, user=user)
def test_import_ssh_keys_creates_keys_and_keysource(self): protocol = random.choice( [KEYS_PROTOCOL_TYPE.LP, KEYS_PROTOCOL_TYPE.GH]) auth_id = factory.make_name('auth_id') ks = "%s:%s" % (protocol, auth_id) key_string = get_data('data/test_rsa0.pub') mock_get_protocol_keys = self.patch(keysource_module, 'get_protocol_keys') mock_get_protocol_keys.return_value = [key_string] response = self.client.post(reverse('sshkeys_handler'), data=dict(op='import', keysource=ks)) added_key = get_one(SSHKey.objects.filter(user=self.user)) self.assertEqual(key_string, added_key.key) self.assertEqual(ks, str(added_key.keysource)) self.assertEqual(http.client.OK, response.status_code, response) self.assertThat(mock_get_protocol_keys, MockCalledOnceWith(protocol, auth_id))
def test_sshkey_user_and_key_unique_together_db_level(self): # Even if we hack our way around model-level checks, uniqueness # of the user/key combination is enforced at the database level. key_string = get_data('data/test_rsa0.pub') user = factory.make_user() existing_key = SSHKey(key=key_string, user=user) existing_key.save() # The trick to hack around the model-level checks: create a # duplicate key for another user, then attach it to the same # user as the existing key by updating it directly in the # database. redundant_key = SSHKey(key=key_string, user=factory.make_user()) redundant_key.save() self.assertRaises( IntegrityError, SSHKey.objects.filter(id=redundant_key.id).update, user=user)
def test_import_ssh_keys_creates_keys_not_duplicate_keysource(self): protocol = random.choice( [KEYS_PROTOCOL_TYPE.LP, KEYS_PROTOCOL_TYPE.GH]) auth_id = factory.make_name("auth_id") ks = "%s:%s" % (protocol, auth_id) keysource = factory.make_KeySource(protocol=protocol, auth_id=auth_id) key_string = get_data("data/test_rsa0.pub") mock_get_protocol_keys = self.patch(keysource_module, "get_protocol_keys") mock_get_protocol_keys.return_value = [key_string] response = self.client.post(reverse("sshkeys_handler"), data=dict(op="import", keysource=ks)) added_key = get_one(SSHKey.objects.filter(user=self.user)) self.assertEqual(key_string, added_key.key) self.assertEqual(str(keysource), str(added_key.keysource)) self.assertEqual(1, KeySource.objects.count()) self.assertEqual(http.client.OK, response.status_code, response) self.assertThat(mock_get_protocol_keys, MockCalledOnceWith(protocol, auth_id))
def make_user_with_keys(self, n_keys=2, user=None, **kwargs): """Create a user with n `SSHKey`. If user is not None, use this user instead of creating one. Additional keyword arguments are passed to `make_user()`. """ if n_keys > MAX_PUBLIC_KEYS: raise RuntimeError( "Cannot create more than %d public keys. If you need more: " "add more keys in src/maasserver/tests/data/." % MAX_PUBLIC_KEYS) if user is None: user = self.make_user(**kwargs) keys = [] for i in range(n_keys): key_string = get_data('data/test_rsa%d.pub' % i) key = SSHKey(user=user, key=key_string) key.save() keys.append(key) return user, keys
def test_import_ssh_keys_creates_keys_keysource_and_audit_event(self): protocol = random.choice( [KEYS_PROTOCOL_TYPE.LP, KEYS_PROTOCOL_TYPE.GH]) auth_id = factory.make_name("auth_id") ks = "%s:%s" % (protocol, auth_id) key_string = get_data("data/test_rsa0.pub") mock_get_protocol_keys = self.patch(keysource_module, "get_protocol_keys") mock_get_protocol_keys.return_value = [key_string] response = self.client.post(reverse("sshkeys_handler"), data=dict(op="import", keysource=ks)) added_key = get_one(SSHKey.objects.filter(user=self.user)) self.assertEqual(key_string, added_key.key) self.assertEqual(ks, str(added_key.keysource)) self.assertEqual(http.client.OK, response.status_code, response) self.assertThat(mock_get_protocol_keys, MockCalledOnceWith(protocol, auth_id)) event = Event.objects.get(type__level=AUDIT) self.assertIsNotNone(event) self.assertEqual(event.description, "Imported SSH keys.")
def test_sshkey_user_and_key_unique_together_db_level(self): # Even if we hack our way around model-level checks, uniqueness # of the user/key combination is enforced at the database level. protocol = random.choice( [KEYS_PROTOCOL_TYPE.LP, KEYS_PROTOCOL_TYPE.GH]) auth_id = factory.make_name('auth_id') keysource = factory.make_KeySource(protocol=protocol, auth_id=auth_id) key_string = get_data('data/test_rsa0.pub') user = factory.make_User() existing_key = SSHKey(key=key_string, user=user, keysource=keysource) existing_key.save() # The trick to hack around the model-level checks: create a # duplicate key for another user, then attach it to the same # user as the existing key by updating it directly in the # database. redundant_key = SSHKey(key=key_string, user=factory.make_User(), keysource=keysource) redundant_key.save() self.assertRaises(IntegrityError, SSHKey.objects.filter(id=redundant_key.id).update, user=user)
def test_validates_dsa_public_key(self): key_string = get_data('data/test_dsa.pub') validate_ssh_public_key(key_string)
def test_sslkey_display_is_marked_as_HTML_safe(self): key_string = get_data('data/test_x509_0.pem') user = factory.make_User() key = SSLKey(key=key_string, user=user) display = key.display_html() self.assertIsInstance(display, SafeString)
def test_sslkey_validation_with_valid_key(self): key_string = get_data('data/test_x509_0.pem') user = factory.make_User() key = SSLKey(key=key_string, user=user) key.full_clean()
def test_validates_x509_public_key(self): key_string = get_data('data/test_x509_0.pem') validate_ssl_key(key_string)
def test_does_not_validate_dsa_private_key(self): key_string = get_data('data/test_dsa') self.assertRaises( ValidationError, validate_ssh_public_key, key_string)
def get_ssh_key_string(num=0): return get_data('data/test_rsa%d.pub' % num)
def make_sshkey(self, user, key_string=None): if key_string is None: key_string = get_data('data/test_rsa0.pub') key = SSHKey(key=key_string, user=user) key.save() return key
def test_sshkey_display_is_marked_as_HTML_safe(self): key_string = get_data('data/test_rsa0.pub') user = factory.make_user() key = SSHKey(key=key_string, user=user) display = key.display_html() self.assertIsInstance(display, SafeUnicode)
def test_sshkey_validation_with_valid_key(self): key_string = get_data('data/test_rsa0.pub') user = factory.make_user() key = SSHKey(key=key_string, user=user) key.full_clean()