signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def setUp(self):
self.graph = bipartite.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)<EOL>]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)<EOL>]<EOL>self.reviews = []<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.reviews.append(<EOL>self.graph.add_review(r, self.products[j], random.random()))<EOL><DEDENT><DEDENT>self.credibility = credibility.WeightedCredibility(self.graph)<EOL>
Set up a sample graph.
f5530:c2:m0
def update(self):
if self.updated:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>res = super(BipartiteGraph, self).update()<EOL>self.updated = True<EOL>return res<EOL>
Update reviewers' anomalous scores and products' summaries. Returns: maximum absolute difference between old summary and new one, and old anomalous score and new one.
f5531:c0:m1
def update_anomalous_score(self):
old = self.anomalous_score<EOL>products = self._graph.retrieve_products(self)<EOL>self.anomalous_score = sum(<EOL>p.summary.difference(<EOL>self._graph.retrieve_review(self, p)) * self._credibility(p) - <NUM_LIT:0.5><EOL>for p in products<EOL>)<EOL>return abs(self.anomalous_score - old)<EOL>
Update anomalous score. New anomalous score is the summation of weighted differences between current summary and reviews. The weights come from credibilities. Therefore, the new anomalous score is defined as .. math:: {\\rm anomalous}(r) = \\sum_{p \\in P} \\mbox{review}(p) \\times \\mbox{credibility}(p) - 0.5 where :math:`P` is a set of products reviewed by this reviewer, review(:math:`p`) and credibility(:math:`p`) are review and credibility of product :math:`p`, respectively. Returns: absolute difference between old anomalous score and updated one.
f5532:c0:m0
def update(self):
res = super(BipartiteGraph, self).update()<EOL>max_v = None<EOL>min_v = float("<STR_LIT>")<EOL>for r in self.reviewers:<EOL><INDENT>max_v = max(max_v, r.anomalous_score)<EOL>min_v = min(min_v, r.anomalous_score)<EOL><DEDENT>width = max_v - min_v<EOL>if width:<EOL><INDENT>for r in self.reviewers:<EOL><INDENT>r.anomalous_score = (r.anomalous_score - min_v) / width<EOL><DEDENT><DEDENT>return res<EOL>
Update reviewers' anomalous scores and products' summaries. The update consists of 2 steps; Step1 (updating summaries): Update summaries of products with anomalous scores of reviewers and weight function. The weight is calculated by the manner in :class:`ria.bipartite.BipartiteGraph`. Step2 (updating anomalous scores): Update its anomalous score of each reviewer by computing the summation of deviation times credibility. See :meth:`Reviewer.update_anomalous_score` for more details. After that those updated anomalous scores are normalized so that every value is in :math:`[0, 1]`. Returns: maximum absolute difference between old summary and new one, and old anomalous score and new one. This value is not normalized and thus it may be grater than actual normalized difference.
f5532:c1:m1
def __call__(self, product):
return <NUM_LIT:1.><EOL>
Compute credibility of a given product. Args: product: An instance of :class:`bipartite.Product`. Returns: Always 1.
f5533:c0:m1
def __init__(self, g):
self._g = g<EOL>
Construct a GraphBasedCredibility with a given graph instance g. Args: g: A bipartite graph instance.
f5533:c1:m0
def __call__(self, product):
raise NotImplementedError<EOL>
Compute credibility of a given product. Args: product: An instance of :class:`ria.bipartite.Product`.
f5533:c1:m1
def reviewers(self, product):
return self._g.retrieve_reviewers(product)<EOL>
Find reviewers who have reviewed a given product. Args: product: An instance of :class:`ria.bipartite.Product`. Returns: A list of reviewers who have reviewed the product.
f5533:c1:m2
def review_score(self, reviewer, product):
return self._g.retrieve_review(reviewer, product).score<EOL>
Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to the product.
f5533:c1:m3
@memoized<EOL><INDENT>def __call__(self, product):<DEDENT>
reviewers = self.reviewers(product)<EOL>Nq = len(reviewers)<EOL>if Nq == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.5><EOL><DEDENT>else:<EOL><INDENT>var = np.var([self.review_score(r, product)<EOL>for r in reviewers], ddof=<NUM_LIT:1>)<EOL>return np.log(Nq) / (var + <NUM_LIT:1>)<EOL><DEDENT>
Compute credibility of a given product. Args: product: An instance of :class:`bipartite.Product`. Returns: The credibility of the product. It is >= 0.5.
f5533:c2:m0
def ria_graph(alpha):
return BipartiteGraph(alpha=alpha)<EOL>
Create a review graph providing RIA algorithm with a parameter alpha. Args: alpha: Parameter. Returns: A review graph.
f5534:m0
def mra_graph():
return BipartiteGraph(credibility=UniformCredibility, alpha=<NUM_LIT:1>)<EOL>
Create a review graph providing MRA algorithm. Returns: A review graph.
f5534:m1
def one_graph():
return one.BipartiteGraph(credibility=UniformCredibility, alpha=<NUM_LIT:1>)<EOL>
Create a review graph providing One algorithm. Returns: A review graph.
f5534:m2
def one_sum_graph():
return bipartite_sum.BipartiteGraph(credibility=UniformCredibility, alpha=<NUM_LIT:1>)<EOL>
Create a review graph providing OneSum algorithm. Returns: A review graph.
f5534:m3
def __init__(self, graph, name=None):
if not isinstance(graph, BipartiteGraph):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>", graph)<EOL><DEDENT>self._graph = graph<EOL>if name:<EOL><INDENT>self.name = name<EOL><DEDENT>else:<EOL><INDENT>self.name = super(_Node, self).__str__()<EOL><DEDENT>self._hash = None<EOL>
Construct a new node. Args: name: Specifying the name of this node. If not given, use strings returned from __str__ method.
f5535:c0:m0
@property<EOL><INDENT>def anomalous_score(self):<DEDENT>
return self._anomalous if self._anomalous else <NUM_LIT:1.> / len(self._graph.reviewers)<EOL>
Anomalous score of this reviewer. Initial anomalous score is :math:`1 / |R|` where :math:`R` is a set of reviewers.
f5535:c1:m1
@anomalous_score.setter<EOL><INDENT>def anomalous_score(self, v):<DEDENT>
self._anomalous = float(v)<EOL>
Set an anomalous score. Args: v: the new anomalous score.
f5535:c1:m2
def update_anomalous_score(self):
products = self._graph.retrieve_products(self)<EOL>diffs = [<EOL>p.summary.difference(self._graph.retrieve_review(self, p))<EOL>for p in products<EOL>]<EOL>old = self.anomalous_score<EOL>try:<EOL><INDENT>self.anomalous_score = np.average(<EOL>diffs, weights=list(map(self._credibility, products)))<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>self.anomalous_score = np.average(diffs)<EOL><DEDENT>return abs(self.anomalous_score - old)<EOL>
Update anomalous score. New anomalous score is a weighted average of differences between current summary and reviews. The weights come from credibilities. Therefore, the new anomalous score of reviewer :math:`p` is as .. math:: {\\rm anomalous}(r) = \\frac{ \\sum_{p \\in P} {\\rm credibility}(p)| {\\rm review}(r, p)-{\\rm summary}(p)| }{ \\sum_{p \\in P} {\\rm credibility}(p) } where :math:`P` is a set of products reviewed by reviewer :math:`p`, review(:math:`r`, :math:`p`) is the rating reviewer :math:`r` posted to product :math:`p`, summary(:math:`p`) and credibility(:math:`p`) are summary and credibility of product :math:`p`, respectively. Returns: absolute difference between old anomalous score and updated one.
f5535:c1:m3
@property<EOL><INDENT>def summary(self):<DEDENT>
if self._summary:<EOL><INDENT>return self._summary<EOL><DEDENT>reviewers = self._graph.retrieve_reviewers(self)<EOL>return self._summary_cls(<EOL>[self._graph.retrieve_review(r, self) for r in reviewers])<EOL>
Summary of reviews for this product. Initial summary is computed by .. math:: \\frac{1}{|R|} \\sum_{r \\in R} \\mbox{review}(r), where :math:`\\mbox{review}(r)` means review from reviewer :math:`r`.
f5535:c2:m1
@summary.setter<EOL><INDENT>def summary(self, v):<DEDENT>
if hasattr(v, "<STR_LIT>"):<EOL><INDENT>self._summary = self._summary_cls(v)<EOL><DEDENT>else:<EOL><INDENT>self._summary = self._summary_cls(float(v))<EOL><DEDENT>
Set summary. Args: v: A new summary. It could be a single number or lists.
f5535:c2:m2
def update_summary(self, w):
old = self.summary.v <EOL>reviewers = self._graph.retrieve_reviewers(self)<EOL>reviews = [self._graph.retrieve_review(<EOL>r, self).score for r in reviewers]<EOL>weights = [w(r.anomalous_score) for r in reviewers]<EOL>if sum(weights) == <NUM_LIT:0>:<EOL><INDENT>self.summary = np.mean(reviews)<EOL><DEDENT>else:<EOL><INDENT>self.summary = np.average(reviews, weights=weights)<EOL><DEDENT>return abs(self.summary.v - old)<EOL>
Update summary. The new summary is a weighted average of reviews i.e. .. math:: \\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times \\mbox{review}(r)} {\\sum_{r \\in R} \\mbox{weight}(r)}, where :math:`R` is a set of reviewers reviewing this product, :math:`\\mbox{review}(r)` and :math:`\\mbox{weight}(r)` are the review and weight of the reviewer :math:`r`, respectively. Args: w: A weight function. Returns: absolute difference between old summary and updated one.
f5535:c2:m3
def __init__(<EOL>self, summary=AverageSummary, alpha=<NUM_LIT:1>,<EOL>credibility=WeightedCredibility, reviewer=Reviewer, product=Product):
self.alpha = alpha<EOL>self.graph = nx.DiGraph()<EOL>self.reviewers = []<EOL>self.products = []<EOL>self._summary_cls = summary<EOL>self._review_cls = summary.review_class()<EOL>self.credibility = credibility(self)<EOL>self._reviewer_cls = reviewer<EOL>self._product_cls = product<EOL>
Construct bipartite graph. Args: summary_type: specify summary type class, default value is AverageSummary. alpha: used to compute weight of anomalous scores, default value is 1. credibility: credibility class to be used in this graph. (Default: WeightedCredibility) reviewer: Class of reviewers. product: Class of products.
f5535:c3:m0
def new_reviewer(self, name, anomalous=None):
n = self._reviewer_cls(<EOL>self, name=name, credibility=self.credibility, anomalous=anomalous)<EOL>self.graph.add_node(n)<EOL>self.reviewers.append(n)<EOL>return n<EOL>
Create a new reviewer. Args: name: name of the new reviewer. anomalous: initial anomalous score. (default: None) Returns: A new reviewer instance.
f5535:c3:m1
def new_product(self, name):
n = self._product_cls(self, name, summary_cls=self._summary_cls)<EOL>self.graph.add_node(n)<EOL>self.products.append(n)<EOL>return n<EOL>
Create a new product. Args: name: name of the new product. Returns: A new product instance.
f5535:c3:m2
def add_review(self, reviewer, product, review, date=None):
if not isinstance(reviewer, self._reviewer_cls):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>", reviewer,<EOL>"<STR_LIT>", self._reviewer_cls)<EOL><DEDENT>elif not isinstance(product, self._product_cls):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>", product,<EOL>"<STR_LIT>", self._product_cls)<EOL><DEDENT>r = self._review_cls(review, date=date)<EOL>self.graph.add_edge(reviewer, product, review=r)<EOL>return r<EOL>
Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer. product: an instance of Product. review: a float value. date: date the review issued. Returns: the added new review object. Raises: TypeError: when given reviewer and product aren't instance of specified reviewer and product class when this graph is constructed.
f5535:c3:m3
@memoized<EOL><INDENT>def retrieve_products(self, reviewer):<DEDENT>
if not isinstance(reviewer, self._reviewer_cls):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>", reviewer,<EOL>"<STR_LIT>", self._reviewer_cls)<EOL><DEDENT>return list(self.graph.successors(reviewer))<EOL>
Retrieve products reviewed by a given reviewer. Args: reviewer: A reviewer. Returns: A list of products which the reviewer reviews. Raises: TypeError: when given reviewer isn't instance of specified reviewer class when this graph is constructed.
f5535:c3:m4
@memoized<EOL><INDENT>def retrieve_reviewers(self, product):<DEDENT>
if not isinstance(product, self._product_cls):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>", product,<EOL>"<STR_LIT>", self._product_cls)<EOL><DEDENT>return list(self.graph.predecessors(product))<EOL>
Retrieve reviewers who reviewed a given product. Args: product: A product specifying reviewers. Returns: A list of reviewers who review the product. Raises: TypeError: when given product isn't instance of specified product class when this graph is constructed.
f5535:c3:m5
@memoized<EOL><INDENT>def retrieve_review(self, reviewer, product):<DEDENT>
if not isinstance(reviewer, self._reviewer_cls):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>", reviewer,<EOL>"<STR_LIT>", self._reviewer_cls)<EOL><DEDENT>elif not isinstance(product, self._product_cls):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>", product,<EOL>"<STR_LIT>", self._product_cls)<EOL><DEDENT>try:<EOL><INDENT>return self.graph[reviewer][product]["<STR_LIT>"]<EOL><DEDENT>except TypeError:<EOL><INDENT>raise KeyError(<EOL>"<STR_LIT>".format(reviewer, product))<EOL><DEDENT>
Retrieve review that the given reviewer put the given product. Args: reviewer: An instance of Reviewer. product: An instance of Product. Returns: A review object. Raises: TypeError: when given reviewer and product aren't instance of specified reviewer and product class when this graph is constructed. KeyError: When the reviewer does not review the product.
f5535:c3:m6
def update(self):
w = self._weight_generator(self.reviewers)<EOL>diff_p = max(p.update_summary(w) for p in self.products)<EOL>diff_a = max(r.update_anomalous_score() for r in self.reviewers)<EOL>return max(diff_p, diff_a)<EOL>
Update reviewers' anomalous scores and products' summaries. Returns: maximum absolute difference between old summary and new one, and old anomalous score and new one.
f5535:c3:m7
def _weight_generator(self, reviewers):
scores = [r.anomalous_score for r in reviewers]<EOL>mu = np.average(scores)<EOL>sigma = np.std(scores)<EOL>if sigma:<EOL><INDENT>def w(v):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>exp = math.exp(self.alpha * (v - mu) / sigma)<EOL>return <NUM_LIT:1.> / (<NUM_LIT:1.> + exp)<EOL><DEDENT>except OverflowError:<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT><DEDENT>return w<EOL><DEDENT>else:<EOL><INDENT>return lambda v: <NUM_LIT:1.><EOL><DEDENT>
Compute a weight function for the given reviewers. Args: reviewers: a set of reviewers to compute weight function. Returns: a function computing a weight for a reviewer.
f5535:c3:m8
def dump_credibilities(self, output):
for p in self.products:<EOL><INDENT>json.dump({<EOL>"<STR_LIT>": p.name,<EOL>"<STR_LIT>": self.credibility(p)<EOL>}, output)<EOL>output.write("<STR_LIT:\n>")<EOL><DEDENT>
Dump credibilities of all products. Args: output: a writable object.
f5535:c3:m9
def to_pydot(self):
return nx.nx_pydot.to_pydot(self.graph)<EOL>
Convert this graph to PyDot object. Returns: PyDot object representing this graph.
f5535:c3:m10
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()<EOL>
Read a file.
f5536:m0
def load_requires_from_file(filepath):
with open(filepath) as fp:<EOL><INDENT>return [pkg_name.strip() for pkg_name in fp.readlines()]<EOL><DEDENT>
Read a package list from a given file path. Args: filepath: file path of the package list. Returns: a list of package names.
f5536:m1
@contextmanager<EOL>def open(path, broken=False):
with maybe_gzip_open(path) as f:<EOL><INDENT>yield reader(f, broken=broken)<EOL><DEDENT>
Context manager for opening and reading json lines files. If file extension suggests gzip (.gz or .gzip), file is decompressed on fly. Pass broken=True if you expect the file can be truncated or broken otherwise; reader will try to recover as much data as possible in this case.
f5539:m0
def reader(file, broken=False):
if not broken:<EOL><INDENT>return _iter_json_lines(file)<EOL><DEDENT>else:<EOL><INDENT>return _iter_json_lines_recovering(file)<EOL><DEDENT>
Read .jl or .jl.gz file with JSON lines data, return iterator with decoded lines. If the .jl.gz archive is broken as much lines as possible are read from the archive.
f5539:m1
def maybe_gzip_open(path, *args, **kwargs):
path = path_to_str(path)<EOL>if path.endswith('<STR_LIT>') or path.endswith('<STR_LIT>'):<EOL><INDENT>_open = gzip.open<EOL><DEDENT>else:<EOL><INDENT>_open = open<EOL><DEDENT>return _open(path, *args, **kwargs)<EOL>
Open file with either open or gzip.open, depending on file extension. This function doesn't handle json lines format, just opens a file in a way it is decoded transparently if needed.
f5540:m0
def path_to_str(path):
try:<EOL><INDENT>from pathlib import Path as _Path<EOL><DEDENT>except ImportError: <EOL><INDENT>class _Path:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if isinstance(path, _Path):<EOL><INDENT>return str(path)<EOL><DEDENT>return path<EOL>
Convert pathlib.Path objects to str; return other objects as-is.
f5540:m1
def get_known_read_position(fp, buffered=True):
buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else <NUM_LIT:0><EOL>return max(fp.tell() - buffer_size, <NUM_LIT:0>)<EOL>
Return a position in a file which is known to be read & handled. It assumes a buffered file and streaming processing.
f5541:m0
def recover(gzfile, last_good_position):<EOL>
pos = get_recover_position(gzfile, last_good_position=last_good_position)<EOL>if pos == -<NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>fp = gzfile.fileobj<EOL>fp.seek(pos)<EOL><INDENT>gzfile.close()<EOL><DEDENT>return gzip.GzipFile(fileobj=fp, mode='<STR_LIT:r>')<EOL>
Skip to the next possibly decompressable part of a gzip file. Return a new GzipFile object if such part is found or None if it is not found.
f5541:m1
def get_recover_position(gzfile, last_good_position):<EOL>
with closing(mmap.mmap(gzfile.fileno(), <NUM_LIT:0>, access=mmap.ACCESS_READ)) as m:<EOL><INDENT>return m.find(GZIP_SIGNATURE, last_good_position + <NUM_LIT:1>)<EOL><DEDENT>
Return position of a next gzip stream in a GzipFile, or -1 if it is not found. XXX: caller must ensure that the same last_good_position is not used multiple times for the same gzfile.
f5541:m2
def change_custom_seed(seed):
if isinstance(seed, (basestring, list, tuple)):<EOL><INDENT>seed = Seed(seed)<EOL><DEDENT>if isinstance(seed, Seed):<EOL><INDENT>CustomCarry.SEED_LIST = seed<EOL><DEDENT>
change CustomCarry seed example: change_custom_seed([1,2,3]) # then CustomCarry.SEED_LIST == '123' is True :param seed: :return:
f5547:m0
def _get_from_cache(dk_class, algorithm, key_length):
try:<EOL><INDENT>return _DELEGATED_KEY_CACHE[dk_class][algorithm][key_length]<EOL><DEDENT>except KeyError:<EOL><INDENT>key = dk_class.generate(algorithm, key_length)<EOL>_DELEGATED_KEY_CACHE[dk_class][algorithm][key_length] = key<EOL>return key<EOL><DEDENT>
Don't generate new keys every time. All we care about is that they are valid keys, not that they are unique.
f5551:m3
def build_static_jce_cmp(encryption_algorithm, encryption_key_length, signing_algorithm, signing_key_length):
encryption_key = _get_from_cache(JceNameLocalDelegatedKey, encryption_algorithm, encryption_key_length)<EOL>authentication_key = _get_from_cache(JceNameLocalDelegatedKey, signing_algorithm, signing_key_length)<EOL>encryption_materials = RawEncryptionMaterials(signing_key=authentication_key, encryption_key=encryption_key)<EOL>decryption_materials = RawDecryptionMaterials(verification_key=authentication_key, decryption_key=encryption_key)<EOL>return StaticCryptographicMaterialsProvider(<EOL>encryption_materials=encryption_materials, decryption_materials=decryption_materials<EOL>)<EOL>
Build a StaticCryptographicMaterialsProvider using ephemeral JceNameLocalDelegatedKeys as specified.
f5551:m4
def _build_wrapped_jce_cmp(wrapping_algorithm, wrapping_key_length, signing_algorithm, signing_key_length):
wrapping_key = _get_from_cache(JceNameLocalDelegatedKey, wrapping_algorithm, wrapping_key_length)<EOL>signing_key = _get_from_cache(JceNameLocalDelegatedKey, signing_algorithm, signing_key_length)<EOL>return WrappedCryptographicMaterialsProvider(<EOL>wrapping_key=wrapping_key, unwrapping_key=wrapping_key, signing_key=signing_key<EOL>)<EOL>
Build a WrappedCryptographicMaterialsProvider using ephemeral JceNameLocalDelegatedKeys as specified.
f5551:m5
def _all_encryption():
return itertools.chain(itertools.product(("<STR_LIT>",), (<NUM_LIT>, <NUM_LIT>)), itertools.product(("<STR_LIT>",), (<NUM_LIT>, <NUM_LIT>, <NUM_LIT>)))<EOL>
All encryption configurations to test in slow tests.
f5551:m6
def _all_authentication():
return itertools.chain(<EOL>itertools.product(("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"), (<NUM_LIT>, <NUM_LIT>)),<EOL>itertools.product(("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"), (<NUM_LIT>, <NUM_LIT>, <NUM_LIT>)),<EOL>)<EOL>
All authentication configurations to test in slow tests.
f5551:m7
def _all_algorithm_pairs():
for encryption_pair, signing_pair in itertools.product(_all_encryption(), _all_authentication()):<EOL><INDENT>yield encryption_pair + signing_pair<EOL><DEDENT>
All algorithm pairs (encryption + authentication) to test in slow tests.
f5551:m8
def _some_algorithm_pairs():
return (("<STR_LIT>", <NUM_LIT>, "<STR_LIT>", <NUM_LIT>), ("<STR_LIT>", <NUM_LIT>, "<STR_LIT>", <NUM_LIT>), ("<STR_LIT>", <NUM_LIT>, "<STR_LIT>", <NUM_LIT>))<EOL>
Cherry-picked set of algorithm pairs (encryption + authentication) to test in fast tests.
f5551:m9
def _all_possible_cmps(algorithm_generator):
<EOL>yield _build_wrapped_jce_cmp("<STR_LIT>", <NUM_LIT>, "<STR_LIT>", <NUM_LIT>)<EOL>for builder_info, args in itertools.product(_cmp_builders.items(), algorithm_generator()):<EOL><INDENT>builder_type, builder_func = builder_info<EOL>encryption_algorithm, encryption_key_length, signing_algorithm, signing_key_length = args<EOL>if builder_type == "<STR_LIT>" and encryption_algorithm != "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>id_string = "<STR_LIT>".format(<EOL>enc_algorithm=encryption_algorithm,<EOL>enc_key_length=encryption_key_length,<EOL>builder_type=builder_type,<EOL>sig_algorithm=signing_algorithm,<EOL>sig_key_length=signing_key_length,<EOL>)<EOL>yield pytest.param(<EOL>builder_func(encryption_algorithm, encryption_key_length, signing_algorithm, signing_key_length),<EOL>id=id_string,<EOL>)<EOL><DEDENT>
Generate all possible cryptographic materials providers based on the supplied generator.
f5551:m10
def set_parametrized_cmp(metafunc):
for name, algorithm_generator in (("<STR_LIT>", _all_algorithm_pairs), ("<STR_LIT>", _some_algorithm_pairs)):<EOL><INDENT>if name in metafunc.fixturenames:<EOL><INDENT>metafunc.parametrize(name, _all_possible_cmps(algorithm_generator))<EOL><DEDENT><DEDENT>
Set paramatrized values for cryptographic materials providers.
f5551:m11
def set_parametrized_actions(metafunc):
for name, actions in _ACTIONS.items():<EOL><INDENT>if name in metafunc.fixturenames:<EOL><INDENT>metafunc.parametrize(name, actions)<EOL><DEDENT><DEDENT>
Set parametrized values for attribute actions.
f5551:m12
def set_parametrized_item(metafunc):
if "<STR_LIT>" in metafunc.fixturenames:<EOL><INDENT>metafunc.parametrize("<STR_LIT>", (pytest.param(diverse_item(), id="<STR_LIT>"),))<EOL><DEDENT>
Set parametrized values for items to cycle.
f5551:m13
def cycle_batch_writer_check(raw_table, encrypted_table, initial_actions, initial_item):
check_attribute_actions = initial_actions.copy()<EOL>check_attribute_actions.set_index_keys(*list(TEST_KEY.keys()))<EOL>items = _generate_items(initial_item, _nop_transformer)<EOL>with encrypted_table.batch_writer() as writer:<EOL><INDENT>for item in items:<EOL><INDENT>writer.put_item(item)<EOL><DEDENT><DEDENT>ddb_keys = [key for key in TEST_BATCH_KEYS]<EOL>encrypted_items = [raw_table.get_item(Key=key, ConsistentRead=True)["<STR_LIT>"] for key in ddb_keys]<EOL>check_many_encrypted_items(<EOL>actual=encrypted_items, expected=items, attribute_actions=check_attribute_actions, transformer=_nop_transformer<EOL>)<EOL>decrypted_result = [encrypted_table.get_item(Key=key, ConsistentRead=True)["<STR_LIT>"] for key in ddb_keys]<EOL>assert_equal_lists_of_items(actual=decrypted_result, expected=items, transformer=_nop_transformer)<EOL>with encrypted_table.batch_writer() as writer:<EOL><INDENT>for key in ddb_keys:<EOL><INDENT>writer.delete_item(key)<EOL><DEDENT><DEDENT>del check_attribute_actions<EOL>del items<EOL>
Check that cycling (plaintext->encrypted->decrypted) items with the Table batch writer has the expected results.
f5551:m26
def cycle_item_check(plaintext_item, crypto_config):
ciphertext_item = encrypt_python_item(plaintext_item, crypto_config)<EOL>check_encrypted_item(plaintext_item, ciphertext_item, crypto_config.attribute_actions)<EOL>cycled_item = decrypt_python_item(ciphertext_item, crypto_config)<EOL>assert cycled_item == plaintext_item<EOL>del ciphertext_item<EOL>del cycled_item<EOL>
Check that cycling (plaintext->encrypted->decrypted) an item has the expected results.
f5551:m28
def _ddb_fraction_to_decimal(val):
return Decimal(val.numerator) / Decimal(val.denominator)<EOL>
Hypothesis does not support providing a custom Context, so working around that.
f5561:m0
def cmk_arn_value():
arn = os.environ.get(AWS_KMS_KEY_ID, None)<EOL>if arn is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>AWS_KMS_KEY_ID<EOL>)<EOL>)<EOL><DEDENT>if arn.startswith("<STR_LIT>") and "<STR_LIT>" not in arn:<EOL><INDENT>return arn<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL>
Retrieve the target CMK ARN from environment variable.
f5587:m0
def read(*args):
return io.open(os.path.join(HERE, *args), encoding="<STR_LIT:utf-8>").read()<EOL>
Reads complete file contents.
f5589:m0
def get_release():
init = read("<STR_LIT:..>", "<STR_LIT:src>", "<STR_LIT>", "<STR_LIT>")<EOL>return VERSION_RE.search(init).group(<NUM_LIT:1>)<EOL>
Reads the release (full three-part version number) from this module.
f5589:m1
def get_version():
_release = get_release()<EOL>split_version = _release.split("<STR_LIT:.>")<EOL>if len(split_version) == <NUM_LIT:3>:<EOL><INDENT>return "<STR_LIT:.>".join(split_version[:<NUM_LIT:2>])<EOL><DEDENT>return _release<EOL>
Reads the version (MAJOR.MINOR) from this module.
f5589:m2
def encrypt_item(table_name, aws_cmk_id, meta_table_name, material_name):
index_key = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>}<EOL>plaintext_item = {<EOL>"<STR_LIT>": "<STR_LIT:data>",<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": Binary(b"<STR_LIT>"),<EOL>"<STR_LIT>": "<STR_LIT>", <EOL>}<EOL>encrypted_attributes = set(plaintext_item.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_key.keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>plaintext_item.update(index_key)<EOL>meta_table = boto3.resource("<STR_LIT>").Table(meta_table_name)<EOL>aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)<EOL>meta_store = MetaStore(table=meta_table, materials_provider=aws_kms_cmp)<EOL>most_recent_cmp = MostRecentProvider(<EOL>provider_store=meta_store,<EOL>material_name=material_name,<EOL>version_ttl=<NUM_LIT>, <EOL>)<EOL>table = boto3.resource("<STR_LIT>").Table(table_name)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_table = EncryptedTable(table=table, materials_provider=most_recent_cmp, attribute_actions=actions)<EOL>encrypted_table.put_item(Item=plaintext_item)<EOL>encrypted_item = table.get_item(Key=index_key)["<STR_LIT>"]<EOL>decrypted_item = encrypted_table.get_item(Key=index_key)["<STR_LIT>"]<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT>encrypted_table.delete_item(Key=index_key)<EOL>
Demonstrate use of EncryptedTable to transparently encrypt an item.
f5596:m0
def encrypt_item(table_name, aws_cmk_id):
index_key = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>}<EOL>plaintext_item = {<EOL>"<STR_LIT>": "<STR_LIT:data>",<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": Binary(b"<STR_LIT>"),<EOL>"<STR_LIT>": "<STR_LIT>", <EOL>}<EOL>encrypted_attributes = set(plaintext_item.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_key.keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>plaintext_item.update(index_key)<EOL>table = boto3.resource("<STR_LIT>").Table(table_name)<EOL>table_info = TableInfo(name=table_name)<EOL>table_info.refresh_indexed_attributes(table.meta.client)<EOL>aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)<EOL>encryption_context = EncryptionContext(<EOL>table_name=table_name,<EOL>partition_key_name=table_info.primary_index.partition,<EOL>sort_key_name=table_info.primary_index.sort,<EOL>attributes=dict_to_ddb(index_key),<EOL>)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>actions.set_index_keys(*table_info.protected_index_keys())<EOL>crypto_config = CryptoConfig(<EOL>materials_provider=aws_kms_cmp, encryption_context=encryption_context, attribute_actions=actions<EOL>)<EOL>encrypted_item = encrypt_python_item(plaintext_item, crypto_config)<EOL>decrypted_item = decrypt_python_item(encrypted_item, crypto_config)<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT>
Demonstrate use of EncryptedTable to transparently encrypt an item.
f5597:m0
def encrypt_item(table_name, aws_cmk_id):
index_key = {"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, "<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"}}<EOL>plaintext_item = {<EOL>"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT:data>"},<EOL>"<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"},<EOL>"<STR_LIT>": {"<STR_LIT:B>": b"<STR_LIT>"},<EOL>"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, <EOL>}<EOL>encrypted_attributes = set(plaintext_item.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_key.keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>plaintext_item.update(index_key)<EOL>client = boto3.client("<STR_LIT>")<EOL>aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_client = EncryptedClient(client=client, materials_provider=aws_kms_cmp, attribute_actions=actions)<EOL>encrypted_client.put_item(TableName=table_name, Item=plaintext_item)<EOL>encrypted_item = client.get_item(TableName=table_name, Key=index_key)["<STR_LIT>"]<EOL>decrypted_item = encrypted_client.get_item(TableName=table_name, Key=index_key)["<STR_LIT>"]<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT>encrypted_client.delete_item(TableName=table_name, Key=index_key)<EOL>
Demonstrate use of EncryptedClient to transparently encrypt an item.
f5598:m0
def encrypt_batch_items(table_name, aws_cmk_id):
index_keys = [<EOL>{"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, "<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"}},<EOL>{"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, "<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"}},<EOL>{"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, "<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"}},<EOL>{"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, "<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"}},<EOL>]<EOL>plaintext_additional_attributes = {<EOL>"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT:data>"},<EOL>"<STR_LIT>": {"<STR_LIT:N>": "<STR_LIT>"},<EOL>"<STR_LIT>": {"<STR_LIT:B>": b"<STR_LIT>"},<EOL>"<STR_LIT>": {"<STR_LIT:S>": "<STR_LIT>"}, <EOL>}<EOL>plaintext_items = []<EOL>for key in index_keys:<EOL><INDENT>_attributes = key.copy()<EOL>_attributes.update(plaintext_additional_attributes)<EOL>plaintext_items.append(_attributes)<EOL><DEDENT>encrypted_attributes = set(plaintext_additional_attributes.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_keys[<NUM_LIT:0>].keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>client = boto3.client("<STR_LIT>")<EOL>aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_client = EncryptedClient(client=client, materials_provider=aws_kms_cmp, attribute_actions=actions)<EOL>encrypted_client.batch_write_item(<EOL>RequestItems={table_name: [{"<STR_LIT>": {"<STR_LIT>": item}} for item in plaintext_items]}<EOL>)<EOL>encrypted_items = client.batch_get_item(RequestItems={table_name: {"<STR_LIT>": index_keys}})["<STR_LIT>"][table_name]<EOL>decrypted_items = encrypted_client.batch_get_item(RequestItems={table_name: {"<STR_LIT>": index_keys}})["<STR_LIT>"][<EOL>table_name<EOL>]<EOL>def _select_index_from_item(item):<EOL><INDENT>"""<STR_LIT>"""<EOL>for index in index_keys:<EOL><INDENT>if all([item[key] == value for key, value in index.items()]):<EOL><INDENT>return index<EOL><DEDENT><DEDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>def _select_item_from_index(index, all_items):<EOL><INDENT>"""<STR_LIT>"""<EOL>for item in all_items:<EOL><INDENT>if all([item[key] == value for key, value in index.items()]):<EOL><INDENT>return item<EOL><DEDENT><DEDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>for encrypted_item in encrypted_items:<EOL><INDENT>key = _select_index_from_item(encrypted_item)<EOL>plaintext_item = _select_item_from_index(key, plaintext_items)<EOL>decrypted_item = _select_item_from_index(key, decrypted_items)<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT><DEDENT>encrypted_client.batch_write_item(<EOL>RequestItems={table_name: [{"<STR_LIT>": {"<STR_LIT>": key}} for key in index_keys]}<EOL>)<EOL>
Demonstrate use of EncryptedClient to transparently encrypt multiple items in a batch request.
f5598:m1
def encrypt_item(table_name, aes_wrapping_key_bytes, hmac_signing_key_bytes):
index_key = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>}<EOL>plaintext_item = {<EOL>"<STR_LIT>": "<STR_LIT:data>",<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": Binary(b"<STR_LIT>"),<EOL>"<STR_LIT>": "<STR_LIT>", <EOL>}<EOL>encrypted_attributes = set(plaintext_item.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_key.keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>plaintext_item.update(index_key)<EOL>table = boto3.resource("<STR_LIT>").Table(table_name)<EOL>wrapping_key = JceNameLocalDelegatedKey(<EOL>key=aes_wrapping_key_bytes,<EOL>algorithm="<STR_LIT>",<EOL>key_type=EncryptionKeyType.SYMMETRIC,<EOL>key_encoding=KeyEncodingType.RAW,<EOL>)<EOL>signing_key = JceNameLocalDelegatedKey(<EOL>key=hmac_signing_key_bytes,<EOL>algorithm="<STR_LIT>",<EOL>key_type=EncryptionKeyType.SYMMETRIC,<EOL>key_encoding=KeyEncodingType.RAW,<EOL>)<EOL>wrapped_cmp = WrappedCryptographicMaterialsProvider(<EOL>wrapping_key=wrapping_key, unwrapping_key=wrapping_key, signing_key=signing_key<EOL>)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_table = EncryptedTable(table=table, materials_provider=wrapped_cmp, attribute_actions=actions)<EOL>encrypted_table.put_item(Item=plaintext_item)<EOL>encrypted_item = table.get_item(Key=index_key)["<STR_LIT>"]<EOL>decrypted_item = encrypted_table.get_item(Key=index_key)["<STR_LIT>"]<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT>encrypted_table.delete_item(Key=index_key)<EOL>
Demonstrate use of EncryptedTable to transparently encrypt an item.
f5599:m0
def encrypt_item(table_name, rsa_wrapping_private_key_bytes, rsa_signing_private_key_bytes):
index_key = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>}<EOL>plaintext_item = {<EOL>"<STR_LIT>": "<STR_LIT:data>",<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": Binary(b"<STR_LIT>"),<EOL>"<STR_LIT>": "<STR_LIT>", <EOL>}<EOL>encrypted_attributes = set(plaintext_item.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_key.keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>plaintext_item.update(index_key)<EOL>table = boto3.resource("<STR_LIT>").Table(table_name)<EOL>wrapping_key = JceNameLocalDelegatedKey(<EOL>key=rsa_wrapping_private_key_bytes,<EOL>algorithm="<STR_LIT>",<EOL>key_type=EncryptionKeyType.PRIVATE,<EOL>key_encoding=KeyEncodingType.DER,<EOL>)<EOL>signing_key = JceNameLocalDelegatedKey(<EOL>key=rsa_signing_private_key_bytes,<EOL>algorithm="<STR_LIT>",<EOL>key_type=EncryptionKeyType.PRIVATE,<EOL>key_encoding=KeyEncodingType.DER,<EOL>)<EOL>wrapped_cmp = WrappedCryptographicMaterialsProvider(<EOL>wrapping_key=wrapping_key, unwrapping_key=wrapping_key, signing_key=signing_key<EOL>)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_table = EncryptedTable(table=table, materials_provider=wrapped_cmp, attribute_actions=actions)<EOL>encrypted_table.put_item(Item=plaintext_item)<EOL>encrypted_item = table.get_item(Key=index_key)["<STR_LIT>"]<EOL>decrypted_item = encrypted_table.get_item(Key=index_key)["<STR_LIT>"]<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT>encrypted_table.delete_item(Key=index_key)<EOL>
Demonstrate use of EncryptedTable to transparently encrypt an item.
f5600:m0
def encrypt_item(table_name, aws_cmk_id):
index_key = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>}<EOL>plaintext_item = {<EOL>"<STR_LIT>": "<STR_LIT:data>",<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": Binary(b"<STR_LIT>"),<EOL>"<STR_LIT>": "<STR_LIT>", <EOL>}<EOL>encrypted_attributes = set(plaintext_item.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_key.keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>plaintext_item.update(index_key)<EOL>table = boto3.resource("<STR_LIT>").Table(table_name)<EOL>aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_table = EncryptedTable(table=table, materials_provider=aws_kms_cmp, attribute_actions=actions)<EOL>encrypted_table.put_item(Item=plaintext_item)<EOL>encrypted_item = table.get_item(Key=index_key)["<STR_LIT>"]<EOL>decrypted_item = encrypted_table.get_item(Key=index_key)["<STR_LIT>"]<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT>encrypted_table.delete_item(Key=index_key)<EOL>
Demonstrate use of EncryptedTable to transparently encrypt an item.
f5601:m0
def encrypt_batch_items(table_name, aws_cmk_id):
index_keys = [<EOL>{"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>},<EOL>{"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>},<EOL>{"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>},<EOL>{"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>},<EOL>]<EOL>plaintext_additional_attributes = {<EOL>"<STR_LIT>": "<STR_LIT:data>",<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": Binary(b"<STR_LIT>"),<EOL>"<STR_LIT>": "<STR_LIT>", <EOL>}<EOL>plaintext_items = []<EOL>for key in index_keys:<EOL><INDENT>_attributes = key.copy()<EOL>_attributes.update(plaintext_additional_attributes)<EOL>plaintext_items.append(_attributes)<EOL><DEDENT>encrypted_attributes = set(plaintext_additional_attributes.keys())<EOL>encrypted_attributes.remove("<STR_LIT>")<EOL>unencrypted_attributes = set(index_keys[<NUM_LIT:0>].keys())<EOL>unencrypted_attributes.add("<STR_LIT>")<EOL>resource = boto3.resource("<STR_LIT>")<EOL>aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)<EOL>actions = AttributeActions(<EOL>default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"<STR_LIT>": CryptoAction.DO_NOTHING}<EOL>)<EOL>encrypted_resource = EncryptedResource(resource=resource, materials_provider=aws_kms_cmp, attribute_actions=actions)<EOL>encrypted_resource.batch_write_item(<EOL>RequestItems={table_name: [{"<STR_LIT>": {"<STR_LIT>": item}} for item in plaintext_items]}<EOL>)<EOL>encrypted_items = resource.batch_get_item(RequestItems={table_name: {"<STR_LIT>": index_keys}})["<STR_LIT>"][table_name]<EOL>decrypted_items = encrypted_resource.batch_get_item(RequestItems={table_name: {"<STR_LIT>": index_keys}})["<STR_LIT>"][<EOL>table_name<EOL>]<EOL>def _select_index_from_item(item):<EOL><INDENT>"""<STR_LIT>"""<EOL>for index in index_keys:<EOL><INDENT>if all([item[key] == value for key, value in index.items()]):<EOL><INDENT>return index<EOL><DEDENT><DEDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>def _select_item_from_index(index, all_items):<EOL><INDENT>"""<STR_LIT>"""<EOL>for item in all_items:<EOL><INDENT>if all([item[key] == value for key, value in index.items()]):<EOL><INDENT>return item<EOL><DEDENT><DEDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>for encrypted_item in encrypted_items:<EOL><INDENT>key = _select_index_from_item(encrypted_item)<EOL>plaintext_item = _select_item_from_index(key, plaintext_items)<EOL>decrypted_item = _select_item_from_index(key, decrypted_items)<EOL>for name in encrypted_attributes:<EOL><INDENT>assert encrypted_item[name] != plaintext_item[name]<EOL>assert decrypted_item[name] == plaintext_item[name]<EOL><DEDENT>for name in unencrypted_attributes:<EOL><INDENT>assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]<EOL><DEDENT><DEDENT>encrypted_resource.batch_write_item(<EOL>RequestItems={table_name: [{"<STR_LIT>": {"<STR_LIT>": key}} for key in index_keys]}<EOL>)<EOL>
Demonstrate use of EncryptedResource to transparently encrypt multiple items in a batch request.
f5602:m0
def __gt__(self, other):<EOL>
return not self.__lt__(other) and not self.__eq__(other)<EOL>
Define CryptoAction equality.
f5603:c0:m0
def __lt__(self, other):<EOL>
return self.value < other.value<EOL>
Define CryptoAction equality.
f5603:c0:m1
def __eq__(self, other):<EOL>
return self.value == other.value<EOL>
Define CryptoAction equality.
f5603:c0:m2
def unpack_value(format_string, stream):
message_bytes = stream.read(struct.calcsize(format_string))<EOL>return struct.unpack(format_string, message_bytes)<EOL>
Helper function to unpack struct data from a stream and update the signature verifier. :param str format_string: Struct format string :param stream: Source data stream :type stream: io.BytesIO :returns: Unpacked values :rtype: tuple
f5604:m0
def decode_length(stream):
(value,) = unpack_value("<STR_LIT>", stream)<EOL>return value<EOL>
Decode the length of a value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded length :rtype: int
f5604:m1
def decode_value(stream):
length = decode_length(stream)<EOL>(value,) = unpack_value("<STR_LIT>".format(length), stream)<EOL>return value<EOL>
Decode the contents of a value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded value :rtype: bytes
f5604:m2
def decode_byte(stream):
(value,) = unpack_value("<STR_LIT>", stream)<EOL>return value<EOL>
Decode a single raw byte from a serialized stream (used for deserialize bool). :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded value :rtype: bytes
f5604:m3
def decode_tag(stream):
(reserved, tag) = unpack_value("<STR_LIT>", stream)<EOL>if reserved != b"<STR_LIT:\x00>":<EOL><INDENT>raise DeserializationError("<STR_LIT>")<EOL><DEDENT>return tag<EOL>
Decode a tag value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded tag :rtype: bytes
f5604:m4
def deserialize_attribute(serialized_attribute): <EOL>
def _transform_binary_value(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(value, Binary):<EOL><INDENT>return value.value<EOL><DEDENT>return value<EOL><DEDENT>def _deserialize_binary(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>value = decode_value(stream)<EOL>return {Tag.BINARY.dynamodb_tag: _transform_binary_value(value)}<EOL><DEDENT>def _transform_string_value(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>return codecs.decode(value, TEXT_ENCODING)<EOL><DEDENT>def _deserialize_string(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>value = decode_value(stream)<EOL>return {Tag.STRING.dynamodb_tag: _transform_string_value(value)}<EOL><DEDENT>def _transform_number_value(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>raw_value = codecs.decode(value, TEXT_ENCODING)<EOL>decimal_value = Decimal(to_str(raw_value)).normalize()<EOL>return "<STR_LIT>".format(decimal_value)<EOL><DEDENT>def _deserialize_number(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>value = decode_value(stream)<EOL>return {Tag.NUMBER.dynamodb_tag: _transform_number_value(value)}<EOL><DEDENT>_boolean_map = {TagValues.FALSE.value: False, TagValues.TRUE.value: True}<EOL>def _deserialize_boolean(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>value = decode_byte(stream)<EOL>return {Tag.BOOLEAN.dynamodb_tag: _boolean_map[value]}<EOL><DEDENT>def _deserialize_null(stream): <EOL><INDENT>"""<STR_LIT>"""<EOL>return {Tag.NULL.dynamodb_tag: True}<EOL><DEDENT>def _deserialize_set(stream, member_transform):<EOL><INDENT>"""<STR_LIT>"""<EOL>member_count = decode_length(stream)<EOL>return sorted([member_transform(decode_value(stream)) for _ in range(member_count)])<EOL><DEDENT>def _deserialize_binary_set(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>return {Tag.BINARY_SET.dynamodb_tag: _deserialize_set(stream, _transform_binary_value)}<EOL><DEDENT>def _deserialize_string_set(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>return {Tag.STRING_SET.dynamodb_tag: _deserialize_set(stream, _transform_string_value)}<EOL><DEDENT>def _deserialize_number_set(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>return {Tag.NUMBER_SET.dynamodb_tag: _deserialize_set(stream, _transform_number_value)}<EOL><DEDENT>def _deserialize_list(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>member_count = decode_length(stream)<EOL>return {Tag.LIST.dynamodb_tag: [_deserialize(stream) for _ in range(member_count)]}<EOL><DEDENT>def _deserialize_map(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>member_count = decode_length(stream)<EOL>members = {} <EOL>for _ in range(member_count):<EOL><INDENT>key = _deserialize(stream)<EOL>if Tag.STRING.dynamodb_tag not in key:<EOL><INDENT>raise DeserializationError(<EOL>'<STR_LIT>'.format(list(key.keys())[<NUM_LIT:0>])<EOL>)<EOL><DEDENT>value = _deserialize(stream)<EOL>members[key[Tag.STRING.dynamodb_tag]] = value<EOL><DEDENT>return {Tag.MAP.dynamodb_tag: members}<EOL><DEDENT>def _deserialize_function(tag):<EOL><INDENT>"""<STR_LIT>"""<EOL>deserialize_functions = {<EOL>Tag.BINARY.tag: _deserialize_binary,<EOL>Tag.BINARY_SET.tag: _deserialize_binary_set,<EOL>Tag.NUMBER.tag: _deserialize_number,<EOL>Tag.NUMBER_SET.tag: _deserialize_number_set,<EOL>Tag.STRING.tag: _deserialize_string,<EOL>Tag.STRING_SET.tag: _deserialize_string_set,<EOL>Tag.BOOLEAN.tag: _deserialize_boolean,<EOL>Tag.NULL.tag: _deserialize_null,<EOL>Tag.LIST.tag: _deserialize_list,<EOL>Tag.MAP.tag: _deserialize_map,<EOL>}<EOL>try:<EOL><INDENT>return deserialize_functions[tag]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise DeserializationError('<STR_LIT>'.format(tag))<EOL><DEDENT><DEDENT>def _deserialize(stream):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>tag = decode_tag(stream)<EOL>return _deserialize_function(tag)(stream)<EOL><DEDENT>except struct.error:<EOL><INDENT>raise DeserializationError("<STR_LIT>")<EOL><DEDENT><DEDENT>if not serialized_attribute:<EOL><INDENT>raise DeserializationError("<STR_LIT>")<EOL><DEDENT>stream = io.BytesIO(serialized_attribute)<EOL>return _deserialize(stream)<EOL>
Deserializes serialized attributes for decryption. :param bytes serialized_attribute: Serialized attribute bytes :returns: Deserialized attribute :rtype: dict
f5605:m0
def serialize(material_description):<EOL>
material_description_bytes = bytearray(_MATERIAL_DESCRIPTION_VERSION)<EOL>for name, value in sorted(material_description.items(), key=lambda x: x[<NUM_LIT:0>]):<EOL><INDENT>try:<EOL><INDENT>material_description_bytes.extend(encode_value(to_bytes(name)))<EOL>material_description_bytes.extend(encode_value(to_bytes(value)))<EOL><DEDENT>except (TypeError, struct.error):<EOL><INDENT>raise InvalidMaterialDescriptionError(<EOL>'<STR_LIT>'.format(name=name, value=value)<EOL>)<EOL><DEDENT><DEDENT>return {Tag.BINARY.dynamodb_tag: bytes(material_description_bytes)}<EOL>
Serialize a material description dictionary into a DynamodDB attribute. :param dict material_description: Material description dictionary :returns: Serialized material description as a DynamoDB binary attribute value :rtype: dict :raises InvalidMaterialDescriptionError: if invalid name or value found in material description
f5606:m0
def deserialize(serialized_material_description):<EOL>
try:<EOL><INDENT>_raw_material_description = serialized_material_description[Tag.BINARY.dynamodb_tag]<EOL>material_description_bytes = io.BytesIO(_raw_material_description)<EOL>total_bytes = len(_raw_material_description)<EOL><DEDENT>except (TypeError, KeyError):<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise InvalidMaterialDescriptionError(message)<EOL><DEDENT>_read_version(material_description_bytes)<EOL>material_description = {}<EOL>try:<EOL><INDENT>while material_description_bytes.tell() < total_bytes:<EOL><INDENT>name = to_str(decode_value(material_description_bytes))<EOL>value = to_str(decode_value(material_description_bytes))<EOL>material_description[name] = value<EOL><DEDENT><DEDENT>except struct.error:<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise InvalidMaterialDescriptionError(message)<EOL><DEDENT>return material_description<EOL>
Deserialize a serialized material description attribute into a material description dictionary. :param dict serialized_material_description: DynamoDB attribute value containing serialized material description. :returns: Material description dictionary :rtype: dict :raises InvalidMaterialDescriptionError: if malformed version :raises InvalidMaterialDescriptionVersionError: if unknown version is found
f5606:m1
def _read_version(material_description_bytes):<EOL>
try:<EOL><INDENT>(version,) = unpack_value("<STR_LIT>", material_description_bytes)<EOL><DEDENT>except struct.error:<EOL><INDENT>message = "<STR_LIT>"<EOL>_LOGGER.exception(message)<EOL>raise InvalidMaterialDescriptionError(message)<EOL><DEDENT>if version != _MATERIAL_DESCRIPTION_VERSION:<EOL><INDENT>raise InvalidMaterialDescriptionVersionError("<STR_LIT>".format(repr(version)))<EOL><DEDENT>
Read the version from the serialized material description and raise an error if it is unknown. :param material_description_bytes: serializezd material description :type material_description_bytes: io.BytesIO :raises InvalidMaterialDescriptionError: if malformed version :raises InvalidMaterialDescriptionVersionError: if unknown version is found
f5606:m2
def encode_length(attribute):<EOL>
return struct.pack("<STR_LIT>", len(attribute))<EOL>
Encodes the length of the attribute as an unsigned int. :param attribute: Attribute with length value :returns: Encoded value :rtype: bytes
f5608:m0
def encode_value(value):<EOL>
return struct.pack("<STR_LIT>".format(attr_len=len(value)), len(value), value)<EOL>
Encodes the value in Length-Value format. :param value: Value to encode :type value: six.string_types or :class:`boto3.dynamodb_encryption_sdk.types.Binary` :returns: Length-Value encoded value :rtype: bytes
f5608:m1
def _sorted_key_map(item, transform=to_bytes):
sorted_items = []<EOL>for key, value in item.items():<EOL><INDENT>_key = transform(key)<EOL>sorted_items.append((_key, value, key))<EOL><DEDENT>sorted_items = sorted(sorted_items, key=lambda x: x[<NUM_LIT:0>])<EOL>return sorted_items<EOL>
Creates a list of the item's key/value pairs as tuples, sorted by the keys transformed by transform. :param dict item: Source dictionary :param function transform: Transform function :returns: List of tuples containing transformed key, original value, and original key for each entry :rtype: list(tuple)
f5609:m0
def serialize_attribute(attribute): <EOL>
def _transform_binary_value(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(value, Binary):<EOL><INDENT>return bytes(value.value)<EOL><DEDENT>return bytes(value)<EOL><DEDENT>def _serialize_binary(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _RESERVED + Tag.BINARY.tag + encode_value(_transform_binary_value(_attribute))<EOL><DEDENT>def _transform_number_value(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>decimal_value = DYNAMODB_CONTEXT.create_decimal(value).normalize()<EOL>return "<STR_LIT>".format(decimal_value).encode("<STR_LIT:utf-8>")<EOL><DEDENT>def _serialize_number(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _RESERVED + Tag.NUMBER.tag + encode_value(_transform_number_value(_attribute))<EOL><DEDENT>def _transform_string_value(value):<EOL><INDENT>"""<STR_LIT>"""<EOL>return to_bytes(value)<EOL><DEDENT>def _serialize_string(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _RESERVED + Tag.STRING.tag + encode_value(_transform_string_value(_attribute))<EOL><DEDENT>def _serialize_boolean(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>_attribute_value = TagValues.TRUE.value if _attribute else TagValues.FALSE.value<EOL>return _RESERVED + Tag.BOOLEAN.tag + _attribute_value<EOL><DEDENT>def _serialize_null(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _RESERVED + Tag.NULL.tag<EOL><DEDENT>def _serialize_set(tag, _attribute, member_function):<EOL><INDENT>"""<STR_LIT>"""<EOL>serialized_attribute = io.BytesIO()<EOL>serialized_attribute.write(_RESERVED)<EOL>serialized_attribute.write(tag.tag)<EOL>serialized_attribute.write(encode_length(_attribute))<EOL>encoded_members = []<EOL>for member in _attribute:<EOL><INDENT>encoded_members.append(member_function(member))<EOL><DEDENT>for member in sorted(encoded_members):<EOL><INDENT>serialized_attribute.write(encode_value(member))<EOL><DEDENT>return serialized_attribute.getvalue()<EOL><DEDENT>def _serialize_binary_set(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _serialize_set(Tag.BINARY_SET, _attribute, _transform_binary_value)<EOL><DEDENT>def _serialize_number_set(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _serialize_set(Tag.NUMBER_SET, _attribute, _transform_number_value)<EOL><DEDENT>def _serialize_string_set(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>return _serialize_set(Tag.STRING_SET, _attribute, _transform_string_value)<EOL><DEDENT>def _serialize_list(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>serialized_attribute = io.BytesIO()<EOL>serialized_attribute.write(_RESERVED)<EOL>serialized_attribute.write(Tag.LIST.tag)<EOL>serialized_attribute.write(encode_length(_attribute))<EOL>for member in _attribute:<EOL><INDENT>serialized_attribute.write(serialize_attribute(member))<EOL><DEDENT>return serialized_attribute.getvalue()<EOL><DEDENT>def _serialize_map(_attribute):<EOL><INDENT>"""<STR_LIT>"""<EOL>serialized_attribute = io.BytesIO()<EOL>serialized_attribute.write(_RESERVED)<EOL>serialized_attribute.write(Tag.MAP.tag)<EOL>serialized_attribute.write(encode_length(_attribute))<EOL>sorted_items = _sorted_key_map(item=_attribute, transform=_transform_string_value)<EOL>for key, value, _original_key in sorted_items:<EOL><INDENT>serialized_attribute.write(_serialize_string(key))<EOL>serialized_attribute.write(serialize_attribute(value))<EOL><DEDENT>return serialized_attribute.getvalue()<EOL><DEDENT>def _serialize_function(dynamodb_tag):<EOL><INDENT>"""<STR_LIT>"""<EOL>serialize_functions = {<EOL>Tag.BINARY.dynamodb_tag: _serialize_binary,<EOL>Tag.BINARY_SET.dynamodb_tag: _serialize_binary_set,<EOL>Tag.NUMBER.dynamodb_tag: _serialize_number,<EOL>Tag.NUMBER_SET.dynamodb_tag: _serialize_number_set,<EOL>Tag.STRING.dynamodb_tag: _serialize_string,<EOL>Tag.STRING_SET.dynamodb_tag: _serialize_string_set,<EOL>Tag.BOOLEAN.dynamodb_tag: _serialize_boolean,<EOL>Tag.NULL.dynamodb_tag: _serialize_null,<EOL>Tag.LIST.dynamodb_tag: _serialize_list,<EOL>Tag.MAP.dynamodb_tag: _serialize_map,<EOL>}<EOL>try:<EOL><INDENT>return serialize_functions[dynamodb_tag]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise SerializationError('<STR_LIT>'.format(dynamodb_tag))<EOL><DEDENT><DEDENT>if not isinstance(attribute, dict):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(type(attribute)))<EOL><DEDENT>if len(attribute) != <NUM_LIT:1>:<EOL><INDENT>raise SerializationError(<EOL>"<STR_LIT>".format(len(attribute))<EOL>)<EOL><DEDENT>key, value = list(attribute.items())[<NUM_LIT:0>]<EOL>return _serialize_function(key)(value)<EOL>
Serializes a raw attribute to a byte string as defined for the DynamoDB Client-Side Encryption Standard. :param dict attribute: Item attribute value :returns: Serialized attribute :rtype: bytes
f5609:m1
def __init__(self, tag, dynamodb_tag, element_tag=None):<EOL>
self.tag = tag<EOL>self.dynamodb_tag = dynamodb_tag<EOL>self.element_tag = element_tag<EOL>
Sets up new Tag object. :param bytes tag: DynamoDB Encryption SDK tag :param bytes dynamodb_tag: DynamoDB tag :param bytes element_tag: The type of tag contained within attributes of this type
f5610:c2:m0
def __init__(self, raw, sha256):<EOL>
self.raw = raw<EOL>self.sha256 = sha256<EOL>
Set up a new :class:`SignatureValues` object. :param bytes raw: Raw value :param bytes sha256: SHA256 hash of raw value
f5610:c4:m0
def dictionary_validator(key_type, value_type):
def _validate_dictionary(instance, attribute, value):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not isinstance(value, dict):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(attribute.name))<EOL><DEDENT>for key, data in value.items():<EOL><INDENT>if not isinstance(key, key_type):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'.format(name=attribute.name, type=key_type)<EOL>)<EOL><DEDENT>if not isinstance(data, value_type):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'.format(name=attribute.name, type=value_type)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>return _validate_dictionary<EOL>
Validator for ``attrs`` that performs deep type checking of dictionaries.
f5611:m0
def iterable_validator(iterable_type, member_type):
def _validate_tuple(instance, attribute, value):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not isinstance(value, iterable_type):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(name=attribute.name, type=iterable_type))<EOL><DEDENT>for member in value:<EOL><INDENT>if not isinstance(member, member_type):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'.format(name=attribute.name, type=member_type)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>return _validate_tuple<EOL>
Validator for ``attrs`` that performs deep type checking of iterables.
f5611:m1
def callable_validator(instance, attribute, value):<EOL>
if not callable(value):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(name=attribute.name, value=value))<EOL><DEDENT>
Validate that an attribute value is callable. :raises TypeError: if ``value`` is not callable
f5611:m2
def sign_item(encrypted_item, signing_key, crypto_config):<EOL>
signature = signing_key.sign(<EOL>algorithm=signing_key.algorithm,<EOL>data=_string_to_sign(<EOL>item=encrypted_item,<EOL>table_name=crypto_config.encryption_context.table_name,<EOL>attribute_actions=crypto_config.attribute_actions,<EOL>),<EOL>)<EOL>return {Tag.BINARY.dynamodb_tag: signature}<EOL>
Generate the signature DynamoDB atttribute. :param dict encrypted_item: Encrypted DynamoDB item :param DelegatedKey signing_key: DelegatedKey to use to calculate the signature :param CryptoConfig crypto_config: Cryptographic configuration :returns: Item signature DynamoDB attribute value :rtype: dict
f5612:m0
def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config):<EOL>
signature = signature_attribute[Tag.BINARY.dynamodb_tag]<EOL>verification_key.verify(<EOL>algorithm=verification_key.algorithm,<EOL>signature=signature,<EOL>data=_string_to_sign(<EOL>item=encrypted_item,<EOL>table_name=crypto_config.encryption_context.table_name,<EOL>attribute_actions=crypto_config.attribute_actions,<EOL>),<EOL>)<EOL>
Verify the item signature. :param dict signature_attribute: Item signature DynamoDB attribute value :param dict encrypted_item: Encrypted DynamoDB item :param DelegatedKey verification_key: DelegatedKey to use to calculate the signature :param CryptoConfig crypto_config: Cryptographic configuration
f5612:m1
def _string_to_sign(item, table_name, attribute_actions):<EOL>
hasher = hashes.Hash(hashes.SHA256(), backend=default_backend())<EOL>data_to_sign = bytearray()<EOL>data_to_sign.extend(_hash_data(hasher=hasher, data="<STR_LIT>".format(table_name).encode(TEXT_ENCODING)))<EOL>for key in sorted(item.keys()):<EOL><INDENT>action = attribute_actions.action(key)<EOL>if action is CryptoAction.DO_NOTHING:<EOL><INDENT>continue<EOL><DEDENT>data_to_sign.extend(_hash_data(hasher=hasher, data=key.encode(TEXT_ENCODING)))<EOL>if action is CryptoAction.SIGN_ONLY:<EOL><INDENT>data_to_sign.extend(SignatureValues.PLAINTEXT.sha256)<EOL><DEDENT>else:<EOL><INDENT>data_to_sign.extend(SignatureValues.ENCRYPTED.sha256)<EOL><DEDENT>data_to_sign.extend(_hash_data(hasher=hasher, data=serialize_attribute(item[key])))<EOL><DEDENT>return bytes(data_to_sign)<EOL>
Generate the string to sign from an encrypted item and configuration. :param dict item: Encrypted DynamoDB item :param str table_name: Table name to use when generating the string to sign :param AttributeActions attribute_actions: Actions to take for item
f5612:m2
def _hash_data(hasher, data):
_hasher = hasher.copy()<EOL>_hasher.update(data)<EOL>return _hasher.finalize()<EOL>
Generate hash of data using provided hash type. :param hasher: Hasher instance to use as a base for calculating hash :type hasher: cryptography.hazmat.primitives.hashes.Hash :param bytes data: Data to sign :returns: Hash of data :rtype: bytes
f5612:m3
def encrypt_attribute(attribute_name, attribute, encryption_key, algorithm):<EOL>
serialized_attribute = serialize_attribute(attribute)<EOL>encrypted_attribute = encryption_key.encrypt(<EOL>algorithm=algorithm, name=attribute_name, plaintext=serialized_attribute<EOL>)<EOL>return {Tag.BINARY.dynamodb_tag: encrypted_attribute}<EOL>
Encrypt a single DynamoDB attribute. :param str attribute_name: DynamoDB attribute name :param dict attribute: Plaintext DynamoDB attribute :param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute :param str algorithm: Encryption algorithm descriptor (passed to encryption_key as algorithm) :returns: Encrypted DynamoDB binary attribute :rtype: dict
f5613:m0
def decrypt_attribute(attribute_name, attribute, decryption_key, algorithm):<EOL>
encrypted_attribute = attribute[Tag.BINARY.dynamodb_tag]<EOL>decrypted_attribute = decryption_key.decrypt(<EOL>algorithm=algorithm, name=attribute_name, ciphertext=encrypted_attribute<EOL>)<EOL>return deserialize_attribute(decrypted_attribute)<EOL>
Decrypt a single DynamoDB attribute. :param str attribute_name: DynamoDB attribute name :param dict attribute: Encrypted DynamoDB attribute :param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute :param str algorithm: Decryption algorithm descriptor (passed to encryption_key as algorithm) :returns: Plaintext DynamoDB attribute :rtype: dict
f5613:m1
@abc.abstractmethod<EOL><INDENT>def load_key(self, key, key_type, key_encoding):<EOL><DEDENT>
Load a key from bytes. :param bytes key: Raw key bytes to load :param EncryptionKeyType key_type: Type of key to load :param KeyEncodingType key_encoding: Encoding used to serialize ``key`` :returns: Loaded key :rtype: bytes
f5615:c0:m0
@abc.abstractmethod<EOL><INDENT>def validate_algorithm(self, algorithm):<EOL><DEDENT>
Determine whether the requested algorithm name is compatible with this authenticator. :param str algorithm: Algorithm name :raises InvalidAlgorithmError: if specified algorithm name is not compatible with this authenticator
f5615:c0:m1
@abc.abstractmethod<EOL><INDENT>def sign(self, key, data):<EOL><DEDENT>
Sign ``data`` using loaded ``key``. :param key: Loaded key :param bytes data: Data to sign :returns: Calculated signature :rtype: bytes :raises SigningError: if unable to sign ``data`` with ``key``
f5615:c0:m2
@abc.abstractmethod<EOL><INDENT>def verify(self, key, signature, data):<EOL><DEDENT>
Verify ``signature`` over ``data`` using ``key``. :param key: Loaded key :param bytes signature: Signature to verify :param bytes data: Data over which to verify signature :raises SignatureVerificationError: if unable to verify ``signature``
f5615:c0:m3
def _build_hmac_signer(self, key):<EOL>
return self.algorithm_type(key, self.hash_type(), backend=default_backend())<EOL>
Build HMAC signer using instance algorithm and hash type and ``key``. :param bytes key: Key to use in signer
f5615:c1:m1