2
0

archiver.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. from binascii import hexlify
  2. from configparser import RawConfigParser
  3. import os
  4. from io import StringIO
  5. import stat
  6. import subprocess
  7. import sys
  8. import shutil
  9. import tempfile
  10. import time
  11. import unittest
  12. from hashlib import sha256
  13. from attic import xattr
  14. from attic.archive import Archive, ChunkBuffer, CHUNK_MAX
  15. from attic.archiver import Archiver
  16. from attic.cache import Cache
  17. from attic.crypto import bytes16_to_int, num_aes_blocks
  18. from attic.helpers import Manifest
  19. from attic.key import parser
  20. from attic.remote import RemoteRepository, PathNotAllowed
  21. from attic.repository import Repository
  22. from attic.testsuite import AtticTestCase
  23. from attic.testsuite.mock import patch
  24. try:
  25. import llfuse
  26. has_llfuse = True
  27. except ImportError:
  28. has_llfuse = False
  29. has_lchflags = hasattr(os, 'lchflags')
  30. src_dir = os.path.join(os.getcwd(), os.path.dirname(__file__), '..')
  31. class changedir:
  32. def __init__(self, dir):
  33. self.dir = dir
  34. def __enter__(self):
  35. self.old = os.getcwd()
  36. os.chdir(self.dir)
  37. def __exit__(self, *args, **kw):
  38. os.chdir(self.old)
  39. class environment_variable:
  40. def __init__(self, **values):
  41. self.values = values
  42. self.old_values = {}
  43. def __enter__(self):
  44. for k, v in self.values.items():
  45. self.old_values[k] = os.environ.get(k)
  46. os.environ[k] = v
  47. def __exit__(self, *args, **kw):
  48. for k, v in self.old_values.items():
  49. if v is not None:
  50. os.environ[k] = v
  51. class ArchiverTestCaseBase(AtticTestCase):
  52. prefix = ''
  53. def setUp(self):
  54. os.environ['ATTIC_CHECK_I_KNOW_WHAT_I_AM_DOING'] = '1'
  55. self.archiver = Archiver()
  56. self.tmpdir = tempfile.mkdtemp()
  57. self.repository_path = os.path.join(self.tmpdir, 'repository')
  58. self.repository_location = self.prefix + self.repository_path
  59. self.input_path = os.path.join(self.tmpdir, 'input')
  60. self.output_path = os.path.join(self.tmpdir, 'output')
  61. self.keys_path = os.path.join(self.tmpdir, 'keys')
  62. self.cache_path = os.path.join(self.tmpdir, 'cache')
  63. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  64. os.environ['ATTIC_KEYS_DIR'] = self.keys_path
  65. os.environ['ATTIC_CACHE_DIR'] = self.cache_path
  66. os.mkdir(self.input_path)
  67. os.mkdir(self.output_path)
  68. os.mkdir(self.keys_path)
  69. os.mkdir(self.cache_path)
  70. with open(self.exclude_file_path, 'wb') as fd:
  71. fd.write(b'input/file2\n# A commment line, then a blank line\n\n')
  72. self._old_wd = os.getcwd()
  73. os.chdir(self.tmpdir)
  74. def tearDown(self):
  75. shutil.rmtree(self.tmpdir)
  76. os.chdir(self._old_wd)
  77. def attic(self, *args, **kw):
  78. exit_code = kw.get('exit_code', 0)
  79. fork = kw.get('fork', False)
  80. if fork:
  81. try:
  82. output = subprocess.check_output((sys.executable, '-m', 'attic.archiver') + args)
  83. ret = 0
  84. except subprocess.CalledProcessError as e:
  85. output = e.output
  86. ret = e.returncode
  87. output = os.fsdecode(output)
  88. if ret != exit_code:
  89. print(output)
  90. self.assert_equal(exit_code, ret)
  91. return output
  92. args = list(args)
  93. stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
  94. try:
  95. sys.stdin = StringIO()
  96. output = StringIO()
  97. sys.stdout = sys.stderr = output
  98. ret = self.archiver.run(args)
  99. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  100. if ret != exit_code:
  101. print(output.getvalue())
  102. self.assert_equal(exit_code, ret)
  103. return output.getvalue()
  104. finally:
  105. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  106. def create_src_archive(self, name):
  107. self.attic('create', self.repository_location + '::' + name, src_dir)
  108. class ArchiverTestCase(ArchiverTestCaseBase):
  109. def create_regular_file(self, name, size=0, contents=None):
  110. filename = os.path.join(self.input_path, name)
  111. if not os.path.exists(os.path.dirname(filename)):
  112. os.makedirs(os.path.dirname(filename))
  113. with open(filename, 'wb') as fd:
  114. if contents is None:
  115. contents = b'X' * size
  116. fd.write(contents)
  117. def create_test_files(self):
  118. """Create a minimal test case including all supported file types
  119. """
  120. # File
  121. self.create_regular_file('empty', size=0)
  122. # next code line raises OverflowError on 32bit cpu (raspberry pi 2):
  123. # 2600-01-01 > 2**64 ns
  124. #os.utime('input/empty', (19880895600, 19880895600))
  125. # thus, we better test with something not that far in future:
  126. # 2038-01-19 (1970 + 2^31 - 1 seconds) is the 32bit "deadline":
  127. os.utime('input/empty', (2**31 - 1, 2**31 - 1))
  128. self.create_regular_file('file1', size=1024 * 80)
  129. self.create_regular_file('flagfile', size=1024)
  130. # Directory
  131. self.create_regular_file('dir2/file2', size=1024 * 80)
  132. # File owner
  133. os.chown('input/file1', 100, 200)
  134. # File mode
  135. os.chmod('input/file1', 0o7755)
  136. os.chmod('input/dir2', 0o555)
  137. # Block device
  138. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  139. # Char device
  140. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  141. # Hard link
  142. os.link(os.path.join(self.input_path, 'file1'),
  143. os.path.join(self.input_path, 'hardlink'))
  144. # Symlink
  145. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  146. if xattr.is_enabled(self.input_path):
  147. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  148. # XXX this always fails for me
  149. # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot
  150. # same for newer ubuntu and centos.
  151. # if this is supported just on specific platform, platform should be checked first,
  152. # so that the test setup for all tests using it does not fail here always for others.
  153. #xattr.setxattr(os.path.join(self.input_path, 'link1'), 'user.foo_symlink', b'bar_symlink', follow_symlinks=False)
  154. # FIFO node
  155. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  156. if has_lchflags:
  157. os.lchflags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP)
  158. def test_basic_functionality(self):
  159. self.create_test_files()
  160. self.attic('init', self.repository_location)
  161. self.attic('create', self.repository_location + '::test', 'input')
  162. self.attic('create', self.repository_location + '::test.2', 'input')
  163. with changedir('output'):
  164. self.attic('extract', self.repository_location + '::test')
  165. self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
  166. self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 11)
  167. self.assert_dirs_equal('input', 'output/input')
  168. info_output = self.attic('info', self.repository_location + '::test')
  169. self.assert_in('Number of files: 4', info_output)
  170. shutil.rmtree(self.cache_path)
  171. with environment_variable(ATTIC_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='1'):
  172. info_output2 = self.attic('info', self.repository_location + '::test')
  173. # info_output2 starts with some "initializing cache" text but should
  174. # end the same way as info_output
  175. assert info_output2.endswith(info_output)
  176. def _extract_repository_id(self, path):
  177. return Repository(self.repository_path).id
  178. def _set_repository_id(self, path, id):
  179. config = RawConfigParser()
  180. config.read(os.path.join(path, 'config'))
  181. config.set('repository', 'id', hexlify(id).decode('ascii'))
  182. with open(os.path.join(path, 'config'), 'w') as fd:
  183. config.write(fd)
  184. return Repository(self.repository_path).id
  185. def test_sparse_file(self):
  186. # no sparse file support on Mac OS X
  187. sparse_support = sys.platform != 'darwin'
  188. filename = os.path.join(self.input_path, 'sparse')
  189. content = b'foobar'
  190. hole_size = 5 * CHUNK_MAX # 5 full chunker buffers
  191. with open(filename, 'wb') as fd:
  192. # create a file that has a hole at the beginning and end (if the
  193. # OS and filesystem supports sparse files)
  194. fd.seek(hole_size, 1)
  195. fd.write(content)
  196. fd.seek(hole_size, 1)
  197. pos = fd.tell()
  198. fd.truncate(pos)
  199. total_len = hole_size + len(content) + hole_size
  200. st = os.stat(filename)
  201. self.assert_equal(st.st_size, total_len)
  202. if sparse_support and hasattr(st, 'st_blocks'):
  203. self.assert_true(st.st_blocks * 512 < total_len / 10) # is input sparse?
  204. self.attic('init', self.repository_location)
  205. self.attic('create', self.repository_location + '::test', 'input')
  206. with changedir('output'):
  207. self.attic('extract', '--sparse', self.repository_location + '::test')
  208. self.assert_dirs_equal('input', 'output/input')
  209. filename = os.path.join(self.output_path, 'input', 'sparse')
  210. with open(filename, 'rb') as fd:
  211. # check if file contents are as expected
  212. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  213. self.assert_equal(fd.read(len(content)), content)
  214. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  215. st = os.stat(filename)
  216. self.assert_equal(st.st_size, total_len)
  217. if sparse_support and hasattr(st, 'st_blocks'):
  218. self.assert_true(st.st_blocks * 512 < total_len / 10) # is output sparse?
  219. def test_repository_swap_detection(self):
  220. self.create_test_files()
  221. os.environ['ATTIC_PASSPHRASE'] = 'passphrase'
  222. self.attic('init', '--encryption=passphrase', self.repository_location)
  223. repository_id = self._extract_repository_id(self.repository_path)
  224. self.attic('create', self.repository_location + '::test', 'input')
  225. shutil.rmtree(self.repository_path)
  226. self.attic('init', '--encryption=none', self.repository_location)
  227. self._set_repository_id(self.repository_path, repository_id)
  228. self.assert_equal(repository_id, self._extract_repository_id(self.repository_path))
  229. self.assert_raises(Cache.EncryptionMethodMismatch, lambda :self.attic('create', self.repository_location + '::test.2', 'input'))
  230. def test_repository_swap_detection2(self):
  231. self.create_test_files()
  232. self.attic('init', '--encryption=none', self.repository_location + '_unencrypted')
  233. os.environ['ATTIC_PASSPHRASE'] = 'passphrase'
  234. self.attic('init', '--encryption=passphrase', self.repository_location + '_encrypted')
  235. self.attic('create', self.repository_location + '_encrypted::test', 'input')
  236. shutil.rmtree(self.repository_path + '_encrypted')
  237. os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted')
  238. self.assert_raises(Cache.RepositoryAccessAborted, lambda :self.attic('create', self.repository_location + '_encrypted::test.2', 'input'))
  239. def test_strip_components(self):
  240. self.attic('init', self.repository_location)
  241. self.create_regular_file('dir/file')
  242. self.attic('create', self.repository_location + '::test', 'input')
  243. with changedir('output'):
  244. self.attic('extract', self.repository_location + '::test', '--strip-components', '3')
  245. self.assert_true(not os.path.exists('file'))
  246. with self.assert_creates_file('file'):
  247. self.attic('extract', self.repository_location + '::test', '--strip-components', '2')
  248. with self.assert_creates_file('dir/file'):
  249. self.attic('extract', self.repository_location + '::test', '--strip-components', '1')
  250. with self.assert_creates_file('input/dir/file'):
  251. self.attic('extract', self.repository_location + '::test', '--strip-components', '0')
  252. def test_extract_include_exclude(self):
  253. self.attic('init', self.repository_location)
  254. self.create_regular_file('file1', size=1024 * 80)
  255. self.create_regular_file('file2', size=1024 * 80)
  256. self.create_regular_file('file3', size=1024 * 80)
  257. self.create_regular_file('file4', size=1024 * 80)
  258. self.attic('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  259. with changedir('output'):
  260. self.attic('extract', self.repository_location + '::test', 'input/file1', )
  261. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  262. with changedir('output'):
  263. self.attic('extract', '--exclude=input/file2', self.repository_location + '::test')
  264. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  265. with changedir('output'):
  266. self.attic('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  267. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  268. def test_exclude_caches(self):
  269. self.attic('init', self.repository_location)
  270. self.create_regular_file('file1', size=1024 * 80)
  271. self.create_regular_file('cache1/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  272. self.create_regular_file('cache2/CACHEDIR.TAG', contents=b'invalid signature')
  273. self.attic('create', '--exclude-caches', self.repository_location + '::test', 'input')
  274. with changedir('output'):
  275. self.attic('extract', self.repository_location + '::test')
  276. self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1'])
  277. self.assert_equal(sorted(os.listdir('output/input/cache2')), ['CACHEDIR.TAG'])
  278. def test_path_normalization(self):
  279. self.attic('init', self.repository_location)
  280. self.create_regular_file('dir1/dir2/file', size=1024 * 80)
  281. with changedir('input/dir1/dir2'):
  282. self.attic('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  283. output = self.attic('list', self.repository_location + '::test')
  284. self.assert_not_in('..', output)
  285. self.assert_in(' input/dir1/dir2/file', output)
  286. def test_exclude_normalization(self):
  287. self.attic('init', self.repository_location)
  288. self.create_regular_file('file1', size=1024 * 80)
  289. self.create_regular_file('file2', size=1024 * 80)
  290. with changedir('input'):
  291. self.attic('create', '--exclude=file1', self.repository_location + '::test1', '.')
  292. with changedir('output'):
  293. self.attic('extract', self.repository_location + '::test1')
  294. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  295. with changedir('input'):
  296. self.attic('create', '--exclude=./file1', self.repository_location + '::test2', '.')
  297. with changedir('output'):
  298. self.attic('extract', self.repository_location + '::test2')
  299. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  300. self.attic('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input')
  301. with changedir('output'):
  302. self.attic('extract', self.repository_location + '::test3')
  303. self.assert_equal(sorted(os.listdir('output/input')), ['file2'])
  304. def test_repeated_files(self):
  305. self.create_regular_file('file1', size=1024 * 80)
  306. self.attic('init', self.repository_location)
  307. self.attic('create', self.repository_location + '::test', 'input', 'input')
  308. def test_overwrite(self):
  309. self.create_regular_file('file1', size=1024 * 80)
  310. self.create_regular_file('dir2/file2', size=1024 * 80)
  311. self.attic('init', self.repository_location)
  312. self.attic('create', self.repository_location + '::test', 'input')
  313. # Overwriting regular files and directories should be supported
  314. os.mkdir('output/input')
  315. os.mkdir('output/input/file1')
  316. os.mkdir('output/input/dir2')
  317. with changedir('output'):
  318. self.attic('extract', self.repository_location + '::test')
  319. self.assert_dirs_equal('input', 'output/input')
  320. # But non-empty dirs should fail
  321. os.unlink('output/input/file1')
  322. os.mkdir('output/input/file1')
  323. os.mkdir('output/input/file1/dir')
  324. with changedir('output'):
  325. self.attic('extract', self.repository_location + '::test', exit_code=1)
  326. def test_rename(self):
  327. self.create_regular_file('file1', size=1024 * 80)
  328. self.create_regular_file('dir2/file2', size=1024 * 80)
  329. self.attic('init', self.repository_location)
  330. self.attic('create', self.repository_location + '::test', 'input')
  331. self.attic('create', self.repository_location + '::test.2', 'input')
  332. self.attic('extract', '--dry-run', self.repository_location + '::test')
  333. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  334. self.attic('rename', self.repository_location + '::test', 'test.3')
  335. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  336. self.attic('rename', self.repository_location + '::test.2', 'test.4')
  337. self.attic('extract', '--dry-run', self.repository_location + '::test.3')
  338. self.attic('extract', '--dry-run', self.repository_location + '::test.4')
  339. # Make sure both archives have been renamed
  340. repository = Repository(self.repository_path)
  341. manifest, key = Manifest.load(repository)
  342. self.assert_equal(len(manifest.archives), 2)
  343. self.assert_in('test.3', manifest.archives)
  344. self.assert_in('test.4', manifest.archives)
  345. def test_delete(self):
  346. self.create_regular_file('file1', size=1024 * 80)
  347. self.create_regular_file('dir2/file2', size=1024 * 80)
  348. self.attic('init', self.repository_location)
  349. self.attic('create', self.repository_location + '::test', 'input')
  350. self.attic('create', self.repository_location + '::test.2', 'input')
  351. self.attic('extract', '--dry-run', self.repository_location + '::test')
  352. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  353. self.attic('delete', self.repository_location + '::test')
  354. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  355. self.attic('delete', self.repository_location + '::test.2')
  356. # Make sure all data except the manifest has been deleted
  357. repository = Repository(self.repository_path)
  358. self.assert_equal(len(repository), 1)
  359. def test_corrupted_repository(self):
  360. self.attic('init', self.repository_location)
  361. self.create_src_archive('test')
  362. self.attic('extract', '--dry-run', self.repository_location + '::test')
  363. self.attic('check', self.repository_location)
  364. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  365. with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+') as fd:
  366. fd.seek(100)
  367. fd.write('XXXX')
  368. self.attic('check', self.repository_location, exit_code=1)
  369. def test_readonly_repository(self):
  370. self.attic('init', self.repository_location)
  371. self.create_src_archive('test')
  372. os.system('chmod -R ugo-w ' + self.repository_path)
  373. try:
  374. self.attic('extract', '--dry-run', self.repository_location + '::test')
  375. finally:
  376. # Restore permissions so shutil.rmtree is able to delete it
  377. os.system('chmod -R u+w ' + self.repository_path)
  378. def test_cmdline_compatibility(self):
  379. self.create_regular_file('file1', size=1024 * 80)
  380. self.attic('init', self.repository_location)
  381. self.attic('create', self.repository_location + '::test', 'input')
  382. output = self.attic('verify', '-v', self.repository_location + '::test')
  383. self.assert_in('"attic verify" has been deprecated', output)
  384. output = self.attic('prune', self.repository_location, '--hourly=1')
  385. self.assert_in('"--hourly" has been deprecated. Use "--keep-hourly" instead', output)
  386. def test_prune_repository(self):
  387. self.attic('init', self.repository_location)
  388. self.attic('create', self.repository_location + '::test1', src_dir)
  389. self.attic('create', self.repository_location + '::test2', src_dir)
  390. output = self.attic('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2')
  391. self.assert_in('Keeping archive: test2', output)
  392. self.assert_in('Would prune: test1', output)
  393. output = self.attic('list', self.repository_location)
  394. self.assert_in('test1', output)
  395. self.assert_in('test2', output)
  396. self.attic('prune', self.repository_location, '--keep-daily=2')
  397. output = self.attic('list', self.repository_location)
  398. self.assert_not_in('test1', output)
  399. self.assert_in('test2', output)
  400. def test_usage(self):
  401. self.assert_raises(SystemExit, lambda: self.attic())
  402. self.assert_raises(SystemExit, lambda: self.attic('-h'))
  403. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  404. def test_fuse_mount_repository(self):
  405. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  406. os.mkdir(mountpoint)
  407. self.attic('init', self.repository_location)
  408. self.create_test_files()
  409. self.attic('create', self.repository_location + '::archive', 'input')
  410. self.attic('create', self.repository_location + '::archive2', 'input')
  411. try:
  412. self.attic('mount', self.repository_location, mountpoint, fork=True)
  413. self.wait_for_mount(mountpoint)
  414. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'))
  415. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'))
  416. finally:
  417. if sys.platform.startswith('linux'):
  418. os.system('fusermount -u ' + mountpoint)
  419. else:
  420. os.system('umount ' + mountpoint)
  421. os.rmdir(mountpoint)
  422. # Give the daemon some time to exit
  423. time.sleep(.2)
  424. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  425. def test_fuse_mount_archive(self):
  426. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  427. os.mkdir(mountpoint)
  428. self.attic('init', self.repository_location)
  429. self.create_test_files()
  430. self.attic('create', self.repository_location + '::archive', 'input')
  431. try:
  432. self.attic('mount', self.repository_location + '::archive', mountpoint, fork=True)
  433. self.wait_for_mount(mountpoint)
  434. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  435. finally:
  436. if sys.platform.startswith('linux'):
  437. os.system('fusermount -u ' + mountpoint)
  438. else:
  439. os.system('umount ' + mountpoint)
  440. os.rmdir(mountpoint)
  441. # Give the daemon some time to exit
  442. time.sleep(.2)
  443. def verify_aes_counter_uniqueness(self, method):
  444. seen = set() # Chunks already seen
  445. used = set() # counter values already used
  446. def verify_uniqueness():
  447. repository = Repository(self.repository_path)
  448. for key, _ in repository.open_index(repository.get_transaction_id()).iteritems():
  449. data = repository.get(key)
  450. hash = sha256(data).digest()
  451. if hash not in seen:
  452. seen.add(hash)
  453. mac, meta, data = parser(data)
  454. num_blocks = num_aes_blocks(len(data))
  455. nonce = bytes16_to_int(meta.iv)
  456. for counter in range(nonce, nonce + num_blocks):
  457. self.assert_not_in(counter, used)
  458. used.add(counter)
  459. self.create_test_files()
  460. os.environ['ATTIC_PASSPHRASE'] = 'passphrase'
  461. self.attic('init', '--encryption=' + method, self.repository_location)
  462. verify_uniqueness()
  463. self.attic('create', self.repository_location + '::test', 'input')
  464. verify_uniqueness()
  465. self.attic('create', self.repository_location + '::test.2', 'input')
  466. verify_uniqueness()
  467. self.attic('delete', self.repository_location + '::test.2')
  468. verify_uniqueness()
  469. self.assert_equal(used, set(range(len(used))))
  470. def test_aes_counter_uniqueness_keyfile(self):
  471. self.verify_aes_counter_uniqueness('keyfile')
  472. def test_aes_counter_uniqueness_passphrase(self):
  473. self.verify_aes_counter_uniqueness('passphrase')
  474. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  475. def setUp(self):
  476. super(ArchiverCheckTestCase, self).setUp()
  477. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  478. self.attic('init', self.repository_location)
  479. self.create_src_archive('archive1')
  480. self.create_src_archive('archive2')
  481. def open_archive(self, name):
  482. repository = Repository(self.repository_path)
  483. manifest, key = Manifest.load(repository)
  484. archive = Archive(repository, key, manifest, name)
  485. return archive, repository
  486. def test_check_usage(self):
  487. output = self.attic('check', self.repository_location, exit_code=0)
  488. self.assert_in('Starting repository check', output)
  489. self.assert_in('Starting archive consistency check', output)
  490. output = self.attic('check', '--repository-only', self.repository_location, exit_code=0)
  491. self.assert_in('Starting repository check', output)
  492. self.assert_not_in('Starting archive consistency check', output)
  493. output = self.attic('check', '--archives-only', self.repository_location, exit_code=0)
  494. self.assert_not_in('Starting repository check', output)
  495. self.assert_in('Starting archive consistency check', output)
  496. def test_missing_file_chunk(self):
  497. archive, repository = self.open_archive('archive1')
  498. for item in archive.iter_items():
  499. if item[b'path'].endswith('testsuite/archiver.py'):
  500. repository.delete(item[b'chunks'][-1][0])
  501. break
  502. repository.commit()
  503. self.attic('check', self.repository_location, exit_code=1)
  504. self.attic('check', '--repair', self.repository_location, exit_code=0)
  505. self.attic('check', self.repository_location, exit_code=0)
  506. def test_missing_archive_item_chunk(self):
  507. archive, repository = self.open_archive('archive1')
  508. repository.delete(archive.metadata[b'items'][-5])
  509. repository.commit()
  510. self.attic('check', self.repository_location, exit_code=1)
  511. self.attic('check', '--repair', self.repository_location, exit_code=0)
  512. self.attic('check', self.repository_location, exit_code=0)
  513. def test_missing_archive_metadata(self):
  514. archive, repository = self.open_archive('archive1')
  515. repository.delete(archive.id)
  516. repository.commit()
  517. self.attic('check', self.repository_location, exit_code=1)
  518. self.attic('check', '--repair', self.repository_location, exit_code=0)
  519. self.attic('check', self.repository_location, exit_code=0)
  520. def test_missing_manifest(self):
  521. archive, repository = self.open_archive('archive1')
  522. repository.delete(Manifest.manifest_id(repository))
  523. repository.commit()
  524. self.attic('check', self.repository_location, exit_code=1)
  525. output = self.attic('check', '--repair', self.repository_location, exit_code=0)
  526. self.assert_in('archive1', output)
  527. self.assert_in('archive2', output)
  528. self.attic('check', self.repository_location, exit_code=0)
  529. def test_extra_chunks(self):
  530. self.attic('check', self.repository_location, exit_code=0)
  531. repository = Repository(self.repository_location)
  532. repository.put(b'0123456789012345', b'xxxx')
  533. repository.commit()
  534. repository.close()
  535. self.attic('check', self.repository_location, exit_code=1)
  536. self.attic('check', self.repository_location, exit_code=1)
  537. self.attic('check', '--repair', self.repository_location, exit_code=0)
  538. self.attic('check', self.repository_location, exit_code=0)
  539. self.attic('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  540. class RemoteArchiverTestCase(ArchiverTestCase):
  541. prefix = '__testsuite__:'
  542. def test_remote_repo_restrict_to_path(self):
  543. self.attic('init', self.repository_location)
  544. path_prefix = os.path.dirname(self.repository_path)
  545. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  546. self.assert_raises(PathNotAllowed, lambda: self.attic('init', self.repository_location + '_1'))
  547. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  548. self.attic('init', self.repository_location + '_2')
  549. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  550. self.attic('init', self.repository_location + '_3')