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.
 
 
 
 

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