diff --git a/.github/workflows/cloud-51did.yml b/.github/workflows/cloud-51did.yml index 461d40ce..ff1effea 100644 --- a/.github/workflows/cloud-51did.yml +++ b/.github/workflows/cloud-51did.yml @@ -19,6 +19,12 @@ name: Cloud 51Did Tests # passes without calling the cloud has proved nothing. The tests themselves # skip without a key. A pull request from a fork gets no secrets, # so run this workflow from a branch in this repository. +# +# The tests ask the staging cloud that the organization variable +# CLOUD_STAGING_ENDPOINT names, because they check what the staging cloud +# does. A page's call that requests HumanConfidence and is handed the +# browser tests gets no 51Did on its first answer there, so the browser +# tests then ask with the license key alone. on: workflow_dispatch: @@ -27,7 +33,7 @@ on: # again, so a field the cloud starts writing, stops writing or changes goes # unnoticed until a customer finds it. That is what happened when the cloud service began # writing the Terms byte. The six 51Did packages are - # staggered ten minutes apart so they do not all ask production at once. + # staggered ten minutes apart so they do not all ask the cloud at once. schedule: - cron: '30 5 * * *' pull_request: @@ -77,28 +83,40 @@ jobs: # license key of the account whose resource key sealed it. The tests # read it from _51DEGREES_LICENSE_KEY_51DID. _51DEGREES_LICENSE_KEY_51DID: ${{ secrets._51DEGREES_LICENSE_KEY_51DID }} - # The cloud service the tests call. The DidClient uses the public - # one when this is empty. - _51DEGREES_CLOUD_ENDPOINT: ${{ vars._51DEGREES_CLOUD_ENDPOINT }} + # The staging cloud, which the tests call under the name the + # DidClient reads. + _51DEGREES_CLOUD_ENDPOINT: ${{ vars.CLOUD_STAGING_ENDPOINT }} # The tests skip without a key, so the run fails here instead, - # naming the variable. -rs lists any test that skipped, and none - # should. + # naming each empty name. A secret or variable that does not exist + # reaches the step as an empty value. -rs lists any test that + # skipped, and none should. shell: pwsh run: | - if (-not $env:_51DEGREES_RESOURCE_KEY_51DID) { - Write-Host '::error::_51DEGREES_RESOURCE_KEY_51DID is not set. It comes from the _51DEGREES_RESOURCE_KEY_51DID organization secret.' - exit 1 + $names = [ordered]@{ + _51DEGREES_RESOURCE_KEY_51DID = '_51DEGREES_RESOURCE_KEY_51DID organization secret' + _51DEGREES_LICENSE_KEY_51DID = '_51DEGREES_LICENSE_KEY_51DID organization secret' + _51DEGREES_CLOUD_ENDPOINT = 'CLOUD_STAGING_ENDPOINT organization variable' + } + $missing = @($names.Keys | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) + foreach ($name in $missing) { + Write-Host "::error::$name is not set. It comes from the $($names[$name])." } + if ($missing) { exit 1 } tox -- tests/test_did_client_live.py -v -rs - name: Cloud 51Did tier test with the Basic key if: ${{ !cancelled() }} env: _51DEGREES_RESOURCE_KEY_BASIC: ${{ secrets._51DEGREES_RESOURCE_KEY_BASIC }} - _51DEGREES_CLOUD_ENDPOINT: ${{ vars._51DEGREES_CLOUD_ENDPOINT }} + _51DEGREES_CLOUD_ENDPOINT: ${{ vars.CLOUD_STAGING_ENDPOINT }} shell: pwsh run: | - if (-not $env:_51DEGREES_RESOURCE_KEY_BASIC) { - Write-Host '::error::_51DEGREES_RESOURCE_KEY_BASIC is not set. It comes from the _51DEGREES_RESOURCE_KEY_BASIC organization secret.' - exit 1 + $names = [ordered]@{ + _51DEGREES_RESOURCE_KEY_BASIC = '_51DEGREES_RESOURCE_KEY_BASIC organization secret' + _51DEGREES_CLOUD_ENDPOINT = 'CLOUD_STAGING_ENDPOINT organization variable' + } + $missing = @($names.Keys | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) + foreach ($name in $missing) { + Write-Host "::error::$name is not set. It comes from the $($names[$name])." } + if ($missing) { exit 1 } tox -- tests/test_did_tier_live.py -v -rs diff --git a/.github/workflows/cloud-human-confidence.yml b/.github/workflows/cloud-human-confidence.yml index a525beb1..49e6a449 100644 --- a/.github/workflows/cloud-human-confidence.yml +++ b/.github/workflows/cloud-human-confidence.yml @@ -3,17 +3,20 @@ name: Cloud Human Confidence Tests # Runs the Human Confidence web example's tests marked staging # (pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/ # test_cloud_humanconfidence_web.py) against the staging cloud, because the -# production cloud does not serve HumanConfidenceSource yet. The Bespoke key -# must get the source Passive, and the Basic key no source. +# production cloud does not seal a Resource Key call yet. The example's +# passive call with the Bespoke Resource Key must get a sealed result, and +# the Basic key no source. A server's call with the License Key and the +# visitor's ja4, h2 and client-ip must get High, Medium or Low. # # CLOUD_STAGING_ENDPOINT, the staging cloud's API base, is an organization # variable, and RESOURCE_KEY_BESPOKE_STAGING, a Bespoke key the staging cloud -# knows, is an organization secret. Only this workflow uses them. common-ci -# passes on only _51DEGREES_ names and its own list of CI secrets, so in the +# knows, is an organization secret. Only this workflow reads +# RESOURCE_KEY_BESPOKE_STAGING, and the Cloud 51Did workflow reads +# CLOUD_STAGING_ENDPOINT too. common-ci passes on only _51DEGREES_ names and its own list of CI secrets, so in the # shared integration tests the staging tests skip, and the other Human # Confidence tests run there against the cloud _51DEGREES_CLOUD_ENDPOINT -# names. _51DEGREES_RESOURCE_KEY_BASIC is an organization secret that both -# clouds know. +# names. _51DEGREES_RESOURCE_KEY_BASIC and _51DEGREES_LICENSE_KEY_BESPOKE are +# organization secrets that both clouds know. # # The run fails when a name is empty, and when a test skipped or none ran, # because a cloud test that passes without calling the cloud has proved @@ -97,18 +100,23 @@ jobs: CLOUD_STAGING_ENDPOINT: ${{ vars.CLOUD_STAGING_ENDPOINT }} RESOURCE_KEY_BESPOKE_STAGING: ${{ secrets.RESOURCE_KEY_BESPOKE_STAGING }} _51DEGREES_RESOURCE_KEY_BASIC: ${{ secrets._51DEGREES_RESOURCE_KEY_BASIC }} + # A License Key valid for Human Confidence, which the tests of a + # server's call present to the staging cloud. + _51DEGREES_LICENSE_KEY: ${{ secrets._51DEGREES_LICENSE_KEY_BESPOKE }} run: | - # Each name, with where it comes from. + # Each name, with the organization variable or secret it comes + # from. $names = [ordered]@{ - CLOUD_STAGING_ENDPOINT = 'organization variable' - RESOURCE_KEY_BESPOKE_STAGING = 'organization secret' - _51DEGREES_RESOURCE_KEY_BASIC = 'organization secret' + CLOUD_STAGING_ENDPOINT = 'organization variable CLOUD_STAGING_ENDPOINT' + RESOURCE_KEY_BESPOKE_STAGING = 'organization secret RESOURCE_KEY_BESPOKE_STAGING' + _51DEGREES_RESOURCE_KEY_BASIC = 'organization secret _51DEGREES_RESOURCE_KEY_BASIC' + _51DEGREES_LICENSE_KEY = 'organization secret _51DEGREES_LICENSE_KEY_BESPOKE' } $missing = $false foreach ($name in $names.Keys) { if (-not [Environment]::GetEnvironmentVariable($name)) { Write-Host ("::error::$name is empty or missing. It comes " + - "from the $($names[$name]) of the same name.") + "from the $($names[$name]).") $missing = $true } } diff --git a/ci/key-names.Tests.ps1 b/ci/key-names.Tests.ps1 index 8b5b8607..15261ea3 100644 --- a/ci/key-names.Tests.ps1 +++ b/ci/key-names.Tests.ps1 @@ -18,6 +18,8 @@ # RESOURCE_KEY_BESPOKE_STAGING, an organization secret, is a Bespoke key it # knows. Only the Cloud Human Confidence workflow sets them, for the tests # marked staging, which check what the production cloud does not serve yet. +# The Cloud 51Did workflow gives CLOUD_STAGING_ENDPOINT as +# _51DEGREES_CLOUD_ENDPOINT, as its tests check what the staging cloud does. BeforeDiscovery { $script:DiscoveryRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path @@ -123,7 +125,7 @@ foreach ($asset in $Assets) { Set-Content -LiteralPath "assets/$asset" '' } @($python + @(Get-StepScript 'cloud-human-confidence.yml' 'Human Confidence tests against the staging cloud')) | Set-Content $stepFile $all = 'CLOUD_STAGING_ENDPOINT', 'RESOURCE_KEY_BESPOKE_STAGING', - '_51DEGREES_RESOURCE_KEY_BASIC' + '_51DEGREES_RESOURCE_KEY_BASIC', '_51DEGREES_LICENSE_KEY' $saved = @{} foreach ($name in $all) { $saved[$name] = [Environment]::GetEnvironmentVariable($name) @@ -146,6 +148,7 @@ foreach ($asset in $Assets) { Set-Content -LiteralPath "assets/$asset" '' } CLOUD_STAGING_ENDPOINT = 'https://cloud.example.test/api/v4/' RESOURCE_KEY_BESPOKE_STAGING = 'staging-bespoke-key' _51DEGREES_RESOURCE_KEY_BASIC = 'basic-key' + _51DEGREES_LICENSE_KEY = 'bespoke-license-key' } # A junit report of the two staging tests, as pytest writes it. @@ -483,9 +486,8 @@ Describe 'Keys under their _51DEGREES_ names' { } # Only the workflow that runs the tests marked staging sets the - # staging names, so no other workflow's tests call the staging cloud. + # staging key, so no other workflow's tests use it. It 'are given from the organization of the same name by the Cloud Human Confidence workflow alone' -ForEach @( - @{ Variable = 'CLOUD_STAGING_ENDPOINT'; Kind = 'variable'; Context = 'vars' } @{ Variable = 'RESOURCE_KEY_BESPOKE_STAGING'; Kind = 'secret'; Context = 'secrets' } ) { $lines = @(Get-ChildItem (Join-Path $script:Root '.github/workflows') -Include *.yml, *.yaml -Recurse | @@ -499,6 +501,29 @@ Describe 'Keys under their _51DEGREES_ names' { $given[0] | Should -Match ":\s*$Variable\s*:\s*\$\{\{\s*$Context\.$Variable\s*\}\}\s*$" } + # The Cloud Human Confidence workflow gives the staging cloud under + # its own name, and the Cloud 51Did workflow gives it as + # _51DEGREES_CLOUD_ENDPOINT, the name the 51Did client reads. No + # other workflow's tests call the staging cloud. + It 'are given CLOUD_STAGING_ENDPOINT from the organization variable by the Cloud Human Confidence and Cloud 51Did workflows alone' { + $lines = @(Get-ChildItem (Join-Path $script:Root '.github/workflows') -Include *.yml, *.yaml -Recurse | + Select-String -Pattern '\bCLOUD_STAGING_ENDPOINT\b' | + Where-Object { $_.Line.Trim() -notmatch '^#' } | + ForEach-Object { "$($_.Filename):$($_.LineNumber): $($_.Line.Trim())" }) + $lines | Where-Object { + $_ -notmatch '^(cloud-human-confidence|cloud-51did)\.yml:' + } | Should -BeNullOrEmpty + $given = @($lines | Where-Object { $_ -match ':\s*CLOUD_STAGING_ENDPOINT\s*:' }) + $given.Count | Should -Be 1 + $given[0] | Should -Match '^cloud-human-confidence\.yml:.*:\s*CLOUD_STAGING_ENDPOINT\s*:\s*\$\{\{\s*vars\.CLOUD_STAGING_ENDPOINT\s*\}\}\s*$' + $endpoint = @($lines | Where-Object { + $_ -match '^cloud-51did\.yml:' -and $_ -match '\$\{\{' }) + $endpoint.Count | Should -BeGreaterThan 0 + $endpoint | Where-Object { + $_ -notmatch ':\s*_51DEGREES_CLOUD_ENDPOINT\s*:\s*\$\{\{\s*vars\.CLOUD_STAGING_ENDPOINT\s*\}\}\s*$' + } | Should -BeNullOrEmpty + } + It 'read the staging cloud and its key from CLOUD_STAGING_ENDPOINT and RESOURCE_KEY_BESPOKE_STAGING in the Human Confidence live test' { $text = Get-Content -Raw (Join-Path $script:Root 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py') $text | Should -Match '"CLOUD_STAGING_ENDPOINT"' @@ -510,6 +535,7 @@ Describe 'Keys under their _51DEGREES_ names' { @{ Missing = 'CLOUD_STAGING_ENDPOINT' } @{ Missing = 'RESOURCE_KEY_BESPOKE_STAGING' } @{ Missing = '_51DEGREES_RESOURCE_KEY_BASIC' } + @{ Missing = '_51DEGREES_LICENSE_KEY' } ) { $names = $script:StagingNames.Clone() $names[$Missing] = $null 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..7ebcce0b 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,18 +26,23 @@ 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 +The example's passive call presents the Resource Key, which is the +browser's route, so the cloud seals HumanConfidence and the example gives +the sealed result. A source given beside it is Passive, as no browser tests have run. The Basic product does not offer HumanConfidenceSource, so a Basic key gets no source. -The production cloud does not serve HumanConfidenceSource yet, so the two -tests that check it are marked staging and call the staging cloud that -CLOUD_STAGING_ENDPOINT names, with the Bespoke key in -RESOURCE_KEY_BESPOKE_STAGING and the Basic key in -_51DEGREES_RESOURCE_KEY_BASIC. Only the Cloud Human Confidence workflow sets -the two staging names, and without them these tests skip. The other tests -call the cloud _51DEGREES_CLOUD_ENDPOINT names. +A server's call presents a License Key valid for Human Confidence, read +from _51DEGREES_LICENSE_KEY, requests HumanConfidence and supplies the +visitor's ja4, h2 and client-ip, and gets High, Medium or Low itself. +Without those three it gets no value and the reason. + +The production cloud does not seal a Resource Key call yet, so these tests +are marked staging and call the staging cloud that CLOUD_STAGING_ENDPOINT +names, with the Bespoke key in RESOURCE_KEY_BESPOKE_STAGING and the Basic +key in _51DEGREES_RESOURCE_KEY_BASIC. Only the Cloud Human Confidence +workflow sets the two staging names, and without them these tests skip. +The other tests call the cloud _51DEGREES_CLOUD_ENDPOINT names. Only the passive step is run here. The active step needs the browser tests, which only a browser runs. @@ -59,9 +64,18 @@ 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 values HumanConfidence takes as a level. Any other text is a sealed +# result. +LEVELS = ("High", "Medium", "Low") + +# A visitor's JA4, in the form a TLS terminator reports it, the visitor's +# HTTP/2 SETTINGS, WINDOW_UPDATE, PRIORITY and pseudo-header order, and a +# public address the cloud can look up. +VISITOR = { + "ja4": "t13d1516h2_8daaf6152771_02713d6af862", + "h2": "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p", + "client-ip": "8.8.8.8", +} # The variable holding a resource key of the Basic product. BASIC_KEY_NAME = "_51DEGREES_RESOURCE_KEY_BASIC" @@ -161,13 +175,84 @@ def test_page_is_served_and_never_kept(client, key): assert key in response.get_data(as_text=True) +def is_sealed(value): + """Whether value is a sealed result, being text that is not a level.""" + return isinstance(value, str) and bool(value.strip()) \ + and value not in LEVELS + + @pytest.mark.staging -def test_passive_source_and_level_come_from_the_cloud( +def test_passive_call_with_the_resource_key_gets_a_sealed_result( staging_client, naming_the_properties): + """The example's passive call presents the Resource Key, which is the + browser's route, so the cloud seals HumanConfidence whatever the + source.""" 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 is_sealed(answer["humanConfidence"]), answer + assert answer["source"] in (None, "Passive"), answer + + +@pytest.fixture(scope="module") +def license_key(): + value = ExampleUtils.get_license_key() + if not value: + pytest.skip( + f"{ExampleUtils.LICENSE_KEY_ENV_VAR} is not set. Set it to a " + "License Key valid for Human Confidence to check a server's " + "call.") + return value + + +def servers_call(staging_api, license_key, visitor): + """The derived member of the staging cloud's answer to a server's call, + which presents the License Key alone, in the body and never the URL, + and requests HumanConfidence. visitor holds the visitor's values the + call supplies.""" + + def redact(text): + return str(text).replace(license_key, "") + + failure = None + try: + answer = requests.request( + "POST", staging_api + "json", + data=dict(visitor, **{ + "license": license_key, "values": PROPERTIES, + "user-agent": DESKTOP_CHROME}), + timeout=example.TIMEOUT) + except requests.RequestException as error: + failure = "The server's call failed: " + redact(error) + if failure: + pytest.fail(failure) + assert answer.status_code == 200, ( + "The server's 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)) + return derived + + +@pytest.mark.staging +def test_a_servers_call_with_the_visitors_values_gets_a_level( + staging_api, license_key): + """A server's call with a License Key valid for Human Confidence and the + visitor's ja4, h2 and client-ip gets the level itself, with the source + Passive.""" + derived = servers_call(staging_api, license_key, VISITOR) + assert derived.get("humanconfidence") in LEVELS, derived + assert derived.get("humanconfidencesource") == "Passive", derived + + +@pytest.mark.staging +def test_a_servers_call_without_the_visitors_values_gets_no_value( + staging_api, license_key): + """The same call without the visitor's ja4, h2 and client-ip gets no + value, and the reason.""" + derived = servers_call(staging_api, license_key, {}) + assert derived.get("humanconfidence") is None, derived + reason = derived.get("humanconfidencenullreason") + assert isinstance(reason, str) and reason.strip(), derived @pytest.mark.staging diff --git a/pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py b/pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py index 990f2f4f..b6103a20 100644 --- a/pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py +++ b/pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py @@ -65,6 +65,14 @@ FODID = "the FODid product" MARKETING = "the CloudV5FODiD product" +# The 51Did Properties a call with the licence key alone names, as it +# requests only the Properties it names. +DID_VALUES = "values=FODiD.IdProbGlobal&values=FODiD.IdProbLic" + +# The request header the cloud reads a licence key from, so the key never +# goes in the URL. +LICENCE_KEY_HEADER = "X-51D-License-Key" + NO_KEY = no_resource_key( FODID + ", and " + MARKETING + " for the marketing usages", "FODiD.IdProbGlobal and FODiD.IdProbLic under each id.usage", @@ -84,6 +92,30 @@ def null_reason(fodid): or fodid.get("idproblicnullreason") +def member(parent, name): + """The member of ``parent`` called ``name`` in any letter case, or + None.""" + if not isinstance(parent, dict): + return None + for key, value in parent.items(): + if key.lower() == name: + return value + return None + + +def waits_for_browser_tests(answer): + """Whether the call requested HumanConfidence, being one whose + ``derived`` member holds it with a value or without, and was handed the + browser tests as a non-empty ``browserderived.BrowserTestsJavaScript``. + Only then does the cloud hold the 51Did back.""" + derived = member(answer, "derived") + requested = isinstance(derived, dict) and any( + key.lower() == "humanconfidence" for key in derived) + script = member(member(answer, "browserderived"), + "browsertestsjavascript") + return requested and isinstance(script, str) and bool(script.strip()) + + def no_creator_context(endpoint, detail): """What to fail with when the host does not offer the creator context, which the 51Degrees cloud does.""" @@ -325,7 +357,14 @@ def get(self, url, user_agent): def create(self, usage="standard"): """Creates a 51Did the way a page does, sending the snippet values - with the request, and returns it.""" + with the request, and returns it. + + A Resource Key whose Properties include HumanConfidence requests it + on every call, and where the cloud hands out the browser tests too, + the page's first answer carries no 51Did. The 51Did comes on a later + call with the browser test answers, which this test can't make, so + it then asks with the licence key alone, which requests only the + 51Did Properties it names.""" query = dict(self.SNIPPETS) query["id.usage"] = usage @@ -334,8 +373,17 @@ def create(self, usage="standard"): urllib.parse.urlencode(query)) status, body = self.get(url, self.CHROME) self.assertEqual(200, status, body[:300]) - fodid = json.loads(body).get("fodid") or {} + answer = json.loads(body) + fodid = answer.get("fodid") or {} value = fodid.get("idproblic") or fodid.get("idprobglobal") + if not value and waits_for_browser_tests(answer): + if not LICENCE_KEY: + self.skipTest( + "The 51Did waits for the browser test answers, and " + "_51DEGREES_LICENSE_KEY_51DID is not set to ask without " + "them.") + fodid = self.create_with_licence_key(query) + value = fodid.get("idproblic") or fodid.get("idprobglobal") if not value: # The probabilistic reason in full, because it names every # snippet result the service is still waiting for. @@ -344,6 +392,26 @@ def create(self, usage="standard"): + usage, null_reason(fodid), MARKETING)) return FodId.from_base64(value) + def create_with_licence_key(self, query): + """The ``fodid`` member of the cloud's answer to the page's request + sent with the licence key alone, in the header the cloud reads it + from, naming the 51Did Properties.""" + + url = "{0}json?{1}&{2}".format( + self.client.endpoint, urllib.parse.urlencode(query), DID_VALUES) + request = urllib.request.Request( + url, headers={"User-Agent": self.CHROME, + LICENCE_KEY_HEADER: LICENCE_KEY}, method="GET") + try: + with urllib.request.urlopen(request, timeout=30) as response: + status = response.status + body = response.read().decode("utf-8") + except urllib.error.HTTPError as error: + status, body = error.code, error.read().decode("utf-8") + self.assertEqual( + 200, status, body[:300].replace(LICENCE_KEY, "")) + return json.loads(body).get("fodid") or {} + def verify_context(self, fod_id, user_agent): """Step one of the browser check, the call the page makes, which answers with a sealed result the page cannot read."""