MetaData Sharing
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

989 lines
28 KiB

  1. #!/usr/bin/env python
  2. #import pdb, sys; mypdb = pdb.Pdb(stdout=sys.stderr); mypdb.set_trace()
  3. from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey, \
  4. Ed448PublicKey
  5. from cryptography.hazmat.primitives.serialization import Encoding, \
  6. PrivateFormat, PublicFormat, NoEncryption
  7. import base58
  8. import copy
  9. import datetime
  10. import hashlib
  11. import mock
  12. import os.path
  13. import pasn1
  14. import shutil
  15. import string
  16. import tempfile
  17. import unittest
  18. import uuid
  19. from contextlib import nested
  20. # The UUID for the namespace representing the path to a file
  21. _NAMESPACE_MEDASHARE_PATH = uuid.UUID('f6f36b62-3770-4a68-bc3d-dc3e31e429e6')
  22. _defaulthash = 'sha512'
  23. _validhashes = set([ 'sha256', 'sha512' ])
  24. _hashlengths = { len(getattr(hashlib, x)().hexdigest()): x for x in _validhashes }
  25. def _iterdictlist(obj):
  26. itms = obj.items()
  27. itms.sort()
  28. for k, v in itms:
  29. if isinstance(v, list):
  30. v = v[:]
  31. v.sort()
  32. for i in v:
  33. yield k, i
  34. else:
  35. yield k, v
  36. def _makeuuid(s):
  37. if isinstance(s, uuid.UUID):
  38. return s
  39. return uuid.UUID(s)
  40. # XXX - known issue, store is not atomic/safe, overwrites in place instead of renames
  41. # XXX - add validation
  42. # XXX - how to add singletons
  43. class MDBase(object):
  44. '''This is a simple wrapper that turns a JSON object into a pythonesc
  45. object where attribute accesses work.'''
  46. _type = 'invalid'
  47. _generated_properties = {
  48. 'uuid': uuid.uuid4,
  49. 'modified': datetime.datetime.utcnow
  50. }
  51. # When decoding, the decoded value should be passed to this function
  52. # to get the correct type
  53. _instance_properties = {
  54. 'uuid': _makeuuid,
  55. 'created_by_ref': _makeuuid,
  56. }
  57. _common_properties = [ 'type', 'created_by_ref' ] # XXX - add lang?
  58. _common_optional = set(('overlay_refs', 'sig'))
  59. _common_names = set(_common_properties + _generated_properties.keys())
  60. def __init__(self, obj={}, **kwargs):
  61. obj = copy.deepcopy(obj)
  62. obj.update(kwargs)
  63. if self._type == MDBase._type:
  64. raise ValueError('call MDBase.create_obj instead so correct class is used.')
  65. if 'type' in obj and obj['type'] != self._type:
  66. raise ValueError(
  67. 'trying to create the wrong type of object, got: %s, expected: %s' %
  68. (`obj['type']`, `self._type`))
  69. if 'type' not in obj:
  70. obj['type'] = self._type
  71. for x in self._common_properties:
  72. if x not in obj:
  73. raise ValueError('common property %s not present' % `x`)
  74. for x, fun in self._instance_properties.iteritems():
  75. if x in obj:
  76. obj[x] = fun(obj[x])
  77. for x, fun in self._generated_properties.iteritems():
  78. if x not in obj:
  79. obj[x] = fun()
  80. self._obj = obj
  81. @classmethod
  82. def create_obj(cls, obj):
  83. '''Using obj as a base, create an instance of MDBase of the
  84. correct type.
  85. If the correct type is not found, a ValueError is raised.'''
  86. if isinstance(obj, cls):
  87. obj = obj._obj
  88. ty = obj['type']
  89. for i in MDBase.__subclasses__():
  90. if i._type == ty:
  91. return i(obj)
  92. else:
  93. raise ValueError('Unable to find class for type %s' %
  94. `ty`)
  95. def new_version(self, *args):
  96. '''For each k, v pari, add the property k as an additional one
  97. (or new one if first), with the value v.'''
  98. obj = copy.deepcopy(self._obj)
  99. common = self._common_names | self._common_optional
  100. for k, v in args:
  101. if k in common:
  102. obj[k] = v
  103. else:
  104. obj.setdefault(k, []).append(v)
  105. del obj['modified']
  106. return self.create_obj(obj)
  107. def __repr__(self): # pragma: no cover
  108. return '%s(%s)' % (self.__class__.__name__, `self._obj`)
  109. def __getattr__(self, k):
  110. return self._obj[k]
  111. def __setattr__(self, k, v):
  112. if k[0] == '_': # direct attribute
  113. self.__dict__[k] = v
  114. else:
  115. self._obj[k] = v
  116. def __getitem__(self, k):
  117. return self._obj[k]
  118. def __to_dict__(self):
  119. return self._obj
  120. def __eq__(self, o):
  121. return cmp(self._obj, o) == 0
  122. def __contains__(self, k):
  123. return k in self._obj
  124. def items(self, skipcommon=True):
  125. return [ (k, v) for k, v in self._obj.iteritems() if
  126. not skipcommon or k not in self._common_names ]
  127. def encode(self):
  128. return _asn1coder.dumps(self)
  129. @classmethod
  130. def decode(cls, s):
  131. return cls.create_obj(_asn1coder.loads(s))
  132. class MetaData(MDBase):
  133. _type = 'metadata'
  134. class Identity(MDBase):
  135. _type = 'identity'
  136. # Identites don't need a created by
  137. _common_properties = [ x for x in MDBase._common_properties if x !=
  138. 'created_by_ref' ]
  139. _common_optional = set([ x for x in MDBase._common_optional if x !=
  140. 'overlay_refs' ] + [ 'name', 'pubkey' ])
  141. _common_names = set(_common_properties + MDBase._generated_properties.keys())
  142. def _trytodict(o):
  143. if isinstance(o, uuid.UUID):
  144. return 'unicode', str(o)
  145. try:
  146. return 'dict', o.__to_dict__()
  147. except Exception: # pragma: no cover
  148. raise TypeError('unable to find __to_dict__ on %s: %s' % (type(o), `o`))
  149. _asn1coder = pasn1.ASN1DictCoder(coerce=_trytodict)
  150. class Persona(object):
  151. '''The object that represents a persona, or identity. It will
  152. create the proper identity object, serialize for saving keys,
  153. create objects for that persona and other management.'''
  154. def __init__(self, identity=None, key=None):
  155. if identity is None:
  156. self._identity = Identity()
  157. else:
  158. self._identity = identity
  159. self._key = key
  160. self._pubkey = None
  161. if 'pubkey' in self._identity:
  162. pubkeybytes = self._identity.pubkey
  163. self._pubkey = Ed448PublicKey.from_public_bytes(pubkeybytes)
  164. self._created_by_ref = self._identity.uuid
  165. def get_identity(self):
  166. '''Return the Identity object for this Persona.'''
  167. return self._identity
  168. def get_pubkey(self):
  169. '''Get a printable version of the public key. This is used
  170. for importing into different programs, or for shared.'''
  171. return base58.b58encode_check(self._identity.pubkey)
  172. def new_version(self, *args):
  173. '''Update the Persona's Identity object.'''
  174. self._identity = self.sign(self._identity.new_version(*args))
  175. return self._identity
  176. def store(self, fname):
  177. '''Store the Persona to a file. If there is a private
  178. key associated w/ the Persona, it will be saved as well.'''
  179. with open(fname, 'w') as fp:
  180. obj = {
  181. 'identity': self._identity,
  182. }
  183. if self._key is not None:
  184. obj['key'] = \
  185. self._key.private_bytes(Encoding.Raw,
  186. PrivateFormat.Raw, NoEncryption())
  187. fp.write(_asn1coder.dumps(obj))
  188. @classmethod
  189. def load(cls, fname):
  190. '''Load the Persona from the provided file.'''
  191. with open(fname) as fp:
  192. objs = _asn1coder.loads(fp.read())
  193. kwargs = {}
  194. if 'key' in objs:
  195. kwargs['key'] = Ed448PrivateKey.from_private_bytes(objs['key'])
  196. return cls(Identity(objs['identity']), **kwargs)
  197. def generate_key(self):
  198. '''Generate a key for this Identity.
  199. Raises a RuntimeError if a key is already present.'''
  200. if self._key:
  201. raise RuntimeError('a key already exists')
  202. self._key = Ed448PrivateKey.generate()
  203. self._pubkey = self._key.public_key()
  204. pubkey = self._pubkey.public_bytes(Encoding.Raw,
  205. PublicFormat.Raw)
  206. self._identity = self.sign(self._identity.new_version(('pubkey',
  207. pubkey)))
  208. def _makesigbytes(self, obj):
  209. obj = dict(obj.items(False))
  210. try:
  211. del obj['sig']
  212. except KeyError:
  213. pass
  214. return _asn1coder.dumps(obj)
  215. def sign(self, obj):
  216. '''Takes the object, adds a signature, and returns the new
  217. object.'''
  218. sigbytes = self._makesigbytes(obj)
  219. sig = self._key.sign(sigbytes)
  220. newobj = MDBase.create_obj(obj)
  221. newobj.sig = sig
  222. return newobj
  223. def verify(self, obj):
  224. sigbytes = self._makesigbytes(obj)
  225. self._pubkey.verify(obj['sig'], sigbytes)
  226. return True
  227. def by_file(self, fname):
  228. '''Return a metadata object for the file named fname.'''
  229. fobj = FileObject.from_file(fname, self._created_by_ref)
  230. return self.sign(fobj)
  231. class ObjectStore(object):
  232. '''A container to store for the various Metadata objects.'''
  233. # The _uuids property contains both the UUIDv4 for objects, and
  234. # looking up the UUIDv5 for FileObjects.
  235. def __init__(self, created_by_ref):
  236. self._created_by_ref = created_by_ref
  237. self._uuids = {}
  238. self._hashes = {}
  239. @staticmethod
  240. def makehash(hashstr, strict=True):
  241. '''Take a hash string, and return a valid hash string from it.
  242. This makes sure that it is of the correct type and length.
  243. If strict is False, the function will detect the length and
  244. return a valid hash if one can be found.'''
  245. try:
  246. hash, value = hashstr.split(':')
  247. except ValueError:
  248. if strict:
  249. raise
  250. hash = _hashlengths[len(hashstr)]
  251. value = hashstr
  252. if strict and len(str(value).translate(None, string.hexdigits.lower())) != 0:
  253. raise ValueError('value has invalid hex digits (must be lower case)', value)
  254. if hash in _validhashes:
  255. return ':'.join((hash, value))
  256. raise ValueError
  257. def __len__(self):
  258. return len(self._uuids)
  259. def store(self, fname):
  260. '''Write out the objects in the store to the file named
  261. fname.'''
  262. with open(fname, 'w') as fp:
  263. obj = {
  264. 'created_by_ref': self._created_by_ref,
  265. 'objects': self._uuids.values(),
  266. }
  267. fp.write(_asn1coder.dumps(obj))
  268. def loadobj(self, obj):
  269. '''Load obj into the data store.'''
  270. obj = MDBase.create_obj(obj)
  271. self._uuids[obj.uuid] = obj
  272. for j in obj.hashes:
  273. h = self.makehash(j)
  274. self._hashes.setdefault(h, []).append(obj)
  275. @classmethod
  276. def load(cls, fname):
  277. '''Load objects from the provided file name.
  278. Basic validation will be done on the objects in the file.
  279. The objects will be accessible via other methods.'''
  280. with open(fname) as fp:
  281. objs = _asn1coder.loads(fp.read())
  282. obj = cls(objs['created_by_ref'])
  283. for i in objs['objects']:
  284. obj.loadobj(i)
  285. return obj
  286. def by_id(self, id):
  287. '''Look up an object by it's UUID.'''
  288. if not isinstance(id, uuid.UUID):
  289. uid = uuid.UUID(id)
  290. else:
  291. uid = id
  292. return self._uuids[uid]
  293. def by_hash(self, hash):
  294. '''Look up an object by it's hash value.'''
  295. h = self.makehash(hash, strict=False)
  296. return self._hashes[h]
  297. def by_file(self, fname):
  298. '''Return a metadata object for the file named fname.'''
  299. fid = FileObject.make_id(fname)
  300. try:
  301. fobj = self.by_id(fid)
  302. except KeyError:
  303. # unable to find it
  304. fobj = FileObject.from_file(fname, self._created_by_ref)
  305. self.loadobj(fobj)
  306. for i in fobj.hashes:
  307. j = self.by_hash(i)
  308. # Filter out non-metadata objects
  309. j = [ x for x in j if x.type == 'metadata' ]
  310. if j:
  311. return j
  312. else:
  313. raise KeyError('unable to find metadata for file')
  314. def _hashfile(fname):
  315. hash = getattr(hashlib, _defaulthash)()
  316. with open(fname) as fp:
  317. r = fp.read()
  318. hash.update(r)
  319. return '%s:%s' % (_defaulthash, hash.hexdigest())
  320. class FileObject(MDBase):
  321. _type = 'file'
  322. @staticmethod
  323. def make_id(fname):
  324. '''Take a local file name, and make the id for it. Note that
  325. converts from the local path separator to a forward slash so
  326. that it will be the same between Windows and Unix systems.'''
  327. fname = os.path.realpath(fname)
  328. return uuid.uuid5(_NAMESPACE_MEDASHARE_PATH,
  329. '/'.join(os.path.split(fname)))
  330. @classmethod
  331. def from_file(cls, filename, created_by_ref):
  332. s = os.stat(filename)
  333. obj = {
  334. 'dir': os.path.dirname(filename),
  335. 'created_by_ref': created_by_ref,
  336. 'filename': os.path.basename(filename),
  337. 'id': cls.make_id(filename),
  338. 'mtime': datetime.datetime.utcfromtimestamp(s.st_mtime),
  339. 'size': s.st_size,
  340. 'hashes': [ _hashfile(filename), ],
  341. }
  342. return cls(obj)
  343. def enumeratedir(_dir, created_by_ref):
  344. '''Enumerate all the files and directories (not recursive) in _dir.
  345. Returned is a list of FileObjects.'''
  346. return map(lambda x: FileObject.from_file(os.path.join(_dir, x), created_by_ref),
  347. os.listdir(_dir))
  348. def main():
  349. from optparse import OptionParser
  350. import sys
  351. parser = OptionParser()
  352. parser.add_option('-a', action='append', dest='add',
  353. default=[], help='add the arg as metadata for files, tag=value')
  354. parser.add_option('-d', action='append', dest='delete',
  355. default=[], help='delete the arg as metadata from files. Either specify tag, and all tags are removed, or specify tag=value and that specific tag will be removed.')
  356. parser.add_option('-g', action='store_true', dest='generateident',
  357. default=False, help='generate an identity')
  358. parser.add_option('-i', action='store_true', dest='updateident',
  359. default=False, help='update the identity')
  360. parser.add_option('-l', action='store_true', dest='list',
  361. default=False, help='list metadata')
  362. parser.add_option('-p', action='store_true', dest='printpub',
  363. default=False, help='Print the public key of the identity')
  364. options, args = parser.parse_args()
  365. # this is shared between generateident and add
  366. addprops = map(lambda x: x.split('=', 1), options.add)
  367. if options.generateident or options.updateident or options.printpub:
  368. identfname = os.path.expanduser('~/.medashare_identity.pasn1')
  369. if options.generateident and os.path.exists(identfname):
  370. print >>sys.stderr, 'Error: Identity already created.'
  371. sys.exit(1)
  372. if options.generateident:
  373. persona = Persona()
  374. persona.generate_key()
  375. else:
  376. persona = Persona.load(identfname)
  377. if options.printpub:
  378. print persona.get_pubkey()
  379. return
  380. persona.new_version(*addprops)
  381. persona.store(identfname)
  382. return
  383. storefname = os.path.expanduser('~/.medashare_store.pasn1')
  384. import sys
  385. #print >>sys.stderr, `storefname`
  386. objstr = ObjectStore.load(storefname)
  387. if options.list:
  388. for i in args:
  389. for j in objstr.by_file(i):
  390. #print >>sys.stderr, `j._obj`
  391. for k, v in _iterdictlist(j):
  392. print '%s:\t%s' % (k, v)
  393. elif options.add:
  394. for i in args:
  395. for j in objstr.by_file(i):
  396. nobj = j.new_version(*addprops)
  397. objstr.loadobj(nobj)
  398. elif options.delete:
  399. for i in args:
  400. for j in objstr.by_file(i):
  401. obj = j.__to_dict__()
  402. for k in options.delete:
  403. try:
  404. key, v = k.split('=', 1)
  405. obj[key].remove(v)
  406. except ValueError:
  407. del obj[k]
  408. nobj = MDBase.create_obj(obj)
  409. objstr.loadobj(nobj)
  410. else: # pragma: no cover
  411. raise NotImplementedError
  412. objstr.store(storefname)
  413. if __name__ == '__main__': # pragma: no cover
  414. main()
  415. class _TestCases(unittest.TestCase):
  416. def setUp(self):
  417. d = os.path.realpath(tempfile.mkdtemp())
  418. self.basetempdir = d
  419. self.tempdir = os.path.join(d, 'subdir')
  420. persona = Persona.load(os.path.join('fixtures', 'sample.persona.pasn1'))
  421. self.created_by_ref = persona.get_identity().uuid
  422. shutil.copytree(os.path.join('fixtures', 'testfiles'),
  423. self.tempdir)
  424. def tearDown(self):
  425. shutil.rmtree(self.basetempdir)
  426. self.tempdir = None
  427. def test_mdbase(self):
  428. self.assertRaises(ValueError, MDBase, created_by_ref='')
  429. self.assertRaises(ValueError, MDBase.create_obj, { 'type': 'unknosldkfj' })
  430. self.assertRaises(ValueError, MDBase.create_obj, { 'type': 'metadata' })
  431. baseobj = {
  432. 'type': 'metadata',
  433. 'created_by_ref': self.created_by_ref,
  434. }
  435. origbase = copy.deepcopy(baseobj)
  436. # that when an MDBase object is created
  437. md = MDBase.create_obj(baseobj)
  438. # it doesn't modify the passed in object (when adding
  439. # generated properties)
  440. self.assertEqual(baseobj, origbase)
  441. # and it has the generted properties
  442. # Note: cannot mock the functions as they are already
  443. # referenced at creation time
  444. self.assertIn('uuid', md)
  445. self.assertIn('modified', md)
  446. # That you can create a new version using new_version
  447. md2 = md.new_version(('dc:creator', 'Jim Bob',))
  448. # that they are different
  449. self.assertNotEqual(md, md2)
  450. # and that the new modified time is different from the old
  451. self.assertNotEqual(md.modified, md2.modified)
  452. # and that the modification is present
  453. self.assertEqual(md2['dc:creator'], [ 'Jim Bob' ])
  454. # that providing a value from common property
  455. fvalue = 'fakesig'
  456. md3 = md.new_version(('sig', fvalue))
  457. # gets set directly, and is not a list
  458. self.assertEqual(md3.sig, fvalue)
  459. def test_mdbase_encode_decode(self):
  460. # that an object
  461. baseobj = {
  462. 'type': 'metadata',
  463. 'created_by_ref': self.created_by_ref,
  464. }
  465. obj = MDBase.create_obj(baseobj)
  466. # can be encoded
  467. coded = obj.encode()
  468. # and that the rsults can be decoded
  469. decobj = MDBase.decode(coded)
  470. # and that they are equal
  471. self.assertEqual(obj, decobj)
  472. def test_mdbase_wrong_type(self):
  473. # that created_by_ref can be passed by kw
  474. obj = MetaData(created_by_ref=self.created_by_ref)
  475. self.assertRaises(ValueError, FileObject, dict(obj.items(False)))
  476. def test_makehash(self):
  477. self.assertRaises(ValueError, ObjectStore.makehash, 'slkj')
  478. self.assertRaises(ValueError, ObjectStore.makehash, 'sha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ADA')
  479. self.assertRaises(ValueError, ObjectStore.makehash, 'bogushash:9e0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ADA', strict=False)
  480. self.assertEqual(ObjectStore.makehash('cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e', strict=False), 'sha512:cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e')
  481. self.assertEqual(ObjectStore.makehash('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', strict=False), 'sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
  482. def test_enumeratedir(self):
  483. files = enumeratedir(self.tempdir, self.created_by_ref)
  484. ftest = files[0]
  485. fname = 'test.txt'
  486. # make sure that they are of type MDBase
  487. self.assertIsInstance(ftest, MDBase)
  488. oldid = ftest.id
  489. self.assertEqual(ftest.filename, fname)
  490. self.assertEqual(ftest.dir, self.tempdir)
  491. # XXX - do we add host information?
  492. self.assertEqual(ftest.id, uuid.uuid5(_NAMESPACE_MEDASHARE_PATH,
  493. '/'.join(os.path.split(self.tempdir) +
  494. ( fname, ))))
  495. self.assertEqual(ftest.mtime, datetime.datetime(2019, 5, 20, 21, 47, 36))
  496. self.assertEqual(ftest.size, 15)
  497. self.assertIn('sha512:7d5768d47b6bc27dc4fa7e9732cfa2de506ca262a2749cb108923e5dddffde842bbfee6cb8d692fb43aca0f12946c521cce2633887914ca1f96898478d10ad3f', ftest.hashes)
  498. # XXX - make sure works w/ relative dirs
  499. files = enumeratedir(os.path.relpath(self.tempdir),
  500. self.created_by_ref)
  501. self.assertEqual(oldid, files[0].id)
  502. def test_mdbaseoverlay(self):
  503. objst = ObjectStore(self.created_by_ref)
  504. # that a base object
  505. bid = uuid.uuid4()
  506. objst.loadobj({
  507. 'type': 'metadata',
  508. 'uuid': bid,
  509. 'modified': datetime.datetime(2019, 6, 10, 14, 3, 10),
  510. 'created_by_ref': self.created_by_ref,
  511. 'hashes': [ 'sha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada' ],
  512. 'someprop': [ 'somevalue' ],
  513. 'lang': 'en',
  514. })
  515. # can have an overlay object
  516. oid = uuid.uuid4()
  517. dhash = 'sha256:a7c96262c21db9a06fd49e307d694fd95f624569f9b35bb3ffacd880440f9787'
  518. objst.loadobj({
  519. 'type': 'metadata',
  520. 'uuid': oid,
  521. 'modified': datetime.datetime(2019, 6, 10, 18, 3, 10),
  522. 'created_by_ref': self.created_by_ref,
  523. 'hashes': [ dhash ],
  524. 'overlay_refs': [ bid ],
  525. 'lang': 'en',
  526. })
  527. # and that when you get it's properties
  528. oobj = objst.by_id(oid)
  529. odict = dict(oobj.items())
  530. # that is has the overlays property
  531. self.assertEqual(odict['overlay_refs'], [ bid ])
  532. # that it doesn't have a common property
  533. self.assertNotIn('type', odict)
  534. # that when skipcommon is False
  535. odict = dict(oobj.items(False))
  536. # that it does have a common property
  537. self.assertIn('type', odict)
  538. def test_persona(self):
  539. # that a newly created persona
  540. persona = Persona()
  541. # has an identity object
  542. idobj = persona.get_identity()
  543. # that a key can be generated
  544. persona.generate_key()
  545. # that the pubkey property is present
  546. idobj = persona.get_identity()
  547. self.assertIsInstance(idobj['pubkey'], str)
  548. # that get_pubkey returns the correct thing
  549. self.assertEqual(persona.get_pubkey(), base58.b58encode_check(idobj['pubkey']))
  550. # and that there is a signature
  551. self.assertIsInstance(idobj['sig'], str)
  552. # that a second time, it raises an exception
  553. self.assertRaises(RuntimeError, persona.generate_key)
  554. # that a file object created by it
  555. testfname = os.path.join(self.tempdir, 'test.txt')
  556. testobj = persona.by_file(testfname)
  557. # has the correct created_by_ref
  558. self.assertEqual(testobj.created_by_ref, idobj.uuid)
  559. # and has a signature
  560. self.assertIn('sig', testobj)
  561. # that a persona created from the identity object
  562. vpersona = Persona(idobj)
  563. # can verify the sig
  564. self.assertTrue(vpersona.verify(testobj))
  565. # and that a bogus signature
  566. bogussig = 'somebogussig'
  567. bogusobj = MDBase.create_obj(testobj)
  568. bogusobj.sig = bogussig
  569. # fails to verify
  570. self.assertRaises(Exception, vpersona.verify, bogusobj)
  571. # and that a modified object
  572. otherobj = testobj.new_version(('customprop', 'value'))
  573. # fails to verify
  574. self.assertRaises(Exception, vpersona.verify, otherobj)
  575. # that a persona object can be written
  576. perpath = os.path.join(self.basetempdir, 'persona.pasn1')
  577. persona.store(perpath)
  578. # and that when loaded back
  579. loadpersona = Persona.load(perpath)
  580. # the new persona object can sign an object
  581. nvtestobj = loadpersona.sign(testobj.new_version())
  582. # and the old persona can verify it.
  583. self.assertTrue(vpersona.verify(nvtestobj))
  584. def test_objectstore(self):
  585. objst = ObjectStore.load(os.path.join('fixtures', 'sample.data.pasn1'))
  586. objst.loadobj({
  587. 'type': 'metadata',
  588. 'uuid': 'c9a1d1e2-3109-4efd-8948-577dc15e44e7',
  589. 'modified': datetime.datetime(2019, 5, 31, 14, 3, 10),
  590. 'created_by_ref': self.created_by_ref,
  591. 'hashes': [ 'sha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada' ],
  592. 'lang': 'en',
  593. })
  594. lst = objst.by_hash('91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada')
  595. self.assertEqual(len(lst), 2)
  596. byid = objst.by_id('3e466e06-45de-4ecc-84ba-2d2a3d970e96')
  597. self.assertIsInstance(byid, MetaData)
  598. self.assertIn(byid, lst)
  599. r = byid
  600. self.assertEqual(r.uuid, uuid.UUID('3e466e06-45de-4ecc-84ba-2d2a3d970e96'))
  601. self.assertEqual(r['dc:creator'], [ u'John-Mark Gurney' ])
  602. fname = 'testfile.pasn1'
  603. objst.store(fname)
  604. with open(fname) as fp:
  605. objs = _asn1coder.loads(fp.read())
  606. os.unlink(fname)
  607. self.assertEqual(len(objs), len(objst))
  608. self.assertEqual(objs['created_by_ref'], str(self.created_by_ref))
  609. for i in objs['objects']:
  610. i['created_by_ref'] = uuid.UUID(i['created_by_ref'])
  611. i['uuid'] = uuid.UUID(i['uuid'])
  612. self.assertEqual(objst.by_id(i['uuid']), i)
  613. testfname = os.path.join(self.tempdir, 'test.txt')
  614. self.assertEqual(objst.by_file(testfname), [ byid ])
  615. self.assertEqual(objst.by_file(testfname), [ byid ])
  616. self.assertRaises(KeyError, objst.by_file, '/dev/null')
  617. # XXX make sure that object store contains fileobject
  618. # Tests to add:
  619. # Non-duplicates when same metadata is located by multiple hashes.
  620. def test_main(self):
  621. # Test the main runner, this is only testing things that are
  622. # specific to running the program, like where the store is
  623. # created.
  624. # setup object store
  625. storefname = os.path.join(self.tempdir, 'storefname')
  626. identfname = os.path.join(self.tempdir, 'identfname')
  627. shutil.copy(os.path.join('fixtures', 'sample.data.pasn1'), storefname)
  628. # setup path mapping
  629. def expandusermock(arg):
  630. if arg == '~/.medashare_store.pasn1':
  631. return storefname
  632. elif arg == '~/.medashare_identity.pasn1':
  633. return identfname
  634. # setup test fname
  635. testfname = os.path.join(self.tempdir, 'test.txt')
  636. import sys
  637. import StringIO
  638. import itertools
  639. with mock.patch('os.path.expanduser', side_effect=expandusermock) \
  640. as eu:
  641. # that generating a new identity
  642. with nested(mock.patch('sys.stdout',
  643. StringIO.StringIO()), mock.patch('sys.argv',
  644. [ 'progname', '-g', '-a', 'name=A Test User' ])) as (stdout, argv):
  645. main()
  646. # does not output anything
  647. self.assertEqual(stdout.getvalue(), '')
  648. # looks up the correct file
  649. eu.assert_called_with('~/.medashare_identity.pasn1')
  650. # and that the identity
  651. persona = Persona.load(identfname)
  652. pident = persona.get_identity()
  653. # has the correct name
  654. self.assertEqual(pident.name, 'A Test User')
  655. # that when generating an identity when one already exists
  656. with nested(mock.patch('sys.stderr',
  657. StringIO.StringIO()), mock.patch('sys.argv',
  658. [ 'progname', '-g', '-a', 'name=A Test User' ])) as (stderr, argv):
  659. # that it exits
  660. with self.assertRaises(SystemExit) as cm:
  661. main()
  662. # with error code 1
  663. self.assertEqual(cm.exception[0], 1)
  664. # and outputs an error message
  665. self.assertEqual(stderr.getvalue(),
  666. 'Error: Identity already created.\n')
  667. # and looked up the correct file
  668. eu.assert_called_with('~/.medashare_identity.pasn1')
  669. # that when updating the identity
  670. with nested(mock.patch('sys.stdout',
  671. StringIO.StringIO()), mock.patch('sys.argv',
  672. [ 'progname', '-i', '-a', 'name=Changed Name' ])) as (stdout, argv):
  673. main()
  674. # it doesn't output anything
  675. self.assertEqual(stdout.getvalue(), '')
  676. # and looked up the correct file
  677. eu.assert_called_with('~/.medashare_identity.pasn1')
  678. npersona = Persona.load(identfname)
  679. nident = npersona.get_identity()
  680. # and has the new name
  681. self.assertEqual(nident.name, 'Changed Name')
  682. # and has the same old uuid
  683. self.assertEqual(nident.uuid, pident.uuid)
  684. # and that the modified date has changed
  685. self.assertNotEqual(pident.modified, nident.modified)
  686. # and that the old Persona can verify the new one
  687. self.assertTrue(persona.verify(nident))
  688. # that when asked to print the public key
  689. with nested(mock.patch('sys.stdout',
  690. StringIO.StringIO()), mock.patch('sys.argv',
  691. [ 'progname', '-p' ])) as (stdout, argv):
  692. main()
  693. # the correct key is printed
  694. self.assertEqual(stdout.getvalue(),
  695. '%s\n' % persona.get_pubkey())
  696. # and looked up the correct file
  697. eu.assert_called_with('~/.medashare_identity.pasn1')
  698. with nested(mock.patch('sys.stdout',
  699. StringIO.StringIO()), mock.patch('sys.argv',
  700. [ 'progname', '-l', testfname ])) as (stdout, argv):
  701. main()
  702. self.assertEqual(stdout.getvalue(),
  703. 'dc:creator:\tJohn-Mark Gurney\nhashes:\tsha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada\nhashes:\tsha512:7d5768d47b6bc27dc4fa7e9732cfa2de506ca262a2749cb108923e5dddffde842bbfee6cb8d692fb43aca0f12946c521cce2633887914ca1f96898478d10ad3f\nlang:\ten\n')
  704. eu.assert_called_with('~/.medashare_store.pasn1')
  705. with nested(mock.patch('sys.stdout',
  706. StringIO.StringIO()), mock.patch('sys.argv',
  707. [ 'progname', '-a', 'dc:creator=Another user', '-a', 'foo=bar=baz', testfname ])) as (stdout, argv):
  708. main()
  709. with nested(mock.patch('sys.stdout',
  710. StringIO.StringIO()), mock.patch('sys.argv',
  711. [ 'progname', '-l', testfname ])) as (stdout, argv):
  712. main()
  713. self.assertEqual(stdout.getvalue(),
  714. 'dc:creator:\tAnother user\ndc:creator:\tJohn-Mark Gurney\nfoo:\tbar=baz\nhashes:\tsha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada\nhashes:\tsha512:7d5768d47b6bc27dc4fa7e9732cfa2de506ca262a2749cb108923e5dddffde842bbfee6cb8d692fb43aca0f12946c521cce2633887914ca1f96898478d10ad3f\nlang:\ten\n')
  715. with nested(mock.patch('sys.stdout',
  716. StringIO.StringIO()), mock.patch('sys.argv',
  717. [ 'progname', '-d', 'dc:creator', testfname ])) as (stdout, argv):
  718. main()
  719. with nested(mock.patch('sys.stdout',
  720. StringIO.StringIO()), mock.patch('sys.argv',
  721. [ 'progname', '-l', testfname ])) as (stdout, argv):
  722. main()
  723. self.assertEqual(stdout.getvalue(),
  724. 'foo:\tbar=baz\nhashes:\tsha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada\nhashes:\tsha512:7d5768d47b6bc27dc4fa7e9732cfa2de506ca262a2749cb108923e5dddffde842bbfee6cb8d692fb43aca0f12946c521cce2633887914ca1f96898478d10ad3f\nlang:\ten\n')
  725. with nested(mock.patch('sys.stdout',
  726. StringIO.StringIO()), mock.patch('sys.argv',
  727. [ 'progname', '-a', 'foo=bleh', testfname ])) as (stdout, argv):
  728. main()
  729. with nested(mock.patch('sys.stdout',
  730. StringIO.StringIO()), mock.patch('sys.argv',
  731. [ 'progname', '-l', testfname ])) as (stdout, argv):
  732. main()
  733. self.assertEqual(stdout.getvalue(),
  734. 'foo:\tbar=baz\nfoo:\tbleh\nhashes:\tsha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada\nhashes:\tsha512:7d5768d47b6bc27dc4fa7e9732cfa2de506ca262a2749cb108923e5dddffde842bbfee6cb8d692fb43aca0f12946c521cce2633887914ca1f96898478d10ad3f\nlang:\ten\n')
  735. with nested(mock.patch('sys.stdout',
  736. StringIO.StringIO()), mock.patch('sys.argv',
  737. [ 'progname', '-d', 'foo=bar=baz', testfname ])) as (stdout, argv):
  738. main()
  739. with nested(mock.patch('sys.stdout',
  740. StringIO.StringIO()), mock.patch('sys.argv',
  741. [ 'progname', '-l', testfname ])) as (stdout, argv):
  742. main()
  743. self.assertEqual(stdout.getvalue(),
  744. 'foo:\tbleh\nhashes:\tsha256:91751cee0a1ab8414400238a761411daa29643ab4b8243e9a91649e25be53ada\nhashes:\tsha512:7d5768d47b6bc27dc4fa7e9732cfa2de506ca262a2749cb108923e5dddffde842bbfee6cb8d692fb43aca0f12946c521cce2633887914ca1f96898478d10ad3f\nlang:\ten\n')