diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py index f200a713..d1148a31 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py @@ -34,12 +34,12 @@ # 1. Passive. This server asks the cloud with the visitor's request headers # and IP address, and gets a plain level. # 2. Active. The 51Degrees client script runs the browser tests and sends -# the answers to the cloud, which answers with a sealed value. This -# server redeems the sealed value with the License Key, which the -# browser never sees, and gets the level. Redeeming needs a cloud that -# offers the redeem call (POST hc/redeem). A sealed value that can't be -# redeemed gives Active Low, and if no sealed value arrives within 30 -# seconds the page says No result. +# the answers to the cloud, which answers with a sealed value. The page +# sends the sealed value to this server, where the cloud request engine +# redeems it with the License Key, which the browser never sees. The +# example reads HumanConfidence and HumanConfidenceSource and nothing +# more. A sealed value that can't be redeemed gives Active Low, and if +# no sealed value arrives within 30 seconds the page says No result. # # The Resource Key is put in the page, as the 51Degrees client script is # loaded with it. The License Key stays on this server. @@ -83,6 +83,7 @@ from flask import Flask, Response, abort, jsonify, make_response from flask import render_template, request +from fiftyone_pipeline_cloudrequestengine.cloudengine import CloudEngine from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ CloudRequestEngine from fiftyone_pipeline_cloudrequestengine.cloudrequestexception import \ @@ -103,9 +104,6 @@ MODES = ("client", "server") MODE_COOKIE = "hc_mode" -# The levels, highest first. A level the cloud doesn't give is the last. -LEVELS = ("High", "Medium", "Low") - # The 51Degrees cloud hosts. The host of the endpoint in use, such as a # private cloud in Docker, counts as a cloud host too. CLOUD_HOSTS = r"cloud[a-z0-9-]*\.51degrees\.com" @@ -220,6 +218,25 @@ def create_app(resource_key, license_key, api): pipeline = PipelineBuilder({"add_javascript_builder": False}).add( engine).build() + # A second pipeline for the active level, whose engine carries the + # License Key, so only this pipeline sends it. It takes what the first + # engine discovered, so building it asks the cloud nothing more. Its + # engine gives each page a challenge and redeems the sealed value the + # page sends back. The cloud engine for "derived" gives the two + # properties the page shows. + active_engine = CloudRequestEngine({ + "resource_key": resource_key, + "license_key": license_key, + "cloud_endpoint": api, + "timeout_seconds": TIMEOUT, + "discovery_state": engine.discovery_state()}) + derived = CloudEngine() + derived.datakey = "derived" + active_pipeline = PipelineBuilder({ + "add_javascript_builder": False, + "suppress_process_exceptions": True}).add(active_engine).add( + derived).build() + def visitor_headers(): # The request headers the cloud reads, from the evidence keys the # engine was given. Only these are passed on, so headers such as @@ -273,8 +290,12 @@ def index(): mode = request.cookies.get(MODE_COOKIE) if mode not in MODES: mode = MODES[0] + # Each page load gets its own challenge, which the page sends to + # the cloud with the browser tests, and a page value it sends back + # with the sealed value. response = make_response(render_template( - "index.html", resource_key=resource_key, api=api, mode=mode)) + "index.html", resource_key=resource_key, api=api, mode=mode, + hc=active_engine.human_confidence_page_values())) response.set_cookie(MODE_COOKIE, mode, samesite="Lax") # The page must never come from a cache, as each load runs the # tests. @@ -295,27 +316,28 @@ def passive(): except Exception as error: return jsonify(error=str(error)) - # Redeem: the page, or a terminal, sends a sealed value, and this server - # redeems it with the License Key. Only the level goes back. A value - # that doesn't redeem gives Low, as nothing then shows a person is - # there. The cloud's own answer is never sent back. - @app.route("/redeem", methods=["POST"]) - def redeem(): - - sealed = request.form.get("value", "") - fields = {"value": sealed} - if license_key: - fields["license"] = license_key - level = None - try: - answer = requests.request( - "POST", api + "hc/redeem", data=fields, timeout=TIMEOUT) - level = read(answer.json(), "humanConfidence") - except (requests.RequestException, ValueError): - pass - if level not in LEVELS: - level = LEVELS[-1] - return jsonify(humanConfidence=level) + # Active: the page, or a terminal, sends the sealed value as + # humanconfidence, with its page value as humanconfidencepage. The + # cloud request engine redeems it, and the example reads the two + # properties. A sealed value that doesn't redeem gives Low. + @app.route("/active", methods=["POST"]) + def active(): + + if not request.form.get("humanconfidence"): + abort(400) + flowdata = active_pipeline.create_flowdata() + for name, value in visitor_headers().items(): + if name != "client-ip": + flowdata.evidence.add("header." + name, value) + for name in ("humanconfidence", "humanconfidencepage"): + flowdata.evidence.add( + "query." + name, request.form.get(name, "")) + flowdata.process() + derived = flowdata.get("derived") + return jsonify( + humanConfidence=derived.get("humanconfidence").value(), + humanConfidenceSource=derived.get( + "humanconfidencesource").value()) # Server mode: the client script, fetched from the cloud for this # visitor, with every cloud address in it pointed at this server. @@ -324,6 +346,10 @@ def script(): try: query = {} + # The page's challenge, which the cloud seals the result to. + challenge = request.args.get("challenge") + if challenge: + query["challenge"] = challenge address = public_ip(request.remote_addr) if address: query["client-ip"] = address diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html index 207c754c..2f24b032 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html @@ -114,8 +114,12 @@

Find out more

var API = {{ api|tojson }}; var API_ORIGIN = new URL(API).origin; var MODE = {{ mode|tojson }}; - // This server's redeem route, which holds the License Key. - var REDEEM = location.origin + "/redeem"; + // This server's route for the active level, whose cloud request engine + // redeems the sealed value with the License Key. + var ACTIVE = location.origin + "/active"; + // The challenge this server gave the page, which the 51Degrees script + // sends to the cloud, and the page value the sealed value goes back with. + var HC = {{ hc|tojson }}; // Server side, the script's calls to the cloud go to // /hc/cloud// here. var FORWARD = /^https?:\/\/[^\/]+\/hc\/cloud\/([^\/]+)\/(.*)$/; @@ -170,8 +174,10 @@

Find out more

active: function (url, pairs) { return "$v = (" + post("curl.exe", url, pairs) + " | ConvertFrom-Json).derived.humanconfidence; \"Active \" + (" + - "curl.exe -s -X POST \"" + REDEEM + "\" --data-urlencode " + - "\"value=$v\" | ConvertFrom-Json).humanConfidence"; + "curl.exe -s -X POST \"" + ACTIVE + "\" --data-urlencode " + + "\"humanconfidence=$v\" --data \"humanconfidencepage=" + + encode(HC.humanconfidencepage) + + "\" | ConvertFrom-Json).humanConfidence"; } }, sh: { @@ -182,7 +188,9 @@

Find out more

active: function (url, pairs) { return "v=$(" + post("curl", url, pairs) + " | " + PY + "['derived']['humanconfidence'])\"); printf 'Active '; " + - "curl -s -X POST \"" + REDEEM + "\" --data-urlencode \"value=$v\"" + + "curl -s -X POST \"" + ACTIVE + "\" --data-urlencode " + + "\"humanconfidence=$v\" --data \"humanconfidencepage=" + + encode(HC.humanconfidencepage) + "\"" + " | " + PY + "['humanConfidence'])\""; } } @@ -285,19 +293,18 @@

Find out more

return originalFetch.apply(this, arguments); }; - // Active. Each new sealed value goes to this server to redeem, and only - // the answer for the newest one is shown. - var seen = null, latest = 0; + // Active. The first sealed value goes to this server with the page + // value, as the challenge it was sealed to is used once, and the level + // that comes back is shown. + var seen = null; function redeem(value) { - var mine = ++latest; var body = new URLSearchParams(); - body.set("value", value); - originalFetch("redeem", { method: "POST", body: body }) + body.set("humanconfidence", value); + body.set("humanconfidencepage", HC.humanconfidencepage); + originalFetch("active", { method: "POST", body: body }) .then(function (r) { return r.json(); }) - .then(function (answer) { - if (mine === latest) { show("active", answer.humanConfidence); } - }) - .catch(function () { if (mine === latest) { show("active", null); } }); + .then(function (answer) { show("active", answer.humanConfidence); }) + .catch(function () { show("active", null); }); } // The script's third party cookie check calls window.fodTpcEndpoint, or @@ -310,7 +317,10 @@

Find out more

// server side. Its result comes back through fod.onChange. var script = document.createElement("script"); script.async = true; - script.src = MODE === "server" ? "hc/script.js" : API + RESOURCE + ".js"; + // The script is asked for with the challenge, which the cloud seals the + // result to. + script.src = (MODE === "server" ? "hc/script.js" : API + RESOURCE + ".js") + + "?challenge=" + encodeURIComponent(HC.challenge); script.onerror = function () { show("active", null); }; script.onload = function () { if (!window.fod || typeof window.fod.onChange !== "function") { @@ -323,7 +333,7 @@

Find out more

// run, and its HumanConfidence is then a plain level. Only a sealed // value is redeemed: redeeming a plain level answers unreadable, // which would show Active Low for tests that haven't run yet. - if (value && PLAIN.indexOf(value) < 0 && value !== seen) { + if (value && PLAIN.indexOf(value) < 0 && seen === null) { seen = value; redeem(value); } diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py index 77385555..1bae9141 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py @@ -30,10 +30,14 @@ answer, and describes the request it sent. A Basic key, whose product does not offer HumanConfidenceSource, is checked the same way. -Only the passive step is run here. The active step needs the browser tests, -which only a browser runs. +A sealed value is made only by the browser tests, which only a browser +runs, so the active step is checked with a value the cloud did not seal, +which gives Active Low. """ +import json +import re + import pytest import requests @@ -133,6 +137,24 @@ def test_a_basic_key_gets_a_passive_level(api, naming_the_properties): assert answer["humanConfidence"] in LEVELS + (None,) +def post_unsealed(client): + """Serves the page, then sends back a value the cloud did not seal, + with the page's own page value.""" + html = client.get("/", headers=HEADERS).get_data(as_text=True) + values = json.loads(re.search(r"var HC = (\{[^;]*\});", html).group(1)) + return client.post("/active", headers=HEADERS, data={ + "humanconfidence": "a-value-the-cloud-did-not-seal", + "humanconfidencepage": values["humanconfidencepage"]}) + + +def test_a_value_that_does_not_redeem_gives_active_low(client): + answer = post_unsealed(client).get_json() + assert answer["humanConfidence"] in LEVELS + assert answer["humanConfidenceSource"] in ("Active", "Passive") + assert answer == { + "humanConfidence": "Low", "humanConfidenceSource": "Active"} + + def test_license_key_never_reaches_the_browser(client): license_key = ExampleUtils.get_license_key() if not license_key: @@ -142,5 +164,5 @@ def test_license_key_never_reaches_the_browser(client): for response in (client.get("/?mode=client", headers=HEADERS), client.get("/?mode=server", headers=HEADERS), client.get("/passive", headers=HEADERS), - client.post("/redeem", data={"value": "not-sealed"})): + post_unsealed(client)): assert license_key.encode() not in response.data diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py index 9b2388d6..aa3d042a 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py @@ -162,6 +162,19 @@ def request(self, method, url, data=None, headers=None, timeout=None, "header.user-agent", "header.sec-ch-ua", "query.client-ip"], url=url) + if bare == RESOURCE_KEY + ".json" and "humanconfidence" in data: + # A sealed value redeems once, with a challenge and the License + # Key, and gives the level as HumanConfidence. + sealed = data["humanconfidence"] + if (sealed in self.redeemed or not data.get("challenge") + or data.get("license") != LICENSE_KEY): + return StubResponse({"derived": { + "humanconfidence": None, + "humanconfidencenullreason": "Not redeemed."}}, url=url) + self.redeemed.add(sealed) + return StubResponse( + {"derived": {"humanconfidence": "High"}}, url=url) + if bare == RESOURCE_KEY + ".json": return StubResponse({"derived": { "humanconfidence": "Medium", @@ -171,14 +184,6 @@ def request(self, method, url, data=None, headers=None, timeout=None, return StubResponse(self.script, url=url, headers=[ ("Content-Type", "application/javascript")]) - if bare == "hc/redeem": - if data.get("value") in self.redeemed: - return StubResponse({"result": "replayed"}, url=url) - self.redeemed.add(data.get("value")) - return StubResponse({ - "humanConfidence": "High", "secondsSinceVerified": 2}, - url=url) - return StubResponse("Not Found", 404, url=url) @@ -217,7 +222,9 @@ def test_page_carries_the_resource_key_and_the_cloud_address(cloud): assert f'var RESOURCE = "{RESOURCE_KEY}";' in html assert f'var API = "{API}";' in html assert '' in html - assert client.get("/css/examples-main.min.css").status_code == 200 + stylesheet = client.get("/css/examples-main.min.css") + stylesheet.close() + assert stylesheet.status_code == 200 def test_page_is_never_kept_by_a_cache(cloud): @@ -519,76 +526,130 @@ def test_passive_answers_when_the_cloud_cannot_be_reached(cloud): assert "cannot be reached" in response.get_json()["error"] -# Redeem. +# Active. + +SEALED = "a-sealed-value" + + +def page_values(client, mode="client"): + """The challenge and page value the page was given.""" + html = client.get("/?mode=" + mode).get_data(as_text=True) + found = re.search(r"var HC = (\{[^;]*\});", html) + assert found, "The page holds no challenge" + return json.loads(found.group(1)) + + +def post_active(client, values, sealed=SEALED): + return client.post("/active", data={ + "humanconfidence": sealed, + "humanconfidencepage": values["humanconfidencepage"]}) + + +def test_page_is_given_a_new_challenge_each_time(cloud): + cloud() + client = client_for() + first, second = page_values(client), page_values(client) + + assert set(first) == {"challenge", "humanconfidencepage"} + assert first["challenge"] != second["challenge"] + assert first["humanconfidencepage"] != second["humanconfidencepage"] + + +def test_page_asks_for_the_script_with_its_challenge(cloud): + cloud() + html = client_for().get("/").get_data(as_text=True) + + assert '+ "?challenge=" + encodeURIComponent(HC.challenge);' in html -def test_redeem_sends_the_sealed_value_with_the_license_key(cloud): + +def test_active_reads_the_two_properties_the_engine_gives(cloud): stub = cloud() - response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + client = client_for() + values = page_values(client) + response = post_active(client, values) assert response.status_code == 200 - assert response.headers["Content-Type"].startswith("application/json") - # Only the level goes back. - assert response.get_json() == {"humanConfidence": "High"} + assert response.get_json() == { + "humanConfidence": "High", "humanConfidenceSource": "Active"} + # The cloud request engine redeemed the sealed value through its JSON + # call, with the challenge the page was given and the License Key. method, url, data = stub.requests[-1] assert method == "POST" - assert url == API + "hc/redeem" - assert data == {"value": "a-sealed-value", "license": LICENSE_KEY} + assert url.split("?")[0] == API + RESOURCE_KEY + ".json" + assert data["humanconfidence"] == SEALED + assert data["challenge"] == values["challenge"] + assert data["license"] == LICENSE_KEY + assert "humanconfidencepage" not in data + assert stub.sent_to("hc/redeem") == [] -def test_second_redeem_of_the_same_value_gives_low(cloud): +def test_second_post_of_the_same_page_gives_low(cloud): cloud() client = client_for() - first = client.post("/redeem", data={"value": "a-sealed-value"}) - second = client.post("/redeem", data={"value": "a-sealed-value"}) + values = page_values(client) + first = post_active(client, values) + second = post_active(client, values) - assert first.get_json() == {"humanConfidence": "High"} - assert second.get_json() == {"humanConfidence": "Low"} + assert first.get_json()["humanConfidence"] == "High" + assert second.get_json() == { + "humanConfidence": "Low", "humanConfidenceSource": "Active"} -def test_redeem_without_a_license_key_sends_none(cloud): +def test_active_without_a_license_key_gives_low(cloud): stub = cloud() - client_for(license_key="").post( - "/redeem", data={"value": "a-sealed-value"}) + client = client_for(license_key="") + response = post_active(client, page_values(client)) - assert stub.requests[-1][2] == {"value": "a-sealed-value"} + assert response.get_json() == { + "humanConfidence": "Low", "humanConfidenceSource": "Active"} + assert "humanconfidence" not in stub.requests[-1][2] + + +def test_active_without_a_sealed_value_is_refused(cloud): + cloud() + client = client_for() + + assert post_active(client, page_values(client), "").status_code == 400 @pytest.mark.parametrize("answer", [ - StubResponse('{"result":"expired"}', 400), - StubResponse('{"result":"unreadable"}', 400), + StubResponse('{"errors":["The sealed value was not redeemed."]}', 400), StubResponse("Not Found", 404), - StubResponse('{"humanConfidence":"Unknown"}'), - StubResponse('{"humanConfidence":"a-sealed-value"}'), + StubResponse({"derived": {"humanconfidence": "Unknown"}}), + StubResponse({"derived": {"humanconfidence": SEALED}}), + StubResponse({"device": {"ismobile": False}}), requests.exceptions.ConnectionError( "The stand-in service cannot be reached."), requests.exceptions.Timeout("The stand-in service took too long."), -], ids=["expired", "unreadable", "not-offered", "unknown", "not-a-level", +], ids=["refused", "not-found", "unknown", "not-a-level", "no-derived", "unreachable", "timeout"]) def test_value_that_does_not_redeem_gives_low(cloud, answer): stub = cloud() - stub.instead["hc/redeem"] = answer - response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + client = client_for() + values = page_values(client) + stub.instead[".json"] = answer + response = post_active(client, values) assert response.status_code == 200 - assert response.get_json() == {"humanConfidence": "Low"} + assert response.get_json() == { + "humanConfidence": "Low", "humanConfidenceSource": "Active"} @pytest.mark.parametrize("answer", [ None, - StubResponse('{"result":"expired"}', 400), + StubResponse('{"errors":["The sealed value was not redeemed."]}', 400), requests.exceptions.ConnectionError( "The stand-in service cannot be reached.")], - ids=["redeemed", "expired", "unreachable"]) + ids=["redeemed", "refused", "unreachable"]) def test_routes_write_nothing_to_the_console(cloud, capsys, answer): stub = cloud() + client = client_for() + values = page_values(client) if answer is not None: - stub.instead["hc/redeem"] = answer stub.instead[".js"] = answer stub.instead[".json"] = answer - client = client_for() - client.get("/") client.get("/passive") - client.post("/redeem", data={"value": "a-sealed-value"}) + post_active(client, values) client.get("/hc/script.js") client.post("/hc/cloud/cloud.example/api/v4/" + RESOURCE_KEY + ".json", data={"fod-test": "an-answer"}) @@ -599,13 +660,22 @@ def test_routes_write_nothing_to_the_console(cloud, capsys, answer): assert printed.err == "" -def test_redeem_waits_the_example_timeout(cloud): +def test_active_waits_the_example_timeout(cloud): stub = cloud() - client_for().post("/redeem", data={"value": "a-sealed-value"}) + client = client_for() + post_active(client, page_values(client)) assert stub.calls[-1]["timeout"] == example.TIMEOUT +def test_script_is_asked_for_with_the_pages_challenge(cloud): + stub = cloud() + client_for().get("/hc/script.js?challenge=a-challenge", + **from_address(LOCAL_ADDRESS)) + + assert stub.calls[-1]["params"] == {"challenge": "a-challenge"} + + # Server mode: the client script. def test_script_points_each_cloud_address_at_this_server(cloud): diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py index f62223cf..f1074db2 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py @@ -43,6 +43,8 @@ from .requestclient import RequestClient from .cloudrequestexception import CloudRequestException from .constants import Constants +from .humanconfidence import HumanConfidenceChallenges +from .humanconfidence import HumanConfidenceNames try: #python2 @@ -109,6 +111,10 @@ def __init__(self, settings = {}): the same credentials, as its discovery_state() gives it, either the JSON text or the dictionary it holds. The engine then makes no discovery request when it is built. + 7) human_confidence_challenges, where the engine keeps the + challenge it gives each page for Human Confidence, an object with + the issue and take methods of HumanConfidenceChallenges. Each + engine keeps its own in memory when this is missing. See the Credentials section of the cloud request engine specification for the combinations that are accepted: @@ -201,6 +207,12 @@ def __init__(self, settings = {}): self.exclude_from_messages = True + # The challenges given to pages for Human Confidence. See + # human_confidence_page_values. + self._challenges = settings.get("human_confidence_challenges") + if self._challenges is None: + self._challenges = HumanConfidenceChallenges() + # The evidence key filter, with the key list it was made from. See # get_evidence_key_filter. self._evidence_key_filter = None @@ -590,6 +602,7 @@ def validate_response( self, cloud_response: requests.Response, check_for_error_messages=True, + hidden=(), ): """! Validate the JSON response from the cloud service. Each entry in @@ -598,6 +611,9 @@ def validate_response( @type: Response @param: Response returned from the cloud service. + @type hidden: tuple + @param hidden: values no error or warning may hold, each shown as + asterisks in full, as masked says @raise CloudRequestException: where the response is not JSON, holds errors, has no data, or has a status other than 200 """ @@ -614,12 +630,12 @@ def validate_response( raise CloudRequestException(self.masked( f'Cloud request engine properties list request returned code "{cloud_response.status_code}"' f' with non-JSON content "{cloud_response.text}"' - ), cloud_response.status_code) + , hidden), cloud_response.status_code) except Exception as e: raise CloudRequestException(self.masked( f'Cloud request engine properties list request returned code "{cloud_response.status_code}"' f' with content "{cloud_response.text}".\nError: "{type(e).__name__}: {e}"' - ), cloud_response.status_code) + , hidden), cloud_response.status_code) has_errors = "errors" in json_response and len(json_response["errors"]) has_data = len(json_response) > (1 if has_errors else 0) @@ -630,7 +646,7 @@ def validate_response( entry if isinstance(entry, str) else json.dumps(entry) for entry in json_response["errors"]) - self._warn_response_warnings(json_response) + self._warn_response_warnings(json_response, hidden) # If there were no errors but there was also no other data # in the response then add an explanation to the list of @@ -658,7 +674,8 @@ def validate_response( # one raised. errors = [ CloudRequestException( - self.masked(Constants.EXCEPTION_CLOUD_ERROR.format(message)), + self.masked(Constants.EXCEPTION_CLOUD_ERROR.format(message), + hidden), cloud_response.status_code, cloud_response.headers, ) @@ -673,26 +690,35 @@ def validate_response( errors, ) - def masked(self, text): + def masked(self, text, hidden=()): """! Text from or about a cloud answer with the licence key in use shown only as its last four characters. The cloud service names the key in some of its errors, and a URL may carry it in its query. + + Each value in hidden is shown as asterisks in full, being the + sealed value, the challenge and the License Key of a request that + redeems a sealed Human Confidence value, as "What a package never + exposes" in the Human Confidence page of the specification says. """ + text = str(text) + for value in hidden: + if value: + text = text.replace(value, Constants.HIDDEN_VALUE) text = mask_licence_keys_in_text(text) if self.license_key != "": text = text.replace( self.license_key, mask_licence_key(self.license_key)) return text - def _warn_response_warnings(self, json_response): + def _warn_response_warnings(self, json_response, hidden=()): """! Give each entry in the warnings list of a cloud answer as a - warning, with the licence key masked. An answer with no such list - gives none. + warning, with the licence key masked and each value in hidden shown + as asterisks. An answer with no such list gives none. """ if not isinstance(json_response, dict): @@ -701,27 +727,38 @@ def _warn_response_warnings(self, json_response): if not isinstance(entries, list): return for entry in entries: - warnings.warn(self.masked(str(entry))) + warnings.warn(self.masked(str(entry), hidden)) - def make_cloud_request(self, type, url, content = None): + def make_cloud_request(self, type, url, content = None, hidden=()): - """! + """! @type url: string @param url - + @type hidden: tuple + @param hidden: values no error or warning may hold, as masked says + @rtype: dict @return Returns dict with data and error properties error contains any errors from the request, data contains the response """ - if _takes_timeout(self.http_client): - cloudResponse = self.http_client.request( - type, url, content, self.cloud_request_origin, - timeout_seconds=self.timeout_seconds) - else: - cloudResponse = self.http_client.request( - type, url, content, self.cloud_request_origin) - - self.validate_response(cloudResponse) + try: + if _takes_timeout(self.http_client): + cloudResponse = self.http_client.request( + type, url, content, self.cloud_request_origin, + timeout_seconds=self.timeout_seconds) + else: + cloudResponse = self.http_client.request( + type, url, content, self.cloud_request_origin) + except Exception as error: + # An error that names a hidden value is raised again with the + # value shown as asterisks. Any other is raised as it is. + text = str(error) + if any(value and value in text for value in hidden): + raise CloudRequestException( + self.masked(text, hidden)) from None + raise + + self.validate_response(cloudResponse, hidden=hidden) return cloudResponse.text @@ -743,16 +780,12 @@ def process_internal(self, flowdata): """ - self._complete_discovery() + sealed = self.sealed_human_confidence(flowdata) + if sealed is not None: + self._process_sealed(flowdata, sealed) + return - # A resource key names the route. A licence key - # alone has no resource key to put there, so it uses the data - # endpoint that takes none and travels in the body with the list - # of properties wanted. - if self.resource_key != "": - url = self.baseURL + self.resource_key + ".json?" - else: - url = self.baseURL + Constants.LICENSE_DATA_PATH + self._complete_discovery() content = self.get_content(flowdata) content.update(self.get_credentials()) @@ -760,7 +793,7 @@ def process_internal(self, flowdata): content[Constants.VALUES_PARAMETER] = ",".join( self.requested_properties) - result = self.make_cloud_request('POST', url, content) + result = self.make_cloud_request('POST', self._data_url(), content) if len(self.requested_properties) > 0: self.report_properties_not_covered(result) @@ -771,6 +804,152 @@ def process_internal(self, flowdata): return + def _data_url(self): + + """! + The address of the JSON call. A resource key names the route. A + licence key alone has no resource key to put there, so it uses the + data endpoint that takes none and travels in the body with the list + of properties wanted. + """ + + if self.resource_key != "": + return self.baseURL + self.resource_key + ".json?" + return self.baseURL + Constants.LICENSE_DATA_PATH + + def human_confidence_page_values(self): + + """! + The values a page that asks for Human Confidence is given, each by + the name the page sends it under. The page sends the challenge to + the cloud service when it asks for Human Confidence, and sends the + page value back with the sealed value, so the engine redeems the + sealed value with the challenge it kept for that page. Each call + gives a new challenge, used once. + + See "The challenge" in the Human Confidence page of the + specification. + + @rtype: dict + @return: the values, by name + """ + + page, challenge = self._challenges.issue() + return {HumanConfidenceNames.CHALLENGE_PARAMETER: challenge, + HumanConfidenceNames.PAGE_PARAMETER: page} + + @staticmethod + def _evidence_value(flowdata, key): + + """! + The text of the evidence under key, in any letter case, whether an + element accepted it or not, or None where there is none. + """ + + evidence = flowdata.evidence + unaccepted = getattr(evidence, "get_unaccepted", dict)() + for source in (evidence.get_all(), unaccepted): + for name, value in source.items(): + if str(name).lower() == key and value is not None: + return str(value) + return None + + def sealed_human_confidence(self, flowdata): + + """! + The sealed Human Confidence value a request carries, being the + evidence query.humanconfidence where it is not empty, or None. + + @type flowdata: FlowData + @param flowdata: the FlowData being processed + @rtype: str + @return: the sealed value, or None + """ + + value = self._evidence_value( + flowdata, HumanConfidenceNames.SEALED_EVIDENCE) + return value if value else None + + def _process_sealed(self, flowdata, sealed): + + """! + Process a request that carries a sealed Human Confidence value. The + sealed value is redeemed through the JSON call, with the challenge + kept for the page and the License Key, and the answer gives + HumanConfidence as the level it redeemed for and + HumanConfidenceSource as Active. A sealed value that is not + redeemed gives Low and Active. An error of the call is still raised, + after the data is set, so the pipeline records it as it records + any other. + + See "Redeeming through the JSON call" in the Human Confidence page + of the specification. + """ + + challenge = self._challenges.take(self._evidence_value( + flowdata, HumanConfidenceNames.PAGE_EVIDENCE)) + redeem = challenge is not None and self.license_key != "" + hidden = (sealed, challenge, self.license_key) + + result = None + try: + self._complete_discovery() + + # The challenge sent is only ever the one kept, so every other + # is left out. The sealed value is sent exactly as it arrived, + # and only where the engine can redeem it. + left_out = (HumanConfidenceNames.CHALLENGE_PARAMETER, + HumanConfidenceNames.SEALED_PARAMETER) + content = self.get_content( + flowdata, left_out=left_out, hidden=hidden) + if redeem: + content[HumanConfidenceNames.SEALED_PARAMETER] = sealed + content[HumanConfidenceNames.CHALLENGE_PARAMETER] = challenge + content.update(self.get_credentials()) + names = list(self.requested_properties) + if (redeem and + HumanConfidenceNames.REQUESTED_PROPERTY not in names): + names.append(HumanConfidenceNames.REQUESTED_PROPERTY) + if len(names) > 0: + content[Constants.VALUES_PARAMETER] = ",".join(names) + + result = self.make_cloud_request( + 'POST', self._data_url(), content, hidden=hidden) + finally: + flowdata.set_element_data(AspectDataDictionary( + self, {"cloud": self._with_human_confidence( + result, redeem)})) + + @staticmethod + def _with_human_confidence(result, redeemed): + + """! + The JSON text of an answer with HumanConfidence set to the level + the sealed value redeemed for, or Low where it was not redeemed, + and HumanConfidenceSource set to Active. An answer that is missing + or cannot be read as a JSON object gives these two alone. + """ + + names = HumanConfidenceNames + try: + answer = json.loads(result) if result is not None else {} + except (JSONDecodeError, TypeError, ValueError): + answer = {} + if not isinstance(answer, dict): + answer = {} + section = answer.get(names.SECTION) + if not isinstance(section, dict): + section = {} + level = section.get(names.LEVEL) if redeemed else None + if level not in names.LEVELS: + level = names.NOT_REDEEMED + for member in (names.LEVEL, names.SOURCE): + section.pop(member + "nullreason", None) + section[names.LEVEL] = level + section[names.SOURCE] = names.ACTIVE + answer[names.SECTION] = section + return json.dumps(answer) + def process(self, flowdata): """! @@ -785,14 +964,20 @@ def process(self, flowdata): @param flowdata: the FlowData to process """ - result = super(CloudRequestEngine, self).process(flowdata) - - # FlowData keeps each element's data under its datakey in lower case. - data = flowdata.data.get(self.datakey.lower()) - if data is not None: - flowdata.data[Constants.RESPONSE_DATA_KEY] = data - - return result + try: + # A request that carries a sealed Human Confidence value is + # neither served from the cache nor stored in it, as the + # caching page of the specification says. + if self.sealed_human_confidence(flowdata) is not None: + return self.process_internal(flowdata) + return super(CloudRequestEngine, self).process(flowdata) + finally: + # FlowData keeps each element's data under its datakey in lower + # case. The data is given under cloud-response even when the + # request failed after setting it. + data = flowdata.data.get(self.datakey.lower()) + if data is not None: + flowdata.data[Constants.RESPONSE_DATA_KEY] = data def is_cacheable(self, data): @@ -876,7 +1061,7 @@ def report_properties_not_covered(self, result): else Constants.MESSAGE_PROPERTIES_NOT_KNOWN) warnings.warn(message.format(", ".join(not_covered))) - def get_content(self, flowData): + def get_content(self, flowData, left_out=(), hidden=()): """! Generate the Content to send in the POST request. One name under @@ -893,21 +1078,29 @@ def get_content(self, flowData): evidence is important to continued optimization. The reserved names and the web request view are left out. + The page value of Human Confidence is never sent, and the names in + left_out are not sent either, under any prefix and in any letter + case. Neither is warned about. + @param: flowData: FlowData + @param left_out: further names, in lower case, not to send + @param hidden: values no warning may hold, as masked says @return: Evidence Dictionary """ queryData = {} + left_out = (HumanConfidenceNames.PAGE_PARAMETER,) + tuple(left_out) evidence = self.sendable_evidence(flowData.evidence) - # Add the other evidence lowest precedence first. - self.add_query_data(queryData, evidence, self.get_selected_evidence(evidence, Constants.EVIDENCE_OTHER)) - # Add cookie evidence. - self.add_query_data(queryData, evidence, self.get_selected_evidence(evidence, Constants.EVIDENCE_COOKIE_PREFIX)) - # Add header evidence. - self.add_query_data(queryData, evidence, self.get_selected_evidence(evidence, Constants.EVIDENCE_HTTPHEADER_PREFIX)) - # Add query evidence. - self.add_query_data(queryData, evidence, self.get_selected_evidence(evidence, Constants.EVIDENCE_QUERY_PREFIX)) + # Lowest precedence first: other, cookie, header, then query. + for prefix in (Constants.EVIDENCE_OTHER, + Constants.EVIDENCE_COOKIE_PREFIX, + Constants.EVIDENCE_HTTPHEADER_PREFIX, + Constants.EVIDENCE_QUERY_PREFIX): + self.add_query_data( + queryData, evidence, + self.get_selected_evidence(evidence, prefix), + left_out=left_out, hidden=hidden) return queryData def sendable_evidence(self, evidence): @@ -932,7 +1125,8 @@ def sendable_evidence(self, evidence): sendable[key] = value return sendable - def add_query_data(self, query_data, all_evidence, evidence): + def add_query_data(self, query_data, all_evidence, evidence, + left_out=(), hidden=()): """! Add query data to the evidence. @@ -941,7 +1135,9 @@ def add_query_data(self, query_data, all_evidence, evidence): @param all_evidence: All evidence in the flow data. This is used to report which evidence keys are conflicting. @param evidence: Evidence to add to the query Data. - """ + @param left_out: names, in lower case, not to send, with no warning + @param hidden: values no warning may hold, as masked says + """ for evidenceKey, evidenceValue in evidence.items(): @@ -954,6 +1150,9 @@ def add_query_data(self, query_data, all_evidence, evidence): suffix = evidenceKey prefix = prefix.lower() + if suffix.lower() in left_out: + continue + # The service reads its credentials and the list of requested # properties from these names, so evidence carrying one of them # would sit beside the engine's own values with no way to know @@ -994,7 +1193,9 @@ def add_query_data(self, query_data, all_evidence, evidence): for key, value in conflicts.items()) if conflictStr: - warnings.warn(warningMessage + conflictStr) + warnings.warn(self.masked( + warningMessage + conflictStr, hidden) + if hidden else warningMessage + conflictStr) # Overwrite the existing queryParameter value. del query_data[existing] diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py index 439741e4..b3f60276 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py @@ -142,6 +142,9 @@ class Constants: # licence key alone. LICENSE_DATA_PATH = "json" + # What a value that no error or warning may hold is shown as. + HIDDEN_VALUE = "********" + # Logged when evidence is left out of a request because its key is one # the service reads its credentials or requested properties from. The # value is not included, as it may be a credential. diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py new file mode 100644 index 00000000..1cd04274 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py @@ -0,0 +1,160 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""! +Redeeming a sealed Human Confidence level, as the Human Confidence page of +the specification sets out: +https://github.com/51Degrees/specifications/blob/main/pipeline-specification/features/human-confidence.md + +The names the page and the cloud service use are kept together here, in +HumanConfidenceNames, so each is stated once. +""" + +import secrets +import threading +import time +from collections import OrderedDict + + +class HumanConfidenceNames: + + """! + The names used to redeem a sealed Human Confidence level. + """ + + # The evidence that carries the sealed value, and the name the cloud + # service reads it under in the JSON call. + SEALED_EVIDENCE = "query.humanconfidence" + SEALED_PARAMETER = "humanconfidence" + + # The name the challenge is sent under, to the cloud service by the + # page and by the engine. It is the name a sealed 51Did creator context + # result uses. + CHALLENGE_PARAMETER = "challenge" + + # The name the page sends its page value under, with the sealed value, + # so the engine can find the challenge it kept for that page. The + # engine never sends it to the cloud service. + PAGE_PARAMETER = "humanconfidencepage" + PAGE_EVIDENCE = "query." + PAGE_PARAMETER + + # The requested property the JSON call names on a request that carries + # a sealed value, as the engine writes property names. + REQUESTED_PROPERTY = "derived.humanconfidence" + + # The section and members of the answer that hold the two properties. + SECTION = "derived" + LEVEL = "humanconfidence" + SOURCE = "humanconfidencesource" + + # The levels a sealed value redeems for, the source of a sealed level, + # and the level given when the sealed value is not redeemed. + LEVELS = ("High", "Medium", "Low") + ACTIVE = "Active" + NOT_REDEEMED = "Low" + + +class HumanConfidenceChallenges: + + """! + The challenges the engine has given to pages and not yet used. Each + page gets a new challenge, kept here on the server under a page value, + and the challenge is used once, when the sealed value the page sends + back is redeemed. A challenge that is not used within lifetime_seconds + is dropped. + + One instance serves one process. Where several servers answer the same + site, give each engine an object with the same issue and take methods + that keeps the challenges where every server can reach them. + """ + + # Long enough for the browser tests to run and the page to send the + # sealed value back, which takes a few seconds. + DEFAULT_LIFETIME_SECONDS = 60 + + # The most challenges kept at once. The oldest is dropped first. + DEFAULT_CAPACITY = 100000 + + def __init__(self, lifetime_seconds=DEFAULT_LIFETIME_SECONDS, + capacity=DEFAULT_CAPACITY, clock=time.monotonic): + + """! + @type lifetime_seconds: float + @param lifetime_seconds: how long a challenge is kept + @type capacity: int + @param capacity: the most challenges kept at once + @type clock: callable + @param clock: gives the time in seconds, for tests + """ + + self._lifetime = lifetime_seconds + self._capacity = capacity + self._clock = clock + self._lock = threading.Lock() + # Page value to (challenge, time issued), oldest first. + self._kept = OrderedDict() + + def issue(self): + + """! + A new page value and challenge for one page, keeping the challenge. + + @rtype: tuple + @return: the page value and the challenge + """ + + page = secrets.token_hex(16) + challenge = secrets.token_hex(16) + now = self._clock() + with self._lock: + self._drop_expired(now) + while len(self._kept) >= self._capacity: + self._kept.popitem(last=False) + self._kept[page] = (challenge, now) + return page, challenge + + def take(self, page): + + """! + The challenge kept for a page value, which is then no longer kept, + or None where there is none or it has been kept too long. + + @type page: str + @param page: the page value the page sent back + @rtype: str + @return: the challenge, or None + """ + + if not isinstance(page, str) or page == "": + return None + now = self._clock() + with self._lock: + self._drop_expired(now) + kept = self._kept.pop(page, None) + return None if kept is None else kept[0] + + def _drop_expired(self, now): + while self._kept: + page, (_, issued) = next(iter(self._kept.items())) + if now - issued < self._lifetime: + break + del self._kept[page] diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/conftest.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/conftest.py index 0ecb4c70..562c34c4 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/conftest.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/conftest.py @@ -29,11 +29,17 @@ import pytest TEST_CLOUDENGINE = Path(__file__).resolve().parent / "test_cloudengine.py" +TEST_HUMAN_CONFIDENCE_LIVE = ( + Path(__file__).resolve().parent / "test_human_confidence_live.py") -# CloudEngineTests needs a resource key for each of its tests, in setUp. +# CloudEngineTests needs a resource key for each of its tests, in setUp, +# and so does every test of the live Human Confidence file. def _is_live(item): - return (Path(item.path).resolve() == TEST_CLOUDENGINE and + path = Path(item.path).resolve() + if path == TEST_HUMAN_CONFIDENCE_LIVE: + return True + return (path == TEST_CLOUDENGINE and getattr(item, "cls", None) is not None and item.cls.__name__ == "CloudEngineTests") diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py new file mode 100644 index 00000000..30538a39 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py @@ -0,0 +1,482 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The Cloud Request Engine redeems a sealed Human Confidence value through +its JSON call, and a consumer reads HumanConfidence and +HumanConfidenceSource, as the Human Confidence page of the specification +says. Each test below follows one item of that page's "Required tests". +""" + +import json +import warnings + +import requests + +from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ + CloudRequestEngine +from fiftyone_pipeline_cloudrequestengine.cloudengine import CloudEngine +from fiftyone_pipeline_cloudrequestengine.humanconfidence import \ + HumanConfidenceChallenges +from fiftyone_pipeline_core.logger import Logger +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder +from fiftyone_pipeline_engines.aspectdata_dictionary import \ + AspectDataDictionary +from fiftyone_pipeline_engines.basic_dictionary_cache import \ + BasicDictionaryCache + +from .classes.cloudrequestengine_testbase import CloudRequestEngineTestsBase +from .classes.mockrequestclient import MockRequestClient + +SEALED = "sealed-0f3a9c27d4b8e615a2c7" +LICENSE_KEY = "license-key-8d2e61b7c3f9" +OTHER_CHALLENGE = "challenge-from-the-request-5b1d" + + +class Answer: + """What the stand-in cloud service answers the JSON call with: a + status and text, or an error it raises.""" + + def __init__(self, text=None, status=200, raises=None): + self.text = text + self.status = status + self.raises = raises + + +def level_answer(level): + """A JSON call answer whose derived section holds the level given.""" + + return Answer(json.dumps({"derived": {"humanconfidence": level}})) + + +class StandInCloud(MockRequestClient): + """Answers discovery as the mock client does, and the JSON call with + the Answer given. Keeps the content of every JSON call.""" + + def __init__(self, answer, discovery_fails=False): + super(StandInCloud, self).__init__() + self.answer = answer + self.discovery_fails = discovery_fails + self.json_calls = [] + + def request(self, type, url, content, originHeader): + discovery = ("accessibleProperties" in url + or "evidencekeys" in url) + if discovery and self.discovery_fails: + raise requests.ConnectionError("discovery failed") + response = super(StandInCloud, self).request( + type, url, content, originHeader) + if discovery: + return response + self.json_calls.append(dict(content or {})) + if self.answer.raises is not None: + raise self.answer.raises + response.status_code = self.answer.status + response.text = self.answer.text + response.content = (self.answer.text or "").encode("utf-8") + response.url = url + response.headers = {} + return response + + +class ListLogger(Logger): + """Keeps every message the pipeline logs.""" + + def __init__(self): + super(ListLogger, self).__init__(min_level="debug") + self.messages = [] + + def log_internal(self, level, log): + self.messages.append(str(log)) + + +def derived_engine(): + """The cloud engine that reads the derived section of the answer, + where HumanConfidence and HumanConfidenceSource are.""" + + engine = CloudEngine() + engine.datakey = "derived" + return engine + + +class TestHumanConfidence(CloudRequestEngineTestsBase): + + def build(self, answer, license_key=LICENSE_KEY, discovery_fails=False, + cache=None, challenges=None, suppress=True): + """A pipeline of a Cloud Request Engine and a cloud engine for derived, + with the stand-in cloud answering the JSON call.""" + + self.cloud = StandInCloud(answer, discovery_fails) + settings = {"resource_key": "resource_key", + "http_client": self.cloud} + if license_key: + settings["license_key"] = license_key + if challenges is not None: + settings["human_confidence_challenges"] = challenges + with warnings.catch_warnings(record=True) as self.build_warnings: + warnings.simplefilter("always") + self.engine = CloudRequestEngine(settings) + if cache is not None: + self.engine.set_cache(cache) + self.logger = ListLogger() + self.pipeline = PipelineBuilder({ + "add_javascript_builder": False, + "use_setheader_properties": False, + "suppress_process_exceptions": suppress}).add( + self.engine).add(derived_engine()).add_logger( + self.logger).build() + self.addCleanup(self.pipeline.close) + return self.engine + + def page(self): + """The values a page is given, as the engine gives them.""" + + return self.engine.human_confidence_page_values() + + def process(self, sealed=SEALED, page=None, evidence=None): + """One request that carries the sealed value and the page value + given. Gives the FlowData and the warnings it gave.""" + + if page is None: + page = self.page()["humanconfidencepage"] + data = self.pipeline.create_flowdata() + data.evidence.add("header.user-agent", "Mozilla/5.0") + if sealed is not None: + data.evidence.add("query.humanconfidence", sealed) + if page: + data.evidence.add("query.humanconfidencepage", page) + for key, value in (evidence or {}).items(): + data.evidence.add(key, value) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + data.process() + self.process_warnings = caught + return data + + def read(self, data): + """HumanConfidence and HumanConfidenceSource, as a consumer reads + them.""" + + derived = data.get("derived") + return (derived.get("humanconfidence").value(), + derived.get("humanconfidencesource").value()) + + def assert_low_and_active(self, data, errors=("cloud",)): + self.assertEqual(("Low", "Active"), self.read(data)) + # The read adds no error of its own. An error of the call is the + # Cloud Request Engine's, and only that. + self.assertTrue(set(data.errors) <= set(errors), data.errors) + answer = json.loads(data.get("cloud-response").get("cloud")) + self.assertEqual("Low", answer["derived"]["humanconfidence"]) + self.assertEqual("Active", answer["derived"]["humanconfidencesource"]) + + # A sealed value that redeems gives the level in the response as + # HumanConfidence, with HumanConfidenceSource Active. + + def test_a_sealed_value_that_redeems_gives_its_level_and_active(self): + for level in ("High", "Medium", "Low"): + with self.subTest(level=level): + self.build(level_answer(level)) + data = self.process() + self.assertEqual((level, "Active"), self.read(data)) + self.assertEqual({}, data.errors) + + def test_the_call_sends_the_sealed_value_challenge_and_license_key(self): + self.build(level_answer("High")) + page = self.page() + self.process(page=page["humanconfidencepage"]) + self.assertEqual(1, len(self.cloud.json_calls)) + sent = self.cloud.json_calls[0] + self.assertEqual(SEALED, sent["humanconfidence"]) + self.assertEqual(page["challenge"], sent["challenge"]) + self.assertEqual(LICENSE_KEY, sent["license"]) + self.assertIn("derived.humanconfidence", sent["values"].split(",")) + self.assertNotIn("humanconfidencepage", + [name.lower() for name in sent]) + + def test_a_source_in_the_answer_does_not_change_active(self): + self.build(Answer(json.dumps({"derived": { + "humanconfidence": "Medium", + "humanconfidencesource": "Passive"}}))) + self.assertEqual(("Medium", "Active"), self.read(self.process())) + + # Each case where the sealed value is not redeemed gives Low and + # Active, and the read adds no error of its own. + + def test_no_license_key_gives_low_and_active(self): + self.build(level_answer("High"), license_key=None) + data = self.process() + self.assert_low_and_active(data) + sent = self.cloud.json_calls[0] + self.assertNotIn("humanconfidence", sent) + self.assertNotIn("challenge", sent) + + def test_no_request_for_the_flow_data_gives_low_and_active(self): + self.build(level_answer("High"), discovery_fails=True) + data = self.process() + self.assertEqual([], self.cloud.json_calls) + # Without the evidence keys the pipeline cannot filter the + # evidence either, which it records as its own "global" error. + self.assert_low_and_active(data, errors=("cloud", "global")) + self.assertIn("cloud", data.errors) + + def test_a_failed_call_gives_low_and_active(self): + answers = { + "status 500": Answer(json.dumps({"errors": ["failed"]}), 500), + "status 400": Answer(json.dumps({"errors": ["refused"]}), 400), + "not JSON": Answer("Bad gateway", 502), + "connection": Answer(raises=requests.ConnectionError("down")), + "timeout": Answer(raises=requests.Timeout("timed out")), + } + for case, answer in answers.items(): + with self.subTest(case=case): + self.build(answer) + data = self.process() + self.assert_low_and_active(data) + self.assertIn("cloud", data.errors) + + def test_a_failed_call_is_still_raised_without_suppression(self): + self.build(Answer(raises=requests.Timeout("timed out")), + suppress=False) + with self.assertRaises(requests.Timeout): + self.process() + + def test_an_answer_without_a_level_gives_low_and_active(self): + answers = { + "no derived": {"device": {"ismobile": True}}, + "no humanconfidence": {"derived": {"other": "x"}}, + "null": {"derived": {"humanconfidence": None, + "humanconfidencenullreason": "none"}}, + "Unknown": {"derived": {"humanconfidence": "Unknown"}}, + "other word": {"derived": {"humanconfidence": "Maybe"}}, + "lower case": {"derived": {"humanconfidence": "high"}}, + "a number": {"derived": {"humanconfidence": 1}}, + "derived not an object": {"derived": "High"}, + } + for case, answer in answers.items(): + with self.subTest(case=case): + self.build(Answer(json.dumps(answer))) + self.assert_low_and_active(self.process()) + + def test_a_page_without_a_kept_challenge_gives_low_and_active(self): + cases = {"no page value": "", + "a page value never given": "0" * 32} + for case, page in cases.items(): + with self.subTest(case=case): + self.build(level_answer("High")) + data = self.process(page=page) + self.assert_low_and_active(data) + self.assertNotIn("humanconfidence", self.cloud.json_calls[0]) + + def test_a_challenge_redeems_once(self): + self.build(level_answer("High")) + page = self.page()["humanconfidencepage"] + self.assertEqual(("High", "Active"), + self.read(self.process(page=page))) + self.assert_low_and_active(self.process(page=page)) + + def test_a_challenge_kept_too_long_gives_low_and_active(self): + now = [1000.0] + challenges = HumanConfidenceChallenges( + lifetime_seconds=60, clock=lambda: now[0]) + self.build(level_answer("High"), challenges=challenges) + page = self.page()["humanconfidencepage"] + now[0] += 60 + self.assert_low_and_active(self.process(page=page)) + + # Two reads of HumanConfidence for one request make one request to the + # remote server. + + def test_two_reads_make_one_request(self): + self.build(level_answer("Medium")) + data = self.process() + first = self.read(data) + second = self.read(data) + self.assertEqual(first, second) + self.assertEqual(("Medium", "Active"), first) + self.assertEqual(1, len(self.cloud.json_calls)) + + # A request that carries a sealed value is neither stored in nor served + # from a cache. + + def test_a_sealed_request_is_not_stored_in_a_cache(self): + cache = BasicDictionaryCache() + self.build(level_answer("High"), cache=cache) + page = self.page()["humanconfidencepage"] + self.process(page=page) + self.process(page=page) + self.assertEqual(2, len(self.cloud.json_calls)) + self.assertEqual({}, dict(cache.cache)) + + def test_a_sealed_request_is_not_served_from_a_cache(self): + class AlwaysHit(BasicDictionaryCache): + entry = None + + def get_cache_value(self, key): + return self.entry + + cache = AlwaysHit() + self.build(level_answer("Medium"), cache=cache) + cache.entry = AspectDataDictionary(self.engine, {"cloud": json.dumps( + {"derived": {"humanconfidence": "High", + "humanconfidencesource": "Active"}})}) + data = self.process() + self.assertEqual(("Medium", "Active"), self.read(data)) + self.assertEqual(1, len(self.cloud.json_calls)) + + def test_a_request_without_a_sealed_value_still_uses_the_cache(self): + cache = BasicDictionaryCache() + self.build(Answer(json.dumps({"device": {"ismobile": True}})), + cache=cache) + self.process(sealed=None, page="") + self.process(sealed=None, page="") + self.assertEqual(1, len(self.cloud.json_calls)) + + # The call holds one challenge, being the one the package kept, where + # the request's evidence also holds one. + + def test_the_call_holds_only_the_challenge_kept(self): + self.build(level_answer("High")) + page = self.page() + self.process(page=page["humanconfidencepage"], evidence={ + "query.challenge": OTHER_CHALLENGE, + "header.Challenge": OTHER_CHALLENGE, + "cookie.CHALLENGE": OTHER_CHALLENGE, + "server.challenge": OTHER_CHALLENGE}) + sent = self.cloud.json_calls[0] + names = [name for name in sent if name.lower() == "challenge"] + self.assertEqual(["challenge"], names) + self.assertEqual(page["challenge"], sent["challenge"]) + self.assertNotIn(OTHER_CHALLENGE, json.dumps(sent)) + + def test_a_challenge_in_the_request_alone_is_not_sent(self): + self.build(level_answer("High")) + self.process(page="", evidence={"query.challenge": OTHER_CHALLENGE}) + self.assertNotIn("challenge", self.cloud.json_calls[0]) + + def test_the_sealed_value_sent_is_the_query_one_exactly(self): + self.build(level_answer("High")) + self.process(evidence={"header.HumanConfidence": "another"}) + sent = self.cloud.json_calls[0] + self.assertEqual( + ["humanconfidence"], + [name for name in sent if name.lower() == "humanconfidence"]) + self.assertEqual(SEALED, sent["humanconfidence"]) + + # No log entry and no error message holds the sealed value, the + # License Key, or the challenge. + + def assert_holds_none(self, texts, values): + for text in texts: + for value in values: + self.assertNotIn(value, text) + + def messages_of(self, data): + texts = list(self.logger.messages) + texts += [str(w.message) for w in self.process_warnings] + for error in data.errors.values(): + texts.append(str(error.exception_instance)) + texts.append(error.exception_traceback) + for inner in getattr(error.exception_instance, + "exceptions", ()) or (): + texts.append(str(inner)) + return texts + + def test_no_message_holds_the_sealed_value_key_or_challenge(self): + page = {} + + def echo(): + # The answer names every value the call sent. + return json.dumps({ + "errors": ["{} {} {}".format( + SEALED, LICENSE_KEY, page["challenge"])], + "warnings": ["{} {} {}".format( + SEALED, LICENSE_KEY, page["challenge"])]}) + + cases = { + "errors and warnings": lambda: Answer(echo(), 400), + "not JSON": lambda: Answer( + "

{} {} {}

".format( + SEALED, LICENSE_KEY, page["challenge"]), 502), + "connection": lambda: Answer(raises=requests.ConnectionError( + "{} {} {}".format(SEALED, LICENSE_KEY, page["challenge"]))), + } + for case, answer in cases.items(): + with self.subTest(case=case): + self.build(Answer()) + page.update(self.page()) + self.cloud.answer = answer() + data = self.process(page=page["humanconfidencepage"]) + texts = self.messages_of(data) + self.assertTrue(texts) + self.assert_holds_none( + texts, (SEALED, LICENSE_KEY, page["challenge"])) + self.assert_low_and_active(data) + + def test_no_conflict_warning_holds_the_sealed_value(self): + self.build(level_answer("High")) + self.process(evidence={ + "cookie.humanconfidencex": SEALED, + "header.humanconfidencex": SEALED}) + texts = [str(w.message) for w in self.process_warnings] + self.assertTrue(texts) + self.assert_holds_none(texts, (SEALED,)) + + # The consumer never handles the challenge. + + def test_the_sealed_value_is_not_in_any_element_data(self): + self.build(level_answer("High")) + page = self.page() + data = self.process(page=page["humanconfidencepage"]) + for key in ("cloud-response", "derived"): + text = json.dumps(data.get(key).as_dictionary(), default=str) + for value in (SEALED, page["challenge"], LICENSE_KEY): + self.assertNotIn(value, text) + + +class TestHumanConfidenceChallenges(CloudRequestEngineTestsBase): + + def test_each_page_gets_a_new_challenge(self): + challenges = HumanConfidenceChallenges() + issued = [challenges.issue() for _ in range(100)] + self.assertEqual(100, len({page for page, _ in issued})) + self.assertEqual(100, len({challenge for _, challenge in issued})) + + def test_a_challenge_is_taken_once(self): + challenges = HumanConfidenceChallenges() + page, challenge = challenges.issue() + self.assertEqual(challenge, challenges.take(page)) + self.assertIsNone(challenges.take(page)) + + def test_the_oldest_challenge_goes_when_full(self): + challenges = HumanConfidenceChallenges(capacity=2) + first, _ = challenges.issue() + second, kept = challenges.issue() + challenges.issue() + self.assertIsNone(challenges.take(first)) + self.assertEqual(kept, challenges.take(second)) + + def test_a_page_value_that_is_not_text_has_no_challenge(self): + challenges = HumanConfidenceChallenges() + challenges.issue() + for page in (None, "", 5): + self.assertIsNone(challenges.take(page)) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence_live.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence_live.py new file mode 100644 index 00000000..e11fd68b --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence_live.py @@ -0,0 +1,106 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Human Confidence against the cloud service that _51DEGREES_CLOUD_ENDPOINT +names, or the public cloud where it is not set. The tests need a Resource +Key that carries HumanConfidence, and a License Key of the same account, +and skip where either is not set. + +A sealed value is made only by the browser tests in a page, so these tests +send one that does not redeem and check it gives Low and Active, through +the same JSON call a sealed value that redeems goes through. +""" + +import unittest +import warnings + +from fiftyone_pipeline_cloudrequestengine.cloudengine import CloudEngine +from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ + CloudRequestEngine +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder + +from .live_cloud import find_resource_key, no_resource_key, read_environment + +RESOURCE_KEY = find_resource_key() +LICENSE_KEY_NAME = "_51DEGREES_LICENSE_KEY_BESPOKE" +LICENSE_KEY = read_environment(LICENSE_KEY_NAME) or "" + +USER_AGENT = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36") + +LEVELS = ("High", "Medium", "Low") +SOURCES = ("Active", "Passive") + + +@unittest.skipUnless(RESOURCE_KEY, no_resource_key( + "the derived product", "HumanConfidence", several=True)) +@unittest.skipUnless( + LICENSE_KEY != "", + f"{LICENSE_KEY_NAME} is not set. Set it to a License Key of the account " + "that holds the Resource Key to run the live Human Confidence tests.") +class HumanConfidenceLiveTests(unittest.TestCase): + + def setUp(self): + self.engine = CloudRequestEngine({ + "resource_key": RESOURCE_KEY, + "license_key": LICENSE_KEY, + "timeout_seconds": 10}) + derived = CloudEngine() + derived.datakey = "derived" + self.pipeline = PipelineBuilder({ + "suppress_process_exceptions": True}).add( + self.engine).add(derived).build() + self.addCleanup(self.pipeline.close) + + def process(self, evidence): + data = self.pipeline.create_flowdata() + data.evidence.add("header.user-agent", USER_AGENT) + for key, value in evidence.items(): + data.evidence.add(key, value) + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + data.process() + derived = data.get("derived") + return (data, + derived.get("humanconfidence").value(), + derived.get("humanconfidencesource").value()) + + def test_a_request_without_a_sealed_value_gives_a_passive_level(self): + data, level, source = self.process({}) + self.assertEqual({}, data.errors) + self.assertIn(level, LEVELS) + self.assertEqual("Passive", source) + + def test_a_sealed_value_that_does_not_redeem_gives_low_and_active(self): + page = self.engine.human_confidence_page_values() + data, level, source = self.process({ + "query.humanconfidence": "a-value-the-cloud-did-not-seal", + "query.humanconfidencepage": page["humanconfidencepage"]}) + self.assertIn(level, LEVELS) + self.assertIn(source, SOURCES) + self.assertEqual(("Low", "Active"), (level, source)) + for error in data.errors.values(): + text = str(error.exception_instance) + self.assertNotIn(LICENSE_KEY, text) + self.assertNotIn(page["challenge"], text)