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):<E...
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} \\m...
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...
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.biparti...
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...
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 Zer...
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{ \\...
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><IN...
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:`...
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: WeightedCre...
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._revi...
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: T...
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 con...
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><INDE...
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 specifie...
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><...
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_ke...
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=s...
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 = ...
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...
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_LI...
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_LI...
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>"}, <EO...
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:...
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_LI...
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_LI...
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_LI...
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>",<...
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...
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)...
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 i...
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(...
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 InvalidMaterialDescriptionErro...
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 InvalidMater...
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 InvalidMaterialDescriptio...
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(...
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>'.for...
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 TypeEr...
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: di...
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,<E...
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 CryptoActi...
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...
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...
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