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.
 
 
 
 

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