Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@
# 1. Passive. This server asks the cloud with the visitor's request headers
# and IP address, and gets a plain level.
# 2. Active. The 51Degrees client script runs the browser tests and sends
# the answers to the cloud, which answers with a sealed value. This
# server redeems the sealed value with the License Key, which the
# browser never sees, and gets the level. Redeeming needs a cloud that
# offers the redeem call (POST hc/redeem). A sealed value that can't be
# redeemed gives Active Low, and if no sealed value arrives within 30
# seconds the page says No result.
# the answers to the cloud, which answers with a sealed value. The page
# sends the sealed value to this server, where the cloud request engine
# redeems it with the License Key, which the browser never sees. The
# example reads HumanConfidence and HumanConfidenceSource and nothing
# more. A sealed value that can't be redeemed gives Active Low, and if
# no sealed value arrives within 30 seconds the page says No result.
#
# The Resource Key is put in the page, as the 51Degrees client script is
# loaded with it. The License Key stays on this server.
Expand Down Expand Up @@ -83,6 +83,7 @@
from flask import Flask, Response, abort, jsonify, make_response
from flask import render_template, request

from fiftyone_pipeline_cloudrequestengine.cloudengine import CloudEngine
from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \
CloudRequestEngine
from fiftyone_pipeline_cloudrequestengine.cloudrequestexception import \
Expand All @@ -103,9 +104,6 @@
MODES = ("client", "server")
MODE_COOKIE = "hc_mode"

# The levels, highest first. A level the cloud doesn't give is the last.
LEVELS = ("High", "Medium", "Low")

# The 51Degrees cloud hosts. The host of the endpoint in use, such as a
# private cloud in Docker, counts as a cloud host too.
CLOUD_HOSTS = r"cloud[a-z0-9-]*\.51degrees\.com"
Expand Down Expand Up @@ -220,6 +218,25 @@ def create_app(resource_key, license_key, api):
pipeline = PipelineBuilder({"add_javascript_builder": False}).add(
engine).build()

# A second pipeline for the active level, whose engine carries the
# License Key, so only this pipeline sends it. It takes what the first
# engine discovered, so building it asks the cloud nothing more. Its
# engine gives each page a challenge and redeems the sealed value the
# page sends back. The cloud engine for "derived" gives the two
# properties the page shows.
active_engine = CloudRequestEngine({
"resource_key": resource_key,
"license_key": license_key,
"cloud_endpoint": api,
"timeout_seconds": TIMEOUT,
"discovery_state": engine.discovery_state()})
derived = CloudEngine()
derived.datakey = "derived"
active_pipeline = PipelineBuilder({
"add_javascript_builder": False,
"suppress_process_exceptions": True}).add(active_engine).add(
derived).build()

def visitor_headers():
# The request headers the cloud reads, from the evidence keys the
# engine was given. Only these are passed on, so headers such as
Expand Down Expand Up @@ -273,8 +290,12 @@ def index():
mode = request.cookies.get(MODE_COOKIE)
if mode not in MODES:
mode = MODES[0]
# Each page load gets its own challenge, which the page sends to
# the cloud with the browser tests, and a page value it sends back
# with the sealed value.
response = make_response(render_template(
"index.html", resource_key=resource_key, api=api, mode=mode))
"index.html", resource_key=resource_key, api=api, mode=mode,
hc=active_engine.human_confidence_page_values()))
response.set_cookie(MODE_COOKIE, mode, samesite="Lax")
# The page must never come from a cache, as each load runs the
# tests.
Expand All @@ -295,27 +316,28 @@ def passive():
except Exception as error:
return jsonify(error=str(error))

# Redeem: the page, or a terminal, sends a sealed value, and this server
# redeems it with the License Key. Only the level goes back. A value
# that doesn't redeem gives Low, as nothing then shows a person is
# there. The cloud's own answer is never sent back.
@app.route("/redeem", methods=["POST"])
def redeem():

sealed = request.form.get("value", "")
fields = {"value": sealed}
if license_key:
fields["license"] = license_key
level = None
try:
answer = requests.request(
"POST", api + "hc/redeem", data=fields, timeout=TIMEOUT)
level = read(answer.json(), "humanConfidence")
except (requests.RequestException, ValueError):
pass
if level not in LEVELS:
level = LEVELS[-1]
return jsonify(humanConfidence=level)
# Active: the page, or a terminal, sends the sealed value as
# humanconfidence, with its page value as humanconfidencepage. The
# cloud request engine redeems it, and the example reads the two
# properties. A sealed value that doesn't redeem gives Low.
@app.route("/active", methods=["POST"])
def active():

if not request.form.get("humanconfidence"):
abort(400)
flowdata = active_pipeline.create_flowdata()
for name, value in visitor_headers().items():
if name != "client-ip":
flowdata.evidence.add("header." + name, value)
for name in ("humanconfidence", "humanconfidencepage"):
flowdata.evidence.add(
"query." + name, request.form.get(name, ""))
flowdata.process()
derived = flowdata.get("derived")
return jsonify(
humanConfidence=derived.get("humanconfidence").value(),
humanConfidenceSource=derived.get(
"humanconfidencesource").value())

# Server mode: the client script, fetched from the cloud for this
# visitor, with every cloud address in it pointed at this server.
Expand All @@ -324,6 +346,10 @@ def script():

try:
query = {}
# The page's challenge, which the cloud seals the result to.
challenge = request.args.get("challenge")
if challenge:
query["challenge"] = challenge
address = public_ip(request.remote_addr)
if address:
query["client-ip"] = address
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,12 @@ <h3 class="c-eg-page__heading">Find out more</h3>
var API = {{ api|tojson }};
var API_ORIGIN = new URL(API).origin;
var MODE = {{ mode|tojson }};
// This server's redeem route, which holds the License Key.
var REDEEM = location.origin + "/redeem";
// This server's route for the active level, whose cloud request engine
// redeems the sealed value with the License Key.
var ACTIVE = location.origin + "/active";
// The challenge this server gave the page, which the 51Degrees script
// sends to the cloud, and the page value the sealed value goes back with.
var HC = {{ hc|tojson }};
// Server side, the script's calls to the cloud go to
// /hc/cloud/<host>/<path> here.
var FORWARD = /^https?:\/\/[^\/]+\/hc\/cloud\/([^\/]+)\/(.*)$/;
Expand Down Expand Up @@ -170,8 +174,10 @@ <h3 class="c-eg-page__heading">Find out more</h3>
active: function (url, pairs) {
return "$v = (" + post("curl.exe", url, pairs) +
" | ConvertFrom-Json).derived.humanconfidence; \"Active \" + (" +
"curl.exe -s -X POST \"" + REDEEM + "\" --data-urlencode " +
"\"value=$v\" | ConvertFrom-Json).humanConfidence";
"curl.exe -s -X POST \"" + ACTIVE + "\" --data-urlencode " +
"\"humanconfidence=$v\" --data \"humanconfidencepage=" +
encode(HC.humanconfidencepage) +
"\" | ConvertFrom-Json).humanConfidence";
}
},
sh: {
Expand All @@ -182,7 +188,9 @@ <h3 class="c-eg-page__heading">Find out more</h3>
active: function (url, pairs) {
return "v=$(" + post("curl", url, pairs) + " | " + PY +
"['derived']['humanconfidence'])\"); printf 'Active '; " +
"curl -s -X POST \"" + REDEEM + "\" --data-urlencode \"value=$v\"" +
"curl -s -X POST \"" + ACTIVE + "\" --data-urlencode " +
"\"humanconfidence=$v\" --data \"humanconfidencepage=" +
encode(HC.humanconfidencepage) + "\"" +
" | " + PY + "['humanConfidence'])\"";
}
}
Expand Down Expand Up @@ -285,19 +293,18 @@ <h3 class="c-eg-page__heading">Find out more</h3>
return originalFetch.apply(this, arguments);
};

// Active. Each new sealed value goes to this server to redeem, and only
// the answer for the newest one is shown.
var seen = null, latest = 0;
// Active. The first sealed value goes to this server with the page
// value, as the challenge it was sealed to is used once, and the level
// that comes back is shown.
var seen = null;
function redeem(value) {
var mine = ++latest;
var body = new URLSearchParams();
body.set("value", value);
originalFetch("redeem", { method: "POST", body: body })
body.set("humanconfidence", value);
body.set("humanconfidencepage", HC.humanconfidencepage);
originalFetch("active", { method: "POST", body: body })
.then(function (r) { return r.json(); })
.then(function (answer) {
if (mine === latest) { show("active", answer.humanConfidence); }
})
.catch(function () { if (mine === latest) { show("active", null); } });
.then(function (answer) { show("active", answer.humanConfidence); })
.catch(function () { show("active", null); });
}

// The script's third party cookie check calls window.fodTpcEndpoint, or
Expand All @@ -310,7 +317,10 @@ <h3 class="c-eg-page__heading">Find out more</h3>
// server side. Its result comes back through fod.onChange.
var script = document.createElement("script");
script.async = true;
script.src = MODE === "server" ? "hc/script.js" : API + RESOURCE + ".js";
// The script is asked for with the challenge, which the cloud seals the
// result to.
script.src = (MODE === "server" ? "hc/script.js" : API + RESOURCE + ".js")
+ "?challenge=" + encodeURIComponent(HC.challenge);
script.onerror = function () { show("active", null); };
script.onload = function () {
if (!window.fod || typeof window.fod.onChange !== "function") {
Expand All @@ -323,7 +333,7 @@ <h3 class="c-eg-page__heading">Find out more</h3>
// run, and its HumanConfidence is then a plain level. Only a sealed
// value is redeemed: redeeming a plain level answers unreadable,
// which would show Active Low for tests that haven't run yet.
if (value && PLAIN.indexOf(value) < 0 && value !== seen) {
if (value && PLAIN.indexOf(value) < 0 && seen === null) {
seen = value;
redeem(value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,14 @@
answer, and describes the request it sent. A Basic key, whose product does
not offer HumanConfidenceSource, is checked the same way.

Only the passive step is run here. The active step needs the browser tests,
which only a browser runs.
A sealed value is made only by the browser tests, which only a browser
runs, so the active step is checked with a value the cloud did not seal,
which gives Active Low.
"""

import json
import re

import pytest
import requests

Expand Down Expand Up @@ -133,6 +137,24 @@ def test_a_basic_key_gets_a_passive_level(api, naming_the_properties):
assert answer["humanConfidence"] in LEVELS + (None,)


def post_unsealed(client):
"""Serves the page, then sends back a value the cloud did not seal,
with the page's own page value."""
html = client.get("/", headers=HEADERS).get_data(as_text=True)
values = json.loads(re.search(r"var HC = (\{[^;]*\});", html).group(1))
return client.post("/active", headers=HEADERS, data={
"humanconfidence": "a-value-the-cloud-did-not-seal",
"humanconfidencepage": values["humanconfidencepage"]})


def test_a_value_that_does_not_redeem_gives_active_low(client):
answer = post_unsealed(client).get_json()
assert answer["humanConfidence"] in LEVELS
assert answer["humanConfidenceSource"] in ("Active", "Passive")
assert answer == {
"humanConfidence": "Low", "humanConfidenceSource": "Active"}


def test_license_key_never_reaches_the_browser(client):
license_key = ExampleUtils.get_license_key()
if not license_key:
Expand All @@ -142,5 +164,5 @@ def test_license_key_never_reaches_the_browser(client):
for response in (client.get("/?mode=client", headers=HEADERS),
client.get("/?mode=server", headers=HEADERS),
client.get("/passive", headers=HEADERS),
client.post("/redeem", data={"value": "not-sealed"})):
post_unsealed(client)):
assert license_key.encode() not in response.data
Loading
Loading