tests.py 10.8 KB
Newer Older
Scott Duckworth committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2013 Scott Duckworth
#
# This file is part of django-sshkey.
#
# django-sshkey is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django-sshkey is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with django-sshkey.  If not, see <http://www.gnu.org/licenses/>.

Scott Duckworth committed
18 19 20 21 22
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
23 24
from django_sshkey.models import UserKey
from django_sshkey import settings
Scott Duckworth committed
25 26 27 28
import os
import shutil
import subprocess
import tempfile
29

Scott Duckworth committed
30 31 32 33 34 35 36 37 38 39 40
def ssh_keygen(type=None, passphrase='', comment=None, file=None):
  cmd = ['ssh-keygen', '-q']
  if type is not None:
    cmd += ['-t', type]
  if passphrase is not None:
    cmd += ['-N', passphrase]
  if comment is not None:
    cmd += ['-C', comment]
  if file is not None:
    cmd += ['-f', file]
  subprocess.check_call(cmd)
41

Scott Duckworth committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
def ssh_fingerprint(pubkey_path):
  cmd = ['ssh-keygen', '-lf', pubkey_path]
  p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  stdout, stderr = p.communicate()
  fingerprint = stdout.split(None, 2)[1]
  return fingerprint

class BaseTestCase(TestCase):
  @classmethod
  def setUpClass(cls):
    cls.key_dir = tempfile.mkdtemp(prefix='sshkey-test.')

  @classmethod
  def tearDownClass(cls):
    if cls.key_dir:
      shutil.rmtree(cls.key_dir)
      cls.key_dir = None

class UserKeyCreationTestCase(BaseTestCase):
  @classmethod
  def setUpClass(cls):
    super(UserKeyCreationTestCase, cls).setUpClass()
    cls.user1 = User.objects.create(username='user1')
    cls.user2 = User.objects.create(username='user2')
    # key1 has a comment
    cls.key1_path = os.path.join(cls.key_dir, 'key1')
    ssh_keygen(comment='comment', file=cls.key1_path)
    # key2 does not have a comment
    cls.key2_path = os.path.join(cls.key_dir, 'key2')
    ssh_keygen(comment='', file=cls.key2_path)

  @classmethod
  def tearDownClass(cls):
    User.objects.all().delete()
    super(UserKeyCreationTestCase, cls).tearDownClass()

  def tearDown(self):
    UserKey.objects.all().delete()

  def test_with_name_with_comment(self):
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key1_path+'.pub').read(),
    )
    key.full_clean()
    key.save()
    self.assertEqual(key.name, 'name')

  def test_with_name_without_comment(self):
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key2_path+'.pub').read(),
    )
    key.full_clean()
    key.save()
    self.assertEqual(key.name, 'name')

  def test_without_name_with_comment(self):
    key = UserKey(
      user = self.user1,
      key = open(self.key1_path+'.pub').read(),
    )
    key.full_clean()
    key.save()
    self.assertEqual(key.name, 'comment')

  def test_without_name_without_comment_fails(self):
    key = UserKey(
      user = self.user1,
      key = open(self.key2_path+'.pub').read(),
    )
    self.assertRaises(ValidationError, key.full_clean)

  def test_private_key_fails(self):
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key1_path).read(),
    )
    self.assertRaises(ValidationError, key.full_clean)

Scott Duckworth committed
125 126 127 128 129 130 131 132
  def test_invalid_key_fails(self):
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = 'ssh-rsa invalid',
    )
    self.assertRaises(ValidationError, key.full_clean)

Scott Duckworth committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  def test_key_with_options_fails(self):
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = 'command="foobar" ' + open(self.key1_path+'.pub').read(),
    )
    self.assertRaises(ValidationError, key.full_clean)

  def test_multiple_keys_fails(self):
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key1_path+'.pub').read() \
          + open(self.key2_path+'.pub').read(),
    )
    self.assertRaises(ValidationError, key.full_clean)

Scott Duckworth committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  def test_fingerprint(self):
    fingerprint = ssh_fingerprint(self.key1_path+'.pub')
    key = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key1_path+'.pub').read(),
    )
    key.full_clean()
    key.save()
    self.assertEqual(key.fingerprint, fingerprint)

  def test_same_name_same_user(self):
    key1 = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key1_path+'.pub').read(),
    )
    key1.full_clean()
    key1.save()
    key2 = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key2_path+'.pub').read(),
    )
    self.assertRaises(ValidationError, key2.full_clean)

  def test_same_name_different_user(self):
    key1 = UserKey(
      user = self.user1,
      name = 'name',
      key = open(self.key1_path+'.pub').read(),
    )
    key1.full_clean()
    key1.save()
    key2 = UserKey(
      user = self.user2,
      name = 'name',
      key = open(self.key2_path+'.pub').read(),
    )
    key2.full_clean()
    key2.save()

  def test_same_key_same_user(self):
    key1 = UserKey(
      user = self.user1,
      name = 'name1',
      key = open(self.key1_path+'.pub').read(),
    )
    key1.full_clean()
    key1.save()
    key2 = UserKey(
      user = self.user1,
      name = 'name2',
      key = open(self.key1_path+'.pub').read(),
    )
    self.assertRaises(ValidationError, key2.full_clean)

  def test_same_key_different_user(self):
    key1 = UserKey(
      user = self.user1,
      name = 'name1',
      key = open(self.key1_path+'.pub').read(),
    )
    key1.full_clean()
    key1.save()
    key2 = UserKey(
      user = self.user2,
      name = 'name2',
      key = open(self.key1_path+'.pub').read(),
    )
    self.assertRaises(ValidationError, key2.full_clean)

class UserKeyLookupTestCase(BaseTestCase):
  @classmethod
  def setUpClass(cls):
    super(UserKeyLookupTestCase, cls).setUpClass()
    cls.original_options = settings.SSHKEY_AUTHORIZED_KEYS_OPTIONS
    settings.SSHKEY_AUTHORIZED_KEYS_OPTIONS = 'command="{username}"'
    cls.user1 = User.objects.create(username='user1')
    cls.user2 = User.objects.create(username='user2')

    cls.key1_path = os.path.join(cls.key_dir, 'key1')
    ssh_keygen(file=cls.key1_path)
    key1 = UserKey(
      user = cls.user1,
      name = 'key1',
      key = open(cls.key1_path+'.pub').read(),
    )
    key1.full_clean()
    key1.save()

    cls.key2_path = os.path.join(cls.key_dir, 'key2')
    ssh_keygen(file=cls.key2_path)
    key2 = UserKey(
      user = cls.user1,
      name = 'key2',
      key = open(cls.key2_path+'.pub').read(),
    )
    key2.full_clean()
    key2.save()

    cls.key3_path = os.path.join(cls.key_dir, 'key3')
    ssh_keygen(file=cls.key3_path)
    key3 = UserKey(
      user = cls.user2,
      name = 'key3',
      key = open(cls.key3_path+'.pub').read(),
    )
    key3.full_clean()
    key3.save()

    cls.key4_path = os.path.join(cls.key_dir, 'key4')
    ssh_keygen(file=cls.key4_path)

  @classmethod
  def tearDownClass(cls):
    settings.SSHKEY_AUTHORIZED_KEYS_OPTIONS = cls.original_options
    User.objects.all().delete()
    super(UserKeyLookupTestCase, cls).tearDownClass()

  def test_lookup_all(self):
    client = Client()
272
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
273 274 275 276
    response = client.get(url)
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
277 278
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
279 280 281
      'command="user1" ' + open(self.key1_path + '.pub').read().strip(),
      'command="user1" ' + open(self.key2_path + '.pub').read().strip(),
      'command="user2" ' + open(self.key3_path + '.pub').read().strip(),
282 283
    ))
    self.assertEqual(actual_content, correct_content)
Scott Duckworth committed
284 285 286

  def test_lookup_by_fingerprint(self):
    client = Client()
287
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
288 289 290 291 292 293
    fingerprint = ssh_fingerprint(self.key1_path+'.pub')
    response = client.get(url, {'fingerprint': fingerprint})
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
    username = self.user1.username
294 295
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
296
      'command="user1" ' + open(self.key1_path + '.pub').read().strip(),
297 298
    ))
    self.assertEqual(actual_content, correct_content)
Scott Duckworth committed
299 300 301

  def test_lookup_by_username_single_result(self):
    client = Client()
302
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
303 304 305 306 307 308
    username = self.user2.username
    response = client.get(url, {'username': username})
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
    body = open(self.key1_path + '.pub').read().strip()
309 310
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
311
      'command="user2" ' + open(self.key3_path + '.pub').read().strip(),
312 313
    ))
    self.assertEqual(actual_content, correct_content)
Scott Duckworth committed
314 315 316

  def test_lookup_by_username_multiple_results(self):
    client = Client()
317
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
318 319 320 321 322 323
    username = self.user1.username
    response = client.get(url, {'username': username})
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
    body = open(self.key1_path + '.pub').read().strip()
324 325
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
326 327
      'command="user1" ' + open(self.key1_path + '.pub').read().strip(),
      'command="user1" ' + open(self.key2_path + '.pub').read().strip(),
328 329
    ))
    self.assertEqual(actual_content, correct_content)
330

Scott Duckworth committed
331 332
  def test_lookup_nonexist_fingerprint(self):
    client = Client()
333
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
334 335 336 337 338 339
    fingerprint = ssh_fingerprint(self.key4_path+'.pub')
    response = client.get(url, {'fingerprint': fingerprint})
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
    self.assertEqual(response.content, '')
340

Scott Duckworth committed
341 342
  def test_lookup_nonexist_username(self):
    client = Client()
343
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
344 345 346 347 348
    response = client.get(url, {'username': 'batman'})
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
    self.assertEqual(response.content, '')