Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,25 @@ def _endpoint_from_environment():
return os.environ.get(Constants.CLOUD_ENDPOINT) or None


def _properties(answer, data_key, name):

"""!
Every value a response gives for a property, being a member named name
within a top-level member named data_key, each name compared in any
case. A response may hold no such member, or more than one that
differs only in case.

@type answer: dict
@param answer: the response's JSON, read as an object
"""

for key, section in answer.items():
if str(key).lower() == data_key and isinstance(section, dict):
for member, value in section.items():
if str(member).lower() == name:
yield value


def _takes_timeout(client):

"""!
Expand Down Expand Up @@ -921,10 +940,14 @@ def process(self, flowdata):
@param flowdata: the FlowData to process
"""

# A sealed result redeems once, so a request that carries one is
# neither served from the cache nor stored in it.
if (hasattr(self, "cache") and humanconfidence.sealed_result_of(
flowdata.evidence) is not None):
# A response to a request carrying a sealed result to redeem, or to
# one bypasses_cache picks out, is made for one visitor, so it is
# neither served from the cache nor stored in it. is_cacheable keeps
# out every other response made for one visitor.
if hasattr(self, "cache") and (
humanconfidence.sealed_result_of(
flowdata.evidence) is not None
or self.bypasses_cache(flowdata.evidence)):
self.process_internal(flowdata)
result = None
else:
Expand All @@ -937,21 +960,65 @@ def process(self, flowdata):

return result

@staticmethod
def bypasses_cache(evidence):

"""!
Whether a request goes to the cloud service whatever the cache
holds, and its answer is not stored. A page iteration carries the
session id and the sequence, and a server may supply the visitor's
JA4 and HTTP/2 settings, so a request carrying any of them is made
for one visitor. The cache key is made from the evidence keys the
service lists, but the engine sends every evidence value, and the
service lists neither the session id nor the sequence. Two
iterations of one page that differ only in those would share a key,
and the later one, which may carry the browser test answers, would
be answered from the cache and never reach the service. So a
request carrying any of Constants.UNCACHED_EVIDENCE_NAMES, under any
prefix and in any letter case, bypasses the cache, and every other
request is cached as before.

@type evidence: Evidence
@param evidence: The flow data's Evidence

@rtype: bool
@return: True if the request bypasses the cache
"""

unaccepted = getattr(evidence, "get_unaccepted", dict)()
for source in (unaccepted, evidence.get_all()):
for key in source:
name = str(key).partition(Constants.EVIDENCE_SEPERATOR)
name = (name[2] if name[1] else name[0]).lower()
if name in Constants.UNCACHED_EVIDENCE_NAMES:
return True
return False

def is_cacheable(self, data):

"""!
A response whose JSON has a top-level member named fodid, in any
case, holds a 51Did created for the one request that asked for it,
so it is neither stored in the cache nor served from it. A fodid
below the top level is not one, and a response that cannot be read
as a JSON object is cached as before.
A response made for one visitor is neither stored in the cache nor
served from it. That is a response whose JSON holds any of these,
with member names compared in any case.

- A 51Did, being a top-level member named fodid. A fodid below the
top level is not one.
- A sealed Human Confidence result, being a HumanConfidence under
derived that humanconfidence.is_sealed_value finds sealed.
HumanConfidenceSource plays no part.
- The browser tests' script, being a BrowserTestsJavaScript under
browserderived that is not blank.

A request made for one visitor never reaches the cache, as process
and bypasses_cache say. A response that cannot be read as a JSON
object is cached as before.

@type data: ElementData
@param data: A response the engine has just made, or one found in
the cache

@rtype: bool
@return: False if the response holds a fodid
@return: False if the response was made for one visitor
"""

try:
Expand All @@ -961,7 +1028,17 @@ def is_cacheable(self, data):
return True
if not isinstance(answer, dict):
return True
return not any(str(name).lower() == "fodid" for name in answer)
if any(str(name).lower() == Constants.DID_MEMBER for name in answer):
return False
if any(humanconfidence.is_sealed_value(value)
for value in _properties(
answer, Constants.HUMAN_CONFIDENCE_DATA_KEY,
Constants.HUMAN_CONFIDENCE_PROPERTY)):
return False
return all(humanconfidence.is_blank(value)
for value in _properties(
answer, Constants.BROWSER_TESTS_DATA_KEY,
Constants.BROWSER_TESTS_PROPERTY))

def report_properties_not_covered(self, result):

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,23 @@ class Constants:
RESOURCE_PARAMETER, LICENSE_PARAMETER, LICENCE_SPELLING,
VALUES_PARAMETER)

# Evidence names, under any prefix, that make a request one made for a
# single visitor, being the session id and the sequence of a page
# iteration and the visitor's JA4 and HTTP/2 settings. A request
# carrying one goes to the service whatever the cache holds. See
# CloudRequestEngine.bypasses_cache.
UNCACHED_EVIDENCE_NAMES = ("session-id", "sequence", "ja4", "h2")

# The members of a response that hold a value made for one visitor,
# compared in any case. See CloudRequestEngine.is_cacheable. A 51Did is
# a top-level member. HumanConfidence and the browser tests' script are
# properties under the data key of the element that gives them.
DID_MEMBER = "fodid"
HUMAN_CONFIDENCE_DATA_KEY = "derived"
HUMAN_CONFIDENCE_PROPERTY = "humanconfidence"
BROWSER_TESTS_DATA_KEY = "browserderived"
BROWSER_TESTS_PROPERTY = "browsertestsjavascript"

# Takes the place of the licence key in every message the engine
# builds, and of the sealed result and the transaction in a message made
# while a sealed result is redeemed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@
# The values HumanConfidence has once a sealed result is redeemed.
REDEEMED_VALUES = ("High", "Medium", "Low")

# The values HumanConfidence has, in lower case. Any other text that is not
# blank, Unknown included, is a sealed result. See is_sealed_value.
UNSEALED_VALUES = ("high", "medium", "low")

# The values HumanConfidenceSource has once a sealed result is redeemed, as
# the response gives them. The package reads them and never sets one.
REDEEMED_SOURCES = ("Passive", "Active")
Expand Down Expand Up @@ -203,6 +207,19 @@ def sealed_result_of(evidence):
return str(value)


def is_sealed_value(value):
"""!
Whether a HumanConfidence value the cloud service returned is a sealed
result, being text that is not blank and is none of UNSEALED_VALUES,
letter case ignored. The value alone decides, never
HumanConfidenceSource, because the route a request takes decides
sealing and a sealed result can be Passive or Active.
"""

return (isinstance(value, str) and not is_blank(value)
and value.lower() not in UNSEALED_VALUES)


class HumanConfidencePage(object):

"""!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
# *********************************************************************

"""
A cache never stores or serves a Cloud Request Engine response that holds a
value created for one request, being a top-level member named fodid in any
case, as the caching page of the specification says.
A cache never stores or serves a Cloud Request Engine response made for one
visitor. That is a response holding a 51Did, being a top-level member named
fodid in any case, a sealed Human Confidence result, or the browser tests'
script.
"""

import json
Expand All @@ -39,6 +40,23 @@
from .classes.cloudrequestengine_testbase import CloudRequestEngineTestsBase
from .classes.mockrequestclient import MockRequestClient

# A sealed result is text the browser can't read. Any text that is not blank
# and is none of High, Medium or Low, letter case ignored, is one.
SEALED = "3z|q7Lx0aB-mN2vR8sT4uW6yZ1cE5gI9kO"

# The browser tests' script the page runs.
SCRIPT = "(function(){/* the browser tests */})();"


def human_confidence(value, source):
"""A response holding HumanConfidence and HumanConfidenceSource under
derived, where source None leaves HumanConfidenceSource out."""

derived = {"humanconfidence": value}
if source is not None:
derived["humanconfidencesource"] = source
return {"device": {"ismobile": True}, "derived": derived}


class CountingClient(MockRequestClient):
"""Answers every data request with the same text and counts them."""
Expand Down Expand Up @@ -144,3 +162,89 @@ def test_an_entry_holding_a_fodid_is_not_served(self):
served, requests = self.found_in_cache(entry_text)
self.assertNotEqual(entry_text, served, name)
self.assertEqual(1, requests, name)

def test_a_sealed_passive_result_is_neither_stored_nor_served(self):
"""A sealed result is told from the HumanConfidence value, so one
whose source is Passive is kept out of the cache as well."""

answer = json.dumps(human_confidence(SEALED, "Passive"))
self.assertEqual(2, self.requests_for(answer))
served, requests = self.found_in_cache(answer)
self.assertNotEqual(answer, served)
self.assertEqual(1, requests)

def test_a_sealed_result_is_kept_out_whatever_its_source(self):
for source in ("Active", None, "Unexpected"):
answer = json.dumps(human_confidence(SEALED, source))
self.assertEqual(2, self.requests_for(answer), source)

def test_a_sealed_result_is_found_in_any_case(self):
for data_key, name in (("Derived", "HumanConfidence"),
("DERIVED", "humanConfidence")):
answer = json.dumps({data_key: {name: SEALED}})
self.assertEqual(2, self.requests_for(answer), data_key)

def test_an_unsealed_active_value_is_cached(self):
"""Active does not mean sealed. A server's call with a License Key
gets the level itself, and nothing else in the response makes it
one made for one visitor."""

for level in ("High", "Medium", "Low"):
answer = json.dumps(human_confidence(level, "Active"))
self.assertEqual(1, self.requests_for(answer), level)

def test_a_value_in_any_case_is_cached(self):
"""A value HumanConfidence has, in another letter case, is not a
sealed result."""

for level, source in (("HIGH", "Active"), ("medium", "Passive"),
("lOW", None)):
answer = json.dumps(human_confidence(level, source))
self.assertEqual(1, self.requests_for(answer), level)

def test_unknown_is_neither_stored_nor_served(self):
"""Unknown is not a value HumanConfidence has, so it is text other
than High, Medium or Low and counts as a sealed result."""

for level, source in (("Unknown", None), ("Unknown", "Passive"),
("Unknown", "Active"), ("unknown", None)):
answer = json.dumps(human_confidence(level, source))
self.assertEqual(2, self.requests_for(answer), level)
served, requests = self.found_in_cache(answer)
self.assertNotEqual(answer, served, level)
self.assertEqual(1, requests, level)

def test_a_null_human_confidence_is_cached(self):
answer = json.dumps({"derived": {
"humanconfidence": None,
"humanconfidencenullreason": "No value for this request."}})
self.assertEqual(1, self.requests_for(answer))

def test_a_blank_human_confidence_is_cached(self):
for blank in ("", " ", "\t\n"):
answer = json.dumps(human_confidence(blank, None))
self.assertEqual(1, self.requests_for(answer), repr(blank))

def test_a_sealed_result_under_another_data_key_does_not_count(self):
answer = json.dumps({"device": {"humanconfidence": SEALED}})
self.assertEqual(1, self.requests_for(answer))

def test_a_response_with_the_browser_tests_is_neither_stored_nor_served(
self):
for data_key, name in (("browserderived", "browsertestsjavascript"),
("BrowserDerived", "BrowserTestsJavaScript")):
answer = json.dumps({data_key: {name: SCRIPT}})
self.assertEqual(2, self.requests_for(answer), data_key)
served, requests = self.found_in_cache(answer)
self.assertNotEqual(answer, served, data_key)
self.assertEqual(1, requests, data_key)

def test_a_response_without_the_browser_tests_script_is_cached(self):
"""The property comes back with no value where the keys in use do
not cover it."""

for value in (None, "", " "):
answer = json.dumps({"browserderived": {
"browsertestsjavascript": value,
"browsertestsjavascriptnullreason": "Not covered."}})
self.assertEqual(1, self.requests_for(answer), repr(value))
Loading
Loading