File size: 5,808 Bytes
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""connectors_amazon_ads.py: the Amazon Ads connector's API layer (S79-T13): the probe and the card state.

The transport is `platform/harness/amazon_ads_client.py`. This module adds the liveness probe the
keychain calls through `register_prober`, and the card state the Connectors directory reads.

⛔ READ ONLY. No route here writes. The probe makes one Login with Amazon token exchange and one
profile listing GET, and only when an administrator tests a stored credential.
⛔ `AMAZON_ADS_FIXTURE=1` answers from the fixture tokens below and opens no socket.
"""
from __future__ import annotations

import json
import sys
import urllib.request
from pathlib import Path

_PLATFORM = Path(__file__).resolve().parents[2] / "platform"
if str(_PLATFORM) not in sys.path:
    sys.path.insert(0, str(_PLATFORM))

from harness import amazon_ads_client as client                        # noqa: E402

KEY = client.KEY
LABEL = client.LABEL
#: Must be a `core.keychain.ENTRY_TYPES` member, or storing the credential 400s.
ENTRY_TYPE = client.ENTRY_TYPE
CREDENTIAL_FIELDS = client.CREDENTIAL_FIELDS

#: The one read the probe makes after the token exchange. GET only, one path.
PROFILES_PATH = "v2/profiles"

#: Fixture refresh tokens. A token with the prefix passes; the expired one fails.
FIXTURE_TOKEN_PREFIX = "Atzr|fixture-ads"
FIXTURE_REFRESH_TOKEN = FIXTURE_TOKEN_PREFIX + "-ok"
FIXTURE_EXPIRED_TOKEN = FIXTURE_TOKEN_PREFIX + "-expired"
FIXTURE_PROFILE_ID = "1234567890"

#: Messages a person reads. No dash, no provider text.
OK_MESSAGE = "Amazon Ads confirmed profile access."
EXPIRED_MESSAGE = "The Amazon Ads token expired. Connect again."
NO_PROFILE_MESSAGE = "The token does not reach this profile. Check the profile ID."
NOT_FIXTURE_MESSAGE = "Fixture mode accepts only the fixture token."
SIGN_IN_MESSAGE = "Amazon Ads did not accept the sign in. Check the fields and connect again."


def fixture_fields(*, expired=False):
    """The fixture credential an administrator pastes on staging. -> the four fields."""
    return {"client_id": "amzn1.application-oa2-client.fixture",
            "client_secret": "fixture-ads-secret",
            "refresh_token": FIXTURE_EXPIRED_TOKEN if expired else FIXTURE_REFRESH_TOKEN,
            "profile_id": FIXTURE_PROFILE_ID}


def missing_fields(fields):
    """The credential fields that are absent or blank, in declaration order."""
    f = fields if isinstance(fields, dict) else {}
    return [key for key in CREDENTIAL_FIELDS if not isinstance(f.get(key), str) or not f[key].strip()]


def _fixture_probe(fields):
    token = fields["refresh_token"].strip()
    if token == FIXTURE_EXPIRED_TOKEN:
        return {"ok": False, "message": EXPIRED_MESSAGE}
    if not token.startswith(FIXTURE_TOKEN_PREFIX):
        return {"ok": False, "message": NOT_FIXTURE_MESSAGE}
    return {"ok": True, "message": OK_MESSAGE}


def _profiles(access_token, fields, timeout):
    """The advertiser's profile ids. One GET; any failure raises `client.AdsError`."""
    host = client.HOSTS.get(str(fields.get("region") or client.DEFAULT_REGION).lower(),
                            client.HOSTS[client.DEFAULT_REGION])
    req = urllib.request.Request(f"{host}/{PROFILES_PATH}", method="GET", headers={
        "Authorization": f"Bearer {access_token}",
        "Amazon-Advertising-API-ClientId": fields["client_id"], "Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            body = json.loads(r.read().decode("utf-8", "replace") or "[]")
    except Exception as exc:                                           # noqa: BLE001
        raise client.AdsError(f"Amazon Ads profiles could not be read ({type(exc).__name__})") from None
    return {str(p.get("profileId")) for p in body if isinstance(p, dict)} if isinstance(body, list) else set()


def probe_credential(fields, timeout=8):
    """`{ok, message}` for a stored `amazon_ads` credential: the keychain's liveness probe."""
    f = fields if isinstance(fields, dict) else {}
    missing = missing_fields(f)
    if missing:
        return {"ok": False, "message": "Missing " + ", ".join(missing) + ". Enter every field."}
    if client.fixture_mode():
        return _fixture_probe(f)
    try:
        profiles = _profiles(client._token(f), f, timeout)
    except client.AdsError:
        return {"ok": False, "message": SIGN_IN_MESSAGE}
    if f["profile_id"].strip() not in profiles:
        return {"ok": False, "message": NO_PROFILE_MESSAGE}
    return {"ok": True, "message": OK_MESSAGE}


def register():
    """Fill the keychain's probe slot for `amazon_ads`. Never raises."""
    try:
        import core.keychain as kc
        return kc.register_prober(ENTRY_TYPE, probe_credential)
    except Exception:                                                  # noqa: BLE001
        return False


def held(rt, entry_id):
    """True when this entry's current ciphertext carries a passing probe proof. No decrypt, no I/O.

    A failed test, an expired token or a replaced secret clears the proof, so the card reads Connect.
    """
    try:
        from core import keychain as kc
        return bool(kc.entry_verified(rt, entry_id))
    except Exception:                                                  # noqa: BLE001
        return False


def card_state(verified):
    """The directory state: `connected` (Settings) only with a verified credential, else `available`."""
    return "connected" if verified else "available"


__all__ = ["KEY", "LABEL", "ENTRY_TYPE", "CREDENTIAL_FIELDS", "PROFILES_PATH", "FIXTURE_TOKEN_PREFIX",
           "FIXTURE_REFRESH_TOKEN", "FIXTURE_EXPIRED_TOKEN", "FIXTURE_PROFILE_ID", "OK_MESSAGE",
           "EXPIRED_MESSAGE", "fixture_fields", "missing_fields", "probe_credential", "register",
           "held", "card_state"]