tests.py 11.6 KB
Newer Older
1 2
# Copyright (c) 2014, Clemson University
# All rights reserved.
Scott Duckworth committed
3
#
4 5
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
Scott Duckworth committed
6
#
7 8
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
Scott Duckworth committed
9
#
10 11 12
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
Scott Duckworth committed
13
#
14 15 16 17 18 19 20 21 22 23 24 25 26 27
# * Neither the name of the {organization} nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Scott Duckworth committed
28

Scott Duckworth committed
29 30 31 32 33
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
34 35
from django_sshkey.models import UserKey
from django_sshkey import settings
Scott Duckworth committed
36 37 38 39
import os
import shutil
import subprocess
import tempfile
40

Scott Duckworth committed
41 42 43 44 45 46 47 48 49 50 51
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)
52

Scott Duckworth committed
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 125 126 127 128 129 130 131 132 133 134 135
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
136 137 138 139 140 141 142 143
  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
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  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
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 272 273 274 275 276 277 278 279 280 281 282
  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()
283
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
284 285 286 287
    response = client.get(url)
    self.assertEqual(response.status_code, 200)
    self.assertIn('Content-Type', response)
    self.assertEqual(response['Content-Type'], 'text/plain')
288 289
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
290 291 292
      '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(),
293 294
    ))
    self.assertEqual(actual_content, correct_content)
Scott Duckworth committed
295 296 297

  def test_lookup_by_fingerprint(self):
    client = Client()
298
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
299 300 301 302 303 304
    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
305 306
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
307
      'command="user1" ' + open(self.key1_path + '.pub').read().strip(),
308 309
    ))
    self.assertEqual(actual_content, correct_content)
Scott Duckworth committed
310 311 312

  def test_lookup_by_username_single_result(self):
    client = Client()
313
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
314 315 316 317 318 319
    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()
320 321
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
322
      'command="user2" ' + open(self.key3_path + '.pub').read().strip(),
323 324
    ))
    self.assertEqual(actual_content, correct_content)
Scott Duckworth committed
325 326 327

  def test_lookup_by_username_multiple_results(self):
    client = Client()
328
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
329 330 331 332 333 334
    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()
335 336
    actual_content = set(response.content.strip().split('\n'))
    correct_content = set((
Scott Duckworth committed
337 338
      'command="user1" ' + open(self.key1_path + '.pub').read().strip(),
      'command="user1" ' + open(self.key2_path + '.pub').read().strip(),
339 340
    ))
    self.assertEqual(actual_content, correct_content)
341

Scott Duckworth committed
342 343
  def test_lookup_nonexist_fingerprint(self):
    client = Client()
344
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
345 346 347 348 349 350
    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, '')
351

Scott Duckworth committed
352 353
  def test_lookup_nonexist_username(self):
    client = Client()
354
    url = reverse('django_sshkey.views.lookup')
Scott Duckworth committed
355 356 357 358 359
    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, '')