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..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 @@ -29,22 +29,34 @@ # 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. Redeeming needs a cloud that +# 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. +# +# 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 +68,27 @@ # 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 logging 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_cloudrequestengine.cloudrequestexception import \ + CloudRequestException +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_pipeline_examples.example_utils import ExampleUtils @@ -81,6 +100,44 @@ # 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 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" + + +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. +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,34 +205,84 @@ 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 # is at /css, as in the other web examples. app = Flask(__name__, static_url_path="") - - # 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] + cloud_host, cloud_url = cloud_patterns(api) + endpoint = urllib.parse.urlsplit(api) + + # 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(): + # 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} + + 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() + if name != "client-ip"} + for name, value in fields: + if name.lower() not in ("resource", "values", "client-ip"): + evidence["query." + name] = value + 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-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": [[name, value] for name, value + in engine.get_content(flowdata).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 +295,147 @@ 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 + # 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(): - fields = {"value": request.form.get("value", "")} + sealed = request.form.get("value", "") + fields = {"value": sealed} if license_key: fields["license"] = license_key try: answer = requests.request( "POST", api + "hc/redeem", data=fields, timeout=TIMEOUT) - except requests.RequestException as error: + if answer.status_code not in REDEEM_ANSWERED: + return jsonify(humanConfidence=None) + verdict = answer.json() + except (requests.RequestException, ValueError): + 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) + + # 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, CloudRequestException, + ValueError): + # An empty script with a failing status, so the page's script + # element fails and the page shows No result for Active. + return Response( + "", 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) + 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 + # 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 + cookies = "; ".join( + f"{name}={value}" for name, value in request.cookies.items() + if name.lower().startswith(COOKIE_PREFIX)) + 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, CloudRequestException) 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 +450,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): """! @@ -263,6 +482,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 @@ -284,7 +517,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: @@ -296,13 +529,17 @@ 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 or No " + "result.") 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}") - 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..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 @@ -21,69 +21,85 @@ * 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
+

Active Low is also given when + 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.

-

+

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,109 +114,246 @@

    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"; + // Server side, the script's calls to the cloud go to + // /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"]); + // 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" }; - 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 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 (PLAIN.indexOf(level) < 0) { level = null; } + shown[id] = true; var element = document.getElementById(id); - element.textContent = text; - element.className = cls; + element.textContent = level || "No result"; + element.className = "hc-level c-eg-status " + + (level ? CLASSES[level] : "c-eg-status--none"); } - 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"; }); + } + // 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; + 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, redeeming = 0; function redeem(value) { + var mine = ++latest; + redeeming++; + function done() { redeeming--; } var body = new URLSearchParams(); body.set("value", value); - return fetch("redeem", { method: "POST", body: body }) - .then(function (r) { return r.json(); }); - } - - 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); - } + 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(); + if (mine === latest) { show("active", answer.humanConfidence); } + }) + .catch(function () { + done(); + if (mine === latest) { show("active", null); } + }); } - // 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; + // 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); } - 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); + + // 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 && !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 6ab34396..d8622da6 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,12 @@ 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 test checks that the example gives a level from the cloud's +answer, and describes the request it sent. The example gives no source, +so the test reads HumanConfidenceSource from the cloud's own answer, and +the Bespoke key gets Passive, as no browser tests have run. A key outside +the Bespoke product, read from the Basic key variable, is checked to get +no HumanConfidenceSource, with the reason the cloud gives. The production cloud does not serve HumanConfidenceSource yet, so the two tests that check it are marked staging and call the staging cloud that @@ -59,9 +61,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" @@ -106,7 +107,8 @@ def naming_the_properties(monkeypatch): answers = [] def request(method, url, data=None, **kwargs): - named = method == "POST" and url.endswith(".json") + # The cloud request engine adds "?" to the address it posts to. + named = method == "POST" and url.split("?")[0].endswith(".json") if named: data = dict(data or {}, values=PROPERTIES) response = real(method, url, data=data, **kwargs) @@ -140,12 +142,17 @@ def staging_api(): @pytest.fixture(scope="module") -def staging_client(staging_api): - staging_key = read_environment(STAGING_KEY_NAME) - if not staging_key: +def staging_key(): + resource_key = read_environment(STAGING_KEY_NAME) + if not resource_key: pytest.skip( f"{STAGING_KEY_NAME} is not set. Set it to a Bespoke resource " "key the staging cloud knows.") + return resource_key + + +@pytest.fixture(scope="module") +def staging_client(staging_api, staging_key): if not example.carries_human_confidence(staging_api, staging_key): pytest.skip( f"The key in {STAGING_KEY_NAME} does not carry HumanConfidence " @@ -163,50 +170,73 @@ def test_page_is_served_and_never_kept(client, key): @pytest.mark.staging def test_passive_source_and_level_come_from_the_cloud( - staging_client, naming_the_properties): + staging_client, staging_api, staging_key, naming_the_properties): + """The example gives the level from the cloud's answer and describes + the request it sent. The example gives no source, so the source is read + from the cloud's own answer, and is Passive, as no browser tests have + run.""" answer = staging_client.get("/passive", headers=HEADERS).get_json() - assert "error" not in answer, answer - assert answer["source"] == "Passive", answer - assert answer["humanConfidence"] in LEVELS + assert "error" not in answer, "The cloud refused the request." + assert answer["humanConfidence"] in LEVELS, answer["humanConfidence"] + # Compared apart from the assert, so a failure does not print the key. + described = answer["sent"]["url"] == staging_api + staging_key + ".json" + assert described, "The example described another address." + + assert naming_the_properties, "The example did not ask the cloud." + derived = naming_the_properties[-1].json().get("derived") or {} + assert derived.get("humanconfidencesource") == "Passive", ( + derived.get("humanconfidencesource")) @pytest.mark.staging -def test_a_basic_key_gets_no_source(staging_api, naming_the_properties): - """The Basic product does not offer HumanConfidenceSource, so the cloud - answers the property with no value and the reason, and the example - gives no source.""" +def test_a_key_outside_bespoke_gets_no_source(staging_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. The Basic product does not offer " - "HumanConfidenceSource. Set the variable to a Basic resource " - "key to check that such a key gets no source.") - client = example.create_app(basic, None, staging_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 - - # The example gives no source for a property the cloud left out too, - # so the cloud's own answer must name the property, with no value and - # a reason. - assert naming_the_properties, "The example did not ask the cloud." - derived = naming_the_properties[-1].json().get("derived") or {} + 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.") + + def redact(text): + return str(text).replace(basic, "") + + failure = None + try: + answer = requests.request( + "POST", staging_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 cloud's answer leaves out humanconfidencesource, so it says " - "nothing about what the Basic product offers.") + "The answer has no humanconfidencesource at all, so this cloud " + "does not serve HumanConfidenceSource: " + redact(derived)) assert derived["humanconfidencesource"] is None, ( - derived["humanconfidencesource"]) - assert isinstance( - derived.get("humanconfidencesourcenullreason"), str), ( - "The cloud gave no humanconfidencesourcenullreason.") + "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_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..00f9f636 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 bare == RESOURCE_KEY + ".js": + return StubResponse(self.script, url=url, headers=[ + ("Content-Type", "application/javascript")]) - if path == "hc/redeem": + 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().get("/") - assert stub.requests == [] + client_for() + assert [(method, url) for method, url, _ in stub.requests] == [ + ("GET", API + "accessibleProperties?resource=" + RESOURCE_KEY), + ("GET", API + "evidencekeys")] -def test_licence_key_never_reaches_the_page(cloud): + +def test_page_is_served_without_asking_the_cloud_again(cloud): + stub = cloud() + client = client_for() + asked = len(stub.requests) + client.get("/") + + assert len(stub.requests) == asked + + +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,77 @@ 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 + + +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, 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. + +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 +342,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_address_of_the_connection_replaces_one_a_header_names(cloud): +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_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 +505,88 @@ 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_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) - assert ("The Basic product does not offer HumanConfidenceSource" - in str(skipped.value)) + + +@pytest.fixture +def basic_key(cloud, monkeypatch): + """Sets the Basic key variable, as the live Basic key test reads it.""" + monkeypatch.setenv(live.BASIC_KEY_NAME, RESOURCE_KEY) + return cloud + + +NO_SOURCE = { + "humanconfidence": "Medium", + "humanconfidencesource": None, + "humanconfidencesourcenullreason": + "The key does not give this property a value."} + + +def test_the_live_basic_key_test_passes_on_no_source(basic_key): + stub = basic_key() + stub.instead[".json"] = StubResponse({"derived": NO_SOURCE}) + + 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 + + +# 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) + + assert RESOURCE_KEY not in str(failed.value) + + +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) + + +# The Cloud Human Confidence workflow runs only the tests marked staging, +# and fails when none runs, so both live tests of the source carry the +# mark. +@pytest.mark.parametrize("test", [ + live.test_passive_source_and_level_come_from_the_cloud, + live.test_a_key_outside_bespoke_gets_no_source, +], ids=["bespoke", "basic"]) +def test_the_live_source_tests_are_marked_staging(test): + assert "staging" in [mark.name for mark in test.pytestmark] def test_passive_says_what_the_cloud_refused(cloud): @@ -301,7 +595,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 +608,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 +642,236 @@ 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): +# 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('{"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"] = 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"} + + +# 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=["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": None} -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") + + printed = capsys.readouterr() + assert printed.out == "" + assert printed.err == "" + + +def test_redeem_waits_the_example_timeout(cloud): + stub = cloud() + 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 response.get_json() == { - "error": f"The service at {API} doesn't redeem Human Confidence."} + 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_redeem_answers_502_when_the_cloud_cannot_be_reached(cloud): +def test_script_from_a_local_connection_names_no_address(cloud): stub = cloud() - stub.instead["hc/redeem"] = requests.exceptions.ConnectionError( + 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 +890,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 +926,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 +973,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 +985,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 +1022,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 +1081,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])