From 79dba9b298e873eae7a72ccd7a80ab703eef60f8 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Mon, 23 Nov 2026 15:03:44 +0000 Subject: [PATCH 1/7] FEAT: Human Confidence web example in client side and server side modes The page shows HumanConfidenceSource and HumanConfidence in a table whose rows are in place from the start, each with a running timer until its level arrives, so nothing on the page moves. Client side, the browser loads the 51Degrees client script from the cloud and this server redeems the sealed result with the License Key. There is no passive row client side, because a passive result passed on by the browser could have been changed. Server side, the browser never calls the cloud. This server serves the client script with every cloud address pointed at itself and sends the calls on through the cloud request engine. The passive row comes from the visitor's request. A toggle reloads the page in the other mode, and the choice is kept in a cookie. Under the table are two curl commands that replay the passive data and the active data from a terminal, and a link to the Configurator. The third party cookie check in the client script is pointed at the cloud named in _51DEGREES_CLOUD_ENDPOINT, as it otherwise goes to the public cloud. --- .../cloud/humanconfidence_web/app.py | 295 ++++++++++++--- .../humanconfidence_web/templates/index.html | 348 ++++++++++++------ 2 files changed, 473 insertions(+), 170 deletions(-) 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 97f13c1d..e2e361d8 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 @@ -29,22 +29,27 @@ # then open http://localhost:5151/ # # Human Confidence says how likely it is that a person is looking at the -# page. It comes in two ways, and this demo shows both. +# page, as High, Medium or Low. The page shows it two ways. # -# 1. Passive. This server asks the cloud itself, sending the visitor's -# request headers and IP address. HumanConfidenceSource is Passive and -# HumanConfidence is a plain level. -# The server asks for it rather than reading it from the page, because -# a level a browser sends can be forged. -# 2. Active. The page loads the 51Degrees client script, which runs the -# browser tests and sends the answers to the cloud. When the script -# completes, HumanConfidenceSource is Active and HumanConfidence holds -# a sealed value the browser can't read or change. -# 3. Redeem. The page hands the sealed value to this server, which calls -# hc/redeem with it and the account's License Key, and gets the true -# level back. A sealed value redeems once, within ten seconds. This -# server is the only party holding the License Key, which the browser -# never sees. +# 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. +# +# The page works in two modes, chosen with ?mode=client or ?mode=server +# and kept in a cookie. +# +# - Client side. The browser loads the client script from the cloud and +# the sealed value comes back to the page through fod.onChange. +# - Server side. The browser never calls the cloud. The page loads the +# client script from this server, with every cloud address in it pointed +# here, and this server sends each call on through the cloud request +# engine. +# +# Under the results the page gives two curl commands that replay the +# passive call and the browser test answers from a terminal. # # This example is available in full on [GitHub](https://github.com/51Degrees/51degrees-python/blob/main/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py). # @@ -56,20 +61,24 @@ # segment, defaults to https://cloud.51degrees.com/api/v4/ # - _51DEGREES_EXAMPLE_HTTP_PORTS, the port to listen on, defaults to 5151 # -# See readme.md beside this file for the steps and what to expect. -# # Required PyPI dependencies: # - [flask](https://pypi.org/project/flask/) # - [requests](https://pypi.org/project/requests/) import ipaddress +import json import os +import re import sys import urllib.parse import requests -from flask import Flask, Response, jsonify, make_response, render_template -from flask import request +from flask import Flask, Response, abort, jsonify, make_response +from flask import render_template, request + +from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ + CloudRequestEngine +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_pipeline_examples.example_utils import ExampleUtils @@ -81,6 +90,28 @@ # A short limit, in seconds, so a slow cloud can't hang the demo. TIMEOUT = 10 +# The two modes, the default first, and the cookie that keeps the choice. +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") + +# Cloud addresses in the client script. In server mode each one is pointed +# at this server. +CLOUD_URL = re.compile( + r"https://(cloud[a-z0-9-]*\.51degrees\.com)/([^\"'\s\\)]*)") +CLOUD_HOST = re.compile(r"cloud[a-z0-9-]*\.51degrees\.com") + +# Headers the cloud lists that are never sent on as HTTP headers, because +# they belong to this server's own connection to the cloud. +NOT_FORWARDED = {"host", "protocol", "client-ip", "content-length", + "content-type", "connection", "cookie"} + +# The prefix, in lower case, of the cookies the client script and the cloud +# set. +COOKIE_PREFIX = "51d" + # Where to go next. The page ends with these links, and the example prints # them when it stops before the page is served. FIND_OUT_MORE = [ @@ -148,7 +179,8 @@ def create_app(resource_key, license_key, api): """! Create the Flask application that serves the page, asks the cloud for - the passive level, and redeems the sealed active level. + the passive level, redeems the sealed active level, and in server mode + sends the browser's calls on to the cloud. """ # Serve the files in the static folder from the root, so the stylesheet @@ -171,11 +203,61 @@ def cloud_headers(): if key.lower().startswith("header.")}) return fetched[0] + def visitor_headers(): + names = cloud_headers() + return {name.lower(): value for name, value in request.headers.items() + if name.lower() in names} + + # The cloud request engine, which sends this server's requests for data + # to the cloud: the passive level, and in server mode the browser's + # test answers. The page's own script is served by this server, so the + # pipeline needs no JavaScript of its own. + pipeline = PipelineBuilder({"add_javascript_builder": False}).add( + CloudRequestEngine({"resource_key": resource_key, + "cloud_endpoint": api})).build() + + def ask_cloud(fields): + """The cloud's answer for the visitor's headers and IP address and + the form fields given, sent through the cloud request engine, with + what was sent described for the page's curl command.""" + evidence = {"header." + name: value + for name, value in visitor_headers().items()} + for name, value in fields: + if name.lower() not in ("resource", "values"): + evidence["query." + name] = value + # Behind a load balancer or CDN, use the visitor's address it + # passes on. Set last, so no header can replace it. + address = public_ip(request.remote_addr) + if address: + evidence["query.client-ip"] = address + flowdata = pipeline.create_flowdata() + for key, value in evidence.items(): + flowdata.evidence.add(key, value) + flowdata.process() + if flowdata.errors: + raise ValueError("; ".join( + str(error) for error in flowdata.errors.values())) + answer = flowdata.get("cloud").get("cloud") + if isinstance(answer, str): + answer = json.loads(answer) + sent = { + "method": "POST", + "url": api + resource_key + ".json", + "form": [[key.split(".", 1)[1], value] + for key, value in evidence.items()]} + return answer, sent + @app.route("/") def index(): + mode = request.args.get("mode") + if mode not in MODES: + mode = request.cookies.get(MODE_COOKIE) + if mode not in MODES: + mode = MODES[0] response = make_response(render_template( - "index.html", resource_key=resource_key, api=api)) + "index.html", resource_key=resource_key, api=api, mode=mode)) + response.set_cookie(MODE_COOKIE, mode, samesite="Lax") # The page must never come from a cache, as each load runs the # tests. response.headers["Cache-Control"] = "no-store" @@ -188,53 +270,140 @@ def index(): def passive(): try: - names = cloud_headers() - evidence = {} - for name, value in request.headers.items(): - if name.lower() in names: - evidence[name.lower()] = value - # Behind a load balancer or CDN, use the visitor's address it - # passes on. Set last, so no header can replace it. - if request.remote_addr: - evidence["client-ip"] = client_ip(request.remote_addr) - answer = requests.request( - "POST", api + resource_key + ".json", data=evidence, - timeout=TIMEOUT) - if answer.status_code >= 400: - return jsonify( - error=f"HTTP {answer.status_code}: {trim(answer.text)}") - derived = answer.json().get("derived") + answer, sent = ask_cloud([]) + derived = answer.get("derived") return jsonify( - source=read(derived, "humanconfidencesource"), - humanConfidence=read(derived, "humanconfidence")) - except (requests.RequestException, ValueError) as error: + humanConfidence=read(derived, "humanconfidence"), sent=sent) + except Exception as error: return jsonify(error=str(error)) - # Redeem: the page sends the sealed value, and this server redeems it - # with the License Key. The answer goes back to the page as the cloud - # gave it. + # 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 logged here, never sent back. @app.route("/redeem", methods=["POST"]) def redeem(): - fields = {"value": request.form.get("value", "")} + sealed = request.form.get("value", "") + fields = {"value": sealed} if license_key: fields["license"] = license_key + level, outcome = None, None try: answer = requests.request( "POST", api + "hc/redeem", data=fields, timeout=TIMEOUT) + body = answer.json() + level = read(body, "humanConfidence") + outcome = read(body, "result") or ( + "redeemed" if level else f"HTTP {answer.status_code}") + except (requests.RequestException, ValueError) as error: + outcome = type(error).__name__ + if level not in LEVELS: + level = LEVELS[-1] + print(f"redeem: {level} ({outcome})", flush=True) + return jsonify(humanConfidence=level) + + # Server mode: the client script, fetched from the cloud for this + # visitor, with every cloud address in it pointed at this server. + @app.route("/hc/script.js") + def script(): + + try: + query = {} + address = public_ip(request.remote_addr) + if address: + query["client-ip"] = address + answer = requests.request( + "GET", api + resource_key + ".js", params=query, + headers=passed_on(visitor_headers()), timeout=TIMEOUT) + except (requests.RequestException, ValueError) as error: + return Response( + "console.log(" + repr(str(error)) + ");", status=502, + content_type="application/javascript") + here = request.host_url + "hc/cloud/" + text = CLOUD_URL.sub( + lambda m: here + m.group(1) + "/" + m.group(2), answer.text) + response = Response( + text, status=answer.status_code, + content_type="application/javascript") + response.headers["Cache-Control"] = "no-store" + return response + + # Server mode: a call the client script makes to the cloud. The test + # answers (a POST) go through the cloud request engine. A GET is the + # third-party cookie check, sent on with the visitor's headers and only + # the cloud's own cookies. Only cloud hosts are reached. + @app.route("/hc/cloud//", methods=["GET", "POST"]) + def forward(host, path): + + if not CLOUD_HOST.fullmatch(host): + abort(404) + if request.method == "POST": + try: + answer, _ = ask_cloud(request.form.items(multi=True)) + except Exception as error: + return jsonify(error=str(error)), 502 + response = jsonify(answer) + response.headers["Cache-Control"] = "no-store" + return response + url = "https://" + host + "/" + path + headers = passed_on(visitor_headers()) + cookies = "; ".join( + f"{name}={value}" for name, value in request.cookies.items() + if name.lower().startswith(COOKIE_PREFIX)) + if cookies: + headers["Cookie"] = cookies + try: + answer = requests.request( + "GET", url, params=request.args, headers=headers, + timeout=TIMEOUT) except requests.RequestException as error: return jsonify(error=str(error)), 502 - if answer.status_code == 404: - return jsonify( - error=f"The service at {api} doesn't redeem Human " - "Confidence.") - return Response( - answer.text, status=answer.status_code, - content_type="application/json") + response = Response( + answer.content, status=answer.status_code, + content_type=answer.headers.get( + "Content-Type", "application/json")) + for cookie in set_cookies(answer): + response.headers.add("Set-Cookie", cookie) + response.headers["Cache-Control"] = "no-store" + return response return app +def passed_on(headers): + + """! + The visitor's headers to send as HTTP headers, without the ones that + belong to this server's own connection. + """ + + return {name: value for name, value in headers.items() + if name.lower() not in NOT_FORWARDED} + + +def set_cookies(answer): + + """! + The cloud's Set-Cookie headers, made to work on this server's own + address by dropping the domain, Secure and SameSite=None. + """ + + raw = getattr(answer, "raw", None) + values = [] + if raw is not None and hasattr(raw, "headers") and \ + hasattr(raw.headers, "getlist"): + values = raw.headers.getlist("Set-Cookie") + kept = [] + for value in values: + parts = [part.strip() for part in value.split(";")] + parts = [part for part in parts if part and not + part.lower().startswith("domain=") and + part.lower() not in ("secure", "samesite=none")] + kept.append("; ".join(parts)) + return kept + + def client_ip(address): """! @@ -249,6 +418,24 @@ def client_ip(address): return str(mapped) if mapped else address +def public_ip(address): + + """! + The visitor's address when it is a public one, otherwise None. A local + or private address means nothing to the cloud, which then reads this + server's own public address, the visitor's too when both are on one + network. + """ + + if not address: + return None + address = client_ip(address) + try: + return address if ipaddress.ip_address(address).is_global else None + except ValueError: + return None + + def read(parent, name): """! @@ -296,13 +483,13 @@ def main(argv): if not license_key.strip(): print(f"No {ExampleUtils.LICENSE_KEY_ENV_VAR} set. The page still " "shows Passive and Active, but an account that holds License " - "Keys can't redeem without one, so the redeemed level will be " - "unreadable.") + "Keys can't redeem without one, so Active will show Low.") app = create_app(resource_key, license_key, api) port = os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151) print(f"Human Confidence demo on http://localhost:{port}/, using {api}") - app.run(port=int(os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151))) + # Threaded, so the page's calls in server mode don't wait on each other. + app.run(port=int(port), threaded=True) if __name__ == "__main__": 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 a847b084..4defb8f3 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 @@ -21,69 +21,83 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* #} -{# Human Confidence demo page. - Served by app.py, which puts in the Resource Key and the cloud address, - and holds the License Key server side. Styling is the 51Degrees example - design system, vendored with this example as the 51Did demo vendors - it. #} +{# Human Confidence demo page. Served by app.py, which puts in the Resource + Key, the cloud address and the mode, and holds the License Key. #} Human Confidence demo +

Human Confidence demo

-

This page shows how likely it is that a - person is looking at it. The server asks the cloud first. Then your - browser runs the 51Degrees browser tests, and the server redeems the - sealed result. The License Key stays on the server.

+

How likely it is that a person is looking at + this page, passive from the request and active from the browser tests.

+ + + {% if mode == 'client' %} +

Client side. The browser loads + the 51Degrees script from the cloud and the result comes back to the page + through fod.onChange, then this server redeems it.

+ {% else %} +

Server side. This server reaches + the cloud through the 51Degrees cloud request engine and the browser never + calls the cloud, so JA4 and HTTP/2 signals are not available.

+ {% endif %} - - - + + - - - - + + + - - - - - - - - - + + +
StepSourceHuman ConfidenceHumanConfidenceSourceHumanConfidence
1. Passive, asked by the serverwaiting…waiting…
Passive
2. After the browser tests, in the pagerunning the tests…waiting…
3. Redeemed by the serverwaiting…waiting…
Active
-

- - -

+

Try it on your own site. Create a Resource Key in the 51Degrees Configurator.

-

+

Replay it from a terminal

+
+ + +
+
+
Replay the passive data +
Waiting for the request…
+ +
+
+
Replay the active data +
Waiting for the browser tests…
+ +

Find out more

    +
  • Configurator
  • Bots and humans
  • Resource keys
  • Pricing
  • @@ -98,106 +112,208 @@

    Find out more

    var RESOURCE = {{ resource_key|tojson }}; // The cloud API base ending in /api/v4/, as the server read it. var API = {{ api|tojson }}; + var MODE = {{ mode|tojson }}; + // This server's redeem route, which holds the License Key. + var REDEEM = location.origin + "/redeem"; + // Server side, the script's calls to the cloud go to + // /hc/cloud// here. + var FORWARD = /^https?:\/\/[^\/]+\/hc\/cloud\/([^\/]+)\/(.*)$/; + var LEVELS = ["High", "Medium", "Low"]; + var CLASSES = { High: "c-eg-status--pass", Medium: "c-eg-status--part", + Low: "c-eg-status--fail" }; - var PASS = "c-eg-status c-eg-status--pass"; - var FAIL = "c-eg-status c-eg-status--fail"; - var PART = "c-eg-status c-eg-status--part"; - var NONE = "c-eg-status c-eg-status--none"; + // Both rows show from the start, each with a running timer until its + // level arrives, so it is clear something is happening. + var started = Date.now(); + var shown = { passive: false, active: false }; + function tick() { + var seconds = ((Date.now() - started) / 1000).toFixed(1) + " s"; + ["passive", "active"].forEach(function (id) { + if (!shown[id]) { document.getElementById(id).textContent = seconds; } + }); + if (!shown.passive || !shown.active) { setTimeout(tick, 100); } + } + tick(); - function show(id, text, cls) { + // Shows a level, Low when there is none to show. + function show(id, level) { + if (LEVELS.indexOf(level) < 0) { level = "Low"; } + shown[id] = true; var element = document.getElementById(id); - element.textContent = text; - element.className = cls; + element.textContent = level; + element.className = "hc-level c-eg-status " + CLASSES[level]; } - function levelClass(level) { - return level === "High" ? PASS : level === "Low" ? FAIL - : level === "Medium" ? PART : NONE; + // Form encoding with every character a shell treats specially escaped, + // so one double quoted text works in PowerShell and bash. + function encode(text) { + return encodeURIComponent(text).replace(/[!'()*~]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); + } + function post(program, url, pairs) { + return program + " -s -X POST \"" + url + "\"" + pairs.map(function (p) { + return " --data \"" + encode(p[0]) + "=" + encode(p[1]) + "\""; + }).join(""); } + var PY = "python3 -c \"import sys,json;print(json.load(sys.stdin)"; + var SHELLS = { + ps: { + passive: function (url, pairs) { + return "\"Passive \" + (" + post("curl.exe", url, pairs) + + " | ConvertFrom-Json).derived.humanconfidence"; + }, + 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"; + } + }, + sh: { + passive: function (url, pairs) { + return "printf 'Passive '; " + post("curl", url, pairs) + " | " + + PY + "['derived']['humanconfidence'])\""; + }, + active: function (url, pairs) { + return "v=$(" + post("curl", url, pairs) + " | " + PY + + "['derived']['humanconfidence'])\"); printf 'Active '; " + + "curl -s -X POST \"" + REDEEM + "\" --data-urlencode \"value=$v\"" + + " | " + PY + "['humanConfidence'])\""; + } + } + }; + var shell = "ps"; + var commands = {}; + function render(name) { + var c = commands[name]; + if (!c) { return; } + document.getElementById("cmd-" + name).textContent = + SHELLS[shell][name](c.url, c.pairs); + } + function setCommand(name, url, pairs) { + commands[name] = { url: url, pairs: pairs }; + render(name); + } + function setShell(name) { + shell = name; + document.getElementById("shell-ps").className = + "b-btn" + (name === "ps" ? "" : " b-btn--secondary"); + document.getElementById("shell-sh").className = + "b-btn" + (name === "sh" ? "" : " b-btn--secondary"); + Object.keys(commands).forEach(render); + } + document.getElementById("shell-ps").onclick = function () { setShell("ps"); }; + document.getElementById("shell-sh").onclick = function () { setShell("sh"); }; + Array.prototype.forEach.call(document.querySelectorAll("[data-copy]"), + function (button) { + button.onclick = function () { + var text = document.getElementById(button.dataset.copy).textContent; + navigator.clipboard.writeText(text).then(function () { + button.textContent = "Copied"; + setTimeout(function () { button.textContent = "Copy"; }, 1500); + }); + }; + }); - var started = Date.now(); - function seconds() { - return ((Date.now() - started) / 1000).toFixed(1) + " s"; + // Passive, server side only. Client side has no passive result, so the + // passive row and its replay are removed and no passive call is made. + if (MODE === "client") { + shown.passive = true; + document.getElementById("row-passive").remove(); + document.getElementById("box-passive").remove(); + } else { + fetch("passive").then(function (r) { return r.json(); }) + .then(function (answer) { + show("passive", answer.humanConfidence); + if (answer.sent) { + setCommand("passive", answer.sent.url, answer.sent.form); + } + }) + .catch(function () { show("passive", null); }); } - // Step 1. The server asks the cloud for the passive level. - fetch("passive").then(function (r) { return r.json(); }) - .then(function (answer) { - if (answer.error) { - show("passive-source", "failed", FAIL); - show("passive-level", answer.error, NONE); - return; - } - show("passive-source", answer.source || "not returned", NONE); - show("passive-level", answer.humanConfidence || "not returned", - levelClass(answer.humanConfidence)); - }) - .catch(function (error) { show("passive-level", String(error), FAIL); }); + // Records the browser test answers the 51Degrees script posts. Server + // side the post comes here and the cloud request engine sends it to the + // Resource Key's JSON address, setting the resource and values fields + // itself. + function bodyPairs(body) { + if (!body) { return []; } + if (typeof body === "string") { + return Array.from(new URLSearchParams(body).entries()); + } + if (body instanceof URLSearchParams || body instanceof FormData) { + return Array.from(body.entries()).map(function (p) { + return [p[0], String(p[1])]; }); + } + return []; + } + function recordPost(url, body) { + var absolute = new URL(url, location.href).href; + var pairs = bodyPairs(body); + if (FORWARD.test(absolute)) { + absolute = API + RESOURCE + ".json"; + pairs = pairs.filter(function (p) { + return p[0] !== "resource" && p[0] !== "values"; }); + } + if (!/51degrees\.com\//.test(absolute) || !pairs.length) { return; } + setCommand("active", absolute, pairs); + } + var open = XMLHttpRequest.prototype.open; + var send = XMLHttpRequest.prototype.send; + XMLHttpRequest.prototype.open = function (method, url) { + this._hcPost = String(method).toUpperCase() === "POST" ? url : null; + return open.apply(this, arguments); + }; + XMLHttpRequest.prototype.send = function (body) { + if (this._hcPost) { recordPost(this._hcPost, body); } + return send.apply(this, arguments); + }; + var originalFetch = window.fetch; + window.fetch = function (input, init) { + if (init && String(init.method || "").toUpperCase() === "POST") { + recordPost(typeof input === "string" ? input : input.url, init.body); + } + return originalFetch.apply(this, arguments); + }; - // Step 3. The server redeems the sealed value with its License Key. + // 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; function redeem(value) { + var mine = ++latest; var body = new URLSearchParams(); body.set("value", value); - return fetch("redeem", { method: "POST", body: body }) - .then(function (r) { return r.json(); }); + originalFetch("redeem", { 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); } }); } - function showRedeemed(answer) { - if (answer.humanConfidence) { - show("redeem-detail", "redeemed " + answer.secondsSinceVerified - + " s after the check", PASS); - show("redeem-level", answer.humanConfidence, - levelClass(answer.humanConfidence)); - } else { - show("redeem-detail", answer.result || answer.error || "no answer", FAIL); - show("redeem-level", "no level", NONE); - } - } - - // Step 2. The client script runs the browser tests, sends the answers, - // and calls back through its complete function with the final result. + // The script's third party cookie check calls window.fodTpcEndpoint, or + // the public cloud when that is not set, so it is pointed at the same + // cloud as everything else. + window.fodTpcEndpoint = MODE === "server" + ? location.origin + "/hc/cloud/" + API.replace(/^https?:\/\//, "") + "3pc" + : API + "3pc"; + // The 51Degrees script, from the cloud client side and from this server + // server side. Its result comes back through fod.onChange. var script = document.createElement("script"); script.async = true; - script.src = API + RESOURCE + ".js"; - script.onerror = function () { - show("active-source", "the 51Degrees script didn't load", FAIL); - }; + script.src = MODE === "server" ? "hc/script.js" : API + RESOURCE + ".js"; + script.onerror = function () { show("active", null); }; script.onload = function () { - if (!window.fod || typeof window.fod.complete !== "function") { - show("active-source", "no fod object on the page", FAIL); + if (!window.fod || typeof window.fod.onChange !== "function") { + show("active", null); return; } - window.fod.complete(function (data) { - var derived = (data && data.derived) || {}; - var source = derived.humanconfidencesource; - var value = derived.humanconfidence; - if (source !== "Active") { - show("active-source", (source || "not returned") + " after " - + seconds(), NONE); - show("active-value", value || "not returned", levelClass(value)); - show("redeem-detail", "nothing to redeem", NONE); - show("redeem-level", "", NONE); - document.getElementById("note").textContent = "The source isn't " - + "Active, so there's no sealed value to redeem."; - return; + window.fod.onChange(function (data) { + var value = data && data.derived && data.derived.humanconfidence; + if (value && value !== seen) { + seen = value; + redeem(value); } - show("active-source", "Active after " + seconds(), PASS); - show("active-value", "sealed value, " + String(value).length - + " characters, unreadable here", NONE); - redeem(value).then(function (answer) { - showRedeemed(answer); - var again = document.getElementById("again"); - again.style.display = ""; - again.onclick = function () { - redeem(value).then(function (second) { - document.getElementById("again-result").textContent = - " Second redeem: " + (second.result || second.humanConfidence - || second.error); - }); - }; - }).catch(function (error) { - show("redeem-detail", String(error), FAIL); - }); }); }; document.head.appendChild(script); From 03b0606066f78007dd061bb5b17a44a0d4e498eb Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Mon, 23 Nov 2026 16:25:17 +0000 Subject: [PATCH 2/7] FIX: Record the active replay when the cloud is a private endpoint The page recorded the browser test answers only when they were sent to a 51degrees.com address, and server side only 51degrees.com addresses in the client script were pointed back at this server. With a private cloud, such as one in Docker at a localhost address, the active replay never filled, and server side the browser sent the test answers to its own machine. Both checks now take the host of the endpoint in use as well as the 51Degrees cloud hosts, and a call sent on to the endpoint's own host keeps the endpoint's scheme, so a plain http private cloud works. --- .../cloud/humanconfidence_web/app.py | 33 ++++++++++++++----- .../humanconfidence_web/templates/index.html | 7 +++- 2 files changed, 30 insertions(+), 10 deletions(-) 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 e2e361d8..5837adb4 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 @@ -97,11 +97,21 @@ # The levels, highest first. A level the cloud doesn't give is the last. LEVELS = ("High", "Medium", "Low") -# Cloud addresses in the client script. In server mode each one is pointed -# at this server. -CLOUD_URL = re.compile( - r"https://(cloud[a-z0-9-]*\.51degrees\.com)/([^\"'\s\\)]*)") -CLOUD_HOST = re.compile(r"cloud[a-z0-9-]*\.51degrees\.com") +# 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" + + +def cloud_patterns(api): + + """! + The cloud hosts for the endpoint api, and the cloud addresses in the + client script, which in server mode are each pointed at this server. + """ + + hosts = CLOUD_HOSTS + "|" + re.escape(urllib.parse.urlsplit(api).netloc) + return (re.compile(hosts), + re.compile(r"(https?)://(" + hosts + r")/([^\"'\s\\)]*)")) # Headers the cloud lists that are never sent on as HTTP headers, because # they belong to this server's own connection to the cloud. @@ -186,6 +196,8 @@ def create_app(resource_key, license_key, api): # Serve the files in the static folder from the root, so the stylesheet # is at /css, as in the other web examples. app = Flask(__name__, static_url_path="") + cloud_host, cloud_url = cloud_patterns(api) + endpoint = urllib.parse.urlsplit(api) # The request headers the cloud reads, from its own list, fetched once. # Only these are passed on, so headers such as Authorization stay here. @@ -321,8 +333,8 @@ def script(): "console.log(" + repr(str(error)) + ");", status=502, content_type="application/javascript") here = request.host_url + "hc/cloud/" - text = CLOUD_URL.sub( - lambda m: here + m.group(1) + "/" + m.group(2), answer.text) + text = cloud_url.sub( + lambda m: here + m.group(2) + "/" + m.group(3), answer.text) response = Response( text, status=answer.status_code, content_type="application/javascript") @@ -336,7 +348,7 @@ def script(): @app.route("/hc/cloud//", methods=["GET", "POST"]) def forward(host, path): - if not CLOUD_HOST.fullmatch(host): + if not cloud_host.fullmatch(host): abort(404) if request.method == "POST": try: @@ -346,7 +358,10 @@ def forward(host, path): response = jsonify(answer) response.headers["Cache-Control"] = "no-store" return response - url = "https://" + host + "/" + path + # The endpoint's own host keeps the endpoint's scheme, as a private + # cloud may be plain http. + scheme = endpoint.scheme if host == endpoint.netloc else "https" + url = scheme + "://" + host + "/" + path headers = passed_on(visitor_headers()) cookies = "; ".join( f"{name}={value}" for name, value in request.cookies.items() 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 4defb8f3..78ad57d0 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 @@ -112,6 +112,7 @@

    Find out more

    var RESOURCE = {{ resource_key|tojson }}; // The cloud API base ending in /api/v4/, as the server read it. 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"; @@ -255,7 +256,11 @@

    Find out more

    pairs = pairs.filter(function (p) { return p[0] !== "resource" && p[0] !== "values"; }); } - if (!/51degrees\.com\//.test(absolute) || !pairs.length) { return; } + // Only posts to the cloud in use, or a 51Degrees cloud host, carry the + // test answers. + var toCloud = absolute.indexOf(API_ORIGIN + "/") === 0 || + /^https:\/\/cloud[a-z0-9-]*\.51degrees\.com\//.test(absolute); + if (!toCloud || !pairs.length) { return; } setCommand("active", absolute, pairs); } var open = XMLHttpRequest.prototype.open; From d061d0ed2f3bd852dbb4ec5154c70e57bd66fb93 Mon Sep 17 00:00:00 2001 From: James Rogers Date: Mon, 23 Nov 2026 16:22:19 +0000 Subject: [PATCH 3/7] FIX: Redeem only a sealed Human Confidence value in the web demo The page redeemed every HumanConfidence value the 51Degrees script gave through fod.onChange. The first one comes before the browser tests have run and is a plain level, which the cloud can't open, so the redeem answered unreadable and the page showed Active Low. When the test answers then didn't arrive, or the page was left early, Low stayed on the page for tests that never ran. The page now redeems only a value that isn't a plain level (High, Medium, Low, or Unknown), so Active shows a level only once the tests have run and their result is sealed. --- .../cloud/humanconfidence_web/templates/index.html | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 78ad57d0..f1fa45ed 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 @@ -120,6 +120,8 @@

    Find out more

    // /hc/cloud// here. var FORWARD = /^https?:\/\/[^\/]+\/hc\/cloud\/([^\/]+)\/(.*)$/; var LEVELS = ["High", "Medium", "Low"]; + // The values HumanConfidence takes before it is sealed. + var PLAIN = LEVELS.concat(["Unknown"]); var CLASSES = { High: "c-eg-status--pass", Medium: "c-eg-status--part", Low: "c-eg-status--fail" }; @@ -315,7 +317,11 @@

    Find out more

    } window.fod.onChange(function (data) { var value = data && data.derived && data.derived.humanconfidence; - if (value && value !== seen) { + // The script's first result comes before the browser tests have + // 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) { seen = value; redeem(value); } From ed60072569d4b2da878c452711d68e3fb431dbe0 Mon Sep 17 00:00:00 2001 From: James Rogers Date: Mon, 23 Nov 2026 16:28:57 +0000 Subject: [PATCH 4/7] FIX: Stop waiting for the Active result after 30 seconds in the web demo Now that only a sealed value is redeemed, a page whose test answers never reach the cloud waited for ever, with the Active timer running on. After 30 seconds with no sealed value the row now says No result. A sealed value that arrives later still replaces it. --- .../cloud/humanconfidence_web/templates/index.html | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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 f1fa45ed..207c754c 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 @@ -122,6 +122,8 @@

    Find out more

    var LEVELS = ["High", "Medium", "Low"]; // The values HumanConfidence takes before it is sealed. var PLAIN = LEVELS.concat(["Unknown"]); + // How long to wait for the browser tests' sealed value. + var ACTIVE_LIMIT_MS = 30000; var CLASSES = { High: "c-eg-status--pass", Medium: "c-eg-status--part", Low: "c-eg-status--fail" }; @@ -328,6 +330,18 @@

    Find out more

    }); }; document.head.appendChild(script); + + // The browser tests take a few seconds. If no sealed value has come back + // by then, the answers didn't reach the cloud, so the timer stops and the + // row says so rather than running on, or showing a level for tests that + // didn't run. A sealed value that arrives later still replaces it. + setTimeout(function () { + if (shown.active) { return; } + shown.active = true; + var element = document.getElementById("active"); + element.textContent = "No result"; + element.className = "hc-level c-eg-status c-eg-status--none"; + }, ACTIVE_LIMIT_MS); })(); From 835755509dd7ee976043d6c6e676d3a410622d93 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Mon, 23 Nov 2026 20:40:45 +0000 Subject: [PATCH 5/7] FIX: Remove trace output from the web demo and update its tests After it starts, the Human Confidence web example writes nothing to the console. /redeem no longer prints each outcome, the web server no longer logs each request, and /hc/script.js answers 502 with an empty script when the cloud can't be reached, so the page shows Active Low. The cloud request engine is built with the example's 10 second timeout, its evidence keys give the headers passed on, and its answer is read under cloud-response. The address sent as client-ip is the connection's own, when it is a public one, and the replay command shows the form the engine sent. The start-up error shows the Resource Key as , and the header comment says what redeeming needs and gives. The three test files now test the example as it is. 88 pass, and the 4 live tests skip with no keys set. --- .../cloud/humanconfidence_web/app.py | 119 ++-- .../tests/test_cloud_humanconfidence_web.py | 46 +- .../test_cloud_humanconfidence_web_offline.py | 641 +++++++++++++++--- .../test_cloud_humanconfidence_web_port.py | 22 +- 4 files changed, 660 insertions(+), 168 deletions(-) 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 5837adb4..f200a713 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 @@ -36,7 +36,13 @@ # 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. +# 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 Resource Key is put in the page, as the 51Degrees client script is +# loaded with it. The License Key stays on this server. # # The page works in two modes, chosen with ?mode=client or ?mode=server # and kept in a cookie. @@ -67,6 +73,7 @@ import ipaddress import json +import logging import os import re import sys @@ -78,6 +85,8 @@ from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ CloudRequestEngine +from fiftyone_pipeline_cloudrequestengine.cloudrequestexception import \ + CloudRequestException from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_pipeline_examples.example_utils import ExampleUtils @@ -199,46 +208,41 @@ def create_app(resource_key, license_key, api): cloud_host, cloud_url = cloud_patterns(api) endpoint = urllib.parse.urlsplit(api) - # The request headers the cloud reads, from its own list, fetched once. - # Only these are passed on, so headers such as Authorization stay here. - fetched = [] - - def cloud_headers(): - if not fetched: - answer = requests.request( - "GET", api + "evidencekeys", timeout=TIMEOUT) - if answer.status_code != 200: - raise ValueError( - f"HTTP {answer.status_code}: {trim(answer.text)}") - fetched.append({ - key[len("header."):].lower() for key in answer.json() - if key.lower().startswith("header.")}) - return fetched[0] + # The cloud request engine, which sends this server's requests for data + # to the cloud: the passive level, and in server mode the browser's + # test answers. It asks the cloud for the properties the key carries + # and the evidence it reads when it is built. The page's own script is + # served by this server, so the pipeline needs no JavaScript of its + # own. + engine = CloudRequestEngine({"resource_key": resource_key, + "cloud_endpoint": api, + "timeout_seconds": TIMEOUT}) + pipeline = PipelineBuilder({"add_javascript_builder": False}).add( + engine).build() def visitor_headers(): - names = cloud_headers() + # The request headers the cloud reads, from the evidence keys the + # engine was given. Only these are passed on, so headers such as + # Authorization stay here. + names = {key[len("header."):].lower() for key in engine.evidence_keys + if key.lower().startswith("header.")} return {name.lower(): value for name, value in request.headers.items() if name.lower() in names} - # The cloud request engine, which sends this server's requests for data - # to the cloud: the passive level, and in server mode the browser's - # test answers. The page's own script is served by this server, so the - # pipeline needs no JavaScript of its own. - pipeline = PipelineBuilder({"add_javascript_builder": False}).add( - CloudRequestEngine({"resource_key": resource_key, - "cloud_endpoint": api})).build() - def ask_cloud(fields): """The cloud's answer for the visitor's headers and IP address and the form fields given, sent through the cloud request engine, with what was sent described for the page's curl command.""" + # The visitor's address is the connection's own address, sent when + # it is a public one. A Client-IP request header is not passed on, + # so with a local or private connection the cloud reads this + # server's public address. evidence = {"header." + name: value - for name, value in visitor_headers().items()} + for name, value in visitor_headers().items() + if name != "client-ip"} for name, value in fields: - if name.lower() not in ("resource", "values"): + if name.lower() not in ("resource", "values", "client-ip"): evidence["query." + name] = value - # Behind a load balancer or CDN, use the visitor's address it - # passes on. Set last, so no header can replace it. address = public_ip(request.remote_addr) if address: evidence["query.client-ip"] = address @@ -249,14 +253,16 @@ def ask_cloud(fields): if flowdata.errors: raise ValueError("; ".join( str(error) for error in flowdata.errors.values())) - answer = flowdata.get("cloud").get("cloud") + answer = flowdata.get("cloud-response").get("cloud") if isinstance(answer, str): answer = json.loads(answer) + # The form fields as the engine sends them, apart from the Resource + # Key, which the address carries. sent = { "method": "POST", "url": api + resource_key + ".json", - "form": [[key.split(".", 1)[1], value] - for key, value in evidence.items()]} + "form": [[name, value] for name, value + in engine.get_content(flowdata).items()]} return answer, sent @app.route("/") @@ -292,7 +298,7 @@ def passive(): # 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 logged here, never sent back. + # there. The cloud's own answer is never sent back. @app.route("/redeem", methods=["POST"]) def redeem(): @@ -300,19 +306,15 @@ def redeem(): fields = {"value": sealed} if license_key: fields["license"] = license_key - level, outcome = None, None + level = None try: answer = requests.request( "POST", api + "hc/redeem", data=fields, timeout=TIMEOUT) - body = answer.json() - level = read(body, "humanConfidence") - outcome = read(body, "result") or ( - "redeemed" if level else f"HTTP {answer.status_code}") - except (requests.RequestException, ValueError) as error: - outcome = type(error).__name__ + level = read(answer.json(), "humanConfidence") + except (requests.RequestException, ValueError): + pass if level not in LEVELS: level = LEVELS[-1] - print(f"redeem: {level} ({outcome})", flush=True) return jsonify(humanConfidence=level) # Server mode: the client script, fetched from the cloud for this @@ -328,10 +330,12 @@ def script(): answer = requests.request( "GET", api + resource_key + ".js", params=query, headers=passed_on(visitor_headers()), timeout=TIMEOUT) - except (requests.RequestException, ValueError) as error: + except (requests.RequestException, CloudRequestException, + ValueError): + # An empty script with a failing status, so the page's script + # element fails and the page shows Active Low. return Response( - "console.log(" + repr(str(error)) + ");", status=502, - content_type="application/javascript") + "", status=502, content_type="application/javascript") here = request.host_url + "hc/cloud/" text = cloud_url.sub( lambda m: here + m.group(2) + "/" + m.group(3), answer.text) @@ -362,17 +366,17 @@ def forward(host, path): # cloud may be plain http. scheme = endpoint.scheme if host == endpoint.netloc else "https" url = scheme + "://" + host + "/" + path - headers = passed_on(visitor_headers()) cookies = "; ".join( f"{name}={value}" for name, value in request.cookies.items() if name.lower().startswith(COOKIE_PREFIX)) - if cookies: - headers["Cookie"] = cookies try: + headers = passed_on(visitor_headers()) + if cookies: + headers["Cookie"] = cookies answer = requests.request( "GET", url, params=request.args, headers=headers, timeout=TIMEOUT) - except requests.RequestException as error: + except (requests.RequestException, CloudRequestException) as error: return jsonify(error=str(error)), 502 response = Response( answer.content, status=answer.status_code, @@ -465,6 +469,20 @@ def trim(text): return text[:200] +def without_key(text, resource_key): + + """! + The text with the Resource Key, as given and as an address holds it, + shown as . An error from the requests library names the + address it asked for, which holds the key. + """ + + for form in {resource_key, urllib.parse.quote(resource_key, safe="")}: + if form: + text = text.replace(form, "") + return text + + def main(argv): # A Resource Key given on the command line is used as it is. Otherwise @@ -486,7 +504,7 @@ def main(argv): try: carried = carries_human_confidence(api, resource_key) except (requests.RequestException, ValueError) as error: - print(error) + print(without_key(str(error), resource_key)) print_find_out_more() sys.exit(1) if not carried: @@ -502,6 +520,9 @@ def main(argv): app = create_app(resource_key, license_key, api) port = os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151) + # The web server writes a line for each request unless told not to. + # The example writes only the line below. + logging.getLogger("werkzeug").setLevel(logging.WARNING) print(f"Human Confidence demo on http://localhost:{port}/, using {api}") # Threaded, so the page's calls in server mode don't wait on each other. app.run(port=int(port), threaded=True) 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 a436ebcb..77385555 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 @@ -26,10 +26,9 @@ the example asks the cloud service about before anything else, and these tests skip themselves when no key is set or the key does not carry it. -The passive tests check that HumanConfidenceSource comes back. The Pro and -Bespoke products offer it, and the Bespoke key gets Passive, as no browser -tests have run. The Basic product does not offer HumanConfidenceSource, so -a Basic key gets no source. +The passive tests check that the example gives a level from the cloud's +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. @@ -87,7 +86,8 @@ def naming_the_properties(monkeypatch): real = requests.request def request(method, url, data=None, **kwargs): - if method == "POST" and url.endswith(".json"): + # The cloud request engine adds "?" to the address it posts to. + if method == "POST" and url.split("?")[0].endswith(".json"): data = dict(data or {}, values=PROPERTIES) return real(method, url, data=data, **kwargs) @@ -111,34 +111,36 @@ def test_page_is_served_and_never_kept(client, key): assert key in response.get_data(as_text=True) -def test_passive_source_and_level_come_from_the_cloud( - client, naming_the_properties): +def test_passive_level_comes_from_the_cloud(client, key, api, + naming_the_properties): answer = client.get("/passive", headers=HEADERS).get_json() - assert "error" not in answer, answer - assert answer["source"] == "Passive", answer + assert "error" not in answer, "The cloud refused the request." assert answer["humanConfidence"] in LEVELS + assert answer["sent"]["url"] == api + key + ".json" -def test_a_basic_key_gets_no_source(api, naming_the_properties): - """The Basic product does not offer HumanConfidenceSource.""" +def test_a_basic_key_gets_a_passive_level(api, naming_the_properties): + """The Basic product does not offer HumanConfidenceSource, and the + passive call still works with its key.""" basic = read_environment(BASIC_KEY_NAME) if not basic: pytest.skip( - f"{BASIC_KEY_NAME} is not set. The Basic product does not offer " - "HumanConfidenceSource. Set the variable to a Basic resource " - "key to check that such a key gets no source.") + f"{BASIC_KEY_NAME} is not set. Set the variable to a Resource " + "Key of the Basic product to check the passive call with it.") client = example.create_app(basic, None, api).test_client() answer = client.get("/passive", headers=HEADERS).get_json() assert "error" not in answer, "The cloud refused the request." - assert answer["source"] is None, answer + assert answer["humanConfidence"] in LEVELS + (None,) -def test_licence_key_never_reaches_the_browser(client): - licence_key = ExampleUtils.get_license_key() - if not licence_key: +def test_license_key_never_reaches_the_browser(client): + license_key = ExampleUtils.get_license_key() + if not license_key: pytest.skip( f"{ExampleUtils.LICENSE_KEY_ENV_VAR} is not set, so there is no " - "licence key to look for.") - for response in (client.get("/", headers=HEADERS), - client.get("/passive", headers=HEADERS)): - assert licence_key.encode() not in response.data + "License Key to look for.") + 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"})): + 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 73afb432..9b2388d6 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 @@ -23,11 +23,13 @@ """ Runs the Human Confidence web example against a stand-in for the cloud service, so each step is checked with known values and without a key. The -stand-in answers in the shapes the example reads, and keeps the requests it -was sent, so the tests see what the example passed on. +stand-in answers in the shapes the example and the cloud request engine +read, and keeps the requests it was sent, so the tests see what was passed +on. """ import json +import logging import re import pytest @@ -40,8 +42,14 @@ import test_cloud_humanconfidence_web as live API = "https://cloud.example/api/v4/" +# A private cloud, such as one in Docker, on plain http. +PRIVATE_API = "http://127.0.0.1:18081/api/v4/" RESOURCE_KEY = "a-resource-key" -LICENCE_KEY = "a-licence-key" +LICENSE_KEY = "a-license-key" + +# A public address, and the address the test client connects from. +PUBLIC_ADDRESS = "81.2.69.142" +LOCAL_ADDRESS = "127.0.0.1" DESKTOP_CHROME = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " @@ -66,11 +74,35 @@ "fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=") +class StubHeaders(dict): + """Response headers, with getlist as urllib3 gives it.""" + + def __init__(self, items=()): + super().__init__() + self.items_list = list(items) + for name, value in self.items_list: + self[name] = value + + def getlist(self, name): + return [value for key, value in self.items_list + if key.lower() == name.lower()] + + +class StubRaw: + + def __init__(self, headers): + self.headers = headers + + class StubResponse: - def __init__(self, body, status_code=200): + def __init__(self, body, status_code=200, headers=(), url=""): self.status_code = status_code self.text = body if isinstance(body, str) else json.dumps(body) + self.content = self.text.encode() + self.headers = StubHeaders(headers) + self.raw = StubRaw(self.headers) + self.url = url def json(self): return json.loads(self.text) @@ -80,72 +112,96 @@ class StubCloud: """ Answers as the cloud service does for a key carrying the named properties, and keeps the requests it was sent as method, address and - form fields. + form fields. The other arguments of each request are kept in calls. """ - def __init__(self, properties): + def __init__(self, properties, api=API): self.properties = properties + self.api = api self.requests = [] + self.calls = [] # The sealed values already redeemed, as each redeems once. self.redeemed = set() # An answer to give in place of the usual one, by the end of the # address, as a StubResponse or an exception to raise. self.instead = {} + # The client script the cloud serves for the Resource Key. + self.script = "/* client script */" def sent_to(self, ending): - """The requests sent to the addresses with the ending.""" - return [sent for sent in self.requests if sent[1].endswith(ending)] + """The requests sent to the addresses with the ending, the query + left out.""" + return [sent for sent in self.requests + if sent[1].split("?")[0].endswith(ending)] - def request(self, method, url, data=None, headers=None, timeout=None): + def request(self, method, url, data=None, headers=None, timeout=None, + params=None, **others): data = dict(data or {}) self.requests.append((method, url, data)) - assert url.startswith(API), url - path = url[len(API):] + self.calls.append({"method": method, "url": url, "data": data, + "headers": dict(headers or {}), + "timeout": timeout, "params": params}) + path = url[len(self.api):] if url.startswith(self.api) else url + bare = path.split("?")[0] for ending, answer in self.instead.items(): - if path.endswith(ending): + if path.endswith(ending) or bare.endswith(ending): if isinstance(answer, BaseException): raise answer return answer - if path.startswith("accessibleproperties"): + # The example asks in lower case, the cloud request engine in + # camel case. The cloud service takes either. + if bare.lower() == "accessibleproperties": return StubResponse({"Products": {"derived": {"Properties": [ {"Name": name, "Type": "String"} - for name in self.properties]}}}) + for name in self.properties]}}}, url=url) - if path == "evidencekeys": + if bare == "evidencekeys": return StubResponse([ - "header.user-agent", "header.sec-ch-ua", "query.client-ip"]) + "header.user-agent", "header.sec-ch-ua", "query.client-ip"], + url=url) - if path == RESOURCE_KEY + ".json": + if bare == RESOURCE_KEY + ".json": return StubResponse({"derived": { "humanconfidence": "Medium", - "humanconfidencesource": "Passive"}}) + "humanconfidencesource": "Passive"}}, url=url) - if path == "hc/redeem": + if bare == RESOURCE_KEY + ".js": + 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"}) + return StubResponse({"result": "replayed"}, url=url) self.redeemed.add(data.get("value")) return StubResponse({ - "humanConfidence": "High", "secondsSinceVerified": 2}) + "humanConfidence": "High", "secondsSinceVerified": 2}, + url=url) - return StubResponse("Not Found", 404) + return StubResponse("Not Found", 404, url=url) @pytest.fixture def cloud(monkeypatch): """Makes a stand-in for the cloud service answer every request.""" - def stand_in(properties=("HumanConfidence", "HumanConfidenceSource")): - stub = StubCloud(properties) + def stand_in(properties=("HumanConfidence", "HumanConfidenceSource"), + api=API): + stub = StubCloud(properties, api) monkeypatch.setattr(requests, "request", stub.request) return stub return stand_in -def client_for(license_key=LICENCE_KEY): - return example.create_app(RESOURCE_KEY, license_key, API).test_client() +def client_for(license_key=LICENSE_KEY, api=API): + return example.create_app(RESOURCE_KEY, license_key, api).test_client() + + +def from_address(address): + """The arguments that make the test client connect from address.""" + return {"environ_base": {"REMOTE_ADDR": address}} # The page. @@ -169,15 +225,29 @@ def test_page_is_never_kept_by_a_cache(cloud): assert client_for().get("/").headers["Cache-Control"] == "no-store" -def test_page_is_served_without_asking_the_cloud(cloud): +def test_building_the_app_asks_the_cloud_what_the_key_carries(cloud): + stub = cloud() + client_for() + + assert [(method, url) for method, url, _ in stub.requests] == [ + ("GET", API + "accessibleProperties?resource=" + RESOURCE_KEY), + ("GET", API + "evidencekeys")] + + +def test_page_is_served_without_asking_the_cloud_again(cloud): stub = cloud() - client_for().get("/") - assert stub.requests == [] + client = client_for() + asked = len(stub.requests) + client.get("/") + + assert len(stub.requests) == asked -def test_licence_key_never_reaches_the_page(cloud): +def test_license_key_never_reaches_the_page(cloud): cloud() - assert LICENCE_KEY not in client_for().get("/").get_data(as_text=True) + for mode in ("client", "server"): + html = client_for().get("/?mode=" + mode).get_data(as_text=True) + assert LICENSE_KEY not in html def test_page_ends_with_its_find_out_more_section(cloud): @@ -192,20 +262,57 @@ def test_page_ends_with_its_find_out_more_section(cloud): assert "-humanconfidence_web-templates-index.html&" in link -# Step 1, passive. +def test_page_redeems_only_a_sealed_value_and_waits_30_seconds(cloud): + cloud() + html = client_for().get("/").get_data(as_text=True) + + assert 'var PLAIN = LEVELS.concat(["Unknown"]);' in html + assert "PLAIN.indexOf(value) < 0" in html + assert "var ACTIVE_LIMIT_MS = 30000;" in html + + +# The mode. + +def test_mode_is_client_side_by_default_and_kept_in_a_cookie(cloud): + cloud() + response = client_for().get("/") + + assert 'var MODE = "client";' in response.get_data(as_text=True) + assert "hc_mode=client" in response.headers["Set-Cookie"] + + +def test_mode_named_is_used_and_kept(cloud): + cloud() + client = client_for() + named = client.get("/?mode=server") + kept = client.get("/") + + assert 'var MODE = "server";' in named.get_data(as_text=True) + assert "hc_mode=server" in named.headers["Set-Cookie"] + assert 'var MODE = "server";' in kept.get_data(as_text=True) + + +def test_mode_not_known_gives_the_default(cloud): + cloud() + html = client_for().get("/?mode=other").get_data(as_text=True) + + assert 'var MODE = "client";' in html + + +# Passive. def test_passive_is_read_from_the_answer_of_the_cloud(cloud): cloud() response = client_for().get( "/passive", headers={"User-Agent": DESKTOP_CHROME}) + answer = response.get_json() assert response.status_code == 200 - assert response.get_json() == { - "source": "Passive", "humanConfidence": "Medium"} + assert answer["humanConfidence"] == "Medium" + assert set(answer) == {"humanConfidence", "sent"} -def test_passive_passes_on_the_headers_the_cloud_lists_and_the_address( - cloud): +def test_passive_goes_through_the_cloud_request_engine(cloud): stub = cloud() client_for().get("/passive", headers={ "User-Agent": DESKTOP_CHROME, @@ -215,57 +322,158 @@ def test_passive_passes_on_the_headers_the_cloud_lists_and_the_address( method, url, data = stub.requests[-1] assert method == "POST" - assert url == API + RESOURCE_KEY + ".json" + assert url.split("?")[0] == API + RESOURCE_KEY + ".json" # The values as the browser sent them, under the names the cloud - # lists, with the address of the connection. Nothing else is sent. + # lists, with the Resource Key the engine adds. Nothing else is sent. assert data == { "user-agent": DESKTOP_CHROME, "sec-ch-ua": '"Chromium";v="120"', - "client-ip": "127.0.0.1"} + "resource": RESOURCE_KEY} + + +def test_passive_describes_what_was_sent(cloud): + cloud() + sent = client_for().get( + "/passive", headers={"User-Agent": DESKTOP_CHROME}, + **from_address(PUBLIC_ADDRESS)).get_json()["sent"] + assert sent["method"] == "POST" + assert sent["url"] == API + RESOURCE_KEY + ".json" + assert dict(sent["form"]) == { + "user-agent": DESKTOP_CHROME, "client-ip": PUBLIC_ADDRESS} -def test_address_of_the_connection_replaces_one_a_header_names(cloud): + +def test_public_address_of_the_connection_is_sent(cloud): + stub = cloud() + client_for().get( + "/passive", headers={"User-Agent": DESKTOP_CHROME}, + **from_address(PUBLIC_ADDRESS)) + + assert stub.requests[-1][2]["client-ip"] == PUBLIC_ADDRESS + + +def test_ipv4_address_written_as_ipv6_is_sent_as_ipv4(cloud): + stub = cloud() + client_for().get( + "/passive", headers={"User-Agent": DESKTOP_CHROME}, + **from_address("::ffff:" + PUBLIC_ADDRESS)) + + assert stub.requests[-1][2]["client-ip"] == PUBLIC_ADDRESS + + +def test_public_address_replaces_one_a_header_names(cloud): stub = cloud() stub.instead["evidencekeys"] = StubResponse( ["header.user-agent", "header.client-ip"]) - client_for().get("/passive", headers={ - "User-Agent": DESKTOP_CHROME, "Client-IP": "203.0.113.9"}) + client_for().get( + "/passive", + headers={"User-Agent": DESKTOP_CHROME, "Client-IP": "203.0.113.9"}, + **from_address(PUBLIC_ADDRESS)) + + assert stub.requests[-1][2]["client-ip"] == PUBLIC_ADDRESS + + +def test_local_connection_sends_no_address(cloud): + stub = cloud() + stub.instead["evidencekeys"] = StubResponse( + ["header.user-agent", "header.client-ip"]) + sent = client_for().get( + "/passive", + headers={"User-Agent": DESKTOP_CHROME, "Client-IP": "203.0.113.9"}, + **from_address(LOCAL_ADDRESS)).get_json()["sent"] + + assert stub.requests[-1][2] == { + "user-agent": DESKTOP_CHROME, "resource": RESOURCE_KEY} + assert sent["form"] == [["user-agent", DESKTOP_CHROME]] + + +def test_address_comes_only_from_the_connection(cloud): + stub = cloud() + client_for().post( + "/hc/cloud/cloud.example/api/v4/" + RESOURCE_KEY + ".json", + headers={"User-Agent": DESKTOP_CHROME}, + data={"client-ip": "203.0.113.9", "fod-test": "an-answer"}, + **from_address(PUBLIC_ADDRESS)) + + assert stub.requests[-1][2]["client-ip"] == PUBLIC_ADDRESS + + +def test_described_form_is_what_the_engine_sent(cloud): + stub = cloud() + stub.instead["evidencekeys"] = StubResponse( + ["header.user-agent", "header.client-ip", "header.sec-ch-ua"]) + sent = client_for().get( + "/passive", + headers={"User-Agent": DESKTOP_CHROME, "Client-IP": "203.0.113.9", + "Sec-CH-UA": '"Chromium";v="120"'}, + **from_address(PUBLIC_ADDRESS)).get_json()["sent"] - assert stub.requests[-1][2]["client-ip"] == "127.0.0.1" + names = [name for name, _ in sent["form"]] + assert len(names) == len(set(names)) + engine_sent = dict(stub.requests[-1][2]) + del engine_sent["resource"] + assert dict(sent["form"]) == engine_sent -def test_list_of_headers_is_asked_for_once(cloud): +def test_list_of_headers_is_the_one_the_engine_was_given(cloud): stub = cloud() client = client_for() client.get("/passive") client.get("/passive") + client.get("/hc/script.js") assert len(stub.sent_to("evidencekeys")) == 1 + assert len(stub.sent_to("accessibleProperties")) == 1 assert len(stub.sent_to(".json")) == 2 -def test_passive_never_sends_the_licence_key(cloud): +def test_engine_waits_the_example_timeout(cloud): + stub = cloud() + client_for().get("/passive") + + engine_calls = [call for call in stub.calls + if "accessibleProperties" in call["url"] + or call["url"].endswith("evidencekeys") + or call["url"].split("?")[0].endswith(".json")] + assert len(engine_calls) == 3 + for call in engine_calls: + assert call["timeout"] == example.TIMEOUT + + +def test_list_of_headers_the_cloud_cannot_give_is_an_error(cloud): + stub = cloud() + stub.instead["evidencekeys"] = StubResponse("Unavailable", 503) + with pytest.warns(UserWarning): + client = client_for() + + assert "error" in client.get("/passive").get_json() + assert client.get("/hc/script.js").status_code == 502 + assert client.get( + "/hc/cloud/cloud.example/api/v4/3pc").status_code == 502 + + +def test_passive_never_sends_the_license_key(cloud): stub = cloud() client_for().get("/passive") for _, url, data in stub.requests: - assert LICENCE_KEY not in url - assert LICENCE_KEY not in data.values() + assert LICENSE_KEY not in url + assert LICENSE_KEY not in data.values() -def test_passive_without_the_properties_returns_neither(cloud): +def test_passive_without_the_property_returns_no_level(cloud): stub = cloud() stub.instead[".json"] = StubResponse({"device": {"ismobile": False}}) - assert client_for().get("/passive").get_json() == { - "source": None, "humanConfidence": None} + assert client_for().get("/passive").get_json()["humanConfidence"] is None # The Basic product does not offer HumanConfidenceSource, so a Basic key is # answered with no source, and with or without a level. The example gives -# what the cloud gave and makes up neither. +# the level the cloud gave and makes up none. @pytest.mark.parametrize("level", [None, "Medium"]) -def test_passive_for_a_basic_key_returns_no_source(cloud, level): +def test_passive_for_a_basic_key_gives_the_level_the_cloud_gave( + cloud, level): stub = cloud() derived = { "humanconfidence": level, @@ -277,22 +485,19 @@ def test_passive_for_a_basic_key_returns_no_source(cloud, level): "The key does not give this property a value.") stub.instead[".json"] = StubResponse({"derived": derived}) - assert client_for().get("/passive").get_json() == { - "source": None, "humanConfidence": level} + assert client_for().get("/passive").get_json()["humanConfidence"] == \ + level -# With no Basic key set, the live test skips, naming the variable it reads -# and what a Basic key is there to check. +# With no Basic key set, the live test skips, naming the variable it reads. def test_the_live_basic_key_test_skips_naming_its_variable(monkeypatch): monkeypatch.delenv(live.BASIC_KEY_NAME, raising=False) with pytest.raises(pytest.skip.Exception) as skipped: - live.test_a_basic_key_gets_no_source(API, None) + live.test_a_basic_key_gets_a_passive_level(API, None) assert live.BASIC_KEY_NAME == "_51DEGREES_RESOURCE_KEY_BASIC" assert f"{live.BASIC_KEY_NAME} is not set" in str(skipped.value) - assert ("The Basic product does not offer HumanConfidenceSource" - in str(skipped.value)) def test_passive_says_what_the_cloud_refused(cloud): @@ -301,7 +506,6 @@ def test_passive_says_what_the_cloud_refused(cloud): '{"errors":["The resource key is not valid."]}', 400) answer = client_for().get("/passive").get_json() - assert answer["error"].startswith("HTTP 400: ") assert "The resource key is not valid." in answer["error"] @@ -315,33 +519,33 @@ def test_passive_answers_when_the_cloud_cannot_be_reached(cloud): assert "cannot be reached" in response.get_json()["error"] -# Step 3, redeem. +# Redeem. -def test_redeem_sends_the_sealed_value_with_the_licence_key(cloud): +def test_redeem_sends_the_sealed_value_with_the_license_key(cloud): stub = cloud() response = client_for().post("/redeem", data={"value": "a-sealed-value"}) assert response.status_code == 200 assert response.headers["Content-Type"].startswith("application/json") - assert response.get_json() == { - "humanConfidence": "High", "secondsSinceVerified": 2} + # Only the level goes back. + assert response.get_json() == {"humanConfidence": "High"} method, url, data = stub.requests[-1] assert method == "POST" assert url == API + "hc/redeem" - assert data == {"value": "a-sealed-value", "license": LICENCE_KEY} + assert data == {"value": "a-sealed-value", "license": LICENSE_KEY} -def test_second_redeem_of_the_same_value_is_replayed(cloud): +def test_second_redeem_of_the_same_value_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"}) - assert first.get_json()["humanConfidence"] == "High" - assert second.get_json() == {"result": "replayed"} + assert first.get_json() == {"humanConfidence": "High"} + assert second.get_json() == {"humanConfidence": "Low"} -def test_redeem_without_a_licence_key_sends_none(cloud): +def test_redeem_without_a_license_key_sends_none(cloud): stub = cloud() client_for(license_key="").post( "/redeem", data={"value": "a-sealed-value"}) @@ -349,32 +553,216 @@ def test_redeem_without_a_licence_key_sends_none(cloud): assert stub.requests[-1][2] == {"value": "a-sealed-value"} -def test_redeem_gives_the_answer_as_the_cloud_gave_it(cloud): +@pytest.mark.parametrize("answer", [ + StubResponse('{"result":"expired"}', 400), + StubResponse('{"result":"unreadable"}', 400), + StubResponse("Not Found", 404), + StubResponse('{"humanConfidence":"Unknown"}'), + StubResponse('{"humanConfidence":"a-sealed-value"}'), + 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", + "unreachable", "timeout"]) +def test_value_that_does_not_redeem_gives_low(cloud, answer): stub = cloud() - stub.instead["hc/redeem"] = StubResponse('{"result":"expired"}', 400) + stub.instead["hc/redeem"] = answer response = client_for().post("/redeem", data={"value": "a-sealed-value"}) - assert response.status_code == 400 - assert response.get_data(as_text=True) == '{"result":"expired"}' + assert response.status_code == 200 + assert response.get_json() == {"humanConfidence": "Low"} -def test_redeem_says_when_the_service_does_not_redeem(cloud): +@pytest.mark.parametrize("answer", [ + None, + StubResponse('{"result":"expired"}', 400), + requests.exceptions.ConnectionError( + "The stand-in service cannot be reached.")], + ids=["redeemed", "expired", "unreachable"]) +def test_routes_write_nothing_to_the_console(cloud, capsys, answer): stub = cloud() - stub.instead["hc/redeem"] = StubResponse("Not Found", 404) - response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + 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"}) + client.get("/hc/script.js") + client.post("/hc/cloud/cloud.example/api/v4/" + RESOURCE_KEY + ".json", + data={"fod-test": "an-answer"}) + client.get("/hc/cloud/cloud.example/api/v4/3pc") - assert response.get_json() == { - "error": f"The service at {API} doesn't redeem Human Confidence."} + printed = capsys.readouterr() + assert printed.out == "" + assert printed.err == "" -def test_redeem_answers_502_when_the_cloud_cannot_be_reached(cloud): +def test_redeem_waits_the_example_timeout(cloud): stub = cloud() - stub.instead["hc/redeem"] = requests.exceptions.ConnectionError( + client_for().post("/redeem", data={"value": "a-sealed-value"}) + + assert stub.calls[-1]["timeout"] == example.TIMEOUT + + +# Server mode: the client script. + +def test_script_points_each_cloud_address_at_this_server(cloud): + stub = cloud() + stub.script = ( + 'a("' + API + RESOURCE_KEY + '.json");' + 'b("https://cloud.51degrees.com/api/v4/3pc");' + 'c("https://cloud-eu.51degrees.com/api/v4/x");' + 'd("https://example.com/x");') + response = client_for().get("/hc/script.js") + text = response.get_data(as_text=True) + + assert response.status_code == 200 + assert response.headers["Content-Type"].startswith( + "application/javascript") + assert response.headers["Cache-Control"] == "no-store" + assert ('a("http://localhost/hc/cloud/cloud.example/api/v4/' + + RESOURCE_KEY + '.json");') in text + assert ('b("http://localhost/hc/cloud/cloud.51degrees.com/api/v4/3pc");' + in text) + assert ('c("http://localhost/hc/cloud/cloud-eu.51degrees.com/api/v4/x");' + in text) + assert 'd("https://example.com/x");' in text + + +def test_script_is_asked_for_with_the_visitors_headers(cloud): + stub = cloud() + client_for().get( + "/hc/script.js", + headers={"User-Agent": DESKTOP_CHROME, "Cookie": "session=a-secret", + "Authorization": "Bearer a-secret"}, + **from_address(PUBLIC_ADDRESS)) + call = stub.calls[-1] + + assert call["method"] == "GET" + assert call["url"] == API + RESOURCE_KEY + ".js" + assert call["params"] == {"client-ip": PUBLIC_ADDRESS} + assert call["headers"] == {"user-agent": DESKTOP_CHROME} + + +def test_script_from_a_local_connection_names_no_address(cloud): + stub = cloud() + client_for().get("/hc/script.js", **from_address(LOCAL_ADDRESS)) + + assert stub.calls[-1]["params"] == {} + + +def test_script_from_a_private_http_cloud_is_pointed_here(cloud): + stub = cloud(api=PRIVATE_API) + stub.script = 'a("' + PRIVATE_API + RESOURCE_KEY + '.json");' + text = client_for(api=PRIVATE_API).get("/hc/script.js").get_data( + as_text=True) + + assert ('a("http://localhost/hc/cloud/127.0.0.1:18081/api/v4/' + + RESOURCE_KEY + '.json");') in text + + +def test_script_the_cloud_cannot_give_answers_502_with_no_script(cloud): + stub = cloud() + stub.instead[".js"] = requests.exceptions.ConnectionError( "The stand-in service cannot be reached.") - response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + response = client_for().get("/hc/script.js") + + assert response.status_code == 502 + assert response.get_data(as_text=True) == "" + + +# Server mode: the calls the client script makes. + +def test_test_answers_go_through_the_cloud_request_engine(cloud): + stub = cloud() + response = client_for().post( + "/hc/cloud/cloud.example/api/v4/" + RESOURCE_KEY + ".json", + headers={"User-Agent": DESKTOP_CHROME}, + data={"resource": "another-key", "values": "x", + "fod-test": "an-answer"}) + + assert response.status_code == 200 + assert response.headers["Cache-Control"] == "no-store" + assert response.get_json()["derived"]["humanconfidence"] == "Medium" + method, url, data = stub.requests[-1] + assert method == "POST" + assert url.split("?")[0] == API + RESOURCE_KEY + ".json" + # The engine sets the Resource Key. The browser's own resource and + # values fields are left out. + assert data == {"user-agent": DESKTOP_CHROME, "fod-test": "an-answer", + "resource": RESOURCE_KEY} + + +def test_call_to_a_host_that_is_not_a_cloud_host_is_not_found(cloud): + stub = cloud() + client = client_for() + asked = len(stub.requests) + + for method in ("get", "post"): + response = getattr(client, method)("/hc/cloud/example.com/x") + assert response.status_code == 404 + assert len(stub.requests) == asked + + +def test_get_to_a_cloud_host_is_sent_on_over_https(cloud): + stub = cloud() + stub.instead["https://cloud.51degrees.com/api/v4/3pc"] = StubResponse( + '{"tpc":true}', headers=[("Content-Type", "application/json")]) + response = client_for().get( + "/hc/cloud/cloud.51degrees.com/api/v4/3pc?a=1", + headers={"User-Agent": DESKTOP_CHROME}) + + assert response.status_code == 200 + assert response.get_json() == {"tpc": True} + call = stub.calls[-1] + assert call["url"] == "https://cloud.51degrees.com/api/v4/3pc" + assert dict(call["params"]) == {"a": "1"} + + +def test_get_to_a_private_http_cloud_keeps_its_scheme(cloud): + stub = cloud(api=PRIVATE_API) + stub.instead["3pc"] = StubResponse("{}") + response = client_for(api=PRIVATE_API).get( + "/hc/cloud/127.0.0.1:18081/api/v4/3pc") + + assert response.status_code == 200 + assert stub.calls[-1]["url"] == "http://127.0.0.1:18081/api/v4/3pc" + + +def test_get_passes_on_only_the_cloud_cookies(cloud): + stub = cloud() + stub.instead["3pc"] = StubResponse("{}") + client = client_for() + client.set_cookie("51D_id", "one") + client.set_cookie("session", "a-secret") + client.get("/hc/cloud/cloud.example/api/v4/3pc", + headers={"User-Agent": DESKTOP_CHROME}) + + assert stub.calls[-1]["headers"] == { + "user-agent": DESKTOP_CHROME, "Cookie": "51D_id=one"} + + +def test_get_gives_the_cloud_cookies_for_this_server(cloud): + stub = cloud() + stub.instead["3pc"] = StubResponse("{}", headers=[ + ("Set-Cookie", + "51D_tpc=1; Domain=51degrees.com; Path=/; Secure; SameSite=None"), + ("Set-Cookie", "51D_two=2; Path=/")]) + response = client_for().get("/hc/cloud/cloud.example/api/v4/3pc") + + assert response.headers.getlist("Set-Cookie") == [ + "51D_tpc=1; Path=/", "51D_two=2; Path=/"] + + +def test_get_the_cloud_cannot_answer_gives_502(cloud): + stub = cloud() + stub.instead["3pc"] = requests.exceptions.ConnectionError( + "The stand-in service cannot be reached.") + response = client_for().get("/hc/cloud/cloud.example/api/v4/3pc") assert response.status_code == 502 - assert "cannot be reached" in response.get_json()["error"] # The cloud address. @@ -393,6 +781,33 @@ def test_cloud_address_named_ends_in_one_slash(named): "https://cloud.example.test/api/v4/" +@pytest.mark.parametrize("host,matched", [ + ("cloud.51degrees.com", True), + ("cloud-eu.51degrees.com", True), + ("127.0.0.1:18081", True), + ("51degrees.com", False), + ("cloud.51degrees.com.example", False), + ("example.com", False)]) +def test_cloud_hosts_are_51degrees_hosts_and_the_endpoint_host( + host, matched): + hosts, _ = example.cloud_patterns(PRIVATE_API) + assert bool(hosts.fullmatch(host)) == matched + + +@pytest.mark.parametrize("address,public", [ + ("81.2.69.142", "81.2.69.142"), + ("::ffff:81.2.69.142", "81.2.69.142"), + ("127.0.0.1", None), + ("10.1.2.3", None), + ("192.168.1.2", None), + ("::1", None), + ("", None), + (None, None), + ("not-an-address", None)]) +def test_public_ip_gives_only_a_public_address(address, public): + assert example.public_ip(address) == public + + # Before the flow. class Started(Exception): @@ -402,14 +817,15 @@ class Started(Exception): @pytest.fixture def start(monkeypatch): """Runs main with the settings given and no others but the address of - the stand-in for the cloud service, with a stand-in for the web server, - and returns what create_app and run were given, or None when the server - was not started.""" + the stand-in for the cloud service, unless endpoint is None, with a + stand-in for the web server, and returns what create_app and run were + given, or None when the server was not started.""" - def run_main(argv=(), **settings): + def run_main(argv=(), endpoint=API, **settings): for name in SETTINGS: monkeypatch.delenv(name, raising=False) - monkeypatch.setenv(ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, API) + if endpoint is not None: + monkeypatch.setenv(ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, endpoint) for name, value in settings.items(): monkeypatch.setenv(name, value) given = {} @@ -448,11 +864,11 @@ def test_starts_when_the_key_carries_human_confidence(cloud, start, capsys): stub = cloud() given = start(**{ ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY, - ExampleUtils.LICENSE_KEY_ENV_VAR: LICENCE_KEY, + ExampleUtils.LICENSE_KEY_ENV_VAR: LICENSE_KEY, ExampleUtils.CLOUD_ENDPOINT_ENV_VAR: API.rstrip("/")}) - assert given["create_app"] == (RESOURCE_KEY, LICENCE_KEY, API) - assert given["run"] == {"port": 5151} + assert given["create_app"] == (RESOURCE_KEY, LICENSE_KEY, API) + assert given["run"] == {"port": 5151, "threaded": True} # The key was checked with the cloud named, before anything else. method, url, _ = stub.requests[0] assert method == "GET" @@ -460,13 +876,34 @@ def test_starts_when_the_key_carries_human_confidence(cloud, start, capsys): assert f"http://localhost:5151/, using {API}" in capsys.readouterr().out +def test_cloud_address_is_the_public_cloud_when_none_is_set(cloud, start): + stub = cloud(api=example.DEFAULT_API) + given = start(endpoint=None, + **{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + assert given["create_app"][2] == example.DEFAULT_API + assert stub.requests[0][1].startswith(example.DEFAULT_API) + + +def test_web_server_writes_no_line_for_each_request(cloud, start): + cloud() + server_log = logging.getLogger("werkzeug") + level = server_log.level + try: + start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + # The web server sets its own level to INFO only when none is set. + assert server_log.level == logging.WARNING + finally: + server_log.setLevel(level) + + def test_listens_on_the_port_named(cloud, start): cloud() given = start(**{ "_51DEGREES_EXAMPLE_HTTP_PORTS": "8080", ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) - assert given["run"] == {"port": 8080} + assert given["run"] == {"port": 8080, "threaded": True} def test_resource_key_can_be_the_first_argument(cloud, start): @@ -476,7 +913,7 @@ def test_resource_key_can_be_the_first_argument(cloud, start): assert given["create_app"][0] == RESOURCE_KEY -def test_starts_without_a_licence_key_and_says_so(cloud, start, capsys): +def test_starts_without_a_license_key_and_says_so(cloud, start, capsys): cloud() given = start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) @@ -535,6 +972,26 @@ def test_cloud_that_cannot_be_reached_ends_saying_so(cloud, start, capsys): assert_ends_with_find_out_more(printed) +@pytest.mark.parametrize("failure", [ + requests.exceptions.ConnectionError( + "Max retries exceeded with url: /api/v4/accessibleproperties" + "?resource=" + RESOURCE_KEY + " (cannot be reached)"), + StubResponse('{"errors":["The resource key ' + RESOURCE_KEY + + ' is not valid."]}', 400)], + ids=["unreachable", "refused"]) +def test_start_up_error_shows_the_resource_key_as_its_name( + cloud, start, capsys, failure): + stub = cloud() + stub.instead["accessibleproperties?resource=" + RESOURCE_KEY] = failure + + with pytest.raises(SystemExit): + start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + printed = capsys.readouterr().out + assert RESOURCE_KEY not in printed + assert "" in printed + + def test_property_is_found_whichever_product_holds_it(cloud): stub = cloud() stub.instead["accessibleproperties?resource=" + RESOURCE_KEY] = \ diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py index a8762b5b..16eb022d 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py @@ -37,27 +37,39 @@ def run_port(): - # The expression the example passes to run as its port. + # The expression the example passes to run as its port, and the value + # last given to each name before that call. with open(APP, encoding="utf-8") as source: tree = ast.parse(source.read()) + names = {} for node in ast.walk(tree): + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name): + names[target.id] = node.value if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "run"): for keyword in node.keywords: if keyword.arg == "port": - return keyword.value - return None + return keyword.value, names + return None, names class CloudHumanConfidenceWebPortTests(unittest.TestCase): def test_listens_on_5151_unless_port_names_another(self): - port = run_port() - # int() of the variable read from os.environ, or of 5151. + port, names = run_port() + # int() of the variable read from os.environ, or of 5151, either + # given directly or through a name assigned it. self.assertIsInstance(port, ast.Call) + self.assertEqual("int", port.func.id) get = port.args[0] + if isinstance(get, ast.Name): + get = names[get.id] + self.assertIsInstance(get, ast.Call) self.assertEqual("get", get.func.attr) + self.assertEqual("environ", get.func.value.attr) self.assertEqual( ["_51DEGREES_EXAMPLE_HTTP_PORTS", 5151], [arg.value for arg in get.args]) From 024e7427c1967376f35c4e87f6bff23936c151a1 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 24 Nov 2026 19:09:14 +0000 Subject: [PATCH 6/7] FIX: Show Unknown as given and a failed passive call as No result The web demo page showed Low for Unknown and for a passive call that gave no level. Unknown now shows as Unknown, in the neutral style. A passive answer that is not a level, a failed fetch, a client script that does not load and a failed redeem fetch show No result. A line under the table says that Active Low is also given when the sealed value cannot be redeemed. The /redeem route is unchanged, so a value that does not redeem still gives Low. At the 30 second limit the page shows No result only when no redeem is still running, so a redeem that is under way can still give its level. The live Basic key test no longer accepts an answer with no HumanConfidence. It asks the cloud whether the key carries the property. If it does, the passive answer must be a level. If it does not, the example must stop at start with the contact link. Offline tests run the live test against the stand-in cloud for a pass and a failure of each. --- .../cloud/humanconfidence_web/app.py | 6 +- .../humanconfidence_web/templates/index.html | 39 +++++++----- .../tests/test_cloud_humanconfidence_web.py | 28 ++++++--- .../test_cloud_humanconfidence_web_offline.py | 62 ++++++++++++++++++- 4 files changed, 107 insertions(+), 28 deletions(-) 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..11b82d9a 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 @@ -38,8 +38,8 @@ # 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. +# redeemed gives Active Low. When a call fails, or 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. @@ -333,7 +333,7 @@ def script(): except (requests.RequestException, CloudRequestException, ValueError): # An empty script with a failing status, so the page's script - # element fails and the page shows Active Low. + # element fails and the page shows No result for Active. return Response( "", status=502, content_type="application/javascript") here = request.host_url + "hc/cloud/" 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..4477d8cb 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 @@ -76,6 +76,8 @@

    Human Confidence demo

    +

    Active Low is also given when + the sealed value can't be redeemed. No result means no level arrived.

    Try it on your own site. Create a Resource Key in the 51Degrees Configurator.

    @@ -125,7 +127,7 @@

    Find out more

    // How long to wait for the browser tests' sealed value. var ACTIVE_LIMIT_MS = 30000; var CLASSES = { High: "c-eg-status--pass", Medium: "c-eg-status--part", - Low: "c-eg-status--fail" }; + Low: "c-eg-status--fail", Unknown: "c-eg-status--none" }; // Both rows show from the start, each with a running timer until its // level arrives, so it is clear something is happening. @@ -140,13 +142,15 @@

    Find out more

    } tick(); - // Shows a level, Low when there is none to show. + // Shows a level as the cloud gave it, Unknown included, or No result + // when there is none to show, as when a call failed. function show(id, level) { - if (LEVELS.indexOf(level) < 0) { level = "Low"; } + if (PLAIN.indexOf(level) < 0) { level = null; } shown[id] = true; var element = document.getElementById(id); - element.textContent = level; - element.className = "hc-level c-eg-status " + CLASSES[level]; + element.textContent = level || "No result"; + element.className = "hc-level c-eg-status " + + (level ? CLASSES[level] : "c-eg-status--none"); } // Form encoding with every character a shell treats specially escaped, @@ -287,17 +291,23 @@

    Find out more

    // 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; + var seen = null, latest = 0, redeeming = 0; function redeem(value) { var mine = ++latest; + redeeming++; + function done() { redeeming--; } var body = new URLSearchParams(); body.set("value", value); originalFetch("redeem", { method: "POST", body: body }) .then(function (r) { return r.json(); }) .then(function (answer) { + done(); if (mine === latest) { show("active", answer.humanConfidence); } }) - .catch(function () { if (mine === latest) { show("active", null); } }); + .catch(function () { + done(); + if (mine === latest) { show("active", null); } + }); } // The script's third party cookie check calls window.fodTpcEndpoint, or @@ -331,16 +341,13 @@

    Find out more

    }; document.head.appendChild(script); - // The browser tests take a few seconds. If no sealed value has come back - // by then, the answers didn't reach the cloud, so the timer stops and the - // row says so rather than running on, or showing a level for tests that - // didn't run. A sealed value that arrives later still replaces it. + // The browser tests take a few seconds. If no sealed value has arrived + // by then, the timer stops and the row says No result rather than + // running on, or showing a level for tests that didn't run. A redeem + // still on its way is left to give its level, and a sealed value that + // arrives later still replaces No result. setTimeout(function () { - if (shown.active) { return; } - shown.active = true; - var element = document.getElementById("active"); - element.textContent = "No result"; - element.className = "hc-level c-eg-status c-eg-status--none"; + if (!shown.active && !redeeming) { show("active", null); } }, ACTIVE_LIMIT_MS); })(); 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..3eea2d0d 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 @@ -28,7 +28,9 @@ The passive tests check that the example gives a level from the cloud's answer, and describes the request it sent. A Basic key, whose product does -not offer HumanConfidenceSource, is checked the same way. +not offer HumanConfidenceSource, gets a level when the cloud says it +carries HumanConfidence, and is otherwise given the contact link when the +example starts. Only the passive step is run here. The active step needs the browser tests, which only a browser runs. @@ -119,18 +121,28 @@ def test_passive_level_comes_from_the_cloud(client, key, api, assert answer["sent"]["url"] == api + key + ".json" -def test_a_basic_key_gets_a_passive_level(api, naming_the_properties): - """The Basic product does not offer HumanConfidenceSource, and the - passive call still works with its key.""" +def test_a_basic_key_gets_a_passive_level(api, naming_the_properties, + capsys): + """The Basic product does not offer HumanConfidenceSource. When the + cloud says its key carries HumanConfidence, the passive call gives a + level. When it says the key does not, the example ends at start with + the contact link, as a user running it with that key sees.""" basic = read_environment(BASIC_KEY_NAME) if not basic: pytest.skip( f"{BASIC_KEY_NAME} is not set. Set the variable to a Resource " "Key of the Basic product to check the passive call with it.") - client = example.create_app(basic, None, api).test_client() - answer = client.get("/passive", headers=HEADERS).get_json() - assert "error" not in answer, "The cloud refused the request." - assert answer["humanConfidence"] in LEVELS + (None,) + if example.carries_human_confidence(api, basic): + client = example.create_app(basic, None, api).test_client() + answer = client.get("/passive", headers=HEADERS).get_json() + assert "error" not in answer, "The cloud refused the request." + assert answer["humanConfidence"] in LEVELS + else: + with pytest.raises(SystemExit) as stopped: + example.main([basic]) + assert stopped.value.code == 1 + printed = capsys.readouterr().out + assert "Contact us: https://51degrees.com/contact-us" in printed def test_license_key_never_reaches_the_browser(client): 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..6994684e 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 @@ -271,6 +271,23 @@ def test_page_redeems_only_a_sealed_value_and_waits_30_seconds(cloud): assert "var ACTIVE_LIMIT_MS = 30000;" in html +def test_page_shows_no_result_for_a_failure_and_unknown_as_given(cloud): + cloud() + html = client_for().get("/").get_data(as_text=True) + + # Any answer that is not a level, such as an error, a failed call, or + # a script that didn't load, shows No result. Unknown shows as Unknown. + assert "if (PLAIN.indexOf(level) < 0) { level = null; }" in html + assert 'element.textContent = level || "No result";' in html + assert 'Unknown: "c-eg-status--none"' in html + assert 'script.onerror = function () { show("active", null); };' in html + # The page says what Active Low and No result mean. + assert 'id="levels-line">Active Low is also given when' in html + assert "No result means no level arrived." in html + # No result is not shown while a redeem is on its way. + assert "if (!shown.active && !redeeming)" in html + + # The mode. def test_mode_is_client_side_by_default_and_kept_in_a_cookie(cloud): @@ -494,12 +511,55 @@ def test_the_live_basic_key_test_skips_naming_its_variable(monkeypatch): monkeypatch.delenv(live.BASIC_KEY_NAME, raising=False) with pytest.raises(pytest.skip.Exception) as skipped: - live.test_a_basic_key_gets_a_passive_level(API, None) + live.test_a_basic_key_gets_a_passive_level(API, None, None) assert live.BASIC_KEY_NAME == "_51DEGREES_RESOURCE_KEY_BASIC" assert f"{live.BASIC_KEY_NAME} is not set" in str(skipped.value) +@pytest.fixture +def basic_key(cloud, monkeypatch): + """Sets the Basic key variable and the address of the stand-in for the + cloud service, as the live Basic key test reads them.""" + monkeypatch.setenv(live.BASIC_KEY_NAME, RESOURCE_KEY) + monkeypatch.setenv(ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, API) + monkeypatch.delenv(ExampleUtils.LICENSE_KEY_ENV_VAR, raising=False) + return cloud + + +# The live Basic key test passes only on a level, or, for a key that does +# not carry HumanConfidence, on the contact link the example gives. +def test_the_live_basic_key_test_passes_on_a_level(basic_key, capsys): + basic_key() + + live.test_a_basic_key_gets_a_passive_level(API, None, capsys) + + +def test_the_live_basic_key_test_fails_on_no_level(basic_key, capsys): + stub = basic_key() + stub.instead[".json"] = StubResponse({"derived": { + "humanconfidence": None, "humanconfidencesource": None}}) + + with pytest.raises(AssertionError): + live.test_a_basic_key_gets_a_passive_level(API, None, capsys) + + +def test_the_live_basic_key_test_passes_on_the_contact_link( + basic_key, capsys): + basic_key(properties=("IsMobile",)) + + live.test_a_basic_key_gets_a_passive_level(API, None, capsys) + + +def test_the_live_basic_key_test_fails_on_no_contact_link( + basic_key, capsys, monkeypatch): + basic_key(properties=("IsMobile",)) + monkeypatch.setattr(example, "main", lambda argv: None) + + with pytest.raises(pytest.fail.Exception): + live.test_a_basic_key_gets_a_passive_level(API, None, capsys) + + def test_passive_says_what_the_cloud_refused(cloud): stub = cloud() stub.instead[".json"] = StubResponse( From 4daa4eb59fd2447eccb8e156516d5c4e241146c7 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 24 Nov 2026 19:13:23 +0000 Subject: [PATCH 7/7] FIX: Give no level when the redeem call fails, and check Basic keys The /redeem route gave Low for every failure, so a cloud without the redeem call showed Active Low on every visit. Low is now given only when the cloud answers 200 or 400 with no level, which is how it refuses a sealed value. Any other answer, or none at all, gives no level, and the page shows No result, as the .NET and Rust examples do. The page also stops waiting for /redeem after 15 seconds. The comments, the start-up message and the line under the table say the same. The live Basic key test makes the passive call itself, naming HumanConfidence and HumanConfidenceSource, as the .NET and Rust live tests do. It expects humanconfidencesource to be present and null and humanconfidencesourcenullreason to be a string. The passive level test accepts only High, Medium and Low, also as in .NET and Rust. Offline tests run the Basic key test against the stand-in cloud. --- .../cloud/humanconfidence_web/app.py | 34 ++++-- .../humanconfidence_web/templates/index.html | 9 +- .../tests/test_cloud_humanconfidence_web.py | 62 ++++++----- .../test_cloud_humanconfidence_web_offline.py | 102 ++++++++++++------ 4 files changed, 139 insertions(+), 68 deletions(-) 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 11b82d9a..54c9bed5 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 @@ -37,9 +37,10 @@ # 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. When a call fails, or no sealed value -# arrives within 30 seconds, the page says No result. +# offers the redeem call (POST hc/redeem). A sealed value the cloud +# refuses gives Active Low. When a call fails, the cloud doesn't offer +# redeem, or 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. @@ -103,9 +104,15 @@ MODES = ("client", "server") MODE_COOKIE = "hc_mode" -# The levels, highest first. A level the cloud doesn't give is the last. +# The levels, highest first. A sealed value the cloud refuses gets the +# last. LEVELS = ("High", "Medium", "Low") +# The statuses of a redeem answer that are the cloud's verdict on the +# sealed value: redeemed, or refused as expired, replayed or unreadable. +# Any other status means the redeem didn't happen. +REDEEM_ANSWERED = (200, 400) + # 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" @@ -297,8 +304,10 @@ def passive(): # 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. + # the cloud refuses gives Low, as nothing then shows a person is there. + # When the cloud can't be reached, doesn't offer redeem or gives an + # answer that isn't JSON, there is no level, and the page says No + # result. The cloud's own answer is never sent back. @app.route("/redeem", methods=["POST"]) def redeem(): @@ -306,13 +315,17 @@ def redeem(): 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") + if answer.status_code not in REDEEM_ANSWERED: + return jsonify(humanConfidence=None) + verdict = answer.json() except (requests.RequestException, ValueError): - pass + return jsonify(humanConfidence=None) + if not isinstance(verdict, dict): + return jsonify(humanConfidence=None) + level = read(verdict, "humanConfidence") if level not in LEVELS: level = LEVELS[-1] return jsonify(humanConfidence=level) @@ -516,7 +529,8 @@ def main(argv): if not license_key.strip(): print(f"No {ExampleUtils.LICENSE_KEY_ENV_VAR} set. The page still " "shows Passive and Active, but an account that holds License " - "Keys can't redeem without one, so Active will show Low.") + "Keys can't redeem without one, so Active will show Low or No " + "result.") app = create_app(resource_key, license_key, api) port = os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151) 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 4477d8cb..87b72dfb 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 @@ -77,7 +77,7 @@

    Human Confidence demo

    Active Low is also given when - the sealed value can't be redeemed. No result means no level arrived.

    + the cloud refuses the sealed value. No result means no level arrived.

    Try it on your own site. Create a Resource Key in the 51Degrees Configurator.

    @@ -126,6 +126,8 @@

    Find out more

    var PLAIN = LEVELS.concat(["Unknown"]); // How long to wait for the browser tests' sealed value. var ACTIVE_LIMIT_MS = 30000; + // How long to wait for this server to answer a redeem. + var REDEEM_LIMIT_MS = 15000; var CLASSES = { High: "c-eg-status--pass", Medium: "c-eg-status--part", Low: "c-eg-status--fail", Unknown: "c-eg-status--none" }; @@ -298,7 +300,10 @@

    Find out more

    function done() { redeeming--; } var body = new URLSearchParams(); body.set("value", value); - originalFetch("redeem", { method: "POST", body: body }) + var abort = new AbortController(); + setTimeout(function () { abort.abort(); }, REDEEM_LIMIT_MS); + originalFetch("redeem", { method: "POST", body: body, + signal: abort.signal }) .then(function (r) { return r.json(); }) .then(function (answer) { done(); 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 3eea2d0d..89f5ea27 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 @@ -27,10 +27,9 @@ tests skip themselves when no key is set or the key does not carry it. The passive tests check that the example gives a level from the cloud's -answer, and describes the request it sent. A Basic key, whose product does -not offer HumanConfidenceSource, gets a level when the cloud says it -carries HumanConfidence, and is otherwise given the contact link when the -example starts. +answer, and describes the request it sent. A key outside the Bespoke +product, read from the Basic key variable, is checked to get no +HumanConfidenceSource, with the reason the cloud gives. Only the passive step is run here. The active step needs the browser tests, which only a browser runs. @@ -52,9 +51,8 @@ HEADERS = {"User-Agent": DESKTOP_CHROME} -# Every value the property has. Unknown is the one the cloud gives when it -# has too little to rate the request. -LEVELS = ("High", "Medium", "Low", "Unknown") +# The levels a passive answer gives. +LEVELS = ("High", "Medium", "Low") # The variable holding a resource key of the Basic product. BASIC_KEY_NAME = "_51DEGREES_RESOURCE_KEY_BASIC" @@ -121,28 +119,44 @@ def test_passive_level_comes_from_the_cloud(client, key, api, assert answer["sent"]["url"] == api + key + ".json" -def test_a_basic_key_gets_a_passive_level(api, naming_the_properties, - capsys): - """The Basic product does not offer HumanConfidenceSource. When the - cloud says its key carries HumanConfidence, the passive call gives a - level. When it says the key does not, the example ends at start with - the contact link, as a user running it with that key sees.""" +def test_a_key_outside_bespoke_gets_no_source(api): + """A key outside the Bespoke product, here a Basic key, is answered + with HumanConfidenceSource present and null, and a reason that says + why, when the passive call names both properties.""" basic = read_environment(BASIC_KEY_NAME) if not basic: pytest.skip( f"{BASIC_KEY_NAME} is not set. Set the variable to a Resource " "Key of the Basic product to check the passive call with it.") - if example.carries_human_confidence(api, basic): - client = example.create_app(basic, None, api).test_client() - answer = client.get("/passive", headers=HEADERS).get_json() - assert "error" not in answer, "The cloud refused the request." - assert answer["humanConfidence"] in LEVELS - else: - with pytest.raises(SystemExit) as stopped: - example.main([basic]) - assert stopped.value.code == 1 - printed = capsys.readouterr().out - assert "Contact us: https://51degrees.com/contact-us" in printed + + def redact(text): + return str(text).replace(basic, "") + + failure = None + try: + answer = requests.request( + "POST", api + basic + ".json", + data={"user-agent": DESKTOP_CHROME, "values": PROPERTIES}, + timeout=example.TIMEOUT) + except requests.RequestException as error: + failure = "The passive call failed: " + redact(error) + if failure: + pytest.fail(failure) + assert answer.status_code == 200, ( + "The passive call did not succeed: " + redact(answer.text)) + derived = answer.json().get("derived") + assert isinstance(derived, dict), ( + "The answer has no derived object: " + redact(answer.text)) + assert "humanconfidencesource" in derived, ( + "The answer has no humanconfidencesource at all, so this cloud " + "does not serve HumanConfidenceSource: " + redact(derived)) + assert derived["humanconfidencesource"] is None, ( + "A key outside the Bespoke product should get a null " + "humanconfidencesource, but the answer has " + + redact(derived["humanconfidencesource"]) + ".") + assert isinstance(derived.get("humanconfidencesourcenullreason"), str), ( + "The null humanconfidencesource has no string " + "humanconfidencesourcenullreason: " + redact(derived)) def test_license_key_never_reaches_the_browser(client): 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 6994684e..26c2e10d 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 @@ -284,8 +284,11 @@ def test_page_shows_no_result_for_a_failure_and_unknown_as_given(cloud): # The page says what Active Low and No result mean. assert 'id="levels-line">Active Low is also given when' in html assert "No result means no level arrived." in html - # No result is not shown while a redeem is on its way. + # No result is not shown while a redeem is on its way, and a redeem + # that this server doesn't answer in 15 seconds is given up. assert "if (!shown.active && !redeeming)" in html + assert "var REDEEM_LIMIT_MS = 15000;" in html + assert "signal: abort.signal" in html # The mode. @@ -511,7 +514,7 @@ def test_the_live_basic_key_test_skips_naming_its_variable(monkeypatch): monkeypatch.delenv(live.BASIC_KEY_NAME, raising=False) with pytest.raises(pytest.skip.Exception) as skipped: - live.test_a_basic_key_gets_a_passive_level(API, None, None) + live.test_a_key_outside_bespoke_gets_no_source(API) assert live.BASIC_KEY_NAME == "_51DEGREES_RESOURCE_KEY_BASIC" assert f"{live.BASIC_KEY_NAME} is not set" in str(skipped.value) @@ -519,45 +522,60 @@ def test_the_live_basic_key_test_skips_naming_its_variable(monkeypatch): @pytest.fixture def basic_key(cloud, monkeypatch): - """Sets the Basic key variable and the address of the stand-in for the - cloud service, as the live Basic key test reads them.""" + """Sets the Basic key variable, as the live Basic key test reads it.""" monkeypatch.setenv(live.BASIC_KEY_NAME, RESOURCE_KEY) - monkeypatch.setenv(ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, API) - monkeypatch.delenv(ExampleUtils.LICENSE_KEY_ENV_VAR, raising=False) return cloud -# The live Basic key test passes only on a level, or, for a key that does -# not carry HumanConfidence, on the contact link the example gives. -def test_the_live_basic_key_test_passes_on_a_level(basic_key, capsys): - basic_key() +NO_SOURCE = { + "humanconfidence": "Medium", + "humanconfidencesource": None, + "humanconfidencesourcenullreason": + "The key does not give this property a value."} - live.test_a_basic_key_gets_a_passive_level(API, None, capsys) - -def test_the_live_basic_key_test_fails_on_no_level(basic_key, capsys): +def test_the_live_basic_key_test_passes_on_no_source(basic_key): stub = basic_key() - stub.instead[".json"] = StubResponse({"derived": { - "humanconfidence": None, "humanconfidencesource": None}}) + stub.instead[".json"] = StubResponse({"derived": NO_SOURCE}) - with pytest.raises(AssertionError): - live.test_a_basic_key_gets_a_passive_level(API, None, capsys) + live.test_a_key_outside_bespoke_gets_no_source(API) + method, url, data = stub.requests[-1] + assert (method, url) == ("POST", API + RESOURCE_KEY + ".json") + assert data["values"] == live.PROPERTIES -def test_the_live_basic_key_test_passes_on_the_contact_link( - basic_key, capsys): - basic_key(properties=("IsMobile",)) - live.test_a_basic_key_gets_a_passive_level(API, None, capsys) +# The live Basic key test fails on any answer but a null source with a +# reason, and never names the key. +@pytest.mark.parametrize("answer", [ + StubResponse({"derived": dict( + NO_SOURCE, humanconfidencesource="Passive")}), + StubResponse({"derived": {"humanconfidence": "Medium"}}), + StubResponse({"derived": dict(NO_SOURCE, + humanconfidencesourcenullreason=None)}), + StubResponse({"device": {}}), + StubResponse('{"errors":["The key ' + RESOURCE_KEY + ' is not valid."]}', + 400), +], ids=["a-source", "no-source", "no-reason", "no-derived", "refused"]) +def test_the_live_basic_key_test_fails_on_any_other_answer(basic_key, answer): + stub = basic_key() + stub.instead[".json"] = answer + with pytest.raises(AssertionError) as failed: + live.test_a_key_outside_bespoke_gets_no_source(API) -def test_the_live_basic_key_test_fails_on_no_contact_link( - basic_key, capsys, monkeypatch): - basic_key(properties=("IsMobile",)) - monkeypatch.setattr(example, "main", lambda argv: None) + assert RESOURCE_KEY not in str(failed.value) - with pytest.raises(pytest.fail.Exception): - live.test_a_basic_key_gets_a_passive_level(API, None, capsys) + +def test_the_live_basic_key_test_fails_on_no_answer(basic_key): + stub = basic_key() + stub.instead[".json"] = requests.exceptions.ConnectionError( + "Max retries exceeded with url: /api/v4/" + RESOURCE_KEY + ".json") + + with pytest.raises(pytest.fail.Exception) as failed: + live.test_a_key_outside_bespoke_gets_no_source(API) + + assert RESOURCE_KEY not in str(failed.value) def test_passive_says_what_the_cloud_refused(cloud): @@ -613,24 +631,44 @@ def test_redeem_without_a_license_key_sends_none(cloud): assert stub.requests[-1][2] == {"value": "a-sealed-value"} +# The cloud answered and refused the sealed value, or answered with no +# level, so nothing shows a person is there. @pytest.mark.parametrize("answer", [ StubResponse('{"result":"expired"}', 400), StubResponse('{"result":"unreadable"}', 400), - StubResponse("Not Found", 404), + StubResponse('{"result":"replayed"}'), StubResponse('{"humanConfidence":"Unknown"}'), StubResponse('{"humanConfidence":"a-sealed-value"}'), +], ids=["expired", "unreadable", "replayed", "unknown", "not-a-level"]) +def test_value_the_cloud_refuses_gives_low(cloud, answer): + stub = cloud() + stub.instead["hc/redeem"] = answer + response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + + assert response.status_code == 200 + assert response.get_json() == {"humanConfidence": "Low"} + + +# The redeem didn't happen, so there is no level and the page says No +# result. +@pytest.mark.parametrize("answer", [ + StubResponse("Not Found", 404), + StubResponse({"errors": ["'redeem' method not found"]}, 404), + StubResponse('{"errors":["The service is not available."]}', 503), + StubResponse("An error page"), + StubResponse('["High"]'), 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", - "unreachable", "timeout"]) -def test_value_that_does_not_redeem_gives_low(cloud, answer): +], ids=["not-offered", "not-offered-json", "unavailable", "not-json", + "not-an-object", "unreachable", "timeout"]) +def test_redeem_that_does_not_happen_gives_no_level(cloud, answer): stub = cloud() stub.instead["hc/redeem"] = answer response = client_for().post("/redeem", data={"value": "a-sealed-value"}) assert response.status_code == 200 - assert response.get_json() == {"humanConfidence": "Low"} + assert response.get_json() == {"humanConfidence": None} @pytest.mark.parametrize("answer", [