Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
2db5763
Send the sealed result and transaction, and read status and Human Con…
Jamesr51d Nov 25, 2026
4eb3a47
Send the sealed result and transaction under their obsolete names too
Jamesr51d Nov 25, 2026
aa03c86
Redeem Human Confidence as sealedResult and read status in the web ex…
Jamesr51d Nov 25, 2026
56ee07d
Read HTTP 503 as unconfirmed and an unknown Human Confidence word as …
Jamesr51d Nov 25, 2026
5e4b222
Show a legacy expired or replayed redeem as a failure in the web example
Jamesr51d Nov 25, 2026
068c721
Verify only on HTTP 200 and read a 503 redeem in one place
Jamesr51d Nov 26, 2026
f17bb6f
Give a reason where a verified or redeemed answer carries no Human Co…
Jamesr51d Nov 26, 2026
81a661c
Say Value, not level, in the Human Confidence example and tidy two wr…
Jamesr51d Nov 26, 2026
d3e1549
Only the five verdicts count as success when redeem has no status
jwrosewell Nov 28, 2026
713d37a
Don't raise on a redeem 200 with nothing usable in it
jwrosewell Nov 28, 2026
42863bc
Let an explicit transaction of None win over the obsolete challenge
Tracy51D Nov 28, 2026
7990fb1
Redeem sealed Human Confidence in the Cloud Request Engine
jwrosewell Nov 28, 2026
4b4b870
Have the Human Confidence example read the pipeline
jwrosewell Nov 28, 2026
5674b66
Show the null reason on the example page when there is no level
Tracy51D Nov 28, 2026
d277ddf
Don't assign process_internal's result on the sealed path
jwrosewell Nov 28, 2026
845571b
Ignore humanconfidence outside the query
jwrosewell Nov 28, 2026
5051f2f
Leave query.humanconfidence out of the JavaScript Builder output
jwrosewell Nov 28, 2026
4dcb109
Make the transaction store's take() private
jwrosewell Nov 28, 2026
813ab57
Mask the whole License Key in engine messages
jwrosewell Nov 28, 2026
b497d33
Add tests for the last two not-redeemed cases
jwrosewell Nov 28, 2026
d5bdccb
Make the no-request test able to fail
jwrosewell Nov 28, 2026
e24e80a
Let DerivedCloud run without a Cloud Request Engine
jwrosewell Nov 28, 2026
22568ba
Give Medium and Active for a sealed result in derived properties
Tracy51D Nov 28, 2026
22f0ac7
Name the redeem endpoint in the 404 error
Tracy51D Nov 28, 2026
556680d
Keep HumanConfidence to its own values
jwrosewell Nov 28, 2026
d5dee46
Document the Human Confidence delay and page policy
Tracy51D Nov 28, 2026
4961a9e
Don't send a whitespace-only humanconfidence
jwrosewell Nov 29, 2026
bde3fe4
Give HumanConfidence for a blank sealed result as for none
jwrosewell Nov 29, 2026
a85eb2c
DidClient: hide license key, sealed result and transaction in errors
jwrosewell Nov 29, 2026
aab2ce3
HC + 51Did client changes for the 4.6 rules
Tracy51D Nov 30, 2026
559b6f8
Merge rc into feature/did-sealed-result-and-human-confidence
Rakesh51D Nov 30, 2026
6403250
FIX: Show the Human Confidence example's step 1 as the sealed result …
Rakesh51D Nov 30, 2026
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
2 changes: 2 additions & 0 deletions .github/workflows/cloud-human-confidence.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ on:
paths:
- 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/**'
- 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py'
# The package that redeems the sealed result for the example.
- 'pipeline/fiftyone_pipeline_cloudrequestengine/src/**'
- 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py'
- 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/live_cloud.py'
- 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,38 @@
# 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.
#
# 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. Asked by the server. This server asks the cloud itself, sending the
# visitor's request headers and IP address with the Resource Key. A
# call with the Resource Key alone is the browser's route, so
# HumanConfidence comes back sealed, and the page shows it as sealed.
# Only a call with a License Key valid for Human Confidence that also
# sends the visitor's ja4, h2 and client-ip, the server route, gets a
# plain level on the first call. A web server like this one doesn't
# see ja4 or h2, which come from the visitor's TLS connection, so this
# example doesn't make that call.
# 2. In the page. The page loads the 51Degrees client script, which runs
# the browser tests and sends the answers to the cloud. When the script
# completes, HumanConfidence holds a sealed result the browser can't
# read or change, whether HumanConfidenceSource is Active or Passive.
# The package gives each page its own script address, which binds the
# sealed result to that page.
# 3. Read on the server. The page always sends the sealed result back to
# this server as humanconfidence, with its page id as
# humanconfidencepage, and never looks at HumanConfidenceSource to
# decide. The server adds them to the evidence of a
# pipeline holding the Cloud Request Engine, and reads the two
# properties from flowdata.derived. The package redeems the sealed
# result itself, with the License Key, so this server never redeems it
# and the browser never sees the License Key. A sealed result redeems
# once, so sending it again gives Medium and no source, with the reason.
#
# The page code a consumer writes, once the client script completes:
# ```
# var body = new URLSearchParams();
# body.set("humanconfidence", data.derived.humanconfidence || "");
# body.set("humanconfidencepage", PAGE);
# fetch("humanconfidence", { method: "POST", body: body });
# ```
#
# 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).
#
Expand All @@ -56,21 +74,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 logging
import os
import sys
import threading
import urllib.parse

import requests
from flask import Flask, Response, jsonify, make_response, render_template
from flask import Flask, jsonify, make_response, render_template
from flask import request

from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \
CloudRequestEngine
from fiftyone_pipeline_cloudrequestengine.constants import Constants
from fiftyone_pipeline_cloudrequestengine.humanconfidence import \
DerivedCloud, HumanConfidenceTransactions
from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
from fiftyone_pipeline_examples.example_utils import ExampleUtils

DEFAULT_API = "https://cloud.51degrees.com/api/v4/"
Expand All @@ -81,6 +105,14 @@
# A short limit, in seconds, so a slow cloud can't hang the demo.
TIMEOUT = 10

# What the page is told when the pipeline can't be built or a property
# can't be read. The details go to the server's log instead, because an
# error's text can name the License Key, which no page may receive.
BUILD_FAILED = "The pipeline could not be built. See the server's log."
READ_FAILED = "The property could not be read. See the server's log."

LOGGER = logging.getLogger(__name__)

# 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 = [
Expand Down Expand Up @@ -122,18 +154,36 @@ def api_base(endpoint):
return (endpoint or DEFAULT_API).rstrip("/") + "/"


def ask_cloud(method, url, endpoint, data=None):

"""!
Send one request to the cloud and give its answer. A redirect is never
followed, whatever the request carries, as the Cloud Request Engine
follows none. It is a failure whose message names the endpoint, with
no key in it, and the status. See
https://github.com/51Degrees/specifications/blob/main/pipeline-specification/pipeline-elements/cloud-request-engine.md#http-requests
"""

answer = requests.request(method, url, data=data, timeout=TIMEOUT,
allow_redirects=False)
if 300 <= answer.status_code < 400:
raise ValueError(Constants.MESSAGE_REDIRECT.format(
endpoint, answer.status_code))
return answer


def carries_human_confidence(api, resource_key):

"""!
Whether the Resource Key carries HumanConfidence, from the cloud's own
list of the properties the key carries.
"""

answer = requests.request(
answer = ask_cloud(
"GET",
api + "accessibleproperties?resource=" +
urllib.parse.quote(resource_key, safe=""),
timeout=TIMEOUT)
api + "accessibleproperties")
if answer.status_code != 200:
raise ValueError(f"HTTP {answer.status_code}: {trim(answer.text)}")
products = answer.json().get("Products") or {}
Expand All @@ -148,21 +198,51 @@ 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, and reads the active level through a pipeline,
whose Cloud Request Engine redeems the sealed result.
"""

# 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="")

# Issues each page its transaction and keeps it here, on the server.
transactions = HumanConfidenceTransactions()

# The pipeline, built on first use, so the page is served without
# asking the cloud anything.
built = []
building = threading.Lock()

def pipeline():
with building:
if not built:
settings = {
"resource_key": resource_key,
"cloud_endpoint": api,
"timeout_seconds": TIMEOUT,
"human_confidence_transactions": transactions}
if license_key:
settings["license_key"] = license_key
built.append(PipelineBuilder({
"add_javascript_builder": False,
"use_setheader_properties": False,
# A failed cloud request still gives the two
# properties, so it is recorded rather than raised.
"suppress_process_exceptions": True})
.add(CloudRequestEngine(settings))
.add(DerivedCloud())
.build())
return built[0]

# 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)
answer = ask_cloud(
"GET", api + "evidencekeys", api + "evidencekeys")
if answer.status_code != 200:
raise ValueError(
f"HTTP {answer.status_code}: {trim(answer.text)}")
Expand All @@ -174,16 +254,21 @@ def cloud_headers():
@app.route("/")
def index():

# A new transaction for each page. The page loads the client script
# from the address the package gives, and sends back the page id.
page = transactions.issue()
response = make_response(render_template(
"index.html", resource_key=resource_key, api=api))
"index.html", script_url=page.script_url(api, resource_key),
page_id=page.id))
# The page must never come from a cache, as each load runs the
# tests.
response.headers["Cache-Control"] = "no-store"
return response

# Passive: this server asks the cloud for the visitor, with the
# visitor's headers and IP address, and reads the plain level from the
# answer.
# Step 1: this server asks the cloud for the visitor, with the
# visitor's headers and IP address and the Resource Key. With the
# Resource Key alone the cloud seals HumanConfidence, so the answer
# holds a sealed result rather than a level.
@app.route("/passive")
def passive():

Expand All @@ -197,9 +282,9 @@ def passive():
# 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)
answer = ask_cloud(
"POST", api + resource_key + ".json",
api + Constants.HIDDEN_VALUE + ".json", data=evidence)
if answer.status_code >= 400:
return jsonify(
error=f"HTTP {answer.status_code}: {trim(answer.text)}")
Expand All @@ -210,31 +295,58 @@ def passive():
except (requests.RequestException, ValueError) 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.
@app.route("/redeem", methods=["POST"])
def redeem():
# Active: the page sends the sealed result and its page id. They go
# into the evidence, and the two properties are read from the derived
# data. The package redeems the sealed result while processing.
@app.route("/humanconfidence", methods=["POST"])
def human_confidence():

fields = {"value": request.form.get("value", "")}
if license_key:
fields["license"] = license_key
try:
answer = requests.request(
"POST", api + "hc/redeem", data=fields, 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")
flowdata = pipeline().create_flowdata()
except Exception as error:
LOGGER.error("Building the pipeline failed: %s",
hide(str(error), license_key))
return jsonify(error=BUILD_FAILED)
for name in ("humanconfidence", "humanconfidencepage"):
flowdata.evidence.add(
"query." + name, request.form.get(name, ""))
flowdata.process()
source, source_reason = property_of(
flowdata, "humanconfidencesource")
value, reason = property_of(flowdata, "humanconfidence")
return jsonify(source=source, humanConfidence=value,
humanConfidenceNullReason=reason,
humanConfidenceSourceNullReason=source_reason)

return app


def property_of(flowdata, name):

"""!
A property of the derived data as its value and the reason it has none,
one of them None.
"""

try:
value = flowdata.derived.get(name)
except Exception as error:
LOGGER.error("Reading %s failed: %s", name, error)
return None, READ_FAILED
if value.has_value():
return value.value(), None
return None, value.no_value_message()


def hide(text, license_key):

"""!
The text with the License Key left out, for the server's log.
"""

return text.replace(license_key, "(hidden)") if license_key else text


def client_ip(address):

"""!
Expand Down Expand Up @@ -295,9 +407,9 @@ 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.")
"shows Passive and Active, but the package redeems a sealed "
"result only with one, so the level after the browser tests "
"will be Medium.")

app = create_app(resource_key, license_key, api)
port = os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151)
Expand Down
Loading
Loading