From f6d4f405b3146183aed4ae9fe4b46151def9168e Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 18:32:01 -0700 Subject: [PATCH 01/11] Unified error tree, checks before requests, written retry policy, event rules - One error tree for every SDK language: MfaRequiredError is an AuthError, ConnectorTimeoutError a ConnectorError, FrontlineRequiredError a WrongLoginError; ApiError.server_message (message kept as an alias); NetworkError.request_sent; AccountError.find(type) - Every helper of both layers checks its arguments before signing in or sending anything - Retries: network failures and 5xx retried for idempotent requests and for sign-in and renewal (renewal only when the request never left); a 429 whose Retry-After exceeds the wait limit fails at once - Client(email, password, *, base_url=..., ...) - parse_first_alert_event accepts any non-empty string id; the payload is not final - Deduplicator flags only exact re-deliveries (same identity and canonical-JSON hash); upsert_key returns the id to store under Co-Authored-By: Claude Opus 5.5 --- src/intelligence_cloud/__init__.py | 3 +- src/intelligence_cloud/accounts.py | 143 +++++++++-- src/intelligence_cloud/client.py | 47 +++- src/intelligence_cloud/conversations.py | 49 +++- src/intelligence_cloud/errors.py | 112 ++++++--- src/intelligence_cloud/receiver.py | 106 +++++++-- tests/unit/test_conversations.py | 9 +- tests/unit/test_policy.py | 303 ++++++++++++++++++++++++ 8 files changed, 677 insertions(+), 95 deletions(-) create mode 100644 tests/unit/test_policy.py diff --git a/src/intelligence_cloud/__init__.py b/src/intelligence_cloud/__init__.py index a5cfc60..f88f9ff 100644 --- a/src/intelligence_cloud/__init__.py +++ b/src/intelligence_cloud/__init__.py @@ -67,6 +67,7 @@ UnknownEvent, parse_after_call_event, parse_first_alert_event, + upsert_key, ) __all__ = [ @@ -77,7 +78,7 @@ "FrontlineRequiredError", "ConnectorError", "ConnectorTimeoutError", "ExtensionMappingError", "AccountError", "WrongLoginError", "WebhookPayloadError", "PayloadTooLargeError", "WebhookTestResult", "RecordingLink", "AfterCallEvent", "AfterCallCall", "AfterCallSummary", "AfterCallLocation", "UnknownEvent", - "parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event", + "parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event", "upsert_key", "Deduplicator", "DedupStore", "MemoryDedupStore", "CustomerSpec", "TeamSpec", "ConnectorSpec", "PersonSpec", "AlertSetting", "AlertSettings", "Customer", "Team", "TeamGroups", "TeamRules", "Member", diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index de2098d..f5f4227 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -451,12 +451,10 @@ def _vertical_id(self, vertical: str) -> str: raise InvalidRequestError(f"Unknown vertical {vertical!r}: use an id or key from list_verticals()") def _check_connector(self, cs: Optional[ConnectorSpec], required: bool = False) -> None: + """The local checks, then the type against the API's list (one request, cached).""" + _check_connector_local(cs, required) if cs is None: - if required: - raise InvalidRequestError("A connector is required: pass a ConnectorSpec") return - if not isinstance(cs, ConnectorSpec): - raise InvalidRequestError("connector must be a ConnectorSpec") if self._connector_types is None: rows = unwrap(self._c.connectors.list_connector_types()) or [] self._connector_types = [r.get("key") for r in rows if isinstance(r, dict) and r.get("key")] @@ -469,6 +467,7 @@ def get_customer(self, company_id: str) -> Customer: """Read the customer's layout back: Management, teams, groups, rules, connectors and what is pending. A layout this SDK does not recognise (for example one built with 0.1.x) is returned with what is missing listed in ``pending``.""" + _check_customer_ref(company_id) self._require_admin() c = self._c company = unwrap(c.companies.get_company(company_id)) or {} @@ -547,13 +546,20 @@ def create_customer(self, spec: CustomerSpec) -> Customer: numbers" off. Alerts without phrases are listed in ``Customer.pending`` and follow with ``set_alerts``. Store ``company_id`` and pass it on later runs: a company is never adopted by its name alone.""" - me = self._require_admin() c = self._c if not isinstance(spec, CustomerSpec): raise InvalidRequestError("spec must be a CustomerSpec") - if not spec.admin or not (spec.admin.phone_number or "").strip(): + if not (spec.company_name or "").strip(): + raise InvalidRequestError("company_name is required") + _check_person(spec.admin) + if not (spec.admin.phone_number or "").strip(): raise InvalidRequestError("admin.phone_number is required for the primary contact") + _check_team_spec(spec.team) _check_alerts(spec.alerts) + _check_connector_local(spec.connector) + if spec.team.name == spec.company_name + MANAGEMENT_SUFFIX: + raise InvalidRequestError(f"{spec.team.name!r} is the Management location; name the team differently") + me = self._require_admin() self._check_connector(spec.connector) reseller_id = spec.reseller_id or me.get("reseller_id") if not reseller_id: @@ -854,11 +860,12 @@ def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSp """Add a further team: its location, connector (required; give the key in full each time), groups, rules (copying the phrases and levels of the first team's rules, except where ``alerts`` sets them) and Insights Hub setup. The rules are created switched off.""" + _check_customer_ref(customer) + _check_team_spec(team) + _check_connector_local(connector, required=True) + _check_alerts(alerts) self._require_admin() - if not isinstance(team, TeamSpec): - raise InvalidRequestError("team must be a TeamSpec") self._check_connector(connector, required=True) - _check_alerts(alerts) cust = self._resolve(customer) if cust.management is not None and team.name == cust.management.name: raise InvalidRequestError("That name is the Management location; name the team differently") @@ -906,10 +913,12 @@ def set_alerts(self, customer: CustomerRef, alerts: AlertSettings, *, team: Opti Anything left as None is kept. Existing rules keep their on or off state; a rule created here (one that was pending its phrases) starts switched off: ``activate_alerts`` switches it on. Returns the ids of the rules created or changed.""" - self._require_admin() - _check_alerts(alerts) + _check_customer_ref(customer) + _check_team_ref(team, required=False) if alerts is None: raise InvalidRequestError("alerts is required") + _check_alerts(alerts) + self._require_admin() cust = self._resolve(customer) teams = self._teams(cust, team) settings = self._settings_from(alerts) @@ -929,6 +938,9 @@ def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, """Attach a phone system to a customer created without one: the named team, or the first team and Management. Refuses (InvalidRequestError, before any write) where an active connector exists. Returns the teams it attached.""" + _check_customer_ref(customer) + _check_team_ref(team, required=False) + _check_connector_local(connector, required=True) self._require_admin() self._check_connector(connector, required=True) cust = self._resolve(customer) @@ -971,6 +983,8 @@ def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = No app only, and the team is listed under ``no_manager`` with the alert groups that have none. Returns ``{"switched_on": [rule ids], "no_manager": [{"location_id", "team", "missing"}]}``.""" + _check_customer_ref(customer) + _check_team_ref(team, required=False) self._require_admin() cust = self._resolve(customer) out: Dict[str, Any] = {"switched_on": [], "no_manager": []} @@ -1154,9 +1168,11 @@ def list_members(self, customer: CustomerRef, *, license: Optional[str] = None, on and their own line mapped; a Base Manager has all three products, is on Management and is in the alert groups of at least one team; an integration user is tagged as one; anyone else is "other", listed so it can be corrected.""" - self._require_admin() + _check_customer_ref(customer) + _check_team_ref(team, required=False) if license is not None and license not in LICENSES: raise InvalidRequestError(f"license: one of {list(LICENSES)}") + self._require_admin() cust = self._resolve(customer) lid = self._team(cust, team).location_id if team is not None else None out = [] @@ -1170,6 +1186,8 @@ def list_members(self, customer: CustomerRef, *, license: Optional[str] = None, def license_report(self, customer: CustomerRef) -> Dict[str, Any]: """People by license and the number of teams (Management not counted).""" + _check_customer_ref(customer) + self._require_admin() cust = self._resolve(customer) members = self.list_members(cust) by: Dict[str, List[Member]] = {k: [] for k in LICENSES} @@ -1364,10 +1382,13 @@ def add_base_user(self, customer: CustomerRef, person: PersonSpec, *, team: Team team's connector and added to the team's First Alert and Insights Hub lines and to every Base Manager and integration user of the team, then the invitation (if ``invite``). If the line cannot be mapped, AccountError (cause ExtensionMappingError) is raised and no invitation is sent.""" + _check_customer_ref(customer) + _check_person(person) + _check_team_ref(team) + line = _line(line) self._require_admin() cust = self._resolve(customer) t = self._team(cust, team) - line = _line(line) self._need_connector(t) self._check_existing(cust, person.email, "base_user") result = Member(user_id="", email=person.email, license="base_user", teams=[t.location_id], lines=[line]) @@ -1398,14 +1419,18 @@ def add_base_manager(self, customer: CustomerRef, person: PersonSpec, *, teams: Management (if ``line``); every Base User line of each team; the three alert groups, Insights Hub Access and Insights Hub Weekly Reports of each team (and the company-wide weekly reports group with ``company_reports=True``); alert email off. The invitation is sent last.""" - self._require_admin() - cust = self._resolve(customer) + _check_customer_ref(customer) + _check_person(person) if isinstance(teams, (str, Team)) or not teams: raise InvalidRequestError("teams: a list of one or more teams") + for x in teams: + _check_team_ref(x) + own = _line(line) if line is not None else None + self._require_admin() + cust = self._resolve(customer) ts = _dedupe_teams([self._team(cust, x) for x in teams]) if cust.management is None: raise InvalidRequestError("This customer has no Management location: run create_customer again") - own = _line(line) if line is not None else None if own: self._need_connector(cust.management) self._check_existing(cust, person.email, "base_manager") @@ -1430,9 +1455,11 @@ def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, inv tagged ``department: "integration"``, all three products, the alert groups and Insights Hub Access, alert email off, every team's lines. Later Base Users' lines are added to it. The company needs MFA off (``CustomerSpec.mfa_off``) for it to sign in.""" - self._require_admin() + _check_customer_ref(customer) + _check_person(person) if person.auth_method != "password": raise InvalidRequestError("An integration user signs in with a password: set auth_method='password'") + self._require_admin() cust = self._resolve(customer) if not cust.teams: raise InvalidRequestError("This customer has no team") @@ -1485,9 +1512,18 @@ def change_license(self, customer: CustomerRef, user_id: str, to: str, *, Safe to run again, also after an AccountError: a person part-way through the change is recognised and the change continues. Until it completes, ``result.lines`` and ``result.teams`` hold what the person had before.""" - self._require_admin() + _check_customer_ref(customer) + _check_user_id(user_id) if to not in ("base_user", "base_manager"): raise InvalidRequestError('to: "base_user" or "base_manager"') + if teams is not None: + if isinstance(teams, (str, Team)) or not teams: + raise InvalidRequestError("teams: a list of one or more teams") + for x in teams: + _check_team_ref(x) + if line is not None: + _line(line) + self._require_admin() cust = self._resolve(customer) if cust.management is None: raise InvalidRequestError("This customer has no Management location: run create_customer again") @@ -1598,6 +1634,12 @@ def move_user(self, customer: CustomerRef, user_id: str, *, from_team: TeamRef, """Move a Base User (membership and line) to another team, or swap one of a Base Manager's teams for another. Calls captured before the move stay with the old team (``Member.notes`` says so). Safe to run again, also after an AccountError: the move continues.""" + _check_customer_ref(customer) + _check_user_id(user_id) + _check_team_ref(from_team) + _check_team_ref(to_team) + if isinstance(from_team, str) and from_team == to_team: + raise InvalidRequestError("from_team and to_team are the same team") self._require_admin() cust = self._resolve(customer) src, dst = self._team(cust, from_team), self._team(cust, to_team) @@ -1685,8 +1727,12 @@ def change_line(self, customer: CustomerRef, user_id: str, old: str, new: str) - ``old`` is released only when no other Base User of the team still holds it. A Base Manager: their own line at Management only; a team line belongs to the Base User who holds it, so ``old`` must be the manager's own line.""" - self._require_admin() + _check_customer_ref(customer) + _check_user_id(user_id) old, new = _line(old, "old"), _line(new, "new") + if old == new: + raise InvalidRequestError("old and new are the same line") + self._require_admin() cust = self._resolve(customer) p, people = self._person(cust, user_id) result = self._member(p) @@ -1746,6 +1792,8 @@ def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = when no other Base User of the team holds it), clear their lines, then deactivate them. Removing a Base Manager or an integration user never takes a line off anyone else. ``notes`` names any team whose alert groups are left with no Base Manager (its alerts are not changed).""" + _check_customer_ref(customer) + _check_user_id(user_id) self._require_admin() cust = self._resolve(customer) p, people = self._person(cust, user_id, include_inactive=True) @@ -1785,6 +1833,12 @@ def send_invitations(self, customer: CustomerRef, *, user_ids: Optional[Sequence """Email invitations to people who have not signed in. Without ``user_ids``: everyone who was never sent one, or whose invitation has expired. With ``user_ids``: re-send to those of them who have not signed in. Returns the ids invited.""" + _check_customer_ref(customer) + if user_ids is not None: + if isinstance(user_ids, str): + raise InvalidRequestError("user_ids: a list of user ids") + for u in user_ids: + _check_user_id(u) self._require_admin() cust = self._resolve(customer) now = datetime.now(timezone.utc) @@ -1820,6 +1874,7 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st Returns ``{"teams": {location_id: {"team", "lines", "other", "first_alert", "insights_hub", "holders"}}, "applied"}``.""" + _check_customer_ref(customer) self._require_admin() cust = self._resolve(customer) people = self._index(cust) @@ -1871,6 +1926,7 @@ def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = pause each After Call webhook (its address is kept; it can't be deleted), clear each First Alert webhook, stop each connector (ends the phone-system subscription), deactivate the integration users, then deactivate the company. Ask your Tresic contact about retention of the customer's data.""" + _check_customer_ref(customer) self._require_admin() cust = self._resolve(customer) c = self._c @@ -1940,6 +1996,55 @@ def norm(ms: Sequence[Mapping[str, Any]]) -> Dict[str, List[str]]: return norm(a) == norm(b) +def _check_connector_local(cs: Optional[ConnectorSpec], required: bool = False) -> None: + if cs is None: + if required: + raise InvalidRequestError("A connector is required: pass a ConnectorSpec") + return + if not isinstance(cs, ConnectorSpec): + raise InvalidRequestError("connector must be a ConnectorSpec") + if not isinstance(cs.type, str) or not cs.type.strip(): + raise InvalidRequestError("connector.type is required") + + +def _check_customer_ref(customer: Any) -> None: + if isinstance(customer, Customer): + return + if not isinstance(customer, str) or not customer.strip(): + raise InvalidRequestError("customer: a Customer or a company id") + + +def _check_team_ref(team: Any, required: bool = True) -> None: + if team is None and not required: + return + if isinstance(team, Team): + return + if not isinstance(team, str) or not team.strip(): + raise InvalidRequestError("team: a Team, its location id or its name") + + +def _check_person(person: Any) -> None: + if not isinstance(person, PersonSpec): + raise InvalidRequestError("person must be a PersonSpec") + if not (person.email or "").strip() or "@" not in person.email: + raise InvalidRequestError("person.email is required") + if person.auth_method not in ("password", "sso"): + raise InvalidRequestError('person.auth_method: "password" or "sso"') + + +def _check_team_spec(team: Any) -> None: + if not isinstance(team, TeamSpec): + raise InvalidRequestError("team must be a TeamSpec") + for f in ("name", "street", "city", "state", "country", "zipcode", "vertical"): + if not str(getattr(team, f) or "").strip(): + raise InvalidRequestError(f"team.{f} is required") + + +def _check_user_id(user_id: Any) -> None: + if not isinstance(user_id, str) or not user_id.strip(): + raise InvalidRequestError("user_id is required") + + def _dedupe_teams(teams: List[Team]) -> List[Team]: seen, out = set(), [] for t in teams: diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index 51e7517..0431ac9 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -56,6 +56,16 @@ def check_base_url(base_url: str) -> str: raise InvalidRequestError("base_url must be an https:// URL (http:// only for localhost)") +def _retry_after_seconds(value: Optional[str]) -> Optional[float]: + """Retry-After in seconds, or None when absent or not a number of seconds.""" + if not value: + return None + try: + return max(0.0, float(value)) + except ValueError: + return None + + def check_app_url(app_url: str) -> str: """The app address for page links: https only, trailing slash removed.""" parts = urlsplit(app_url or "") @@ -79,12 +89,12 @@ class Client: def __init__( self, - base_url: str = DEFAULT_BASE_URL, email: Optional[str] = None, password: Optional[str] = None, + *, + base_url: str = DEFAULT_BASE_URL, token_store: Optional[TokenStore] = None, timeout: float = 30, - *, user_agent: Optional[str] = None, max_retries: int = 3, transport: Optional[httpx.BaseTransport] = None, @@ -190,11 +200,15 @@ def _login_locked(self) -> Dict[str, Any]: waited = False while True: resp = self._send_with_retries("POST", "/auth/login", op_id="login", json_body=body, - auth=False, retry_429=False) + auth=False, retry_429=False, retry_failures=True) if resp.status_code == 429 and not waited and self._login_wait > 0: - waited = True - self._sleep(self._login_wait) - continue + # Wait once, but only when the server's Retry-After fits the configured wait: a longer + # one fails at once with RateLimitError.retry_after instead of blocking first. + ra = _retry_after_seconds(resp.headers.get("Retry-After")) + if ra is None or ra <= self._login_wait: + waited = True + self._sleep(ra if ra is not None else self._login_wait) + continue break if resp.status_code >= 400: self._raise(resp, "login") @@ -254,7 +268,7 @@ def _renew_locked(self, tokens: Tokens) -> None: try: resp = self._send_with_retries("POST", "/auth/refresh", op_id="refresh", json_body={"refresh_token": refresh_token}, auth=False, - retry_429=False) + retry_429=False, retry_failures=True, only_unsent=True) except NetworkError: resp = None if resp is None or resp.status_code != 429: @@ -296,6 +310,7 @@ def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Toke if tokens is not None: h["Authorization"] = f"Bearer {tokens.access_token}" failed = None + sent = True try: return self._http.request(method, self._url(path), params=params or None, json=json_body, headers=h) @@ -304,15 +319,24 @@ def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Toke else "transport" if isinstance(exc, httpx.TransportError) else "decoding" if isinstance(exc, httpx.DecodingError) else "transport") failed = (kind, type(exc).__name__) + sent = not isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) # Raised outside the except block so the HTTP library's error, which holds the request, is not kept # on this error as its context. - raise NetworkError(*failed) + raise NetworkError(*failed, request_sent=sent) def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, json_body=None, headers: Optional[Dict[str, str]] = None, auth: bool = True, - retry_429: bool = True) -> httpx.Response: + retry_429: bool = True, retry_failures: Optional[bool] = None, + only_unsent: bool = False) -> httpx.Response: + """Send with the retry policy (README "Retries"): network failures and 5xx are retried up to + ``max_retries`` with backoff for idempotent requests (reads, updates, deletes, user create with + its idempotency key) and for sign-in and token renewal (``retry_failures``; renewal retries a + network failure only when the request never left, ``only_unsent``, so a refresh token is never + sent twice). 429 honours Retry-After up to MAX_RETRY_AFTER; a longer one fails at once.""" headers = dict(headers or {}) idempotent = method in RETRY_METHODS or "Idempotency-Key" in headers + if retry_failures is not None: + idempotent = retry_failures attempt = 0 refreshed = False while True: @@ -323,7 +347,8 @@ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, resp = self._send_raw(method, path, op_id=op_id, tokens=tokens, params=params, json_body=json_body, headers=headers) except NetworkError as exc: - if exc.kind != "decoding" and idempotent and attempt < self._max_retries: + if (exc.kind != "decoding" and idempotent and attempt < self._max_retries + and not (only_unsent and exc.request_sent)): self._sleep(self._backoff(attempt, None) or 0.0) attempt += 1 continue @@ -343,7 +368,7 @@ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, return resp @staticmethod - def _backoff(attempt: int, retry_after: Optional[str]) -> Optional[float]: + def _backoff(attempt: int, retry_after: Optional[str]) -> Optional[float]: # noqa: D401 """Seconds to wait before the next try, or None when Retry-After asks for more than MAX_RETRY_AFTER seconds.""" if retry_after: diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py index cf6df1f..5319957 100644 --- a/src/intelligence_cloud/conversations.py +++ b/src/intelligence_cloud/conversations.py @@ -192,6 +192,28 @@ class Reference: link: Optional[str] = None # the page in the app: /after-call-copilot/calls/ or .../first-alert-copilot/alerts/ +def _id(value: Any, name: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise InvalidRequestError(f"{name}: a non-empty id") + return value.strip() + + +def _check_team(team: Any) -> None: + if team is None or isinstance(team, TeamRef) or hasattr(team, "location_id"): + return + if not isinstance(team, str) or not team.strip(): + raise InvalidRequestError("team: a TeamRef, a location id or a team name") + + +def _check_due(due: Any) -> None: + if due is None or isinstance(due, date): + return + try: + date.fromisoformat(str(due)) + except ValueError: + raise InvalidRequestError("due: a date (YYYY-MM-DD)") from None + + class Conversations(Namespace): """A signed-in person's calls, tasks and alerts (user login).""" @@ -364,10 +386,11 @@ def calls(self, *, day: Optional[Union[date, datetime]] = None, since: Optional[ number: Optional[str] = None, search: Optional[str] = None, limit: int = 50) -> List[CallBrief]: """Calls, newest first, as briefs. Default: today. The window is at most 31 days and ``limit`` at most 200. ``number`` and ``search`` share the API's one search field: pass one or the other.""" - self._require_user() limit = self._limit(limit, MAX_LIMIT) start, end = self._window(day, since, until) term = _search_term(number, search) + _check_team(team) + self._require_user() lid = self._team_id(team) rows = self._pages(lambda n, cur: self._c.calls.list_calls( date_from=start, date_to=end, search=term, location_id=lid, limit=n, cursor=cur), limit) @@ -376,6 +399,7 @@ def calls(self, *, day: Optional[Union[date, datetime]] = None, since: Optional[ def brief(self, call_id: str) -> CallBrief: """One call: when, direction, parties, summary, key points, tasks, sentiment, topics and the alerts it raised. No transcript and no recording.""" + call_id = _id(call_id, "call_id") self._require_user() data = unwrap(self._c.calls.get_call(call_id)) or {} b = self._brief_from_row(data) @@ -400,6 +424,7 @@ def brief(self, call_id: str) -> CallBrief: def transcript(self, call_id: str) -> List[Dict[str, Any]]: """The transcript of one call: segments with ``time``, ``speaker``, ``name`` and ``text``.""" + call_id = _id(call_id, "call_id") self._require_user() data = unwrap(self._c.calls.get_call_transcript(call_id)) or {} return data.get("transcript") or [] @@ -407,15 +432,18 @@ def transcript(self, call_id: str) -> List[Dict[str, Any]]: def recording_link(self, call_id: str) -> Optional[RecordingLink]: """A link to the call's audio that expires, or None when the call has no recording. The SDK never downloads the audio. Treat the link as a secret: never log or store it.""" + call_id = _id(call_id, "call_id") self._require_user() return self._c.intelligence.get_recording_url(call_id) def caller_history(self, number: str, *, limit: int = 10) -> List[CallBrief]: """Recent briefs for one caller (the last 31 days), for use before a callback. ``limit`` at most 50.""" - self._require_user() limit = self._limit(limit, MAX_HISTORY) + if number is None or not str(number).strip(): + raise InvalidRequestError("number is required") term = _search_term(number, None) start, end = self._window(None, None, None, default_days=MAX_WINDOW_DAYS) + self._require_user() rows = self._pages(lambda n, cur: self._c.calls.list_calls( date_from=start, date_to=end, search=term, limit=n, cursor=cur), limit) return [self._brief_from_row(r) for r in rows] @@ -425,6 +453,8 @@ def caller_history(self, number: str, *, limit: int = 10) -> List[CallBrief]: def open_tasks(self, *, due: Optional[Union[date, str]] = None, team: Optional[Union[str, TeamRef]] = None) -> List[TaskBrief]: """Open tasks (up to 200), each with the id of the call it came from. ``due``: only tasks due that day.""" + _check_due(due) + _check_team(team) self._require_user() lid = self._team_id(team) rows = self._pages(lambda n, cur: self._c.tasks.list_tasks( @@ -436,11 +466,12 @@ def alerts(self, *, since: Optional[When] = None, until: Optional[When] = None, limit: int = 50) -> List[AlertBrief]: """Alerts on this person's teams, newest first. Default: today; at most 31 days and 200 alerts. ``status`` is refused: the API has no alert status filter yet.""" - self._require_user() if status is not None: raise InvalidRequestError("status: the API has no alert status filter yet") limit = self._limit(limit, MAX_LIMIT) start, end = self._window(None, since, until) + _check_team(team) + self._require_user() lid = self._team_id(team) rows = self._pages(lambda n, cur: self._c.alerts.list_alerts( date_from=start, date_to=end, location_id=lid, limit=n, cursor=cur), limit) @@ -448,8 +479,8 @@ def alerts(self, *, since: Optional[When] = None, until: Optional[When] = None, def alert(self, alert_id: str) -> Optional[AlertBrief]: """One alert with its call brief, or None when this login cannot see it.""" + aid = _id(alert_id, "alert_id").lower() self._require_user() - aid = str(alert_id).strip().lower() page = self._c.alerts.list_alerts(search=aid, limit=10) row = next((a for a in page.items if a.get("id") == aid), None) if row is None: @@ -463,11 +494,12 @@ def team_view(self, team: Union[str, TeamRef], *, day: Optional[Union[date, date since: Optional[When] = None, until: Optional[When] = None) -> TeamView: """For a manager: one team's counts, alerts, open tasks and briefs (up to 200) for a day or a window of at most 31 days. Default: today.""" - self._require_user() - lid = self._team_id(team) - if lid is None: + if team is None: raise InvalidRequestError("team is required") + _check_team(team) start, end = self._window(day, since, until) + self._require_user() + lid = self._team_id(team) first = self._c.calls.list_calls(date_from=start, date_to=end, location_id=lid, limit=_PAGE) rows = list(first.items) if first.has_more and first.next_cursor: @@ -489,8 +521,9 @@ def topics(self, *, since: Optional[When] = None, until: Optional[When] = None, team: Optional[Union[str, TeamRef]] = None) -> TopicsView: """What customers are raising and which topics are rising. Default: the last 7 days; at most 31. Needs Insights Hub access.""" - self._require_user() start, end = self._window(None, since, until, default_days=7) + _check_team(team) + self._require_user() lid = self._team_id(team) data = unwrap(self._c.insights.get_insights_dashboard(start=start, end=end, location_id=lid)) or {} stats = data.get("stats") or {} diff --git a/src/intelligence_cloud/errors.py b/src/intelligence_cloud/errors.py index ad08643..ed410fb 100644 --- a/src/intelligence_cloud/errors.py +++ b/src/intelligence_cloud/errors.py @@ -1,12 +1,28 @@ -"""Errors raised by the SDK. - -Everything the SDK raises derives from :class:`IntelligenceCloudError`. Errors returned by the API -derive from :class:`ApiError` and carry ``status``, ``code``, ``message`` and ``request_id``. +"""Errors raised by the SDK. The tree is the same in every SDK language: + + IntelligenceCloudError + |- ApiError (status, code, server_message, request_id, public_message; .message = server_message) + | |- AuthError + | | |- MfaRequiredError + | | `- PasswordExpiredError + | |- NotFoundError, ConflictError, ValidationError, RateLimitError (retry_after) + | `- NetworkError (status 0; kind transport | timeout | decoding) + |- InvalidRequestError (also a ValueError) + |- WrongLoginError + | `- FrontlineRequiredError (kept for client.intelligence) + |- ConnectorError + | `- ConnectorTimeoutError + |- ExtensionMappingError + |- AccountError (step, result, cause, find()) + `- WebhookPayloadError (also a ValueError) + `- PayloadTooLargeError """ from __future__ import annotations import re -from typing import Any, List, Optional +from typing import Any, List, Optional, TypeVar + +E = TypeVar("E", bound=BaseException) EXTENSION_CONFLICT_MESSAGE = "Extension is already monitored at another location." MFA_MESSAGE = "Integration users need MFA off for their company. API keys arrive in December 2026." @@ -24,19 +40,29 @@ class ApiError(IntelligenceCloudError): """The API answered with an error status. ``str(error)`` carries only the status, code and request id, plus text the SDK wrote itself - (``public_message``). The server's own text is on ``message``: it can echo phone numbers or other - values from the request, so keep it out of logs. Log ``status``, ``code`` and ``request_id``. + (``public_message``). The server's own text is on ``server_message`` (also ``message``): it can echo + phone numbers or other values from the request, so keep it out of logs. Log ``status``, ``code`` and + ``request_id``. """ def __init__(self, status: int, code: Optional[str], message: str, request_id: Optional[str] = None, *, public_message: Optional[str] = None): self.status = status self.code = code - self.message = message + self.server_message = message self.request_id = request_id self.public_message = public_message super().__init__(self._text()) + @property + def message(self) -> str: + """The server's own text; the same as ``server_message``.""" + return self.server_message + + @message.setter + def message(self, value: str) -> None: + self.server_message = value + def _text(self) -> str: parts = [f"HTTP {self.status}"] if self.code: @@ -56,8 +82,10 @@ class NetworkError(ApiError): or ``decoding``. The underlying HTTP library error is deliberately not attached: it holds the request, and a request can hold a password, a token or a connection key.""" - def __init__(self, kind: str, detail: str): + def __init__(self, kind: str, detail: str, request_sent: bool = True): self.kind = kind + # False when the connection was never made (the server cannot have acted on the request). + self.request_sent = request_sent super().__init__(0, "timeout" if kind == "timeout" else "network_error", "The request did not complete.", public_message=f"the request did not complete ({detail})") @@ -71,6 +99,17 @@ class PasswordExpiredError(AuthError): your secret store and sign in again.""" +class MfaRequiredError(AuthError): + """Sign-in returned ``mfa_required``. Integration users need MFA off for their company. + ``status`` is the sign-in response's status (200) and ``code`` is ``mfa_required``.""" + + def __init__(self, message: str = MFA_MESSAGE, status: int = 200): + super().__init__(status, "mfa_required", message, public_message=message) + + def _text(self) -> str: + return self.public_message or MFA_MESSAGE + + class NotFoundError(ApiError): """404. Also returned for records outside your login's scope.""" @@ -100,24 +139,6 @@ def __init__(self, status: int, code: Optional[str], message: str, request_id: O super().__init__(status, code, message, request_id, public_message=public_message) -class MfaRequiredError(IntelligenceCloudError): - """Sign-in returned ``mfa_required``. Integration users need MFA off for their company.""" - - def __init__(self, message: str = MFA_MESSAGE): - super().__init__(message) - - -class FrontlineRequiredError(IntelligenceCloudError): - """Conversation data needs a frontline login. Admin logins see empty lists by design.""" - - def __init__(self, role: Optional[str]): - self.role = role - super().__init__( - f"This login has role {role!r}. Conversation data (calls, alerts, tasks, insights) needs a " - "frontline_user login; admin logins get empty lists." - ) - - class ConnectorError(IntelligenceCloudError): """A connector ended in ``error``. ``state_reason`` says why (for example ``invalid_permissions``).""" @@ -131,14 +152,19 @@ def __init__(self, connector: Any): super().__init__(f"Connector {self.connector_id} is in error: {self.state_reason or 'unknown reason'}") -class ConnectorTimeoutError(IntelligenceCloudError): - """The connector did not reach a final status in time. Check it again later with get_connector.""" +class ConnectorTimeoutError(ConnectorError): + """The connector did not reach a final status in time. Check it again later with get_connector. + ``state_reason`` is usually empty: the connector is still settling.""" def __init__(self, connector: Any, waited: float): data = connector if isinstance(connector, dict) else {} self.connector = data + self.connector_id = data.get("id") self.status = data.get("status") - super().__init__(f"Connector {data.get('id')} still {self.status!r} after {waited:.0f} s") + self.state_reason = data.get("state_reason") + self.status_message = data.get("status_message") + self.waited = waited + IntelligenceCloudError.__init__(self, f"Connector {self.connector_id} still {self.status!r} after {waited:.0f} s") class ExtensionMappingError(IntelligenceCloudError): @@ -169,6 +195,20 @@ def __init__(self, step: str, result: Any, cause: BaseException): self.cause = cause super().__init__(f"Stopped at step {step!r}: {cause}. Run the helper again to continue.") + def find(self, error_type: "type[E]") -> "Optional[E]": + """The first error of ``error_type`` in the cause chain (``cause``, its ``cause`` ...), or None. + + A line another location holds arrives as AccountError -> ExtensionMappingError -> ConflictError: + ``err.find(ConflictError)`` returns the ConflictError.""" + seen = set() + err: Optional[BaseException] = self.cause + while err is not None and id(err) not in seen: + seen.add(id(err)) + if isinstance(err, error_type): + return err + err = getattr(err, "cause", None) or err.__cause__ + return None + class WrongLoginError(IntelligenceCloudError): """The helper needs the other kind of login. @@ -189,6 +229,18 @@ def __init__(self, role: Optional[str], needed: str): super().__init__(text) +class FrontlineRequiredError(WrongLoginError): + """``client.intelligence`` conversation data needs a frontline login. Admin logins see empty lists by + design. A WrongLoginError, kept under this name for ``client.intelligence``.""" + + def __init__(self, role: Optional[str]): + self.role = role + self.needed = "user" + IntelligenceCloudError.__init__( + self, f"This login has role {role!r}. Conversation data (calls, alerts, tasks, insights) needs a " + "frontline_user login; admin logins get empty lists.") + + class WebhookPayloadError(IntelligenceCloudError, ValueError): """The webhook body is not JSON, or is a malformed After Call or First Alert event. Answer 400.""" diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index c5218db..0b3c83d 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -1,13 +1,15 @@ -"""Receive the After Call and First Alert webhooks: parse the event and drop duplicates. +"""Receive the After Call and First Alert webhooks: parse the event and spot exact re-deliveries. The webhook sends every call at the location, unsigned. Use an unguessable HTTPS URL, answer 2xx within 2 seconds and do the work afterwards. Treat an event as a notification: read the call with -``client.intelligence.get_call(event.call.id)`` before you write it anywhere. Expect repeats of the -same ``call.id``; upsert on it. Event types you don't handle come back as :class:`UnknownEvent`: -answer 2xx and ignore them. +``client.intelligence.get_call(event.call.id)`` before you write it anywhere. The same call can arrive +again, and a later delivery can carry newer data: store by call id (``upsert_key``) and upsert, so the +later delivery replaces the earlier one. Event types you don't handle come back as +:class:`UnknownEvent`: answer 2xx and ignore them. """ from __future__ import annotations +import hashlib import json import threading from collections import OrderedDict @@ -158,8 +160,12 @@ class FirstAlertEvent: """A First Alert delivery. Take the alert id, answer 2xx, then read the alert with ``client.conversations.alert(event.alert_id)``. Printing it shows only the alert id and time. - The published event schema is an open object (alert id, rule, location, call, time), so only the - alert id is required; the other fields are None when the delivery does not carry them.""" + **The First Alert payload is not final.** The published schema is an open object (alert id, rule, + location, call, time). The parser needs only an alert id: any non-empty string under ``alert_id``, + ``alert.id`` or ``id``. Rule, location, call and time are read from the shapes seen today + (``rule_name``/``rule.name``/``rule``/``alert_name``, ``location_id``/``location.id``, + ``call_id``/``call.id``, ``timestamp``/``fired_at``/``created_at``) and are None when absent. ``raw`` is + the whole payload as received, for anything the parser does not read yet.""" alert_id: str rule: Optional[str] = None @@ -183,10 +189,6 @@ def _first_str(*values: Any) -> Optional[str]: return None -def _uuid(value: Optional[str]) -> Optional[str]: - if value is None: - return None - return value.lower() if _spec.is_uuid(value) else None def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping[str, Any]: @@ -217,7 +219,7 @@ def sub(key: str) -> Mapping[str, Any]: return v if isinstance(v, Mapping) else {} alert, rule, call, loc = sub("alert"), sub("rule"), sub("call"), sub("location") - alert_id = _uuid(_first_str(data.get("alert_id"), alert.get("id"), data.get("id"))) + alert_id = _first_str(data.get("alert_id"), alert.get("id"), data.get("id")) if alert_id is None: raise WebhookPayloadError("event has no alert id") stamp = _first_str(data.get("timestamp"), data.get("fired_at"), data.get("created_at"), alert.get("created_at")) @@ -229,8 +231,8 @@ def sub(key: str) -> Mapping[str, Any]: alert_id=alert_id, rule=_first_str(data.get("rule_name"), rule.get("name"), data.get("rule") if isinstance(data.get("rule"), str) else None, data.get("alert_name"), alert.get("rule_name"), alert.get("name")), - location_id=_uuid(_first_str(data.get("location_id"), loc.get("id"), alert.get("location_id"))), - call_id=_uuid(_first_str(data.get("call_id"), call.get("id"), alert.get("call_id"))), + location_id=_first_str(data.get("location_id"), loc.get("id"), alert.get("location_id")), + call_id=_first_str(data.get("call_id"), call.get("id"), alert.get("call_id")), timestamp=when, is_test=data.get("is_test") is True, raw=dict(data), @@ -262,20 +264,78 @@ def add(self, key: str) -> bool: return True +def _canonical_hash(body: Any) -> str: + """A stable hash of a JSON body: keys sorted, no whitespace.""" + text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str) + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def _as_event(item: Any) -> Any: + """An AfterCallEvent, FirstAlertEvent or UnknownEvent from an event, a parsed body or raw bytes.""" + if isinstance(item, (AfterCallEvent, FirstAlertEvent, UnknownEvent)): + return item + body = _load(item, MAX_EVENT_BYTES) + ev = parse_after_call_event(body) + if isinstance(ev, UnknownEvent): + try: + return parse_first_alert_event(body) + except WebhookPayloadError: + return ev + return ev + + +def upsert_key(event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> str: + """The key to store a delivery under: the call id for an After Call event, the alert id for a First + Alert event. Store by it and upsert: a later delivery for the same call replaces the earlier one.""" + ev = _as_event(event) + if isinstance(ev, AfterCallEvent): + return ev.call.id + if isinstance(ev, FirstAlertEvent): + return ev.alert_id + raise WebhookPayloadError("not an After Call or First Alert event") + + +def delivery_key(event: Any) -> str: + """The identity of one exact delivery: event type, location, call (or alert) id, and a SHA-256 of the + canonical JSON body. A re-delivery of the same content has the same key; a later delivery with + newer data does not.""" + if isinstance(event, str) and not event.lstrip().startswith("{"): + return "id:" + event.strip() # a bare id (an alert id): alerts do not change once raised + ev = _as_event(event) + if isinstance(ev, AfterCallEvent): + return f"{ev.type}:{ev.location_id}:{ev.call.id}:{_canonical_hash(ev.raw)}" + if isinstance(ev, FirstAlertEvent): + return f"first_alert:{ev.alert_id}:{_canonical_hash(ev.raw)}" + return f"{ev.type}:{_canonical_hash(ev.raw)}" + + class Deduplicator: - """Spots repeat deliveries of the same call. Pass a shared ``store`` when you run several workers. + """Spots exact re-deliveries, and never hides newer data. + + ``is_duplicate(event)`` is True only when the same delivery arrives again: the same event type, + location and call id **and** the same content (a SHA-256 of the canonical JSON body, because the + payload carries no per-delivery version). A later delivery for the same call with changed content + is not a duplicate: store it under ``upsert_key(event)`` (the call id) and replace the earlier copy. - The same name and meaning in every SDK: ``is_duplicate`` (Python), ``isDuplicate`` (PHP, - TypeScript) returns True for a repeat. A repeat can carry newer data: when you keep a copy, upsert - on ``call.id`` rather than dropping the later delivery. + It accepts an event object, a parsed body or the raw request bytes. A bare string that is not JSON + is taken as an exact id (for First Alert alert ids). The same name and meaning in every SDK: + ``is_duplicate`` (Python), ``isDuplicate`` (PHP, TypeScript). + + The default store is in memory, per process: with more than one worker or process, pass a shared + ``store`` whose ``add(key)`` returns True only for a new key (for example a cache's set-if-absent + with an expiry). """ def __init__(self, max_size: int = 10_000, store: Optional[DedupStore] = None): self.store = store or MemoryDedupStore(max_size) - def is_duplicate(self, event_or_call_id: Union[AfterCallEvent, str]) -> bool: - """True if this call was seen before; otherwise records it and returns False.""" - key = event_or_call_id.call.id if isinstance(event_or_call_id, AfterCallEvent) else str(event_or_call_id) - if not key: - raise ValueError("a call id is required") - return not self.store.add(key) + def is_duplicate(self, event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> bool: + """True for an exact re-delivery; otherwise records the delivery and returns False.""" + if event is None or event == "" or event == b"": + raise ValueError("an event is required") + return not self.store.add(delivery_key(event)) + + @staticmethod + def upsert_key(event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> str: + """The call id (After Call) or alert id (First Alert) to store the delivery under.""" + return upsert_key(event) diff --git a/tests/unit/test_conversations.py b/tests/unit/test_conversations.py index 06c2c0a..1d7da63 100644 --- a/tests/unit/test_conversations.py +++ b/tests/unit/test_conversations.py @@ -184,19 +184,22 @@ def test_parse_first_alert_event_shapes(): flat = {"alert_id": ALERT.upper(), "rule_name": "Customer Threat", "location_id": LOC, "call_id": CALL, "timestamp": "2026-11-02T16:46:12Z"} ev = ic.parse_first_alert_event(json.dumps(flat)) - assert (ev.alert_id, ev.rule, ev.location_id, ev.call_id) == (ALERT, "Customer Threat", LOC, CALL) + assert (ev.alert_id, ev.rule, ev.location_id, ev.call_id) == (ALERT.upper(), "Customer Threat", LOC, CALL) assert ev.timestamp == datetime(2026, 11, 2, 16, 46, 12, tzinfo=timezone.utc) - assert repr(ev) == f"FirstAlertEvent(alert_id='{ALERT}', timestamp='2026-11-02T16:46:12+00:00')" + assert repr(ev) == f"FirstAlertEvent(alert_id='{ALERT.upper()}', timestamp='2026-11-02T16:46:12+00:00')" + assert ev.raw == flat # the whole payload, as received nested = {"alert": {"id": ALERT}, "rule": {"name": "Upset Customer"}, "location": {"id": LOC}, "call": {"id": CALL, "caller_number": "+15555550142"}, "fired_at": "2026-11-02T16:46:12Z"} ev2 = ic.Client(email="x@example.com", password="pw").conversations.parse_first_alert_event(json.dumps(nested).encode()) assert (ev2.alert_id, ev2.rule, ev2.call_id) == (ALERT, "Upset Customer", CALL) assert "5555550142" not in repr(ev2) assert ic.parse_first_alert_event({"id": ALERT}).rule is None + # the payload is not final: any non-empty string id is accepted + assert ic.parse_first_alert_event(b'{"alert_id": "fa-12345"}').alert_id == "fa-12345" def test_parse_first_alert_event_refuses_bad_bodies(): - for bad in (b"not json", b"[1]", b'{"alert_id": "not-a-uuid"}', b"{}"): + for bad in (b"not json", b"[1]", b'{"alert_id": ""}', b'{"alert_id": 5}', b"{}"): with pytest.raises(ic.WebhookPayloadError): ic.parse_first_alert_event(bad) with pytest.raises(ic.PayloadTooLargeError): diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py new file mode 100644 index 0000000..6fd72e1 --- /dev/null +++ b/tests/unit/test_policy.py @@ -0,0 +1,303 @@ +"""0.3.0 policies: input checks before any request, the retry policy, the error tree, the client +signature, AccountError.find and the Deduplicator rule.""" +from __future__ import annotations + +import inspect +import json +from datetime import date, datetime, timedelta, timezone +from pathlib import Path + +import httpx +import pytest + +import intelligence_cloud as ic + +from .test_client import UID, login_ok, make, token_body + +SAMPLE = Path(__file__).resolve().parents[2] / "examples" / "after-call-sample.json" + + +# ---------------------------------------------------------------------- the error tree (copy this table) + +ERROR_TREE = [ + # (class, parent) + ("ApiError", "IntelligenceCloudError"), + ("AuthError", "ApiError"), + ("MfaRequiredError", "AuthError"), + ("PasswordExpiredError", "AuthError"), + ("NotFoundError", "ApiError"), + ("ConflictError", "ApiError"), + ("ValidationError", "ApiError"), + ("RateLimitError", "ApiError"), + ("NetworkError", "ApiError"), + ("InvalidRequestError", "IntelligenceCloudError"), + ("WrongLoginError", "IntelligenceCloudError"), + ("FrontlineRequiredError", "WrongLoginError"), + ("ConnectorError", "IntelligenceCloudError"), + ("ConnectorTimeoutError", "ConnectorError"), + ("ExtensionMappingError", "IntelligenceCloudError"), + ("AccountError", "IntelligenceCloudError"), + ("WebhookPayloadError", "IntelligenceCloudError"), + ("PayloadTooLargeError", "WebhookPayloadError"), +] +# Python only: these are also ValueErrors. +ALSO_VALUE_ERROR = ["InvalidRequestError", "WebhookPayloadError"] + + +@pytest.mark.parametrize("name,parent", ERROR_TREE) +def test_error_tree(name, parent): + cls, base = getattr(ic, name), getattr(ic, parent) + assert issubclass(cls, base) + assert issubclass(cls, ic.IntelligenceCloudError) + + +def test_error_tree_is_complete_and_value_errors(): + exported = {n for n in ic.__all__ if n.endswith("Error") and isinstance(getattr(ic, n), type)} + assert exported == {n for n, _ in ERROR_TREE} | {"IntelligenceCloudError"} + for n in ALSO_VALUE_ERROR: + assert issubclass(getattr(ic, n), ValueError) + + +def test_api_error_fields(): + e = ic.ConflictError(409, "CONFLICT", "server text 5555550142", "req-1", public_message="ours") + assert e.server_message == e.message == "server text 5555550142" + assert (e.status, e.code, e.request_id, e.public_message) == (409, "CONFLICT", "req-1", "ours") + assert "5555550142" not in str(e) + m = ic.MfaRequiredError() + assert m.code == "mfa_required" and "December 2026" in str(m) and isinstance(m, ic.AuthError) + t = ic.ConnectorTimeoutError({"id": "c1", "status": "connecting"}, 600) + assert isinstance(t, ic.ConnectorError) and t.connector_id == "c1" and t.status == "connecting" + + +def test_account_error_find(): + conflict = ic.ConflictError(409, "CONFLICT", "x", extensions=["2101"]) + err = ic.AccountError("line", None, ic.ExtensionMappingError("u1", conflict)) + assert err.find(ic.ConflictError) is conflict + assert err.find(ic.ExtensionMappingError).user_id == "u1" + assert err.find(ic.ApiError) is conflict and err.find(ic.RateLimitError) is None + assert ic.AccountError("s", None, ic.InvalidRequestError("bad")).find(ic.ConflictError) is None + + +# ---------------------------------------------------------------------- A4: the client signature + + +def test_client_takes_email_and_password_first(): + c = ic.Client("someone@example.com", "pw") + assert c._email == "someone@example.com" and c._password == "pw" + params = list(inspect.signature(ic.Client.__init__).parameters.values())[1:] + assert [p.name for p in params[:2]] == ["email", "password"] + assert all(p.kind is inspect.Parameter.KEYWORD_ONLY for p in params[2:]) + with pytest.raises(TypeError): + ic.Client("someone@example.com", "pw", "https://app.example.com/api/v1") # type: ignore[misc] + + +# ---------------------------------------------------------------------- A1: checks before any request + + +class Down: + """A transport that fails every request, and counts them.""" + + def __init__(self): + self.n = 0 + + def __call__(self, request): + self.n += 1 + raise httpx.ConnectError("down", request=request) + + +def down_client(): + t = Down() + return ic.Client("someone@example.com", "pw", transport=httpx.MockTransport(t), sleep=lambda s: None, + max_retries=0), t + + +def _bad_calls(c): + now = datetime.now(timezone.utc) + conv, acc = c.conversations, c.accounts + person = ic.PersonSpec("x@example.com", "A", "B") + team = ic.TeamSpec("Riverbend - Main", "1 River Rd", "Springfield", "IL", "US", "62701", "service-providers") + return [ + lambda: conv.calls(since=now - timedelta(days=40)), + lambda: conv.calls(limit=500), + lambda: conv.calls(number="5555550142", search="billing"), + lambda: conv.calls(day=date(2026, 11, 2), since=now), + lambda: conv.calls(team=""), + lambda: conv.alerts(status="open"), + lambda: conv.alerts(limit=0), + lambda: conv.brief(""), + lambda: conv.transcript(None), # type: ignore[arg-type] + lambda: conv.recording_link(""), + lambda: conv.caller_history("5555550142", limit=51), + lambda: conv.caller_history(""), + lambda: conv.open_tasks(due="tomorrow"), + lambda: conv.alert(""), + lambda: conv.team_view(None), # type: ignore[arg-type] + lambda: conv.topics(since=now - timedelta(days=60)), + lambda: acc.create_customer("not a spec"), # type: ignore[arg-type] + lambda: acc.create_customer(ic.CustomerSpec("Riverbend Auto Group", person, team)), # no phone + lambda: acc.create_customer(ic.CustomerSpec( + "Riverbend Auto Group", ic.PersonSpec("x@example.com", "A", "B", phone_number="+15555550100"), team, + alerts=ic.AlertSettings(low_sentiment=ic.AlertSetting(sentiment_below=0)))), + lambda: acc.get_customer(""), + lambda: acc.add_team("company-1", team, None), # type: ignore[arg-type] + lambda: acc.set_alerts("company-1", None), # type: ignore[arg-type] + lambda: acc.set_connector("company-1", "netsapiens"), # type: ignore[arg-type] + lambda: acc.add_base_user("company-1", person, team="t", line=""), + lambda: acc.add_base_user("company-1", "x@example.com", team="t", line="2101"), # type: ignore[arg-type] + lambda: acc.add_base_manager("company-1", person, teams=[]), + lambda: acc.add_integration_user("company-1", ic.PersonSpec("x@example.com", "A", "B", auth_method="sso")), + lambda: acc.change_license("company-1", "u1", "manager"), + lambda: acc.move_user("company-1", "u1", from_team="t", to_team="t"), + lambda: acc.change_line("company-1", "u1", "2101", "2101"), + lambda: acc.remove_user("company-1", ""), + lambda: acc.list_members("company-1", license="seat-holder"), + lambda: acc.send_invitations("company-1", user_ids="u1"), # type: ignore[arg-type] + lambda: acc.activate_alerts(""), + lambda: acc.offboard_customer(None), # type: ignore[arg-type] + ] + + +def test_bad_input_raises_before_any_request(): + c, t = down_client() + for i, call in enumerate(_bad_calls(c)): + with pytest.raises(ic.InvalidRequestError): + call() + assert t.n == 0, f"case {i} sent a request" + + +# ---------------------------------------------------------------------- A2: the retry policy + + +def test_sign_in_retries_a_503_and_a_network_failure(): + state = {"n": 0} + + def h(r): + if r.url.path.endswith("/auth/login"): + state["n"] += 1 + if state["n"] == 1: + return httpx.Response(503, json={"error": {"code": "UNAVAILABLE"}}) + if state["n"] == 2: + raise httpx.ConnectError("down", request=r) + return login_ok(r) + return httpx.Response(200, json={"data": {"id": UID, "role": "frontline_user"}}) + c, t, sleeps = make(h) + c.account.get_me() + assert state["n"] == 3 and len(sleeps) == 2 + + +def test_sign_in_429_longer_than_the_wait_fails_at_once(): + def h(r): + return httpx.Response(429, headers={"Retry-After": "120"}, json={"error": {"code": "RATE_LIMITED"}}) + c, t, sleeps = make(h) + with pytest.raises(ic.RateLimitError) as e: + c.login() + assert sleeps == [] and e.value.retry_after == 120 and len(t.requests) == 1 + + +def test_sign_in_429_within_the_wait_waits_retry_after_once(): + state = {"n": 0} + + def h(r): + state["n"] += 1 + if state["n"] == 1: + return httpx.Response(429, headers={"Retry-After": "5"}, json={}) + return login_ok(r) + c, t, sleeps = make(h) + c.login() + assert sleeps == [5.0] + + +def test_reads_retry_5xx_up_to_max_retries_and_creates_do_not(): + def h(r): + if r.url.path.endswith("/auth/login"): + return login_ok(r) + return httpx.Response(503, json={"error": {"code": "UNAVAILABLE"}}) + c, t, sleeps = make(h, max_retries=3) + with pytest.raises(ic.ApiError) as e: + c.account.get_me() + assert e.value.status == 503 and len([r for r in t.requests if r.url.path.endswith("/me")]) == 4 + assert len(sleeps) == 3 and all(s <= 8 * 1.5 for s in sleeps) + with pytest.raises(ic.ApiError): + c.companies.create_company(UID, {"company_name": "Riverbend Auto Group", "primary_admin_contact_name": "A", + "primary_admin_contact_email": "a@example.com", + "primary_admin_contact_phone": "+15555550100"}) + assert len([r for r in t.requests if r.method == "POST" and r.url.path.endswith("/companies")]) == 1 + + +def test_user_create_retries_with_the_same_idempotency_key(): + keys = [] + + def h(r): + if r.url.path.endswith("/auth/login"): + return login_ok(r) + keys.append(r.headers["Idempotency-Key"]) + if len(keys) == 1: + return httpx.Response(503, json={}) + return httpx.Response(201, json={"data": {"type": "company_user", "attributes": {"id": UID}}}) + c, t, sleeps = make(h) + c.users.create_company_user(UID, {"email": "a@example.com", "first_name": "A", "last_name": "B", + "role": "frontline_user"}) + assert len(keys) == 2 and keys[0] == keys[1] + + +def test_renewal_retries_only_a_request_that_never_left(): + sent = [] + + def h(r): + p = r.url.path + if p.endswith("/auth/login"): + sent.append("login") + return httpx.Response(200, json=token_body(9)) + if p.endswith("/auth/refresh"): + sent.append("refresh") + if sent.count("refresh") == 1: + raise httpx.ConnectError("no route", request=r) # never reached the server: retried + if sent.count("refresh") == 2: + raise httpx.ReadTimeout("slow", request=r) # may have been used: not sent again + return httpx.Response(200, json=token_body(2)) + if r.headers["Authorization"] == "Bearer A1": + return httpx.Response(401, json={}) + return httpx.Response(200, json={"data": {"id": UID, "role": "frontline_user"}}) + c, t, sleeps = make(h, token_store=ic.MemoryTokenStore(ic.Tokens("A1", "R1", expires_at=0))) + c.account.get_me() + assert sent == ["refresh", "refresh", "login"] + + +# ---------------------------------------------------------------------- C: the Deduplicator + + +def test_deduplicator_rule(): + body = json.loads(SAMPLE.read_text()) + d = ic.Deduplicator() + raw = json.dumps(body).encode() + assert d.is_duplicate(raw) is False + assert d.is_duplicate(raw) is True # identical re-delivery + assert d.is_duplicate(ic.parse_after_call_event(raw)) is True # the same delivery, parsed + assert d.is_duplicate(json.dumps(body, indent=2, sort_keys=True)) is True # formatting does not matter + newer = json.loads(json.dumps(body)) + newer["summary"]["text"] = "Updated summary." + assert d.is_duplicate(newer) is False # same call, newer data: never dropped + assert ic.upsert_key(newer) == body["call"]["id"] == d.upsert_key(raw) + other = json.loads(json.dumps(body)) + other["call"]["id"] = "0193b6d0-0000-7a3b-8c4d-000000000002" + assert d.is_duplicate(other) is False # different call + alert = {"alert_id": "0193b6e1-1e2f-7a3b-8c4d-5e6f7a8b9c02", "rule_name": "Upset Customer"} + assert d.is_duplicate(alert) is False and d.is_duplicate(json.dumps(alert)) is True + assert ic.upsert_key(alert) == alert["alert_id"] + assert d.is_duplicate("0193b6e1-alert") is False and d.is_duplicate("0193b6e1-alert") is True # a bare id + + +def test_deduplicator_uses_a_shared_store(): + class Shared: + def __init__(self): + self.keys = set() + + def add(self, key): + if key in self.keys: + return False + self.keys.add(key) + return True + store = Shared() + a, b = ic.Deduplicator(store=store), ic.Deduplicator(store=store) + raw = SAMPLE.read_bytes() + assert a.is_duplicate(raw) is False and b.is_duplicate(raw) is True From 1ae6338f276a59fdd595092e8db7f125d3adc4af Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 18:35:19 -0700 Subject: [PATCH 02/11] Ship intelligence_cloud.testing: a supported fake API FakeAPI.client(role="admin"|"user") returns a real Client wired to an in-memory fake. seed_customer() and seed_calls() add fictional data; connector_outcome, fail_write, network_down and rate_limit cover the failures callers must handle; requests and writes log every request. With strict=True (default) it refuses unknown paths and methods, unknown query parameters and bodies missing required fields, from the bundled spec. The unit tests now use it; tests/unit/fake_api.py re-exports it. Connector waits also count the check intervals slept, so a replaced sleep cannot spin for the full timeout. Co-Authored-By: Claude Opus 5.5 --- src/intelligence_cloud/resources.py | 6 +- src/intelligence_cloud/testing/__init__.py | 21 + src/intelligence_cloud/testing/_fake.py | 824 +++++++++++++++++++++ tests/unit/fake_api.py | 551 +------------- tests/unit/test_accounts.py | 48 +- tests/unit/test_review_fixes.py | 14 +- tests/unit/test_testing_module.py | 143 ++++ 7 files changed, 1026 insertions(+), 581 deletions(-) create mode 100644 src/intelligence_cloud/testing/__init__.py create mode 100644 src/intelligence_cloud/testing/_fake.py create mode 100644 tests/unit/test_testing_module.py diff --git a/src/intelligence_cloud/resources.py b/src/intelligence_cloud/resources.py index 1a1b4a6..226d51e 100644 --- a/src/intelligence_cloud/resources.py +++ b/src/intelligence_cloud/resources.py @@ -176,6 +176,7 @@ class ConnectorsAPI(g.ConnectorsAPI): def wait_for_status(self, location_id: str, connector_id: str, final: Sequence[str], timeout: float = 600.0, raise_on_error: bool = True) -> Dict[str, Any]: start = time.monotonic() + checks = 0 while True: conn = unwrap(self.get_connector(location_id, connector_id)) status = conn.get("status") @@ -183,10 +184,13 @@ def wait_for_status(self, location_id: str, connector_id: str, final: Sequence[s raise ConnectorError(conn) if status in final: return conn - waited = time.monotonic() - start + # The time waited: the clock, or the check intervals slept so far when the client's sleep is + # replaced (tests, the testing module), whichever is longer. + waited = max(time.monotonic() - start, checks * self.check_interval) if waited >= timeout: raise ConnectorTimeoutError(conn, waited) self._c._sleep(self.check_interval) + checks += 1 def create_connector(self, location_id: str, body: Mapping[str, Any], *, wait: bool = True, timeout: float = 600.0) -> Any: diff --git a/src/intelligence_cloud/testing/__init__.py b/src/intelligence_cloud/testing/__init__.py new file mode 100644 index 0000000..ca6bafe --- /dev/null +++ b/src/intelligence_cloud/testing/__init__.py @@ -0,0 +1,21 @@ +"""Test your integration with no account: a fake Intelligence Cloud API. + + from intelligence_cloud.testing import FakeAPI + + api = FakeAPI() + seeded = api.seed_customer() # "Riverbend Auto Group", fictional + admin = api.client(role="admin") + admin.accounts.add_base_user(seeded.customer, PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=seeded.customer.teams[0], line="2109") + assert ("POST", f"/companies/{seeded.company_id}/users") in api.writes + + api.seed_calls(3) + briefs = api.client(role="user").conversations.calls() + +``FakeAPI.client`` returns a real :class:`~intelligence_cloud.Client`, so your code runs unchanged. The +fake keeps its state in memory, refuses requests the published spec does not define, and has knobs for +the failures your code must handle. It is supported: its names follow the SDK's version. +""" +from ._fake import CONNECTOR_OUTCOMES, FakeAPI, FakeRequest, SeededCustomer, new_id + +__all__ = ["FakeAPI", "FakeRequest", "SeededCustomer", "CONNECTOR_OUTCOMES", "new_id"] diff --git a/src/intelligence_cloud/testing/_fake.py b/src/intelligence_cloud/testing/_fake.py new file mode 100644 index 0000000..ac90c06 --- /dev/null +++ b/src/intelligence_cloud/testing/_fake.py @@ -0,0 +1,824 @@ +"""The fake API behind :mod:`intelligence_cloud.testing`: an in-memory stand-in served through +``httpx.MockTransport``. No network, no account. Every value it holds is fictional.""" +from __future__ import annotations + +import json +import re +import uuid +from dataclasses import dataclass, field +from datetime import datetime, time as dtime, timedelta, timezone +from typing import Any, Callable, Dict, List, Optional, Tuple + +import httpx + +from .. import _spec +from ..client import Client + +RESELLER = "00000000-0000-4000-8000-0000000000aa" +VERTICAL = "00000000-0000-4000-8000-0000000000bb" +CONNECTOR_TYPES = [{"key": "netsapiens", "name": "NetSapiens"}, {"key": "examplepbx", "name": "Example PBX"}] +SECRET_WORDS = ("key", "secret", "token", "password") +ROLES = {"admin": "reseller_admin", "user": "frontline_user"} +CONNECTOR_OUTCOMES = ("active", "connected", "error", "stuck") + + +def new_id() -> str: + return str(uuid.uuid4()) + + +def res(type_: str, attrs: Dict[str, Any]) -> Dict[str, Any]: + return {"data": {"type": type_, "attributes": attrs}} + + +def page(rows: List[Dict[str, Any]], type_: Optional[str] = None) -> Dict[str, Any]: + data = [{"type": type_, "attributes": r} for r in rows] if type_ else rows + return {"data": data, "pagination": {"has_more": False, "next_cursor": None, "total_count": len(rows)}} + + +def _error(status: int, code: str, message: str) -> httpx.Response: + return httpx.Response(status, json={"error": {"code": code, "message": message, "request_id": "req-fake"}}) + + +@dataclass +class FakeRequest: + """One request the fake received (sign-in and token renewal are not logged).""" + + method: str + path: str # without the /api/v1 prefix + query: Dict[str, str] + body: Any + operation: Optional[str] # the operationId it matched in the published spec + + +@dataclass +class SeededCustomer: + """What ``FakeAPI.seed_customer`` built: the customer and the people's ids by email.""" + + customer: Any # intelligence_cloud.Customer + base_users: Dict[str, str] = field(default_factory=dict) + managers: Dict[str, str] = field(default_factory=dict) + + @property + def company_id(self) -> str: + return self.customer.company_id + + +def _op_table() -> List[Tuple[str, "re.Pattern[str]", str]]: + """(method, path regex, operationId) for every published operation, most specific first.""" + rows = [] + for op_id, op in _spec.spec()["operations"].items(): + rx = re.compile("^" + re.sub(r"\{[^}]+\}", "[^/]+", op["path"]) + "$") + rows.append((op["path"].count("{"), -len(op["path"]), op["method"], rx, op_id)) + rows.sort(key=lambda r: (r[0], r[1])) + return [(m, rx, op_id) for _, _, m, rx, op_id in rows] + + +class FakeAPI: + """An in-memory Intelligence Cloud API for tests and CI. Use :meth:`client` to get a real + :class:`~intelligence_cloud.Client` wired to it. + + It behaves like the API where it matters to callers: products, groups and alert email preferences + are per location; number mappings are company-wide with one extension per location (409 otherwise); + new users start with alert email on; connectors settle in the background; a duplicate email is 409. + + With ``strict=True`` (the default) it refuses requests the published spec does not define: an + unknown path or method (404), an unknown query parameter (400) or a body missing a required field + (422), with the API's error shape. + + Knobs for the failures your code must handle: ``connector_outcome`` ("active", "connected", "error" + or "stuck"), :meth:`fail_write`, :meth:`network_down` and :meth:`rate_limit`. Assert on + :attr:`requests` and :attr:`writes`. + """ + + def __init__(self, *, connector_outcome: str = "active", role: str = "admin", strict: bool = True): + self.requests: List[FakeRequest] = [] + self.calls: List[Tuple[str, str]] = [] # (METHOD, full path), kept for older tests + self.bodies: List[Tuple[str, str, Any]] = [] + self.connector_outcome = connector_outcome + self.role = ROLES.get(role, role) + self.strict = strict + self.companies: Dict[str, Dict[str, Any]] = {} + self.locations: Dict[str, Dict[str, Any]] = {} + self.groups: Dict[str, Dict[str, Any]] = {} + self.rules: Dict[str, Dict[str, Any]] = {} + self.connectors: Dict[str, Dict[str, Any]] = {} + self.ih_setup: Dict[str, Dict[str, Any]] = {} + self.ih_config: Dict[str, bool] = {} + self.fa_config: Dict[str, Dict[str, Any]] = {} + self.users: Dict[str, Dict[str, Any]] = {} + self.mappings: Dict[str, List[Dict[str, Any]]] = {} + self.email_prefs: Dict[Any, Dict[str, Any]] = {} + self.invitations: List[str] = [] # user ids emailed an invitation, in order + self.after_call_hooks: Dict[str, Dict[str, Any]] = {} + self.domains: Dict[str, List[Dict[str, Any]]] = {} + self.secrets_sent: List[Dict[str, Any]] = [] # connector configs as sent (keys included), for assertions + self.me_extra: Dict[str, Any] = {} + # conversation data (user reads) + self.visible_locations: List[Dict[str, Any]] = [] + self.call_rows: List[Dict[str, Any]] = [] + self.call_details: Dict[str, Dict[str, Any]] = {} + self.alert_rows: List[Dict[str, Any]] = [] + self.task_rows: List[Dict[str, Any]] = [] + self.insights: Dict[str, Any] = {} + self._clock = 0 + self._tokens: Dict[str, str] = {} # access token -> role + self._logins: Dict[str, str] = {} # email -> role + self._token_n = 0 + self._fail: Optional[Tuple[int, int]] = None # (writes left before the failing one, status) + self._down = False + self._limited: Tuple[int, float] = (0, 0.0) + self._ops = _op_table() + self.routes: List[Tuple[str, re.Pattern, Callable]] = [] + self._register() + + # ------------------------------------------------------------------ public surface + + def client(self, role: Optional[str] = None, **client_options: Any) -> Client: + """A real Client wired to this fake. ``role``: "admin" (an administrator login) or "user" (a + person's own login); default the role given to FakeAPI. Other options go to Client, for example + ``mask_numbers=False``. Waits (retries, connector checks) do not sleep unless you pass ``sleep``.""" + r = ROLES.get(role, role) if role else self.role + email = f"{'admin' if r == 'reseller_admin' else 'user'}.{len(self._logins) + 1}@example.com" + self._logins[email] = r + client_options.setdefault("sleep", lambda s: None) + return Client(email, "fake-password", transport=httpx.MockTransport(self), **client_options) + + @property + def writes(self) -> List[Tuple[str, str]]: + """Every write request so far as (METHOD, path), oldest first.""" + return self.writes_since(0) + + def writes_since(self, start: int = 0) -> List[Tuple[str, str]]: + """The writes after ``start`` (an index into :attr:`requests`, e.g. ``len(api.requests)``).""" + return [(r.method, r.path) for r in self.requests[start:] if r.method != "GET"] + + def count(self, method: str, pattern: str) -> int: + """How many requests matched ``method`` and the path regex ``pattern`` (without /api/v1).""" + rx = re.compile("^" + pattern + "$") + return sum(1 for r in self.requests if r.method == method and rx.match(r.path)) + + def reset_log(self) -> None: + """Forget the request log (state is kept).""" + self.requests.clear() + self.calls.clear() + self.bodies.clear() + + def fail_write(self, nth: int = 1, status: int = 400) -> None: + """Make the ``nth`` write from now (1 = the next one) fail once with ``status``.""" + if nth < 1: + raise ValueError("nth: 1 or more") + self._fail = (nth - 1, status) + + def network_down(self, down: bool = True) -> None: + """Every request fails as if there were no network (the client raises NetworkError).""" + self._down = down + + def rate_limit(self, count: int = 1, retry_after: float = 1) -> None: + """The next ``count`` requests (sign-in included) answer 429 with ``Retry-After``.""" + self._limited = (count, retry_after) + + # ------------------------------------------------------------------ plumbing + + def route(self, method: str, pattern: str): + def deco(fn): + self.routes.append((method, re.compile("^/api/v1" + pattern + "$"), fn)) + return fn + return deco + + def _operation(self, method: str, path: str) -> Optional[str]: + for m, rx, op_id in self._ops: + if m == method and rx.match(path): + return op_id + return None + + def _check_strict(self, op_id: Optional[str], request: httpx.Request, path: str, body: Any) -> Optional[httpx.Response]: + if op_id is None: + return _error(404, "NOT_FOUND", f"{request.method} {path} is not in the published API") + op = _spec.operation(op_id) + unknown = sorted(set(request.url.params.keys()) - set(op["query"])) + if unknown: + return _error(400, "VALIDATION_ERROR", f"Unknown query parameter(s): {', '.join(unknown)}") + if op["body"] is not None: + if body is None: + if op["body"]["required"]: + return _error(422, "VALIDATION_ERROR", "A request body is required") + else: + schema = _spec._resolve(op["body"]["schema"]) + missing = [k for k in (schema.get("required") or []) if not isinstance(body, dict) or k not in body] + if missing: + return _error(422, "VALIDATION_ERROR", f"Missing required field(s): {', '.join(missing)}") + return None + + def _role_of(self, request: httpx.Request) -> str: + token = (request.headers.get("Authorization") or "").replace("Bearer ", "") + return self._tokens.get(token, self.role) + + def _issue(self, role: str) -> Dict[str, Any]: + self._token_n += 1 + access, refresh = f"fake-access-{self._token_n}", f"fake-refresh-{self._token_n}" + self._tokens[access] = role + self._tokens[refresh] = role + return {"access_token": access, "refresh_token": refresh, "token_type": "Bearer", "expires_in": 899, + "user": {"id": new_id(), "role": role}} + + def __call__(self, request: httpx.Request) -> httpx.Response: + if self._down: + raise httpx.ConnectError("the fake network is down", request=request) + count, retry_after = self._limited + if count > 0: + self._limited = (count - 1, retry_after) + return httpx.Response(429, headers={"Retry-After": str(retry_after)}, + json={"error": {"code": "RATE_LIMITED", "message": "Too many requests"}}) + full = request.url.path + path = full[len("/api/v1"):] if full.startswith("/api/v1") else full + try: + body = json.loads(request.content) if request.content else None + except ValueError: + return _error(400, "VALIDATION_ERROR", "The body is not JSON") + op_id = self._operation(request.method, path) + if self.strict: + refused = self._check_strict(op_id, request, path, body) + if refused is not None: + return refused + if path == "/auth/login": + role = self._logins.get((body or {}).get("email"), self.role) + return httpx.Response(200, json=self._issue(role)) + if path == "/auth/refresh": + role = self._tokens.pop((body or {}).get("refresh_token"), None) + if role is None: + return _error(401, "UNAUTHORIZED", "Invalid refresh token") + return httpx.Response(200, json=self._issue(role)) + if path == "/auth/logout": + return httpx.Response(204) + self.requests.append(FakeRequest(request.method, path, dict(request.url.params), body, op_id)) + self.calls.append((request.method, full)) + self.bodies.append((request.method, full, body)) + if request.method != "GET" and self._fail is not None: + left, status = self._fail + if left == 0: + self._fail = None + return _error(status, "FAKE_FAILURE", "Failed on purpose by FakeAPI.fail_write") + self._fail = (left - 1, status) + self._request_role = self._role_of(request) + for method, rx, fn in self.routes: + m = rx.match(full) + if m and method == request.method: + try: + out = fn(request, body, *m.groups()) + except KeyError: + return _error(404, "NOT_FOUND", "Not found") + if isinstance(out, httpx.Response): + return out + status, payload = out + return httpx.Response(status, json=payload) if payload is not None else httpx.Response(status) + return _error(501, "NOT_IMPLEMENTED", f"{op_id or path} is published but this fake does not serve it yet") + + # ------------------------------------------------------------------ seed data (fictional) + + def seed_customer(self, *, teams: int = 1, people: bool = True) -> SeededCustomer: + """Build "Riverbend Auto Group" through the account layer: ``teams`` teams with connectors, the + Management location, groups and the Low Sentiment alert (the phrase alerts stay pending: the + fake holds no phrase lists). With ``people``, two Base Users per team and one Base Manager on + every team. The request log is cleared afterwards.""" + from ..accounts import ConnectorSpec, CustomerSpec, PersonSpec, TeamSpec + outcome, self.connector_outcome = self.connector_outcome, "active" + try: + acc = self.client(role="admin").accounts + + def team_spec(i: int) -> Any: + name = "Riverbend - Main" if i == 0 else f"Riverbend - Team {i + 1}" + return TeamSpec(name=name, street=f"{100 + i} River Rd", city="Springfield", state="IL", + country="US", zipcode="62701", vertical="service-providers") + + def conn(i: int) -> Any: + return ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", f"riverbend{i + 1}.example.com", + "example-key") + cust = acc.create_customer(CustomerSpec( + company_name="Riverbend Auto Group", + admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"), + team=team_spec(0), connector=conn(0), mfa_off=True)) + for i in range(1, teams): + acc.add_team(cust, team_spec(i), conn(i)) + seeded = SeededCustomer(customer=cust) + if people: + for i, t in enumerate(cust.teams): + for j in (1, 2): + email = f"base.user{i + 1}{j}@example.com" + m = acc.add_base_user(cust, PersonSpec(email, "Base", f"User {i + 1}{j}"), team=t, + line=f"2{i + 1:02d}{j}", invite=False) + seeded.base_users[email] = m.user_id + mgr = acc.add_base_manager(cust, PersonSpec("dana.cho@example.com", "Dana", "Cho"), + teams=list(cust.teams), line="2001", invite=False) + seeded.managers["dana.cho@example.com"] = mgr.user_id + self.visible_locations = [{"id": t.location_id, "location_name": t.name} + for t in ([cust.management] if cust.management else []) + cust.teams] + finally: + self.connector_outcome = outcome + self.reset_log() + return seeded + + def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Optional[Any] = None, + alerts: bool = True, tasks: bool = True) -> List[str]: + """Add ``n`` fictional calls (today, or on ``day``) for user logins to read, each with a detail + record, an open task and, for every other call, an "Upset Customer" alert. Callers use 555-01xx + numbers. Returns the call ids, newest first.""" + names = ["Morgan Diaz", "Riley Park", "Avery Lane", "Jamie Fox", "Quinn Hale"] + lid = location_id or (self.visible_locations[-1]["id"] if self.visible_locations else new_id()) + if not self.visible_locations: + self.visible_locations = [{"id": lid, "location_name": "Riverbend - Main"}] + if day is None: + base = datetime.now(timezone.utc) - timedelta(minutes=5) + else: + base = datetime.combine(day, dtime(12, 0)).astimezone().astimezone(timezone.utc) + ids: List[str] = [] + new_calls: List[Dict[str, Any]] = [] + new_tasks: List[Dict[str, Any]] = [] + new_alerts: List[Dict[str, Any]] = [] + for i in range(n): + cid = new_id() + when = (base - timedelta(minutes=i)).strftime("%Y-%m-%dT%H:%M:%SZ") + row = {"id": cid, "call_date": when, "call_type": "inbound", "status": "completed", "duration": 120 + i, + "caller_name": names[i % len(names)], "caller_number": f"+1555555{100 + i % 100:04d}", + "callee_name": "Riverbend front desk", "callee_number": "2101", "location_id": lid, + "summary": "The caller asked about a service appointment.", "sentiment": "neutral", + "sentiment_score": 0, "task_count": 1 if tasks else 0} + new_calls.append(row) + detail = dict(row, analysis={"summary": {"text": row["summary"], "key_points": ["Asked about an appointment"], + "action_items": ["Call back"]}, + "sentiment": {"overall": "neutral"}, "topics": [{"name": "Service"}]}, + tasks=[{"id": new_id(), "title": "Call back", "status": "pending", "due_date": None}] if tasks else []) + self.call_details[cid] = detail + if tasks: + new_tasks.append({"id": new_id(), "title": "Call back", "status": "pending", "due_date": None, + "call_id": cid, "location_id": lid}) + if alerts and i % 2 == 0: + new_alerts.append({"id": new_id(), "call_id": cid, "call_date": when, + "caller_name": row["caller_name"], "caller_number": row["caller_number"], + "callee_name": row["callee_name"], "callee_number": row["callee_number"], + "summary": row["summary"], "sentiment": "negative", "sentiment_score": -30, + "keywords": ["Upset Customer"], "topics": []}) + ids.append(cid) + self.call_rows[:0] = new_calls # newest first, as the API lists them + self.task_rows[:0] = new_tasks + self.alert_rows[:0] = new_alerts + return ids + + # ------------------------------------------------------------------ state readers (for assertions) + + def location_users(self, lid: str) -> List[Dict[str, Any]]: + return [u for u in self.users.values() if lid in u["_locations"]] + + def tick(self) -> str: + self._clock += 1 + return f"2026-11-01T00:00:{self._clock:02d}Z" + + def products(self, uid: str, lid: str) -> set: + """The products a user has at a location.""" + return self.users[uid]["_products"].setdefault(lid, set()) + + def numbers(self, uid: str, connector_id: Optional[str] = None) -> List[str]: + """The numbers mapped to a user (on one connector, or on all).""" + return [n for m in self.mappings.get(uid, []) if connector_id in (None, m["connector_id"]) + for n in m["monitored_numbers"]] + + def fa_numbers(self, lid: str) -> List[str]: + """The lines First Alert watches at a location.""" + return [n for m in self.fa_config.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] + + def ih_numbers(self, lid: str) -> List[str]: + """The lines Insights Hub covers at a location.""" + return [n for m in self.ih_setup.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] + + def group_members(self, lid: str, name: str) -> List[str]: + """The user ids in the named group at a location.""" + return next((g["members"] for g in self.groups.values() if g["location_id"] == lid and g["group_name"] == name), []) + + # ------------------------------------------------------------------ routes + def _register(self) -> None: # noqa: C901 - a fake server is a long switch + api = self + + @self.route("GET", r"/me") + def me(req, body): + role = api._request_role + return 200, {"data": dict({"id": new_id(), "role": role, + "reseller_id": RESELLER if role != "frontline_user" else None, + "user_type": "reseller_user" if role != "frontline_user" else "company_user", + "unexpected_field": "redacted"}, **api.me_extra)} + + @self.route("GET", r"/connector-types") + def connector_types(req, body): + return 200, {"data": CONNECTOR_TYPES} + + @self.route("GET", r"/verticals") + def verticals(req, body): + return 200, {"data": [{"id": VERTICAL, "key": "service-providers", "name": "Service providers"}]} + + # companies + @self.route("GET", r"/resellers/([^/]+)/companies") + def list_companies(req, body, rid): + q = req.url.params.get("search", "") + rows = [c for c in api.companies.values() if c["company_name"].lower().startswith(q.lower())] + return 200, {"data": [{"type": "company", "attributes": c} for c in rows], "has_more": False, + "next_cursor": None, "total_count": len(rows)} + + @self.route("POST", r"/resellers/([^/]+)/companies") + def create_company(req, body, rid): + cid = new_id() + c = dict(body, id=cid, reseller_id=rid, is_active=True, mfa_enforced=True) + api.companies[cid] = c + return 201, {"data": {"type": "company", "attributes": c}, + "invited_user": {"id": new_id(), "email": body["primary_admin_contact_email"]}} + + @self.route("GET", r"/companies/([^/]+)") + def get_company(req, body, cid): + return (200, res("company", api.companies[cid])) if cid in api.companies else (404, {"error": {}}) + + @self.route("PATCH", r"/companies/([^/]+)") + def patch_company(req, body, cid): + api.companies[cid].update(body) + return 200, res("company", api.companies[cid]) + + @self.route("POST", r"/companies/([^/]+)/deactivate") + def deact_company(req, body, cid): + if not api.companies[cid]["is_active"]: + return 409, {"error": {"code": "CONFLICT", "message": "Company is already inactive"}} + api.companies[cid]["is_active"] = False + return 200, res("company", api.companies[cid]) + + @self.route("GET", r"/locations/([^/]+)/after-call/automation") + def get_hook(req, body, lid): + return 200, {"data": api.after_call_hooks.get(lid)} + + @self.route("PUT", r"/locations/([^/]+)/after-call/automation") + def put_hook(req, body, lid): + api.after_call_hooks[lid] = {"webhook_url": body["webhook_url"], "enabled": body.get("enabled", True)} + return 200, {"data": api.after_call_hooks[lid]} + + @self.route("POST", r"/companies/([^/]+)/reactivate") + def react_company(req, body, cid): + api.companies[cid]["is_active"] = True + return 200, res("company", api.companies[cid]) + + @self.route("POST", r"/companies/([^/]+)/domains") + def claim(req, body, cid): + d = {"id": "dom-1", "domain": body["domain"], "status": "pending", + "verification": {"type": "TXT", "name": "_ic-verify." + body["domain"], "value": "abc"}} + api.domains.setdefault(cid, []).append(d) + return 201, {"data": d} + + @self.route("GET", r"/companies/([^/]+)/domains") + def list_domains(req, body, cid): + return 200, {"data": api.domains.get(cid, [])} + + # locations + @self.route("GET", r"/companies/([^/]+)/locations") + def list_locations(req, body, cid): + q = req.url.params.get("search", "") + rows = [x for x in api.locations.values() if x["company_id"] == cid and q.lower() in x["location_name"].lower()] + return 200, page(rows, "location") + + @self.route("POST", r"/companies/([^/]+)/locations") + def create_location(req, body, cid): + lid = new_id() + api.locations[lid] = dict(body, id=lid, company_id=cid, is_active=True, created_at=api.tick()) + return 201, res("location", api.locations[lid]) + + @self.route("GET", r"/companies/([^/]+)/locations/([^/]+)") + def get_location(req, body, cid, lid): + return 200, res("location", api.locations[lid]) + + @self.route("PATCH", r"/companies/([^/]+)/locations/([^/]+)") + def patch_location(req, body, cid, lid): + api.locations[lid].update(body) + return 200, res("location", api.locations[lid]) + + # groups + @self.route("GET", r"/locations/([^/]+)/user-groups") + def list_groups(req, body, lid): + q = req.url.params.get("search", "") + rows = [{k: v for k, v in g.items() if k != "members"} for g in api.groups.values() + if g["location_id"] == lid and q.lower() in g["group_name"].lower()] + return 200, page(rows, "user_group") + + @self.route("POST", r"/locations/([^/]+)/user-groups") + def create_group(req, body, lid): + gid = new_id() + api.groups[gid] = {"id": gid, "location_id": lid, "group_name": body["group_name"], "members": []} + return 201, res("user_group", api.groups[gid]) + + @self.route("GET", r"/locations/([^/]+)/user-groups/([^/]+)") + def get_group(req, body, lid, gid): + g = api.groups[gid] + return 200, res("user_group", dict(g, members=[{"id": m} for m in g["members"]])) + + @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/group-membership") + def get_membership(req, body, lid, uid): + return 200, {"data": [{"id": g["id"], "name": g["group_name"], "is_member": uid in g["members"]} + for g in api.groups.values() if g["location_id"] == lid]} + + @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/group-membership") + def put_membership(req, body, lid, uid): + for g in api.groups.values(): + if g["location_id"] != lid: + continue + if g["id"] in body["group_ids"] and uid not in g["members"]: + g["members"].append(uid) + if g["id"] not in body["group_ids"] and uid in g["members"]: + g["members"].remove(uid) + return get_membership(req, None, lid, uid) + + # rules + @self.route("GET", r"/locations/([^/]+)/first-alert/rules") + def list_rules(req, body, lid): + rows = [{k: v for k, v in r.items() if k != "triggers"} for r in api.rules.values() if r["location_id"] == lid] + return 200, page(rows, "first_alert_rule") + + @self.route("POST", r"/locations/([^/]+)/first-alert/rules") + def create_rule(req, body, lid): + rid = new_id() + r = dict(body, id=rid, location_id=lid, groups=[{"id": g} for g in body.get("group_ids", [])]) + r.pop("group_ids", None) + api.rules[rid] = r + return 201, res("first_alert_rule", r) + + @self.route("GET", r"/locations/([^/]+)/first-alert/rules/([^/]+)") + def get_rule(req, body, lid, rid): + return 200, res("first_alert_rule", api.rules[rid]) + + @self.route("PATCH", r"/locations/([^/]+)/first-alert/rules/([^/]+)") + def patch_rule(req, body, lid, rid): + body = dict(body) + if "group_ids" in body: + api.rules[rid]["groups"] = [{"id": g} for g in body.pop("group_ids")] + api.rules[rid].update(body) + return 200, res("first_alert_rule", api.rules[rid]) + + # connectors + @self.route("GET", r"/locations/([^/]+)/connectors") + def list_conns(req, body, lid): + rows = [{k: v for k, v in c.items() if k != "config"} for c in api.connectors.values() if c["location_id"] == lid] + return 200, page(rows) + + @self.route("POST", r"/locations/([^/]+)/connectors") + def create_conn(req, body, lid): + if body["type"] not in [t["key"] for t in CONNECTOR_TYPES]: + return 422, {"error": {"code": "VALIDATION_ERROR", "message": "unknown connector type"}} + cid = new_id() + api.secrets_sent.append(dict(body["config"])) + public = {k: v for k, v in body["config"].items() if not any(w in k.lower() for w in SECRET_WORDS)} + api.connectors[cid] = {"id": cid, "location_id": lid, "name": body["name"], "type": body["type"], + "status": "connecting", "_polls": 0, + "config": dict(public, unexpected_field="redacted")} + return 202, {"data": api.connectors[cid]} + + @self.route("GET", r"/locations/([^/]+)/connectors/([^/]+)") + def get_conn(req, body, lid, cid): + c = api.connectors[cid] + c["_polls"] += 1 + if c["status"] == "connecting" and c["_polls"] >= 2 and api.connector_outcome not in ("stuck", "connecting"): + c["status"] = api.connector_outcome + if c["status"] == "error": + c["state_reason"] = "invalid_permissions" + c["status_message"] = "The key was refused." + if c["status"] == "deactivating": + c["status"] = "inactive" + return 200, {"data": c} + + @self.route("PATCH", r"/locations/([^/]+)/connectors/([^/]+)") + def patch_conn(req, body, lid, cid): + c = api.connectors[cid] + if "name" in body: + c["name"] = body["name"] + if "config" in body: + api.secrets_sent.append(dict(body["config"])) + c["config"].update({k: v for k, v in body["config"].items() + if not any(w in k.lower() for w in SECRET_WORDS)}) + c["_key"] = body["config"].get("api_key") + return 200, {"data": c} + + @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/deactivate") + def deact_conn(req, body, lid, cid): + api.connectors[cid]["status"] = "deactivating" + return 202, {"data": api.connectors[cid]} + + @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/reactivate") + def react_conn(req, body, lid, cid): + api.connectors[cid].update(status="connecting", _polls=0) + return 202, {"data": api.connectors[cid]} + + # Insights Hub + @self.route("GET", r"/locations/([^/]+)/insights-hub/setup") + def get_ih(req, body, lid): + s = api.ih_setup.get(lid, {"connector_mappings": [], "group_access": []}) + return 200, {"data": {"type": "insights_hub_setup", "attributes": s}} + + @self.route("POST", r"/locations/([^/]+)/insights-hub/setup") + def post_ih(req, body, lid): + api.ih_setup[lid] = {"connector_mappings": body["connector_mappings"], "group_access": body["group_access"]} + return 201, {"data": {"type": "insights_hub_setup", "attributes": api.ih_setup[lid]}} + + @self.route("PATCH", r"/locations/([^/]+)/insights-hub/setup") + def patch_ih(req, body, lid): + s = api.ih_setup.setdefault(lid, {"connector_mappings": [], "group_access": []}) + s.update(body) + return 200, {"data": {"type": "insights_hub_setup", "attributes": s}} + + @self.route("GET", r"/locations/([^/]+)/insights-hub/config") + def get_ihc(req, body, lid): + return 200, {"data": {"type": "insights_hub_config", + "attributes": {"monitor_all_numbers": api.ih_config.get(lid, False)}}} + + @self.route("PATCH", r"/locations/([^/]+)/insights-hub/config") + def patch_ihc(req, body, lid): + api.ih_config[lid] = body["monitor_all_numbers"] + return get_ihc(req, None, lid) + + # First Alert config + @self.route("GET", r"/locations/([^/]+)/first-alert/config") + def get_fa(req, body, lid): + return 200, {"data": api.fa_config.get(lid, {"webhook_url": None, "connector_mappings": []})} + + @self.route("PUT", r"/locations/([^/]+)/first-alert/config") + def put_fa(req, body, lid): + api.fa_config[lid] = {"webhook_url": body.get("webhook_url"), + "connector_mappings": [dict(m, id=new_id()) for m in body["connector_mappings"]]} + return get_fa(req, None, lid) + + # users + @self.route("GET", r"/companies/([^/]+)/users") + def list_users(req, body, cid): + q = (req.url.params.get("search") or "").lower() + lid = req.url.params.get("location_id") + rows = [api._user_attrs(u) for u in api.users.values() if u["company_id"] == cid and q in u["email"].lower() + and (not lid or lid in u["_locations"])] + return 200, page(rows, "company_user") + + @self.route("POST", r"/companies/([^/]+)/users") + def create_user(req, body, cid): + assert req.headers.get("Idempotency-Key") + if any(u["email"].lower() == body["email"].lower() for u in api.users.values()): + return 409, {"error": {"code": "CONFLICT", "message": "A user with this email already exists"}} + uid = new_id() + api.users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], + "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": {}, + "invited_at": None} + if body.get("send_invitation"): + api.invitations.append(uid) + api.users[uid]["invited_at"] = api.tick() + return 201, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}, + "meta": {"invitation_link": "https://app.example.com/accept?token=SECRET"}} + + @self.route("GET", r"/companies/([^/]+)/users/([^/]+)") + def get_user(req, body, cid, uid): + return 200, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}} + + @self.route("PATCH", r"/companies/([^/]+)/users/([^/]+)") + def patch_user(req, body, cid, uid): + if "location_ids" in body: + api.users[uid]["_locations"] = list(body["location_ids"]) + if "department" in body: + api.users[uid]["department"] = body["department"] + return get_user(req, None, cid, uid) + + @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/deactivate") + def deact_user(req, body, cid, uid): + if api.users[uid]["status"] == "deactivated": + return 409, {"error": {"code": "CONFLICT", "message": "User is already deactivated"}} + api.users[uid]["status"] = "deactivated" + return get_user(req, None, cid, uid) + + @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/resend-invitation") + def resend(req, body, cid, uid): + if api.users[uid]["status"] != "invited": + return 409, {"error": {"code": "CONFLICT", "message": "User does not have a pending invitation"}} + api.invitations.append(uid) + api.users[uid]["invited_at"] = api.tick() + return 202, {"data": {"type": "invitation_resend", "attributes": {"user_id": uid, + "email": api.users[uid]["email"]}}} + + @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/reactivate") + def react_user(req, body, cid, uid): + api.users[uid]["status"] = "active" + return get_user(req, None, cid, uid) + + @self.route("GET", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") + def get_maps(req, body, cid, uid): + return 200, {"data": api.mappings.get(uid, [])} + + @self.route("PUT", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") + def put_maps(req, body, cid, uid): + for m in body["mappings"]: + if api.connectors.get(m["connector_id"], {}).get("status") not in ("active", "connected"): + return 422, {"error": {"code": "VALIDATION_ERROR", "message": "connector not found or inactive"}} + for m in body["mappings"]: # one extension, one location + lid = api.connectors[m["connector_id"]]["location_id"] + for other, maps in api.mappings.items(): + if other == uid: + continue + for om in maps: + olid = api.connectors.get(om["connector_id"], {}).get("location_id") + clash = set(om["monitored_numbers"]) & set(m["monitored_numbers"]) + if olid != lid and clash: + return 409, {"error": {"code": "CONFLICT", + "message": f"Extension {sorted(clash)[0]} is monitored at another location"}} + api.mappings[uid] = body["mappings"] + return 200, {"data": body["mappings"]} + + @self.route("GET", r"/locations/([^/]+)/users") + def list_loc_users(req, body, lid): + return 200, page([api._loc_user(u, lid) for u in api.location_users(lid)], "location_user") + + @self.route("GET", r"/locations/([^/]+)/users/([^/]+)") + def get_loc_user(req, body, lid, uid): + return 200, {"data": {"type": "location_user", "attributes": api._loc_user(api.users[uid], lid)}} + + @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/enable") + def enable(req, body, lid, uid, key): + api.products(uid, lid).add(key) + return 200, {"data": {"product_key": key, "enabled": True}} + + @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/disable") + def disable(req, body, lid, uid, key): + api.products(uid, lid).discard(key) + return 200, {"data": {"product_key": key, "enabled": False}} + + @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/first-alert/email-preferences") + def email_prefs(req, body, lid, uid): + api.email_prefs[(lid, uid)] = body + return 200, {"emailNotifications": {"masterEnabled": body["masterEnabled"], "alerts": []}} + + @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/first-alert/notification-preferences") + def get_prefs(req, body, lid, uid): + master = api.email_prefs.get((lid, uid), {"masterEnabled": True})["masterEnabled"] + alerts = [{"alertId": r["id"], "alertName": r["name"], "emailEnabled": master} + for r in api.rules.values() if r["location_id"] == lid] + return 200, {"emailNotifications": {"masterEnabled": master, "alerts": alerts}, + "digest": {"enabled": False}, "webhook": {"url": None}} + + # conversation data (frontline) + @self.route("GET", r"/locations") + def visible_locations(req, body): + return 200, page(api.visible_locations, "location") + + @self.route("GET", r"/calls") + def list_calls(req, body): + if api._request_role != "frontline_user": # administrator logins get empty lists, as on the API + return api._paged(req, [], "calls", {"total_calls": 0, "missed_calls": 0}) + lid = req.url.params.get("location_id") + q = req.url.params.get("search") + rows = [r for r in api.call_rows if (not lid or r.get("location_id") in lid.split(",")) + and (not q or q in (r.get("caller_number") or "") + (r.get("summary") or ""))] + return api._paged(req, rows, "calls", {"total_calls": len(rows), "missed_calls": 0}) + + @self.route("GET", r"/calls/([^/]+)") + def get_call(req, body, cid): + if cid not in api.call_details: + return 404, {"error": {"code": "NOT_FOUND", "message": "not found"}} + return 200, {"data": api.call_details[cid]} + + @self.route("GET", r"/calls/([^/]+)/transcript") + def get_transcript(req, body, cid): + return 200, {"data": {"transcript": [{"time": 0.0, "speaker": "Speaker 1", "name": "Sam", "text": "Hello"}]}} + + @self.route("GET", r"/alerts") + def list_alerts(req, body): + if api._request_role != "frontline_user": + return api._paged(req, [], "alerts", {"total": 0}) + # as published: caller or callee name or number, summary text, or an exact lowercase alert id + q = (req.url.params.get("search") or "").lower() + fields = ("caller_name", "caller_number", "callee_name", "callee_number", "summary") + rows = [a for a in api.alert_rows if not q or a["id"] == q + or any(q in str(a.get(f) or "").lower() for f in fields)] + return api._paged(req, rows, "alerts", {"total": len(rows)}) + + @self.route("GET", r"/tasks") + def list_tasks(req, body): + if api._request_role != "frontline_user": + return 200, {"data": [], "meta": {"has_more": False, "next_cursor": None}} + st = req.url.params.get("status") + rows = [t for t in api.task_rows if st != "open" or t["status"] in ("pending", "in_progress", "overdue")] + return 200, {"data": rows, "meta": {"has_more": False, "next_cursor": None}} + + @self.route("GET", r"/insights/dashboard") + def insights(req, body): + return 200, {"data": api.insights} + + def _paged(self, req: httpx.Request, rows: List[Dict[str, Any]], key: str, summary: Dict[str, Any]): + limit = int(req.url.params.get("limit") or 50) + start = int(req.url.params.get("cursor") or 0) + chunk = rows[start:start + limit] + more = start + limit < len(rows) + return 200, {"data": {key: chunk, "summary": summary}, + "meta": {"has_more": more, "next_cursor": str(start + limit) if more else None, "limit": limit}} + + def _user_attrs(self, u: Dict[str, Any]) -> Dict[str, Any]: + return {"id": u["id"], "company_id": u["company_id"], "email": u["email"], "role": u["role"], + "status": u["status"], "locations": [{"location_id": x} for x in u["_locations"]], + "invited_at": u.get("invited_at"), + **({"department": u["department"]} if u.get("department") else {})} + + def _loc_user(self, u: Dict[str, Any], lid: str) -> Dict[str, Any]: + return {"id": u["id"], "email": u["email"], "role": u["role"], "status": u["status"], "location_id": lid, + "enabled_products": sorted(u["_products"].get(lid, set())), + "groups": [g["group_name"] for g in self.groups.values() + if g["location_id"] == lid and u["id"] in g["members"]]} diff --git a/tests/unit/fake_api.py b/tests/unit/fake_api.py index fe9ceba..9b94eda 100644 --- a/tests/unit/fake_api.py +++ b/tests/unit/fake_api.py @@ -1,549 +1,2 @@ -"""An in-memory stand-in for the API, used through httpx.MockTransport. No network.""" -from __future__ import annotations - -import json -import re -import uuid -from typing import Any, Callable, Dict, List, Optional, Tuple - -import httpx - -import intelligence_cloud as ic - -RESELLER = "00000000-0000-4000-8000-0000000000aa" -VERTICAL = "00000000-0000-4000-8000-0000000000bb" -CONNECTOR_TYPES = [{"key": "netsapiens", "name": "NetSapiens"}, {"key": "examplepbx", "name": "Example PBX"}] -SECRET_WORDS = ("key", "secret", "token", "password") - - -def new_id() -> str: - return str(uuid.uuid4()) - - -def res(type_: str, attrs: Dict[str, Any]) -> Dict[str, Any]: - return {"data": {"type": type_, "attributes": attrs}} - - -def page(rows: List[Dict[str, Any]], type_: Optional[str] = None) -> Dict[str, Any]: - data = [{"type": type_, "attributes": r} for r in rows] if type_ else rows - return {"data": data, "pagination": {"has_more": False, "next_cursor": None, "total_count": len(rows)}} - - -class FakeAPI: - """Stateful fake. ``calls`` logs (METHOD, path) for every request after sign-in. - - Products, groups and alert email preferences are per location. A user's number mappings are - company-wide, one entry per connector; mapping a number that a user at another location already - holds returns 409, as the API does. New users start with alert email on, as on the platform.""" - - def __init__(self, connector_outcome: str = "active", role: str = "reseller_admin"): - self.calls: List[Tuple[str, str]] = [] - self.bodies: List[Tuple[str, str, Any]] = [] - self.connector_outcome = connector_outcome - self.role = role - self.companies: Dict[str, Dict[str, Any]] = {} - self.locations: Dict[str, Dict[str, Any]] = {} - self.groups: Dict[str, Dict[str, Any]] = {} - self.rules: Dict[str, Dict[str, Any]] = {} - self.connectors: Dict[str, Dict[str, Any]] = {} - self.ih_setup: Dict[str, Dict[str, Any]] = {} - self.ih_config: Dict[str, bool] = {} - self.fa_config: Dict[str, Dict[str, Any]] = {} - self.users: Dict[str, Dict[str, Any]] = {} - self.mappings: Dict[str, List[Dict[str, Any]]] = {} - self.email_prefs: Dict[str, Dict[str, Any]] = {} - self.invitations: List[str] = [] # user ids emailed an invitation, in order - self.after_call_hooks: Dict[str, Dict[str, Any]] = {} - self.domains: Dict[str, List[Dict[str, Any]]] = {} - self.secrets_sent: List[Dict[str, Any]] = [] # connector configs as sent (keys included), for assertions - self.me_extra: Dict[str, Any] = {} - # conversation data (frontline reads) - self.visible_locations: List[Dict[str, Any]] = [] - self.call_rows: List[Dict[str, Any]] = [] - self.call_details: Dict[str, Dict[str, Any]] = {} - self.alert_rows: List[Dict[str, Any]] = [] - self.task_rows: List[Dict[str, Any]] = [] - self.insights: Dict[str, Any] = {} - self._clock = 0 - self.routes: List[Tuple[str, re.Pattern, Callable]] = [] - self._register() - - # ------------------------------------------------------------------ plumbing - def client(self, **kw) -> ic.Client: - kw.setdefault("sleep", lambda s: None) - return ic.Client(email="integration@example.com", password="pw", transport=httpx.MockTransport(self), **kw) - - def route(self, method: str, pattern: str): - def deco(fn): - self.routes.append((method, re.compile("^/api/v1" + pattern + "$"), fn)) - return fn - return deco - - def __call__(self, request: httpx.Request) -> httpx.Response: - path = request.url.path - body = json.loads(request.content) if request.content else None - if path == "/api/v1/auth/login": - return httpx.Response(200, json={"access_token": "A", "refresh_token": "R", "token_type": "Bearer", - "expires_in": 899, "user": {"id": new_id(), "role": self.role}}) - self.calls.append((request.method, path)) - self.bodies.append((request.method, path, body)) - for method, rx, fn in self.routes: - m = rx.match(path) - if m and method == request.method: - out = fn(request, body, *m.groups()) - if isinstance(out, httpx.Response): - return out - status, payload = out - return httpx.Response(status, json=payload) if payload is not None else httpx.Response(status) - return httpx.Response(404, json={"error": {"code": "NOT_FOUND", "message": f"no route {path}"}}) - - def count(self, method: str, pattern: str) -> int: - rx = re.compile("^/api/v1" + pattern + "$") - return sum(1 for m, p in self.calls if m == method and rx.match(p)) - - def location_users(self, lid: str) -> List[Dict[str, Any]]: - return [u for u in self.users.values() if lid in u["_locations"]] - - def tick(self) -> str: - self._clock += 1 - return f"2026-11-01T00:00:{self._clock:02d}Z" - - def writes(self, start: int = 0) -> List[Tuple[str, str]]: - return [(m, p.split("/api/v1")[-1]) for m, p in self.calls[start:] if m != "GET"] - - def products(self, uid: str, lid: str) -> set: - return self.users[uid]["_products"].setdefault(lid, set()) - - def numbers(self, uid: str, connector_id: Optional[str] = None) -> List[str]: - return [n for m in self.mappings.get(uid, []) if connector_id in (None, m["connector_id"]) - for n in m["monitored_numbers"]] - - def fa_numbers(self, lid: str) -> List[str]: - return [n for m in self.fa_config.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] - - def ih_numbers(self, lid: str) -> List[str]: - return [n for m in self.ih_setup.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] - - def group_members(self, lid: str, name: str) -> List[str]: - return next((g["members"] for g in self.groups.values() if g["location_id"] == lid and g["group_name"] == name), []) - - # ------------------------------------------------------------------ routes - def _register(self) -> None: # noqa: C901 - a fake server is a long switch - api = self - - @self.route("GET", r"/me") - def me(req, body): - return 200, {"data": dict({"id": new_id(), "role": api.role, "reseller_id": RESELLER, - "user_type": "reseller_user", "unexpected_field": "redacted"}, **api.me_extra)} - - @self.route("GET", r"/connector-types") - def connector_types(req, body): - return 200, {"data": CONNECTOR_TYPES} - - @self.route("GET", r"/verticals") - def verticals(req, body): - return 200, {"data": [{"id": VERTICAL, "key": "service-providers", "name": "Service providers"}]} - - # companies - @self.route("GET", r"/resellers/([^/]+)/companies") - def list_companies(req, body, rid): - q = req.url.params.get("search", "") - rows = [c for c in api.companies.values() if c["company_name"].lower().startswith(q.lower())] - return 200, {"data": [{"type": "company", "attributes": c} for c in rows], "has_more": False, - "next_cursor": None, "total_count": len(rows)} - - @self.route("POST", r"/resellers/([^/]+)/companies") - def create_company(req, body, rid): - cid = new_id() - c = dict(body, id=cid, reseller_id=rid, is_active=True, mfa_enforced=True) - api.companies[cid] = c - return 201, {"data": {"type": "company", "attributes": c}, - "invited_user": {"id": new_id(), "email": body["primary_admin_contact_email"]}} - - @self.route("GET", r"/companies/([^/]+)") - def get_company(req, body, cid): - return (200, res("company", api.companies[cid])) if cid in api.companies else (404, {"error": {}}) - - @self.route("PATCH", r"/companies/([^/]+)") - def patch_company(req, body, cid): - api.companies[cid].update(body) - return 200, res("company", api.companies[cid]) - - @self.route("POST", r"/companies/([^/]+)/deactivate") - def deact_company(req, body, cid): - if not api.companies[cid]["is_active"]: - return 409, {"error": {"code": "CONFLICT", "message": "Company is already inactive"}} - api.companies[cid]["is_active"] = False - return 200, res("company", api.companies[cid]) - - @self.route("GET", r"/locations/([^/]+)/after-call/automation") - def get_hook(req, body, lid): - return 200, {"data": api.after_call_hooks.get(lid)} - - @self.route("PUT", r"/locations/([^/]+)/after-call/automation") - def put_hook(req, body, lid): - api.after_call_hooks[lid] = {"webhook_url": body["webhook_url"], "enabled": body.get("enabled", True)} - return 200, {"data": api.after_call_hooks[lid]} - - @self.route("POST", r"/companies/([^/]+)/reactivate") - def react_company(req, body, cid): - api.companies[cid]["is_active"] = True - return 200, res("company", api.companies[cid]) - - @self.route("POST", r"/companies/([^/]+)/domains") - def claim(req, body, cid): - d = {"id": "dom-1", "domain": body["domain"], "status": "pending", - "verification": {"type": "TXT", "name": "_ic-verify." + body["domain"], "value": "abc"}} - api.domains.setdefault(cid, []).append(d) - return 201, {"data": d} - - @self.route("GET", r"/companies/([^/]+)/domains") - def list_domains(req, body, cid): - return 200, {"data": api.domains.get(cid, [])} - - # locations - @self.route("GET", r"/companies/([^/]+)/locations") - def list_locations(req, body, cid): - q = req.url.params.get("search", "") - rows = [x for x in api.locations.values() if x["company_id"] == cid and q.lower() in x["location_name"].lower()] - return 200, page(rows, "location") - - @self.route("POST", r"/companies/([^/]+)/locations") - def create_location(req, body, cid): - lid = new_id() - api.locations[lid] = dict(body, id=lid, company_id=cid, is_active=True, created_at=api.tick()) - return 201, res("location", api.locations[lid]) - - @self.route("GET", r"/companies/([^/]+)/locations/([^/]+)") - def get_location(req, body, cid, lid): - return 200, res("location", api.locations[lid]) - - @self.route("PATCH", r"/companies/([^/]+)/locations/([^/]+)") - def patch_location(req, body, cid, lid): - api.locations[lid].update(body) - return 200, res("location", api.locations[lid]) - - # groups - @self.route("GET", r"/locations/([^/]+)/user-groups") - def list_groups(req, body, lid): - q = req.url.params.get("search", "") - rows = [{k: v for k, v in g.items() if k != "members"} for g in api.groups.values() - if g["location_id"] == lid and q.lower() in g["group_name"].lower()] - return 200, page(rows, "user_group") - - @self.route("POST", r"/locations/([^/]+)/user-groups") - def create_group(req, body, lid): - gid = new_id() - api.groups[gid] = {"id": gid, "location_id": lid, "group_name": body["group_name"], "members": []} - return 201, res("user_group", api.groups[gid]) - - @self.route("GET", r"/locations/([^/]+)/user-groups/([^/]+)") - def get_group(req, body, lid, gid): - g = api.groups[gid] - return 200, res("user_group", dict(g, members=[{"id": m} for m in g["members"]])) - - @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/group-membership") - def get_membership(req, body, lid, uid): - return 200, {"data": [{"id": g["id"], "name": g["group_name"], "is_member": uid in g["members"]} - for g in api.groups.values() if g["location_id"] == lid]} - - @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/group-membership") - def put_membership(req, body, lid, uid): - for g in api.groups.values(): - if g["location_id"] != lid: - continue - if g["id"] in body["group_ids"] and uid not in g["members"]: - g["members"].append(uid) - if g["id"] not in body["group_ids"] and uid in g["members"]: - g["members"].remove(uid) - return get_membership(req, None, lid, uid) - - # rules - @self.route("GET", r"/locations/([^/]+)/first-alert/rules") - def list_rules(req, body, lid): - rows = [{k: v for k, v in r.items() if k != "triggers"} for r in api.rules.values() if r["location_id"] == lid] - return 200, page(rows, "first_alert_rule") - - @self.route("POST", r"/locations/([^/]+)/first-alert/rules") - def create_rule(req, body, lid): - rid = new_id() - r = dict(body, id=rid, location_id=lid, groups=[{"id": g} for g in body.get("group_ids", [])]) - r.pop("group_ids", None) - api.rules[rid] = r - return 201, res("first_alert_rule", r) - - @self.route("GET", r"/locations/([^/]+)/first-alert/rules/([^/]+)") - def get_rule(req, body, lid, rid): - return 200, res("first_alert_rule", api.rules[rid]) - - @self.route("PATCH", r"/locations/([^/]+)/first-alert/rules/([^/]+)") - def patch_rule(req, body, lid, rid): - body = dict(body) - if "group_ids" in body: - api.rules[rid]["groups"] = [{"id": g} for g in body.pop("group_ids")] - api.rules[rid].update(body) - return 200, res("first_alert_rule", api.rules[rid]) - - # connectors - @self.route("GET", r"/locations/([^/]+)/connectors") - def list_conns(req, body, lid): - rows = [{k: v for k, v in c.items() if k != "config"} for c in api.connectors.values() if c["location_id"] == lid] - return 200, page(rows) - - @self.route("POST", r"/locations/([^/]+)/connectors") - def create_conn(req, body, lid): - if body["type"] not in [t["key"] for t in CONNECTOR_TYPES]: - return 422, {"error": {"code": "VALIDATION_ERROR", "message": "unknown connector type"}} - cid = new_id() - api.secrets_sent.append(dict(body["config"])) - public = {k: v for k, v in body["config"].items() if not any(w in k.lower() for w in SECRET_WORDS)} - api.connectors[cid] = {"id": cid, "location_id": lid, "name": body["name"], "type": body["type"], - "status": "connecting", "_polls": 0, - "config": dict(public, unexpected_field="redacted")} - return 202, {"data": api.connectors[cid]} - - @self.route("GET", r"/locations/([^/]+)/connectors/([^/]+)") - def get_conn(req, body, lid, cid): - c = api.connectors[cid] - c["_polls"] += 1 - if c["status"] == "connecting" and c["_polls"] >= 2: - c["status"] = api.connector_outcome - if c["status"] == "error": - c["state_reason"] = "invalid_permissions" - c["status_message"] = "The key was refused." - if c["status"] == "deactivating": - c["status"] = "inactive" - return 200, {"data": c} - - @self.route("PATCH", r"/locations/([^/]+)/connectors/([^/]+)") - def patch_conn(req, body, lid, cid): - c = api.connectors[cid] - if "name" in body: - c["name"] = body["name"] - if "config" in body: - api.secrets_sent.append(dict(body["config"])) - c["config"].update({k: v for k, v in body["config"].items() - if not any(w in k.lower() for w in SECRET_WORDS)}) - c["_key"] = body["config"].get("api_key") - return 200, {"data": c} - - @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/deactivate") - def deact_conn(req, body, lid, cid): - api.connectors[cid]["status"] = "deactivating" - return 202, {"data": api.connectors[cid]} - - @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/reactivate") - def react_conn(req, body, lid, cid): - api.connectors[cid].update(status="connecting", _polls=0) - return 202, {"data": api.connectors[cid]} - - # Insights Hub - @self.route("GET", r"/locations/([^/]+)/insights-hub/setup") - def get_ih(req, body, lid): - s = api.ih_setup.get(lid, {"connector_mappings": [], "group_access": []}) - return 200, {"data": {"type": "insights_hub_setup", "attributes": s}} - - @self.route("POST", r"/locations/([^/]+)/insights-hub/setup") - def post_ih(req, body, lid): - api.ih_setup[lid] = {"connector_mappings": body["connector_mappings"], "group_access": body["group_access"]} - return 201, {"data": {"type": "insights_hub_setup", "attributes": api.ih_setup[lid]}} - - @self.route("PATCH", r"/locations/([^/]+)/insights-hub/setup") - def patch_ih(req, body, lid): - s = api.ih_setup.setdefault(lid, {"connector_mappings": [], "group_access": []}) - s.update(body) - return 200, {"data": {"type": "insights_hub_setup", "attributes": s}} - - @self.route("GET", r"/locations/([^/]+)/insights-hub/config") - def get_ihc(req, body, lid): - return 200, {"data": {"type": "insights_hub_config", - "attributes": {"monitor_all_numbers": api.ih_config.get(lid, False)}}} - - @self.route("PATCH", r"/locations/([^/]+)/insights-hub/config") - def patch_ihc(req, body, lid): - api.ih_config[lid] = body["monitor_all_numbers"] - return get_ihc(req, None, lid) - - # First Alert config - @self.route("GET", r"/locations/([^/]+)/first-alert/config") - def get_fa(req, body, lid): - return 200, {"data": api.fa_config.get(lid, {"webhook_url": None, "connector_mappings": []})} - - @self.route("PUT", r"/locations/([^/]+)/first-alert/config") - def put_fa(req, body, lid): - api.fa_config[lid] = {"webhook_url": body.get("webhook_url"), - "connector_mappings": [dict(m, id=new_id()) for m in body["connector_mappings"]]} - return get_fa(req, None, lid) - - # users - @self.route("GET", r"/companies/([^/]+)/users") - def list_users(req, body, cid): - q = (req.url.params.get("search") or "").lower() - lid = req.url.params.get("location_id") - rows = [api._user_attrs(u) for u in api.users.values() if u["company_id"] == cid and q in u["email"].lower() - and (not lid or lid in u["_locations"])] - return 200, page(rows, "company_user") - - @self.route("POST", r"/companies/([^/]+)/users") - def create_user(req, body, cid): - assert req.headers.get("Idempotency-Key") - if any(u["email"].lower() == body["email"].lower() for u in api.users.values()): - return 409, {"error": {"code": "CONFLICT", "message": "A user with this email already exists"}} - uid = new_id() - api.users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], - "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": {}, - "invited_at": None} - if body.get("send_invitation"): - api.invitations.append(uid) - api.users[uid]["invited_at"] = api.tick() - return 201, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}, - "meta": {"invitation_link": "https://app.example.com/accept?token=SECRET"}} - - @self.route("GET", r"/companies/([^/]+)/users/([^/]+)") - def get_user(req, body, cid, uid): - return 200, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}} - - @self.route("PATCH", r"/companies/([^/]+)/users/([^/]+)") - def patch_user(req, body, cid, uid): - if "location_ids" in body: - api.users[uid]["_locations"] = list(body["location_ids"]) - if "department" in body: - api.users[uid]["department"] = body["department"] - return get_user(req, None, cid, uid) - - @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/deactivate") - def deact_user(req, body, cid, uid): - if api.users[uid]["status"] == "deactivated": - return 409, {"error": {"code": "CONFLICT", "message": "User is already deactivated"}} - api.users[uid]["status"] = "deactivated" - return get_user(req, None, cid, uid) - - @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/resend-invitation") - def resend(req, body, cid, uid): - if api.users[uid]["status"] != "invited": - return 409, {"error": {"code": "CONFLICT", "message": "User does not have a pending invitation"}} - api.invitations.append(uid) - api.users[uid]["invited_at"] = api.tick() - return 202, {"data": {"type": "invitation_resend", "attributes": {"user_id": uid, - "email": api.users[uid]["email"]}}} - - @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/reactivate") - def react_user(req, body, cid, uid): - api.users[uid]["status"] = "active" - return get_user(req, None, cid, uid) - - @self.route("GET", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") - def get_maps(req, body, cid, uid): - return 200, {"data": api.mappings.get(uid, [])} - - @self.route("PUT", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") - def put_maps(req, body, cid, uid): - for m in body["mappings"]: - if api.connectors.get(m["connector_id"], {}).get("status") not in ("active", "connected"): - return 422, {"error": {"code": "VALIDATION_ERROR", "message": "connector not found or inactive"}} - for m in body["mappings"]: # one extension, one location - lid = api.connectors[m["connector_id"]]["location_id"] - for other, maps in api.mappings.items(): - if other == uid: - continue - for om in maps: - olid = api.connectors.get(om["connector_id"], {}).get("location_id") - clash = set(om["monitored_numbers"]) & set(m["monitored_numbers"]) - if olid != lid and clash: - return 409, {"error": {"code": "CONFLICT", - "message": f"Extension {sorted(clash)[0]} is monitored at Other Co"}} - api.mappings[uid] = body["mappings"] - return 200, {"data": body["mappings"]} - - @self.route("GET", r"/locations/([^/]+)/users") - def list_loc_users(req, body, lid): - return 200, page([api._loc_user(u, lid) for u in api.location_users(lid)], "location_user") - - @self.route("GET", r"/locations/([^/]+)/users/([^/]+)") - def get_loc_user(req, body, lid, uid): - return 200, {"data": {"type": "location_user", "attributes": api._loc_user(api.users[uid], lid)}} - - @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/enable") - def enable(req, body, lid, uid, key): - api.products(uid, lid).add(key) - return 200, {"data": {"product_key": key, "enabled": True}} - - @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/disable") - def disable(req, body, lid, uid, key): - api.products(uid, lid).discard(key) - return 200, {"data": {"product_key": key, "enabled": False}} - - @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/first-alert/email-preferences") - def email_prefs(req, body, lid, uid): - api.email_prefs[(lid, uid)] = body - return 200, {"emailNotifications": {"masterEnabled": body["masterEnabled"], "alerts": []}} - - @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/first-alert/notification-preferences") - def get_prefs(req, body, lid, uid): - master = api.email_prefs.get((lid, uid), {"masterEnabled": True})["masterEnabled"] - alerts = [{"alertId": r["id"], "alertName": r["name"], "emailEnabled": master} - for r in api.rules.values() if r["location_id"] == lid] - return 200, {"emailNotifications": {"masterEnabled": master, "alerts": alerts}, - "digest": {"enabled": False}, "webhook": {"url": None}} - - # conversation data (frontline) - @self.route("GET", r"/locations") - def visible_locations(req, body): - return 200, page(api.visible_locations, "location") - - @self.route("GET", r"/calls") - def list_calls(req, body): - lid = req.url.params.get("location_id") - q = req.url.params.get("search") - rows = [r for r in api.call_rows if (not lid or r.get("location_id") in lid.split(",")) - and (not q or q in (r.get("caller_number") or "") + (r.get("summary") or ""))] - return api._paged(req, rows, "calls", {"total_calls": len(rows), "missed_calls": 0}) - - @self.route("GET", r"/calls/([^/]+)") - def get_call(req, body, cid): - if cid not in api.call_details: - return 404, {"error": {"code": "NOT_FOUND", "message": "not found"}} - return 200, {"data": api.call_details[cid]} - - @self.route("GET", r"/calls/([^/]+)/transcript") - def get_transcript(req, body, cid): - return 200, {"data": {"transcript": [{"time": 0.0, "speaker": "Speaker 1", "name": "Sam", "text": "Hello"}]}} - - @self.route("GET", r"/alerts") - def list_alerts(req, body): - # as published: caller or callee name or number, summary text, or an exact lowercase alert id - q = (req.url.params.get("search") or "").lower() - fields = ("caller_name", "caller_number", "callee_name", "callee_number", "summary") - rows = [a for a in api.alert_rows if not q or a["id"] == q - or any(q in str(a.get(f) or "").lower() for f in fields)] - return api._paged(req, rows, "alerts", {"total": len(rows)}) - - @self.route("GET", r"/tasks") - def list_tasks(req, body): - st = req.url.params.get("status") - rows = [t for t in api.task_rows if st != "open" or t["status"] in ("pending", "in_progress", "overdue")] - return 200, {"data": rows, "meta": {"has_more": False, "next_cursor": None}} - - @self.route("GET", r"/insights/dashboard") - def insights(req, body): - return 200, {"data": api.insights} - - def _paged(self, req: httpx.Request, rows: List[Dict[str, Any]], key: str, summary: Dict[str, Any]): - limit = int(req.url.params.get("limit") or 50) - start = int(req.url.params.get("cursor") or 0) - chunk = rows[start:start + limit] - more = start + limit < len(rows) - return 200, {"data": {key: chunk, "summary": summary}, - "meta": {"has_more": more, "next_cursor": str(start + limit) if more else None, "limit": limit}} - - def _user_attrs(self, u: Dict[str, Any]) -> Dict[str, Any]: - return {"id": u["id"], "company_id": u["company_id"], "email": u["email"], "role": u["role"], - "status": u["status"], "locations": [{"location_id": x} for x in u["_locations"]], - "invited_at": u.get("invited_at"), - **({"department": u["department"]} if u.get("department") else {})} - - def _loc_user(self, u: Dict[str, Any], lid: str) -> Dict[str, Any]: - return {"id": u["id"], "email": u["email"], "role": u["role"], "status": u["status"], "location_id": lid, - "enabled_products": sorted(u["_products"].get(lid, set())), - "groups": [g["group_name"] for g in self.groups.values() - if g["location_id"] == lid and u["id"] in g["members"]]} +"""The unit tests use the public fake: intelligence_cloud.testing.""" +from intelligence_cloud.testing._fake import RESELLER, VERTICAL, FakeAPI, new_id # noqa: F401 diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index f40916a..aa3fc79 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -74,7 +74,7 @@ def test_create_follows_the_setup_flow(api, client): ("POST", r"/companies/[^/]+/domains"), ("POST", r"/companies/[^/]+/locations"), ("POST", r"/locations/[^/]+/connectors"), ("POST", r"/locations/[^/]+/user-groups"), ("POST", r"/locations/[^/]+/first-alert/rules"), ("POST", r"/locations/[^/]+/insights-hub/setup")] - seq = api.writes() + seq = api.writes_since() pos = -1 for m, pat in order: pos = next(i for i, (mm, pp) in enumerate(seq) if mm == m and re.match("^" + pat + "$", pp) and i > pos) @@ -119,7 +119,7 @@ def test_create_follows_the_setup_flow(api, client): def test_rerun_writes_nothing(api, client, customer): start = len(api.calls) again = client.accounts.create_customer(spec(company_id=customer.company_id)) - assert api.writes(start) == [] + assert api.writes_since(start) == [] assert again.company_id == customer.company_id and again.teams[0].location_id == customer.teams[0].location_id assert again.teams[0].rules == customer.teams[0].rules and again.management.groups == customer.management.groups assert not again.created and again.existing @@ -143,7 +143,7 @@ def test_create_without_phrases_leaves_them_pending(api, client): assert rule(api, team.location_id, "Customer Threat")["triggers"][1]["config"]["keywords"] == THREAT assert client.accounts.get_customer(cust.company_id).pending == [] start = len(api.calls) - assert client.accounts.set_alerts(cust, ALERTS) == [] and api.writes(start) == [] + assert client.accounts.set_alerts(cust, ALERTS) == [] and api.writes_since(start) == [] def test_alert_levels_and_phrases_change_independently(api, client, customer): @@ -167,7 +167,7 @@ def test_bad_alert_settings_are_refused_before_any_write(api, client, bad): with pytest.raises(ic.InvalidRequestError): client.accounts.create_customer(spec(alerts=ic.AlertSettings( low_sentiment=ic.AlertSetting(phrases=["x"])))) - assert api.writes() == [] + assert api.writes_since() == [] def test_set_alerts_keeps_on_off_state(api, client, customer): @@ -189,14 +189,14 @@ def test_inactive_company_needs_reactivate(api, client, customer): def test_management_name_is_reserved(api, client): with pytest.raises(ic.InvalidRequestError): client.accounts.create_customer(spec(team=ic.TeamSpec(**{**vars(TEAM), "name": MGMT}))) - assert api.writes() == [] + assert api.writes_since() == [] def test_user_login_is_refused(api): api.role = "frontline_user" with pytest.raises(ic.WrongLoginError) as e: api.client().accounts.create_customer(spec()) - assert "administrator" in str(e.value) and api.writes() == [] + assert "administrator" in str(e.value) and api.writes_since() == [] # ---------------------------------------------------------------------- company matching @@ -215,7 +215,7 @@ def test_same_name_other_contact_is_refused_before_any_write(api, client): with pytest.raises(ic.ConflictError) as e: client.accounts.create_customer(spec()) assert e.value.code == "company_name_conflict" and "company_id" in str(e.value) - assert api.writes() == [] + assert api.writes_since() == [] def test_same_name_and_contact_is_reused(api, client): @@ -256,14 +256,14 @@ def test_connector_of_another_type_from_type_and_config(api, caplog): assert "T0KEN-SECRET" not in repr(cust) + caplog.text start = len(api.calls) c.accounts.create_customer(spec(connector=other, company_id=cust.company_id)) - assert api.writes(start) == [] + assert api.writes_since(start) == [] def test_unknown_connector_type_is_refused_before_any_write(api, client): bad = ic.ConnectorSpec(type="nosuchpbx", config={"api_key": "K-SECRET"}) with pytest.raises(ic.InvalidRequestError) as e: client.accounts.create_customer(spec(connector=bad)) - assert "K-SECRET" not in str(e.value) and api.writes() == [] + assert "K-SECRET" not in str(e.value) and api.writes_since() == [] def create_with_connector_stop(c, s): @@ -308,10 +308,10 @@ def test_set_connector_attaches_one_later_and_refuses_an_active_one(api, client) assert [t.kind for t in teams] == ["team", "management"] and all(t.connector_status == "active" for t in teams) start = len(api.calls) client.accounts.set_connector(cust, CONN) - assert api.writes(start) == [] + assert api.writes_since(start) == [] with pytest.raises(ic.InvalidRequestError): client.accounts.set_connector(cust, EAST_CONN) - assert api.writes(start) == [] + assert api.writes_since(start) == [] # ---------------------------------------------------------------------- teams @@ -327,7 +327,7 @@ def test_add_team_copies_the_first_teams_alerts(api, client, customer): assert len([g for g in api.groups.values() if g["location_id"] == east.location_id]) == 5 start = len(api.calls) again = client.accounts.add_team(customer.company_id, EAST, EAST_CONN) - assert again.location_id == east.location_id and api.writes(start) == [] + assert again.location_id == east.location_id and api.writes_since(start) == [] with pytest.raises(ic.InvalidRequestError): client.accounts.add_team(customer, EAST, None) # type: ignore[arg-type] other = client.accounts.add_team(customer, ic.TeamSpec(**{**vars(EAST), "name": "Riverbend - West"}), @@ -366,7 +366,7 @@ def test_add_base_user(api, client, customer): mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) start = len(api.calls) bu = client.accounts.add_base_user(customer, person(1), team=team, line="2101") - writes = api.writes(start) + writes = api.writes_since(start) assert writes[0][1].endswith("/users") and writes[-1][1].endswith(f"/{bu.user_id}/resend-invitation") create = next(b for m, p, b in api.bodies if m == "POST" and p.endswith("/users") and b["email"] == "user1@example.com") assert create["send_invitation"] is False and create["location_ids"] == [team.location_id] @@ -379,7 +379,7 @@ def test_add_base_user(api, client, customer): start = len(api.calls) again = client.accounts.add_base_user(customer, person(1), team=team, line="2101") assert again.user_id == bu.user_id and not again.created and not again.invited - assert api.writes(start) == [] + assert api.writes_since(start) == [] invariants(api) @@ -418,7 +418,7 @@ def test_activate_alerts_does_not_need_a_manager(api, client, customer): out = client.accounts.activate_alerts(customer) assert out == {"switched_on": [], "no_manager": []} start = len(api.calls) - assert client.accounts.activate_alerts(customer)["switched_on"] == [] and api.writes(start) == [] + assert client.accounts.activate_alerts(customer)["switched_on"] == [] and api.writes_since(start) == [] def test_mapping_failure_raises_account_error_and_rerun_continues(api): @@ -469,7 +469,7 @@ def test_remove_user_releases_only_a_line_no_one_else_holds(api, client, custome assert api.fa_numbers(team.location_id) == ["2103"] and api.ih_numbers(team.location_id) == ["2103"] start = len(api.calls) client.accounts.remove_user(customer, a.user_id) - assert api.writes(start) == [] + assert api.writes_since(start) == [] out = client.accounts.remove_user(customer, mgr.user_id) assert out["license"] == "base_manager" and out["released_lines"] == [] assert api.fa_numbers(team.location_id) == ["2103"] @@ -491,7 +491,7 @@ def test_sync_lines(api, client, customer): client.users.set_numbers(customer.company_id, mgr.user_id, team.connector_id, ["2199"]) start = len(api.calls) diff = client.accounts.sync_lines(customer, dry_run=True) - assert api.writes(start) == [] and not diff["applied"] + assert api.writes_since(start) == [] and not diff["applied"] d = diff["teams"][team.location_id] assert d["first_alert"] == {"add": ["2101"], "remove": ["2199"]} and d["insights_hub"] == {"add": [], "remove": []} assert d["holders"][mgr.user_id] == {"add": ["2101"], "remove": ["2199"]} @@ -501,7 +501,7 @@ def test_sync_lines(api, client, customer): assert api.numbers(mgr.user_id, customer.management.connector_id) == ["2001"] # own line kept start = len(api.calls) client.accounts.sync_lines(customer) - assert api.writes(start) == [] + assert api.writes_since(start) == [] def test_send_invitations(api, client, customer): @@ -525,7 +525,7 @@ def test_offboard_customer(api, client, customer): out = client.accounts.offboard_customer(customer) kinds = [("automation" in p and "hook") or ("first-alert/config" in p and "fa") or ("/connectors/" in p and "conn") or ("/users/" in p and "user") or ("/deactivate" in p and "company") - for _, p in api.writes(start)] + for _, p in api.writes_since(start)] assert kinds == ["hook", "fa", "conn", "conn", "user", "company"] assert api.after_call_hooks[team.location_id]["enabled"] is False assert api.fa_config[team.location_id]["webhook_url"] is None and api.fa_numbers(team.location_id) == ["2101"] @@ -534,7 +534,7 @@ def test_offboard_customer(api, client, customer): assert api.users[mgr.user_id]["status"] != "deactivated" and not api.companies[customer.company_id]["is_active"] start = len(api.calls) again = client.accounts.offboard_customer(customer) - assert not again["company_deactivated"] and again["connectors_deactivated"] == [] and api.writes(start) == [] + assert not again["company_deactivated"] and again["connectors_deactivated"] == [] and api.writes_since(start) == [] # ---------------------------------------------------------------------- the acceptance scenario @@ -551,7 +551,7 @@ def test_acceptance_scenario(api, client): # re-run: no writes start = len(api.calls) acc.create_customer(spec(company_id=cust.company_id)) - assert api.writes(start) == [] + assert api.writes_since(start) == [] # add team east = acc.add_team(cust, EAST, EAST_CONN) assert [t.name for t in cust.teams] == ["Riverbend - Main", "Riverbend - East"] @@ -573,7 +573,7 @@ def test_acceptance_scenario(api, client): assert ben.user_id in api.group_members(main.location_id, "Customer Threats") start = len(api.calls) acc.change_license(cust, ben.user_id, "base_manager", teams=[main]) - assert api.writes(start) == [] + assert api.writes_since(start) == [] # change license: Base Manager -> Base User (keeps one team and their own line) down = acc.change_license(cust, ben.user_id, "base_user", teams=[main]) assert down.license == "base_user" and down.lines == ["2103"] @@ -592,7 +592,7 @@ def test_acceptance_scenario(api, client): assert sorted(api.numbers(dee.user_id, east.connector_id)) == ["2101", "3101"] start = len(api.calls) acc.move_user(cust, ana.user_id, from_team=main, to_team=east) - assert api.writes(start) == [] + assert api.writes_since(start) == [] # move: swap one of a Base Manager's teams eve = acc.add_base_manager(cust, person(6), teams=[main], invite=False) acc.move_user(cust, eve.user_id, from_team=main, to_team=east) @@ -606,7 +606,7 @@ def test_acceptance_scenario(api, client): assert "3109" in api.numbers(dee.user_id, east.connector_id) and "3101" not in api.numbers(dee.user_id) start = len(api.calls) acc.change_line(cust, cy.user_id, "3101", "3109") - assert api.writes(start) == [] + assert api.writes_since(start) == [] # remove out = acc.remove_user(cust, cy.user_id) assert out["released_lines"] == ["3109"] and "3109" not in api.numbers(dee.user_id) diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py index 9a3d9c5..e11ae3f 100644 --- a/tests/unit/test_review_fixes.py +++ b/tests/unit/test_review_fixes.py @@ -60,7 +60,7 @@ def test_add_base_user_refuses_an_existing_manager_before_any_write(): start = len(api.calls) with pytest.raises(ic.InvalidRequestError) as e: c.accounts.add_base_user(cust, person(9), team=t, line="299") - assert "change_license" in str(e.value) and api.writes(start) == [] + assert "change_license" in str(e.value) and api.writes_since(start) == [] assert sorted(api.numbers(m.user_id)) == ["201", "202", "900"] @@ -73,7 +73,7 @@ def test_add_base_manager_refuses_an_existing_base_user_and_integration_refuses_ c.accounts.add_base_manager(cust, person(1), teams=[t], line="901") with pytest.raises(ic.InvalidRequestError): c.accounts.add_integration_user(cust, person(1)) - assert api.writes(start) == [] and api.numbers(u.user_id) == ["201"] + assert api.writes_since(start) == [] and api.numbers(u.user_id) == ["201"] assert api.fa_numbers(t.location_id) == ["201"] @@ -102,7 +102,7 @@ def test_change_line_keeps_a_line_another_base_user_still_holds(): assert sorted(api.numbers(m.user_id, t.connector_id)) == ["201", "211"] start = len(api.calls) c.accounts.change_line(cust, u1.user_id, "201", "211") - assert api.writes(start) == [] + assert api.writes_since(start) == [] c.accounts.change_line(cust, u2.user_id, "201", "212") # the last holder: 201 is released now assert sorted(api.fa_numbers(t.location_id)) == ["211", "212"] assert sorted(api.numbers(m.user_id, t.connector_id)) == ["211", "212"] @@ -117,7 +117,7 @@ def test_change_line_for_a_manager_touches_only_their_own_line(): start = len(api.calls) with pytest.raises(ic.InvalidRequestError): c.accounts.change_line(cust, m.user_id, "201", "777") - assert api.writes(start) == [] + assert api.writes_since(start) == [] c.accounts.change_line(cust, m.user_id, "900", "901") assert api.numbers(m.user_id, cust.management.connector_id) == ["901"] assert api.numbers(m.user_id, t.connector_id) == ["201"] and api.numbers(m2.user_id, t.connector_id) == ["201"] @@ -132,7 +132,7 @@ def _writes_of(setup, action): ctx = setup(c) start = len(api.calls) action(c, ctx) - return len(api.writes(start)) + return len(api.writes_since(start)) def _resume_every_step(setup, action, check): @@ -150,7 +150,7 @@ def _resume_every_step(setup, action, check): check(api, ctx) start = len(api.calls) action(c, ctx) - assert api.writes(start) == [], f"write {k}: the third run wrote" + assert api.writes_since(start) == [], f"write {k}: the third run wrote" def test_change_license_to_base_user_resumes_after_any_step(): @@ -313,7 +313,7 @@ def everyone(): everyone() start = len(api.calls) everyone() - assert api.writes(start) == [] + assert api.writes_since(start) == [] # ---------------------------------------------------------------------- S1: nested secrets diff --git a/tests/unit/test_testing_module.py b/tests/unit/test_testing_module.py new file mode 100644 index 0000000..a6f6041 --- /dev/null +++ b/tests/unit/test_testing_module.py @@ -0,0 +1,143 @@ +"""intelligence_cloud.testing: the README examples run end to end, the knobs work, and the fake refuses +requests the published spec does not define.""" +from __future__ import annotations + +import httpx +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.testing import CONNECTOR_OUTCOMES, FakeAPI, FakeRequest, SeededCustomer + + +# ---------------------------------------------------------------------- the README examples + + +def test_readme_account_example(): + api = FakeAPI() + seeded = api.seed_customer() + admin = api.client(role="admin") + team = seeded.customer.teams[0] + member = admin.accounts.add_base_user(seeded.customer, ic.PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=team, line="2109") + assert member.license == "base_user" + assert ("POST", f"/companies/{seeded.company_id}/users") in api.writes + assert api.fa_numbers(team.location_id)[-1] == "2109" + start = len(api.requests) + admin.accounts.add_base_user(seeded.customer, ic.PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=team, line="2109") + assert api.writes_since(start) == [] # safe to re-run + + +def test_readme_conversation_example(): + api = FakeAPI() + ids = api.seed_calls(3) + me = api.client(role="user") + briefs = me.conversations.calls() + assert [b.id for b in briefs] == ids + assert briefs[0].caller_number.startswith("***") + assert me.conversations.brief(ids[0]).key_points == ["Asked about an appointment"] + assert len(me.conversations.open_tasks()) == 3 and len(me.conversations.alerts()) == 2 + with pytest.raises(ic.WrongLoginError): + api.client(role="admin").conversations.calls() + + +def test_readme_failed_then_resumed_example(): + api = FakeAPI() + seeded = api.seed_customer() + admin = api.client(role="admin") + api.fail_write(2) # the second write of the next call fails + with pytest.raises(ic.AccountError) as e: + admin.accounts.add_base_user(seeded.customer, ic.PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=seeded.customer.teams[0], line="2109") + assert e.value.find(ic.ValidationError) is not None + again = admin.accounts.add_base_user(seeded.customer, ic.PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=seeded.customer.teams[0], line="2109") + assert again.user_id == e.value.result.user_id + + +# ---------------------------------------------------------------------- seed data and knobs + + +def test_seed_customer_is_fictional_and_complete(): + api = FakeAPI() + seeded = api.seed_customer(teams=2) + assert isinstance(seeded, SeededCustomer) and len(seeded.customer.teams) == 2 + assert all(e.endswith("@example.com") for e in list(seeded.base_users) + list(seeded.managers)) + assert len(seeded.base_users) == 4 and len(seeded.managers) == 1 + assert api.requests == [] and api.writes == [] # the log starts clean + report = api.client(role="admin").accounts.license_report(seeded.company_id) + assert (report["base_user"], report["base_manager"], report["teams"]) == (4, 1, 2) + + +@pytest.mark.parametrize("outcome", CONNECTOR_OUTCOMES) +def test_connector_outcomes(outcome): + api = FakeAPI(connector_outcome=outcome) + seeded = api.seed_customer(people=False) # seeding always succeeds + admin = api.client(role="admin") + team = ic.TeamSpec("Riverbend - East", "9 Lake St", "Springfield", "IL", "US", "62702", "service-providers") + conn = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend-east.example.com", "example-key", + timeout=60) + if outcome in ("active", "connected"): + assert admin.accounts.add_team(seeded.customer, team, conn).connector_status == outcome + else: + with pytest.raises(ic.AccountError) as e: + admin.accounts.add_team(seeded.customer, team, conn) + expected = ic.ConnectorTimeoutError if outcome == "stuck" else ic.ConnectorError + assert isinstance(e.value.cause, expected) + + +def test_network_down_and_rate_limited(): + api = FakeAPI() + me = api.client(role="user", max_retries=1) + api.network_down() + with pytest.raises(ic.NetworkError): + me.conversations.calls() + api.network_down(False) + api.rate_limit(count=5, retry_after=120) + with pytest.raises(ic.RateLimitError) as e: + me.conversations.calls() + assert e.value.retry_after == 120 + api.rate_limit(0) + assert me.conversations.calls() == [] + + +def test_request_log(): + api = FakeAPI() + api.seed_calls(1) + api.client(role="user").conversations.calls() + last = api.requests[-1] + assert isinstance(last, FakeRequest) and last.method == "GET" and last.path == "/calls" + assert last.operation == "listCalls" and "date_from" in last.query + assert api.count("GET", r"/calls") == 1 + + +# ---------------------------------------------------------------------- strictness + + +def raw(api): + return httpx.Client(base_url="https://app.intelligence.cloud/api/v1", transport=httpx.MockTransport(api)) + + +def test_unknown_path_is_refused(): + api = FakeAPI() + r = raw(api).get("/calls/export") + assert r.status_code == 404 and r.json()["error"]["code"] == "NOT_FOUND" + assert raw(api).delete("/companies/x").status_code == 404 # a method the path does not have + + +def test_unknown_query_parameter_is_refused(): + api = FakeAPI() + r = raw(api).get("/calls", params={"page_size": 10}) + assert r.status_code == 400 and "page_size" in r.json()["error"]["message"] + + +def test_missing_required_body_field_is_refused(): + api = FakeAPI() + r = raw(api).post("/locations/l1/user-groups", json={"member_ids": []}) + assert r.status_code == 422 and "group_name" in r.json()["error"]["message"] + assert raw(api).post("/auth/login", json={"email": "a@example.com"}).status_code == 422 + + +def test_strictness_can_be_switched_off(): + api = FakeAPI(strict=False) + assert raw(api).get("/nothing/here").status_code == 501 From 0a75e456c9d956271bb25934be52732eec4c6c85 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 18:41:46 -0700 Subject: [PATCH 03/11] 0.3.0: README, CHANGELOG, examples, request counts, metadata - README: retry policy with worst-case blocking time, the error tree, AccountError.find, the event rule (store by call id and upsert), First Alert payload not final, "Testing your code", "Running helpers from more than one process", "How many requests" (pinned by a test), links to the SDK pages; examples ship in the sdist, not the wheel - CHANGELOG 0.3.0 with a breaking-changes table; corrected the 0.2.0 activate_alerts line - Examples: Riverbend Auto Group, IC_ADMIN_* and IC_USER_* (IC_DATA_* as a fallback); the receiver skips only exact re-deliveries - Package metadata links to the SDK pages and a changelog; version 0.3.0 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 29 +++- README.md | 217 +++++++++++++++++++++++------ examples/_common.py | 23 +-- examples/alert_webhook_receiver.py | 4 +- examples/create_customer.py | 2 +- examples/my_day.py | 4 +- examples/webhook_receiver.py | 42 ++++-- pyproject.toml | 12 +- src/intelligence_cloud/_version.py | 2 +- src/intelligence_cloud/client.py | 1 + src/intelligence_cloud/receiver.py | 2 +- tests/unit/test_policy.py | 2 +- tests/unit/test_request_counts.py | 80 +++++++++++ tests/unit/test_testing_module.py | 14 ++ 14 files changed, 354 insertions(+), 80 deletions(-) create mode 100644 tests/unit/test_request_counts.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 13cc754..b61670c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,39 @@ # Changelog +## 0.3.0 (2026-12-01) + +### What changed for callers + +- **Bad input never reaches the network.** Every helper of `client.accounts` and `client.conversations` checks its arguments before it signs in or sends anything. A 40-day window, `limit=500` or `alerts(status=...)` raise `InvalidRequestError` with no request made, even with the network down, and cost no sign-in. +- **One retry policy, written down** (README "Retries"). Network failures and 5xx are now retried on sign-in too, and on token renewal when the request never left. A 429 whose `Retry-After` is longer than the wait limit raises `RateLimitError` at once with `.retry_after` (a sign-in 429 with `Retry-After: 120` used to wait 60 seconds and then fail). User creation keeps retrying with its idempotency key. +- **One error tree in every SDK language** (README "Error handling"). `ApiError.server_message` holds the server's text; `.message` stays as an alias. `NetworkError.request_sent` says whether the request left. `AccountError.find(ErrorType)` returns the first error of that type in the cause chain: a clashing line is `AccountError` → `ExtensionMappingError` → `ConflictError`. +- **Events: store by call id and upsert.** A later After Call delivery for the same call can carry newer data. `Deduplicator.is_duplicate(event)` is now True only for an exact re-delivery (same event type, location, call id and canonical-JSON content) and takes an event, a parsed body or raw bytes; it never hides newer data. New `upsert_key(event)` (also `Deduplicator.upsert_key`) returns the call id (or alert id) to store under. The README receiver section and `examples/webhook_receiver.py` follow this. +- **First Alert payload is not final.** `parse_first_alert_event` accepts any non-empty string id (it used to refuse ids that were not UUIDs and lower-cased them); it keeps reading rule, location, call and time from today's shapes, and `raw` holds the whole payload. +- **`intelligence_cloud.testing`**: a supported fake API for your tests and CI. `FakeAPI.client(role="admin" | "user")`, fictional seed data (`seed_customer`, `seed_calls`), failure knobs (`connector_outcome`, `fail_write`, `network_down`, `rate_limit`), a request log, and strict refusal of requests the published spec does not define. README "Testing your code". +- Connector waits count the check intervals as well as the clock, so a replaced `sleep` (tests) cannot spin for the whole timeout. +- README: "Retries" with worst-case blocking time, "Testing your code", "Running helpers from more than one process", "How many requests" (pinned by a test), the error tree. SDK documentation links now point to the SDK pages (https://docs.intelligence.cloud/sdk/, /sdk/quick-start, /sdk/reference, /sdk/events, /sdk/configuration, /sdk/downloads); API links stay https://docs.intelligence.cloud/api and https://docs.intelligence.cloud/reference. The examples ship in the source distribution, not the wheel, and the README says so. Package metadata links to the SDK pages, with "Changelog" on https://docs.intelligence.cloud/sdk/downloads. +- Examples use one fictional customer, Riverbend Auto Group, and the variables `IC_ADMIN_EMAIL` / `IC_ADMIN_PASSWORD` and `IC_USER_EMAIL` / `IC_USER_PASSWORD` (`IC_DATA_*` still read by the examples as a fallback). + +### Breaking changes + +| 0.2.0 | 0.3.0 | +|---|---| +| `Client(base_url, email, password, token_store, timeout, ...)`, positional | `Client(email, password, *, base_url=..., token_store=..., timeout=..., ...)`: only email and password by position | +| `MfaRequiredError` derived from `IntelligenceCloudError` only | It is an `AuthError` (status 200, code `mfa_required`): an `except AuthError` now catches it | +| `ConnectorTimeoutError` was not a `ConnectorError` | It is: an `except ConnectorError` now catches timeouts too (put `except ConnectorTimeoutError` first to tell them apart) | +| `FrontlineRequiredError` derived from `IntelligenceCloudError` only | It is a `WrongLoginError` | +| `Deduplicator.is_duplicate(event)` was True for any repeat of a call id | True only for an exact re-delivery; a changed delivery for the same call returns False | +| `parse_first_alert_event` refused non-UUID ids and lower-cased ids | Any non-empty string id, kept as sent | +| A sign-in 429 always waited `login_rate_limit_wait` once | It waits only when `Retry-After` fits in that limit; otherwise raises at once | +| Conversation and account helpers signed in before checking arguments | They check first; with a bad argument no request is sent (your mocks may see fewer requests) | + ## 0.2.0 (2026-11-29) Two new layers. `client.accounts` replaces `client.workflows`; `client.conversations` is new. Every generated resource method and every `client.intelligence` helper keeps its name and behaviour. - **Account layer, `client.accounts`** (administrator login): create and maintain a customer on Base User and Base Manager licenses. A customer is a company with teams and a ` - Management` location. Each team gets its own connector, five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub Access, Insights Hub Weekly Reports) and three alerts (Customer Threat, Upset Customer, Low Sentiment), each routed to its group. Management gets its own connector, which captures the managers' own lines, and the weekly reports group; it has no alerts. Helpers: `create_customer`, `get_customer`, `add_team`, `set_alerts`, `set_connector`, `add_base_user`, `add_base_manager`, `add_integration_user`, `change_license`, `move_user`, `change_line`, `remove_user`, `activate_alerts`, `send_invitations`, `list_members`, `license_report`, `sync_lines`, `offboard_customer`. - Every account helper finds what exists before it writes: a second run with the same input writes nothing. A helper that stops part-way raises `AccountError` with the step, the result so far and the cause. -- A customer can be created without the phrase lists: Low Sentiment and every group are created, `Customer.pending` lists the two phrase alerts, and `set_alerts` creates them when the lists arrive. `AlertSettings` sets the phrases and the sentiment level of each alert; `None` keeps what is there. Alerts are created switched off; `activate_alerts` switches them on for teams with a Base Manager in each alert group. +- A customer can be created without the phrase lists: Low Sentiment and every group are created, `Customer.pending` lists the two phrase alerts, and `set_alerts` creates them when the lists arrive. `AlertSettings` sets the phrases and the sentiment level of each alert; `None` keeps what is there. Alerts are created switched off; `activate_alerts` switches them on for every team, and lists under `no_manager` the teams whose alert groups have no Base Manager (their alerts show in the app only). (Corrected in 0.3.0: this entry first said alerts came on only where each group had a manager.) - Alert email is off for every person the helpers create, managers included (0.1.x switched it on for managers). Insights Hub "monitor all numbers" stays off. - `ConnectorSpec(type, config, name=None, timeout=600)` takes any connector type the API accepts with that type's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Values whose names contain key, secret, token or password are hidden when the spec is printed. `add_team` requires a connector; `set_connector` attaches one to a customer created without it. - **Conversation layer, `client.conversations`** (the person's own login): `me`, `teams`, `calls`, `brief`, `transcript`, `recording_link`, `caller_history`, `open_tasks`, `alerts`, `alert`, `team_view`, `topics`, `reference`, `parse_first_alert_event`. Caller numbers are masked to their last four digits unless the client is created with `mask_numbers=False`. Windows are at most 31 days and lists at most 200 (`caller_history` 50), checked before any request. Printing a `CallBrief` or `AlertBrief` shows only its id and time. diff --git a/README.md b/README.md index beebb1a..08a613a 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ Python client for the Intelligence Cloud partner API. It covers both jobs: - **Customers** with an administrator login: the account layer (`client.accounts`) creates and maintains a customer on Base User and Base Manager licenses, beside one method per API operation (companies, locations, users, products, connectors, First Alert, Insights Hub). - **Conversations** with a user login: the conversation layer (`client.conversations`) gives a signed-in person their own calls, tasks and alerts; `client.intelligence` reads calls, transcripts, recordings, alerts, tasks and insights; and the After Call and First Alert webhooks. -Version 0.2.0. Python 3.10 or later. One dependency: `httpx` (0.27 or later). +Version 0.3.0. Python 3.10 or later. One dependency: `httpx` (0.27 or later). Changes: `CHANGELOG.md`. -The API reference is at https://docs.intelligence.cloud/reference.html, built from https://docs.intelligence.cloud/openapi.yaml. +SDK documentation: overview https://docs.intelligence.cloud/sdk/, quick start https://docs.intelligence.cloud/sdk/quick-start, every helper https://docs.intelligence.cloud/sdk/reference, events https://docs.intelligence.cloud/sdk/events, client options and errors https://docs.intelligence.cloud/sdk/configuration, downloads and versions https://docs.intelligence.cloud/sdk/downloads. The API itself: the guide https://docs.intelligence.cloud/api and the API reference https://docs.intelligence.cloud/reference, built from https://docs.intelligence.cloud/openapi.yaml. ## Install @@ -24,7 +24,7 @@ unzip python.zip && cd python pip install . # or: uv pip install . ``` -To run the examples without installing: `uv run --with httpx --with-editable . python examples/whoami.py`. +The examples are not in the wheel. They ship in the source distribution (`pip download --no-binary :all: --no-deps intelligence-cloud`, then unpack it) and in the source repository linked from the package page. From an unpacked source distribution: `uv run --with httpx --with-editable . python examples/whoami.py`. ## Credentials @@ -45,11 +45,11 @@ Keep credentials out of source code. Read them from your secret store or environ import os from intelligence_cloud import Client -admin = Client(email=os.environ["IC_ADMIN_EMAIL"], password=os.environ["IC_ADMIN_PASSWORD"]) -data = Client(email=os.environ["IC_DATA_EMAIL"], password=os.environ["IC_DATA_PASSWORD"]) +admin = Client(os.environ["IC_ADMIN_EMAIL"], os.environ["IC_ADMIN_PASSWORD"]) +data = Client(os.environ["IC_USER_EMAIL"], os.environ["IC_USER_PASSWORD"]) ``` -`Client(base_url="https://app.intelligence.cloud/api/v1", email, password, token_store=None, timeout=30)`; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. +`Client(email, password, *, base_url="https://app.intelligence.cloud/api/v1", token_store=None, timeout=30, ...)`: email and password first (by position or keyword), everything else by keyword; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. ### Sign-in, tokens and sign-out @@ -80,7 +80,7 @@ phone_system = ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "ri customer = admin.accounts.create_customer(CustomerSpec( company_id=saved_company_id, # None the first time; store customer.company_id and pass it on re-runs - company_name="Riverbend Dental", + company_name="Riverbend Auto Group", admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"), team=TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", country="US", zipcode="62701", vertical=""), @@ -128,7 +128,16 @@ admin.accounts.activate_alerts(customer) # once each team has a manager in it | `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | changes | | `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary | -Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only: a clash raises `ConflictError` with the message "Extension is already monitored at another location." +Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only. A line another location already holds reaches you as **`AccountError` → `ExtensionMappingError` → `ConflictError`** (message "Extension is already monitored at another location.", the clashing numbers on `.extensions`). Use `AccountError.find` instead of walking the chain: + +```python +try: + admin.accounts.add_base_user(customer, person, team=team, line="2101") +except AccountError as err: + clash = err.find(ConflictError) # None when the stop had another cause + if clash: + print("already captured at another location:", clash.extensions) +``` ## Conversation layer: `client.conversations` (user login) @@ -243,7 +252,24 @@ Module level: `parse_after_call_event`, `parse_first_alert_event`, `UnknownEvent - **Connectors:** `create_connector`, `reactivate_connector` and `deactivate_connector` wait for the final status, checking every 10 seconds for up to 10 minutes (`timeout=` in seconds; `wait=False` to return at once). An `error` raises `ConnectorError` with `state_reason`; no final status in time raises `ConnectorTimeoutError`. - **Responses** carry only the fields in the published reference. Anything else is dropped. With `Client(keep_unknown_fields=True)` new fields the reference does not list yet are kept on the customer-lifecycle (admin) reads; `get_me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields. Either way, the one-time sign-in link a user create can return is never passed through or logged. - **Test endpoints** (connector dry run, webhook tests) report only success and the HTTP status. -- **Retries:** 429 and 5xx are retried up to 3 times with backoff and jitter, honouring `Retry-After` up to 60 seconds. A longer `Retry-After` is not waited out: `RateLimitError` is raised at once with `.retry_after`. 5xx is retried only for reads, updates, deletes and user create, never for other creates. +- **Retries:** see "Retries" below. +- **Checks first:** every helper of both layers checks its arguments before it signs in or sends anything. Bad input raises `InvalidRequestError` with no request made, so it costs no sign-in (sign-in is limited to 5 a minute). + +### Retries + +One policy, the same in every SDK: + +| Situation | What the client does | +|---|---| +| Network failure (no connection, timeout) or 5xx on a read, update, delete, or user create (which carries an idempotency key, reused on every try) | Retries up to `max_retries` (3) times with exponential backoff and jitter: about 0.5, 1 and 2 seconds plus up to half again | +| The same on sign-in | Retried the same way | +| The same on token renewal | 5xx retried; a network failure retried only when the request never left (a refresh token is used once and must never be sent twice) | +| Network failure or 5xx on any other create | Not retried: the error is raised, so nothing is created twice | +| 429 with `Retry-After` within the limit (60 s; for sign-in, `login_rate_limit_wait`, default 60 s) | Waits `Retry-After` (backoff when absent), then retries; sign-in waits once | +| 429 with `Retry-After` above the limit | Raises `RateLimitError` at once with `.retry_after` set; it never waits first and then fails | +| 401 on a request | Renews the token once and retries | + +Worst case with the defaults (`timeout=30`, `max_retries=3`), one call can block for about: **2 minutes 5 seconds** when the network fails every try (4 tries × 30 s timeout + about 5 s of backoff); **3 minutes** when every try answers 429 with `Retry-After: 60` (3 waits of 60 s); and **1 minute** more on the first call if sign-in answers 429 within `login_rate_limit_wait`. Inside a web request, pass `login_rate_limit_wait=0`, a smaller `timeout` and `max_retries=1`. ## Error handling @@ -258,26 +284,31 @@ except ApiError as e: log.warning("Intelligence Cloud error %s %s request_id=%s", e.status, e.code, e.request_id) ``` -Log `status`, `code` and `request_id`, not exception text or response bodies. `str(error)` carries only the status, code and request id, plus text the SDK wrote itself (such as "Extension is already monitored at another location."). The server's own text is on `e.message`: it can echo numbers or names from the request, so keep it out of logs. +Log `status`, `code` and `request_id`, not exception text or response bodies. `str(error)` carries only the status, code and request id, plus text the SDK wrote itself (such as "Extension is already monitored at another location."). The server's own text is on `e.server_message` (also `e.message`): it can echo numbers or names from the request, so keep it out of logs. -| Error | When | -|---|---| -| `ApiError` | Any API error: `status`, `code`, `message`, `request_id` | -| `NetworkError` | The request did not complete (no connection, a timeout, an unreadable response): `status` 0, `code` `network_error` or `timeout`, `kind`. The HTTP library's own error is not attached, because it holds the request | -| `AuthError` (401), `PasswordExpiredError` | Sign-in failed, or the token could not be renewed | -| `NotFoundError` (404) | Not found, or outside what this login can see | -| `ConflictError` (409) | Duplicate name or email, already active or inactive, extension already monitored (`.extensions`) | -| `ValidationError` (400, 422) | Malformed request or refused value | -| `RateLimitError` (429) | Still rate limited after retries (`.retry_after`) | -| `InvalidRequestError` | Bad input, refused by the SDK before sending | -| `MfaRequiredError` | The integration user's company has MFA on | -| `FrontlineRequiredError` | `client.intelligence` conversation data asked for with an admin login | -| `WrongLoginError` | An account helper with a user login, or a conversation helper with an administrator login; the message says which login to use | -| `AccountError` | An account helper stopped part-way (`.step`, `.result`, `.cause`); run it again to continue | -| `ConnectorError`, `ConnectorTimeoutError` | A connector ended in `error`, or a new connector did not settle in time | -| `ExtensionMappingError` | A helper could not map numbers (`.user_id`, `.cause`); the `.cause` of an `AccountError` | -| `WebhookPayloadError` | A webhook body is not JSON, or is a malformed After Call or First Alert event (answer 400) | -| `PayloadTooLargeError` | A webhook body is over `max_bytes` (256 KB; answer 413) | +The error tree is the same in every SDK language: + +``` +IntelligenceCloudError +├─ ApiError (status, code, server_message, request_id, public_message; .message = server_message) +│ ├─ AuthError (401: sign-in failed, or the token could not be renewed) +│ │ ├─ MfaRequiredError (the integration user's company has MFA on) +│ │ └─ PasswordExpiredError +│ ├─ NotFoundError (404: not found, or outside what this login can see) +│ ├─ ConflictError (409: duplicate, already active or inactive, extension held elsewhere; .extensions) +│ ├─ ValidationError (400, 422) +│ ├─ RateLimitError (429; .retry_after) +│ └─ NetworkError (status 0; .kind transport | timeout | decoding; the HTTP library's error is not attached) +├─ InvalidRequestError (bad input, refused before sending; also a ValueError) +├─ WrongLoginError (the other kind of login is needed; the message says which) +│ └─ FrontlineRequiredError (client.intelligence asked for conversation data with an admin login) +├─ ConnectorError (a connector ended in error; .state_reason) +│ └─ ConnectorTimeoutError (a new connector did not settle in time) +├─ ExtensionMappingError (numbers not mapped; .user_id, .cause) +├─ AccountError (an account helper stopped part-way; .step, .result, .cause, .find(type)) +└─ WebhookPayloadError (a webhook body is not JSON or is malformed: answer 400; also a ValueError) + └─ PayloadTooLargeError (over max_bytes, 256 KB: answer 413) +``` All derive from `IntelligenceCloudError`. @@ -304,8 +335,10 @@ admin.intelligence.test_first_alert_webhook(location_id) - Answer 2xx within 2 seconds and do the work afterwards. Redirects count as failures. Delivery is tried 3 times, then dropped. - `parse_after_call_event` refuses bodies over 256 KB (`PayloadTooLargeError`: answer 413) and returns `UnknownEvent` for event types it doesn't handle: answer 2xx and ignore them. Answer 400 only for a body that isn't JSON or a malformed After Call event, and 404 for a wrong token. - Treat an event as a notification. Before you write anything from it into another system, read the call with `get_call(event.call.id)` using your frontline integration user; a `NotFoundError` means drop the event. -- Expect repeats of the same `call.id` (retries, and calls with several legs); a later one can carry newer data. Store events durably before acknowledging, and upsert on `call.id`. -- To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test`. +- **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsert_key(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before. +- `Deduplicator.is_duplicate(event)` is True only for an **exact re-delivery**: the same event type, location and call id and the same content (a SHA-256 of the canonical JSON body, because the payload carries no version marker). A later delivery with newer data is not a duplicate. It takes an event, a parsed body or the raw bytes. Use it to skip repeat work, never to skip an update. +- Its default store is **in memory and per process**: with more than one worker or process it misses repeats the others saw. Pass a shared store whose `add(key)` returns True only for a new key, for example `Deduplicator(store=RedisStore(redis_client))` where `RedisStore.add` is `return bool(r.set("ic:" + key, 1, nx=True, ex=86400))`. +- To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test` (from the source distribution). FastAPI: @@ -315,7 +348,7 @@ import os from fastapi import BackgroundTasks, FastAPI, HTTPException, Request from intelligence_cloud import (AfterCallEvent, Deduplicator, PayloadTooLargeError, WebhookPayloadError, - parse_after_call_event) + parse_after_call_event, upsert_key) app = FastAPI() dedup = Deduplicator() @@ -334,7 +367,8 @@ async def after_call(token: str, request: Request, background: BackgroundTasks): except WebhookPayloadError: raise HTTPException(status_code=400) if isinstance(event, AfterCallEvent) and not event.is_test and not dedup.is_duplicate(event): - background.add_task(handle, event.call.id) # read the call with get_call, then upsert on its id + store.upsert(upsert_key(event), event.raw) # durable, keyed on the call id: newer data replaces older + background.add_task(handle, upsert_key(event)) # read the call with get_call, then upsert your copy return {"ok": True} ``` @@ -360,15 +394,15 @@ def after_call(token): except WebhookPayloadError: abort(400) if isinstance(event, AfterCallEvent) and not event.is_test: - durable_queue.put_once(event.call.id) # a persistent queue keyed on call.id; process outside the request + durable_queue.upsert(event.call.id) # a persistent queue keyed on call.id: a later delivery re-opens it return {"ok": True} ``` -`Deduplicator.is_duplicate(...)` returns True for a repeat (the same name and meaning in all three SDKs: `isDuplicate` in PHP and TypeScript). It keeps the last 10,000 call ids in memory. With several workers, pass a shared `store` whose `add(key)` returns True only for a new key (for example a shared cache's set-if-absent with an expiry). Use it to skip repeat work, not to drop updates: when you keep a copy of the call, upsert on `call.id`. +`is_duplicate` has the same name and meaning in all three SDKs (`isDuplicate` in PHP and TypeScript). The in-memory store keeps the last 10,000 delivery keys. ### Receive First Alert -The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. `parse_first_alert_event` returns a `FirstAlertEvent` (`alert_id`, and `rule`, `location_id`, `call_id`, `timestamp` when the delivery carries them). Take the alert id, answer 2xx at once, then fetch the alert and its call with a frontline integration user in every alert group: +The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. **The First Alert payload is not final yet.** `parse_first_alert_event` returns a `FirstAlertEvent`: `alert_id` (any non-empty string under `alert_id`, `alert.id` or `id`), and `rule`, `location_id`, `call_id` and `timestamp` when the delivery carries them in the shapes known today; `raw` holds the whole payload. Take the alert id, answer 2xx at once, then fetch the alert and its call with a login in every alert group: ```python @app.post("/ic/alerts/{token}") @@ -381,7 +415,7 @@ async def first_alert(token: str, request: Request, background: BackgroundTasks) raise HTTPException(status_code=413) except WebhookPayloadError: raise HTTPException(status_code=400) - if not alert_dedup.is_duplicate(alert_id): # a second Deduplicator, keyed on the alert id + if not alert_dedup.is_duplicate(alert_id): # a bare alert id is an exact key: alerts do not change background.add_task(handle_alert, alert_id) return {"ok": True} @@ -401,19 +435,116 @@ for alert in data.intelligence.iter_alerts(date_from=went_down - timedelta(minut Alerts are dated by their call, so start the window 30 minutes before the receiver went down. +## Testing your code + +`intelligence_cloud.testing` is a supported fake API: run your code and CI with no account and no network. `FakeAPI.client(role="admin" | "user", **client_options)` returns a real `Client` wired to it. + +```python +import pytest +from intelligence_cloud import AccountError, PersonSpec, ValidationError +from intelligence_cloud.testing import FakeAPI + + +def test_adds_a_base_user(): + api = FakeAPI() + seeded = api.seed_customer() # "Riverbend Auto Group": fictional data + admin = api.client(role="admin") + member = admin.accounts.add_base_user(seeded.customer, PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=seeded.customer.teams[0], line="2109") + assert member.license == "base_user" + assert ("POST", f"/companies/{seeded.company_id}/users") in api.writes + + +def test_reads_todays_calls(): + api = FakeAPI() + ids = api.seed_calls(3) + briefs = api.client(role="user").conversations.calls() + assert [b.id for b in briefs] == ids and briefs[0].caller_number.startswith("***") + + +def test_resumes_after_a_stop(): + api = FakeAPI() + seeded = api.seed_customer() + admin = api.client(role="admin") + person = PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz") + api.fail_write(2) # the second write of the next call fails + with pytest.raises(AccountError) as err: + admin.accounts.add_base_user(seeded.customer, person, team=seeded.customer.teams[0], line="2109") + assert err.value.find(ValidationError) + again = admin.accounts.add_base_user(seeded.customer, person, team=seeded.customer.teams[0], line="2109") + assert again.user_id == err.value.result.user_id # running it again continues +``` + +| `FakeAPI` | Does | +|---|---| +| `FakeAPI(*, connector_outcome="active", role="admin", strict=True)` | A new, empty fake | +| `client(role=None, **client_options)` | A real `Client` (role "admin" or "user"); waits do not sleep | +| `seed_customer(*, teams=1, people=True)` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `company_id`, `base_users`, `managers`) | +| `seed_calls(n=3, *, location_id=None, day=None, alerts=True, tasks=True)` | Fictional calls with details, tasks and alerts (555-01xx numbers). Returns the call ids, newest first | +| `connector_outcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connectors created from now on | +| `fail_write(nth=1, status=400)`, `network_down(down=True)`, `rate_limit(count=1, retry_after=1)` | Failures your code must handle | +| `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()` | The request log (sign-in not included) | +| `products(uid, lid)`, `numbers(uid, connector_id=None)`, `fa_numbers(lid)`, `ih_numbers(lid)`, `group_members(lid, name)` | State to assert on | + +With `strict=True` the fake refuses what the published spec does not define, with the API's error shape: an unknown path or method (404), an unknown query parameter (400), a body missing a required field (422). It checks paths, methods, query names and top-level required body fields; it does not check value formats or nested fields, and its data is simpler than the platform's (for example search matching). Code that passes against it still needs one run against a test company before release. + +## Running helpers from more than one process + +Account helpers read, merge and write whole lists. Two processes changing the same customer at once can each read the old list and write back their own version, and one change is lost; two runs of `create_customer` for a new customer can create it twice. Run at most one account helper per customer at a time. On one machine, a file lock is enough: + +```python +import fcntl + +def with_customer_lock(company_id, fn): + with open(f"/tmp/ic-customer-{company_id}.lock", "w") as fh: + fcntl.flock(fh, fcntl.LOCK_EX) # waits for any other process on this machine + return fn() + +with_customer_lock(company_id, lambda: admin.accounts.add_base_user(company_id, person, team=team, line="2101")) +``` + +Across several machines, use your database. With PostgreSQL, an advisory lock held for the length of a transaction: + +```python +def with_customer_lock(conn, company_id, fn): + with conn.transaction(): + conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", ("ic-customer:" + company_id,)) + return fn() # released when the transaction ends +``` + +For a new customer, lock on a key you already have (your own account id) until `create_customer` returns and you have stored `company_id`. + +## How many requests + +Measured against `intelligence_cloud.testing` with a fresh client (one `GET /me` included, sign-in not counted); a test pins these numbers. The published limits are **5 requests a second per user, bursts of 20, and 50,000 a day per company**. + +| Helper | 1-team customer | 10-team customer | +|---|---|---| +| `create_customer` (first run, one team) | 35 | 35, plus 21 for each `add_team` (224 in all) | +| `create_customer`, re-run | 19 | 19 | +| `add_base_user` (customer passed as a company id) | 36 | 90 | +| `add_base_manager` (on every team) | 29 | 137 | +| `activate_alerts` | 14 | 86 | +| `calls` (one page) | 2 | 2 | +| `brief` | 3 | 3 | + +The counts assume two Base Users per team and one manager. At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. + ## Examples -| File | Shows | Credential | +The examples ship in the source distribution and the source repository, not in the wheel. Each uses the fictional customer Riverbend Auto Group. + +| File | Shows | Sign-in | |---|---|---| -| `examples/whoami.py` | Sign in and print the role | any | -| `examples/export_calls.py` | Export yesterday's calls to CSV (ids, dates, sentiment, duration) | frontline | +| `examples/whoami.py` | Sign in and print the role | either | +| `examples/export_calls.py` | Export yesterday's calls to CSV (ids, dates, sentiment, duration) | user | | `examples/create_customer.py` | Create a customer, add a Base User and a Base Manager, switch the alerts on (dry run unless `--apply`; phrase lists from the files in `IC_THREAT_PHRASES_FILE` and `IC_UPSET_PHRASES_FILE`, optional) | admin | -| `examples/my_day.py` | A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs | frontline (the person's own login) | -| `examples/webhook_receiver.py` | A dependency-free After Call webhook receiver: 256 KB cap, a persistent queue keyed on `call.id`, a worker that reads each call (`--self-test` to try it offline) | frontline (worker) | +| `examples/my_day.py` | A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs | user | +| `examples/webhook_receiver.py` | An After Call receiver: 256 KB cap, a persistent queue keyed on call id where newer data replaces older, exact re-deliveries skipped (`--self-test` to try it offline) | user (worker) | | `examples/after-call-sample.json` | A sample After Call event for local tests | none | -| `examples/alert_webhook_receiver.py` | A dependency-free First Alert webhook receiver that fetches each alert and its call (`--self-test` to try it offline) | frontline | +| `examples/alert_webhook_receiver.py` | A First Alert receiver that fetches each alert and its call (`--self-test` to try it offline) | user | -The admin examples read `IC_ADMIN_EMAIL` and `IC_ADMIN_PASSWORD`; the frontline examples read `IC_DATA_EMAIL` and `IC_DATA_PASSWORD`. `whoami.py` uses whichever pair is set. +Administrator examples read `IC_ADMIN_EMAIL` and `IC_ADMIN_PASSWORD`; the others read `IC_USER_EMAIL` and `IC_USER_PASSWORD`. `whoami.py` uses whichever pair is set. ## Regenerating from the spec diff --git a/examples/_common.py b/examples/_common.py index 0fe01bb..db5abb6 100644 --- a/examples/_common.py +++ b/examples/_common.py @@ -1,23 +1,24 @@ """Shared by the examples: a client from the environment. -Admin examples read IC_ADMIN_EMAIL / IC_ADMIN_PASSWORD; frontline examples read IC_DATA_EMAIL / -IC_DATA_PASSWORD. Each is a dedicated integration user. +Administrator examples read IC_ADMIN_EMAIL / IC_ADMIN_PASSWORD. Examples that act as a person read +IC_USER_EMAIL / IC_USER_PASSWORD (the older IC_DATA_EMAIL / IC_DATA_PASSWORD still work here). """ import os import sys from intelligence_cloud import Client -PAIRS = {"admin": ("IC_ADMIN_EMAIL", "IC_ADMIN_PASSWORD"), "data": ("IC_DATA_EMAIL", "IC_DATA_PASSWORD")} +PAIRS = {"admin": ("IC_ADMIN_EMAIL", "IC_ADMIN_PASSWORD"), "user": ("IC_USER_EMAIL", "IC_USER_PASSWORD")} +OLD_NAMES = {"user": ("IC_DATA_EMAIL", "IC_DATA_PASSWORD")} -def client_from_env(kind: str = "data") -> Client: - """kind: "admin", "data", or "any" (the first pair that is set).""" - kinds = ["admin", "data"] if kind == "any" else [kind] +def client_from_env(kind: str = "user") -> Client: + """kind: "admin", "user", or "any" (the first pair that is set).""" + kinds = ["admin", "user"] if kind == "any" else [kind] for k in kinds: - e, p = PAIRS[k] - email, password = os.environ.get(e), os.environ.get(p) - if email and password: - return Client(email=email, password=password, user_agent="ic-examples/0.2") + for e, p in [PAIRS[k]] + ([OLD_NAMES[k]] if k in OLD_NAMES else []): + email, password = os.environ.get(e), os.environ.get(p) + if email and password: + return Client(email, password, user_agent="ic-examples/0.3") names = " or ".join(f"{PAIRS[k][0]} and {PAIRS[k][1]}" for k in kinds) - sys.exit(f"Set {names} (a dedicated integration user).") + sys.exit(f"Set {names}.") diff --git a/examples/alert_webhook_receiver.py b/examples/alert_webhook_receiver.py index 8e41602..d0d871c 100644 --- a/examples/alert_webhook_receiver.py +++ b/examples/alert_webhook_receiver.py @@ -1,6 +1,6 @@ """A dependency-free First Alert webhook receiver (standard library plus this SDK). - IC_ALERT_WEBHOOK_TOKEN=<32+ random characters> IC_DATA_EMAIL=... IC_DATA_PASSWORD=... \ + IC_ALERT_WEBHOOK_TOKEN=<32+ random characters> IC_USER_EMAIL=... IC_USER_PASSWORD=... \ python alert_webhook_receiver.py [port] Make a token with: python -c "import secrets; print(secrets.token_urlsafe(32))" @@ -80,7 +80,7 @@ def worker(fetch: bool): client = None if fetch: from _common import client_from_env - client = client_from_env("data") + client = client_from_env("user") while True: alert_id = alert_ids.get() if client is not None: diff --git a/examples/create_customer.py b/examples/create_customer.py index 629b926..12383c9 100644 --- a/examples/create_customer.py +++ b/examples/create_customer.py @@ -25,7 +25,7 @@ def phrases(env_name): threat, upset = phrases("IC_THREAT_PHRASES_FILE"), phrases("IC_UPSET_PHRASES_FILE") spec = CustomerSpec( company_id=os.environ.get("IC_COMPANY_ID") or None, # store customer.company_id after the first run - company_name="Riverbend Dental", + company_name="Riverbend Auto Group", admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"), team=TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", country="US", zipcode="62701", vertical=os.environ.get("IC_VERTICAL", "")), diff --git a/examples/my_day.py b/examples/my_day.py index d6f95a0..9686e4b 100644 --- a/examples/my_day.py +++ b/examples/my_day.py @@ -1,6 +1,6 @@ """A person's day: today's calls, open tasks and alerts. The person's own login. - IC_DATA_EMAIL=... IC_DATA_PASSWORD=... python my_day.py + IC_USER_EMAIL=... IC_USER_PASSWORD=... python my_day.py Caller numbers are shown as their last four digits. Printing a brief shows only its id and time, so this script prints the fields it means to show and writes nothing to logs. @@ -8,7 +8,7 @@ from _common import client_from_env from intelligence_cloud import WrongLoginError -with client_from_env("data") as client: +with client_from_env("user") as client: conv = client.conversations try: me = conv.me() diff --git a/examples/webhook_receiver.py b/examples/webhook_receiver.py index 5a27488..59d3579 100644 --- a/examples/webhook_receiver.py +++ b/examples/webhook_receiver.py @@ -1,6 +1,6 @@ """A dependency-free After Call webhook receiver (standard library plus this SDK). - IC_WEBHOOK_TOKEN=<32+ random characters> IC_DATA_EMAIL=... IC_DATA_PASSWORD=... \ + IC_WEBHOOK_TOKEN=<32+ random characters> IC_USER_EMAIL=... IC_USER_PASSWORD=... \ python webhook_receiver.py [port] Make a token with: python -c "import secrets; print(secrets.token_urlsafe(32))" @@ -10,12 +10,15 @@ - The path token is compared in constant time; a wrong token gets 404. - Bodies over 256 KB get 413; a body that is not JSON, or a malformed After Call event, gets 400. Event types this SDK doesn't handle get 204 and are ignored. -- Each event's call id is written to a persistent queue (SQLite, keyed on call.id) BEFORE the - delivery is acknowledged, so nothing is lost on restart and repeats collapse into one entry. -- A worker reads each queued call with the frontline integration user (the event is only a - notification) and then upserts your copy on call.id. A 404 means drop it. - -Pass --self-test to post the sample event to itself twice, without reading the API, and exit. +- A delivery is stored by its call id (upsert_key) in a persistent queue (SQLite) BEFORE it is + acknowledged, so nothing is lost on restart. A later delivery for the same call can carry newer data: + it replaces the stored entry and re-opens it. Only an exact re-delivery (same call, same content) is + skipped, which the Deduplicator recognises. Its default store is per process: with several workers, + pass Deduplicator(store=...) a shared store, or rely on the queue's upsert alone. +- A worker reads each queued call with the person's login (the event is only a notification) and then + upserts your copy on call.id. A 404 means drop it. + +Pass --self-test to post the sample event twice and then a changed copy, without reading the API, and exit. """ import hmac import json @@ -33,6 +36,7 @@ from intelligence_cloud import ( MAX_EVENT_BYTES, AfterCallEvent, + Deduplicator, NotFoundError, PayloadTooLargeError, WebhookPayloadError, @@ -51,7 +55,7 @@ class CallQueue: - """A persistent queue of call ids. A repeat delivery of a queued call id is one entry.""" + """A persistent queue keyed on call id: a later delivery for a call replaces its entry.""" def __init__(self, path: str): self._db = sqlite3.connect(path, check_same_thread=False, isolation_level=None) @@ -79,6 +83,7 @@ def pending(self) -> int: calls = CallQueue(QUEUE_PATH) +dedup = Deduplicator() # per process; pass store= when several workers receive class Handler(BaseHTTPRequestHandler): @@ -102,8 +107,11 @@ def do_POST(self): return self._answer(413) except WebhookPayloadError: return self._answer(400) - if isinstance(event, AfterCallEvent): - calls.put(event.call.id) # stored before the acknowledgement + if isinstance(event, AfterCallEvent) and not event.is_test: + if dedup.is_duplicate(event): + print(f"call {dedup.upsert_key(event)}: exact re-delivery, skipped") + else: + calls.put(dedup.upsert_key(event)) # upsert by call id, before the acknowledgement return self._answer(204) def log_message(self, *args): # don't log request lines: the path holds the secret token @@ -114,7 +122,7 @@ def worker(fetch: bool) -> None: client = None if fetch: from _common import client_from_env - client = client_from_env("data") + client = client_from_env("user") while True: call_id = calls.next() if call_id is None: @@ -139,10 +147,16 @@ def worker(fetch: bool) -> None: threading.Thread(target=server.serve_forever, daemon=True).start() if SELF_TEST: url = f"http://127.0.0.1:{PORT}/ic/after-call/{TOKEN}" - body = SAMPLE.read_bytes() - for _ in range(2): # the second delivery is a repeat of the same call id: one queue entry - req = urllib.request.Request(url, data=body, method="POST", headers={"Content-Type": "application/json"}) + sample = json.loads(SAMPLE.read_bytes()) + sample["is_test"] = False + newer = json.loads(json.dumps(sample)) + newer["summary"]["text"] = "The refund was approved." + # the same delivery twice (the second is skipped), then newer data for the same call (stored again) + for body in (sample, sample, newer): + req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", + headers={"Content-Type": "application/json"}) print("delivery answered", urllib.request.urlopen(req).status) + time.sleep(0.3) while calls.pending(): time.sleep(0.1) server.shutdown() diff --git a/pyproject.toml b/pyproject.toml index 9567bd1..147d180 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "intelligence-cloud" -version = "0.2.0" +version = "0.3.0" description = "Python client for the Intelligence Cloud partner API: customer lifecycle and conversation intelligence." readme = "README.md" requires-python = ">=3.10" @@ -19,8 +19,14 @@ classifiers = [ ] [project.urls] -Homepage = "https://docs.intelligence.cloud" -Documentation = "https://docs.intelligence.cloud/api" +Homepage = "https://docs.intelligence.cloud/sdk/" +Documentation = "https://docs.intelligence.cloud/sdk/reference" +"Quick start" = "https://docs.intelligence.cloud/sdk/quick-start" +Configuration = "https://docs.intelligence.cloud/sdk/configuration" +Events = "https://docs.intelligence.cloud/sdk/events" +Changelog = "https://docs.intelligence.cloud/sdk/downloads" +"API guide" = "https://docs.intelligence.cloud/api" +"API reference" = "https://docs.intelligence.cloud/reference" Source = "https://github.com/tresic-cloud/intelligence-cloud-sdk-python" [tool.hatch.build.targets.wheel] diff --git a/src/intelligence_cloud/_version.py b/src/intelligence_cloud/_version.py index d3ec452..493f741 100644 --- a/src/intelligence_cloud/_version.py +++ b/src/intelligence_cloud/_version.py @@ -1 +1 @@ -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index 0431ac9..80e0a0c 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -82,6 +82,7 @@ class Client: ``client.conversations`` a user login. ``mask_numbers=False`` shows caller numbers in full in ``client.conversations`` (by default only their last four digits are shown). ``app_url`` is the app's address for call and alert page links (default https://app.intelligence.cloud). + Options, retries and errors: https://docs.intelligence.cloud/sdk/configuration >>> client = Client(email="integration@example.com", password="...") >>> client.intelligence.whoami()["role"] diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index 0b3c83d..d8f6954 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -5,7 +5,7 @@ ``client.intelligence.get_call(event.call.id)`` before you write it anywhere. The same call can arrive again, and a later delivery can carry newer data: store by call id (``upsert_key``) and upsert, so the later delivery replaces the earlier one. Event types you don't handle come back as -:class:`UnknownEvent`: answer 2xx and ignore them. +:class:`UnknownEvent`: answer 2xx and ignore them. See https://docs.intelligence.cloud/sdk/events """ from __future__ import annotations diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py index 6fd72e1..3865774 100644 --- a/tests/unit/test_policy.py +++ b/tests/unit/test_policy.py @@ -150,7 +150,7 @@ def _bad_calls(c): lambda: acc.move_user("company-1", "u1", from_team="t", to_team="t"), lambda: acc.change_line("company-1", "u1", "2101", "2101"), lambda: acc.remove_user("company-1", ""), - lambda: acc.list_members("company-1", license="seat-holder"), + lambda: acc.list_members("company-1", license="everyone"), lambda: acc.send_invitations("company-1", user_ids="u1"), # type: ignore[arg-type] lambda: acc.activate_alerts(""), lambda: acc.offboard_customer(None), # type: ignore[arg-type] diff --git a/tests/unit/test_request_counts.py b/tests/unit/test_request_counts.py new file mode 100644 index 0000000..26c4367 --- /dev/null +++ b/tests/unit/test_request_counts.py @@ -0,0 +1,80 @@ +"""Pins how many requests the common helpers make, measured against the fake (sign-in not counted). +The README's "How many requests" table quotes these numbers: change both together.""" +from __future__ import annotations + +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.testing import FakeAPI + +# helper -> (1-team customer, 10-team customer); each measured with a fresh client, so GET /me is included +EXPECTED = { + "create_customer": (35, 35), + "add_team (each further team)": (None, 21), + "create_customer, re-run": (19, 19), + "add_base_user": (36, 90), + "add_base_manager (every team)": (29, 137), + "activate_alerts": (14, 86), + "calls (one page)": (2, 2), + "brief": (3, 3), +} + + +def _spec(): + return ic.CustomerSpec( + company_name="Riverbend Auto Group", + admin=ic.PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"), + team=ic.TeamSpec("Riverbend - Main", "100 River Rd", "Springfield", "IL", "US", "62701", "service-providers"), + connector=ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend1.example.com", + "example-key"), + mfa_off=True) + + +def measure(teams: int) -> dict: + out = {} + api = FakeAPI() + start = len(api.requests) + cust = api.client(role="admin").accounts.create_customer(_spec()) + out["create_customer"] = len(api.requests) - start + if teams > 1: + start = len(api.requests) + api.client(role="admin").accounts.add_team(cust, ic.TeamSpec( + "Riverbend - Team 2", "101 River Rd", "Springfield", "IL", "US", "62701", "service-providers"), + ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend2.example.com", "example-key")) + out["add_team (each further team)"] = len(api.requests) - start + else: + out["add_team (each further team)"] = None + start = len(api.requests) + api.client(role="admin").accounts.create_customer(ic.CustomerSpec(**{**vars(_spec()), "company_id": cust.company_id})) + out["create_customer, re-run"] = len(api.requests) - start + + api = FakeAPI() + seeded = api.seed_customer(teams=teams) # two Base Users per team and one manager on every team + start = len(api.requests) + api.client(role="admin").accounts.add_base_user(seeded.company_id, ic.PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), + team=seeded.customer.teams[0].location_id, line="2999") + # by company id, as most callers store it: the layout is read first + out["add_base_user"] = len(api.requests) - start + start = len(api.requests) + api.client(role="admin").accounts.add_base_manager(seeded.customer, ic.PersonSpec("lee.park@example.com", "Lee", "Park"), + teams=list(seeded.customer.teams), line="2002") + out["add_base_manager (every team)"] = len(api.requests) - start + start = len(api.requests) + api.client(role="admin").accounts.activate_alerts(seeded.customer) + out["activate_alerts"] = len(api.requests) - start + + ids = api.seed_calls(3) + start = len(api.requests) + api.client(role="user").conversations.calls() + out["calls (one page)"] = len(api.requests) - start + start = len(api.requests) + api.client(role="user").conversations.brief(ids[0]) + out["brief"] = len(api.requests) - start + return out + + +@pytest.mark.parametrize("col,teams", [(0, 1), (1, 10)]) +def test_request_counts(col, teams): + got = measure(teams) + want = {k: v[col] for k, v in EXPECTED.items()} + assert got == want diff --git a/tests/unit/test_testing_module.py b/tests/unit/test_testing_module.py index a6f6041..303dc05 100644 --- a/tests/unit/test_testing_module.py +++ b/tests/unit/test_testing_module.py @@ -141,3 +141,17 @@ def test_missing_required_body_field_is_refused(): def test_strictness_can_be_switched_off(): api = FakeAPI(strict=False) assert raw(api).get("/nothing/here").status_code == 501 + + +def test_the_readme_testing_section_runs_as_written(): + import re + from pathlib import Path + readme = (Path(__file__).resolve().parents[2] / "README.md").read_text() + section = readme[readme.index("## Testing your code"):readme.index("## Running helpers from more than one process")] + code = re.search(r"```python\n(.*?)```", section, re.S).group(1) + ns: dict = {} + exec(compile(code, "README.md", "exec"), ns) + tests = [v for k, v in ns.items() if k.startswith("test_")] + assert len(tests) == 3 + for t in tests: + t() From ed0546b4a4cafebab96bb4d98297046fa9ab6747 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 19:01:12 -0700 Subject: [PATCH 04/11] Fix review findings for 0.3.0: renewal, arguments, events, deadline, fake - Token renewal resends a refresh token only after a 429 or a failure that never left (connect, pool, local protocol, unsupported protocol); a 5xx, a timeout after sending or an unreadable answer means sign in - Client(deadline=120, clock=...) bounds one request with its sign-in, renewal, retries and waits; each attempt's httpx phases share timeout - List arguments are read once (generators work); every spec field and argument is type-checked before any request - Deduplicator.seen(event) checks and remember(event) records after the durable write; is_duplicate is removed; a plain id is refused; stores need has() and add(); a BOM no longer turns a body into an id - First Alert ids and app-link ids must be [A-Za-z0-9_-]{1,128}; a non-string top-level alert_id is refused rather than passed over - due accepts only a date or YYYY-MM-DD on every Python version; AccountError.find tolerates a non-exception cause attribute - Testing module: refresh-token reuse ends every session; fail_next for each HTTP and network failure; expire_access_tokens; auth_log; strict mode checks top-level value types, enums, formats and unknown fields; a small documented surface, internals underscored; transport= refused - Examples and README follow check, store, remember; README states the deadline bounds and the strict-mode limits; request counts measured for the 2nd and 10th team Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 +- README.md | 48 +- examples/alert_webhook_receiver.py | 31 +- examples/webhook_receiver.py | 16 +- src/intelligence_cloud/accounts.py | 136 +++-- src/intelligence_cloud/client.py | 94 +++- src/intelligence_cloud/conversations.py | 25 +- src/intelligence_cloud/errors.py | 3 +- src/intelligence_cloud/receiver.py | 103 ++-- src/intelligence_cloud/testing/_fake.py | 660 ++++++++++++++++-------- tests/unit/test_accounts.py | 150 +++--- tests/unit/test_conversations.py | 22 +- tests/unit/test_intelligence.py | 23 +- tests/unit/test_policy.py | 69 ++- tests/unit/test_request_counts.py | 17 +- tests/unit/test_review_030.py | 303 +++++++++++ tests/unit/test_review_fixes.py | 50 +- tests/unit/test_testing_module.py | 2 +- 18 files changed, 1260 insertions(+), 508 deletions(-) create mode 100644 tests/unit/test_review_030.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b61670c..1eeae40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,14 @@ ### What changed for callers - **Bad input never reaches the network.** Every helper of `client.accounts` and `client.conversations` checks its arguments before it signs in or sends anything. A 40-day window, `limit=500` or `alerts(status=...)` raise `InvalidRequestError` with no request made, even with the network down, and cost no sign-in. +- **Token renewal never resends a refresh token that may have been used.** It is sent again only after a 429 or a network failure that provably never left (no connection, no free pooled connection, a request that could not be written); after a 5xx, a timeout after sending or an unreadable answer the client signs in instead. Sending a used refresh token ends every session of the login. +- **`Client(deadline=120)`** bounds one API request, with its sign-in, renewal, retries and waits; when the time left cannot cover the next wait it stops at once (`RateLimitError`, `NetworkError` kind `"timeout"`, or the last 5xx). Each attempt gets at most `timeout` split across httpx's phases. `clock=` replaces the clock in tests. +- **Arguments are read once and type-checked.** A generator passed as `teams`, `user_ids` or `phrases` is read a single time; a value of the wrong type anywhere in a spec or argument raises `InvalidRequestError` before any request. - **One retry policy, written down** (README "Retries"). Network failures and 5xx are now retried on sign-in too, and on token renewal when the request never left. A 429 whose `Retry-After` is longer than the wait limit raises `RateLimitError` at once with `.retry_after` (a sign-in 429 with `Retry-After: 120` used to wait 60 seconds and then fail). User creation keeps retrying with its idempotency key. - **One error tree in every SDK language** (README "Error handling"). `ApiError.server_message` holds the server's text; `.message` stays as an alias. `NetworkError.request_sent` says whether the request left. `AccountError.find(ErrorType)` returns the first error of that type in the cause chain: a clashing line is `AccountError` → `ExtensionMappingError` → `ConflictError`. -- **Events: store by call id and upsert.** A later After Call delivery for the same call can carry newer data. `Deduplicator.is_duplicate(event)` is now True only for an exact re-delivery (same event type, location, call id and canonical-JSON content) and takes an event, a parsed body or raw bytes; it never hides newer data. New `upsert_key(event)` (also `Deduplicator.upsert_key`) returns the call id (or alert id) to store under. The README receiver section and `examples/webhook_receiver.py` follow this. -- **First Alert payload is not final.** `parse_first_alert_event` accepts any non-empty string id (it used to refuse ids that were not UUIDs and lower-cased them); it keeps reading rule, location, call and time from today's shapes, and `raw` holds the whole payload. -- **`intelligence_cloud.testing`**: a supported fake API for your tests and CI. `FakeAPI.client(role="admin" | "user")`, fictional seed data (`seed_customer`, `seed_calls`), failure knobs (`connector_outcome`, `fail_write`, `network_down`, `rate_limit`), a request log, and strict refusal of requests the published spec does not define. README "Testing your code". +- **Events: store by call id and upsert.** A later After Call delivery for the same call can carry newer data. `Deduplicator.seen(event)` only checks whether this exact delivery (same event type, location, call id and canonical-JSON content) was remembered; `Deduplicator.remember(event)` records it and is called after your durable write, so a delivery whose storage failed is processed when it is retried. Both take an event, a parsed body or raw bytes; a plain id is refused. Newer data is never hidden. New `upsert_key(event)` (also `Deduplicator.upsert_key`) returns the call id (or alert id) to store under. The README receiver section and `examples/webhook_receiver.py` follow this. +- **First Alert payload is not final.** `parse_first_alert_event` accepts any id of letters, digits, `-` and `_` up to 128 characters (it used to accept only UUIDs and lower-cased them); the first of `alert_id`, `alert.id`, `id` that is present decides; it keeps reading rule, location, call and time from today's shapes, and `raw` holds the whole payload. +- **`intelligence_cloud.testing`**: a supported fake API for your tests and CI. `FakeAPI.client(role="admin" | "user")`, fictional seed data (`seed_customer`, `seed_calls`), failure knobs (`connector_outcome`, `fail_next` for each HTTP and network failure, `fail_write`, `network_down`, `rate_limit`, `expire_access_tokens`), a request log and `auth_log`, refresh-token reuse that ends every session as on the platform, and strict refusal of requests the published spec does not define, including value types, enums and formats of top-level fields. README "Testing your code" lists the whole supported surface. - Connector waits count the check intervals as well as the clock, so a replaced `sleep` (tests) cannot spin for the whole timeout. - README: "Retries" with worst-case blocking time, "Testing your code", "Running helpers from more than one process", "How many requests" (pinned by a test), the error tree. SDK documentation links now point to the SDK pages (https://docs.intelligence.cloud/sdk/, /sdk/quick-start, /sdk/reference, /sdk/events, /sdk/configuration, /sdk/downloads); API links stay https://docs.intelligence.cloud/api and https://docs.intelligence.cloud/reference. The examples ship in the source distribution, not the wheel, and the README says so. Package metadata links to the SDK pages, with "Changelog" on https://docs.intelligence.cloud/sdk/downloads. - Examples use one fictional customer, Riverbend Auto Group, and the variables `IC_ADMIN_EMAIL` / `IC_ADMIN_PASSWORD` and `IC_USER_EMAIL` / `IC_USER_PASSWORD` (`IC_DATA_*` still read by the examples as a fallback). @@ -22,8 +25,11 @@ | `MfaRequiredError` derived from `IntelligenceCloudError` only | It is an `AuthError` (status 200, code `mfa_required`): an `except AuthError` now catches it | | `ConnectorTimeoutError` was not a `ConnectorError` | It is: an `except ConnectorError` now catches timeouts too (put `except ConnectorTimeoutError` first to tell them apart) | | `FrontlineRequiredError` derived from `IntelligenceCloudError` only | It is a `WrongLoginError` | -| `Deduplicator.is_duplicate(event)` was True for any repeat of a call id | True only for an exact re-delivery; a changed delivery for the same call returns False | -| `parse_first_alert_event` refused non-UUID ids and lower-cased ids | Any non-empty string id, kept as sent | +| `Deduplicator.is_duplicate(event_or_call_id)` checked and recorded in one call, keyed on the call id | Removed, with no alias: `seen(event)` checks, `remember(event)` records after your write. A plain id raises `InvalidRequestError` | +| A custom `DedupStore` needed `add(key) -> bool` | It needs `has(key) -> bool` and `add(key)` | +| No overall time limit | `deadline=120` seconds per API request (sign-in, renewal, retries and waits included); raise it for long Retry-After waits | +| An id inside an app link could be any string | Links carry only ids of letters, digits, `-` and `_`; `reference()` refuses others and briefs with such an id get `link=None` | +| `parse_first_alert_event` refused non-UUID ids and lower-cased ids | Ids of letters, digits, `-` and `_` (at most 128), kept as sent | | A sign-in 429 always waited `login_rate_limit_wait` once | It waits only when `Retry-After` fits in that limit; otherwise raises at once | | Conversation and account helpers signed in before checking arguments | They check first; with a bad argument no request is sent (your mocks may see fewer requests) | diff --git a/README.md b/README.md index 08a613a..f557f33 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ admin = Client(os.environ["IC_ADMIN_EMAIL"], os.environ["IC_ADMIN_PASSWORD"]) data = Client(os.environ["IC_USER_EMAIL"], os.environ["IC_USER_PASSWORD"]) ``` -`Client(email, password, *, base_url="https://app.intelligence.cloud/api/v1", token_store=None, timeout=30, ...)`: email and password first (by position or keyword), everything else by keyword; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. +`Client(email, password, *, base_url="https://app.intelligence.cloud/api/v1", token_store=None, timeout=30, ...)`: email and password first (by position or keyword), everything else by keyword; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"), and `deadline=120` (see "Retries"; `clock=` replaces the clock for tests). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. ### Sign-in, tokens and sign-out @@ -263,13 +263,13 @@ One policy, the same in every SDK: |---|---| | Network failure (no connection, timeout) or 5xx on a read, update, delete, or user create (which carries an idempotency key, reused on every try) | Retries up to `max_retries` (3) times with exponential backoff and jitter: about 0.5, 1 and 2 seconds plus up to half again | | The same on sign-in | Retried the same way | -| The same on token renewal | 5xx retried; a network failure retried only when the request never left (a refresh token is used once and must never be sent twice) | +| Token renewal | The refresh token is sent again **only** after a 429 (the server did not use it) or after a network failure that provably never left this machine (no connection made, no free connection in the pool, a request that could not be written). Any other outcome (a 5xx, a timeout after the request left, an unreadable answer) may have used it: it is never resent, and the client signs in instead. Sending a used refresh token ends every session of that login | | Network failure or 5xx on any other create | Not retried: the error is raised, so nothing is created twice | | 429 with `Retry-After` within the limit (60 s; for sign-in, `login_rate_limit_wait`, default 60 s) | Waits `Retry-After` (backoff when absent), then retries; sign-in waits once | | 429 with `Retry-After` above the limit | Raises `RateLimitError` at once with `.retry_after` set; it never waits first and then fails | | 401 on a request | Renews the token once and retries | -Worst case with the defaults (`timeout=30`, `max_retries=3`), one call can block for about: **2 minutes 5 seconds** when the network fails every try (4 tries × 30 s timeout + about 5 s of backoff); **3 minutes** when every try answers 429 with `Retry-After: 60` (3 waits of 60 s); and **1 minute** more on the first call if sign-in answers 429 within `login_rate_limit_wait`. Inside a web request, pass `login_rate_limit_wait=0`, a smaller `timeout` and `max_retries=1`. +**Bounds.** One API request, including the sign-in or token renewal it needs and every retry and wait, never runs past **`deadline`** (default **120 seconds**). When the time left cannot cover the next wait, the client stops at once: `RateLimitError` (with `.retry_after`) after a 429, `NetworkError` with `kind` `"timeout"` after network failures, or the last 5xx as an `ApiError`. Each attempt gets at most `timeout` (30 s) or the time left, whichever is less, split across httpx's phases (connect 20%, write 20%, read 50%, pool 10%); a response that keeps sending bytes slowly can still outlast `timeout`, because httpx times the gap between reads, not the whole read, but never the deadline beyond one such gap. Helpers that make many requests (`create_customer`) apply the deadline to each request. Connector settle waits are not counted: they have their own `timeout` (600 s). Inside a web request, pass a smaller `deadline` (for example 10), `login_rate_limit_wait=0` and `max_retries=1`. ## Error handling @@ -336,8 +336,8 @@ admin.intelligence.test_first_alert_webhook(location_id) - `parse_after_call_event` refuses bodies over 256 KB (`PayloadTooLargeError`: answer 413) and returns `UnknownEvent` for event types it doesn't handle: answer 2xx and ignore them. Answer 400 only for a body that isn't JSON or a malformed After Call event, and 404 for a wrong token. - Treat an event as a notification. Before you write anything from it into another system, read the call with `get_call(event.call.id)` using your frontline integration user; a `NotFoundError` means drop the event. - **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsert_key(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before. -- `Deduplicator.is_duplicate(event)` is True only for an **exact re-delivery**: the same event type, location and call id and the same content (a SHA-256 of the canonical JSON body, because the payload carries no version marker). A later delivery with newer data is not a duplicate. It takes an event, a parsed body or the raw bytes. Use it to skip repeat work, never to skip an update. -- Its default store is **in memory and per process**: with more than one worker or process it misses repeats the others saw. Pass a shared store whose `add(key)` returns True only for a new key, for example `Deduplicator(store=RedisStore(redis_client))` where `RedisStore.add` is `return bool(r.set("ic:" + key, 1, nx=True, ex=86400))`. +- **Check, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse → if `seen(event)`: answer 2xx → upsert under `upsert_key(event)` → `remember(event)` → answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. An exact re-delivery is the same event type, location and call id with the same content (a SHA-256 of the canonical JSON body, because the payload carries no version marker); a later delivery with newer data is not seen. It takes an event, a parsed body or the raw bytes; a plain id is refused, because an id alone cannot tell newer data apart. +- Its default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)`, for example `Deduplicator(store=RedisStore(r))` where `has` is `return bool(r.exists("ic:" + key))` and `add` is `r.set("ic:" + key, 1, ex=86400)`. - To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test` (from the source distribution). FastAPI: @@ -366,9 +366,14 @@ async def after_call(token: str, request: Request, background: BackgroundTasks): raise HTTPException(status_code=413) except WebhookPayloadError: raise HTTPException(status_code=400) - if isinstance(event, AfterCallEvent) and not event.is_test and not dedup.is_duplicate(event): + if not isinstance(event, AfterCallEvent) or event.is_test or dedup.seen(event): + return {"ok": True} # other types, tests and exact re-deliveries + try: store.upsert(upsert_key(event), event.raw) # durable, keyed on the call id: newer data replaces older - background.add_task(handle, upsert_key(event)) # read the call with get_call, then upsert your copy + except StorageError: + raise HTTPException(status_code=503) # not remembered: the sender's retry is processed + dedup.remember(event) # only after the write + background.add_task(handle, upsert_key(event)) # read the call with get_call, then upsert your copy return {"ok": True} ``` @@ -398,11 +403,11 @@ def after_call(token): return {"ok": True} ``` -`is_duplicate` has the same name and meaning in all three SDKs (`isDuplicate` in PHP and TypeScript). The in-memory store keeps the last 10,000 delivery keys. +`seen` and `remember` have the same names and meaning in all three SDKs. The in-memory store keeps the last 10,000 delivery keys. ### Receive First Alert -The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. **The First Alert payload is not final yet.** `parse_first_alert_event` returns a `FirstAlertEvent`: `alert_id` (any non-empty string under `alert_id`, `alert.id` or `id`), and `rule`, `location_id`, `call_id` and `timestamp` when the delivery carries them in the shapes known today; `raw` holds the whole payload. Take the alert id, answer 2xx at once, then fetch the alert and its call with a login in every alert group: +The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. **The First Alert payload is not final yet.** `parse_first_alert_event` returns a `FirstAlertEvent`: `alert_id` (letters, digits, `-` and `_`, at most 128 characters, under `alert_id`, else `alert.id`, else `id`; the first present decides, and anything else is refused), and `rule`, `location_id`, `call_id` and `timestamp` when the delivery carries them in the shapes known today; `raw` holds the whole payload. Take the alert id, answer 2xx at once, then fetch the alert and its call with a login in every alert group: ```python @app.post("/ic/alerts/{token}") @@ -410,13 +415,15 @@ async def first_alert(token: str, request: Request, background: BackgroundTasks) if not hmac.compare_digest(token.encode(), ALERT_TOKEN.encode()): # IC_ALERT_WEBHOOK_TOKEN, 32+ characters raise HTTPException(status_code=404) try: - alert_id = parse_first_alert_event(await request.body()).alert_id + event = parse_first_alert_event(await request.body()) except PayloadTooLargeError: raise HTTPException(status_code=413) except WebhookPayloadError: raise HTTPException(status_code=400) - if not alert_dedup.is_duplicate(alert_id): # a bare alert id is an exact key: alerts do not change - background.add_task(handle_alert, alert_id) + if not alert_dedup.seen(event): + alert_queue.put(event.alert_id) # durable + alert_dedup.remember(event) # after the write + background.add_task(handle_alert, event.alert_id) return {"ok": True} def handle_alert(alert_id: str): @@ -429,8 +436,9 @@ If your receiver was unavailable, read the window you missed once and skip alert ```python for alert in data.intelligence.iter_alerts(date_from=went_down - timedelta(minutes=30), date_to=came_back): - if not alert_dedup.is_duplicate(alert["id"]): + if alert["id"] not in handled: # your own store of handled alert ids handle_alert(alert["id"]) + handled.add(alert["id"]) ``` Alerts are dated by their call, so start the window 30 minutes before the receiver went down. @@ -482,11 +490,14 @@ def test_resumes_after_a_stop(): | `seed_customer(*, teams=1, people=True)` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `company_id`, `base_users`, `managers`) | | `seed_calls(n=3, *, location_id=None, day=None, alerts=True, tasks=True)` | Fictional calls with details, tasks and alerts (555-01xx numbers). Returns the call ids, newest first | | `connector_outcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connectors created from now on | -| `fail_write(nth=1, status=400)`, `network_down(down=True)`, `rate_limit(count=1, retry_after=1)` | Failures your code must handle | -| `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()` | The request log (sign-in not included) | +| `fail_next(status=None, *, network=None, method=None, path=None, retry_after=None)` | The next matching request fails once: an HTTP status, or `network="connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"undecodable"`. A renewal that fails any way but "connect" has used its token | +| `fail_write(nth=1, status=400)`, `network_down(down=True)`, `rate_limit(count=1, retry_after=1)`, `expire_access_tokens()` | Simpler knobs: the nth write fails; no network; 429s; every access token expires (the next call renews) | +| `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()`, `auth_log` | The request log (sign-in and renewal are in `auth_log`: "login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) | | `products(uid, lid)`, `numbers(uid, connector_id=None)`, `fa_numbers(lid)`, `ih_numbers(lid)`, `group_members(lid, name)` | State to assert on | -With `strict=True` the fake refuses what the published spec does not define, with the API's error shape: an unknown path or method (404), an unknown query parameter (400), a body missing a required field (422). It checks paths, methods, query names and top-level required body fields; it does not check value formats or nested fields, and its data is simpler than the platform's (for example search matching). Code that passes against it still needs one run against a test company before release. +That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore and may change. `client(transport=...)` is refused. + +**Strict mode** (`strict=True`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type (whole number, true/false), outside its enum or range, or not in its format (uuid, date-time) (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states (for example the spec gives no list of user roles). Code that passes against it still needs one run against a test company before release. ## Running helpers from more than one process @@ -520,7 +531,8 @@ Measured against `intelligence_cloud.testing` with a fresh client (one `GET /me` | Helper | 1-team customer | 10-team customer | |---|---|---| -| `create_customer` (first run, one team) | 35 | 35, plus 21 for each `add_team` (224 in all) | +| `create_customer` (first run, one team) | 35 | 35 | +| `add_team` (the 2nd team; the 10th team) | n/a | 21; 21 (224 for all ten teams) | | `create_customer`, re-run | 19 | 19 | | `add_base_user` (customer passed as a company id) | 36 | 90 | | `add_base_manager` (on every team) | 29 | 137 | @@ -528,7 +540,7 @@ Measured against `intelligence_cloud.testing` with a fresh client (one `GET /me` | `calls` (one page) | 2 | 2 | | `brief` | 3 | 3 | -The counts assume two Base Users per team and one manager. At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. +The counts assume two Base Users per team and one manager, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. ## Examples diff --git a/examples/alert_webhook_receiver.py b/examples/alert_webhook_receiver.py index d0d871c..a2b978a 100644 --- a/examples/alert_webhook_receiver.py +++ b/examples/alert_webhook_receiver.py @@ -20,11 +20,9 @@ import sys import threading import urllib.request -import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from typing import Optional -from intelligence_cloud import Deduplicator +from intelligence_cloud import Deduplicator, WebhookPayloadError, parse_first_alert_event SELF_TEST = "--self-test" in sys.argv TOKEN = os.environ.get("IC_ALERT_WEBHOOK_TOKEN") or (secrets.token_urlsafe(32) if SELF_TEST else "") @@ -37,22 +35,12 @@ dedup = Deduplicator() -def alert_id_from(body: bytes) -> Optional[str]: - """The alert id from a First Alert delivery, or None. Reads nothing else from the request.""" +def event_from(body: bytes): + """The First Alert event, or None when the body has no valid alert id. The payload is not final.""" try: - data = json.loads(body) - except ValueError: + return parse_first_alert_event(body) + except WebhookPayloadError: return None - if not isinstance(data, dict): - return None - nested = data.get("alert") if isinstance(data.get("alert"), dict) else {} - for value in (data.get("alert_id"), nested.get("id"), data.get("id")): - if isinstance(value, str): - try: - return str(uuid.UUID(value.strip())) - except ValueError: - continue - return None class Handler(BaseHTTPRequestHandler): @@ -62,13 +50,14 @@ def do_POST(self): self.end_headers() return length = int(self.headers.get("Content-Length") or 0) - alert_id = alert_id_from(self.rfile.read(length)) if 0 < length <= MAX_BODY else None - if alert_id is None: + event = event_from(self.rfile.read(length)) if 0 < length <= MAX_BODY else None + if event is None: self.send_response(400) self.end_headers() return - if not dedup.is_duplicate(alert_id): - alert_ids.put(alert_id) + if not dedup.seen(event): + alert_ids.put(event.alert_id) # an in-memory queue here; use a durable one in production + dedup.remember(event) # after the write self.send_response(204) self.end_headers() diff --git a/examples/webhook_receiver.py b/examples/webhook_receiver.py index 59d3579..99ac195 100644 --- a/examples/webhook_receiver.py +++ b/examples/webhook_receiver.py @@ -13,8 +13,10 @@ - A delivery is stored by its call id (upsert_key) in a persistent queue (SQLite) BEFORE it is acknowledged, so nothing is lost on restart. A later delivery for the same call can carry newer data: it replaces the stored entry and re-opens it. Only an exact re-delivery (same call, same content) is - skipped, which the Deduplicator recognises. Its default store is per process: with several workers, - pass Deduplicator(store=...) a shared store, or rely on the queue's upsert alone. + skipped: the Deduplicator checks with seen(event) and is told remember(event) only after the queue + write succeeded, so a delivery whose write failed (answered 503) is processed when it is retried. + Its default store is per process: with several workers pass Deduplicator(store=...) a shared store + (has/add), or rely on the queue's upsert alone. - A worker reads each queued call with the person's login (the event is only a notification) and then upserts your copy on call.id. A 404 means drop it. @@ -108,10 +110,14 @@ def do_POST(self): except WebhookPayloadError: return self._answer(400) if isinstance(event, AfterCallEvent) and not event.is_test: - if dedup.is_duplicate(event): + if dedup.seen(event): # an exact re-delivery we already stored print(f"call {dedup.upsert_key(event)}: exact re-delivery, skipped") - else: - calls.put(dedup.upsert_key(event)) # upsert by call id, before the acknowledgement + return self._answer(204) + try: + calls.put(dedup.upsert_key(event)) # upsert by call id: the durable write + except sqlite3.Error: + return self._answer(503) # not remembered: the sender's retry is processed + dedup.remember(event) # only after the write succeeded return self._answer(204) def log_message(self, *args): # don't log request lines: the path holds the secret token diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index f5f4227..a6bc880 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -274,37 +274,61 @@ def _uniq(values: Iterable[str]) -> List[str]: def _line(value: Any, name: str = "line") -> str: - v = str(value).strip() if value is not None else "" - if not v: + return _str(value, name) + + +def _str(value: Any, name: str, required: bool = True) -> Optional[str]: + """A string argument: refused (InvalidRequestError, before any request) when it is not a string, or + empty when required. Returns it stripped, or None when it is optional and absent.""" + if value is None and not required: + return None + if not isinstance(value, str): + raise InvalidRequestError(f"{name}: a string" + ("" if required else " or None")) + v = value.strip() + if required and not v: raise InvalidRequestError(f"{name} is required") return v -def _check_setting(key: str, s: Optional[AlertSetting]) -> None: +def _list(value: Any, name: str) -> List[Any]: + """A list argument, materialised once (a generator is read a single time).""" + if value is None or isinstance(value, (str, bytes, Team, Mapping)): + raise InvalidRequestError(f"{name}: a list") + try: + return list(value) + except TypeError: + raise InvalidRequestError(f"{name}: a list") from None + + +def _check_setting(key: str, s: Optional[AlertSetting]) -> Optional[AlertSetting]: + """The setting checked and copied, with ``phrases`` as a list read once.""" if s is None: - return + return None if not isinstance(s, AlertSetting): raise InvalidRequestError(f"alerts.{key} must be an AlertSetting") if s.sentiment_below is not None: lvl = s.sentiment_below if isinstance(lvl, bool) or not isinstance(lvl, int) or not -100 <= lvl <= -1: raise InvalidRequestError(f"alerts.{key}.sentiment_below: a whole number from -100 to -1") + phrases = None if s.phrases is not None: if not RULES[key].has_phrases: raise InvalidRequestError(f"alerts.{key} has no phrases; set sentiment_below only") - if isinstance(s.phrases, str) or not all(isinstance(p, str) for p in s.phrases): + phrases = _list(s.phrases, f"alerts.{key}.phrases") + if not all(isinstance(p, str) for p in phrases): raise InvalidRequestError(f"alerts.{key}.phrases must be a list of strings") - if not [p for p in s.phrases if p.strip()]: + if not [p for p in phrases if p.strip()]: raise InvalidRequestError(f"alerts.{key}.phrases is empty; pass None to keep the current phrases") + return AlertSetting(phrases=phrases, sentiment_below=s.sentiment_below) -def _check_alerts(alerts: Optional[AlertSettings]) -> None: +def _check_alerts(alerts: Optional[AlertSettings]) -> Optional[AlertSettings]: + """The settings checked and copied (lists read once).""" if alerts is None: - return + return None if not isinstance(alerts, AlertSettings): raise InvalidRequestError("alerts must be an AlertSettings") - for key in RULES: - _check_setting(key, getattr(alerts, key)) + return AlertSettings(**{key: _check_setting(key, getattr(alerts, key)) for key in RULES}) def _clean_phrases(phrases: Optional[List[str]]) -> Optional[List[str]]: @@ -549,14 +573,17 @@ def create_customer(self, spec: CustomerSpec) -> Customer: c = self._c if not isinstance(spec, CustomerSpec): raise InvalidRequestError("spec must be a CustomerSpec") - if not (spec.company_name or "").strip(): - raise InvalidRequestError("company_name is required") + _str(spec.company_name, "company_name") _check_person(spec.admin) - if not (spec.admin.phone_number or "").strip(): - raise InvalidRequestError("admin.phone_number is required for the primary contact") + _str(spec.admin.phone_number, "admin.phone_number") _check_team_spec(spec.team) - _check_alerts(spec.alerts) + alerts = _check_alerts(spec.alerts) _check_connector_local(spec.connector) + for f in ("reseller_id", "company_code", "company_id", "sso_domain"): + _str(getattr(spec, f), f, required=False) + for f in ("mfa_off", "reactivate"): + if not isinstance(getattr(spec, f), bool): + raise InvalidRequestError(f"{f}: True or False") if spec.team.name == spec.company_name + MANAGEMENT_SUFFIX: raise InvalidRequestError(f"{spec.team.name!r} is the Management location; name the team differently") me = self._require_admin() @@ -633,7 +660,7 @@ def create_customer(self, spec: CustomerSpec) -> Customer: self._ensure_groups(mgmt, result) run.step = "rules" - settings = self._settings_from(spec.alerts) + settings = self._settings_from(alerts) self._ensure_rules(team, settings, result) run.step = "insights_hub" @@ -863,7 +890,7 @@ def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSp _check_customer_ref(customer) _check_team_spec(team) _check_connector_local(connector, required=True) - _check_alerts(alerts) + alerts = _check_alerts(alerts) self._require_admin() self._check_connector(connector, required=True) cust = self._resolve(customer) @@ -917,7 +944,11 @@ def set_alerts(self, customer: CustomerRef, alerts: AlertSettings, *, team: Opti _check_team_ref(team, required=False) if alerts is None: raise InvalidRequestError("alerts is required") - _check_alerts(alerts) + alerts = _check_alerts(alerts) + if all(getattr(alerts, k) is None for k in RULES): + raise InvalidRequestError("alerts sets nothing: give at least one AlertSetting") + if isinstance(customer, Customer) and team is not None: + self._team(customer, team) self._require_admin() cust = self._resolve(customer) teams = self._teams(cust, team) @@ -941,6 +972,8 @@ def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, _check_customer_ref(customer) _check_team_ref(team, required=False) _check_connector_local(connector, required=True) + if isinstance(customer, Customer) and team is not None: + self._team(customer, team) self._require_admin() self._check_connector(connector, required=True) cust = self._resolve(customer) @@ -985,6 +1018,8 @@ def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = No Returns ``{"switched_on": [rule ids], "no_manager": [{"location_id", "team", "missing"}]}``.""" _check_customer_ref(customer) _check_team_ref(team, required=False) + if isinstance(customer, Customer) and team is not None: + self._team(customer, team) self._require_admin() cust = self._resolve(customer) out: Dict[str, Any] = {"switched_on": [], "no_manager": []} @@ -1172,6 +1207,8 @@ def list_members(self, customer: CustomerRef, *, license: Optional[str] = None, _check_team_ref(team, required=False) if license is not None and license not in LICENSES: raise InvalidRequestError(f"license: one of {list(LICENSES)}") + if isinstance(customer, Customer) and team is not None: + self._team(customer, team) self._require_admin() cust = self._resolve(customer) lid = self._team(cust, team).location_id if team is not None else None @@ -1386,6 +1423,9 @@ def add_base_user(self, customer: CustomerRef, person: PersonSpec, *, team: Team _check_person(person) _check_team_ref(team) line = _line(line) + _check_invite(invite) + if isinstance(customer, Customer): + self._team(customer, team) self._require_admin() cust = self._resolve(customer) t = self._team(cust, team) @@ -1421,11 +1461,17 @@ def add_base_manager(self, customer: CustomerRef, person: PersonSpec, *, teams: group with ``company_reports=True``); alert email off. The invitation is sent last.""" _check_customer_ref(customer) _check_person(person) - if isinstance(teams, (str, Team)) or not teams: + teams = _list(teams, "teams") + if not teams: raise InvalidRequestError("teams: a list of one or more teams") for x in teams: _check_team_ref(x) own = _line(line) if line is not None else None + _check_invite(invite) + _check_bool(company_reports, "company_reports") + if isinstance(customer, Customer): + for x in teams: + self._team(customer, x) self._require_admin() cust = self._resolve(customer) ts = _dedupe_teams([self._team(cust, x) for x in teams]) @@ -1459,6 +1505,7 @@ def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, inv _check_person(person) if person.auth_method != "password": raise InvalidRequestError("An integration user signs in with a password: set auth_method='password'") + _check_invite(invite) self._require_admin() cust = self._resolve(customer) if not cust.teams: @@ -1517,10 +1564,14 @@ def change_license(self, customer: CustomerRef, user_id: str, to: str, *, if to not in ("base_user", "base_manager"): raise InvalidRequestError('to: "base_user" or "base_manager"') if teams is not None: - if isinstance(teams, (str, Team)) or not teams: + teams = _list(teams, "teams") + if not teams: raise InvalidRequestError("teams: a list of one or more teams") for x in teams: _check_team_ref(x) + if isinstance(customer, Customer): + for x in teams: + self._team(customer, x) if line is not None: _line(line) self._require_admin() @@ -1638,8 +1689,12 @@ def move_user(self, customer: CustomerRef, user_id: str, *, from_team: TeamRef, _check_user_id(user_id) _check_team_ref(from_team) _check_team_ref(to_team) - if isinstance(from_team, str) and from_team == to_team: + if (from_team.location_id if isinstance(from_team, Team) else from_team) == \ + (to_team.location_id if isinstance(to_team, Team) else to_team): raise InvalidRequestError("from_team and to_team are the same team") + if isinstance(customer, Customer): + if self._team(customer, from_team).location_id == self._team(customer, to_team).location_id: + raise InvalidRequestError("from_team and to_team are the same team") self._require_admin() cust = self._resolve(customer) src, dst = self._team(cust, from_team), self._team(cust, to_team) @@ -1794,6 +1849,7 @@ def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = team whose alert groups are left with no Base Manager (its alerts are not changed).""" _check_customer_ref(customer) _check_user_id(user_id) + _check_bool(keep_lines, "keep_lines") self._require_admin() cust = self._resolve(customer) p, people = self._person(cust, user_id, include_inactive=True) @@ -1835,8 +1891,7 @@ def send_invitations(self, customer: CustomerRef, *, user_ids: Optional[Sequence have not signed in. Returns the ids invited.""" _check_customer_ref(customer) if user_ids is not None: - if isinstance(user_ids, str): - raise InvalidRequestError("user_ids: a list of user ids") + user_ids = _list(user_ids, "user_ids") for u in user_ids: _check_user_id(u) self._require_admin() @@ -1875,6 +1930,7 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st Returns ``{"teams": {location_id: {"team", "lines", "other", "first_alert", "insights_hub", "holders"}}, "applied"}``.""" _check_customer_ref(customer) + _check_bool(dry_run, "dry_run") self._require_admin() cust = self._resolve(customer) people = self._index(cust) @@ -1927,6 +1983,7 @@ def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = webhook, stop each connector (ends the phone-system subscription), deactivate the integration users, then deactivate the company. Ask your Tresic contact about retention of the customer's data.""" _check_customer_ref(customer) + _check_bool(deactivate_company, "deactivate_company") self._require_admin() cust = self._resolve(customer) c = self._c @@ -2003,12 +2060,19 @@ def _check_connector_local(cs: Optional[ConnectorSpec], required: bool = False) return if not isinstance(cs, ConnectorSpec): raise InvalidRequestError("connector must be a ConnectorSpec") - if not isinstance(cs.type, str) or not cs.type.strip(): - raise InvalidRequestError("connector.type is required") + _str(cs.type, "connector.type") + _str(cs.name, "connector.name", required=False) + if isinstance(cs.timeout, bool) or not isinstance(cs.timeout, (int, float)) or cs.timeout < 0: + raise InvalidRequestError("connector.timeout: a number of seconds") + for k in cs.config: + if not isinstance(k, str): + raise InvalidRequestError("connector.config: setting names must be strings") def _check_customer_ref(customer: Any) -> None: if isinstance(customer, Customer): + if not isinstance(customer.company_id, str) or not customer.company_id: + raise InvalidRequestError("customer.company_id is required") return if not isinstance(customer, str) or not customer.strip(): raise InvalidRequestError("customer: a Customer or a company id") @@ -2026,8 +2090,11 @@ def _check_team_ref(team: Any, required: bool = True) -> None: def _check_person(person: Any) -> None: if not isinstance(person, PersonSpec): raise InvalidRequestError("person must be a PersonSpec") - if not (person.email or "").strip() or "@" not in person.email: - raise InvalidRequestError("person.email is required") + if "@" not in _str(person.email, "person.email"): + raise InvalidRequestError("person.email: an email address") + _str(person.first_name, "person.first_name") + _str(person.last_name, "person.last_name") + _str(person.phone_number, "person.phone_number", required=False) if person.auth_method not in ("password", "sso"): raise InvalidRequestError('person.auth_method: "password" or "sso"') @@ -2036,13 +2103,20 @@ def _check_team_spec(team: Any) -> None: if not isinstance(team, TeamSpec): raise InvalidRequestError("team must be a TeamSpec") for f in ("name", "street", "city", "state", "country", "zipcode", "vertical"): - if not str(getattr(team, f) or "").strip(): - raise InvalidRequestError(f"team.{f} is required") + _str(getattr(team, f), f"team.{f}") + + +def _check_bool(value: Any, name: str) -> None: + if not isinstance(value, bool): + raise InvalidRequestError(f"{name}: True or False") + + +def _check_invite(invite: Any) -> None: + _check_bool(invite, "invite") def _check_user_id(user_id: Any) -> None: - if not isinstance(user_id, str) or not user_id.strip(): - raise InvalidRequestError("user_id is required") + _str(user_id, "user_id") def _dedupe_teams(teams: List[Team]) -> List[Team]: diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index 80e0a0c..a4bf8de 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -56,6 +56,19 @@ def check_base_url(base_url: str) -> str: raise InvalidRequestError("base_url must be an https:// URL (http:// only for localhost)") +DEFAULT_DEADLINE = 120.0 +# Failures raised before the request left this machine: the server cannot have acted on them. +NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout, httpx.LocalProtocolError, + httpx.UnsupportedProtocol) + + +def attempt_timeout(seconds: float) -> httpx.Timeout: + """httpx times each phase separately; split ``seconds`` across them so that one attempt stays within + ``seconds`` (a response that keeps sending bytes slowly can still run past it: httpx times the gap + between reads, not the whole read).""" + return httpx.Timeout(connect=seconds * 0.2, write=seconds * 0.2, read=seconds * 0.5, pool=seconds * 0.1) + + def _retry_after_seconds(value: Optional[str]) -> Optional[float]: """Retry-After in seconds, or None when absent or not a number of seconds.""" if not value: @@ -104,6 +117,8 @@ def __init__( keep_unknown_fields: bool = False, mask_numbers: bool = True, app_url: str = DEFAULT_APP_URL, + deadline: float = DEFAULT_DEADLINE, + clock: Callable[[], float] = time.monotonic, ): self.base_url = check_base_url(base_url).rstrip("/") self._email = email @@ -112,6 +127,14 @@ def __init__( self._auth_lock = threading.Lock() self._max_retries = max_retries self._sleep = sleep + self._clock = clock + if not isinstance(deadline, (int, float)) or isinstance(deadline, bool) or deadline <= 0: + raise InvalidRequestError("deadline: a number of seconds above 0") + if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0: + raise InvalidRequestError("timeout: a number of seconds above 0") + self._deadline = float(deadline) + self._timeout = float(timeout) + self._local = threading.local() # the current request's deadline, per thread self._login_wait = max(0.0, float(login_rate_limit_wait)) self.keep_unknown_fields = keep_unknown_fields # client.conversations shows caller numbers as their last four digits unless this is False. @@ -122,7 +145,8 @@ def __init__( ua = f"intelligence-cloud-python/{__version__}" if user_agent: ua = f"{user_agent} {ua}" - self._http = httpx.Client(timeout=timeout, transport=transport, headers={"User-Agent": ua}) + self._http = httpx.Client(timeout=attempt_timeout(self._timeout), transport=transport, + headers={"User-Agent": ua}) self._spent_refresh_tokens: set = set() from .resources import ( @@ -177,7 +201,7 @@ def _store_lock(self) -> ContextManager[Any]: def login(self) -> Dict[str, Any]: """Sign in now and return the signed-in user. The client also signs in by itself on first use.""" - with self._auth_lock, self._store_lock(): + with self._budget(), self._auth_lock, self._store_lock(): return self._login_locked() def logout(self) -> None: @@ -188,7 +212,8 @@ def logout(self) -> None: tokens = self._store.get() if tokens is None: return - resp = self._send_raw("POST", "/auth/logout", op_id="logout", tokens=tokens) + with self._budget(): + resp = self._send_raw("POST", "/auth/logout", op_id="logout", tokens=tokens) self._store.set(None) if resp.status_code >= 400 and resp.status_code != 401: self._raise(resp, "logout") @@ -208,7 +233,8 @@ def _login_locked(self) -> Dict[str, Any]: ra = _retry_after_seconds(resp.headers.get("Retry-After")) if ra is None or ra <= self._login_wait: waited = True - self._sleep(ra if ra is not None else self._login_wait) + if not self._wait(ra if ra is not None else self._login_wait): + break # the deadline cannot cover the wait: RateLimitError below continue break if resp.status_code >= 400: @@ -257,8 +283,10 @@ def _renew(self, stale: Tokens) -> Tokens: def _renew_locked(self, tokens: Tokens) -> None: """Rotate the refresh token. A refresh token is used once. - A 429 means the token was not used: wait and send the same token again (it never turns into a - sign-in, which has a much lower limit). Any other failure: sign in again. + The token may be sent again only after a 429 (the server did not use it), or after a network + failure that provably never left this machine. Anything else (a 5xx, a failure after the + request left, an unreadable response) may have used it: it is never sent again, and the client + signs in instead. Sending a used refresh token ends every session of the login. """ refresh_token = tokens.refresh_token if refresh_token in self._spent_refresh_tokens: @@ -275,9 +303,8 @@ def _renew_locked(self, tokens: Tokens) -> None: if resp is None or resp.status_code != 429: break wait = self._backoff(attempt, resp.headers.get("Retry-After")) - if attempt >= self._max_retries or wait is None: + if attempt >= self._max_retries or wait is None or not self._wait(wait): self._raise(resp, "refresh") - self._sleep(wait) # type: ignore[arg-type] attempt += 1 self._spent_refresh_tokens.add(refresh_token) if resp is not None and resp.status_code == 200: @@ -312,15 +339,18 @@ def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Toke h["Authorization"] = f"Bearer {tokens.access_token}" failed = None sent = True + remaining = self._remaining() + if remaining <= 0: + raise NetworkError("timeout", "deadline reached", request_sent=False) try: - return self._http.request(method, self._url(path), params=params or None, - json=json_body, headers=h) + return self._http.request(method, self._url(path), params=params or None, json=json_body, + headers=h, timeout=attempt_timeout(min(self._timeout, remaining))) except httpx.HTTPError as exc: kind = ("timeout" if isinstance(exc, httpx.TimeoutException) else "transport" if isinstance(exc, httpx.TransportError) else "decoding" if isinstance(exc, httpx.DecodingError) else "transport") failed = (kind, type(exc).__name__) - sent = not isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) + sent = not isinstance(exc, NOT_SENT) # Raised outside the except block so the HTTP library's error, which holds the request, is not kept # on this error as its context. raise NetworkError(*failed, request_sent=sent) @@ -350,7 +380,8 @@ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, except NetworkError as exc: if (exc.kind != "decoding" and idempotent and attempt < self._max_retries and not (only_unsent and exc.request_sent)): - self._sleep(self._backoff(attempt, None) or 0.0) + if not self._wait(self._backoff(attempt, None) or 0.0): + raise NetworkError("timeout", "deadline reached", request_sent=exc.request_sent) from None attempt += 1 continue raise @@ -358,16 +389,42 @@ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, refreshed = True self._renew(tokens) # type: ignore[arg-type] continue - retryable = (resp.status_code == 429 and retry_429) or (resp.status_code >= 500 and idempotent) + # only_unsent (token renewal): a 5xx may come after the server used the request, so never resend + retryable = ((resp.status_code == 429 and retry_429) + or (resp.status_code >= 500 and idempotent and not only_unsent)) if retryable and attempt < self._max_retries: wait = self._backoff(attempt, resp.headers.get("Retry-After")) - if wait is None: - return resp # Retry-After above MAX_RETRY_AFTER: fail now rather than block - self._sleep(wait) + if wait is None or not self._wait(wait): + return resp # Retry-After above the limit, or past the deadline: fail now, never wait first attempt += 1 continue return resp + # ------------------------------------------------------------------ the deadline + + @contextlib.contextmanager + def _budget(self) -> Iterator[None]: + """Start the deadline for one API request, unless one is running (sign-in inside a request).""" + if getattr(self._local, "deadline_at", None) is not None: + yield + return + self._local.deadline_at = self._clock() + self._deadline + try: + yield + finally: + self._local.deadline_at = None + + def _remaining(self) -> float: + at = getattr(self._local, "deadline_at", None) + return float("inf") if at is None else at - self._clock() + + def _wait(self, seconds: float) -> bool: + """Sleep ``seconds`` if the deadline leaves room; otherwise return False without sleeping.""" + if seconds > self._remaining(): + return False + self._sleep(seconds) + return True + @staticmethod def _backoff(attempt: int, retry_after: Optional[str]) -> Optional[float]: # noqa: D401 """Seconds to wait before the next try, or None when Retry-After asks for more than @@ -460,8 +517,9 @@ def _request(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any] op, url_path, params = self._build(op_id, path, query, body) if op["method"] != "GET": self._writes += 1 - resp = self._send_with_retries(op["method"], url_path, op_id=op_id, params=params, - json_body=dict(body) if body is not None else None, headers=headers) + with self._budget(): + resp = self._send_with_retries(op["method"], url_path, op_id=op_id, params=params, + json_body=dict(body) if body is not None else None, headers=headers) if resp.status_code >= 400: self._raise(resp, op_id) return resp diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py index 5319957..e6eee02 100644 --- a/src/intelligence_cloud/conversations.py +++ b/src/intelligence_cloud/conversations.py @@ -21,7 +21,7 @@ from ._spec import is_uuid from .errors import InvalidRequestError, WrongLoginError from .intelligence import RecordingLink, _search_term -from .receiver import FirstAlertEvent, parse_first_alert_event +from .receiver import ID_RE, FirstAlertEvent, parse_first_alert_event MAX_WINDOW_DAYS = 31 MAX_LIMIT = 200 @@ -205,13 +205,20 @@ def _check_team(team: Any) -> None: raise InvalidRequestError("team: a TeamRef, a location id or a team name") +_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + + def _check_due(due: Any) -> None: - if due is None or isinstance(due, date): + """A date or "YYYY-MM-DD", the same on every Python version (3.11 also parses "20261102").""" + if due is None or (isinstance(due, date) and not isinstance(due, datetime)): return - try: - date.fromisoformat(str(due)) - except ValueError: - raise InvalidRequestError("due: a date (YYYY-MM-DD)") from None + if isinstance(due, str) and _DATE_RE.match(due): + try: + date.fromisoformat(due) + return + except ValueError: + pass + raise InvalidRequestError("due: a date (YYYY-MM-DD)") class Conversations(Namespace): @@ -237,8 +244,8 @@ def _mask_name(self, name: Optional[str]) -> Optional[str]: return mask_name(name) if self._c.mask_numbers else name def _link(self, kind: str, item_id: str) -> Optional[str]: - if not item_id: - return None + if not isinstance(item_id, str) or not ID_RE.match(item_id): + return None # only plain ids go into an app link page = "after-call-copilot/calls" if kind == "call" else "first-alert-copilot/alerts" return f"{self._c.app_url}/{page}/{quote(item_id, safe='')}" @@ -553,6 +560,8 @@ def reference(self, call_or_alert: Union[CallBrief, AlertBrief, FirstAlertEvent, kind, item = "call", call_or_alert.strip() else: raise InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") + if not ID_RE.match(item): + raise InvalidRequestError("reference: an id of letters, digits, '-' and '_' (at most 128)") return Reference(kind=kind, id=item, link=self._link(kind, item)) @staticmethod diff --git a/src/intelligence_cloud/errors.py b/src/intelligence_cloud/errors.py index ed410fb..a82e1e8 100644 --- a/src/intelligence_cloud/errors.py +++ b/src/intelligence_cloud/errors.py @@ -206,7 +206,8 @@ def find(self, error_type: "type[E]") -> "Optional[E]": seen.add(id(err)) if isinstance(err, error_type): return err - err = getattr(err, "cause", None) or err.__cause__ + nxt = getattr(err, "cause", None) + err = nxt if isinstance(nxt, BaseException) else err.__cause__ return None diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index d8f6954..3c25b54 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -11,6 +11,7 @@ import hashlib import json +import re import threading from collections import OrderedDict from dataclasses import dataclass, field @@ -18,9 +19,11 @@ from typing import Any, Dict, List, Mapping, Optional, Protocol, Union from . import _spec -from .errors import PayloadTooLargeError, WebhookPayloadError +from .errors import InvalidRequestError, PayloadTooLargeError, WebhookPayloadError AFTER_CALL_EVENT_TYPE = "end_of_call_summary" +# An id that may go into an app link or a key: letters, digits, "-" and "_", at most 128. +ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") MAX_EVENT_BYTES = 262_144 # 256 KB; answer 413 to anything larger @@ -111,7 +114,7 @@ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], if max_bytes and len(body) > max_bytes: raise PayloadTooLargeError(f"body is larger than {max_bytes} bytes") try: - body = json.loads(bytes(body).decode("utf-8")) + body = json.loads(bytes(body).decode("utf-8-sig")) except (ValueError, UnicodeDecodeError): raise WebhookPayloadError("body is not JSON") from None if not isinstance(body, Mapping): @@ -161,8 +164,8 @@ class FirstAlertEvent: ``client.conversations.alert(event.alert_id)``. Printing it shows only the alert id and time. **The First Alert payload is not final.** The published schema is an open object (alert id, rule, - location, call, time). The parser needs only an alert id: any non-empty string under ``alert_id``, - ``alert.id`` or ``id``. Rule, location, call and time are read from the shapes seen today + location, call, time). The parser needs only an alert id: letters, digits, "-" and "_" (at most + 128) under ``alert_id``, else ``alert.id``, else ``id``; the first of these present decides. Rule, location, call and time are read from the shapes seen today (``rule_name``/``rule.name``/``rule``/``alert_name``, ``location_id``/``location.id``, ``call_id``/``call.id``, ``timestamp``/``fired_at``/``created_at``) and are None when absent. ``raw`` is the whole payload as received, for anything the parser does not read yet.""" @@ -191,6 +194,10 @@ def _first_str(*values: Any) -> Optional[str]: +def _plain_id(value: Optional[str]) -> Optional[str]: + return value if value is not None and ID_RE.match(value) else None + + def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping[str, Any]: if isinstance(body, str): body = body.encode("utf-8") @@ -198,7 +205,7 @@ def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping if max_bytes and len(body) > max_bytes: raise PayloadTooLargeError(f"body is larger than {max_bytes} bytes") try: - body = json.loads(bytes(body).decode("utf-8")) + body = json.loads(bytes(body).decode("utf-8-sig")) except (ValueError, UnicodeDecodeError): raise WebhookPayloadError("body is not JSON") from None if not isinstance(body, Mapping): @@ -219,9 +226,17 @@ def sub(key: str) -> Mapping[str, Any]: return v if isinstance(v, Mapping) else {} alert, rule, call, loc = sub("alert"), sub("rule"), sub("call"), sub("location") - alert_id = _first_str(data.get("alert_id"), alert.get("id"), data.get("id")) - if alert_id is None: - raise WebhookPayloadError("event has no alert id") + # The first place that has an id decides: a top-level alert_id that is not a string is refused rather + # than passed over for a nested one. + if "alert_id" in data: + raw_id = data.get("alert_id") + elif "id" in alert: + raw_id = alert.get("id") + else: + raw_id = data.get("id") + alert_id = raw_id.strip() if isinstance(raw_id, str) else None + if not alert_id or not ID_RE.match(alert_id): + raise WebhookPayloadError("event has no valid alert id (letters, digits, '-' and '_', at most 128)") stamp = _first_str(data.get("timestamp"), data.get("fired_at"), data.get("created_at"), alert.get("created_at")) try: when = _ts(stamp, "timestamp") if stamp else None @@ -231,8 +246,8 @@ def sub(key: str) -> Mapping[str, Any]: alert_id=alert_id, rule=_first_str(data.get("rule_name"), rule.get("name"), data.get("rule") if isinstance(data.get("rule"), str) else None, data.get("alert_name"), alert.get("rule_name"), alert.get("name")), - location_id=_first_str(data.get("location_id"), loc.get("id"), alert.get("location_id")), - call_id=_first_str(data.get("call_id"), call.get("id"), alert.get("call_id")), + location_id=_plain_id(_first_str(data.get("location_id"), loc.get("id"), alert.get("location_id"))), + call_id=_plain_id(_first_str(data.get("call_id"), call.get("id"), alert.get("call_id"))), timestamp=when, is_test=data.get("is_test") is True, raw=dict(data), @@ -240,9 +255,11 @@ def sub(key: str) -> Mapping[str, Any]: class DedupStore(Protocol): - """Remembers which keys were seen. ``add`` returns True when the key is new.""" + """Remembers delivery keys. ``has`` only checks; ``add`` records (after your durable write).""" + + def has(self, key: str) -> bool: ... - def add(self, key: str) -> bool: ... + def add(self, key: str) -> None: ... class MemoryDedupStore: @@ -253,15 +270,19 @@ def __init__(self, max_size: int = 10_000): self._keys: "OrderedDict[str, None]" = OrderedDict() self._lock = threading.Lock() - def add(self, key: str) -> bool: + def has(self, key: str) -> bool: with self._lock: if key in self._keys: self._keys.move_to_end(key) - return False + return True + return False + + def add(self, key: str) -> None: + with self._lock: self._keys[key] = None + self._keys.move_to_end(key) if len(self._keys) > self.max_size: self._keys.popitem(last=False) - return True def _canonical_hash(body: Any) -> str: @@ -299,8 +320,9 @@ def delivery_key(event: Any) -> str: """The identity of one exact delivery: event type, location, call (or alert) id, and a SHA-256 of the canonical JSON body. A re-delivery of the same content has the same key; a later delivery with newer data does not.""" - if isinstance(event, str) and not event.lstrip().startswith("{"): - return "id:" + event.strip() # a bare id (an alert id): alerts do not change once raised + if isinstance(event, str) and not event.lstrip("\ufeff \t\r\n").startswith("{"): + raise InvalidRequestError("seen(event) and remember(event) take the event, its parsed body or the " + "raw request body, not an id: an id alone cannot tell newer data apart") ev = _as_event(event) if isinstance(ev, AfterCallEvent): return f"{ev.type}:{ev.location_id}:{ev.call.id}:{_canonical_hash(ev.raw)}" @@ -310,32 +332,47 @@ def delivery_key(event: Any) -> str: class Deduplicator: - """Spots exact re-deliveries, and never hides newer data. + """Recognises an exact re-delivery, and never hides newer data or loses an event. - ``is_duplicate(event)`` is True only when the same delivery arrives again: the same event type, - location and call id **and** the same content (a SHA-256 of the canonical JSON body, because the - payload carries no per-delivery version). A later delivery for the same call with changed content - is not a duplicate: store it under ``upsert_key(event)`` (the call id) and replace the earlier copy. + Check, store, then remember:: - It accepts an event object, a parsed body or the raw request bytes. A bare string that is not JSON - is taken as an exact id (for First Alert alert ids). The same name and meaning in every SDK: - ``is_duplicate`` (Python), ``isDuplicate`` (PHP, TypeScript). + if dedup.seen(event): # an exact re-delivery you already stored + return 204 + store.upsert(upsert_key(event), event) # your durable write, keyed on the call id + dedup.remember(event) # only after the write succeeded + return 204 # on a storage failure answer 5xx and do not remember - The default store is in memory, per process: with more than one worker or process, pass a shared - ``store`` whose ``add(key)`` returns True only for a new key (for example a cache's set-if-absent - with an expiry). + ``seen`` only checks; it records nothing, so a delivery whose storage failed is processed again + when the sender retries. A delivery's identity is its event type, location and call (or alert) id + **and** its content (a SHA-256 of the canonical JSON body: the payload carries no per-delivery + version). A later delivery for the same call with changed content is not seen: upsert it. + + Takes an event object, a parsed body or the raw request bytes; a string that is not JSON is + refused (InvalidRequestError), because an id alone cannot tell newer data apart. The same names in + every SDK: ``seen``/``remember`` (Python), ``seen``/``remember`` (PHP, TypeScript). + + The default store is in memory, per process: with more than one worker or process pass a shared + ``store`` with ``has(key)`` and ``add(key)``, for example a cache key with an expiry. """ def __init__(self, max_size: int = 10_000, store: Optional[DedupStore] = None): self.store = store or MemoryDedupStore(max_size) - def is_duplicate(self, event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> bool: - """True for an exact re-delivery; otherwise records the delivery and returns False.""" - if event is None or event == "" or event == b"": - raise ValueError("an event is required") - return not self.store.add(delivery_key(event)) + def seen(self, event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> bool: + """True when this exact delivery was remembered before. Records nothing.""" + return bool(self.store.has(delivery_key(_present(event)))) + + def remember(self, event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> None: + """Record this delivery. Call it after your durable write succeeded.""" + self.store.add(delivery_key(_present(event))) @staticmethod def upsert_key(event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping[str, Any]]) -> str: """The call id (After Call) or alert id (First Alert) to store the delivery under.""" return upsert_key(event) + + +def _present(event: Any) -> Any: + if event is None or event == "" or event == b"": + raise InvalidRequestError("an event is required") + return event diff --git a/src/intelligence_cloud/testing/_fake.py b/src/intelligence_cloud/testing/_fake.py index ac90c06..be528a7 100644 --- a/src/intelligence_cloud/testing/_fake.py +++ b/src/intelligence_cloud/testing/_fake.py @@ -7,12 +7,13 @@ import uuid from dataclasses import dataclass, field from datetime import datetime, time as dtime, timedelta, timezone -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple import httpx from .. import _spec from ..client import Client +from ..errors import InvalidRequestError RESELLER = "00000000-0000-4000-8000-0000000000aa" VERTICAL = "00000000-0000-4000-8000-0000000000bb" @@ -79,56 +80,76 @@ class FakeAPI: It behaves like the API where it matters to callers: products, groups and alert email preferences are per location; number mappings are company-wide with one extension per location (409 otherwise); - new users start with alert email on; connectors settle in the background; a duplicate email is 409. - - With ``strict=True`` (the default) it refuses requests the published spec does not define: an - unknown path or method (404), an unknown query parameter (400) or a body missing a required field - (422), with the API's error shape. - - Knobs for the failures your code must handle: ``connector_outcome`` ("active", "connected", "error" - or "stuck"), :meth:`fail_write`, :meth:`network_down` and :meth:`rate_limit`. Assert on - :attr:`requests` and :attr:`writes`. + new users start with alert email on; connectors settle in the background; a duplicate email is 409; + access tokens expire and are renewed; and **sending a refresh token a second time ends every session + of that login**, as on the platform (the old access token stops working; the next call signs in). + + **Strict mode** (``strict=True``, the default) refuses, with the API's error shape: + + - a path or method the published spec does not define (404); + - a query parameter it does not define (400), or a query value of the wrong type (integer, boolean), + outside its enum, or not in its format (uuid, date-time) (400); + - a body missing a required top-level field, with a top-level field the spec does not define, or + with a top-level field of the wrong JSON type, outside its enum or not in its format; for a list, + each item's type, enum and format (422). + + It does **not** check nested objects, rules that join several fields, or how the platform searches + and sorts; its data is simpler than the platform's. Run once against a test company before release. + + **Supported surface** (everything else is internal and may change): the constructor, :meth:`client`, + :meth:`seed_customer`, :meth:`seed_calls`, ``connector_outcome``, :meth:`fail_next`, + :meth:`fail_write`, :meth:`network_down`, :meth:`rate_limit`, :meth:`expire_access_tokens`, the + request log (:attr:`requests`, :attr:`writes`, :meth:`writes_since`, :meth:`count`, + :meth:`reset_log`, :attr:`auth_log`) and the readers :meth:`products`, :meth:`numbers`, + :meth:`fa_numbers`, :meth:`ih_numbers`, :meth:`group_members`. """ def __init__(self, *, connector_outcome: str = "active", role: str = "admin", strict: bool = True): + if connector_outcome not in CONNECTOR_OUTCOMES + ("connecting",): + raise ValueError(f"connector_outcome: one of {CONNECTOR_OUTCOMES}") self.requests: List[FakeRequest] = [] - self.calls: List[Tuple[str, str]] = [] # (METHOD, full path), kept for older tests - self.bodies: List[Tuple[str, str, Any]] = [] + self._auth_log: List[Tuple[str, str]] = [] + self._calls: List[Tuple[str, str]] = [] # (METHOD, full path), for the SDK's own tests + self._bodies: List[Tuple[str, str, Any]] = [] self.connector_outcome = connector_outcome - self.role = ROLES.get(role, role) - self.strict = strict - self.companies: Dict[str, Dict[str, Any]] = {} - self.locations: Dict[str, Dict[str, Any]] = {} - self.groups: Dict[str, Dict[str, Any]] = {} - self.rules: Dict[str, Dict[str, Any]] = {} - self.connectors: Dict[str, Dict[str, Any]] = {} - self.ih_setup: Dict[str, Dict[str, Any]] = {} - self.ih_config: Dict[str, bool] = {} - self.fa_config: Dict[str, Dict[str, Any]] = {} - self.users: Dict[str, Dict[str, Any]] = {} - self.mappings: Dict[str, List[Dict[str, Any]]] = {} - self.email_prefs: Dict[Any, Dict[str, Any]] = {} - self.invitations: List[str] = [] # user ids emailed an invitation, in order - self.after_call_hooks: Dict[str, Dict[str, Any]] = {} - self.domains: Dict[str, List[Dict[str, Any]]] = {} - self.secrets_sent: List[Dict[str, Any]] = [] # connector configs as sent (keys included), for assertions - self.me_extra: Dict[str, Any] = {} + self._role = ROLES.get(role, role) + self._strict = strict + self._companies: Dict[str, Dict[str, Any]] = {} + self._locations: Dict[str, Dict[str, Any]] = {} + self._groups: Dict[str, Dict[str, Any]] = {} + self._rules: Dict[str, Dict[str, Any]] = {} + self._connectors: Dict[str, Dict[str, Any]] = {} + self._ih_setup: Dict[str, Dict[str, Any]] = {} + self._ih_config: Dict[str, bool] = {} + self._fa_config: Dict[str, Dict[str, Any]] = {} + self._users: Dict[str, Dict[str, Any]] = {} + self._mappings: Dict[str, List[Dict[str, Any]]] = {} + self._email_prefs: Dict[Any, Dict[str, Any]] = {} + self._invitations: List[str] = [] # user ids emailed an invitation, in order + self._after_call_hooks: Dict[str, Dict[str, Any]] = {} + self._domains: Dict[str, List[Dict[str, Any]]] = {} + self._secrets_sent: List[Dict[str, Any]] = [] # connector configs as sent (keys included) + self._me_extra: Dict[str, Any] = {} # conversation data (user reads) - self.visible_locations: List[Dict[str, Any]] = [] - self.call_rows: List[Dict[str, Any]] = [] - self.call_details: Dict[str, Dict[str, Any]] = {} - self.alert_rows: List[Dict[str, Any]] = [] - self.task_rows: List[Dict[str, Any]] = [] - self.insights: Dict[str, Any] = {} + self._visible_locations: List[Dict[str, Any]] = [] + self._call_rows: List[Dict[str, Any]] = [] + self._call_details: Dict[str, Dict[str, Any]] = {} + self._alert_rows: List[Dict[str, Any]] = [] + self._task_rows: List[Dict[str, Any]] = [] + self._insights: Dict[str, Any] = {} self._clock = 0 - self._tokens: Dict[str, str] = {} # access token -> role + self._access: Dict[str, Tuple[str, str]] = {} # live access token -> (role, email) + self._refresh: Dict[str, Tuple[str, str]] = {} # unused refresh token -> (role, email) + self._used_refresh: Dict[str, str] = {} # used refresh token -> email self._logins: Dict[str, str] = {} # email -> role self._token_n = 0 + self._request_role = self._role self._fail: Optional[Tuple[int, int]] = None # (writes left before the failing one, status) + self._next_failures: List[Dict[str, Any]] = [] self._down = False self._limited: Tuple[int, float] = (0, 0.0) self._ops = _op_table() - self.routes: List[Tuple[str, re.Pattern, Callable]] = [] + self._routes: List[Tuple[str, re.Pattern, Callable]] = [] self._register() # ------------------------------------------------------------------ public surface @@ -137,7 +158,11 @@ def client(self, role: Optional[str] = None, **client_options: Any) -> Client: """A real Client wired to this fake. ``role``: "admin" (an administrator login) or "user" (a person's own login); default the role given to FakeAPI. Other options go to Client, for example ``mask_numbers=False``. Waits (retries, connector checks) do not sleep unless you pass ``sleep``.""" - r = ROLES.get(role, role) if role else self.role + if "transport" in client_options: + raise InvalidRequestError("FakeAPI.client() wires the fake as the transport: do not pass transport=") + if role is not None and role not in ROLES and role not in ROLES.values(): + raise InvalidRequestError('role: "admin" or "user"') + r = ROLES.get(role, role) if role else self._role email = f"{'admin' if r == 'reseller_admin' else 'user'}.{len(self._logins) + 1}@example.com" self._logins[email] = r client_options.setdefault("sleep", lambda s: None) @@ -152,16 +177,23 @@ def writes_since(self, start: int = 0) -> List[Tuple[str, str]]: """The writes after ``start`` (an index into :attr:`requests`, e.g. ``len(api.requests)``).""" return [(r.method, r.path) for r in self.requests[start:] if r.method != "GET"] + @property + def auth_log(self) -> List[Tuple[str, str]]: + """Sign-in and token renewal, oldest first: ("login" | "refresh" | "refresh_reused", email). + "refresh_reused" means a used refresh token was sent again and every session of that login ended.""" + return list(self._auth_log) + def count(self, method: str, pattern: str) -> int: """How many requests matched ``method`` and the path regex ``pattern`` (without /api/v1).""" rx = re.compile("^" + pattern + "$") return sum(1 for r in self.requests if r.method == method and rx.match(r.path)) def reset_log(self) -> None: - """Forget the request log (state is kept).""" + """Forget the request log and the auth log (state is kept).""" self.requests.clear() - self.calls.clear() - self.bodies.clear() + self._auth_log.clear() + self._calls.clear() + self._bodies.clear() def fail_write(self, nth: int = 1, status: int = 400) -> None: """Make the ``nth`` write from now (1 = the next one) fail once with ``status``.""" @@ -169,6 +201,21 @@ def fail_write(self, nth: int = 1, status: int = 400) -> None: raise ValueError("nth: 1 or more") self._fail = (nth - 1, status) + def fail_next(self, status: Optional[int] = None, *, network: Optional[str] = None, + method: Optional[str] = None, path: Optional[str] = None, retry_after: Optional[float] = None) -> None: + """Make the next request that matches ``method`` and the path regex ``path`` (without /api/v1; + sign-in is "/auth/login", renewal "/auth/refresh") fail once: with HTTP ``status``, or with a + ``network`` failure: "connect" (never left), "read_timeout" or "write_timeout" (left, no answer), + or "undecodable" (an answer that cannot be read). A renewal that fails in any way except + "connect" has already used its refresh token, as a gateway error after the platform would.""" + if (status is None) == (network is None): + raise ValueError("fail_next: give status or network") + if network is not None and network not in NETWORK_FAILURES: + raise ValueError(f"network: one of {NETWORK_FAILURES}") + self._next_failures.append({"status": status, "network": network, "method": method, + "path": re.compile("^" + path + "$") if path else None, + "retry_after": retry_after}) + def network_down(self, down: bool = True) -> None: """Every request fails as if there were no network (the client raises NetworkError).""" self._down = down @@ -177,11 +224,15 @@ def rate_limit(self, count: int = 1, retry_after: float = 1) -> None: """The next ``count`` requests (sign-in included) answer 429 with ``Retry-After``.""" self._limited = (count, retry_after) + def expire_access_tokens(self) -> None: + """Every access token stops working, as when they expire: the next call renews its token.""" + self._access.clear() + # ------------------------------------------------------------------ plumbing - def route(self, method: str, pattern: str): + def _route(self, method: str, pattern: str): def deco(fn): - self.routes.append((method, re.compile("^/api/v1" + pattern + "$"), fn)) + self._routes.append((method, re.compile("^/api/v1" + pattern + "$"), fn)) return fn return deco @@ -198,29 +249,79 @@ def _check_strict(self, op_id: Optional[str], request: httpx.Request, path: str, unknown = sorted(set(request.url.params.keys()) - set(op["query"])) if unknown: return _error(400, "VALIDATION_ERROR", f"Unknown query parameter(s): {', '.join(unknown)}") + for name, value in request.url.params.multi_items(): + problem = _query_problem(op["query"][name], value) + if problem: + return _error(400, "VALIDATION_ERROR", f"{name}: {problem}") if op["body"] is not None: if body is None: if op["body"]["required"]: return _error(422, "VALIDATION_ERROR", "A request body is required") else: schema = _spec._resolve(op["body"]["schema"]) - missing = [k for k in (schema.get("required") or []) if not isinstance(body, dict) or k not in body] + if not isinstance(body, dict): + return _error(422, "VALIDATION_ERROR", "The body must be a JSON object") + missing = [k for k in (schema.get("required") or []) if k not in body] if missing: return _error(422, "VALIDATION_ERROR", f"Missing required field(s): {', '.join(missing)}") + props = schema.get("properties") or {} + extra = sorted(set(body) - set(props)) if props else [] + if extra: + return _error(422, "VALIDATION_ERROR", f"Unknown field(s): {', '.join(extra)}") + for name, value in body.items(): + problem = _value_problem(_spec._resolve(props.get(name, {})), value, items=True) + if problem: + return _error(422, "VALIDATION_ERROR", f"{name}: {problem}") return None - def _role_of(self, request: httpx.Request) -> str: - token = (request.headers.get("Authorization") or "").replace("Bearer ", "") - return self._tokens.get(token, self.role) - - def _issue(self, role: str) -> Dict[str, Any]: + def _issue(self, role: str, email: str) -> Dict[str, Any]: self._token_n += 1 access, refresh = f"fake-access-{self._token_n}", f"fake-refresh-{self._token_n}" - self._tokens[access] = role - self._tokens[refresh] = role + self._access[access] = (role, email) + self._refresh[refresh] = (role, email) return {"access_token": access, "refresh_token": refresh, "token_type": "Bearer", "expires_in": 899, "user": {"id": new_id(), "role": role}} + def _end_sessions(self, email: str) -> None: + for table in (self._access, self._refresh): + for tok in [t for t, (_, e) in table.items() if e == email]: + del table[tok] + + def _use_refresh(self, token: Any) -> Optional[Tuple[str, str]]: + """Use a refresh token once. A second use ends every session of its login.""" + if token in self._refresh: + owner = self._refresh.pop(token) + self._used_refresh[token] = owner[1] + return owner + if token in self._used_refresh: + email = self._used_refresh[token] + self._auth_log.append(("refresh_reused", email)) + self._end_sessions(email) + return None + + def _take_failure(self, method: str, path: str) -> Optional[Dict[str, Any]]: + for i, f in enumerate(self._next_failures): + if (f["method"] is None or f["method"] == method) and (f["path"] is None or f["path"].match(path)): + return self._next_failures.pop(i) + return None + + @staticmethod + def _failure_response(f: Dict[str, Any], request: httpx.Request) -> httpx.Response: + net = f["network"] + if net == "connect": + raise httpx.ConnectError("connection refused (FakeAPI.fail_next)", request=request) + if net == "read_timeout": + raise httpx.ReadTimeout("read timed out (FakeAPI.fail_next)", request=request) + if net == "write_timeout": + raise httpx.WriteTimeout("write timed out (FakeAPI.fail_next)", request=request) + if net == "undecodable": + return httpx.Response(200, headers={"Content-Encoding": "gzip", "Content-Type": "application/json"}, + content=b"this is not gzip") + headers = {"Retry-After": str(f["retry_after"])} if f["retry_after"] is not None else {} + return httpx.Response(f["status"], headers=headers, + json={"error": {"code": "FAKE_FAILURE", "message": "Failed on purpose by FakeAPI.fail_next", + "request_id": "req-fake"}}) + def __call__(self, request: httpx.Request) -> httpx.Response: if self._down: raise httpx.ConnectError("the fake network is down", request=request) @@ -231,36 +332,55 @@ def __call__(self, request: httpx.Request) -> httpx.Response: json={"error": {"code": "RATE_LIMITED", "message": "Too many requests"}}) full = request.url.path path = full[len("/api/v1"):] if full.startswith("/api/v1") else full + failure = self._take_failure(request.method, path) + if failure is not None and failure["network"] == "connect": + return self._failure_response(failure, request) # never left: nothing happens on the server try: body = json.loads(request.content) if request.content else None except ValueError: return _error(400, "VALIDATION_ERROR", "The body is not JSON") op_id = self._operation(request.method, path) - if self.strict: + if self._strict: refused = self._check_strict(op_id, request, path, body) if refused is not None: return refused + elif op_id is None: + return _error(501, "NOT_IMPLEMENTED", f"{request.method} {path} is not served by this fake") if path == "/auth/login": - role = self._logins.get((body or {}).get("email"), self.role) - return httpx.Response(200, json=self._issue(role)) + if failure is not None: + return self._failure_response(failure, request) + email = (body or {}).get("email") + role = self._logins.get(email, self._role) + self._auth_log.append(("login", str(email))) + return httpx.Response(200, json=self._issue(role, str(email))) if path == "/auth/refresh": - role = self._tokens.pop((body or {}).get("refresh_token"), None) - if role is None: + owner = self._use_refresh((body or {}).get("refresh_token")) + if owner is not None: + self._auth_log.append(("refresh", owner[1])) + issued = self._issue(*owner) + if failure is not None: + return self._failure_response(failure, request) # the token is used already + if owner is None: return _error(401, "UNAUTHORIZED", "Invalid refresh token") - return httpx.Response(200, json=self._issue(role)) + return httpx.Response(200, json=issued) if path == "/auth/logout": return httpx.Response(204) + token = (request.headers.get("Authorization") or "").replace("Bearer ", "") + if token not in self._access: + return _error(401, "UNAUTHORIZED", "The access token is not valid") + self._request_role = self._access[token][0] self.requests.append(FakeRequest(request.method, path, dict(request.url.params), body, op_id)) - self.calls.append((request.method, full)) - self.bodies.append((request.method, full, body)) + self._calls.append((request.method, full)) + self._bodies.append((request.method, full, body)) + if failure is not None: + return self._failure_response(failure, request) if request.method != "GET" and self._fail is not None: left, status = self._fail if left == 0: self._fail = None return _error(status, "FAKE_FAILURE", "Failed on purpose by FakeAPI.fail_write") self._fail = (left - 1, status) - self._request_role = self._role_of(request) - for method, rx, fn in self.routes: + for method, rx, fn in self._routes: m = rx.match(full) if m and method == request.method: try: @@ -273,6 +393,7 @@ def __call__(self, request: httpx.Request) -> httpx.Response: return httpx.Response(status, json=payload) if payload is not None else httpx.Response(status) return _error(501, "NOT_IMPLEMENTED", f"{op_id or path} is published but this fake does not serve it yet") + # ------------------------------------------------------------------ seed data (fictional) def seed_customer(self, *, teams: int = 1, people: bool = True) -> SeededCustomer: @@ -310,7 +431,7 @@ def conn(i: int) -> Any: mgr = acc.add_base_manager(cust, PersonSpec("dana.cho@example.com", "Dana", "Cho"), teams=list(cust.teams), line="2001", invite=False) seeded.managers["dana.cho@example.com"] = mgr.user_id - self.visible_locations = [{"id": t.location_id, "location_name": t.name} + self._visible_locations = [{"id": t.location_id, "location_name": t.name} for t in ([cust.management] if cust.management else []) + cust.teams] finally: self.connector_outcome = outcome @@ -323,9 +444,9 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti record, an open task and, for every other call, an "Upset Customer" alert. Callers use 555-01xx numbers. Returns the call ids, newest first.""" names = ["Morgan Diaz", "Riley Park", "Avery Lane", "Jamie Fox", "Quinn Hale"] - lid = location_id or (self.visible_locations[-1]["id"] if self.visible_locations else new_id()) - if not self.visible_locations: - self.visible_locations = [{"id": lid, "location_name": "Riverbend - Main"}] + lid = location_id or (self._visible_locations[-1]["id"] if self._visible_locations else new_id()) + if not self._visible_locations: + self._visible_locations = [{"id": lid, "location_name": "Riverbend - Main"}] if day is None: base = datetime.now(timezone.utc) - timedelta(minutes=5) else: @@ -347,7 +468,7 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti "action_items": ["Call back"]}, "sentiment": {"overall": "neutral"}, "topics": [{"name": "Service"}]}, tasks=[{"id": new_id(), "title": "Call back", "status": "pending", "due_date": None}] if tasks else []) - self.call_details[cid] = detail + self._call_details[cid] = detail if tasks: new_tasks.append({"id": new_id(), "title": "Call back", "status": "pending", "due_date": None, "call_id": cid, "location_id": lid}) @@ -358,167 +479,167 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti "summary": row["summary"], "sentiment": "negative", "sentiment_score": -30, "keywords": ["Upset Customer"], "topics": []}) ids.append(cid) - self.call_rows[:0] = new_calls # newest first, as the API lists them - self.task_rows[:0] = new_tasks - self.alert_rows[:0] = new_alerts + self._call_rows[:0] = new_calls # newest first, as the API lists them + self._task_rows[:0] = new_tasks + self._alert_rows[:0] = new_alerts return ids # ------------------------------------------------------------------ state readers (for assertions) - def location_users(self, lid: str) -> List[Dict[str, Any]]: - return [u for u in self.users.values() if lid in u["_locations"]] + def _location_users(self, lid: str) -> List[Dict[str, Any]]: + return [u for u in self._users.values() if lid in u["_locations"]] - def tick(self) -> str: + def _tick(self) -> str: self._clock += 1 return f"2026-11-01T00:00:{self._clock:02d}Z" def products(self, uid: str, lid: str) -> set: """The products a user has at a location.""" - return self.users[uid]["_products"].setdefault(lid, set()) + return self._users[uid]["_products"].setdefault(lid, set()) def numbers(self, uid: str, connector_id: Optional[str] = None) -> List[str]: """The numbers mapped to a user (on one connector, or on all).""" - return [n for m in self.mappings.get(uid, []) if connector_id in (None, m["connector_id"]) + return [n for m in self._mappings.get(uid, []) if connector_id in (None, m["connector_id"]) for n in m["monitored_numbers"]] def fa_numbers(self, lid: str) -> List[str]: """The lines First Alert watches at a location.""" - return [n for m in self.fa_config.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] + return [n for m in self._fa_config.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] def ih_numbers(self, lid: str) -> List[str]: """The lines Insights Hub covers at a location.""" - return [n for m in self.ih_setup.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] + return [n for m in self._ih_setup.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] def group_members(self, lid: str, name: str) -> List[str]: """The user ids in the named group at a location.""" - return next((g["members"] for g in self.groups.values() if g["location_id"] == lid and g["group_name"] == name), []) + return next((g["members"] for g in self._groups.values() if g["location_id"] == lid and g["group_name"] == name), []) # ------------------------------------------------------------------ routes def _register(self) -> None: # noqa: C901 - a fake server is a long switch api = self - @self.route("GET", r"/me") + @self._route("GET", r"/me") def me(req, body): role = api._request_role return 200, {"data": dict({"id": new_id(), "role": role, "reseller_id": RESELLER if role != "frontline_user" else None, "user_type": "reseller_user" if role != "frontline_user" else "company_user", - "unexpected_field": "redacted"}, **api.me_extra)} + "unexpected_field": "redacted"}, **api._me_extra)} - @self.route("GET", r"/connector-types") + @self._route("GET", r"/connector-types") def connector_types(req, body): return 200, {"data": CONNECTOR_TYPES} - @self.route("GET", r"/verticals") + @self._route("GET", r"/verticals") def verticals(req, body): return 200, {"data": [{"id": VERTICAL, "key": "service-providers", "name": "Service providers"}]} # companies - @self.route("GET", r"/resellers/([^/]+)/companies") + @self._route("GET", r"/resellers/([^/]+)/companies") def list_companies(req, body, rid): q = req.url.params.get("search", "") - rows = [c for c in api.companies.values() if c["company_name"].lower().startswith(q.lower())] + rows = [c for c in api._companies.values() if c["company_name"].lower().startswith(q.lower())] return 200, {"data": [{"type": "company", "attributes": c} for c in rows], "has_more": False, "next_cursor": None, "total_count": len(rows)} - @self.route("POST", r"/resellers/([^/]+)/companies") + @self._route("POST", r"/resellers/([^/]+)/companies") def create_company(req, body, rid): cid = new_id() c = dict(body, id=cid, reseller_id=rid, is_active=True, mfa_enforced=True) - api.companies[cid] = c + api._companies[cid] = c return 201, {"data": {"type": "company", "attributes": c}, "invited_user": {"id": new_id(), "email": body["primary_admin_contact_email"]}} - @self.route("GET", r"/companies/([^/]+)") + @self._route("GET", r"/companies/([^/]+)") def get_company(req, body, cid): - return (200, res("company", api.companies[cid])) if cid in api.companies else (404, {"error": {}}) + return (200, res("company", api._companies[cid])) if cid in api._companies else (404, {"error": {}}) - @self.route("PATCH", r"/companies/([^/]+)") + @self._route("PATCH", r"/companies/([^/]+)") def patch_company(req, body, cid): - api.companies[cid].update(body) - return 200, res("company", api.companies[cid]) + api._companies[cid].update(body) + return 200, res("company", api._companies[cid]) - @self.route("POST", r"/companies/([^/]+)/deactivate") + @self._route("POST", r"/companies/([^/]+)/deactivate") def deact_company(req, body, cid): - if not api.companies[cid]["is_active"]: + if not api._companies[cid]["is_active"]: return 409, {"error": {"code": "CONFLICT", "message": "Company is already inactive"}} - api.companies[cid]["is_active"] = False - return 200, res("company", api.companies[cid]) + api._companies[cid]["is_active"] = False + return 200, res("company", api._companies[cid]) - @self.route("GET", r"/locations/([^/]+)/after-call/automation") + @self._route("GET", r"/locations/([^/]+)/after-call/automation") def get_hook(req, body, lid): - return 200, {"data": api.after_call_hooks.get(lid)} + return 200, {"data": api._after_call_hooks.get(lid)} - @self.route("PUT", r"/locations/([^/]+)/after-call/automation") + @self._route("PUT", r"/locations/([^/]+)/after-call/automation") def put_hook(req, body, lid): - api.after_call_hooks[lid] = {"webhook_url": body["webhook_url"], "enabled": body.get("enabled", True)} - return 200, {"data": api.after_call_hooks[lid]} + api._after_call_hooks[lid] = {"webhook_url": body["webhook_url"], "enabled": body.get("enabled", True)} + return 200, {"data": api._after_call_hooks[lid]} - @self.route("POST", r"/companies/([^/]+)/reactivate") + @self._route("POST", r"/companies/([^/]+)/reactivate") def react_company(req, body, cid): - api.companies[cid]["is_active"] = True - return 200, res("company", api.companies[cid]) + api._companies[cid]["is_active"] = True + return 200, res("company", api._companies[cid]) - @self.route("POST", r"/companies/([^/]+)/domains") + @self._route("POST", r"/companies/([^/]+)/domains") def claim(req, body, cid): d = {"id": "dom-1", "domain": body["domain"], "status": "pending", "verification": {"type": "TXT", "name": "_ic-verify." + body["domain"], "value": "abc"}} - api.domains.setdefault(cid, []).append(d) + api._domains.setdefault(cid, []).append(d) return 201, {"data": d} - @self.route("GET", r"/companies/([^/]+)/domains") + @self._route("GET", r"/companies/([^/]+)/domains") def list_domains(req, body, cid): - return 200, {"data": api.domains.get(cid, [])} + return 200, {"data": api._domains.get(cid, [])} # locations - @self.route("GET", r"/companies/([^/]+)/locations") + @self._route("GET", r"/companies/([^/]+)/locations") def list_locations(req, body, cid): q = req.url.params.get("search", "") - rows = [x for x in api.locations.values() if x["company_id"] == cid and q.lower() in x["location_name"].lower()] + rows = [x for x in api._locations.values() if x["company_id"] == cid and q.lower() in x["location_name"].lower()] return 200, page(rows, "location") - @self.route("POST", r"/companies/([^/]+)/locations") + @self._route("POST", r"/companies/([^/]+)/locations") def create_location(req, body, cid): lid = new_id() - api.locations[lid] = dict(body, id=lid, company_id=cid, is_active=True, created_at=api.tick()) - return 201, res("location", api.locations[lid]) + api._locations[lid] = dict(body, id=lid, company_id=cid, is_active=True, created_at=api._tick()) + return 201, res("location", api._locations[lid]) - @self.route("GET", r"/companies/([^/]+)/locations/([^/]+)") + @self._route("GET", r"/companies/([^/]+)/locations/([^/]+)") def get_location(req, body, cid, lid): - return 200, res("location", api.locations[lid]) + return 200, res("location", api._locations[lid]) - @self.route("PATCH", r"/companies/([^/]+)/locations/([^/]+)") + @self._route("PATCH", r"/companies/([^/]+)/locations/([^/]+)") def patch_location(req, body, cid, lid): - api.locations[lid].update(body) - return 200, res("location", api.locations[lid]) + api._locations[lid].update(body) + return 200, res("location", api._locations[lid]) # groups - @self.route("GET", r"/locations/([^/]+)/user-groups") + @self._route("GET", r"/locations/([^/]+)/user-groups") def list_groups(req, body, lid): q = req.url.params.get("search", "") - rows = [{k: v for k, v in g.items() if k != "members"} for g in api.groups.values() + rows = [{k: v for k, v in g.items() if k != "members"} for g in api._groups.values() if g["location_id"] == lid and q.lower() in g["group_name"].lower()] return 200, page(rows, "user_group") - @self.route("POST", r"/locations/([^/]+)/user-groups") + @self._route("POST", r"/locations/([^/]+)/user-groups") def create_group(req, body, lid): gid = new_id() - api.groups[gid] = {"id": gid, "location_id": lid, "group_name": body["group_name"], "members": []} - return 201, res("user_group", api.groups[gid]) + api._groups[gid] = {"id": gid, "location_id": lid, "group_name": body["group_name"], "members": []} + return 201, res("user_group", api._groups[gid]) - @self.route("GET", r"/locations/([^/]+)/user-groups/([^/]+)") + @self._route("GET", r"/locations/([^/]+)/user-groups/([^/]+)") def get_group(req, body, lid, gid): - g = api.groups[gid] + g = api._groups[gid] return 200, res("user_group", dict(g, members=[{"id": m} for m in g["members"]])) - @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/group-membership") + @self._route("GET", r"/locations/([^/]+)/users/([^/]+)/group-membership") def get_membership(req, body, lid, uid): return 200, {"data": [{"id": g["id"], "name": g["group_name"], "is_member": uid in g["members"]} - for g in api.groups.values() if g["location_id"] == lid]} + for g in api._groups.values() if g["location_id"] == lid]} - @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/group-membership") + @self._route("PUT", r"/locations/([^/]+)/users/([^/]+)/group-membership") def put_membership(req, body, lid, uid): - for g in api.groups.values(): + for g in api._groups.values(): if g["location_id"] != lid: continue if g["id"] in body["group_ids"] and uid not in g["members"]: @@ -528,52 +649,52 @@ def put_membership(req, body, lid, uid): return get_membership(req, None, lid, uid) # rules - @self.route("GET", r"/locations/([^/]+)/first-alert/rules") + @self._route("GET", r"/locations/([^/]+)/first-alert/rules") def list_rules(req, body, lid): - rows = [{k: v for k, v in r.items() if k != "triggers"} for r in api.rules.values() if r["location_id"] == lid] + rows = [{k: v for k, v in r.items() if k != "triggers"} for r in api._rules.values() if r["location_id"] == lid] return 200, page(rows, "first_alert_rule") - @self.route("POST", r"/locations/([^/]+)/first-alert/rules") + @self._route("POST", r"/locations/([^/]+)/first-alert/rules") def create_rule(req, body, lid): rid = new_id() r = dict(body, id=rid, location_id=lid, groups=[{"id": g} for g in body.get("group_ids", [])]) r.pop("group_ids", None) - api.rules[rid] = r + api._rules[rid] = r return 201, res("first_alert_rule", r) - @self.route("GET", r"/locations/([^/]+)/first-alert/rules/([^/]+)") + @self._route("GET", r"/locations/([^/]+)/first-alert/rules/([^/]+)") def get_rule(req, body, lid, rid): - return 200, res("first_alert_rule", api.rules[rid]) + return 200, res("first_alert_rule", api._rules[rid]) - @self.route("PATCH", r"/locations/([^/]+)/first-alert/rules/([^/]+)") + @self._route("PATCH", r"/locations/([^/]+)/first-alert/rules/([^/]+)") def patch_rule(req, body, lid, rid): body = dict(body) if "group_ids" in body: - api.rules[rid]["groups"] = [{"id": g} for g in body.pop("group_ids")] - api.rules[rid].update(body) - return 200, res("first_alert_rule", api.rules[rid]) + api._rules[rid]["groups"] = [{"id": g} for g in body.pop("group_ids")] + api._rules[rid].update(body) + return 200, res("first_alert_rule", api._rules[rid]) # connectors - @self.route("GET", r"/locations/([^/]+)/connectors") + @self._route("GET", r"/locations/([^/]+)/connectors") def list_conns(req, body, lid): - rows = [{k: v for k, v in c.items() if k != "config"} for c in api.connectors.values() if c["location_id"] == lid] + rows = [{k: v for k, v in c.items() if k != "config"} for c in api._connectors.values() if c["location_id"] == lid] return 200, page(rows) - @self.route("POST", r"/locations/([^/]+)/connectors") + @self._route("POST", r"/locations/([^/]+)/connectors") def create_conn(req, body, lid): if body["type"] not in [t["key"] for t in CONNECTOR_TYPES]: return 422, {"error": {"code": "VALIDATION_ERROR", "message": "unknown connector type"}} cid = new_id() - api.secrets_sent.append(dict(body["config"])) + api._secrets_sent.append(dict(body["config"])) public = {k: v for k, v in body["config"].items() if not any(w in k.lower() for w in SECRET_WORDS)} - api.connectors[cid] = {"id": cid, "location_id": lid, "name": body["name"], "type": body["type"], + api._connectors[cid] = {"id": cid, "location_id": lid, "name": body["name"], "type": body["type"], "status": "connecting", "_polls": 0, "config": dict(public, unexpected_field="redacted")} - return 202, {"data": api.connectors[cid]} + return 202, {"data": api._connectors[cid]} - @self.route("GET", r"/locations/([^/]+)/connectors/([^/]+)") + @self._route("GET", r"/locations/([^/]+)/connectors/([^/]+)") def get_conn(req, body, lid, cid): - c = api.connectors[cid] + c = api._connectors[cid] c["_polls"] += 1 if c["status"] == "connecting" and c["_polls"] >= 2 and api.connector_outcome not in ("stuck", "connecting"): c["status"] = api.connector_outcome @@ -584,224 +705,225 @@ def get_conn(req, body, lid, cid): c["status"] = "inactive" return 200, {"data": c} - @self.route("PATCH", r"/locations/([^/]+)/connectors/([^/]+)") + @self._route("PATCH", r"/locations/([^/]+)/connectors/([^/]+)") def patch_conn(req, body, lid, cid): - c = api.connectors[cid] + c = api._connectors[cid] if "name" in body: c["name"] = body["name"] if "config" in body: - api.secrets_sent.append(dict(body["config"])) + api._secrets_sent.append(dict(body["config"])) c["config"].update({k: v for k, v in body["config"].items() if not any(w in k.lower() for w in SECRET_WORDS)}) c["_key"] = body["config"].get("api_key") return 200, {"data": c} - @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/deactivate") + @self._route("POST", r"/locations/([^/]+)/connectors/([^/]+)/deactivate") def deact_conn(req, body, lid, cid): - api.connectors[cid]["status"] = "deactivating" - return 202, {"data": api.connectors[cid]} + api._connectors[cid]["status"] = "deactivating" + return 202, {"data": api._connectors[cid]} - @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/reactivate") + @self._route("POST", r"/locations/([^/]+)/connectors/([^/]+)/reactivate") def react_conn(req, body, lid, cid): - api.connectors[cid].update(status="connecting", _polls=0) - return 202, {"data": api.connectors[cid]} + api._connectors[cid].update(status="connecting", _polls=0) + return 202, {"data": api._connectors[cid]} # Insights Hub - @self.route("GET", r"/locations/([^/]+)/insights-hub/setup") + @self._route("GET", r"/locations/([^/]+)/insights-hub/setup") def get_ih(req, body, lid): - s = api.ih_setup.get(lid, {"connector_mappings": [], "group_access": []}) + s = api._ih_setup.get(lid, {"connector_mappings": [], "group_access": []}) return 200, {"data": {"type": "insights_hub_setup", "attributes": s}} - @self.route("POST", r"/locations/([^/]+)/insights-hub/setup") + @self._route("POST", r"/locations/([^/]+)/insights-hub/setup") def post_ih(req, body, lid): - api.ih_setup[lid] = {"connector_mappings": body["connector_mappings"], "group_access": body["group_access"]} - return 201, {"data": {"type": "insights_hub_setup", "attributes": api.ih_setup[lid]}} + api._ih_setup[lid] = {"connector_mappings": body["connector_mappings"], "group_access": body["group_access"]} + return 201, {"data": {"type": "insights_hub_setup", "attributes": api._ih_setup[lid]}} - @self.route("PATCH", r"/locations/([^/]+)/insights-hub/setup") + @self._route("PATCH", r"/locations/([^/]+)/insights-hub/setup") def patch_ih(req, body, lid): - s = api.ih_setup.setdefault(lid, {"connector_mappings": [], "group_access": []}) + s = api._ih_setup.setdefault(lid, {"connector_mappings": [], "group_access": []}) s.update(body) return 200, {"data": {"type": "insights_hub_setup", "attributes": s}} - @self.route("GET", r"/locations/([^/]+)/insights-hub/config") + @self._route("GET", r"/locations/([^/]+)/insights-hub/config") def get_ihc(req, body, lid): return 200, {"data": {"type": "insights_hub_config", - "attributes": {"monitor_all_numbers": api.ih_config.get(lid, False)}}} + "attributes": {"monitor_all_numbers": api._ih_config.get(lid, False)}}} - @self.route("PATCH", r"/locations/([^/]+)/insights-hub/config") + @self._route("PATCH", r"/locations/([^/]+)/insights-hub/config") def patch_ihc(req, body, lid): - api.ih_config[lid] = body["monitor_all_numbers"] + api._ih_config[lid] = body["monitor_all_numbers"] return get_ihc(req, None, lid) # First Alert config - @self.route("GET", r"/locations/([^/]+)/first-alert/config") + @self._route("GET", r"/locations/([^/]+)/first-alert/config") def get_fa(req, body, lid): - return 200, {"data": api.fa_config.get(lid, {"webhook_url": None, "connector_mappings": []})} + return 200, {"data": api._fa_config.get(lid, {"webhook_url": None, "connector_mappings": []})} - @self.route("PUT", r"/locations/([^/]+)/first-alert/config") + @self._route("PUT", r"/locations/([^/]+)/first-alert/config") def put_fa(req, body, lid): - api.fa_config[lid] = {"webhook_url": body.get("webhook_url"), + api._fa_config[lid] = {"webhook_url": body.get("webhook_url"), "connector_mappings": [dict(m, id=new_id()) for m in body["connector_mappings"]]} return get_fa(req, None, lid) # users - @self.route("GET", r"/companies/([^/]+)/users") + @self._route("GET", r"/companies/([^/]+)/users") def list_users(req, body, cid): q = (req.url.params.get("search") or "").lower() lid = req.url.params.get("location_id") - rows = [api._user_attrs(u) for u in api.users.values() if u["company_id"] == cid and q in u["email"].lower() + rows = [api._user_attrs(u) for u in api._users.values() if u["company_id"] == cid and q in u["email"].lower() and (not lid or lid in u["_locations"])] return 200, page(rows, "company_user") - @self.route("POST", r"/companies/([^/]+)/users") + @self._route("POST", r"/companies/([^/]+)/users") def create_user(req, body, cid): - assert req.headers.get("Idempotency-Key") - if any(u["email"].lower() == body["email"].lower() for u in api.users.values()): + if not req.headers.get("Idempotency-Key"): + return 400, {"error": {"code": "VALIDATION_ERROR", "message": "Idempotency-Key header is required"}} + if any(u["email"].lower() == body["email"].lower() for u in api._users.values()): return 409, {"error": {"code": "CONFLICT", "message": "A user with this email already exists"}} uid = new_id() - api.users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], + api._users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": {}, "invited_at": None} if body.get("send_invitation"): - api.invitations.append(uid) - api.users[uid]["invited_at"] = api.tick() - return 201, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}, + api._invitations.append(uid) + api._users[uid]["invited_at"] = api._tick() + return 201, {"data": {"type": "company_user", "attributes": api._user_attrs(api._users[uid])}, "meta": {"invitation_link": "https://app.example.com/accept?token=SECRET"}} - @self.route("GET", r"/companies/([^/]+)/users/([^/]+)") + @self._route("GET", r"/companies/([^/]+)/users/([^/]+)") def get_user(req, body, cid, uid): - return 200, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}} + return 200, {"data": {"type": "company_user", "attributes": api._user_attrs(api._users[uid])}} - @self.route("PATCH", r"/companies/([^/]+)/users/([^/]+)") + @self._route("PATCH", r"/companies/([^/]+)/users/([^/]+)") def patch_user(req, body, cid, uid): if "location_ids" in body: - api.users[uid]["_locations"] = list(body["location_ids"]) + api._users[uid]["_locations"] = list(body["location_ids"]) if "department" in body: - api.users[uid]["department"] = body["department"] + api._users[uid]["department"] = body["department"] return get_user(req, None, cid, uid) - @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/deactivate") + @self._route("POST", r"/companies/([^/]+)/users/([^/]+)/deactivate") def deact_user(req, body, cid, uid): - if api.users[uid]["status"] == "deactivated": + if api._users[uid]["status"] == "deactivated": return 409, {"error": {"code": "CONFLICT", "message": "User is already deactivated"}} - api.users[uid]["status"] = "deactivated" + api._users[uid]["status"] = "deactivated" return get_user(req, None, cid, uid) - @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/resend-invitation") + @self._route("POST", r"/companies/([^/]+)/users/([^/]+)/resend-invitation") def resend(req, body, cid, uid): - if api.users[uid]["status"] != "invited": + if api._users[uid]["status"] != "invited": return 409, {"error": {"code": "CONFLICT", "message": "User does not have a pending invitation"}} - api.invitations.append(uid) - api.users[uid]["invited_at"] = api.tick() + api._invitations.append(uid) + api._users[uid]["invited_at"] = api._tick() return 202, {"data": {"type": "invitation_resend", "attributes": {"user_id": uid, - "email": api.users[uid]["email"]}}} + "email": api._users[uid]["email"]}}} - @self.route("POST", r"/companies/([^/]+)/users/([^/]+)/reactivate") + @self._route("POST", r"/companies/([^/]+)/users/([^/]+)/reactivate") def react_user(req, body, cid, uid): - api.users[uid]["status"] = "active" + api._users[uid]["status"] = "active" return get_user(req, None, cid, uid) - @self.route("GET", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") + @self._route("GET", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") def get_maps(req, body, cid, uid): - return 200, {"data": api.mappings.get(uid, [])} + return 200, {"data": api._mappings.get(uid, [])} - @self.route("PUT", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") + @self._route("PUT", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") def put_maps(req, body, cid, uid): for m in body["mappings"]: - if api.connectors.get(m["connector_id"], {}).get("status") not in ("active", "connected"): + if api._connectors.get(m["connector_id"], {}).get("status") not in ("active", "connected"): return 422, {"error": {"code": "VALIDATION_ERROR", "message": "connector not found or inactive"}} for m in body["mappings"]: # one extension, one location - lid = api.connectors[m["connector_id"]]["location_id"] - for other, maps in api.mappings.items(): + lid = api._connectors[m["connector_id"]]["location_id"] + for other, maps in api._mappings.items(): if other == uid: continue for om in maps: - olid = api.connectors.get(om["connector_id"], {}).get("location_id") + olid = api._connectors.get(om["connector_id"], {}).get("location_id") clash = set(om["monitored_numbers"]) & set(m["monitored_numbers"]) if olid != lid and clash: return 409, {"error": {"code": "CONFLICT", "message": f"Extension {sorted(clash)[0]} is monitored at another location"}} - api.mappings[uid] = body["mappings"] + api._mappings[uid] = body["mappings"] return 200, {"data": body["mappings"]} - @self.route("GET", r"/locations/([^/]+)/users") + @self._route("GET", r"/locations/([^/]+)/users") def list_loc_users(req, body, lid): - return 200, page([api._loc_user(u, lid) for u in api.location_users(lid)], "location_user") + return 200, page([api._loc_user(u, lid) for u in api._location_users(lid)], "location_user") - @self.route("GET", r"/locations/([^/]+)/users/([^/]+)") + @self._route("GET", r"/locations/([^/]+)/users/([^/]+)") def get_loc_user(req, body, lid, uid): - return 200, {"data": {"type": "location_user", "attributes": api._loc_user(api.users[uid], lid)}} + return 200, {"data": {"type": "location_user", "attributes": api._loc_user(api._users[uid], lid)}} - @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/enable") + @self._route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/enable") def enable(req, body, lid, uid, key): api.products(uid, lid).add(key) return 200, {"data": {"product_key": key, "enabled": True}} - @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/disable") + @self._route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/disable") def disable(req, body, lid, uid, key): api.products(uid, lid).discard(key) return 200, {"data": {"product_key": key, "enabled": False}} - @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/first-alert/email-preferences") + @self._route("PUT", r"/locations/([^/]+)/users/([^/]+)/first-alert/email-preferences") def email_prefs(req, body, lid, uid): - api.email_prefs[(lid, uid)] = body + api._email_prefs[(lid, uid)] = body return 200, {"emailNotifications": {"masterEnabled": body["masterEnabled"], "alerts": []}} - @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/first-alert/notification-preferences") + @self._route("GET", r"/locations/([^/]+)/users/([^/]+)/first-alert/notification-preferences") def get_prefs(req, body, lid, uid): - master = api.email_prefs.get((lid, uid), {"masterEnabled": True})["masterEnabled"] + master = api._email_prefs.get((lid, uid), {"masterEnabled": True})["masterEnabled"] alerts = [{"alertId": r["id"], "alertName": r["name"], "emailEnabled": master} - for r in api.rules.values() if r["location_id"] == lid] + for r in api._rules.values() if r["location_id"] == lid] return 200, {"emailNotifications": {"masterEnabled": master, "alerts": alerts}, "digest": {"enabled": False}, "webhook": {"url": None}} # conversation data (frontline) - @self.route("GET", r"/locations") + @self._route("GET", r"/locations") def visible_locations(req, body): - return 200, page(api.visible_locations, "location") + return 200, page(api._visible_locations, "location") - @self.route("GET", r"/calls") + @self._route("GET", r"/calls") def list_calls(req, body): if api._request_role != "frontline_user": # administrator logins get empty lists, as on the API return api._paged(req, [], "calls", {"total_calls": 0, "missed_calls": 0}) lid = req.url.params.get("location_id") q = req.url.params.get("search") - rows = [r for r in api.call_rows if (not lid or r.get("location_id") in lid.split(",")) + rows = [r for r in api._call_rows if (not lid or r.get("location_id") in lid.split(",")) and (not q or q in (r.get("caller_number") or "") + (r.get("summary") or ""))] return api._paged(req, rows, "calls", {"total_calls": len(rows), "missed_calls": 0}) - @self.route("GET", r"/calls/([^/]+)") + @self._route("GET", r"/calls/([^/]+)") def get_call(req, body, cid): - if cid not in api.call_details: + if cid not in api._call_details: return 404, {"error": {"code": "NOT_FOUND", "message": "not found"}} - return 200, {"data": api.call_details[cid]} + return 200, {"data": api._call_details[cid]} - @self.route("GET", r"/calls/([^/]+)/transcript") + @self._route("GET", r"/calls/([^/]+)/transcript") def get_transcript(req, body, cid): return 200, {"data": {"transcript": [{"time": 0.0, "speaker": "Speaker 1", "name": "Sam", "text": "Hello"}]}} - @self.route("GET", r"/alerts") + @self._route("GET", r"/alerts") def list_alerts(req, body): if api._request_role != "frontline_user": return api._paged(req, [], "alerts", {"total": 0}) # as published: caller or callee name or number, summary text, or an exact lowercase alert id q = (req.url.params.get("search") or "").lower() fields = ("caller_name", "caller_number", "callee_name", "callee_number", "summary") - rows = [a for a in api.alert_rows if not q or a["id"] == q + rows = [a for a in api._alert_rows if not q or a["id"] == q or any(q in str(a.get(f) or "").lower() for f in fields)] return api._paged(req, rows, "alerts", {"total": len(rows)}) - @self.route("GET", r"/tasks") + @self._route("GET", r"/tasks") def list_tasks(req, body): if api._request_role != "frontline_user": return 200, {"data": [], "meta": {"has_more": False, "next_cursor": None}} st = req.url.params.get("status") - rows = [t for t in api.task_rows if st != "open" or t["status"] in ("pending", "in_progress", "overdue")] + rows = [t for t in api._task_rows if st != "open" or t["status"] in ("pending", "in_progress", "overdue")] return 200, {"data": rows, "meta": {"has_more": False, "next_cursor": None}} - @self.route("GET", r"/insights/dashboard") + @self._route("GET", r"/insights/dashboard") def insights(req, body): - return 200, {"data": api.insights} + return 200, {"data": api._insights} def _paged(self, req: httpx.Request, rows: List[Dict[str, Any]], key: str, summary: Dict[str, Any]): limit = int(req.url.params.get("limit") or 50) @@ -820,5 +942,87 @@ def _user_attrs(self, u: Dict[str, Any]) -> Dict[str, Any]: def _loc_user(self, u: Dict[str, Any], lid: str) -> Dict[str, Any]: return {"id": u["id"], "email": u["email"], "role": u["role"], "status": u["status"], "location_id": lid, "enabled_products": sorted(u["_products"].get(lid, set())), - "groups": [g["group_name"] for g in self.groups.values() + "groups": [g["group_name"] for g in self._groups.values() if g["location_id"] == lid and u["id"] in g["members"]]} + + +NETWORK_FAILURES = ("connect", "read_timeout", "write_timeout", "undecodable") +_JSON_TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict} + + +def _format_problem(fmt: Optional[str], value: str) -> Optional[str]: + if fmt == "uuid" and not _spec.is_uuid(value): + return "not a UUID" + if fmt == "date-time": + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return "not an RFC 3339 date-time" + if parsed.tzinfo is None: + return "a date-time needs a time zone" + if fmt == "date": + try: + datetime.strptime(value, "%Y-%m-%d") + except ValueError: + return "not a date (YYYY-MM-DD)" + return None + + +def _value_problem(schema: Mapping[str, Any], value: Any, items: bool = False) -> Optional[str]: + """Type, enum and format of one JSON value (and of each item of a list, one level down).""" + if not schema: + return None + types = schema.get("type") + types = [types] if isinstance(types, str) else list(types or []) + if value is None: + return None if (not types or "null" in types) else "must not be null" + if types: + ok = False + for t in types: + py = _JSON_TYPES.get(t) + if py is None: + continue + if t in ("integer", "number") and isinstance(value, bool): + continue + if isinstance(value, py): + ok = True + if not ok: + return f"must be {' or '.join(t for t in types if t != 'null')}" + if "enum" in schema and value not in schema["enum"]: + return f"must be one of {schema['enum']}" + if isinstance(value, str): + problem = _format_problem(schema.get("format"), value) + if problem: + return problem + if items and isinstance(value, list) and schema.get("items"): + item_schema = _spec._resolve(schema["items"]) + for v in value: + problem = _value_problem(item_schema, v) + if problem: + return f"item {v!r}: {problem}" + return None + + +def _query_problem(q: Mapping[str, Any], raw: str) -> Optional[str]: + """A query value as sent (text) against its published parameter.""" + t = q.get("type") + values = raw.split(",") if t == "array" else [raw] + item = q.get("items") or {} if t == "array" else q + for v in values: + it = item.get("type") + if it == "integer": + try: + n = int(v) + except ValueError: + return "must be a whole number" + if "minimum" in item and n < item["minimum"] or "maximum" in item and n > item["maximum"]: + return f"must be from {item.get('minimum')} to {item.get('maximum')}" + continue + if it == "boolean" and v not in ("true", "false"): + return 'must be "true" or "false"' + if "enum" in item and v not in item["enum"]: + return f"must be one of {item['enum']}" + problem = _format_problem(item.get("format"), v) + if problem: + return problem + return None diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index aa3fc79..e0fb739 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -39,15 +39,15 @@ def person(n): def rule(api, lid, name): - return next(r for r in api.rules.values() if r["location_id"] == lid and r["name"] == name) + return next(r for r in api._rules.values() if r["location_id"] == lid and r["name"] == name) def invariants(api): """Monitor-all off everywhere, no alert email on for anyone, no rules at Management.""" - assert not any(api.ih_config.values()) - assert all(p["masterEnabled"] is False for p in api.email_prefs.values()) - mgmt = [lid for lid, loc in api.locations.items() if loc["location_name"].endswith(" - Management")] - assert not [r for r in api.rules.values() if r["location_id"] in mgmt] + assert not any(api._ih_config.values()) + assert all(p["masterEnabled"] is False for p in api._email_prefs.values()) + mgmt = [lid for lid, loc in api._locations.items() if loc["location_name"].endswith(" - Management")] + assert not [r for r in api._rules.values() if r["location_id"] in mgmt] @pytest.fixture @@ -78,16 +78,16 @@ def test_create_follows_the_setup_flow(api, client): pos = -1 for m, pat in order: pos = next(i for i, (mm, pp) in enumerate(seq) if mm == m and re.match("^" + pat + "$", pp) and i > pos) - company = api.companies[cust.company_id] + company = api._companies[cust.company_id] assert company["mfa_enforced"] is False assert company["enabled_products"] == ["after-call-copilot", "first-alert-copilot", "insights-hub"] team, mgmt = cust.teams[0], cust.management assert (team.name, team.kind, mgmt.name, mgmt.kind) == ("Riverbend - Main", "team", MGMT, "management") assert api.count("POST", r"/companies/[^/]+/locations") == 2 # five groups on the team, the weekly reports group at Management - assert sorted(g["group_name"] for g in api.groups.values() if g["location_id"] == team.location_id) == \ + assert sorted(g["group_name"] for g in api._groups.values() if g["location_id"] == team.location_id) == \ sorted(TEAM_GROUPS.values()) - assert [g["group_name"] for g in api.groups.values() if g["location_id"] == mgmt.location_id] == \ + assert [g["group_name"] for g in api._groups.values() if g["location_id"] == mgmt.location_id] == \ ["Insights Hub Weekly Reports"] # three rules, switched off, each routed to its group, at the documented levels and priorities ct, uc, ls = (rule(api, team.location_id, n) for n in ("Customer Threat", "Upset Customer", "Low Sentiment")) @@ -100,24 +100,24 @@ def test_create_follows_the_setup_flow(api, client): assert ct["groups"] == [{"id": team.groups.customer_threats}] assert uc["groups"] == [{"id": team.groups.upset_customers}] assert ls["groups"] == [{"id": team.groups.low_sentiment_calls}] - assert not any(r["enabled"] for r in api.rules.values()) + assert not any(r["enabled"] for r in api._rules.values()) assert (team.rules.customer_threat, team.rules.upset_customer, team.rules.low_sentiment) == (ct["id"], uc["id"], ls["id"]) assert mgmt.rules == ic.TeamRules() # connector on each location, named " phone system" - names = sorted(c["name"] for c in api.connectors.values()) + names = sorted(c["name"] for c in api._connectors.values()) assert names == sorted([f"{MGMT} phone system", "Riverbend - Main phone system"]) assert team.connector_status == mgmt.connector_status == "active" and team.connector_id != mgmt.connector_id - assert api.ih_setup[team.location_id]["group_access"] == [team.groups.insights_hub_access] + assert api._ih_setup[team.location_id]["group_access"] == [team.groups.insights_hub_access] assert cust.sso_txt_record == {"name": "_ic-verify.riverbend.example.com", "value": "abc"} assert cust.pending == [] and "company" in cust.created - loc_body = next(b for m, p, b in api.bodies if m == "POST" and p.endswith("/locations")) + loc_body = next(b for m, p, b in api._bodies if m == "POST" and p.endswith("/locations")) assert set(loc_body) == {"location_name", "street", "city", "state", "country", "zipcode", "vertical_id", "enabled_products"} invariants(api) def test_rerun_writes_nothing(api, client, customer): - start = len(api.calls) + start = len(api._calls) again = client.accounts.create_customer(spec(company_id=customer.company_id)) assert api.writes_since(start) == [] assert again.company_id == customer.company_id and again.teams[0].location_id == customer.teams[0].location_id @@ -126,23 +126,23 @@ def test_rerun_writes_nothing(api, client, customer): def test_rerun_switches_monitor_all_off(api, client, customer): - api.ih_config[customer.teams[0].location_id] = True - api.ih_config[customer.management.location_id] = True + api._ih_config[customer.teams[0].location_id] = True + api._ih_config[customer.management.location_id] = True client.accounts.create_customer(spec()) - assert not any(api.ih_config.values()) + assert not any(api._ih_config.values()) def test_create_without_phrases_leaves_them_pending(api, client): cust = client.accounts.create_customer(spec(alerts=None)) team = cust.teams[0] assert cust.pending == ["customer_threat", "upset_customer"] - assert [r["name"] for r in api.rules.values()] == ["Low Sentiment"] - assert len([g for g in api.groups.values() if g["location_id"] == team.location_id]) == 5 + assert [r["name"] for r in api._rules.values()] == ["Low Sentiment"] + assert len([g for g in api._groups.values() if g["location_id"] == team.location_id]) == 5 changed = client.accounts.set_alerts(cust, ALERTS) assert len(changed) == 2 and cust.pending == [] assert rule(api, team.location_id, "Customer Threat")["triggers"][1]["config"]["keywords"] == THREAT assert client.accounts.get_customer(cust.company_id).pending == [] - start = len(api.calls) + start = len(api._calls) assert client.accounts.set_alerts(cust, ALERTS) == [] and api.writes_since(start) == [] @@ -179,11 +179,11 @@ def test_set_alerts_keeps_on_off_state(api, client, customer): def test_inactive_company_needs_reactivate(api, client, customer): - api.companies[customer.company_id]["is_active"] = False + api._companies[customer.company_id]["is_active"] = False with pytest.raises(ic.InvalidRequestError): client.accounts.create_customer(spec()) client.accounts.create_customer(spec(reactivate=True)) - assert api.companies[customer.company_id]["is_active"] + assert api._companies[customer.company_id]["is_active"] def test_management_name_is_reserved(api, client): @@ -193,7 +193,7 @@ def test_management_name_is_reserved(api, client): def test_user_login_is_refused(api): - api.role = "frontline_user" + api._role = "frontline_user" with pytest.raises(ic.WrongLoginError) as e: api.client().accounts.create_customer(spec()) assert "administrator" in str(e.value) and api.writes_since() == [] @@ -204,7 +204,7 @@ def test_user_login_is_refused(api): def add_company(api, name, email): cid = new_id() - api.companies[cid] = {"id": cid, "company_name": name, "primary_admin_contact_email": email, + api._companies[cid] = {"id": cid, "company_name": name, "primary_admin_contact_email": email, "reseller_id": RESELLER, "is_active": True, "mfa_enforced": True, "enabled_products": ["after-call-copilot"]} return cid @@ -223,7 +223,7 @@ def test_same_name_and_contact_is_reused(api, client): cust = client.accounts.create_customer(spec()) assert cust.company_id == cid and "company" in cust.existing assert api.count("POST", r"/resellers/[^/]+/companies") == 0 - assert api.companies[cid]["enabled_products"] == ["after-call-copilot", "first-alert-copilot", "insights-hub"] + assert api._companies[cid]["enabled_products"] == ["after-call-copilot", "first-alert-copilot", "insights-hub"] def test_explicit_company_id_wins(api, client): @@ -250,11 +250,11 @@ def test_connector_of_another_type_from_type_and_config(api, caplog): "api_token": "T0KEN-SECRET"}) c = api.client() cust = c.accounts.create_customer(spec(connector=other)) - assert {x["type"] for x in api.connectors.values()} == {"examplepbx"} - assert all(x["config"]["host"] == "pbx.example.com" for x in api.connectors.values()) - assert api.secrets_sent[0] == {"host": "pbx.example.com", "domain": "rb.example", "api_token": "T0KEN-SECRET"} + assert {x["type"] for x in api._connectors.values()} == {"examplepbx"} + assert all(x["config"]["host"] == "pbx.example.com" for x in api._connectors.values()) + assert api._secrets_sent[0] == {"host": "pbx.example.com", "domain": "rb.example", "api_token": "T0KEN-SECRET"} assert "T0KEN-SECRET" not in repr(cust) + caplog.text - start = len(api.calls) + start = len(api._calls) c.accounts.create_customer(spec(connector=other, company_id=cust.company_id)) assert api.writes_since(start) == [] @@ -289,7 +289,7 @@ def test_connector_error_is_recorded_and_a_fixed_key_repairs_it(api): again = c.accounts.create_customer(spec(connector=fixed, company_id=first.company_id, sso_domain=None)) assert again.teams[0].connector_id == first.teams[0].connector_id assert again.teams[0].connector_status == "active" - assert api.connectors[first.teams[0].connector_id]["_key"] == "NEW-KEY" + assert api._connectors[first.teams[0].connector_id]["_key"] == "NEW-KEY" assert api.count("POST", r"/locations/[^/]+/connectors") == 2 # never a second one per location @@ -298,15 +298,15 @@ def test_same_domain_under_another_name_is_reused(api, client, customer): again = client.accounts.create_customer(spec(connector=renamed, company_id=customer.company_id)) assert again.teams[0].connector_id == customer.teams[0].connector_id assert api.count("POST", r"/locations/[^/]+/connectors") == 2 - assert api.connectors[customer.teams[0].connector_id]["name"] == "Phones" + assert api._connectors[customer.teams[0].connector_id]["name"] == "Phones" def test_set_connector_attaches_one_later_and_refuses_an_active_one(api, client): cust = client.accounts.create_customer(spec(connector=None, sso_domain=None)) - assert cust.teams[0].connector_id is None and api.connectors == {} + assert cust.teams[0].connector_id is None and api._connectors == {} teams = client.accounts.set_connector(cust, CONN) assert [t.kind for t in teams] == ["team", "management"] and all(t.connector_status == "active" for t in teams) - start = len(api.calls) + start = len(api._calls) client.accounts.set_connector(cust, CONN) assert api.writes_since(start) == [] with pytest.raises(ic.InvalidRequestError): @@ -323,9 +323,9 @@ def test_add_team_copies_the_first_teams_alerts(api, client, customer): assert east.kind == "team" and east.connector_status == "active" and len(customer.teams) == 2 assert rule(api, east.location_id, "Customer Threat")["triggers"][1]["config"]["keywords"] == THREAT assert rule(api, east.location_id, "Upset Customer")["triggers"][0]["config"]["threshold"] == -35 - assert not any(r["enabled"] for r in api.rules.values() if r["location_id"] == east.location_id) - assert len([g for g in api.groups.values() if g["location_id"] == east.location_id]) == 5 - start = len(api.calls) + assert not any(r["enabled"] for r in api._rules.values() if r["location_id"] == east.location_id) + assert len([g for g in api._groups.values() if g["location_id"] == east.location_id]) == 5 + start = len(api._calls) again = client.accounts.add_team(customer.company_id, EAST, EAST_CONN) assert again.location_id == east.location_id and api.writes_since(start) == [] with pytest.raises(ic.InvalidRequestError): @@ -348,10 +348,10 @@ def test_get_customer_reads_the_layout(api, client, customer): def test_an_old_layout_is_reported_with_what_is_missing(api, client): cid = add_company(api, COMPANY, "pat@example.com") lid = new_id() - api.locations[lid] = {"id": lid, "company_id": cid, "location_name": "Riverbend - Main", "is_active": True, - "created_at": api.tick()} + api._locations[lid] = {"id": lid, "company_id": cid, "location_name": "Riverbend - Main", "is_active": True, + "created_at": api._tick()} gid = new_id() - api.groups[gid] = {"id": gid, "location_id": lid, "group_name": "Manager Alerts", "members": []} + api._groups[gid] = {"id": gid, "location_id": lid, "group_name": "Manager Alerts", "members": []} got = client.accounts.get_customer(cid) assert "management location" in got.pending and "customer_threat" in got.pending assert "Riverbend - Main: group Customer Threats" in got.pending @@ -364,19 +364,19 @@ def test_an_old_layout_is_reported_with_what_is_missing(api, client): def test_add_base_user(api, client, customer): team = customer.teams[0] mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) - start = len(api.calls) + start = len(api._calls) bu = client.accounts.add_base_user(customer, person(1), team=team, line="2101") writes = api.writes_since(start) assert writes[0][1].endswith("/users") and writes[-1][1].endswith(f"/{bu.user_id}/resend-invitation") - create = next(b for m, p, b in api.bodies if m == "POST" and p.endswith("/users") and b["email"] == "user1@example.com") + create = next(b for m, p, b in api._bodies if m == "POST" and p.endswith("/users") and b["email"] == "user1@example.com") assert create["send_invitation"] is False and create["location_ids"] == [team.location_id] assert api.products(bu.user_id, team.location_id) == {"after-call-copilot"} - assert api.mappings[bu.user_id] == [{"connector_id": team.connector_id, "monitored_numbers": ["2101"]}] + assert api._mappings[bu.user_id] == [{"connector_id": team.connector_id, "monitored_numbers": ["2101"]}] assert api.fa_numbers(team.location_id) == ["2101"] and api.ih_numbers(team.location_id) == ["2101"] assert api.numbers(mgr.user_id, team.connector_id) == ["2101"] - assert api.email_prefs[(team.location_id, bu.user_id)]["masterEnabled"] is False - assert bu.created and bu.invited and bu.license == "base_user" and api.invitations == [bu.user_id] - start = len(api.calls) + assert api._email_prefs[(team.location_id, bu.user_id)]["masterEnabled"] is False + assert bu.created and bu.invited and bu.license == "base_user" and api._invitations == [bu.user_id] + start = len(api._calls) again = client.accounts.add_base_user(customer, person(1), team=team, line="2101") assert again.user_id == bu.user_id and not again.created and not again.invited assert api.writes_since(start) == [] @@ -397,7 +397,7 @@ def test_add_base_manager(api, client, customer): assert mgr.user_id in api.group_members(team.location_id, name) assert mgr.user_id in api.group_members(mgmt.location_id, "Insights Hub Weekly Reports") assert "2001" not in api.fa_numbers(team.location_id) + api.ih_numbers(team.location_id) - assert api.email_prefs[(team.location_id, mgr.user_id)]["masterEnabled"] is False + assert api._email_prefs[(team.location_id, mgr.user_id)]["masterEnabled"] is False other = client.accounts.add_base_manager(customer, person(4), teams=[team]) assert other.user_id not in api.group_members(mgmt.location_id, "Insights Hub Weekly Reports") with pytest.raises(TypeError): @@ -409,15 +409,15 @@ def test_activate_alerts_does_not_need_a_manager(api, client, customer): team = customer.teams[0] out = client.accounts.activate_alerts(customer) # a team with no manager: alerts go on, and it is reported assert len(out["switched_on"]) == 3 and out["no_manager"][0]["missing"] == list(ALERT_GROUPS) - assert all(r["enabled"] for r in api.rules.values()) + assert all(r["enabled"] for r in api._rules.values()) mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], invite=False) - api.groups[team.groups.upset_customers]["members"].remove(mgr.user_id) + api._groups[team.groups.upset_customers]["members"].remove(mgr.user_id) out = client.accounts.activate_alerts(customer) assert out["switched_on"] == [] and out["no_manager"][0]["missing"] == ["Upset Customers"] - api.groups[team.groups.upset_customers]["members"].append(mgr.user_id) + api._groups[team.groups.upset_customers]["members"].append(mgr.user_id) out = client.accounts.activate_alerts(customer) assert out == {"switched_on": [], "no_manager": []} - start = len(api.calls) + start = len(api._calls) assert client.accounts.activate_alerts(customer)["switched_on"] == [] and api.writes_since(start) == [] @@ -429,9 +429,9 @@ def test_mapping_failure_raises_account_error_and_rerun_continues(api): c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="2101") err = e.value assert err.step == "line" and isinstance(err.cause, ic.ExtensionMappingError) - assert err.result.user_id in api.users and api.invitations == [] - assert not api.fa_config.get(cust.teams[0].location_id) - api.connectors[cust.teams[0].connector_id]["status"] = "active" # the connector is fixed + assert err.result.user_id in api._users and api._invitations == [] + assert not api._fa_config.get(cust.teams[0].location_id) + api._connectors[cust.teams[0].connector_id]["status"] = "active" # the connector is fixed again = c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="2101") assert again.user_id == err.result.user_id and not again.created and again.invited @@ -441,8 +441,8 @@ def test_integration_user(api, client, customer): a = client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], invite=False) integ = client.accounts.add_integration_user(customer, person(9), invite=False) - assert api.users[integ.user_id]["department"] == "integration" and integ.lines == ["2101"] - assert api.email_prefs[(team.location_id, integ.user_id)]["masterEnabled"] is False + assert api._users[integ.user_id]["department"] == "integration" and integ.lines == ["2101"] + assert api._email_prefs[(team.location_id, integ.user_id)]["masterEnabled"] is False client.accounts.add_base_user(customer, person(3), team=team, line="2103", invite=False) assert sorted(api.numbers(integ.user_id)) == ["2101", "2103"] by = client.accounts.license_report(customer) @@ -464,16 +464,16 @@ def test_remove_user_releases_only_a_line_no_one_else_holds(api, client, custome mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) out = client.accounts.remove_user(customer, a.user_id) assert out["released_lines"] == ["2101"] and out["deactivated"] - assert api.users[a.user_id]["status"] == "deactivated" and api.mappings[a.user_id] == [] + assert api._users[a.user_id]["status"] == "deactivated" and api._mappings[a.user_id] == [] assert api.numbers(mgr.user_id, team.connector_id) == ["2103"] assert api.fa_numbers(team.location_id) == ["2103"] and api.ih_numbers(team.location_id) == ["2103"] - start = len(api.calls) + start = len(api._calls) client.accounts.remove_user(customer, a.user_id) assert api.writes_since(start) == [] out = client.accounts.remove_user(customer, mgr.user_id) assert out["license"] == "base_manager" and out["released_lines"] == [] assert api.fa_numbers(team.location_id) == ["2103"] - assert all(mgr.user_id not in g["members"] for g in api.groups.values()) + assert all(mgr.user_id not in g["members"] for g in api._groups.values()) def test_remove_user_keep_lines(api, client, customer): @@ -489,7 +489,7 @@ def test_sync_lines(api, client, customer): mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) client.first_alert.set_monitored_numbers(team.location_id, team.connector_id, ["2199"]) client.users.set_numbers(customer.company_id, mgr.user_id, team.connector_id, ["2199"]) - start = len(api.calls) + start = len(api._calls) diff = client.accounts.sync_lines(customer, dry_run=True) assert api.writes_since(start) == [] and not diff["applied"] d = diff["teams"][team.location_id] @@ -499,7 +499,7 @@ def test_sync_lines(api, client, customer): assert api.fa_numbers(team.location_id) == ["2101"] assert api.numbers(mgr.user_id, team.connector_id) == ["2101"] assert api.numbers(mgr.user_id, customer.management.connector_id) == ["2001"] # own line kept - start = len(api.calls) + start = len(api._calls) client.accounts.sync_lines(customer) assert api.writes_since(start) == [] @@ -508,7 +508,7 @@ def test_send_invitations(api, client, customer): team = customer.teams[0] a = client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) b = client.accounts.add_base_user(customer, person(3), team=team, line="2103") - assert api.invitations == [b.user_id] + assert api._invitations == [b.user_id] assert client.accounts.send_invitations(customer) == [a.user_id] assert client.accounts.send_invitations(customer) == [] assert client.accounts.send_invitations(customer, user_ids=[b.user_id]) == [b.user_id] @@ -521,18 +521,18 @@ def test_offboard_customer(api, client, customer): integ = client.accounts.add_integration_user(customer, person(9), invite=False) client.intelligence.set_after_call_webhook(team.location_id, "https://hooks.example.com/ic/" + "x" * 32) client.intelligence.set_first_alert_webhook(team.location_id, "https://hooks.example.com/fa/" + "y" * 32) - start = len(api.calls) + start = len(api._calls) out = client.accounts.offboard_customer(customer) kinds = [("automation" in p and "hook") or ("first-alert/config" in p and "fa") or ("/connectors/" in p and "conn") or ("/users/" in p and "user") or ("/deactivate" in p and "company") for _, p in api.writes_since(start)] assert kinds == ["hook", "fa", "conn", "conn", "user", "company"] - assert api.after_call_hooks[team.location_id]["enabled"] is False - assert api.fa_config[team.location_id]["webhook_url"] is None and api.fa_numbers(team.location_id) == ["2101"] - assert all(c["status"] == "inactive" for c in api.connectors.values()) + assert api._after_call_hooks[team.location_id]["enabled"] is False + assert api._fa_config[team.location_id]["webhook_url"] is None and api.fa_numbers(team.location_id) == ["2101"] + assert all(c["status"] == "inactive" for c in api._connectors.values()) assert out["integration_users_deactivated"] == [integ.user_id] - assert api.users[mgr.user_id]["status"] != "deactivated" and not api.companies[customer.company_id]["is_active"] - start = len(api.calls) + assert api._users[mgr.user_id]["status"] != "deactivated" and not api._companies[customer.company_id]["is_active"] + start = len(api._calls) again = client.accounts.offboard_customer(customer) assert not again["company_deactivated"] and again["connectors_deactivated"] == [] and api.writes_since(start) == [] @@ -549,7 +549,7 @@ def test_acceptance_scenario(api, client): main, mgmt = cust.teams[0], cust.management invariants(api) # re-run: no writes - start = len(api.calls) + start = len(api._calls) acc.create_customer(spec(company_id=cust.company_id)) assert api.writes_since(start) == [] # add team @@ -571,26 +571,26 @@ def test_acceptance_scenario(api, client): assert "2103" not in api.fa_numbers(main.location_id) + api.ih_numbers(main.location_id) assert api.numbers(dee.user_id, main.connector_id) == ["2101"] assert ben.user_id in api.group_members(main.location_id, "Customer Threats") - start = len(api.calls) + start = len(api._calls) acc.change_license(cust, ben.user_id, "base_manager", teams=[main]) assert api.writes_since(start) == [] # change license: Base Manager -> Base User (keeps one team and their own line) down = acc.change_license(cust, ben.user_id, "base_user", teams=[main]) assert down.license == "base_user" and down.lines == ["2103"] - assert api.mappings[ben.user_id] == [{"connector_id": main.connector_id, "monitored_numbers": ["2103"]}] + assert api._mappings[ben.user_id] == [{"connector_id": main.connector_id, "monitored_numbers": ["2103"]}] assert api.products(ben.user_id, main.location_id) == {"after-call-copilot"} - assert mgmt.location_id not in api.users[ben.user_id]["_locations"] - assert all(ben.user_id not in g["members"] for g in api.groups.values()) + assert mgmt.location_id not in api._users[ben.user_id]["_locations"] + assert all(ben.user_id not in g["members"] for g in api._groups.values()) assert sorted(api.fa_numbers(main.location_id)) == ["2101", "2103"] assert sorted(api.numbers(dee.user_id, main.connector_id)) == ["2101", "2103"] invariants(api) # move a Base User to another team moved = acc.move_user(cust, ana.user_id, from_team=main, to_team=east) assert moved.teams == [east.location_id] and "Call history stays with Riverbend - Main" in moved.notes[0] - assert api.mappings[ana.user_id] == [{"connector_id": east.connector_id, "monitored_numbers": ["2101"]}] + assert api._mappings[ana.user_id] == [{"connector_id": east.connector_id, "monitored_numbers": ["2101"]}] assert api.fa_numbers(main.location_id) == ["2103"] and sorted(api.fa_numbers(east.location_id)) == ["2101", "3101"] assert sorted(api.numbers(dee.user_id, east.connector_id)) == ["2101", "3101"] - start = len(api.calls) + start = len(api._calls) acc.move_user(cust, ana.user_id, from_team=main, to_team=east) assert api.writes_since(start) == [] # move: swap one of a Base Manager's teams @@ -604,7 +604,7 @@ def test_acceptance_scenario(api, client): assert api.numbers(cy.user_id) == ["3109"] and "3101" not in api.fa_numbers(east.location_id) assert "3109" in api.fa_numbers(east.location_id) and "3109" in api.ih_numbers(east.location_id) assert "3109" in api.numbers(dee.user_id, east.connector_id) and "3101" not in api.numbers(dee.user_id) - start = len(api.calls) + start = len(api._calls) acc.change_line(cust, cy.user_id, "3101", "3109") assert api.writes_since(start) == [] # remove @@ -613,7 +613,7 @@ def test_acceptance_scenario(api, client): # activate act = acc.activate_alerts(cust) assert len(act["switched_on"]) == 6 and act["no_manager"] == [] - assert all(r["enabled"] for r in api.rules.values()) + assert all(r["enabled"] for r in api._rules.values()) # report rep = acc.license_report(cust) assert (rep["base_user"], rep["base_manager"], rep["integration"], rep["other"], rep["teams"]) == (2, 2, 0, 0, 2) diff --git a/tests/unit/test_conversations.py b/tests/unit/test_conversations.py index 1d7da63..cb25a49 100644 --- a/tests/unit/test_conversations.py +++ b/tests/unit/test_conversations.py @@ -30,23 +30,23 @@ def call_row(i=0, **kw): @pytest.fixture def api(): a = FakeAPI(role="frontline_user") - a.me_extra = {"email": "jordan.reyes@example.com", "first_name": "Jordan", "last_name": "Reyes", + a._me_extra = {"email": "jordan.reyes@example.com", "first_name": "Jordan", "last_name": "Reyes", "company_id": new_id(), "location_ids": [LOC]} - a.visible_locations = [{"id": LOC, "location_name": "Riverbend - Main"}, + a._visible_locations = [{"id": LOC, "location_name": "Riverbend - Main"}, {"id": MGMT, "location_name": "Riverbend Auto Group - Management"}] - a.call_rows = [call_row()] - a.call_details[CALL] = dict(call_row(), analysis={ + a._call_rows = [call_row()] + a._call_details[CALL] = dict(call_row(), analysis={ "summary": {"text": SUMMARY, "key_points": ["Billed twice"], "action_items": ["Refund"]}, "sentiment": {"overall": "negative"}, "topics": [{"name": "Billing"}]}, tasks=[{"id": new_id(), "title": "Call back", "status": "pending", "due_date": "2026-11-03"}], vcon={"recording_url": "https://media.example.com/rec?sig=SECRET", "recording_url_expires_at": "2026-11-02T18:41:07Z"}) - a.alert_rows = [{"id": ALERT, "call_id": CALL, "call_date": "2026-11-02T16:41:07Z", "caller_name": "Morgan Diaz", + a._alert_rows = [{"id": ALERT, "call_id": CALL, "call_date": "2026-11-02T16:41:07Z", "caller_name": "Morgan Diaz", "caller_number": "+15555550142", "callee_name": "Jordan Reyes", "callee_number": "2102", "summary": SUMMARY, "sentiment": "negative", "sentiment_score": -46, "keywords": ["Upset Customer"], "topics": []}] - a.task_rows = [{"id": new_id(), "title": "Call back", "status": "pending", "due_date": "2026-11-03", + a._task_rows = [{"id": new_id(), "title": "Call back", "status": "pending", "due_date": "2026-11-03", "call_id": CALL}, {"id": new_id(), "title": "Done", "status": "done", "call_id": CALL}] - a.insights = {"stats": {"total_calls": 10, "answered_calls": 8, "unanswered_calls": 2}, + a._insights = {"stats": {"total_calls": 10, "answered_calls": 8, "unanswered_calls": 2}, "topic_call_volumes": [{"name": "Billing", "slug": "billing", "call_count": 4}], "trending_topics": [{"name": "Billing", "slug": "billing", "call_count": 4, "percentage_change": 50, "previous_call_count": 2, "trend_data": []}, @@ -55,7 +55,7 @@ def api(): def data_requests(api): - return [p for _, p in api.calls if not p.endswith("/me")] + return [p for _, p in api._calls if not p.endswith("/me")] def test_caller_numbers_are_masked_by_default(api): @@ -111,7 +111,7 @@ def test_limits_are_enforced_before_any_request(api): def test_calls_follow_pages_up_to_the_limit(api): - api.call_rows = [call_row(i) for i in range(260)] + api._call_rows = [call_row(i) for i in range(260)] conv = api.client().conversations assert len(conv.calls(limit=150)) == 150 assert api.count("GET", r"/calls") == 2 @@ -120,12 +120,12 @@ def test_calls_follow_pages_up_to_the_limit(api): def test_day_window(api): api.client().conversations.calls(day=date(2026, 11, 2), team=LOC) - _, path, _ = api.bodies[-1] + _, path, _ = api._bodies[-1] assert path.endswith("/calls") def test_administrator_login_gets_wrong_login_error(api): - api.role = "reseller_admin" + api._role = "reseller_admin" conv = api.client().conversations for fn in (conv.calls, conv.me, conv.teams, conv.open_tasks, conv.alerts, lambda: conv.brief(CALL), lambda: conv.transcript(CALL), lambda: conv.caller_history("5555550142"), diff --git a/tests/unit/test_intelligence.py b/tests/unit/test_intelligence.py index dc369b7..5d17998 100644 --- a/tests/unit/test_intelligence.py +++ b/tests/unit/test_intelligence.py @@ -169,10 +169,14 @@ def test_parse_rejects_non_json(): def test_deduplicator_lru(): d = ic.Deduplicator(max_size=2) ev = ic.parse_after_call_event(EVENT) - assert not d.is_duplicate(ev) - assert d.is_duplicate(ev) - assert not d.is_duplicate("b") and not d.is_duplicate("c") - assert not d.is_duplicate(ev) # evicted + assert not d.seen(ev) + d.remember(ev) + assert d.seen(ev) + for n in (1, 2): + other = json.loads(json.dumps(ev.raw)) + other["call"]["id"] = f"0193b6d0-0000-7a3b-8c4d-00000000000{n}" + d.remember(other) + assert not d.seen(ev) # evicted def test_dedup_custom_store(): @@ -180,13 +184,16 @@ class Store: def __init__(self): self.keys = set() + def has(self, key): + return key in self.keys + def add(self, key): - if key in self.keys: - return False self.keys.add(key) - return True d = ic.Deduplicator(store=Store()) - assert not d.is_duplicate("x") and d.is_duplicate("x") + ev = ic.parse_after_call_event(EVENT) + assert not d.seen(ev) + d.remember(ev) + assert d.seen(ev) def test_get_recording_url_returns_only_link_and_expiry(): diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py index 3865774..db30a01 100644 --- a/tests/unit/test_policy.py +++ b/tests/unit/test_policy.py @@ -270,21 +270,63 @@ def test_deduplicator_rule(): body = json.loads(SAMPLE.read_text()) d = ic.Deduplicator() raw = json.dumps(body).encode() - assert d.is_duplicate(raw) is False - assert d.is_duplicate(raw) is True # identical re-delivery - assert d.is_duplicate(ic.parse_after_call_event(raw)) is True # the same delivery, parsed - assert d.is_duplicate(json.dumps(body, indent=2, sort_keys=True)) is True # formatting does not matter + assert d.seen(raw) is False + assert d.seen(raw) is False # seen() only checks: nothing is recorded until remember() + d.remember(raw) + assert d.seen(raw) is True # identical re-delivery + assert d.seen(ic.parse_after_call_event(raw)) is True # the same delivery, parsed + assert d.seen(json.dumps(body, indent=2, sort_keys=True)) is True # formatting does not matter + assert d.seen("\ufeff" + json.dumps(body)) is True and d.seen(b"\xef\xbb\xbf" + raw) is True # a BOM newer = json.loads(json.dumps(body)) newer["summary"]["text"] = "Updated summary." - assert d.is_duplicate(newer) is False # same call, newer data: never dropped + assert d.seen(newer) is False # same call, newer data: never dropped assert ic.upsert_key(newer) == body["call"]["id"] == d.upsert_key(raw) other = json.loads(json.dumps(body)) other["call"]["id"] = "0193b6d0-0000-7a3b-8c4d-000000000002" - assert d.is_duplicate(other) is False # different call + assert d.seen(other) is False # different call alert = {"alert_id": "0193b6e1-1e2f-7a3b-8c4d-5e6f7a8b9c02", "rule_name": "Upset Customer"} - assert d.is_duplicate(alert) is False and d.is_duplicate(json.dumps(alert)) is True - assert ic.upsert_key(alert) == alert["alert_id"] - assert d.is_duplicate("0193b6e1-alert") is False and d.is_duplicate("0193b6e1-alert") is True # a bare id + d.remember(alert) + assert d.seen(json.dumps(alert)) is True and ic.upsert_key(alert) == alert["alert_id"] + + +def test_an_id_alone_is_refused(): + d = ic.Deduplicator() + for bare in (json.loads(SAMPLE.read_text())["call"]["id"], "0193b6e1-alert"): + with pytest.raises(ic.InvalidRequestError) as e: + d.seen(bare) + assert "seen(event)" in str(e.value) + with pytest.raises(ic.InvalidRequestError): + d.remember(bare) + assert not hasattr(d, "is_duplicate") + + +def test_a_failed_store_is_processed_again_on_retry(): + """The receiver pattern: if seen -> 2xx; upsert; remember; 2xx. A storage failure answers 5xx unremembered.""" + d = ic.Deduplicator() + stored, fail = {}, {"next": True} + + def receive(body: bytes) -> int: + ev = ic.parse_after_call_event(body) + if d.seen(ev): + return 204 + try: + if fail["next"]: + fail["next"] = False + raise OSError("disk full") + stored[ic.upsert_key(ev)] = ev.raw + except OSError: + return 503 + d.remember(ev) + return 204 + raw = SAMPLE.read_bytes() + assert receive(raw) == 503 and stored == {} # the store failed: not remembered + assert receive(raw) == 204 and len(stored) == 1 # the sender's retry is processed + first = dict(next(iter(stored.values()))) + assert receive(raw) == 204 and next(iter(stored.values())) == first # exact re-delivery skipped + newer = json.loads(raw) + newer["summary"]["text"] = "The refund was approved." + assert receive(json.dumps(newer).encode()) == 204 + assert next(iter(stored.values()))["summary"]["text"] == "The refund was approved." # newer data replaces def test_deduplicator_uses_a_shared_store(): @@ -292,12 +334,13 @@ class Shared: def __init__(self): self.keys = set() + def has(self, key): + return key in self.keys + def add(self, key): - if key in self.keys: - return False self.keys.add(key) - return True store = Shared() a, b = ic.Deduplicator(store=store), ic.Deduplicator(store=store) raw = SAMPLE.read_bytes() - assert a.is_duplicate(raw) is False and b.is_duplicate(raw) is True + a.remember(raw) + assert b.seen(raw) is True diff --git a/tests/unit/test_request_counts.py b/tests/unit/test_request_counts.py index 26c4367..c9768fc 100644 --- a/tests/unit/test_request_counts.py +++ b/tests/unit/test_request_counts.py @@ -10,7 +10,8 @@ # helper -> (1-team customer, 10-team customer); each measured with a fresh client, so GET /me is included EXPECTED = { "create_customer": (35, 35), - "add_team (each further team)": (None, 21), + "add_team (2nd team)": (None, 21), + "add_team (10th team)": (None, 21), "create_customer, re-run": (19, 19), "add_base_user": (36, 90), "add_base_manager (every team)": (29, 137), @@ -36,14 +37,16 @@ def measure(teams: int) -> dict: start = len(api.requests) cust = api.client(role="admin").accounts.create_customer(_spec()) out["create_customer"] = len(api.requests) - start - if teams > 1: + out["add_team (2nd team)"] = out["add_team (10th team)"] = None + for i in range(1, teams): start = len(api.requests) api.client(role="admin").accounts.add_team(cust, ic.TeamSpec( - "Riverbend - Team 2", "101 River Rd", "Springfield", "IL", "US", "62701", "service-providers"), - ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend2.example.com", "example-key")) - out["add_team (each further team)"] = len(api.requests) - start - else: - out["add_team (each further team)"] = None + f"Riverbend - Team {i + 1}", f"{100 + i} River Rd", "Springfield", "IL", "US", "62701", "service-providers"), + ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", f"riverbend{i + 1}.example.com", "example-key")) + if i == 1: + out["add_team (2nd team)"] = len(api.requests) - start + if i == 9: + out["add_team (10th team)"] = len(api.requests) - start start = len(api.requests) api.client(role="admin").accounts.create_customer(ic.CustomerSpec(**{**vars(_spec()), "company_id": cust.company_id})) out["create_customer, re-run"] = len(api.requests) - start diff --git a/tests/unit/test_review_030.py b/tests/unit/test_review_030.py new file mode 100644 index 0000000..2cc12db --- /dev/null +++ b/tests/unit/test_review_030.py @@ -0,0 +1,303 @@ +"""Regression tests for the 0.3.0 review: refresh-token reuse, arguments read once, type checks, the +deadline, unsent failures, the testing module's failure knobs and strictness, First Alert ids, dates.""" +from __future__ import annotations + +import json +from datetime import date, datetime, timedelta, timezone + +import httpx +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.testing import FakeAPI + +UID = "0193b6d0-0000-7a3b-8c4d-000000000001" +BASE = "https://app.intelligence.cloud/api/v1" + + +def tok(n): + return {"access_token": f"A{n}", "refresh_token": f"R{n}", "expires_in": 900, + "user": {"id": UID, "role": "frontline_user"}} + + +def run_refresh(fail): + """The first renewal fails with ``fail``; returns what was sent to the auth endpoints.""" + sent = [] + + def h(r): + p = r.url.path + if p.endswith("/auth/login"): + sent.append("login") + return httpx.Response(200, json=tok(9)) + if p.endswith("/auth/refresh"): + sent.append(("refresh", json.loads(r.content)["refresh_token"])) + if len([s for s in sent if s != "login"]) == 1: + return fail(r) + return httpx.Response(200, json=tok(2)) + if r.headers["Authorization"] == "Bearer A1": + return httpx.Response(401, json={}) + return httpx.Response(200, json={"data": {"id": UID, "role": "frontline_user"}}) + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(h), sleep=lambda s: None, + token_store=ic.MemoryTokenStore(ic.Tokens("A1", "R1", expires_at=0))) + c.account.get_me() + return sent + + +def _raise(cls): + def f(r): + raise cls("x", request=r) + return f + + +# ---------------------------------------------------------------------- B1 + S6: renewal + + +@pytest.mark.parametrize("fail", [lambda r: httpx.Response(502, json={}), lambda r: httpx.Response(500, json={}), + _raise(httpx.ReadTimeout), _raise(httpx.WriteTimeout), + _raise(httpx.RemoteProtocolError)]) +def test_a_refresh_token_that_may_be_used_is_never_sent_again(fail): + assert run_refresh(fail) == [("refresh", "R1"), "login"] + + +@pytest.mark.parametrize("cls", [httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout, + httpx.LocalProtocolError, httpx.UnsupportedProtocol]) +def test_a_refresh_that_never_left_is_sent_again(cls): + assert run_refresh(_raise(cls)) == [("refresh", "R1"), ("refresh", "R1")] + + +@pytest.mark.parametrize("failure", [{"status": 502}, {"status": 503}, {"network": "read_timeout"}, + {"network": "write_timeout"}, {"network": "undecodable"}]) +def test_the_fake_catches_refresh_token_reuse(failure): + api = FakeAPI() + api.seed_calls(1) + me = api.client(role="user") + me.conversations.calls() + api.expire_access_tokens() + api.fail_next(**failure, path="/auth/refresh") + me.conversations.calls() # renewal fails after the platform used the token: the client signs in + kinds = [k for k, _ in api.auth_log] + assert "refresh_reused" not in kinds and kinds[-2:] == ["refresh", "login"] + + +def test_the_fake_ends_every_session_when_a_refresh_token_is_reused(): + api = FakeAPI() + t = api._issue("frontline_user", "user.1@example.com") + raw = httpx.Client(base_url=BASE, transport=httpx.MockTransport(api)) + first = raw.post("/auth/refresh", json={"refresh_token": t["refresh_token"]}) + assert first.status_code == 200 + assert raw.post("/auth/refresh", json={"refresh_token": t["refresh_token"]}).status_code == 401 + assert ("refresh_reused", "user.1@example.com") in api.auth_log + for access in (t["access_token"], first.json()["access_token"]): # old and new sessions both end + assert raw.get("/me", headers={"Authorization": f"Bearer {access}"}).status_code == 401 + assert raw.post("/auth/refresh", json={"refresh_token": first.json()["refresh_token"]}).status_code == 401 + + +# ---------------------------------------------------------------------- B2: arguments read once + + +def test_generators_are_read_once(): + api = FakeAPI() + s = api.seed_customer(teams=2, people=True) + admin = api.client(role="admin") + cust = admin.accounts.get_customer(s.company_id) + m = admin.accounts.add_base_manager(cust, ic.PersonSpec("gen.mgr@example.com", "G", "M"), + teams=(t for t in cust.teams), invite=False) + assert sorted(m.teams) == sorted(t.location_id for t in cust.teams) + uid = s.base_users["base.user11@example.com"] + up = admin.accounts.change_license(cust, uid, "base_manager", teams=(t for t in cust.teams[:1])) + assert up.license == "base_manager" + invited = admin.accounts.send_invitations(cust, user_ids=(u for u in [m.user_id])) + assert invited == [m.user_id] + admin.accounts.set_alerts(cust, ic.AlertSettings( + customer_threat=ic.AlertSetting(phrases=(p for p in ["example phrase one"])))) + rules = [r for r in api._rules.values() if r["name"] == "Customer Threat"] + assert rules and all(r["triggers"][1]["config"]["keywords"] == ["example phrase one"] for r in rules) + + +# ---------------------------------------------------------------------- S1: types + + +class Down: + n = 0 + + def __call__(self, r): + self.n += 1 + raise httpx.ConnectError("down", request=r) + + +def test_wrong_types_raise_invalid_request_with_no_request(): + t = Down() + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(t), sleep=lambda s: None, max_retries=0) + acc, conv = c.accounts, c.conversations + team = ic.TeamSpec("Main", "1 Rd", "Springfield", "IL", "US", "62701", "service-providers") + + def P(**k): + return ic.PersonSpec(**{"email": "x@example.com", "first_name": "A", "last_name": "B", **k}) + cust = ic.Customer(company_id="c1", teams=[ic.Team("L1", "Main")]) + cases = [ + lambda: acc.add_base_user("c1", P(email=123), team="t", line="1"), + lambda: acc.create_customer(ic.CustomerSpec(123, P(phone_number="+15555550100"), team)), + lambda: acc.create_customer(ic.CustomerSpec("Co", P(phone_number=5555550100), team)), + lambda: acc.create_customer(ic.CustomerSpec("Co", P(phone_number="+15555550100"), team, mfa_off="yes")), + lambda: acc.create_customer(ic.CustomerSpec("Co", P(phone_number="+15555550100"), + ic.TeamSpec("Main", 1, "Springfield", "IL", "US", "62701", "v"))), + lambda: acc.add_base_user(cust, P(), team=ic.Team("L9", "Other"), line="2101"), + lambda: acc.move_user("c1", "u1", from_team=ic.Team("L1", "Main"), to_team=ic.Team("L1", "Main")), + lambda: acc.add_base_user("c1", P(), team="t", line=object()), + lambda: acc.add_base_user("c1", P(), team="t", line=2101), + lambda: acc.add_base_user("c1", P(), team="t", line="2101", invite="no"), + lambda: acc.set_alerts("c1", ic.AlertSettings()), + lambda: acc.set_connector("c1", ic.ConnectorSpec("netsapiens", {"k": "v"}, name=5)), + lambda: acc.remove_user("c1", "u1", keep_lines=1), + lambda: acc.sync_lines("c1", dry_run="yes"), + lambda: conv.open_tasks(due=20261102), + lambda: conv.open_tasks(due="20261102"), + lambda: conv.open_tasks(due=datetime(2026, 11, 2, tzinfo=timezone.utc)), + lambda: conv.reference(".."), + lambda: conv.reference("../admin"), + ] + for i, case in enumerate(cases): + with pytest.raises(ic.InvalidRequestError): + case() + assert t.n == 0, f"case {i} sent a request" + + +def test_due_date_accepts_only_yyyy_mm_dd(): + api = FakeAPI() + api.seed_calls(1) + conv = api.client(role="user").conversations + assert isinstance(conv.open_tasks(due="2026-11-02"), list) + assert isinstance(conv.open_tasks(due=date(2026, 11, 2)), list) + + +# ---------------------------------------------------------------------- S4: the deadline + + +class Clock: + def __init__(self): + self.now = 0.0 + + def __call__(self): + return self.now + + def sleep(self, s): + self.now += s + + +def test_deadline_caps_retry_waits_and_fails_without_sleeping_first(): + clock = Clock() + + def h(r): + if r.url.path.endswith("/auth/login"): + return httpx.Response(200, json=tok(1)) + return httpx.Response(429, headers={"Retry-After": "30"}, json={"error": {"code": "RATE_LIMITED"}}) + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(h), sleep=clock.sleep, clock=clock, + deadline=40) + with pytest.raises(ic.RateLimitError) as e: + c.account.get_me() + assert clock.now == 30 and e.value.retry_after == 30 # one wait fit; the second would pass the deadline + + +def test_deadline_stops_network_retries_with_a_timeout(): + clock = Clock() + timeouts = [] + + def h(r): + timeouts.append(r.extensions["timeout"]["read"]) + clock.now += 25 # each attempt takes 25 s before failing + raise httpx.ConnectError("down", request=r) + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(h), sleep=clock.sleep, clock=clock, + deadline=60, timeout=30, max_retries=10) + with pytest.raises(ic.NetworkError) as e: + c.login() + assert e.value.kind == "timeout" and clock.now <= 60 + 25 + assert timeouts[0] == pytest.approx(30 * 0.5) # one attempt's phases share the timeout + assert all(t <= 30 * 0.5 for t in timeouts) and timeouts[-1] < timeouts[0] # later attempts get what is left + + +def test_deadline_is_checked(): + for bad in (0, -1, True, "120"): + with pytest.raises(ic.InvalidRequestError): + ic.Client("a@example.com", "pw", deadline=bad) + + +# ---------------------------------------------------------------------- S5b + S5c: knobs and strictness + + +def test_fail_next_covers_each_failure_the_sdk_distinguishes(): + api = FakeAPI() + api.seed_calls(1) + me = api.client(role="user") + api.fail_next(503, method="GET", path="/calls") + assert len(me.conversations.calls()) == 1 # a 5xx on a read is retried + api.fail_next(network="read_timeout", path="/calls") + assert len(me.conversations.calls()) == 1 # so is a timeout + api.fail_next(network="undecodable", path="/calls") + with pytest.raises(ic.NetworkError) as e: + me.conversations.calls() + assert e.value.kind == "decoding" # an unreadable answer is not retried + api.fail_next(network="connect") + assert len(me.conversations.calls()) == 1 + with pytest.raises(ValueError): + api.fail_next() + with pytest.raises(ValueError): + api.fail_next(network="dns") + + +def test_strict_mode_checks_values(): + api = FakeAPI() + s = api.seed_customer(people=False) + raw = httpx.Client(base_url=BASE, transport=httpx.MockTransport(api)) + lid = s.customer.teams[0].location_id + cases = [ + ("PATCH", f"/locations/{lid}/insights-hub/config", {"monitor_all_numbers": "yes"}, None, 422), + ("PATCH", f"/locations/{lid}/insights-hub/config", {"monitor_all_numbers": False, "zzz": 1}, None, 422), + ("POST", f"/locations/{lid}/user-groups", {"group_name": 5}, None, 422), + ("GET", "/calls", None, {"limit": "500"}, 400), + ("GET", "/calls", None, {"status": "bogus"}, 400), + ("GET", "/calls", None, {"location_id": "not-a-uuid"}, 400), + ("GET", "/calls", None, {"date_from": "2026-11-01T00:00:00"}, 400), + ("GET", "/calls", None, {"multi_leg": "yes"}, 400), + ] + for method, path, body, params, status in cases: + r = raw.request(method, path, json=body, params=params) + assert r.status_code == status, (path, body, params, r.text) + assert r.json()["error"]["code"] == "VALIDATION_ERROR" + + +# ---------------------------------------------------------------------- N1 / N3 / N5 + + +@pytest.mark.parametrize("payload", [{"alert_id": ".."}, {"alert_id": "../../admin?x=1#"}, + {"alert_id": 5, "alert": {"id": "evil"}}, {"alert_id": "a" * 129}, + {"alert": {"id": "a b"}}]) +def test_first_alert_ids_are_plain(payload): + with pytest.raises(ic.WebhookPayloadError): + ic.parse_first_alert_event(payload) + + +def test_links_carry_only_plain_ids(): + api = FakeAPI() + api._call_rows.append({"id": "../x", "call_date": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}) + b = api.client(role="user").conversations.calls()[0] + assert b.id == "../x" and b.link is None + assert ic.parse_first_alert_event({"alert_id": "fa_123-x"}).alert_id == "fa_123-x" + + +def test_find_survives_a_cause_that_is_not_an_exception(): + class W(Exception): + cause = "oops" + assert ic.AccountError("s", None, W()).find(ic.ConflictError) is None + + +def test_fake_surface_is_small_and_transport_is_refused(): + api = FakeAPI() + with pytest.raises(ic.InvalidRequestError): + api.client(transport=httpx.HTTPTransport()) + with pytest.raises(ic.InvalidRequestError): + api.client(role="superuser") + public = {n for n in dir(api) if not n.startswith("_")} + assert public == {"client", "seed_customer", "seed_calls", "connector_outcome", "fail_next", "fail_write", + "network_down", "rate_limit", "expire_access_tokens", "requests", "writes", "writes_since", + "count", "reset_log", "auth_log", "products", "numbers", "fa_numbers", "ih_numbers", + "group_members"} diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py index e11ae3f..8970b23 100644 --- a/tests/unit/test_review_fixes.py +++ b/tests/unit/test_review_fixes.py @@ -57,7 +57,7 @@ def test_add_base_user_refuses_an_existing_manager_before_any_write(): c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) c.accounts.add_base_user(cust, person(2), team=t, line="202", invite=False) m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) - start = len(api.calls) + start = len(api._calls) with pytest.raises(ic.InvalidRequestError) as e: c.accounts.add_base_user(cust, person(9), team=t, line="299") assert "change_license" in str(e.value) and api.writes_since(start) == [] @@ -68,7 +68,7 @@ def test_add_base_manager_refuses_an_existing_base_user_and_integration_refuses_ api, c, cust = base() t = cust.teams[0] u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) - start = len(api.calls) + start = len(api._calls) with pytest.raises(ic.InvalidRequestError): c.accounts.add_base_manager(cust, person(1), teams=[t], line="901") with pytest.raises(ic.InvalidRequestError): @@ -100,7 +100,7 @@ def test_change_line_keeps_a_line_another_base_user_still_holds(): assert api.numbers(u1.user_id) == ["211"] and api.numbers(u2.user_id) == ["201"] assert sorted(api.fa_numbers(t.location_id)) == sorted(api.ih_numbers(t.location_id)) == ["201", "211"] assert sorted(api.numbers(m.user_id, t.connector_id)) == ["201", "211"] - start = len(api.calls) + start = len(api._calls) c.accounts.change_line(cust, u1.user_id, "201", "211") assert api.writes_since(start) == [] c.accounts.change_line(cust, u2.user_id, "201", "212") # the last holder: 201 is released now @@ -114,7 +114,7 @@ def test_change_line_for_a_manager_touches_only_their_own_line(): u1 = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) m2 = c.accounts.add_base_manager(cust, person(8), teams=[t], line="800", invite=False) - start = len(api.calls) + start = len(api._calls) with pytest.raises(ic.InvalidRequestError): c.accounts.change_line(cust, m.user_id, "201", "777") assert api.writes_since(start) == [] @@ -130,7 +130,7 @@ def test_change_line_for_a_manager_touches_only_their_own_line(): def _writes_of(setup, action): api, f, c = flaky() ctx = setup(c) - start = len(api.calls) + start = len(api._calls) action(c, ctx) return len(api.writes_since(start)) @@ -148,7 +148,7 @@ def _resume_every_step(setup, action, check): ctx["error"] = e.value action(c, ctx) check(api, ctx) - start = len(api.calls) + start = len(api._calls) action(c, ctx) assert api.writes_since(start) == [], f"write {k}: the third run wrote" @@ -167,11 +167,11 @@ def action(c, x): def check(api, x): t, m = x["t"], x["m"] assert x["error"].result.lines == ["201", "900"] or sorted(x["error"].result.lines) == ["201", "900"] - assert api.mappings[m.user_id] == [{"connector_id": t.connector_id, "monitored_numbers": ["900"]}] + assert api._mappings[m.user_id] == [{"connector_id": t.connector_id, "monitored_numbers": ["900"]}] assert sorted(api.fa_numbers(t.location_id)) == ["201", "900"] assert api.products(m.user_id, t.location_id) == {"after-call-copilot"} - assert api.users[m.user_id]["_locations"] == [t.location_id] - assert all(m.user_id not in g["members"] for g in api.groups.values()) + assert api._users[m.user_id]["_locations"] == [t.location_id] + assert all(m.user_id not in g["members"] for g in api._groups.values()) assert api.numbers(x["u"].user_id) == ["201"] _resume_every_step(setup, action, check) @@ -212,10 +212,10 @@ def action(c, x): def check(api, x): t, east, u, m = x["t"], x["east"], x["u"], x["m"] - assert api.mappings[u.user_id] == [{"connector_id": east.connector_id, "monitored_numbers": ["201"]}] + assert api._mappings[u.user_id] == [{"connector_id": east.connector_id, "monitored_numbers": ["201"]}] assert api.fa_numbers(t.location_id) == [] and api.fa_numbers(east.location_id) == ["201"] assert api.numbers(m.user_id, t.connector_id) == [] and api.numbers(m.user_id, east.connector_id) == ["201"] - assert api.users[u.user_id]["_locations"] == [east.location_id] + assert api._users[u.user_id]["_locations"] == [east.location_id] _resume_every_step(setup, action, check) @@ -238,7 +238,7 @@ def check(api, x): assert api.numbers(m.user_id, east.connector_id) == ["301"] assert m.user_id in api.group_members(east.location_id, "Upset Customers") assert m.user_id not in api.group_members(t.location_id, "Upset Customers") - assert sorted(api.users[m.user_id]["_locations"]) == sorted([east.location_id, mg.location_id]) + assert sorted(api._users[m.user_id]["_locations"]) == sorted([east.location_id, mg.location_id]) _resume_every_step(setup, action, check) @@ -253,7 +253,7 @@ def test_promoting_onto_another_team_leaves_the_old_one(): c.accounts.add_base_user(cust, person(2), team=t, line="202", invite=False) r = c.accounts.change_license(cust, u.user_id, "base_manager", teams=[east]) assert r.teams == [east.location_id] - assert t.location_id not in api.users[u.user_id]["_locations"] + assert t.location_id not in api._users[u.user_id]["_locations"] assert api.numbers(u.user_id) == ["201"] and api.fa_numbers(t.location_id) == ["202"] c.accounts.add_base_user(cust, person(3), team=t, line="203", invite=False) assert api.numbers(u.user_id) == ["201"] # not a holder of the old team's lines @@ -270,7 +270,7 @@ def test_demoting_a_manager_of_several_teams_keeps_one_and_notes_empty_groups(): r = c.accounts.change_license(cust, m.user_id, "base_user", teams=[east]) assert r.license == "base_user" and r.lines == ["900"] and r.teams == [east.location_id] assert sorted(api.fa_numbers(east.location_id)) == ["301", "900"] and api.fa_numbers(t.location_id) == ["201"] - assert api.users[m.user_id]["_locations"] == [east.location_id] + assert api._users[m.user_id]["_locations"] == [east.location_id] assert len(r.notes) == 1 and "Riverbend - East" in r.notes[0] and "Customer Threats" in r.notes[0] out = c.accounts.remove_user(cust, other.user_id) assert "Riverbend - Main has no Base Manager left in Customer Threats, Upset Customers, Low Sentiment Calls" \ @@ -311,7 +311,7 @@ def everyone(): c.accounts.sync_lines(cust) c.accounts.activate_alerts(cust) everyone() - start = len(api.calls) + start = len(api._calls) everyone() assert api.writes_since(start) == [] @@ -391,14 +391,14 @@ def test_add_team_and_set_connector_stop_on_a_connector_error(): def test_people_helpers_switch_monitor_all_off_on_teams_they_touch(): api, c, cust = base() t = cust.teams[0] - api.ih_config[t.location_id] = True + api._ih_config[t.location_id] = True c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) - assert api.ih_config[t.location_id] is False - api.ih_config[t.location_id] = True + assert api._ih_config[t.location_id] is False + api._ih_config[t.location_id] = True c.accounts.sync_lines(cust, dry_run=True) - assert api.ih_config[t.location_id] is True # a dry run writes nothing + assert api._ih_config[t.location_id] is True # a dry run writes nothing c.accounts.sync_lines(cust) - assert api.ih_config[t.location_id] is False + assert api._ih_config[t.location_id] is False # ---------------------------------------------------------------------- N5: the fake follows the API @@ -420,11 +420,11 @@ def user_api(): a = FakeAPI(role="frontline_user") now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") cid, aid = new_id(), new_id() - a.call_rows = [{"id": cid, "call_date": now, "caller_name": "+1 555 867 5309", "caller_number": "+15558675309", + a._call_rows = [{"id": cid, "call_date": now, "caller_name": "+1 555 867 5309", "caller_number": "+15558675309", "callee_name": "WIRELESS 5558675309", "callee_number": "5558675309"}] - a.alert_rows = [{"id": aid, "call_id": cid, "call_date": now, "caller_name": "CALLER 555-867-5309", + a._alert_rows = [{"id": aid, "call_id": cid, "call_date": now, "caller_name": "CALLER 555-867-5309", "caller_number": "+15558675309", "summary": "billing question", "keywords": ["Upset Customer"]}] - a.call_details[cid] = dict(a.call_rows[0]) + a._call_details[cid] = dict(a._call_rows[0]) a.ids = (cid, aid) return a @@ -495,9 +495,9 @@ def test_a_connector_that_reports_connected_is_running(): c = api.client() cust = c.accounts.create_customer(spec(connector=CONN)) assert cust.teams[0].connector_status == "connected" and cust.management.connector_status == "connected" - before = len([x for x in api.calls if x[0] != "GET"]) + before = len([x for x in api._calls if x[0] != "GET"]) again = c.accounts.create_customer(spec(connector=CONN, company_id=cust.company_id)) - assert len([x for x in api.calls if x[0] != "GET"]) == before # nothing written on the re-run + assert len([x for x in api._calls if x[0] != "GET"]) == before # nothing written on the re-run user = c.accounts.add_base_user(again, person(1), team=again.teams[0], line="201", invite=False) assert user.lines == ["201"] diff --git a/tests/unit/test_testing_module.py b/tests/unit/test_testing_module.py index 303dc05..b8c61fc 100644 --- a/tests/unit/test_testing_module.py +++ b/tests/unit/test_testing_module.py @@ -120,7 +120,7 @@ def raw(api): def test_unknown_path_is_refused(): api = FakeAPI() - r = raw(api).get("/calls/export") + r = raw(api).get("/calls/export/all") assert r.status_code == 404 and r.json()["error"]["code"] == "NOT_FOUND" assert raw(api).delete("/companies/x").status_code == 404 # a method the path does not have From 769fa3fe4d9591cdac0bb189a313931736dfeb1e Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 19:48:45 -0700 Subject: [PATCH 05/11] Cross-language rules: path arguments, RFC 8785 keys, parse and Retry-After rules, live Customers - Path arguments are checked where paths are built: 1-128 characters, not "." or "..", none of / \ ? # %, whitespace or controls; then percent-encoded. Helpers apply the same check before signing in - Free-text and number arguments must be real strings (at most 200) - Delivery keys hash the RFC 8785 canonical form (canonical_json) of the event as read; non I-JSON bodies are WebhookPayloadError - After Call events are refused exactly when a schema-required field is missing or wrongly typed; optional fields of the wrong type read None - Retry-After counts only as decimal seconds; otherwise backoff applies - A passed Customer is checked against the live location list and re-read when it differs; group and rule ids are read live; a Customer with another company's locations is refused; refreshed_at added - Testing module: fail_next(after_processing=False) fails before the platform acts; explicit patterns for numbers, dates, date-times and uuids; body enums and formats (generator keeps them in spec.json); secret-named values masked in the request log - Shared vectors in tests/unit/fixtures with tools/make_shared_vectors.py - README, CHANGELOG and request counts updated Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + README.md | 22 +- src/intelligence_cloud/_spec.py | 28 ++ src/intelligence_cloud/accounts.py | 77 +++- src/intelligence_cloud/client.py | 40 +- src/intelligence_cloud/conversations.py | 8 +- src/intelligence_cloud/data/spec.json | 347 ++++++++++++++++++ src/intelligence_cloud/intelligence.py | 25 +- src/intelligence_cloud/receiver.py | 224 +++++++++-- src/intelligence_cloud/testing/_fake.py | 91 +++-- .../fixtures/after_call_parse_vectors.json | 182 +++++++++ tests/unit/fixtures/canonical_vectors.json | 170 +++++++++ tests/unit/fixtures/delivery_key_vectors.json | 224 +++++++++++ .../fixtures/fake_strictness_vectors.json | 267 ++++++++++++++ tests/unit/fixtures/retry_after_vectors.json | 94 +++++ tests/unit/test_accounts.py | 5 +- tests/unit/test_intelligence.py | 8 +- tests/unit/test_request_counts.py | 8 +- tests/unit/test_review_030.py | 15 +- tests/unit/test_shared_vectors.py | 254 +++++++++++++ tools/generate.py | 3 +- tools/make_shared_vectors.py | 268 ++++++++++++++ 22 files changed, 2251 insertions(+), 120 deletions(-) create mode 100644 tests/unit/fixtures/after_call_parse_vectors.json create mode 100644 tests/unit/fixtures/canonical_vectors.json create mode 100644 tests/unit/fixtures/delivery_key_vectors.json create mode 100644 tests/unit/fixtures/fake_strictness_vectors.json create mode 100644 tests/unit/fixtures/retry_after_vectors.json create mode 100644 tests/unit/test_shared_vectors.py create mode 100644 tools/make_shared_vectors.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1eeae40..f27160f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,12 @@ - **Events: store by call id and upsert.** A later After Call delivery for the same call can carry newer data. `Deduplicator.seen(event)` only checks whether this exact delivery (same event type, location, call id and canonical-JSON content) was remembered; `Deduplicator.remember(event)` records it and is called after your durable write, so a delivery whose storage failed is processed when it is retried. Both take an event, a parsed body or raw bytes; a plain id is refused. Newer data is never hidden. New `upsert_key(event)` (also `Deduplicator.upsert_key`) returns the call id (or alert id) to store under. The README receiver section and `examples/webhook_receiver.py` follow this. - **First Alert payload is not final.** `parse_first_alert_event` accepts any id of letters, digits, `-` and `_` up to 128 characters (it used to accept only UUIDs and lower-cased them); the first of `alert_id`, `alert.id`, `id` that is present decides; it keeps reading rule, location, call and time from today's shapes, and `raw` holds the whole payload. - **`intelligence_cloud.testing`**: a supported fake API for your tests and CI. `FakeAPI.client(role="admin" | "user")`, fictional seed data (`seed_customer`, `seed_calls`), failure knobs (`connector_outcome`, `fail_next` for each HTTP and network failure, `fail_write`, `network_down`, `rate_limit`, `expire_access_tokens`), a request log and `auth_log`, refresh-token reuse that ends every session as on the platform, and strict refusal of requests the published spec does not define, including value types, enums and formats of top-level fields. README "Testing your code" lists the whole supported surface. +- **Path arguments are checked at the one place paths are built**: a value of `.`, `..`, or with `/`, `\`, `?`, `#`, `%`, whitespace or control characters, or longer than 128 characters, raises `InvalidRequestError` before any request (0.2.0 let `".."` collapse the URL, so `deactivate_company_user(cid, "..")` reached the company). Free-text and number arguments must be real strings of at most 200 characters. +- **Delivery keys use RFC 8785 (JSON Canonicalization Scheme)** over the event as the SDK reads it, so every SDK computes the same key; bodies that are not I-JSON (duplicate keys, NaN, Infinity, lone surrogates) raise `WebhookPayloadError`. New `canonical_json` in `intelligence_cloud.receiver`. Shared test vectors ship in `tests/unit/fixtures/` (the sdist). +- **One After Call parse rule:** an event is refused exactly when a field the published schema marks required is missing or has the wrong JSON type; optional fields of the wrong type read as None; `call_date` and `timestamp` read as None when their text is not a date (they used to refuse the event). +- **One Retry-After rule:** only decimal seconds count; anything else means the client's own backoff. `RateLimitError.retry_after` is a float or None. +- **A passed `Customer` is kept current:** helpers check it against the live location list (one request) and re-read it when it differs; group and rule ids are read live for the teams they touch; a Customer carrying another company's locations is refused. `Customer.refreshed_at` is new. +- Testing module: `fail_next(..., after_processing=False)` fails before the platform acts by default (a renewal's 429 keeps its token); strict mode uses explicit patterns for numbers, dates, date-times and uuids and checks body enums and formats (the generator now keeps them in the bundled spec); secret-named values are masked in the request log. - Connector waits count the check intervals as well as the clock, so a replaced `sleep` (tests) cannot spin for the whole timeout. - README: "Retries" with worst-case blocking time, "Testing your code", "Running helpers from more than one process", "How many requests" (pinned by a test), the error tree. SDK documentation links now point to the SDK pages (https://docs.intelligence.cloud/sdk/, /sdk/quick-start, /sdk/reference, /sdk/events, /sdk/configuration, /sdk/downloads); API links stay https://docs.intelligence.cloud/api and https://docs.intelligence.cloud/reference. The examples ship in the source distribution, not the wheel, and the README says so. Package metadata links to the SDK pages, with "Changelog" on https://docs.intelligence.cloud/sdk/downloads. - Examples use one fictional customer, Riverbend Auto Group, and the variables `IC_ADMIN_EMAIL` / `IC_ADMIN_PASSWORD` and `IC_USER_EMAIL` / `IC_USER_PASSWORD` (`IC_DATA_*` still read by the examples as a fallback). @@ -28,6 +34,11 @@ | `Deduplicator.is_duplicate(event_or_call_id)` checked and recorded in one call, keyed on the call id | Removed, with no alias: `seen(event)` checks, `remember(event)` records after your write. A plain id raises `InvalidRequestError` | | A custom `DedupStore` needed `add(key) -> bool` | It needs `has(key) -> bool` and `add(key)` | | No overall time limit | `deadline=120` seconds per API request (sign-in, renewal, retries and waits included); raise it for long Retry-After waits | +| A path argument such as `".."` reached the API | Refused before any request (see the path rule) | +| `parse_after_call_event` refused a `call_date` or `timestamp` that was not a date | Accepted; the field reads as None. Refused only for a missing or wrongly typed required field | +| `AfterCallCall.call_date` and `AfterCallEvent.timestamp` were always set | Optional (None when the text is not a date) | +| Retry-After values such as `" 5"` or `"1e2"` were honoured | Treated as absent: backoff applies | +| Bodies with duplicate keys or NaN were parsed | Refused with `WebhookPayloadError` | | An id inside an app link could be any string | Links carry only ids of letters, digits, `-` and `_`; `reference()` refuses others and briefs with such an id get `link=None` | | `parse_first_alert_event` refused non-UUID ids and lower-cased ids | Ids of letters, digits, `-` and `_` (at most 128), kept as sent | | A sign-in 429 always waited `login_rate_limit_wait` once | It waits only when `Retry-After` fits in that limit; otherwise raises at once | diff --git a/README.md b/README.md index f557f33..5659891 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ admin.accounts.activate_alerts(customer) # once each team has a manager in it | `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | changes | | `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary | -Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only. A line another location already holds reaches you as **`AccountError` → `ExtensionMappingError` → `ConflictError`** (message "Extension is already monitored at another location.", the clashing numbers on `.extensions`). Use `AccountError.find` instead of walking the chain: +Every helper that takes `customer` also takes a company id. **A `Customer` is a snapshot the helpers keep current**: each helper first reads the company's location list once and compares it with the object's teams and Management (ids and active state); when anything differs it re-reads the whole layout and updates the object in place (`refreshed_at` says when). Group and rule ids for the teams a helper touches are always read live in that call, never taken from the object; a missing group stops the helper before it writes. A `Customer` carrying a location its company does not have is refused (`InvalidRequestError`). `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only. A line another location already holds reaches you as **`AccountError` → `ExtensionMappingError` → `ConflictError`** (message "Extension is already monitored at another location.", the clashing numbers on `.extensions`). Use `AccountError.find` instead of walking the chain: ```python try: @@ -253,6 +253,8 @@ Module level: `parse_after_call_event`, `parse_first_alert_event`, `UnknownEvent - **Responses** carry only the fields in the published reference. Anything else is dropped. With `Client(keep_unknown_fields=True)` new fields the reference does not list yet are kept on the customer-lifecycle (admin) reads; `get_me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields. Either way, the one-time sign-in link a user create can return is never passed through or logged. - **Test endpoints** (connector dry run, webhook tests) report only success and the HTTP status. - **Retries:** see "Retries" below. +- **Path arguments:** every value placed in a URL path (ids) must be 1 to 128 characters, not `.` or `..`, with no `/`, `\`, `?`, `#`, `%`, whitespace or control characters; anything else raises `InvalidRequestError` before any request. What remains is percent-encoded. +- **Free text:** search terms, numbers and alert names must be real strings, trimmed, at most 200 characters (search terms at least 2). - **Checks first:** every helper of both layers checks its arguments before it signs in or sends anything. Bad input raises `InvalidRequestError` with no request made, so it costs no sign-in (sign-in is limited to 5 a minute). ### Retries @@ -265,7 +267,7 @@ One policy, the same in every SDK: | The same on sign-in | Retried the same way | | Token renewal | The refresh token is sent again **only** after a 429 (the server did not use it) or after a network failure that provably never left this machine (no connection made, no free connection in the pool, a request that could not be written). Any other outcome (a 5xx, a timeout after the request left, an unreadable answer) may have used it: it is never resent, and the client signs in instead. Sending a used refresh token ends every session of that login | | Network failure or 5xx on any other create | Not retried: the error is raised, so nothing is created twice | -| 429 with `Retry-After` within the limit (60 s; for sign-in, `login_rate_limit_wait`, default 60 s) | Waits `Retry-After` (backoff when absent), then retries; sign-in waits once | +| 429 with `Retry-After` within the limit (60 s; for sign-in, `login_rate_limit_wait`, default 60 s) | Waits `Retry-After` (backoff when absent), then retries; sign-in waits once. `Retry-After` counts only as decimal seconds (`[0-9]+(.[0-9]+)?`, at most 9 digits before the point); an HTTP date, `INF`, `NaN`, `1e2`, a negative or empty value is treated as absent (backoff applies). `RateLimitError.retry_after` is a float or None | | 429 with `Retry-After` above the limit | Raises `RateLimitError` at once with `.retry_after` set; it never waits first and then fails | | 401 on a request | Renews the token once and retries | @@ -333,10 +335,10 @@ admin.intelligence.test_first_alert_webhook(location_id) - Use HTTPS and put a token of at least 32 random characters in the path, one per location, read from your secret store: `python -c "import secrets; print(secrets.token_urlsafe(32))"`. Compare it in constant time (`hmac.compare_digest` on bytes). Requests are not signed: treat the URL as a secret and keep it out of proxy, load balancer and APM logs. - Answer 2xx within 2 seconds and do the work afterwards. Redirects count as failures. Delivery is tried 3 times, then dropped. -- `parse_after_call_event` refuses bodies over 256 KB (`PayloadTooLargeError`: answer 413) and returns `UnknownEvent` for event types it doesn't handle: answer 2xx and ignore them. Answer 400 only for a body that isn't JSON or a malformed After Call event, and 404 for a wrong token. +- `parse_after_call_event` refuses bodies over 256 KB (`PayloadTooLargeError`: answer 413) and returns `UnknownEvent` for event types it doesn't handle: answer 2xx and ignore them. It refuses an event (`WebhookPayloadError`: answer 400) exactly when a field the published schema marks required is missing or has the wrong JSON type (`version`, `type`, `is_test`, `location_id`, `timestamp`, `call` with `id`, `call_type`, `duration_seconds`, `call_date`, and `location`); other fields may be absent and read as None when they have the wrong type; unknown fields are dropped; an integer is a whole-number JSON number. `call_date` and `timestamp` read as None when their text is not a date. Answer 404 for a wrong token. - Treat an event as a notification. Before you write anything from it into another system, read the call with `get_call(event.call.id)` using your frontline integration user; a `NotFoundError` means drop the event. - **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsert_key(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before. -- **Check, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse → if `seen(event)`: answer 2xx → upsert under `upsert_key(event)` → `remember(event)` → answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. An exact re-delivery is the same event type, location and call id with the same content (a SHA-256 of the canonical JSON body, because the payload carries no version marker); a later delivery with newer data is not seen. It takes an event, a parsed body or the raw bytes; a plain id is refused, because an id alone cannot tell newer data apart. +- **Check, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse → if `seen(event)`: answer 2xx → upsert under `upsert_key(event)` → `remember(event)` → answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. An exact re-delivery is the same event type, location and call id with the same content: the SHA-256 of the **RFC 8785 (JSON Canonicalization Scheme)** form of the event as the SDK reads it (numbers as doubles, keys in UTF-16 order), because the payload carries no version marker. A later delivery with newer data is not seen. Bodies that are not I-JSON (duplicate keys, NaN, a lone surrogate) are refused with `WebhookPayloadError`. Two things follow: two identical deliveries arriving at the same moment can both be "not seen" (harmless, because storing is an upsert by call id); and a delivery that differs only in a field the SDK does not document counts as a re-delivery, because the event is read through the published schema before hashing. It takes an event, a parsed body or the raw bytes; a plain id is refused, because an id alone cannot tell newer data apart. - Its default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)`, for example `Deduplicator(store=RedisStore(r))` where `has` is `return bool(r.exists("ic:" + key))` and `add` is `r.set("ic:" + key, 1, ex=86400)`. - To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test` (from the source distribution). @@ -490,14 +492,14 @@ def test_resumes_after_a_stop(): | `seed_customer(*, teams=1, people=True)` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `company_id`, `base_users`, `managers`) | | `seed_calls(n=3, *, location_id=None, day=None, alerts=True, tasks=True)` | Fictional calls with details, tasks and alerts (555-01xx numbers). Returns the call ids, newest first | | `connector_outcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connectors created from now on | -| `fail_next(status=None, *, network=None, method=None, path=None, retry_after=None)` | The next matching request fails once: an HTTP status, or `network="connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"undecodable"`. A renewal that fails any way but "connect" has used its token | +| `fail_next(status=None, *, network=None, method=None, path=None, retry_after=None, after_processing=False)` | The next matching request fails once: an HTTP status, or `network="connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"undecodable"`. By default the failure comes before the platform acts (a renewal's token stays unused); `after_processing=True` applies the request first (a write lands, a refresh token is rotated) and loses the answer | | `fail_write(nth=1, status=400)`, `network_down(down=True)`, `rate_limit(count=1, retry_after=1)`, `expire_access_tokens()` | Simpler knobs: the nth write fails; no network; 429s; every access token expires (the next call renews) | | `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()`, `auth_log` | The request log (sign-in and renewal are in `auth_log`: "login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) | | `products(uid, lid)`, `numbers(uid, connector_id=None)`, `fa_numbers(lid)`, `ih_numbers(lid)`, `group_members(lid, name)` | State to assert on | That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore and may change. `client(transport=...)` is refused. -**Strict mode** (`strict=True`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type (whole number, true/false), outside its enum or range, or not in its format (uuid, date-time) (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states (for example the spec gives no list of user roles). Code that passes against it still needs one run against a test company before release. +**Strict mode** (`strict=True`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type, outside its enum or range, or not in its format (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). Formats use explicit patterns, the same in every SDK: whole number `-?(0|[1-9][0-9]*)`; date `YYYY-MM-DD` on a real calendar day; date-time RFC 3339 with seconds, `T`, and `Z` or `±HH:MM`; uuid hyphenated, all lower or all upper case. Body enums and formats come from the bundled spec. It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states (for example the spec gives no list of user roles). Code that passes against it still needs one run against a test company before release. ## Running helpers from more than one process @@ -532,15 +534,15 @@ Measured against `intelligence_cloud.testing` with a fresh client (one `GET /me` | Helper | 1-team customer | 10-team customer | |---|---|---| | `create_customer` (first run, one team) | 35 | 35 | -| `add_team` (the 2nd team; the 10th team) | n/a | 21; 21 (224 for all ten teams) | +| `add_team` (the 2nd team; the 10th team) | n/a | 25; 25 (260 for all ten teams) | | `create_customer`, re-run | 19 | 19 | | `add_base_user` (customer passed as a company id) | 36 | 90 | -| `add_base_manager` (on every team) | 29 | 137 | -| `activate_alerts` | 14 | 86 | +| `add_base_manager` (on every team) | 33 | 168 | +| `activate_alerts` | 18 | 117 | | `calls` (one page) | 2 | 2 | | `brief` | 3 | 3 | -The counts assume two Base Users per team and one manager, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. +A helper given a `Customer` object adds one request (the location list it checks the object against) and two per team whose group and rule ids it uses (live listings). The counts assume two Base Users per team and one manager, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. ## Examples diff --git a/src/intelligence_cloud/_spec.py b/src/intelligence_cloud/_spec.py index 4bf35a9..abf41f5 100644 --- a/src/intelligence_cloud/_spec.py +++ b/src/intelligence_cloud/_spec.py @@ -183,6 +183,34 @@ def check_body(op_id: str, body: Mapping[str, Any]) -> None: raise InvalidRequestError(f"{op_id}: missing required field(s) {missing}") +# A value placed in a URL path: 1-128 characters, not "." or "..", and none of / \ ? # %, whitespace or +# control characters (a dot segment or a slash would change which resource the request reaches). +_PATH_VALUE = re.compile(r"^[^/\\?#%\s\x00-\x1f\x7f-\x9f]{1,128}$") + + +def check_path_value(value: Any, name: str) -> str: + """Refuse (InvalidRequestError, before any request) a path argument that could change the URL.""" + if not isinstance(value, str) or value in (".", "..") or not _PATH_VALUE.match(value): + raise InvalidRequestError(f"{name}: an id of 1 to 128 characters without / \\ ? # %, spaces or " + "control characters, and not '.' or '..'") + return value + + +MAX_TEXT = 200 + + +def check_text(value: Any, name: str, min_len: int = 1, max_len: int = MAX_TEXT) -> str: + """A free-text or number argument: a real string, trimmed, ``min_len`` to ``max_len`` characters.""" + if not isinstance(value, str): + raise InvalidRequestError(f"{name}: a string") + v = value.strip() + if len(v) < min_len: + raise InvalidRequestError(f"{name}: at least {min_len} character{'s' if min_len > 1 else ''}") + if len(v) > max_len: + raise InvalidRequestError(f"{name}: at most {max_len} characters") + return v + + def is_uuid(value: Any) -> bool: if not isinstance(value, str): return False diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index a6bc880..4e83cdb 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -27,8 +27,9 @@ import httpx from ._base import Namespace, unwrap -from ._spec import is_uuid +from ._spec import check_path_value, is_uuid from .errors import ( + NotFoundError, AccountError, ApiError, ConflictError, @@ -234,6 +235,11 @@ class Team: @dataclass class Customer: + """A snapshot of the customer's layout. Every helper that takes it first checks it against the live + location list (one request) and re-reads the layout when it differs, updating this object in place; + group and rule ids are always read live for the teams a helper touches. ``refreshed_at`` is when it + was last read or checked.""" + company_id: str management: Optional[Team] = None teams: List[Team] = field(default_factory=list) @@ -244,6 +250,7 @@ class Customer: sso_txt_record: Optional[Dict[str, str]] = None # {"name": ..., "value": ...} for the customer's DNS created: List[str] = field(default_factory=list) existing: List[str] = field(default_factory=list) + refreshed_at: Optional[datetime] = None @dataclass @@ -439,11 +446,44 @@ def _stop(self, run: _Run, exc: BaseException) -> None: def _resolve(self, customer: CustomerRef) -> Customer: if isinstance(customer, Customer): - return customer + return self._sync(customer) if isinstance(customer, str) and customer.strip(): return self.get_customer(customer.strip()) raise InvalidRequestError("customer: a Customer or a company id") + def _sync(self, cust: Customer) -> Customer: + """One live read (the company's locations). A Customer that carries a location the company does + not have is refused; one whose teams, Management or their active state differ is re-read in full + and updated in place.""" + try: + live = list(self._c.locations.iter_company_locations(cust.company_id)) + except NotFoundError: + raise InvalidRequestError("This Customer's company is not visible to this login") from None + by_id = {x.get("id"): x for x in live} + carried = self._locations(cust) + for t in carried: + if t.location_id not in by_id: + raise InvalidRequestError(f"This Customer carries a location that company {cust.company_id} " + "does not have: read it with get_customer(company_id)") + active = {x["id"] for x in live if x.get("is_active", True)} + if active != {t.location_id for t in carried}: + fresh = self.get_customer(cust.company_id) + cust.management, cust.teams, cust.pending = fresh.management, fresh.teams, fresh.pending + cust.sso_domain_id, cust.sso_txt_record = fresh.sso_domain_id, fresh.sso_txt_record + cust.refreshed_at = datetime.now(timezone.utc) + return cust + + def _live(self, team: Team, need: Iterable[str] = ()) -> Team: + """Read the team's groups and rules now and put their ids on ``team``. Raises InvalidRequestError + when a group in ``need`` (Team.groups field names) is missing.""" + fresh = self._read_team(team.location_id, team.name, team.kind) + team.groups, team.rules = fresh.groups, fresh.rules + missing = [TEAM_GROUPS[f] for f in need if getattr(team.groups, f) is None] + if missing: + raise InvalidRequestError(f"{team.name}: group {', '.join(missing)} is missing; run create_customer " + "(or add_team) again to restore the layout") + return team + @staticmethod def _team(cust: Customer, team: TeamRef) -> Team: if isinstance(team, Team): @@ -508,6 +548,7 @@ def get_customer(self, company_id: str) -> Customer: else: cust.teams.append(team) cust.pending = self._pending(cust) + cust.refreshed_at = datetime.now(timezone.utc) for dom in unwrap(c.sso.list_company_domains(company_id)) or []: cust.sso_domain_id = dom.get("id") ver = dom.get("verification") or {} @@ -580,7 +621,8 @@ def create_customer(self, spec: CustomerSpec) -> Customer: alerts = _check_alerts(spec.alerts) _check_connector_local(spec.connector) for f in ("reseller_id", "company_code", "company_id", "sso_domain"): - _str(getattr(spec, f), f, required=False) + if _str(getattr(spec, f), f, required=False) and f in ("reseller_id", "company_id"): + check_path_value(getattr(spec, f).strip(), f) for f in ("mfa_off", "reactivate"): if not isinstance(getattr(spec, f), bool): raise InvalidRequestError(f"{f}: True or False") @@ -667,6 +709,7 @@ def create_customer(self, spec: CustomerSpec) -> Customer: self._ensure_insights_hub(team) self._monitor_all_off(mgmt.location_id) result.pending = self._pending(result) + result.refreshed_at = datetime.now(timezone.utc) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) _raise_connector_failure(failures, result) @@ -905,6 +948,7 @@ def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSp try: run.step = "copy_alerts" if first is not None: + self._live(first) for key, d in RULES.items(): rid = getattr(first.rules, key) if rid is None: @@ -951,7 +995,7 @@ def set_alerts(self, customer: CustomerRef, alerts: AlertSettings, *, team: Opti self._team(customer, team) self._require_admin() cust = self._resolve(customer) - teams = self._teams(cust, team) + teams = [self._live(t, ALERT_GROUPS) for t in self._teams(cust, team)] settings = self._settings_from(alerts) changed: List[str] = [] run = self._run(changed) @@ -1026,8 +1070,9 @@ def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = No people = self._index(cust) managers = {p.id for p in people.values() if p.license == "base_manager"} run = self._run(out) + targets = [self._live(t) for t in self._teams(cust, team)] try: - for t in self._teams(cust, team): + for t in targets: run.step = f"activate:{t.name}" missing = [] for f in ALERT_GROUPS: @@ -1290,7 +1335,10 @@ def _products_off(self, location_id: str, uid: str, keys: Iterable[str]) -> None self._c.products.disable_user_product(location_id, uid, key) def _join_groups(self, location_id: str, uid: str, group_ids: Iterable[str]) -> None: - want = [g for g in group_ids if g] + group_ids = list(group_ids) + if any(not g for g in group_ids): + raise InvalidRequestError("A group the person should join is missing; run create_customer again") + want = list(group_ids) current = self._c.groups.user_group_ids(location_id, uid) if any(g not in current for g in want): self._c.groups.set_user_group_membership(location_id, uid, {"group_ids": _uniq(current + want)}) @@ -1477,6 +1525,10 @@ def add_base_manager(self, customer: CustomerRef, person: PersonSpec, *, teams: ts = _dedupe_teams([self._team(cust, x) for x in teams]) if cust.management is None: raise InvalidRequestError("This customer has no Management location: run create_customer again") + for t in ts: + self._live(t, TEAM_GROUPS) + if company_reports: + self._live(cust.management, ["weekly_reports"]) if own: self._need_connector(cust.management) self._check_existing(cust, person.email, "base_manager") @@ -1510,6 +1562,8 @@ def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, inv cust = self._resolve(customer) if not cust.teams: raise InvalidRequestError("This customer has no team") + for t in cust.teams: + self._live(t, ALERT_GROUPS + ("insights_hub_access",)) self._check_existing(cust, person.email, "integration") result = Member(user_id="", email=person.email, license="integration", teams=[t.location_id for t in cust.teams]) @@ -1585,6 +1639,9 @@ def change_license(self, customer: CustomerRef, user_id: str, to: str, *, [t for t in cust.teams if t.location_id in p.teams] if not ts: raise InvalidRequestError("teams: the person is on no team; pass teams") + if to == "base_manager": + for t in ts: + self._live(t, TEAM_GROUPS) result = self._member(p) run = self._run(result) try: @@ -1709,6 +1766,8 @@ def move_user(self, customer: CustomerRef, user_id: str, *, from_team: TeamRef, raise InvalidRequestError(f"User {user_id} is not on {src.name}") if p.license == "integration": raise InvalidRequestError(f"User {user_id} is an integration user; it is on every team already") + if p.license == "base_manager": + self._live(dst, TEAM_GROUPS) run = self._run(result) try: if p.license == "base_manager": @@ -2071,11 +2130,11 @@ def _check_connector_local(cs: Optional[ConnectorSpec], required: bool = False) def _check_customer_ref(customer: Any) -> None: if isinstance(customer, Customer): - if not isinstance(customer.company_id, str) or not customer.company_id: - raise InvalidRequestError("customer.company_id is required") + check_path_value(customer.company_id, "customer.company_id") return if not isinstance(customer, str) or not customer.strip(): raise InvalidRequestError("customer: a Customer or a company id") + check_path_value(customer.strip(), "customer") def _check_team_ref(team: Any, required: bool = True) -> None: @@ -2116,7 +2175,7 @@ def _check_invite(invite: Any) -> None: def _check_user_id(user_id: Any) -> None: - _str(user_id, "user_id") + check_path_value(_str(user_id, "user_id"), "user_id") def _dedupe_teams(teams: List[Team]) -> List[Team]: diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index a4bf8de..af37393 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -4,6 +4,7 @@ import contextlib import json import random +import re import threading import time import uuid @@ -69,14 +70,20 @@ def attempt_timeout(seconds: float) -> httpx.Timeout: return httpx.Timeout(connect=seconds * 0.2, write=seconds * 0.2, read=seconds * 0.5, pool=seconds * 0.1) -def _retry_after_seconds(value: Optional[str]) -> Optional[float]: - """Retry-After in seconds, or None when absent or not a number of seconds.""" - if not value: - return None - try: - return max(0.0, float(value)) - except ValueError: +_RETRY_AFTER_RE = re.compile(r"^[0-9]{1,9}(\.[0-9]+)?$") + + +def parse_retry_after(value: Optional[str]) -> Optional[float]: + """Retry-After as seconds (a float), the same in every SDK: only non-negative decimal seconds + (``[0-9]+(.[0-9]+)?``, at most 9 digits before the point) count. Anything else (an HTTP date, "INF", + "NaN", "1e2", a negative number, an empty value) is treated as if the header were absent (None), + so the client's own backoff applies.""" + if value is None or not _RETRY_AFTER_RE.match(value): return None + return float(value) + + +_retry_after_seconds = parse_retry_after def check_app_url(app_url: str) -> str: @@ -429,15 +436,9 @@ def _wait(self, seconds: float) -> bool: def _backoff(attempt: int, retry_after: Optional[str]) -> Optional[float]: # noqa: D401 """Seconds to wait before the next try, or None when Retry-After asks for more than MAX_RETRY_AFTER seconds.""" - if retry_after: - try: - wait = max(0.0, float(retry_after)) - except ValueError: - wait = -1.0 - if wait > MAX_RETRY_AFTER: - return None - if wait >= 0: - return wait + wait = parse_retry_after(retry_after) + if wait is not None: + return None if wait > MAX_RETRY_AFTER else wait base = min(8.0, 0.5 * (2 ** attempt)) return base + random.uniform(0, base / 2) @@ -489,7 +490,7 @@ def _raise(self, resp: httpx.Response, op_id: str) -> None: if status == 429: ra = resp.headers.get("Retry-After") raise RateLimitError(status, code, message, request_id, - retry_after=float(ra) if ra and ra.replace(".", "", 1).isdigit() else None, + retry_after=parse_retry_after(ra), public_message=public) raise ApiError(status, code, message, request_id, public_message=public) @@ -499,10 +500,7 @@ def _build(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any], op = _spec.operation(op_id) url_path = op["path"] for name in op["path_params"]: - value = path.get(name) - if not value or not isinstance(value, str): - from .errors import InvalidRequestError - raise InvalidRequestError(f"{op_id}: {name} is required") + value = _spec.check_path_value(path.get(name), f"{op_id}: {name}") url_path = url_path.replace("{" + name + "}", quote(value, safe="")) params = _spec.encode_query(op_id, query) if body is not None: diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py index e6eee02..513edf7 100644 --- a/src/intelligence_cloud/conversations.py +++ b/src/intelligence_cloud/conversations.py @@ -18,7 +18,7 @@ from urllib.parse import quote from ._base import Namespace, Page, unwrap -from ._spec import is_uuid +from ._spec import check_path_value, check_text, is_uuid from .errors import InvalidRequestError, WrongLoginError from .intelligence import RecordingLink, _search_term from .receiver import ID_RE, FirstAlertEvent, parse_first_alert_event @@ -195,7 +195,7 @@ class Reference: def _id(value: Any, name: str) -> str: if not isinstance(value, str) or not value.strip(): raise InvalidRequestError(f"{name}: a non-empty id") - return value.strip() + return check_path_value(value.strip(), name) def _check_team(team: Any) -> None: @@ -446,9 +446,7 @@ def recording_link(self, call_id: str) -> Optional[RecordingLink]: def caller_history(self, number: str, *, limit: int = 10) -> List[CallBrief]: """Recent briefs for one caller (the last 31 days), for use before a callback. ``limit`` at most 50.""" limit = self._limit(limit, MAX_HISTORY) - if number is None or not str(number).strip(): - raise InvalidRequestError("number is required") - term = _search_term(number, None) + term = _search_term(check_text(number, "number", min_len=2), None) start, end = self._window(None, None, None, default_days=MAX_WINDOW_DAYS) self._require_user() rows = self._pages(lambda n, cur: self._c.calls.list_calls( diff --git a/src/intelligence_cloud/data/spec.json b/src/intelligence_cloud/data/spec.json index bc02032..5cca505 100644 --- a/src/intelligence_cloud/data/spec.json +++ b/src/intelligence_cloud/data/spec.json @@ -145,6 +145,9 @@ "type": "string" }, "type": { + "enum": [ + "netsapiens" + ], "type": "string" } }, @@ -207,6 +210,7 @@ }, "member_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -1947,6 +1951,7 @@ "type": "integer" }, "id": { + "format": "uuid", "type": "string" }, "is_active": { @@ -2206,15 +2211,18 @@ "attributes": { "properties": { "email": { + "format": "email", "type": "string" }, "invite_expires_at": { + "format": "date-time", "type": "string" }, "message": { "type": "string" }, "user_id": { + "format": "uuid", "type": "string" } }, @@ -2253,12 +2261,14 @@ "attributes": { "properties": { "email": { + "format": "email", "type": "string" }, "message": { "type": "string" }, "user_id": { + "format": "uuid", "type": "string" } }, @@ -2286,6 +2296,7 @@ "type": "boolean" }, "webhook_url": { + "format": "uri", "type": "string" } }, @@ -2349,6 +2360,7 @@ }, "group_access": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -2439,6 +2451,7 @@ "items": { "properties": { "alertId": { + "format": "uuid", "type": "string" }, "emailEnabled": { @@ -2488,6 +2501,7 @@ "properties": { "group_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -2605,9 +2619,13 @@ "$ref": "#/components/schemas/NetSapiensConfigInput" }, "connector_id": { + "format": "uuid", "type": "string" }, "type": { + "enum": [ + "netsapiens" + ], "type": "string" } }, @@ -2651,6 +2669,7 @@ "schema": { "properties": { "url": { + "format": "uri", "type": "string" } }, @@ -2915,6 +2934,7 @@ }, "group_access": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -3024,6 +3044,7 @@ }, "member_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -3085,6 +3106,7 @@ "items": { "properties": { "connector_id": { + "format": "uuid", "type": "string" }, "connector_name": { @@ -3129,18 +3151,21 @@ ] }, "last_changed_at": { + "format": "date-time", "type": [ "string", "null" ] }, "last_changed_by": { + "format": "uuid", "type": [ "string", "null" ] }, "user_id": { + "format": "uuid", "type": "string" } }, @@ -3158,9 +3183,19 @@ "type": "array" }, "digest_frequency": { + "enum": [ + "daily", + "weekly", + "both", + "never" + ], "type": "string" }, "digest_time_format": { + "enum": [ + "12h", + "24h" + ], "type": "string" }, "eoc_enabled": { @@ -3183,9 +3218,18 @@ "call": { "properties": { "call_date": { + "format": "date", "type": "string" }, "call_type": { + "enum": [ + "inbound", + "outbound", + "internal", + "missed", + "forwarded", + "unknown" + ], "type": "string" }, "callee_name": { @@ -3204,6 +3248,7 @@ "type": "integer" }, "id": { + "format": "uuid", "type": "string" }, "platform": { @@ -3224,18 +3269,22 @@ "location": { "properties": { "company_id": { + "format": "uuid", "type": "string" }, "connector_id": { + "format": "uuid", "type": "string" }, "id": { + "format": "uuid", "type": "string" } }, "type": "object" }, "location_id": { + "format": "uuid", "type": "string" }, "summary": { @@ -3262,6 +3311,7 @@ "type": "object" }, "timestamp": { + "format": "date-time", "type": "string" }, "type": { @@ -3287,18 +3337,22 @@ "data": { "properties": { "created_at": { + "format": "date-time", "type": "string" }, "enabled": { "type": "boolean" }, "id": { + "format": "uuid", "type": "string" }, "location_id": { + "format": "uuid", "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" }, "webhook_url": { @@ -3316,9 +3370,11 @@ "Alert": { "properties": { "call_date": { + "format": "date-time", "type": "string" }, "call_id": { + "format": "uuid", "type": "string" }, "callee_name": { @@ -3337,6 +3393,7 @@ "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "keywords": { @@ -3375,12 +3432,22 @@ "type": "boolean" }, "frequency": { + "enum": [ + "daily", + "weekly", + "both", + "never" + ], "type": "string" }, "sendTime": { "type": "string" }, "timeFormat": { + "enum": [ + "12h", + "24h" + ], "type": "string" }, "timezone": { @@ -3450,6 +3517,7 @@ "items": { "properties": { "alertId": { + "format": "uuid", "type": "string" }, "alertName": { @@ -3484,6 +3552,7 @@ "AlertRule": { "properties": { "created_at": { + "format": "date-time", "type": "string" }, "enabled": { @@ -3496,6 +3565,7 @@ "type": "string" }, "id": { + "format": "uuid", "type": "string" } }, @@ -3504,12 +3574,14 @@ "type": "array" }, "id": { + "format": "uuid", "type": "string" }, "is_default": { "type": "boolean" }, "location_id": { + "format": "uuid", "type": "string" }, "match_logic": { @@ -3519,6 +3591,12 @@ "type": "string" }, "priority": { + "enum": [ + "critical", + "high", + "medium", + "low" + ], "type": "string" }, "trigger_types": { @@ -3534,6 +3612,7 @@ "type": "array" }, "updated_at": { + "format": "date-time", "type": "string" } }, @@ -3546,17 +3625,28 @@ }, "group_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" }, "match_logic": { + "enum": [ + "any", + "all" + ], "type": "string" }, "name": { "type": "string" }, "priority": { + "enum": [ + "critical", + "high", + "medium", + "low" + ], "type": "string" }, "triggers": { @@ -3613,17 +3703,28 @@ }, "group_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" }, "match_logic": { + "enum": [ + "any", + "all" + ], "type": "string" }, "name": { "type": "string" }, "priority": { + "enum": [ + "critical", + "high", + "medium", + "low" + ], "type": "string" }, "triggers": { @@ -3742,6 +3843,7 @@ ] }, "call_date": { + "format": "date-time", "type": "string" }, "call_outcome": { @@ -3787,6 +3889,7 @@ "type": "boolean" }, "id": { + "format": "uuid", "type": "string" }, "leg_count": { @@ -3835,6 +3938,7 @@ ] }, "id": { + "format": "uuid", "type": "string" }, "source": { @@ -3860,12 +3964,14 @@ ] }, "recording_url": { + "format": "uri", "type": [ "string", "null" ] }, "recording_url_expires_at": { + "format": "date-time", "type": [ "string", "null" @@ -3928,9 +4034,18 @@ "CallListItem": { "properties": { "call_date": { + "format": "date-time", "type": "string" }, "call_type": { + "enum": [ + "inbound", + "outbound", + "internal", + "missed", + "forwarded", + "unknown" + ], "type": "string" }, "callee_name": { @@ -3976,12 +4091,14 @@ "type": "array" }, "id": { + "format": "uuid", "type": "string" }, "leg_count": { "type": "integer" }, "location_id": { + "format": "uuid", "type": "string" }, "sentiment": { @@ -3997,6 +4114,13 @@ ] }, "status": { + "enum": [ + "completed", + "missed", + "voicemail", + "failed", + "cancelled" + ], "type": "string" }, "summary": { @@ -4018,6 +4142,12 @@ "type": "object" }, "CallSentiment": { + "enum": [ + "positive", + "neutral", + "negative", + null + ], "type": [ "string", "null" @@ -4041,6 +4171,7 @@ "type": "string" }, "created_at": { + "format": "date-time", "type": "string" }, "enabled_products": { @@ -4050,6 +4181,7 @@ "type": "array" }, "id": { + "format": "uuid", "type": "string" }, "is_active": { @@ -4065,6 +4197,7 @@ "type": "boolean" }, "primary_admin_contact_email": { + "format": "email", "type": "string" }, "primary_admin_contact_name": { @@ -4074,12 +4207,14 @@ "type": "string" }, "reseller_id": { + "format": "uuid", "type": "string" }, "reseller_name": { "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" }, "user_count": { @@ -4101,6 +4236,7 @@ "attributes": { "properties": { "company_id": { + "format": "uuid", "type": "string" }, "company_logo_url": { @@ -4116,6 +4252,7 @@ ] }, "created_at": { + "format": "date-time", "type": [ "string", "null" @@ -4170,6 +4307,7 @@ ] }, "updated_at": { + "format": "date-time", "type": [ "string", "null" @@ -4199,15 +4337,18 @@ "type": "string" }, "privacy_policy_url": { + "format": "uri", "type": "string" }, "secondary_accent_color": { "type": "string" }, "support_email": { + "format": "email", "type": "string" }, "terms_of_service_url": { + "format": "uri", "type": "string" } }, @@ -4225,6 +4366,7 @@ "items": { "properties": { "id": { + "format": "uuid", "type": "string" }, "location_name": { @@ -4268,6 +4410,7 @@ "type": "array" }, "primary_admin_contact_email": { + "format": "email", "type": "string" }, "primary_admin_contact_name": { @@ -4296,15 +4439,19 @@ "type": "string" }, "email": { + "format": "email", "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "invite_expires_at": { + "format": "date-time", "type": "string" }, "invited_at": { + "format": "date-time", "type": "string" }, "role": { @@ -4325,9 +4472,11 @@ "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "last_checked_at": { + "format": "date-time", "type": [ "string", "null" @@ -4357,6 +4506,7 @@ "type": "object" }, "verified_at": { + "format": "date-time", "type": [ "string", "null" @@ -4482,6 +4632,7 @@ "type": "boolean" }, "primary_admin_contact_email": { + "format": "email", "type": "string" }, "primary_admin_contact_name": { @@ -4499,18 +4650,25 @@ "CompanyUser": { "properties": { "activated_at": { + "format": "date-time", "type": [ "string", "null" ] }, "auth_method": { + "enum": [ + "password", + "sso" + ], "type": "string" }, "company_id": { + "format": "uuid", "type": "string" }, "created_at": { + "format": "date-time", "type": "string" }, "department": { @@ -4520,27 +4678,32 @@ "type": "string" }, "email": { + "format": "email", "type": "string" }, "first_name": { "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "invite_expires_at": { + "format": "date-time", "type": [ "string", "null" ] }, "invited_at": { + "format": "date-time", "type": [ "string", "null" ] }, "last_login_at": { + "format": "date-time", "type": [ "string", "null" @@ -4553,9 +4716,11 @@ "items": { "properties": { "assigned_at": { + "format": "date-time", "type": "string" }, "location_id": { + "format": "uuid", "type": "string" } }, @@ -4567,15 +4732,26 @@ "type": "string" }, "reseller_id": { + "format": "uuid", "type": "string" }, "role": { + "enum": [ + "customer_admin", + "frontline_user" + ], "type": "string" }, "status": { + "enum": [ + "invited", + "active", + "deactivated" + ], "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" } }, @@ -4628,18 +4804,22 @@ "type": "object" }, "created_at": { + "format": "date-time", "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "last_synced_at": { + "format": "date-time", "type": [ "string", "null" ] }, "location_id": { + "format": "uuid", "type": "string" }, "name": { @@ -4667,6 +4847,7 @@ "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" } }, @@ -4689,18 +4870,22 @@ "ConnectorListItem": { "properties": { "created_at": { + "format": "date-time", "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "last_synced_at": { + "format": "date-time", "type": [ "string", "null" ] }, "location_id": { + "format": "uuid", "type": "string" }, "location_name": { @@ -4731,6 +4916,7 @@ "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" } }, @@ -4745,11 +4931,20 @@ "type": "object" }, "ConnectorStatus": { + "enum": [ + "connecting", + "active", + "connected", + "error", + "deactivating", + "inactive" + ], "type": "string" }, "DomainVerification": { "properties": { "checked_at": { + "format": "date-time", "type": "string" }, "failure_reason": { @@ -4811,6 +5006,7 @@ { "properties": { "id": { + "format": "uuid", "type": "string" } }, @@ -4841,6 +5037,7 @@ "type": "array" }, "webhook_url": { + "format": "uri", "type": [ "string", "null" @@ -4858,6 +5055,7 @@ "items": { "properties": { "id": { + "format": "uuid", "type": "string" }, "is_member": { @@ -4883,15 +5081,26 @@ "IdentityProviderCreate": { "properties": { "acknowledgement": { + "enum": [ + "true", + "yes", + "acknowledged", + "1" + ], "type": "string" }, "client_auth_method": { + "enum": [ + "client_secret", + "none" + ], "type": "string" }, "client_id": { "type": "string" }, "client_secret": { + "format": "password", "type": "string" }, "display_name": { @@ -4901,12 +5110,14 @@ "type": "string" }, "secret_expires_at": { + "format": "date-time", "type": "string" }, "type": { "type": "string" }, "well_known_endpoint": { + "format": "uri", "type": "string" } }, @@ -4931,12 +5142,14 @@ "type": "string" }, "created_at": { + "format": "date-time", "type": "string" }, "display_name": { "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "instructions": { @@ -5087,6 +5300,7 @@ "items": { "properties": { "id": { + "format": "uuid", "type": "string" }, "name": { @@ -5108,6 +5322,7 @@ }, "group_access": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -5122,6 +5337,7 @@ "type": "boolean" }, "id": { + "format": "uuid", "type": "string" } }, @@ -5147,6 +5363,7 @@ "type": "string" }, "company_id": { + "format": "uuid", "type": "string" }, "company_name": { @@ -5156,6 +5373,7 @@ "type": "string" }, "created_at": { + "format": "date-time", "type": "string" }, "enabled_products": { @@ -5165,6 +5383,7 @@ "type": "array" }, "id": { + "format": "uuid", "type": "string" }, "is_active": { @@ -5192,12 +5411,14 @@ "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" }, "user_count": { "type": "integer" }, "vertical_id": { + "format": "uuid", "type": "string" }, "vertical_name": { @@ -5233,6 +5454,7 @@ "type": "string" }, "vertical_id": { + "format": "uuid", "type": "string" }, "zipcode": { @@ -5307,6 +5529,7 @@ "type": "string" }, "vertical_id": { + "format": "uuid", "type": "string" }, "zipcode": { @@ -5318,18 +5541,22 @@ "LocationUser": { "properties": { "assigned_at": { + "format": "date-time", "type": "string" }, "company_id": { + "format": "uuid", "type": "string" }, "created_at": { + "format": "date-time", "type": "string" }, "display_name": { "type": "string" }, "email": { + "format": "email", "type": "string" }, "enabled_products": { @@ -5354,9 +5581,11 @@ ] }, "id": { + "format": "uuid", "type": "string" }, "invited_at": { + "format": "date-time", "type": [ "string", "null" @@ -5366,6 +5595,7 @@ "type": "string" }, "location_id": { + "format": "uuid", "type": "string" }, "location_name": { @@ -5375,9 +5605,11 @@ "items": { "properties": { "assigned_at": { + "format": "date-time", "type": "string" }, "location_id": { + "format": "uuid", "type": "string" } }, @@ -5392,9 +5624,18 @@ "type": "string" }, "role": { + "enum": [ + "customer_admin", + "frontline_user" + ], "type": "string" }, "status": { + "enum": [ + "invited", + "active", + "deactivated" + ], "type": "string" } }, @@ -5436,9 +5677,11 @@ "LoginRequest": { "properties": { "email": { + "format": "email", "type": "string" }, "password": { + "format": "password", "type": "string" } }, @@ -5453,6 +5696,7 @@ "data": { "properties": { "company_id": { + "format": "uuid", "type": [ "string", "null" @@ -5462,6 +5706,7 @@ "type": "string" }, "email": { + "format": "email", "type": "string" }, "enabled_products": { @@ -5477,6 +5722,7 @@ "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "last_name": { @@ -5484,6 +5730,7 @@ }, "location_ids": { "items": { + "format": "uuid", "type": "string" }, "type": [ @@ -5495,6 +5742,7 @@ "type": "boolean" }, "reseller_id": { + "format": "uuid", "type": [ "string", "null" @@ -5513,6 +5761,10 @@ "type": "string" }, "user_type": { + "enum": [ + "company_user", + "reseller_user" + ], "type": "string" } }, @@ -5552,9 +5804,11 @@ "NetSapiensConfigInput": { "properties": { "api_key": { + "format": "password", "type": "string" }, "api_url": { + "format": "uri", "type": "string" }, "domain": { @@ -5571,6 +5825,7 @@ "NumberMapping": { "properties": { "connector_id": { + "format": "uuid", "type": "string" }, "connector_name": { @@ -5591,6 +5846,7 @@ "NumberMappingInput": { "properties": { "connector_id": { + "format": "uuid", "type": "string" }, "monitored_numbers": { @@ -5624,6 +5880,11 @@ "type": "object" }, "ProductKey": { + "enum": [ + "after-call-copilot", + "first-alert-copilot", + "insights-hub" + ], "type": "string" }, "ProductState": { @@ -5632,12 +5893,14 @@ "type": "boolean" }, "enabled_at": { + "format": "date-time", "type": [ "string", "null" ] }, "enabled_by": { + "format": "uuid", "type": [ "string", "null" @@ -5695,6 +5958,7 @@ ] }, "created_at": { + "format": "date-time", "type": [ "string", "null" @@ -5737,6 +6001,7 @@ ] }, "reseller_id": { + "format": "uuid", "type": "string" }, "secondary_accent_color": { @@ -5764,6 +6029,7 @@ ] }, "updated_at": { + "format": "date-time", "type": [ "string", "null" @@ -5793,24 +6059,34 @@ "type": "string" }, "privacy_policy_url": { + "format": "uri", "type": "string" }, "secondary_accent_color": { "type": "string" }, "support_email": { + "format": "email", "type": "string" }, "support_portal_url": { + "format": "uri", "type": "string" }, "terms_of_service_url": { + "format": "uri", "type": "string" } }, "type": "object" }, "Role": { + "enum": [ + "frontline_user", + "customer_admin", + "reseller_admin", + "reseller_support" + ], "type": "string" }, "SmtpSettingsResponse": { @@ -5820,12 +6096,15 @@ "attributes": { "properties": { "created_at": { + "format": "date-time", "type": "string" }, "reseller_id": { + "format": "uuid", "type": "string" }, "sender_email": { + "format": "email", "type": "string" }, "sender_name": { @@ -5844,6 +6123,7 @@ "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" } }, @@ -5861,6 +6141,7 @@ "SmtpSettingsUpdate": { "properties": { "sender_email": { + "format": "email", "type": "string" }, "sender_name": { @@ -5870,6 +6151,7 @@ "type": "string" }, "smtp_password": { + "format": "password", "type": "string" }, "smtp_port": { @@ -5893,18 +6175,22 @@ "$ref": "#/components/schemas/TaskUser" }, "call_id": { + "format": "uuid", "type": "string" }, "company_id": { + "format": "uuid", "type": "string" }, "completed_at": { + "format": "date-time", "type": [ "string", "null" ] }, "created_at": { + "format": "date-time", "type": "string" }, "description": { @@ -5920,21 +6206,34 @@ ] }, "id": { + "format": "uuid", "type": "string" }, "location_id": { + "format": "uuid", "type": "string" }, "source": { + "enum": [ + "ai", + "manual" + ], "type": "string" }, "status": { + "enum": [ + "pending", + "in_progress", + "completed", + "cancelled" + ], "type": "string" }, "title": { "type": "string" }, "updated_at": { + "format": "date-time", "type": "string" } }, @@ -5999,9 +6298,11 @@ "type": "string" }, "email": { + "format": "email", "type": "string" }, "id": { + "format": "uuid", "type": "string" } }, @@ -6033,18 +6334,21 @@ "type": "string" }, "email": { + "format": "email", "type": "string" }, "first_name": { "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "last_name": { "type": "string" }, "reseller_id": { + "format": "uuid", "type": [ "string", "null" @@ -6060,6 +6364,10 @@ "type": "array" }, "user_type": { + "enum": [ + "company_user", + "reseller_user" + ], "type": "string" } }, @@ -6087,9 +6395,11 @@ ] }, "date": { + "format": "date-time", "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "outcome": { @@ -6178,6 +6488,11 @@ { "properties": { "operator": { + "enum": [ + "lt", + "gt", + "eq" + ], "type": "string" }, "threshold": { @@ -6199,6 +6514,11 @@ "type": "array" }, "match_logic": { + "enum": [ + "any", + "all", + "exact_phrase" + ], "type": "string" } }, @@ -6225,9 +6545,15 @@ ] }, "id": { + "format": "uuid", "type": "string" }, "trigger_type": { + "enum": [ + "sentiment", + "keyword_match", + "conversation_topic" + ], "type": "string" } }, @@ -6240,9 +6566,14 @@ "UserCreate": { "properties": { "auth_method": { + "enum": [ + "password", + "sso" + ], "type": "string" }, "email": { + "format": "email", "type": "string" }, "first_name": { @@ -6253,6 +6584,7 @@ }, "location_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -6261,6 +6593,10 @@ "type": "string" }, "role": { + "enum": [ + "customer_admin", + "frontline_user" + ], "type": "string" }, "send_invitation": { @@ -6278,15 +6614,18 @@ "UserGroup": { "properties": { "created_at": { + "format": "date-time", "type": "string" }, "group_name": { "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "location_id": { + "format": "uuid", "type": "string" }, "members": { @@ -6296,12 +6635,14 @@ "type": "string" }, "email": { + "format": "email", "type": "string" }, "first_name": { "type": "string" }, "id": { + "format": "uuid", "type": "string" }, "last_name": { @@ -6313,6 +6654,7 @@ "type": "array" }, "updated_at": { + "format": "date-time", "type": "string" }, "user_count": { @@ -6367,6 +6709,7 @@ }, "location_ids": { "items": { + "format": "uuid", "type": "string" }, "type": "array" @@ -6375,6 +6718,10 @@ "type": "string" }, "role": { + "enum": [ + "customer_admin", + "frontline_user" + ], "type": "string" } }, diff --git a/src/intelligence_cloud/intelligence.py b/src/intelligence_cloud/intelligence.py index ed88b2c..aa3f5d8 100644 --- a/src/intelligence_cloud/intelligence.py +++ b/src/intelligence_cloud/intelligence.py @@ -39,9 +39,13 @@ def _search_term(phone: Optional[str], text: Optional[str]) -> Optional[str]: term = phone if phone is not None else text if term is None: return None - term = str(term).strip() + if not isinstance(term, str): + raise InvalidRequestError("search terms must be strings") + term = term.strip() if len(term) < 2: raise InvalidRequestError("search terms need at least 2 characters (shorter ones are ignored by the API)") + if len(term) > _spec.MAX_TEXT: + raise InvalidRequestError(f"search terms: at most {_spec.MAX_TEXT} characters") return term @@ -70,8 +74,9 @@ def require_frontline(self) -> Dict[str, Any]: def _call_filters(self, phone, text, date_from, date_to, status, sentiment, has_open_tasks, multi_leg, location_ids, company_id) -> Dict[str, Any]: + term = _search_term(phone, text) # checked before signing in self.require_frontline() - return dict(search=_search_term(phone, text), date_from=date_from, date_to=date_to, status=status, + return dict(search=term, date_from=date_from, date_to=date_to, status=status, sentiment=sentiment, has_open_tasks=has_open_tasks, multi_leg=multi_leg, location_id=location_ids, company_id=company_id) @@ -101,11 +106,13 @@ def iter_calls(self, phone: Optional[str] = None, text: Optional[str] = None, def get_call(self, call_id: str) -> Dict[str, Any]: """Call detail: summary, analysis, sentiment, tasks.""" + _spec.check_path_value(call_id, 'call_id') self.require_frontline() return unwrap(self._c.calls.get_call(call_id)) def get_transcript(self, call_id: str) -> List[Dict[str, Any]]: """Transcript segments: ``time``, ``speaker`` ("Speaker 1"...), ``name``, ``text``.""" + _spec.check_path_value(call_id, 'call_id') self.require_frontline() data = unwrap(self._c.calls.get_call_transcript(call_id)) or {} return data.get("transcript") or [] @@ -114,6 +121,7 @@ def get_recording_url(self, call_id: str) -> Optional[RecordingLink]: """The call's recording link and its expiry, or None when the call has no recording. Only the link and expiry are returned. Fetch a new link when it expires.""" + _spec.check_path_value(call_id, 'call_id') self.require_frontline() resp = self._c._request("getCall", {"callId": call_id}, {}, None) link = _spec.recording_link(self._c._json(resp)) @@ -131,10 +139,15 @@ def get_recording_url(self, call_id: str) -> Optional[RecordingLink]: def _alert_filters(self, alert_name, numbers, text, sentiment, date_from, date_to, location_ids, topic, company_id) -> Dict[str, Any]: - self.require_frontline() if numbers is not None and isinstance(numbers, str): numbers = [numbers] - return dict(keyword=alert_name, numbers=numbers, search=_search_term(None, text), sentiment=sentiment, + if numbers is not None: + numbers = [_spec.check_text(n, "numbers") for n in list(numbers)] + if alert_name is not None: + alert_name = _spec.check_text(alert_name, "alert_name") + term = _search_term(None, text) + self.require_frontline() + return dict(keyword=alert_name, numbers=numbers, search=term, sentiment=sentiment, date_from=date_from, date_to=date_to, location_id=location_ids, topic=topic, company_id=company_id) @@ -165,8 +178,8 @@ def iter_alerts(self, alert_name: Optional[str] = None, numbers: Optional[Sequen def get_alert(self, alert_id: str, with_call: bool = False) -> Optional[Dict[str, Any]]: """One alert by id (searched by id, no date window). With ``with_call`` the call detail is added under ``call``. Returns None when the alert is not visible.""" + aid = _spec.check_path_value(_spec.check_text(alert_id, "alert_id"), "alert_id").lower() self.require_frontline() - aid = alert_id.strip().lower() page = self._c.alerts.list_alerts(search=aid, limit=10) alert = next((a for a in page.items if a.get("id") == aid), None) if alert is not None and with_call and alert.get("call_id"): @@ -229,6 +242,7 @@ def list_topic_calls(self, slug: str, date_from: Optional[When] = None, date_to: company_id: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> Page: """Calls for one topic (slug from the dashboard's ``topic_call_volumes``).""" + _spec.check_path_value(slug, 'slug') self.require_frontline() return self._c.insights.list_topic_calls(slug, date_from=date_from, date_to=date_to, sentiment=sentiment, outcome=outcome, search=_search_term(None, search), @@ -239,6 +253,7 @@ def iter_topic_calls(self, slug: str, date_from: Optional[When] = None, date_to: sentiment: Optional[str] = None, outcome: Optional[str] = None, search: Optional[str] = None, location_ids: Optional[Ids] = None, *, company_id: Optional[str] = None) -> Iterator[Dict[str, Any]]: + _spec.check_path_value(slug, 'slug') self.require_frontline() return self._c.insights.iter_topic_calls(slug, date_from=date_from, date_to=date_to, sentiment=sentiment, outcome=outcome, search=_search_term(None, search), diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index 3c25b54..1c4c749 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -16,7 +16,7 @@ from collections import OrderedDict from dataclasses import dataclass, field from datetime import date, datetime, timezone -from typing import Any, Dict, List, Mapping, Optional, Protocol, Union +from typing import Any, Dict, List, Mapping, Optional, Protocol, Tuple, Union from . import _spec from .errors import InvalidRequestError, PayloadTooLargeError, WebhookPayloadError @@ -32,7 +32,7 @@ class AfterCallCall: id: str call_type: str duration_seconds: int - call_date: date + call_date: Optional[date] # None when the string is not YYYY-MM-DD (the schema gives no format) caller_name: Optional[str] = None caller_number: Optional[str] = None callee_name: Optional[str] = None @@ -63,7 +63,7 @@ class AfterCallEvent: type: str is_test: bool location_id: str - timestamp: datetime + timestamp: Optional[datetime] # None when the string is not an RFC 3339 date-time call: AfterCallCall location: AfterCallLocation summary: Optional[AfterCallSummary] = None @@ -79,31 +79,57 @@ class UnknownEvent: raw: Dict[str, Any] = field(default_factory=dict, repr=False) +def _is_type(v: Any, typ: Any) -> bool: + """JSON types as every SDK reads them: an integer is a whole-number JSON number (12 or 12.0, never + true/false); a string, boolean, object or array is exactly that.""" + if typ is int: + return isinstance(v, (int, float)) and not isinstance(v, bool) and float(v).is_integer() + if typ is bool: + return isinstance(v, bool) + return isinstance(v, typ) + + def _req(d: Mapping[str, Any], key: str, typ: Any, where: str) -> Any: + """A field the published schema marks required: refused when missing or of the wrong JSON type.""" if key not in d: raise WebhookPayloadError(f"{where}.{key} is missing") v = d[key] - if typ is int and isinstance(v, bool): + if not _is_type(v, typ): raise WebhookPayloadError(f"{where}.{key} has the wrong type") - if not isinstance(v, typ): - raise WebhookPayloadError(f"{where}.{key} has the wrong type") - return v + return int(v) if typ is int else v + +def _opt(d: Mapping[str, Any], key: str, typ: Any = str) -> Any: + """A field the schema does not mark required: None when absent or of the wrong JSON type.""" + v = d.get(key) + return v if v is not None and _is_type(v, typ) else None -def _ts(value: str, where: str) -> datetime: + +def _str_list(d: Mapping[str, Any], key: str) -> List[str]: + v = d.get(key) + return [x for x in v if isinstance(x, str)] if isinstance(v, list) else [] + + +def _ts(value: str, where: str) -> Optional[datetime]: try: return datetime.fromisoformat(value.replace("Z", "+00:00").replace("z", "+00:00")).astimezone(timezone.utc) except (ValueError, AttributeError): try: return datetime.fromisoformat(_spec.format_datetime(value, where).replace("Z", "+00:00")) except Exception: - raise WebhookPayloadError(f"{where} is not an RFC 3339 timestamp") from None + return None def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int = MAX_EVENT_BYTES) -> Union[AfterCallEvent, UnknownEvent]: """Parse and check an After Call webhook body. Fields outside the published schema are dropped. + The same rule in every SDK: the event is refused exactly when a field the published schema marks + required (version, type, is_test, location_id, timestamp, call, location; call.id, call.call_type, + call.duration_seconds, call.call_date) is missing or has the wrong JSON type. Other fields may be + absent, and are None when they have the wrong type. A ``type`` other than "end_of_call_summary" is + an :class:`UnknownEvent`. ``call_date`` and ``timestamp`` are None when their text is not a date. + Returns :class:`AfterCallEvent`, or :class:`UnknownEvent` for any other event type (answer 2xx and ignore it). Raises :class:`PayloadTooLargeError` (answer 413) for a body over ``max_bytes`` and :class:`WebhookPayloadError` (answer 400) for a body that is not JSON or a malformed After Call event. @@ -114,7 +140,9 @@ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], if max_bytes and len(body) > max_bytes: raise PayloadTooLargeError(f"body is larger than {max_bytes} bytes") try: - body = json.loads(bytes(body).decode("utf-8-sig")) + body = loads_ijson(bytes(body)) + except WebhookPayloadError: + raise except (ValueError, UnicodeDecodeError): raise WebhookPayloadError("body is not JSON") from None if not isinstance(body, Mapping): @@ -124,35 +152,38 @@ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], return UnknownEvent(type=typ if isinstance(typ, str) else None, version=ver if isinstance(ver, str) else None, raw=dict(body)) data = _spec.project(dict(body), _spec.schema_by_name("AfterCallSummaryEvent")) + version = _req(data, "version", str, "event") + is_test = _req(data, "is_test", bool, "event") + location_id = _req(data, "location_id", str, "event") + stamp = _req(data, "timestamp", str, "event") call = _req(data, "call", dict, "event") loc = _req(data, "location", dict, "event") + call_id = _req(call, "id", str, "call") + call_type = _req(call, "call_type", str, "call") + duration = _req(call, "duration_seconds", int, "call") + call_date_text = _req(call, "call_date", str, "call") try: - call_date = date.fromisoformat(_req(call, "call_date", str, "call")) + call_date: Optional[date] = date.fromisoformat(call_date_text) if len(call_date_text) == 10 else None except ValueError: - raise WebhookPayloadError("call.call_date is not YYYY-MM-DD") from None + call_date = None summary = data.get("summary") return AfterCallEvent( - version=_req(data, "version", str, "event"), + version=version, type=data["type"], - is_test=_req(data, "is_test", bool, "event"), - location_id=_req(data, "location_id", str, "event"), - timestamp=_ts(_req(data, "timestamp", str, "event"), "timestamp"), + is_test=is_test, + location_id=location_id, + timestamp=_ts(stamp, "timestamp"), call=AfterCallCall( - id=_req(call, "id", str, "call"), - call_type=_req(call, "call_type", str, "call"), - duration_seconds=_req(call, "duration_seconds", int, "call"), - call_date=call_date, - caller_name=call.get("caller_name"), - caller_number=call.get("caller_number"), - callee_name=call.get("callee_name"), - callee_number=call.get("callee_number"), - platform=call.get("platform"), + id=call_id, call_type=call_type, duration_seconds=duration, call_date=call_date, + caller_name=_opt(call, "caller_name"), caller_number=_opt(call, "caller_number"), + callee_name=_opt(call, "callee_name"), callee_number=_opt(call, "callee_number"), + platform=_opt(call, "platform"), ), - location=AfterCallLocation(id=loc.get("id") or data["location_id"], company_id=loc.get("company_id"), - connector_id=loc.get("connector_id")), + location=AfterCallLocation(id=_opt(loc, "id") or location_id, company_id=_opt(loc, "company_id"), + connector_id=_opt(loc, "connector_id")), summary=AfterCallSummary( - text=summary.get("text"), sentiment=summary.get("sentiment"), - key_points=list(summary.get("key_points") or []), action_items=list(summary.get("action_items") or []), + text=_opt(summary, "text"), sentiment=_opt(summary, "sentiment"), + key_points=_str_list(summary, "key_points"), action_items=_str_list(summary, "action_items"), ) if isinstance(summary, dict) else None, raw=data, ) @@ -194,6 +225,128 @@ def _first_str(*values: Any) -> Optional[str]: +# ---------------------------------------------------------------------- RFC 8785 canonical JSON + + +def _no_duplicates(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]: + out: Dict[str, Any] = {} + for k, v in pairs: + if k in out: + raise WebhookPayloadError("body has a duplicate object key") + out[k] = v + return out + + +def _no_constant(name: str) -> Any: + raise WebhookPayloadError(f"body has {name}, which is not JSON") + + +def loads_ijson(raw: Union[bytes, str]) -> Any: + """Parse a delivery body as I-JSON: UTF-8 (a leading byte-order mark is ignored), no duplicate object + keys, no NaN or Infinity. Lone surrogates are refused when the value is canonicalised.""" + text = raw.decode("utf-8-sig") if isinstance(raw, (bytes, bytearray)) else raw.lstrip("\ufeff") + return json.loads(text, object_pairs_hook=_no_duplicates, parse_constant=_no_constant) + + +def es_number(x: float) -> str: + """A finite double as ECMAScript's Number::toString writes it (RFC 8785 section 3.2.2.3).""" + if x != x or x in (float("inf"), float("-inf")): + raise WebhookPayloadError("NaN and Infinity are not JSON") + if x == 0: + return "0" + if x < 0: + return "-" + es_number(-x) + # repr() gives the shortest digits that round-trip, as ECMAScript requires. + mant, _, exp = repr(x).partition("e") + int_part, _, frac = mant.partition(".") + digits = (int_part + frac).lstrip("0") + n = len(int_part.lstrip("0")) + (int(exp) if exp else 0) # decimal point position + if not int_part.lstrip("0"): # 0.000123: leading zeros in the fraction move the point left + n = (int(exp) if exp else 0) - (len(frac) - len(frac.lstrip("0"))) + digits = digits.rstrip("0") or "0" + k = len(digits) + if k <= n <= 21: + return digits + "0" * (n - k) + if 0 < n <= 21: + return digits[:n] + "." + digits[n:] + if -6 < n <= 0: + return "0." + "0" * (-n) + digits + e = n - 1 + sign = "+" if e >= 0 else "-" + return (digits if k == 1 else digits[0] + "." + digits[1:]) + "e" + sign + str(abs(e)) + + +_ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"} + + +def _es_string(value: str) -> str: + out = ['"'] + for ch in value: + o = ord(ch) + if 0xD800 <= o <= 0xDFFF: + raise WebhookPayloadError("body has a lone surrogate, which is not I-JSON") + if ch in _ESCAPES: + out.append(_ESCAPES[ch]) + elif o < 0x20: + out.append("\\u%04x" % o) + else: + out.append(ch) + out.append('"') + return "".join(out) + + +def _utf16_key(k: str) -> bytes: + return k.encode("utf-16-be", "surrogatepass") + + +def _canonical(value: Any, out: List[str]) -> None: + if value is None: + out.append("null") + elif value is True: + out.append("true") + elif value is False: + out.append("false") + elif isinstance(value, str): + out.append(_es_string(value)) + elif isinstance(value, int): + try: + out.append(es_number(float(value))) # every number is a double: beyond 2^53 precision is lost + except OverflowError: + raise WebhookPayloadError("body has a number too large for a double") from None + elif isinstance(value, float): + out.append(es_number(value)) + elif isinstance(value, Mapping): + for k in value: + if not isinstance(k, str): + raise WebhookPayloadError("object keys must be strings") + out.append("{") + for i, k in enumerate(sorted(value, key=_utf16_key)): + if i: + out.append(",") + out.append(_es_string(k)) + out.append(":") + _canonical(value[k], out) + out.append("}") + elif isinstance(value, (list, tuple)): + out.append("[") + for i, v in enumerate(value): + if i: + out.append(",") + _canonical(v, out) + out.append("]") + else: + raise WebhookPayloadError(f"{type(value).__name__} is not a JSON value") + + +def canonical_json(value: Any) -> bytes: + """The RFC 8785 (JSON Canonicalization Scheme) form of a parsed JSON value, UTF-8 encoded: keys sorted + by UTF-16 code units, numbers as ECMAScript doubles, only the mandatory string escapes, no whitespace. + Lone surrogates, NaN and Infinity raise WebhookPayloadError.""" + out: List[str] = [] + _canonical(value, out) + return "".join(out).encode("utf-8") + + def _plain_id(value: Optional[str]) -> Optional[str]: return value if value is not None and ID_RE.match(value) else None @@ -205,7 +358,9 @@ def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping if max_bytes and len(body) > max_bytes: raise PayloadTooLargeError(f"body is larger than {max_bytes} bytes") try: - body = json.loads(bytes(body).decode("utf-8-sig")) + body = loads_ijson(bytes(body)) + except WebhookPayloadError: + raise except (ValueError, UnicodeDecodeError): raise WebhookPayloadError("body is not JSON") from None if not isinstance(body, Mapping): @@ -286,9 +441,8 @@ def add(self, key: str) -> None: def _canonical_hash(body: Any) -> str: - """A stable hash of a JSON body: keys sorted, no whitespace.""" - text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str) - return hashlib.sha256(text.encode("utf-8")).hexdigest() + """SHA-256 (hex) of the RFC 8785 canonical form of ``body``.""" + return hashlib.sha256(canonical_json(body)).hexdigest() def _as_event(item: Any) -> Any: @@ -344,8 +498,8 @@ class Deduplicator: ``seen`` only checks; it records nothing, so a delivery whose storage failed is processed again when the sender retries. A delivery's identity is its event type, location and call (or alert) id - **and** its content (a SHA-256 of the canonical JSON body: the payload carries no per-delivery - version). A later delivery for the same call with changed content is not seen: upsert it. + **and** its content: the SHA-256 of the RFC 8785 canonical JSON (:func:`canonical_json`) of the event + as the SDK reads it (the payload carries no per-delivery version). A later delivery for the same call with changed content is not seen: upsert it. Takes an event object, a parsed body or the raw request bytes; a string that is not JSON is refused (InvalidRequestError), because an id alone cannot tell newer data apart. The same names in diff --git a/src/intelligence_cloud/testing/_fake.py b/src/intelligence_cloud/testing/_fake.py index be528a7..d1466ff 100644 --- a/src/intelligence_cloud/testing/_fake.py +++ b/src/intelligence_cloud/testing/_fake.py @@ -6,7 +6,7 @@ import re import uuid from dataclasses import dataclass, field -from datetime import datetime, time as dtime, timedelta, timezone +from datetime import date, datetime, time as dtime, timedelta, timezone from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple import httpx @@ -88,11 +88,16 @@ class FakeAPI: - a path or method the published spec does not define (404); - a query parameter it does not define (400), or a query value of the wrong type (integer, boolean), - outside its enum, or not in its format (uuid, date-time) (400); + outside its enum or range, or not in its format (400); - a body missing a required top-level field, with a top-level field the spec does not define, or with a top-level field of the wrong JSON type, outside its enum or not in its format; for a list, each item's type, enum and format (422). + Formats use explicit patterns, the same in every SDK: whole number ``-?(0|[1-9][0-9]*)``; date + ``YYYY-MM-DD`` on a real calendar day; date-time RFC 3339 with seconds, "T" and "Z" or "+HH:MM"; uuid + hyphenated, all lower or all upper case. Body enums and formats come from the bundled spec. + Secret-named values (key, secret, token, password, pwd, credential, auth) are masked in the log. + It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts; its data is simpler than the platform's. Run once against a test company before release. @@ -202,19 +207,24 @@ def fail_write(self, nth: int = 1, status: int = 400) -> None: self._fail = (nth - 1, status) def fail_next(self, status: Optional[int] = None, *, network: Optional[str] = None, - method: Optional[str] = None, path: Optional[str] = None, retry_after: Optional[float] = None) -> None: + method: Optional[str] = None, path: Optional[str] = None, retry_after: Optional[float] = None, + after_processing: bool = False) -> None: """Make the next request that matches ``method`` and the path regex ``path`` (without /api/v1; sign-in is "/auth/login", renewal "/auth/refresh") fail once: with HTTP ``status``, or with a ``network`` failure: "connect" (never left), "read_timeout" or "write_timeout" (left, no answer), - or "undecodable" (an answer that cannot be read). A renewal that fails in any way except - "connect" has already used its refresh token, as a gateway error after the platform would.""" + or "undecodable" (an answer that cannot be read). + + By default the failure comes **before** the platform acts on the request: nothing changes and a + renewal's refresh token is still unused. With ``after_processing=True`` the platform has acted + first (a write is applied, a refresh token is rotated) and the answer is lost, as with a gateway + error after the server. "connect" is always before.""" if (status is None) == (network is None): raise ValueError("fail_next: give status or network") if network is not None and network not in NETWORK_FAILURES: raise ValueError(f"network: one of {NETWORK_FAILURES}") self._next_failures.append({"status": status, "network": network, "method": method, "path": re.compile("^" + path + "$") if path else None, - "retry_after": retry_after}) + "retry_after": retry_after, "after": bool(after_processing)}) def network_down(self, down: bool = True) -> None: """Every request fails as if there were no network (the client raises NetworkError).""" @@ -346,9 +356,10 @@ def __call__(self, request: httpx.Request) -> httpx.Response: return refused elif op_id is None: return _error(501, "NOT_IMPLEMENTED", f"{request.method} {path} is not served by this fake") + before = failure is not None and not failure["after"] + if before: + return self._failure_response(failure, request) # nothing happens on the server if path == "/auth/login": - if failure is not None: - return self._failure_response(failure, request) email = (body or {}).get("email") role = self._logins.get(email, self._role) self._auth_log.append(("login", str(email))) @@ -359,7 +370,7 @@ def __call__(self, request: httpx.Request) -> httpx.Response: self._auth_log.append(("refresh", owner[1])) issued = self._issue(*owner) if failure is not None: - return self._failure_response(failure, request) # the token is used already + return self._failure_response(failure, request) # after processing: the token is used already if owner is None: return _error(401, "UNAUTHORIZED", "Invalid refresh token") return httpx.Response(200, json=issued) @@ -369,11 +380,10 @@ def __call__(self, request: httpx.Request) -> httpx.Response: if token not in self._access: return _error(401, "UNAUTHORIZED", "The access token is not valid") self._request_role = self._access[token][0] - self.requests.append(FakeRequest(request.method, path, dict(request.url.params), body, op_id)) + logged = _masked(body) + self.requests.append(FakeRequest(request.method, path, dict(request.url.params), logged, op_id)) self._calls.append((request.method, full)) - self._bodies.append((request.method, full, body)) - if failure is not None: - return self._failure_response(failure, request) + self._bodies.append((request.method, full, logged)) if request.method != "GET" and self._fail is not None: left, status = self._fail if left == 0: @@ -387,6 +397,8 @@ def __call__(self, request: httpx.Request) -> httpx.Response: out = fn(request, body, *m.groups()) except KeyError: return _error(404, "NOT_FOUND", "Not found") + if failure is not None: # after processing: applied, but the answer is lost + return self._failure_response(failure, request) if isinstance(out, httpx.Response): return out status, payload = out @@ -946,24 +958,50 @@ def _loc_user(self, u: Dict[str, Any], lid: str) -> Dict[str, Any]: if g["location_id"] == lid and u["id"] in g["members"]]} +_MASK_WORDS = ("key", "secret", "token", "password", "passwd", "pwd", "credential", "auth") + + +def _masked(value: Any) -> Any: + """A copy with the values of secret-named fields replaced by "***", at any depth.""" + if isinstance(value, dict): + return {k: ("***" if any(w in str(k).lower() for w in _MASK_WORDS) else _masked(v)) for k, v in value.items()} + if isinstance(value, list): + return [_masked(v) for v in value] + return value + + NETWORK_FAILURES = ("connect", "read_timeout", "write_timeout", "undecodable") _JSON_TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict} +# Explicit patterns, the same in every SDK's testing module (no lenient library parsing). +INTEGER_RE = re.compile(r"^-?(0|[1-9][0-9]*)$") +DATE_RE = re.compile(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})$") +DATE_TIME_RE = re.compile(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?" + r"(Z|[+-]([0-9]{2}):([0-9]{2}))$") +UUID_RE = re.compile(r"^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + r"|[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})$") + + +def _real_date(y: str, m: str, d: str) -> bool: + try: + date(int(y), int(m), int(d)) + return True + except ValueError: + return False + + def _format_problem(fmt: Optional[str], value: str) -> Optional[str]: - if fmt == "uuid" and not _spec.is_uuid(value): - return "not a UUID" + if fmt == "uuid" and not UUID_RE.match(value): + return "not a UUID (hyphenated, all lower or all upper case)" if fmt == "date-time": - try: - parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) - except ValueError: - return "not an RFC 3339 date-time" - if parsed.tzinfo is None: - return "a date-time needs a time zone" + m = DATE_TIME_RE.match(value) + if (not m or not _real_date(*m.group(1, 2, 3)) or int(m.group(4)) > 23 or int(m.group(5)) > 59 + or int(m.group(6)) > 59 or (m.group(9) and (int(m.group(9)) > 23 or int(m.group(10)) > 59))): + return "not an RFC 3339 date-time (YYYY-MM-DDTHH:MM:SS, then Z or +HH:MM)" if fmt == "date": - try: - datetime.strptime(value, "%Y-%m-%d") - except ValueError: + m = DATE_RE.match(value) + if not m or not _real_date(*m.groups()): return "not a date (YYYY-MM-DD)" return None @@ -1011,10 +1049,9 @@ def _query_problem(q: Mapping[str, Any], raw: str) -> Optional[str]: for v in values: it = item.get("type") if it == "integer": - try: - n = int(v) - except ValueError: + if not INTEGER_RE.match(v): return "must be a whole number" + n = int(v) if "minimum" in item and n < item["minimum"] or "maximum" in item and n > item["maximum"]: return f"must be from {item.get('minimum')} to {item.get('maximum')}" continue diff --git a/tests/unit/fixtures/after_call_parse_vectors.json b/tests/unit/fixtures/after_call_parse_vectors.json new file mode 100644 index 0000000..5d64b87 --- /dev/null +++ b/tests/unit/fixtures/after_call_parse_vectors.json @@ -0,0 +1,182 @@ +[ + { + "name": "the sample event", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "every required field present" + }, + { + "name": "missing version", + "raw": "{\"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "version is required" + }, + { + "name": "missing is_test", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "is_test is required" + }, + { + "name": "missing location_id", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "location_id is required" + }, + { + "name": "missing timestamp", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "timestamp is required" + }, + { + "name": "missing call", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call is required" + }, + { + "name": "missing location", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}}", + "result": "refused", + "reason": "location is required" + }, + { + "name": "missing call.id", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id is required" + }, + { + "name": "missing call.call_type", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.call_type is required" + }, + { + "name": "missing call.duration_seconds", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.duration_seconds is required" + }, + { + "name": "missing call.call_date", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.call_date is required" + }, + { + "name": "version is a number", + "raw": "{\"version\": 1, \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "version must be a string" + }, + { + "name": "is_test is the string \"true\"", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": \"true\", \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "is_test must be a boolean" + }, + { + "name": "call.id is a number", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": 5, \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id must be a string" + }, + { + "name": "call.call_date is a number", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": 20261102, \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.call_date must be a string" + }, + { + "name": "duration_seconds is a string", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": \"184\", \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "duration_seconds must be an integer" + }, + { + "name": "duration_seconds is 184.5", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184.5, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "an integer is a whole number" + }, + { + "name": "duration_seconds is true", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": true, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "a boolean is not an integer" + }, + { + "name": "duration_seconds is 184.0", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184.0, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "a whole-number JSON number is an integer" + }, + { + "name": "location is a string", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": \"loc\"}", + "result": "refused", + "reason": "location must be an object" + }, + { + "name": "call.caller_name is a number", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": 5, \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "optional field of the wrong type: accepted, read as absent" + }, + { + "name": "summary missing", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "summary is optional" + }, + { + "name": "summary is a string", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": \"text\", \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "optional field of the wrong type" + }, + { + "name": "location without id", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "location.id is optional" + }, + { + "name": "call_date is not a date", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"yesterday\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "ok", + "reason": "a string; the schema gives no format: call_date reads as None" + }, + { + "name": "an unknown field", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}, \"extra\": 1}", + "result": "ok", + "reason": "unknown fields are dropped" + }, + { + "name": "another event type", + "raw": "{\"version\": \"1.0\", \"type\": \"something_new\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "unknown", + "reason": "UnknownEvent: answer 2xx" + }, + { + "name": "type missing", + "raw": "{\"version\": \"1.0\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "unknown", + "reason": "UnknownEvent: answer 2xx" + }, + { + "name": "a JSON array", + "raw": "[1, 2]", + "result": "refused", + "reason": "not an object" + }, + { + "name": "not JSON", + "raw": "{", + "result": "refused", + "reason": "not JSON" + } +] diff --git a/tests/unit/fixtures/canonical_vectors.json b/tests/unit/fixtures/canonical_vectors.json new file mode 100644 index 0000000..d9bd206 --- /dev/null +++ b/tests/unit/fixtures/canonical_vectors.json @@ -0,0 +1,170 @@ +[ + { + "name": "RFC 8785 number 1e21", + "value_json": "1e21", + "canonical": "1e+21", + "error": false + }, + { + "name": "1e-7", + "value_json": "1e-7", + "canonical": "1e-7", + "error": false + }, + { + "name": "0.000001", + "value_json": "0.000001", + "canonical": "0.000001", + "error": false + }, + { + "name": "333333333.33333329", + "value_json": "333333333.33333329", + "canonical": "333333333.3333333", + "error": false + }, + { + "name": "1E30", + "value_json": "1E30", + "canonical": "1e+30", + "error": false + }, + { + "name": "4.50", + "value_json": "4.50", + "canonical": "4.5", + "error": false + }, + { + "name": "2e-3", + "value_json": "2e-3", + "canonical": "0.002", + "error": false + }, + { + "name": "1e-27", + "value_json": "0.000000000000000000000000001", + "canonical": "1e-27", + "error": false + }, + { + "name": "1.0", + "value_json": "1.0", + "canonical": "1", + "error": false + }, + { + "name": "1E2", + "value_json": "1E2", + "canonical": "100", + "error": false + }, + { + "name": "-0.0", + "value_json": "-0.0", + "canonical": "0", + "error": false + }, + { + "name": "0.1+0.2 as written", + "value_json": "0.30000000000000004", + "canonical": "0.30000000000000004", + "error": false + }, + { + "name": "2^53 + 1", + "value_json": "9007199254740993", + "canonical": "9007199254740992", + "error": false + }, + { + "name": "2^68", + "value_json": "295147905179352830000", + "canonical": "295147905179352830000", + "error": false + }, + { + "name": "largest double", + "value_json": "1.7976931348623157e308", + "canonical": "1.7976931348623157e+308", + "error": false + }, + { + "name": "smallest double", + "value_json": "5e-324", + "canonical": "5e-324", + "error": false + }, + { + "name": "-1.5", + "value_json": "-1.5", + "canonical": "-1.5", + "error": false + }, + { + "name": "1e20", + "value_json": "1e20", + "canonical": "100000000000000000000", + "error": false + }, + { + "name": "RFC 8785 key order", + "value_json": "{\"\\u20ac\":\"Euro Sign\",\"\\r\":\"Carriage Return\",\"\\ufb33\":\"Hebrew Letter Dalet With Dagesh\",\"1\":\"One\",\"\\ud83d\\ude00\":\"Emoji: Grinning Face\",\"\\u0080\":\"Control\",\"\\u00f6\":\"Latin Small Letter O With Diaeresis\"}", + "canonical": "{\"\\r\":\"Carriage Return\",\"1\":\"One\",\"€\":\"Control\",\"ö\":\"Latin Small Letter O With Diaeresis\",\"€\":\"Euro Sign\",\"😀\":\"Emoji: Grinning Face\",\"דּ\":\"Hebrew Letter Dalet With Dagesh\"}", + "error": false + }, + { + "name": "escapes", + "value_json": "\"\\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u0001 \\u001F \\u2028 \\u2029 \\u00e9\"", + "canonical": "\"\\\" \\\\ / \\b \\f \\n \\r \\t \\u0001 \\u001f 
 
 é\"", + "error": false + }, + { + "name": "literals and nesting", + "value_json": "[null, true, false, {}, [], {\"b\": [], \"a\": {}}]", + "canonical": "[null,true,false,{},[],{\"a\":{},\"b\":[]}]", + "error": false + }, + { + "name": "whitespace", + "value_json": " { \"b\" : 1 ,\n \"a\" : [ 1 , 2 ] } ", + "canonical": "{\"a\":[1,2],\"b\":1}", + "error": false + }, + { + "name": "lone surrogate", + "value_json": "\"\\ud800\"", + "canonical": null, + "error": true + }, + { + "name": "duplicate key", + "value_json": "{\"a\":1,\"a\":2}", + "canonical": null, + "error": true + }, + { + "name": "NaN", + "value_json": "NaN", + "canonical": null, + "error": true + }, + { + "name": "Infinity", + "value_json": "[Infinity]", + "canonical": null, + "error": true + }, + { + "name": "-Infinity", + "value_json": "-Infinity", + "canonical": null, + "error": true + }, + { + "name": "number too large", + "value_json": "1e400", + "canonical": null, + "error": true + } +] diff --git a/tests/unit/fixtures/delivery_key_vectors.json b/tests/unit/fixtures/delivery_key_vectors.json new file mode 100644 index 0000000..ea615ae --- /dev/null +++ b/tests/unit/fixtures/delivery_key_vectors.json @@ -0,0 +1,224 @@ +[ + { + "name": "sample event", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "changed summary text", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The appointment moved to Friday.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:d311820e72eb6ee4d6305490cf6c4806118153f12551a82c3e70bd6bc7083513", + "error": false + }, + { + "name": "same event, keys in another order", + "raw": "{\"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"call\": {\"platform\": \"netsapiens\", \"callee_number\": \"2001\", \"callee_name\": \"Riverbend Service Desk\", \"caller_number\": \"5555550142\", \"caller_name\": \"Jordan Example\", \"call_date\": \"2026-11-02\", \"duration_seconds\": 184, \"call_type\": \"inbound\", \"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\"}, \"timestamp\": \"2026-11-02T16:46:12Z\", \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"is_test\": false, \"type\": \"end_of_call_summary\", \"version\": \"1.0\"}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "same event, insignificant whitespace", + "raw": "{\n \"version\": \"1.0\",\n \"type\": \"end_of_call_summary\",\n \"is_test\": false,\n \"location_id\": \"11111111-2222-4333-8444-555555555555\",\n \"timestamp\": \"2026-11-02T16:46:12Z\",\n \"call\": {\n \"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\",\n \"call_type\": \"inbound\",\n \"duration_seconds\": 184,\n \"call_date\": \"2026-11-02\",\n \"caller_name\": \"Jordan Example\",\n \"caller_number\": \"5555550142\",\n \"callee_name\": \"Riverbend Service Desk\",\n \"callee_number\": \"2001\",\n \"platform\": \"netsapiens\"\n },\n \"summary\": {\n \"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\",\n \"sentiment\": \"positive\"\n },\n \"location\": {\n \"id\": \"11111111-2222-4333-8444-555555555555\",\n \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\",\n \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"\n }\n}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "same event, compact", + "raw": "{\"version\":\"1.0\",\"type\":\"end_of_call_summary\",\"is_test\":false,\"location_id\":\"11111111-2222-4333-8444-555555555555\",\"timestamp\":\"2026-11-02T16:46:12Z\",\"call\":{\"id\":\"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\",\"call_type\":\"inbound\",\"duration_seconds\":184,\"call_date\":\"2026-11-02\",\"caller_name\":\"Jordan Example\",\"caller_number\":\"5555550142\",\"callee_name\":\"Riverbend Service Desk\",\"callee_number\":\"2001\",\"platform\":\"netsapiens\"},\"summary\":{\"text\":\"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\",\"sentiment\":\"positive\"},\"location\":{\"id\":\"11111111-2222-4333-8444-555555555555\",\"company_id\":\"66666666-7777-4888-8999-aaaaaaaaaaaa\",\"connector_id\":\"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "same event, non-ASCII escaped as \\u", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "unknown fields are dropped before hashing", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\", \"new_field\": \"v\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}, \"extra_field\": {\"x\": 1}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "duration 9007199254740993 (beyond 2^53)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 9007199254740993, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:3c0b62c66cbbb036ec013e2814e7f5a3c4b7c8259e66cb206a11ef0f5fa63558", + "error": false + }, + { + "name": "duration 9007199254740992 (2^53): collides with the next one by rule, numbers are doubles", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 9007199254740992, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:3c0b62c66cbbb036ec013e2814e7f5a3c4b7c8259e66cb206a11ef0f5fa63558", + "error": false + }, + { + "name": "duration 184.0 equals 184", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184.0, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:9b45617185ec095622589f1f97a3a2c3fdaecdd4710d00785f4e89bdd836322c", + "error": false + }, + { + "name": "summary.sentiment null", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": null}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:5ff0064954a8df036ec7e80a60c586fe8a471fef267bef572aca3b1ec17defc5", + "error": false + }, + { + "name": "summary.sentiment missing", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:367daa06f219806003b6ed935f2741633c7a283244a7241b6f71ea49b8fb12a2", + "error": false + }, + { + "name": "summary.key_points empty array", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\", \"key_points\": []}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:866f35907858315d7b067e127753942a610034decce674b6656f2bf733cdf671", + "error": false + }, + { + "name": "summary.key_points empty object", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\", \"key_points\": {}}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:4453939dcf46e325d4dc150d7c6eaa48729915e2e3356b17ee9420369efd1c71", + "error": false + }, + { + "name": "non-ASCII and non-BMP text in a value", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"Café ☕ — 😀 𝄞 日本\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:1f5228587f3256411c703305576906d2a1d25f9594a4d4c9da7ddefef43d5425", + "error": false + }, + { + "name": "every mandatory escape, U+2028, U+2029 and '/' in a value", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"q\\\" b\\\\ s/ \\b\\f\\n\\r\\t \\u0001 \\u001f 
 
\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee:96695720cd4703c2f2bc27fc4cc8e511fee53ac3fcab48f0b21ca42d3e7222a3", + "error": false + }, + { + "name": "a different call", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-000000000002\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": "end_of_call_summary:11111111-2222-4333-8444-555555555555:aaaaaaaa-bbbb-4ccc-8ddd-000000000002:a1c0c624b8ec430174d64b57957fd1330800860c192f14cadb8b4f0321291913", + "error": false + }, + { + "name": "First Alert event", + "raw": "{\"alert_id\": \"fa-1001\", \"rule_name\": \"Upset Customer\", \"location_id\": \"loc-1\", \"call_id\": \"call-1\", \"timestamp\": \"2026-11-02T16:46:12Z\"}", + "key": "first_alert:fa-1001:597ee967d1d999c983232e7ad09a287a5974e12308b6fda6cd79ddcbf43e2d40", + "error": false + }, + { + "name": "First Alert with the number 1.0", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 1.0}", + "key": "first_alert:fa-num:a895bcf54df2018f2027f82b2490660fd53609dd68584e43085f304c4268cff8", + "error": false + }, + { + "name": "First Alert with the number 1", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 1}", + "key": "first_alert:fa-num:a895bcf54df2018f2027f82b2490660fd53609dd68584e43085f304c4268cff8", + "error": false + }, + { + "name": "First Alert with the number 1.5", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 1.5}", + "key": "first_alert:fa-num:3ea289b4acfdbe4bfdef605fe0c9ef549af6c8d1433577bca0ea6fef07db8c71", + "error": false + }, + { + "name": "First Alert with the number 1E2", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 1E2}", + "key": "first_alert:fa-num:b4a74fbb8919fe122c8d09274d87277ad8303c1f0f6ed0a75869537de936da79", + "error": false + }, + { + "name": "First Alert with the number 100", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 100}", + "key": "first_alert:fa-num:b4a74fbb8919fe122c8d09274d87277ad8303c1f0f6ed0a75869537de936da79", + "error": false + }, + { + "name": "First Alert with the number -0.0", + "raw": "{\"alert_id\": \"fa-num\", \"score\": -0.0}", + "key": "first_alert:fa-num:df8af7ca4bf0ffd39441cd30662982ae29f8e6957daf3341da47394613545368", + "error": false + }, + { + "name": "First Alert with the number 0", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 0}", + "key": "first_alert:fa-num:df8af7ca4bf0ffd39441cd30662982ae29f8e6957daf3341da47394613545368", + "error": false + }, + { + "name": "First Alert with the number 0.30000000000000004", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 0.30000000000000004}", + "key": "first_alert:fa-num:be6d97d637810f44c8499598de040f13d06797bfd6eee6da365e5e9a2c5c687a", + "error": false + }, + { + "name": "First Alert with the number 1e21", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 1e21}", + "key": "first_alert:fa-num:70cda09ff73bcd4811ea86e2f1dd96101936d1665b950cb4b5aa2a44ab13a3c4", + "error": false + }, + { + "name": "First Alert with the number 1e-7", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 1e-7}", + "key": "first_alert:fa-num:32f42ec044d6880580cb63b608df7b923aab72125ad26d06d8ae541d42e0fd37", + "error": false + }, + { + "name": "First Alert with the number 0.000001", + "raw": "{\"alert_id\": \"fa-num\", \"score\": 0.000001}", + "key": "first_alert:fa-num:f133369b1e8f7700a554664d73fffc6b62f1c32a0ed95ec8c1eaa0c3c287646f", + "error": false + }, + { + "name": "First Alert with keys whose UTF-16 order differs from code-point order", + "raw": "{\"alert_id\": \"fa-keys\", \"😀\": \"emoji (surrogates D83D DE00)\", \"ア\": \"half-width katakana\", \"דּ\": \"hebrew presentation form\", \"a\": \"ascii\"}", + "key": "first_alert:fa-keys:8762e801a9de2c84a9edfe7b353b6d296ad929d2c0fbc1868230a2919ab56b81", + "error": false + }, + { + "name": "the same keys in another order", + "raw": "{\"ア\": \"half-width katakana\", \"a\": \"ascii\", \"דּ\": \"hebrew presentation form\", \"alert_id\": \"fa-keys\", \"😀\": \"emoji (surrogates D83D DE00)\"}", + "key": "first_alert:fa-keys:8762e801a9de2c84a9edfe7b353b6d296ad929d2c0fbc1868230a2919ab56b81", + "error": false + }, + { + "name": "lone surrogate (refused)", + "raw": "{\"alert_id\": \"fa-bad\", \"text\": \"\\ud800\"}", + "key": null, + "error": true + }, + { + "name": "lone low surrogate in an After Call field (refused)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"\\udc00\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "duplicate object keys (refused)", + "raw": "{\"alert_id\": \"fa-dup\", \"alert_id\": \"fa-dup2\"}", + "key": null, + "error": true + }, + { + "name": "not JSON (refused)", + "raw": "{\"alert_id\": \"fa-1\",", + "key": null, + "error": true + }, + { + "name": "NaN (refused)", + "raw": "{\"alert_id\": \"fa-nan\", \"score\": NaN}", + "key": null, + "error": true + }, + { + "name": "Infinity (refused)", + "raw": "{\"alert_id\": \"fa-inf\", \"score\": Infinity}", + "key": null, + "error": true + } +] diff --git a/tests/unit/fixtures/fake_strictness_vectors.json b/tests/unit/fixtures/fake_strictness_vectors.json new file mode 100644 index 0000000..33b12a2 --- /dev/null +++ b/tests/unit/fixtures/fake_strictness_vectors.json @@ -0,0 +1,267 @@ +[ + { + "name": "limit=+5", + "method": "GET", + "path": "/calls", + "query": { + "limit": "+5" + }, + "body": null, + "status": 400 + }, + { + "name": "limit=5_0", + "method": "GET", + "path": "/calls", + "query": { + "limit": "5_0" + }, + "body": null, + "status": 400 + }, + { + "name": "limit=05", + "method": "GET", + "path": "/calls", + "query": { + "limit": "05" + }, + "body": null, + "status": 400 + }, + { + "name": "limit=5 (valid)", + "method": "GET", + "path": "/calls", + "query": { + "limit": "5" + }, + "body": null, + "status": 200 + }, + { + "name": "date-time without seconds", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-11-01T10:00Z" + }, + "body": null, + "status": 400 + }, + { + "name": "date-time with a space for T", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-11-01 10:00:00Z" + }, + "body": null, + "status": 400 + }, + { + "name": "offset without a colon", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-11-01T10:00:00+0000" + }, + "body": null, + "status": 400 + }, + { + "name": "date-time on 30 February", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-02-30T10:00:00Z" + }, + "body": null, + "status": 400 + }, + { + "name": "date-time without a time zone", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-11-01T10:00:00" + }, + "body": null, + "status": 400 + }, + { + "name": "date-time with Z (valid)", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-11-01T10:00:00Z" + }, + "body": null, + "status": 200 + }, + { + "name": "date-time with +01:00 and fraction (valid)", + "method": "GET", + "path": "/calls", + "query": { + "date_from": "2026-11-01T10:00:00.5+01:00" + }, + "body": null, + "status": 200 + }, + { + "name": "due_on=2026-1-5", + "method": "GET", + "path": "/tasks", + "query": { + "due_on": "2026-1-5" + }, + "body": null, + "status": 400 + }, + { + "name": "due_on on 30 February", + "method": "GET", + "path": "/tasks", + "query": { + "due_on": "2026-02-30" + }, + "body": null, + "status": 400 + }, + { + "name": "due_on=2026-01-05 (valid)", + "method": "GET", + "path": "/tasks", + "query": { + "due_on": "2026-01-05" + }, + "body": null, + "status": 200 + }, + { + "name": "uuid without hyphens", + "method": "GET", + "path": "/calls", + "query": { + "location_id": "0193b6c26b297a51b0e41c8f3d5e7a02" + }, + "body": null, + "status": 400 + }, + { + "name": "uuid in mixed case", + "method": "GET", + "path": "/calls", + "query": { + "location_id": "0193B6c2-6b29-7a51-b0e4-1c8f3d5e7a02" + }, + "body": null, + "status": 400 + }, + { + "name": "uuid in upper case (valid)", + "method": "GET", + "path": "/calls", + "query": { + "location_id": "0193B6C2-6B29-7A51-B0E4-1C8F3D5E7A02" + }, + "body": null, + "status": 200 + }, + { + "name": "status outside its enum", + "method": "GET", + "path": "/calls", + "query": { + "status": "bogus" + }, + "body": null, + "status": 400 + }, + { + "name": "unknown query parameter", + "method": "GET", + "path": "/calls", + "query": { + "page_size": "10" + }, + "body": null, + "status": 400 + }, + { + "name": "body: boolean given as a string", + "method": "PATCH", + "path": "/locations/{location_id}/insights-hub/config", + "query": null, + "body": { + "monitor_all_numbers": "yes" + }, + "status": 422 + }, + { + "name": "body: unknown field", + "method": "PATCH", + "path": "/locations/{location_id}/insights-hub/config", + "query": null, + "body": { + "monitor_all_numbers": false, + "zzz": 1 + }, + "status": 422 + }, + { + "name": "body: valid", + "method": "PATCH", + "path": "/locations/{location_id}/insights-hub/config", + "query": null, + "body": { + "monitor_all_numbers": false + }, + "status": 200 + }, + { + "name": "body: string given as a number", + "method": "POST", + "path": "/locations/{location_id}/user-groups", + "query": null, + "body": { + "group_name": 5 + }, + "status": 422 + }, + { + "name": "body: missing required field", + "method": "POST", + "path": "/locations/{location_id}/user-groups", + "query": null, + "body": { + "member_ids": [] + }, + "status": 422 + }, + { + "name": "body: enum (connector type)", + "method": "POST", + "path": "/locations/{location_id}/connectors", + "query": null, + "body": { + "name": "x", + "type": "examplepbx", + "config": { + "api_url": "https://pbx.example.com/ns-api/v2", + "domain": "d.example.com", + "api_key": "example-key" + } + }, + "status": 422 + }, + { + "name": "unknown path", + "method": "GET", + "path": "/calls/export/all", + "query": null, + "body": null, + "status": 404 + } +] diff --git a/tests/unit/fixtures/retry_after_vectors.json b/tests/unit/fixtures/retry_after_vectors.json new file mode 100644 index 0000000..9a71bf4 --- /dev/null +++ b/tests/unit/fixtures/retry_after_vectors.json @@ -0,0 +1,94 @@ +[ + { + "header": "0", + "seconds": 0.0 + }, + { + "header": "5", + "seconds": 5.0 + }, + { + "header": "1.5", + "seconds": 1.5 + }, + { + "header": "120", + "seconds": 120.0 + }, + { + "header": "007", + "seconds": 7.0 + }, + { + "header": "999999999", + "seconds": 999999999.0 + }, + { + "header": "999999999.25", + "seconds": 999999999.25 + }, + { + "header": "1234567890", + "seconds": null + }, + { + "header": "-1", + "seconds": null + }, + { + "header": "", + "seconds": null + }, + { + "header": " 5", + "seconds": null + }, + { + "header": "5 ", + "seconds": null + }, + { + "header": "1e2", + "seconds": null + }, + { + "header": "INF", + "seconds": null + }, + { + "header": "NaN", + "seconds": null + }, + { + "header": "Infinity", + "seconds": null + }, + { + "header": "Wed, 21 Oct 2015 07:28:00 GMT", + "seconds": null + }, + { + "header": "1.", + "seconds": null + }, + { + "header": ".5", + "seconds": null + }, + { + "header": "+5", + "seconds": null + }, + { + "header": "0x10", + "seconds": null + }, + { + "header": "1,5", + "seconds": null + }, + { + "header": "5s", + "seconds": null + } +] diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index e0fb739..2549a51 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -244,7 +244,10 @@ def test_connector_spec_hides_secrets(): assert "pbx.example.com" in text and cs.config["client_secret"] == "S3CRET" -def test_connector_of_another_type_from_type_and_config(api, caplog): +def test_connector_of_another_type_from_type_and_config(caplog): + # The published spec lists only "netsapiens", so strict mode would refuse another type: this test is + # about the SDK's generic path (a type the API adds later), so the fake runs without strictness. + api = FakeAPI(strict=False) caplog.set_level(logging.DEBUG) other = ic.ConnectorSpec(type="examplepbx", config={"host": "pbx.example.com", "domain": "rb.example", "api_token": "T0KEN-SECRET"}) diff --git a/tests/unit/test_intelligence.py b/tests/unit/test_intelligence.py index 5d17998..ff7124c 100644 --- a/tests/unit/test_intelligence.py +++ b/tests/unit/test_intelligence.py @@ -152,7 +152,7 @@ def test_parse_after_call_event(): @pytest.mark.parametrize("mutate", [ lambda e: e.pop("call"), lambda e: e["call"].update(duration_seconds="284"), - lambda e: e["call"].update(call_date="yesterday"), + lambda e: e["call"].update(call_date=20261102), ]) def test_parse_rejects_bad_events(mutate): bad = json.loads(json.dumps(EVENT)) @@ -161,6 +161,12 @@ def test_parse_rejects_bad_events(mutate): ic.parse_after_call_event(bad) +def test_a_required_string_that_is_not_a_date_is_kept_as_none(): + odd = json.loads(json.dumps(EVENT)) + odd["call"]["call_date"] = "yesterday" + assert ic.parse_after_call_event(odd).call.call_date is None + + def test_parse_rejects_non_json(): with pytest.raises(ic.WebhookPayloadError): ic.parse_after_call_event(b"") diff --git a/tests/unit/test_request_counts.py b/tests/unit/test_request_counts.py index c9768fc..9fb9449 100644 --- a/tests/unit/test_request_counts.py +++ b/tests/unit/test_request_counts.py @@ -10,12 +10,12 @@ # helper -> (1-team customer, 10-team customer); each measured with a fresh client, so GET /me is included EXPECTED = { "create_customer": (35, 35), - "add_team (2nd team)": (None, 21), - "add_team (10th team)": (None, 21), + "add_team (2nd team)": (None, 25), + "add_team (10th team)": (None, 25), "create_customer, re-run": (19, 19), "add_base_user": (36, 90), - "add_base_manager (every team)": (29, 137), - "activate_alerts": (14, 86), + "add_base_manager (every team)": (33, 168), + "activate_alerts": (18, 117), "calls (one page)": (2, 2), "brief": (3, 3), } diff --git a/tests/unit/test_review_030.py b/tests/unit/test_review_030.py index 2cc12db..95a2482 100644 --- a/tests/unit/test_review_030.py +++ b/tests/unit/test_review_030.py @@ -73,12 +73,25 @@ def test_the_fake_catches_refresh_token_reuse(failure): me = api.client(role="user") me.conversations.calls() api.expire_access_tokens() - api.fail_next(**failure, path="/auth/refresh") + api.fail_next(**failure, path="/auth/refresh", after_processing=True) me.conversations.calls() # renewal fails after the platform used the token: the client signs in kinds = [k for k, _ in api.auth_log] assert "refresh_reused" not in kinds and kinds[-2:] == ["refresh", "login"] +@pytest.mark.parametrize("failure", [{"status": 429, "retry_after": 1}, {"network": "connect"}]) +def test_a_renewal_refused_before_processing_keeps_its_token(failure): + api = FakeAPI() + api.seed_calls(1) + me = api.client(role="user") + me.conversations.calls() + api.reset_log() + api.expire_access_tokens() + api.fail_next(**failure, path="/auth/refresh") # before processing (the default): the token is unused + assert len(me.conversations.calls()) == 1 + assert [k for k, _ in api.auth_log] == ["refresh"] # the same token, sent again, worked: no reuse, no sign-in + + def test_the_fake_ends_every_session_when_a_refresh_token_is_reused(): api = FakeAPI() t = api._issue("frontline_user", "user.1@example.com") diff --git a/tests/unit/test_shared_vectors.py b/tests/unit/test_shared_vectors.py new file mode 100644 index 0000000..a3ae4a3 --- /dev/null +++ b/tests/unit/test_shared_vectors.py @@ -0,0 +1,254 @@ +"""The cross-language rules: shared vectors (tests/unit/fixtures/*.json, copied to every SDK), the path +rule, free-text arguments, masked request logs and stale Customer objects.""" +from __future__ import annotations + +import json +import math +from datetime import datetime, timezone +from pathlib import Path + +import httpx +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.client import parse_retry_after +from intelligence_cloud.receiver import canonical_json, delivery_key, loads_ijson +from intelligence_cloud.testing import FakeAPI + +FIX = Path(__file__).resolve().parent / "fixtures" +BASE = "https://app.intelligence.cloud/api/v1" + + +def load(name): + return json.loads((FIX / name).read_text(encoding="utf-8")) + + +# ---------------------------------------------------------------------- shared vectors + + +@pytest.mark.parametrize("v", load("delivery_key_vectors.json"), ids=lambda v: v["name"]) +def test_delivery_key_vectors(v): + for raw in (v["raw"], v["raw"].encode("utf-8")): + if v["error"]: + with pytest.raises(ic.WebhookPayloadError): + delivery_key(raw) + else: + assert delivery_key(raw) == v["key"] + + +def test_delivery_key_vectors_cover_the_rule(): + vs = load("delivery_key_vectors.json") + assert len(vs) >= 20 and sum(v["error"] for v in vs) >= 4 + by = {v["name"]: v["key"] for v in vs} + assert by["duration 9007199254740993 (beyond 2^53)"] == by[ + "duration 9007199254740992 (2^53): collides with the next one by rule, numbers are doubles"] + assert by["summary.key_points empty array"] != by["summary.key_points empty object"] + assert by["summary.sentiment null"] != by["summary.sentiment missing"] + assert by["unknown fields are dropped before hashing"] == by["sample event"] + + +@pytest.mark.parametrize("v", load("canonical_vectors.json"), ids=lambda v: v["name"]) +def test_canonical_vectors(v): + if v["error"]: + with pytest.raises((ic.WebhookPayloadError, ValueError)): + canonical_json(loads_ijson(v["value_json"])) + else: + assert canonical_json(loads_ijson(v["value_json"])) == v["canonical"].encode("utf-8") + + +def test_canonical_refuses_values_that_are_not_i_json(): + for bad in (float("nan"), float("inf"), {"a": "\ud800"}, {1: "x"}, object()): + with pytest.raises(ic.WebhookPayloadError): + canonical_json(bad) + + +@pytest.mark.parametrize("v", load("retry_after_vectors.json"), ids=lambda v: repr(v["header"])) +def test_retry_after_vectors(v): + got = parse_retry_after(v["header"]) + assert got == v["seconds"] and (got is None or isinstance(got, float)) + + +def test_retry_after_outside_the_pattern_means_backoff(): + def h(r): + if r.url.path.endswith("/auth/login"): + return httpx.Response(200, json={"access_token": "A", "refresh_token": "R", "expires_in": 900, + "user": {"id": "u", "role": "frontline_user"}}) + return httpx.Response(429, headers={"Retry-After": "1e2"}, json={}) + sleeps = [] + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(h), sleep=sleeps.append, max_retries=2) + with pytest.raises(ic.RateLimitError) as e: + c.account.get_me() + assert e.value.retry_after is None and len(sleeps) == 2 and all(s < 10 for s in sleeps) + + +@pytest.mark.parametrize("v", load("after_call_parse_vectors.json"), ids=lambda v: v["name"]) +def test_after_call_parse_vectors(v): + if v["result"] == "refused": + with pytest.raises(ic.WebhookPayloadError): + ic.parse_after_call_event(v["raw"]) + else: + ev = ic.parse_after_call_event(v["raw"]) + assert type(ev).__name__ == ("AfterCallEvent" if v["result"] == "ok" else "UnknownEvent") + + +def test_parse_vectors_are_enough(): + assert len(load("after_call_parse_vectors.json")) >= 15 + + +@pytest.mark.parametrize("v", load("fake_strictness_vectors.json"), ids=lambda v: v["name"]) +def test_fake_strictness_vectors(v): + api = FakeAPI() + seeded = api.seed_customer(people=False) + token = api._issue("reseller_admin", "admin.vectors@example.com")["access_token"] + path = v["path"].format(company_id=seeded.company_id, location_id=seeded.customer.teams[0].location_id) + raw = httpx.Client(base_url=BASE, transport=httpx.MockTransport(api)) + r = raw.request(v["method"], path, params=v["query"], json=v["body"], + headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == v["status"], r.text + if r.status_code >= 400: + assert set(r.json()["error"]) >= {"code", "message"} + + +def test_vector_copies_match_the_shared_folder_when_present(): + shared = Path("/private/tmp/claude-501/-Users-robertgalop-Dev/7ebbbd38-ce89-42da-b25d-ac8d3f58f6de/scratchpad/shared-vectors") + if not shared.exists(): + pytest.skip("the shared folder is not on this machine") + for f in FIX.glob("*.json"): + assert (shared / f.name).read_bytes() == f.read_bytes(), f.name + + +# ---------------------------------------------------------------------- the path rule + + +class Count: + def __init__(self): + self.n = 0 + + def __call__(self, r): + self.n += 1 + raise httpx.ConnectError("down", request=r) + + +BAD_IDS = ["..", ".", "", "a/b", "a\\b", "a?b", "a#b", "a%2Fb", "a b", "a\tb", "a\x00b", "x" * 129, None, 5] + + +@pytest.mark.parametrize("bad", BAD_IDS) +def test_path_arguments_that_could_change_the_url_are_refused(bad): + t = Count() + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(t), sleep=lambda s: None, max_retries=0) + for call in (lambda: c.users.deactivate_company_user("cid", bad), # generated method + lambda: c.intelligence.get_call(bad), # intelligence helper + lambda: c.accounts.remove_user("cid", bad), # accounts helper + lambda: c.accounts.remove_user(bad, "uid"), + lambda: c.conversations.brief(bad)): # conversations helper + with pytest.raises(ic.InvalidRequestError): + call() + assert t.n == 0 + + +def test_a_plain_id_is_percent_encoded_and_sent(): + api = FakeAPI() + s = api.seed_customer(people=False) + admin = api.client(role="admin") + with pytest.raises(ic.NotFoundError): + admin.users.get_company_user(s.company_id, "no-such_user.1") + assert api.requests[-1].path == f"/companies/{s.company_id}/users/no-such_user.1" + + +# ---------------------------------------------------------------------- free text + + +@pytest.mark.parametrize("bad", [float("nan"), True, {}, object(), datetime.now(timezone.utc), 5555550142, " ", "y" * 201]) +def test_free_text_must_be_a_real_string(bad): + t = Count() + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(t), sleep=lambda s: None, max_retries=0) + for call in (lambda: c.conversations.caller_history(bad), lambda: c.conversations.calls(search=bad), + lambda: c.conversations.calls(number=bad), lambda: c.intelligence.search_calls(phone=bad), + lambda: c.intelligence.search_calls(text=bad), lambda: c.intelligence.search_alerts(numbers=[bad]), + lambda: c.intelligence.get_alert(bad)): + with pytest.raises(ic.InvalidRequestError): + call() + assert t.n == 0 + + +# ---------------------------------------------------------------------- masked request log + + +def test_the_request_log_masks_secrets(): + api = FakeAPI() + s = api.seed_customer(people=False) + admin = api.client(role="admin") + admin.accounts.add_team(s.customer, ic.TeamSpec("Riverbend - East", "9 Lake St", "Springfield", "IL", "US", + "62702", "service-providers"), + ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "east.example.com", + "KEY-SECRET-123")) + text = repr(api.requests) + json.dumps([r.body for r in api.requests]) + assert "KEY-SECRET-123" not in text and "fake-password" not in text + created = next(r for r in api.requests if r.path.endswith("/connectors") and r.method == "POST") + assert created.body["config"]["api_key"] == "***" and created.body["config"]["domain"] == "east.example.com" + + +# ---------------------------------------------------------------------- stale Customer objects + + +def _second_team_behind_the_back(api, s): + other = api.client(role="admin") + other.accounts.add_team(s.company_id, ic.TeamSpec("Riverbend - East", "9 Lake St", "Springfield", "IL", "US", + "62702", "service-providers"), + ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "east.example.com", + "example-key")) + return other.accounts.get_customer(s.company_id).teams[1] + + +def test_a_stale_customer_is_refreshed_before_set_alerts(): + api = FakeAPI() + s = api.seed_customer(people=False) + stale = s.customer + east = _second_team_behind_the_back(api, s) + admin = api.client(role="admin") + admin.accounts.set_alerts(stale, ic.AlertSettings(customer_threat=ic.AlertSetting(phrases=["example phrase"]))) + assert [t.location_id for t in stale.teams][-1] == east.location_id and stale.refreshed_at + fresh = admin.accounts.get_customer(s.company_id) + assert all(t.rules.customer_threat for t in fresh.teams) and "customer_threat" not in fresh.pending + + +def test_a_stale_customer_is_refreshed_for_activate_sync_and_report(): + api = FakeAPI() + s = api.seed_customer(people=True) + stale = s.customer + east = _second_team_behind_the_back(api, s) + admin = api.client(role="admin") + out = admin.accounts.activate_alerts(stale) + assert any(r["location_id"] == east.location_id for r in api._rules.values() if r["enabled"]) + assert east.location_id in {t["location_id"] for t in out["no_manager"]} + diff = admin.accounts.sync_lines(stale) + assert east.location_id in diff["teams"] + assert admin.accounts.license_report(stale)["teams"] == 2 + + +def test_a_group_removed_behind_the_objects_back_is_noticed(): + api = FakeAPI() + s = api.seed_customer(people=False) + team = s.customer.teams[0] + gid = team.groups.upset_customers + del api._groups[gid] # removed elsewhere + admin = api.client(role="admin") + start = len(api.requests) + with pytest.raises(ic.InvalidRequestError) as e: + admin.accounts.add_base_manager(s.customer, ic.PersonSpec("lee.park@example.com", "Lee", "Park"), + teams=[team], invite=False) + assert "Upset Customers" in str(e.value) and api.writes_since(start) == [] + + +def test_a_hand_built_customer_with_another_companys_ids_is_refused(): + api = FakeAPI() + a = api.seed_customer(people=False) + other = api.client(role="admin").accounts.create_customer(ic.CustomerSpec( + "Lakeside Auto Group", ic.PersonSpec("sam.lee@example.com", "Sam", "Lee", phone_number="+15555550101"), + ic.TeamSpec("Lakeside - Main", "1 Lake Rd", "Springfield", "IL", "US", "62703", "service-providers"), + connector=ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "lakeside.example.com", "example-key"))) + forged = ic.Customer(company_id=a.company_id, management=other.management, teams=list(other.teams)) + start = len(api.requests) + with pytest.raises(ic.InvalidRequestError): + api.client(role="admin").accounts.activate_alerts(forged) + assert api.writes_since(start) == [] diff --git a/tools/generate.py b/tools/generate.py index b6d6c95..ccdc415 100644 --- a/tools/generate.py +++ b/tools/generate.py @@ -42,7 +42,8 @@ "Insights": ("insights", "InsightsAPI"), "Events and webhooks": ("webhooks", "WebhooksAPI"), } -KEEP = {"type", "properties", "items", "oneOf", "anyOf", "allOf", "additionalProperties", "$ref", "required"} +KEEP = {"type", "properties", "items", "oneOf", "anyOf", "allOf", "additionalProperties", "$ref", "required", + "enum", "format"} # enum and format let the testing module check body values def snake(name: str) -> str: diff --git a/tools/make_shared_vectors.py b/tools/make_shared_vectors.py new file mode 100644 index 0000000..a4b4d20 --- /dev/null +++ b/tools/make_shared_vectors.py @@ -0,0 +1,268 @@ +"""Write the cross-language test vectors every SDK asserts (the Python SDK is the reference). + + uv run --with httpx --with-editable . python tools/make_shared_vectors.py [extra_output_dir] + +Writes into tests/unit/fixtures/ (and the same files into extra_output_dir, when given): + delivery_key_vectors.json {name, raw, key, error}: the exact delivery body and its delivery key + canonical_vectors.json {name, value_json, canonical, error}: RFC 8785 serialisation alone + retry_after_vectors.json {header, seconds}: Retry-After parsing (null = treated as absent) + after_call_parse_vectors.json {name, raw, result, reason}: result "ok", "refused" or "unknown" + fake_strictness_vectors.json {name, method, path, query, body, status}: the testing module's strict mode + +Expected values come from the reference implementation; the script checks the properties each case +exists to show (collisions, differences, refusals) before writing. +""" +from __future__ import annotations + +import copy +import json +import pathlib +import sys + +from intelligence_cloud.client import parse_retry_after +from intelligence_cloud.errors import WebhookPayloadError +from intelligence_cloud.receiver import canonical_json, delivery_key, loads_ijson, parse_after_call_event + +HERE = pathlib.Path(__file__).resolve().parent.parent +OUT = HERE / "tests" / "unit" / "fixtures" +SAMPLE = json.loads((HERE / "examples" / "after-call-sample.json").read_text()) + + +def dumps(value) -> str: + return json.dumps(value, ensure_ascii=False, separators=(", ", ": ")) + + +def key_of(raw: str): + try: + return delivery_key(raw), False + except WebhookPayloadError: + return None, True + + +def delivery_vectors(): + s = copy.deepcopy(SAMPLE) + s["is_test"] = False + v = [] + + def add(name, raw): + key, err = key_of(raw) + v.append({"name": name, "raw": raw, "key": key, "error": err}) + return key + + def ac(mutate=None): + e = copy.deepcopy(s) + if mutate: + mutate(e) + return dumps(e) + + base = add("sample event", ac()) + changed = add("changed summary text", ac(lambda e: e["summary"].update(text="The appointment moved to Friday."))) + assert changed != base + shuffled = json.loads(ac()) + shuffled = dict(reversed(list(shuffled.items()))) + shuffled["call"] = dict(reversed(list(shuffled["call"].items()))) + assert add("same event, keys in another order", dumps(shuffled)) == base + assert add("same event, insignificant whitespace", json.dumps(json.loads(ac()), indent=4)) == base + assert add("same event, compact", json.dumps(json.loads(ac()), separators=(",", ":"))) == base + assert add("same event, non-ASCII escaped as \\u", json.dumps(json.loads(ac()), ensure_ascii=True)) == base + unknown = add("unknown fields are dropped before hashing", + ac(lambda e: (e.update(extra_field={"x": 1}), e["call"].update(new_field="v")))) + assert unknown == base + big1 = add("duration 9007199254740993 (beyond 2^53)", ac(lambda e: e["call"].update(duration_seconds=9007199254740993))) + big0 = add("duration 9007199254740992 (2^53): collides with the next one by rule, numbers are doubles", + ac(lambda e: e["call"].update(duration_seconds=9007199254740992))) + assert big0 == big1 + whole = add("duration 184.0 equals 184", ac(lambda e: e["call"].update(duration_seconds=184.0))) + assert whole == base + null = add("summary.sentiment null", ac(lambda e: e["summary"].update(sentiment=None))) + missing = add("summary.sentiment missing", ac(lambda e: e["summary"].pop("sentiment"))) + assert null != missing + empty_list = add("summary.key_points empty array", ac(lambda e: e["summary"].update(key_points=[]))) + empty_obj = add("summary.key_points empty object", ac(lambda e: e["summary"].update(key_points={}))) + assert empty_list != empty_obj + add("non-ASCII and non-BMP text in a value", ac(lambda e: e["summary"].update(text="Café ☕ — 😀 𝄞 日本"))) + add("every mandatory escape, U+2028, U+2029 and '/' in a value", + ac(lambda e: e["summary"].update(text="q\" b\\ s/ \b\f\n\r\t \u0001 \u001f 
 
"))) + other_call = add("a different call", ac(lambda e: e["call"].update(id="aaaaaaaa-bbbb-4ccc-8ddd-000000000002"))) + assert other_call != base + + def fa(payload): + return dumps(payload) + add("First Alert event", fa({"alert_id": "fa-1001", "rule_name": "Upset Customer", "location_id": "loc-1", + "call_id": "call-1", "timestamp": "2026-11-02T16:46:12Z"})) + floats = {} + for text in ("1.0", "1", "1.5", "1E2", "100", "-0.0", "0", "0.30000000000000004", "1e21", "1e-7", "0.000001"): + floats[text] = add(f"First Alert with the number {text}", + '{"alert_id": "fa-num", "score": %s}' % text) + assert floats["1.0"] == floats["1"] and floats["1E2"] == floats["100"] and floats["-0.0"] == floats["0"] + assert floats["1.5"] != floats["1"] + k1 = add("First Alert with keys whose UTF-16 order differs from code-point order", + fa({"alert_id": "fa-keys", "\U0001F600": "emoji (surrogates D83D DE00)", "ア": "half-width katakana", + "דּ": "hebrew presentation form", "a": "ascii"})) + k2 = add("the same keys in another order", + fa({"ア": "half-width katakana", "a": "ascii", "דּ": "hebrew presentation form", + "alert_id": "fa-keys", "\U0001F600": "emoji (surrogates D83D DE00)"})) + assert k1 == k2 + for name, raw in (("lone surrogate (refused)", '{"alert_id": "fa-bad", "text": "\\ud800"}'), + ("lone low surrogate in an After Call field (refused)", + ac(lambda e: e["summary"].update(text="x")).replace('"x"', '"\\udc00"')), + ("duplicate object keys (refused)", '{"alert_id": "fa-dup", "alert_id": "fa-dup2"}'), + ("not JSON (refused)", '{"alert_id": "fa-1",'), + ("NaN (refused)", '{"alert_id": "fa-nan", "score": NaN}'), + ("Infinity (refused)", '{"alert_id": "fa-inf", "score": Infinity}')): + key, err = key_of(raw) + if not err: + raise SystemExit(f"expected a refusal: {name}") + v.append({"name": name, "raw": raw, "key": None, "error": True}) + return v + + +def canonical_vectors(): + cases = [ + ("RFC 8785 number 1e21", "1e21", "1e+21"), ("1e-7", "1e-7", "1e-7"), ("0.000001", "0.000001", "0.000001"), + ("333333333.33333329", "333333333.33333329", "333333333.3333333"), ("1E30", "1E30", "1e+30"), + ("4.50", "4.50", "4.5"), ("2e-3", "2e-3", "0.002"), ("1e-27", "0.000000000000000000000000001", "1e-27"), + ("1.0", "1.0", "1"), ("1E2", "1E2", "100"), ("-0.0", "-0.0", "0"), ("0.1+0.2 as written", "0.30000000000000004", + "0.30000000000000004"), + ("2^53 + 1", "9007199254740993", "9007199254740992"), ("2^68", "295147905179352830000", "295147905179352830000"), + ("largest double", "1.7976931348623157e308", "1.7976931348623157e+308"), ("smallest double", "5e-324", "5e-324"), + ("-1.5", "-1.5", "-1.5"), ("1e20", "1e20", "100000000000000000000"), + ("RFC 8785 key order", '{"\\u20ac":"Euro Sign","\\r":"Carriage Return","\\ufb33":"Hebrew Letter Dalet With Dagesh",' + '"1":"One","\\ud83d\\ude00":"Emoji: Grinning Face","\\u0080":"Control","\\u00f6":"Latin Small Letter O With Diaeresis"}', + '{"\\r":"Carriage Return","1":"One","\u0080":"Control","ö":"Latin Small Letter O With Diaeresis","€":"Euro Sign",' + '"\U0001F600":"Emoji: Grinning Face","דּ":"Hebrew Letter Dalet With Dagesh"}'), + ("escapes", '"\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u0001 \\u001F \\u2028 \\u2029 \\u00e9"', + '"\\" \\\\ / \\b \\f \\n \\r \\t \\u0001 \\u001f 
 
 é"'), + ("literals and nesting", '[null, true, false, {}, [], {"b": [], "a": {}}]', '[null,true,false,{},[],{"a":{},"b":[]}]'), + ("whitespace", ' { "b" : 1 ,\n "a" : [ 1 , 2 ] } ', '{"a":[1,2],"b":1}'), + ] + out = [] + for name, value_json, want in cases: + got = canonical_json(loads_ijson(value_json)).decode("utf-8") + if got != want: + raise SystemExit(f"canonical mismatch {name}: {got!r} != {want!r}") + out.append({"name": name, "value_json": value_json, "canonical": want, "error": False}) + for name, value_json in (("lone surrogate", '"\\ud800"'), ("duplicate key", '{"a":1,"a":2}'), ("NaN", "NaN"), + ("Infinity", "[Infinity]"), ("-Infinity", "-Infinity"), ("number too large", "1e400")): + try: + canonical_json(loads_ijson(value_json)) + except (WebhookPayloadError, ValueError): + out.append({"name": name, "value_json": value_json, "canonical": None, "error": True}) + continue + raise SystemExit(f"expected a refusal: {name}") + return out + + +def retry_after_vectors(): + headers = ["0", "5", "1.5", "120", "007", "999999999", "999999999.25", "1234567890", "-1", "", " 5", "5 ", "1e2", + "INF", "NaN", "Infinity", "Wed, 21 Oct 2015 07:28:00 GMT", "1.", ".5", "+5", "0x10", "1,5", "5s"] + return [{"header": h, "seconds": parse_retry_after(h)} for h in headers] + + +def parse_vectors(): + s = copy.deepcopy(SAMPLE) + out = [] + + def add(name, mutate=None, raw=None, reason=""): + e = copy.deepcopy(s) + if mutate: + mutate(e) + body = raw if raw is not None else dumps(e) + try: + ev = parse_after_call_event(body) + result = "ok" if type(ev).__name__ == "AfterCallEvent" else "unknown" + except WebhookPayloadError: + result = "refused" + out.append({"name": name, "raw": body, "result": result, "reason": reason}) + return result + + assert add("the sample event", reason="every required field present") == "ok" + for f in ("version", "is_test", "location_id", "timestamp", "call", "location"): + assert add(f"missing {f}", lambda e, f=f: e.pop(f), reason=f"{f} is required") == "refused" + for f in ("id", "call_type", "duration_seconds", "call_date"): + assert add(f"missing call.{f}", lambda e, f=f: e["call"].pop(f), reason=f"call.{f} is required") == "refused" + assert add("version is a number", lambda e: e.update(version=1), reason="version must be a string") == "refused" + assert add("is_test is the string \"true\"", lambda e: e.update(is_test="true"), reason="is_test must be a boolean") == "refused" + assert add("call.id is a number", lambda e: e["call"].update(id=5), reason="call.id must be a string") == "refused" + assert add("call.call_date is a number", lambda e: e["call"].update(call_date=20261102), + reason="call.call_date must be a string") == "refused" + assert add("duration_seconds is a string", lambda e: e["call"].update(duration_seconds="184"), + reason="duration_seconds must be an integer") == "refused" + assert add("duration_seconds is 184.5", lambda e: e["call"].update(duration_seconds=184.5), + reason="an integer is a whole number") == "refused" + assert add("duration_seconds is true", lambda e: e["call"].update(duration_seconds=True), + reason="a boolean is not an integer") == "refused" + assert add("duration_seconds is 184.0", lambda e: e["call"].update(duration_seconds=184.0), + reason="a whole-number JSON number is an integer") == "ok" + assert add("location is a string", lambda e: e.update(location="loc"), reason="location must be an object") == "refused" + assert add("call.caller_name is a number", lambda e: e["call"].update(caller_name=5), + reason="optional field of the wrong type: accepted, read as absent") == "ok" + assert add("summary missing", lambda e: e.pop("summary"), reason="summary is optional") == "ok" + assert add("summary is a string", lambda e: e.update(summary="text"), reason="optional field of the wrong type") == "ok" + assert add("location without id", lambda e: e["location"].pop("id"), reason="location.id is optional") == "ok" + assert add("call_date is not a date", lambda e: e["call"].update(call_date="yesterday"), + reason="a string; the schema gives no format: call_date reads as None") == "ok" + assert add("an unknown field", lambda e: e.update(extra=1), reason="unknown fields are dropped") == "ok" + assert add("another event type", lambda e: e.update(type="something_new"), reason="UnknownEvent: answer 2xx") == "unknown" + assert add("type missing", lambda e: e.pop("type"), reason="UnknownEvent: answer 2xx") == "unknown" + assert add("a JSON array", raw="[1, 2]", reason="not an object") == "refused" + assert add("not JSON", raw="{", reason="not JSON") == "refused" + return out + + +def strictness_vectors(): + # Placeholders {company_id} and {location_id} are filled from FakeAPI.seed_customer(). + q = [ + ("limit=+5", "GET", "/calls", {"limit": "+5"}, None, 400), + ("limit=5_0", "GET", "/calls", {"limit": "5_0"}, None, 400), + ("limit=05", "GET", "/calls", {"limit": "05"}, None, 400), + ("limit=5 (valid)", "GET", "/calls", {"limit": "5"}, None, 200), + ("date-time without seconds", "GET", "/calls", {"date_from": "2026-11-01T10:00Z"}, None, 400), + ("date-time with a space for T", "GET", "/calls", {"date_from": "2026-11-01 10:00:00Z"}, None, 400), + ("offset without a colon", "GET", "/calls", {"date_from": "2026-11-01T10:00:00+0000"}, None, 400), + ("date-time on 30 February", "GET", "/calls", {"date_from": "2026-02-30T10:00:00Z"}, None, 400), + ("date-time without a time zone", "GET", "/calls", {"date_from": "2026-11-01T10:00:00"}, None, 400), + ("date-time with Z (valid)", "GET", "/calls", {"date_from": "2026-11-01T10:00:00Z"}, None, 200), + ("date-time with +01:00 and fraction (valid)", "GET", "/calls", {"date_from": "2026-11-01T10:00:00.5+01:00"}, None, 200), + ("due_on=2026-1-5", "GET", "/tasks", {"due_on": "2026-1-5"}, None, 400), + ("due_on on 30 February", "GET", "/tasks", {"due_on": "2026-02-30"}, None, 400), + ("due_on=2026-01-05 (valid)", "GET", "/tasks", {"due_on": "2026-01-05"}, None, 200), + ("uuid without hyphens", "GET", "/calls", {"location_id": "0193b6c26b297a51b0e41c8f3d5e7a02"}, None, 400), + ("uuid in mixed case", "GET", "/calls", {"location_id": "0193B6c2-6b29-7a51-b0e4-1c8f3d5e7a02"}, None, 400), + ("uuid in upper case (valid)", "GET", "/calls", {"location_id": "0193B6C2-6B29-7A51-B0E4-1C8F3D5E7A02"}, None, 200), + ("status outside its enum", "GET", "/calls", {"status": "bogus"}, None, 400), + ("unknown query parameter", "GET", "/calls", {"page_size": "10"}, None, 400), + ("body: boolean given as a string", "PATCH", "/locations/{location_id}/insights-hub/config", + None, {"monitor_all_numbers": "yes"}, 422), + ("body: unknown field", "PATCH", "/locations/{location_id}/insights-hub/config", + None, {"monitor_all_numbers": False, "zzz": 1}, 422), + ("body: valid", "PATCH", "/locations/{location_id}/insights-hub/config", None, {"monitor_all_numbers": False}, 200), + ("body: string given as a number", "POST", "/locations/{location_id}/user-groups", None, {"group_name": 5}, 422), + ("body: missing required field", "POST", "/locations/{location_id}/user-groups", None, {"member_ids": []}, 422), + ("body: enum (connector type)", "POST", "/locations/{location_id}/connectors", None, + {"name": "x", "type": "examplepbx", "config": {"api_url": "https://pbx.example.com/ns-api/v2", + "domain": "d.example.com", "api_key": "example-key"}}, 422), + ("unknown path", "GET", "/calls/export/all", None, None, 404), + ] + return [{"name": n, "method": m, "path": p, "query": qq, "body": b, "status": st} for n, m, p, qq, b, st in q] + + +def main() -> None: + files = { + "delivery_key_vectors.json": delivery_vectors(), + "canonical_vectors.json": canonical_vectors(), + "retry_after_vectors.json": retry_after_vectors(), + "after_call_parse_vectors.json": parse_vectors(), + "fake_strictness_vectors.json": strictness_vectors(), + } + dirs = [OUT] + [pathlib.Path(a) for a in sys.argv[1:]] + for d in dirs: + d.mkdir(parents=True, exist_ok=True) + for name, data in files.items(): + (d / name).write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + for name, data in files.items(): + print(f"{name}: {len(data)} entries") + + +if __name__ == "__main__": + main() From 873a3ba660f65b9f8b654861af543f2d07f5e9dc Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 20:17:27 -0700 Subject: [PATCH 06/11] Final cross-language rules for 0.3.0 - Validation patterns match the whole value (fullmatch); one explicit path rule (1-128 code points, no / \ ? # %, controls or whitespace, not "." or "..", never trimmed) for helpers, reference() and ids - Event bodies deeper than 64 levels are refused without recursion; call.id, location_id and First Alert ids must be plain ids; events with no string type key as "unknown" - Top-level body JSON types checked before sending for every method; allowed values left to the platform (no client-side enums, no connector-type list read before a connector write) - Sign-in is retried only after a failure that never left, a 5xx, or a 429 within the wait limit - Bodies, headers and webhook addresses travel in redacting types, so tracebacks captured with locals show no secrets; the fake's log hides URL paths - license_report reads the customer once; teams read earlier in the same call are not read again; request counts re-measured and pinned - README: retry table, Customer-object cost, a portable SQL row lock - Shared vectors regenerated (version 3) with path_argument_vectors Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + README.md | 40 ++- src/intelligence_cloud/_redact.py | 69 +++++ src/intelligence_cloud/_spec.py | 66 ++++- src/intelligence_cloud/accounts.py | 59 +++-- src/intelligence_cloud/client.py | 27 +- src/intelligence_cloud/conversations.py | 15 +- src/intelligence_cloud/intelligence.py | 17 +- src/intelligence_cloud/receiver.py | 65 ++++- src/intelligence_cloud/testing/_fake.py | 29 +-- .../fixtures/after_call_parse_vectors.json | 42 +++ tests/unit/fixtures/delivery_key_vectors.json | 72 ++++++ .../unit/fixtures/path_argument_vectors.json | 147 +++++++++++ tests/unit/fixtures/retry_after_vectors.json | 4 + tests/unit/test_accounts.py | 43 ++-- tests/unit/test_final_030.py | 241 ++++++++++++++++++ tests/unit/test_request_counts.py | 31 ++- tests/unit/test_shared_vectors.py | 11 + tools/make_shared_vectors.py | 64 ++++- 19 files changed, 929 insertions(+), 122 deletions(-) create mode 100644 src/intelligence_cloud/_redact.py create mode 100644 tests/unit/fixtures/path_argument_vectors.json create mode 100644 tests/unit/test_final_030.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f27160f..3342a98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ - **One Retry-After rule:** only decimal seconds count; anything else means the client's own backoff. `RateLimitError.retry_after` is a float or None. - **A passed `Customer` is kept current:** helpers check it against the live location list (one request) and re-read it when it differs; group and rule ids are read live for the teams they touch; a Customer carrying another company's locations is refused. `Customer.refreshed_at` is new. - Testing module: `fail_next(..., after_processing=False)` fails before the platform acts by default (a renewal's 429 keeps its token); strict mode uses explicit patterns for numbers, dates, date-times and uuids and checks body enums and formats (the generator now keeps them in the bundled spec); secret-named values are masked in the request log. +- **Whole-value checks and one path rule:** every pattern validates the whole value (a trailing newline no longer passes); a path argument is 1-128 code points with no `/ \ ? #` `%`, control characters or whitespace, never trimmed. +- **Event safety:** bodies nested deeper than 64 levels are refused (`WebhookPayloadError`) without recursion; `call.id`, `location_id` and First Alert ids must be plain ids (`[A-Za-z0-9_-]{1,128}`); an event with no string `type` has the delivery-key prefix `unknown`. +- **Top-level body types are checked before sending** for every generated method and helper; allowed values (enums) are left to the platform, so a connector type the spec does not list still reaches the API. The account layer no longer reads the connector-type list before a connector write. +- **Sign-in is not retried after a timeout or reset once the request was sent** (still after a failure that never left, a 5xx, or a 429 within the wait limit). +- **Secrets stay out of tracebacks:** request bodies, headers and webhook addresses travel in types whose printed form hides secret-named values and URL paths; the refresh token stays inside `Tokens`. +- `license_report` reads the customer once; a team read earlier in the same helper call is not read again. - Connector waits count the check intervals as well as the clock, so a replaced `sleep` (tests) cannot spin for the whole timeout. - README: "Retries" with worst-case blocking time, "Testing your code", "Running helpers from more than one process", "How many requests" (pinned by a test), the error tree. SDK documentation links now point to the SDK pages (https://docs.intelligence.cloud/sdk/, /sdk/quick-start, /sdk/reference, /sdk/events, /sdk/configuration, /sdk/downloads); API links stay https://docs.intelligence.cloud/api and https://docs.intelligence.cloud/reference. The examples ship in the source distribution, not the wheel, and the README says so. Package metadata links to the SDK pages, with "Changelog" on https://docs.intelligence.cloud/sdk/downloads. - Examples use one fictional customer, Riverbend Auto Group, and the variables `IC_ADMIN_EMAIL` / `IC_ADMIN_PASSWORD` and `IC_USER_EMAIL` / `IC_USER_PASSWORD` (`IC_DATA_*` still read by the examples as a fallback). @@ -39,6 +45,9 @@ | `AfterCallCall.call_date` and `AfterCallEvent.timestamp` were always set | Optional (None when the text is not a date) | | Retry-After values such as `" 5"` or `"1e2"` were honoured | Treated as absent: backoff applies | | Bodies with duplicate keys or NaN were parsed | Refused with `WebhookPayloadError` | +| Ids such as `" a"` were trimmed, and `"a\n"` passed | Refused, never trimmed | +| A body value of the wrong JSON type was sent | Refused before sending | +| Event `call.id` / `location_id` could be any string | Plain ids only; deeper than 64 levels refused | | An id inside an app link could be any string | Links carry only ids of letters, digits, `-` and `_`; `reference()` refuses others and briefs with such an id get `link=None` | | `parse_first_alert_event` refused non-UUID ids and lower-cased ids | Ids of letters, digits, `-` and `_` (at most 128), kept as sent | | A sign-in 429 always waited `login_rate_limit_wait` once | It waits only when `Retry-After` fits in that limit; otherwise raises at once | diff --git a/README.md b/README.md index 5659891..992277c 100644 --- a/README.md +++ b/README.md @@ -253,7 +253,8 @@ Module level: `parse_after_call_event`, `parse_first_alert_event`, `UnknownEvent - **Responses** carry only the fields in the published reference. Anything else is dropped. With `Client(keep_unknown_fields=True)` new fields the reference does not list yet are kept on the customer-lifecycle (admin) reads; `get_me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields. Either way, the one-time sign-in link a user create can return is never passed through or logged. - **Test endpoints** (connector dry run, webhook tests) report only success and the HTTP status. - **Retries:** see "Retries" below. -- **Path arguments:** every value placed in a URL path (ids) must be 1 to 128 characters, not `.` or `..`, with no `/`, `\`, `?`, `#`, `%`, whitespace or control characters; anything else raises `InvalidRequestError` before any request. What remains is percent-encoded. +- **Path arguments:** every value placed in a URL path (ids) must be the whole value, 1 to 128 Unicode code points, not `.` or `..`, with no `/`, `\`, `?`, `#`, `%`, control character (U+0000–U+001F, U+007F–U+009F) or whitespace (including U+00A0, U+2028, U+2029, U+3000 and U+FEFF); nothing is trimmed first, so `" a"` is refused. Anything else raises `InvalidRequestError` before any request. What remains is percent-encoded. +- **Body types:** the JSON type of every top-level body field is checked against the spec before sending (a boolean must be `true`/`false`, a number a number). Allowed values are not checked: the platform decides them and adds new ones (a connector type it does not have is refused by the platform). - **Free text:** search terms, numbers and alert names must be real strings, trimmed, at most 200 characters (search terms at least 2). - **Checks first:** every helper of both layers checks its arguments before it signs in or sends anything. Bad input raises `InvalidRequestError` with no request made, so it costs no sign-in (sign-in is limited to 5 a minute). @@ -264,7 +265,7 @@ One policy, the same in every SDK: | Situation | What the client does | |---|---| | Network failure (no connection, timeout) or 5xx on a read, update, delete, or user create (which carries an idempotency key, reused on every try) | Retries up to `max_retries` (3) times with exponential backoff and jitter: about 0.5, 1 and 2 seconds plus up to half again | -| The same on sign-in | Retried the same way | +| Sign-in | Retried after a failure that provably never left (no connection made, no free pooled connection, a request that could not be written), after a 5xx, and after a 429 within the wait limit. **Not** retried after a timeout or reset once the request was sent | | Token renewal | The refresh token is sent again **only** after a 429 (the server did not use it) or after a network failure that provably never left this machine (no connection made, no free connection in the pool, a request that could not be written). Any other outcome (a 5xx, a timeout after the request left, an unreadable answer) may have used it: it is never resent, and the client signs in instead. Sending a used refresh token ends every session of that login | | Network failure or 5xx on any other create | Not retried: the error is raised, so nothing is created twice | | 429 with `Retry-After` within the limit (60 s; for sign-in, `login_rate_limit_wait`, default 60 s) | Waits `Retry-After` (backoff when absent), then retries; sign-in waits once. `Retry-After` counts only as decimal seconds (`[0-9]+(.[0-9]+)?`, at most 9 digits before the point); an HTTP date, `INF`, `NaN`, `1e2`, a negative or empty value is treated as absent (backoff applies). `RateLimitError.retry_after` is a float or None | @@ -497,7 +498,7 @@ def test_resumes_after_a_stop(): | `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()`, `auth_log` | The request log (sign-in and renewal are in `auth_log`: "login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) | | `products(uid, lid)`, `numbers(uid, connector_id=None)`, `fa_numbers(lid)`, `ih_numbers(lid)`, `group_members(lid, name)` | State to assert on | -That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore and may change. `client(transport=...)` is refused. +That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore and may change. `client(transport=...)` is refused. The request log masks secret-named values and shows URL fields (`url`, `webhook_url`, any `*_url`) with their path hidden (`https://hooks.example.com/***`), as the SDK does in its own printed forms and tracebacks. **Strict mode** (`strict=True`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type, outside its enum or range, or not in its format (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). Formats use explicit patterns, the same in every SDK: whole number `-?(0|[1-9][0-9]*)`; date `YYYY-MM-DD` on a real calendar day; date-time RFC 3339 with seconds, `T`, and `Z` or `±HH:MM`; uuid hyphenated, all lower or all upper case. Body enums and formats come from the bundled spec. It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states (for example the spec gives no list of user roles). Code that passes against it still needs one run against a test company before release. @@ -516,15 +517,26 @@ def with_customer_lock(company_id, fn): with_customer_lock(company_id, lambda: admin.accounts.add_base_user(company_id, person, team=team, line="2101")) ``` -Across several machines, use your database. With PostgreSQL, an advisory lock held for the length of a transaction: +Across several machines, use your database: a row per customer, locked for the length of a transaction. This works in any SQL database with row locks: + +```sql +CREATE TABLE customer_locks (company_id VARCHAR(128) PRIMARY KEY); +``` ```python def with_customer_lock(conn, company_id, fn): - with conn.transaction(): - conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", ("ic-customer:" + company_id,)) - return fn() # released when the transaction ends + with conn: # one transaction around the helper call + cur = conn.cursor() + try: + cur.execute("INSERT INTO customer_locks (company_id) VALUES (%s)", (company_id,)) + except IntegrityError: # the row exists already: fine + conn.rollback() + cur.execute("SELECT company_id FROM customer_locks WHERE company_id = %s FOR UPDATE", (company_id,)) + return fn() # others wait here; the lock ends with the transaction ``` +Use your driver's parameter style and its unique-violation error (or the database's insert-if-missing form). + For a new customer, lock on a key you already have (your own account id) until `create_customer` returns and you have stored `company_id`. ## How many requests @@ -533,16 +545,18 @@ Measured against `intelligence_cloud.testing` with a fresh client (one `GET /me` | Helper | 1-team customer | 10-team customer | |---|---|---| -| `create_customer` (first run, one team) | 35 | 35 | -| `add_team` (the 2nd team; the 10th team) | n/a | 25; 25 (260 for all ten teams) | -| `create_customer`, re-run | 19 | 19 | +| `create_customer` (first run, one team) | 34 | 34 | +| `add_team` (the 2nd team; the 10th team) | n/a | 23; 23 (241 for all ten teams) | +| `create_customer`, re-run | 18 | 18 | | `add_base_user` (customer passed as a company id) | 36 | 90 | -| `add_base_manager` (on every team) | 33 | 168 | -| `activate_alerts` | 18 | 117 | +| `add_base_manager` (on every team, Customer object) | 32 | 158 | +| `activate_alerts` (Customer object; company id) | 17; 21 | 107; 120 | +| `sync_lines` (Customer object; company id) | 11; 19 | 65; 100 | +| `license_report` (Customer object; company id) | 8; 16 | 35; 70 | | `calls` (one page) | 2 | 2 | | `brief` | 3 | 3 | -A helper given a `Customer` object adds one request (the location list it checks the object against) and two per team whose group and rule ids it uses (live listings). The counts assume two Base Users per team and one manager, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. +A helper given a company id reads the whole layout first (for a 1-team customer 9 requests: the company, its locations, and each location's groups, rules and connectors, plus the domains); given a `Customer` object it reads only the location list it checks the object against (1 request), plus the groups and rules of each team whose ids it uses (2 per team), so passing the object saves 8 requests on a 1-team customer and 35 on a 10-team one for `sync_lines` and `license_report`. The counts assume two Base Users per team and one manager, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. ## Examples diff --git a/src/intelligence_cloud/_redact.py b/src/intelligence_cloud/_redact.py new file mode 100644 index 0000000..0312817 --- /dev/null +++ b/src/intelligence_cloud/_redact.py @@ -0,0 +1,69 @@ +"""Printed forms that hide secrets: request bodies and headers carried through the client, and webhook +addresses. A traceback captured with its frames' locals then shows none of them. + +The rule, the same in every SDK: a value whose field name contains key, secret, token, password, passwd, +pwd, credential or auth is shown as "***", at any depth; a field named ``url`` or ending in ``_url`` keeps +its scheme and host and shows its path as "/***" (a webhook address carries its secret in the path).""" +from __future__ import annotations + +from typing import Any, Mapping +from urllib.parse import urlsplit + +SECRET_WORDS = ("key", "secret", "token", "password", "passwd", "pwd", "credential", "auth") + + +def is_secret(name: Any) -> bool: + low = str(name).lower() + return any(w in low for w in SECRET_WORDS) + + +def is_url_field(name: Any) -> bool: + low = str(name).lower() + return low == "url" or low.endswith("_url") + + +def mask_url(value: Any) -> Any: + """``https://hooks.example.com/***``: scheme and host kept, path, query and fragment hidden.""" + if not isinstance(value, str): + return value + try: + parts = urlsplit(value) + except ValueError: + return "***" + if not parts.scheme or not parts.netloc: + return "***" + rest = parts.path not in ("", "/") or parts.query or parts.fragment + return f"{parts.scheme}://{parts.hostname or ''}{':' + str(parts.port) if parts.port else ''}" + ("/***" if rest else "") + + +def redact(value: Any) -> Any: + """A copy safe to show: secret-named values as "***", URL fields with their path hidden.""" + if isinstance(value, Mapping): + out = {} + for k, v in value.items(): + if is_secret(k): + out[k] = "***" + elif is_url_field(k): + out[k] = mask_url(v) if isinstance(v, str) else redact(v) + else: + out[k] = redact(v) + return out + if isinstance(value, (list, tuple)): + return [redact(v) for v in value] + return value + + +class RedactedDict(dict): + """A dict sent as given, printed with its secrets hidden (see :func:`redact`).""" + + def __repr__(self) -> str: + return repr(redact(dict(self))) + + __str__ = __repr__ + + +class SecretURL(str): + """A webhook address: used as the plain string, printed with its path hidden.""" + + def __repr__(self) -> str: + return repr(mask_url(str.__str__(self))) diff --git a/src/intelligence_cloud/_spec.py b/src/intelligence_cloud/_spec.py index abf41f5..7e125a3 100644 --- a/src/intelligence_cloud/_spec.py +++ b/src/intelligence_cloud/_spec.py @@ -16,12 +16,12 @@ MAX_NUMBERS = 25 _RFC3339 = re.compile( - r"^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$" + r"^[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt ][0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?([Zz]|[+-][0-9]{2}:[0-9]{2})$" ) _RFC3339_PARTS = re.compile( - r"^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})$" + r"^([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt ]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?([Zz]|[+-][0-9]{2}:[0-9]{2})$" ) -_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +_DATE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$") _NUMBER_OK = re.compile(r"^[A-Za-z0-9@#]+$") _NUMBER_STRIP = re.compile(r"[\s+\-().]") @@ -181,16 +181,58 @@ def check_body(op_id: str, body: Mapping[str, Any]) -> None: missing = [k for k in schema.get("required", []) if k not in body] if missing: raise InvalidRequestError(f"{op_id}: missing required field(s) {missing}") + for name, value in body.items(): + problem = json_type_problem(_resolve(props[name]), value) + if problem: + raise InvalidRequestError(f"{op_id}: {name} {problem}") -# A value placed in a URL path: 1-128 characters, not "." or "..", and none of / \ ? # %, whitespace or -# control characters (a dot segment or a slash would change which resource the request reaches). -_PATH_VALUE = re.compile(r"^[^/\\?#%\s\x00-\x1f\x7f-\x9f]{1,128}$") +_JSON_TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": (list, tuple), + "object": Mapping} + + +def json_type_problem(schema: Any, value: Any) -> Optional[str]: + """Why ``value`` does not fit the top-level JSON type the spec gives, or None. The same rule in every + SDK: an integer is a whole number and never true/false; null only where the spec allows it. Allowed + values (enums) and formats are NOT checked here: the platform decides them and adds new ones (the + testing module's strict mode checks them).""" + if not isinstance(schema, dict): + return None + types = schema.get("type") + types = [types] if isinstance(types, str) else list(types or []) + if value is None: + return None if (not types or "null" in types) else "must not be null" + if types: + ok = False + for t in types: + py = _JSON_TYPES.get(t) + if py is None or (t in ("integer", "number") and isinstance(value, bool)): + continue + if t == "integer" and isinstance(value, float) and not value.is_integer(): + continue + if t == "integer" and isinstance(value, float): + ok = True + if isinstance(value, py): + ok = True + if not ok: + return "must be " + " or ".join(t for t in types if t != "null") + return None + + +# The path rule, the same in every SDK. A value placed in a URL path is 1 to 128 Unicode code points, is +# not "." or "..", and contains none of: / \ ? # %; a control character (U+0000-U+001F, U+007F-U+009F); +# or a space or other whitespace (U+0020, U+00A0, U+1680, U+2000-U+200A, U+2028, U+2029, U+202F, U+205F, +# U+3000, U+FEFF). Nothing is trimmed first: " a" is refused. A dot segment or a slash would change which +# resource the request reaches. +PATH_FORBIDDEN = ("/\\?#%\u0020\u00a0\u1680\u2028\u2029\u202f\u205f\u3000\ufeff" + + "".join(chr(c) for c in range(0x00, 0x20)) + "".join(chr(c) for c in range(0x7f, 0xa0)) + + "".join(chr(c) for c in range(0x2000, 0x200b))) +_PATH_VALUE = re.compile("[^" + re.escape(PATH_FORBIDDEN) + "]{1,128}") def check_path_value(value: Any, name: str) -> str: """Refuse (InvalidRequestError, before any request) a path argument that could change the URL.""" - if not isinstance(value, str) or value in (".", "..") or not _PATH_VALUE.match(value): + if not isinstance(value, str) or value in (".", "..") or not _PATH_VALUE.fullmatch(value): raise InvalidRequestError(f"{name}: an id of 1 to 128 characters without / \\ ? # %, spaces or " "control characters, and not '.' or '..'") return value @@ -238,15 +280,15 @@ def format_datetime(value: Any, name: str) -> str: ) if isinstance(value, str): v = value.strip() - if _DATE.match(v): + if _DATE.fullmatch(v): raise InvalidRequestError( f"{name}: {v!r} is a date only. Use a full timestamp, e.g. {v}T00:00:00Z" ) - if not _RFC3339.match(v): + if not _RFC3339.fullmatch(v): raise InvalidRequestError( f"{name}: {v!r} is not a full RFC 3339 timestamp (e.g. 2026-11-01T00:00:00Z)" ) - m = _RFC3339_PARTS.match(v) + m = _RFC3339_PARTS.fullmatch(v) frac = (m.group(7) or "")[:6].ljust(6, "0") if m.group(7) else "0" off = m.group(8) if off in ("Z", "z"): @@ -265,7 +307,7 @@ def format_date(value: Any, name: str) -> str: raise InvalidRequestError(f"{name}: pass a date (YYYY-MM-DD), not a datetime") if isinstance(value, date): return value.isoformat() - if isinstance(value, str) and _DATE.match(value.strip()): + if isinstance(value, str) and _DATE.fullmatch(value.strip()): return value.strip() raise InvalidRequestError(f"{name}: expected YYYY-MM-DD") @@ -274,7 +316,7 @@ def clean_number(entry: str, name: str = "numbers") -> str: """Strip formatting. A North American number written with its leading 1 (11 digits) is sent as its last 10 digits, so it also matches records stored without the 1.""" v = _NUMBER_STRIP.sub("", str(entry)) - if not _NUMBER_OK.match(v): + if not _NUMBER_OK.fullmatch(v): raise InvalidRequestError(f"{name}: {entry!r} must be digits (letters, @ and # are also allowed)") if len(v) == 11 and v.isdigit() and v.startswith("1"): v = v[1:] diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index 4e83cdb..4901b29 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -24,6 +24,8 @@ from datetime import datetime, timezone from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union +import threading + import httpx from ._base import Namespace, unwrap @@ -125,7 +127,8 @@ def __setitem__(self, key: Any, value: Any) -> None: super().__setitem__(key, _wrap(value)) def __repr__(self) -> str: - return "{" + ", ".join(f"{k!r}: {'***' if _is_secret(k) else repr(v)}" for k, v in self.items()) + "}" + from ._redact import redact + return repr(redact(dict(self))) __str__ = __repr__ @@ -425,6 +428,7 @@ def __init__(self, client: Any): self._me: Optional[Dict[str, Any]] = None self._verticals: Optional[List[Dict[str, Any]]] = None self._connector_types: Optional[List[str]] = None + self._local = threading.local() # which helper call is running (for "read live in this call") # ------------------------------------------------------------------ plumbing @@ -445,6 +449,8 @@ def _stop(self, run: _Run, exc: BaseException) -> None: raise AccountError(run.step, run.result, exc) from exc def _resolve(self, customer: CustomerRef) -> Customer: + """The customer for this helper call. Starts a new call: teams read from here on count as live.""" + self._local.call = object() # a token unique to this call if isinstance(customer, Customer): return self._sync(customer) if isinstance(customer, str) and customer.strip(): @@ -476,8 +482,11 @@ def _sync(self, cust: Customer) -> Customer: def _live(self, team: Team, need: Iterable[str] = ()) -> Team: """Read the team's groups and rules now and put their ids on ``team``. Raises InvalidRequestError when a group in ``need`` (Team.groups field names) is missing.""" - fresh = self._read_team(team.location_id, team.name, team.kind) - team.groups, team.rules = fresh.groups, fresh.rules + call = getattr(self._local, "call", None) + if call is None or getattr(team, "_read_in_call", None) is not call: + groups, rules = self._read_groups_rules(team.location_id) + team.groups, team.rules = groups, rules + team._read_in_call = getattr(self._local, "call", None) # type: ignore[attr-defined] missing = [TEAM_GROUPS[f] for f in need if getattr(team.groups, f) is None] if missing: raise InvalidRequestError(f"{team.name}: group {', '.join(missing)} is missing; run create_customer " @@ -515,15 +524,9 @@ def _vertical_id(self, vertical: str) -> str: raise InvalidRequestError(f"Unknown vertical {vertical!r}: use an id or key from list_verticals()") def _check_connector(self, cs: Optional[ConnectorSpec], required: bool = False) -> None: - """The local checks, then the type against the API's list (one request, cached).""" + """The local checks only. The type's value is the platform's to judge: it refuses a type it does + not have (the SDK passes any type through, with no list read first).""" _check_connector_local(cs, required) - if cs is None: - return - if self._connector_types is None: - rows = unwrap(self._c.connectors.list_connector_types()) or [] - self._connector_types = [r.get("key") for r in rows if isinstance(r, dict) and r.get("key")] - if cs.type not in self._connector_types: - raise InvalidRequestError(f"Unknown connector type {cs.type!r}: one of {self._connector_types}") # ------------------------------------------------------------------ reading the layout @@ -556,16 +559,22 @@ def get_customer(self, company_id: str) -> Customer: break return cust - def _read_team(self, location_id: str, name: str, kind: str) -> Team: + def _read_groups_rules(self, location_id: str) -> Tuple[TeamGroups, TeamRules]: c = self._c - team = Team(location_id=location_id, name=name, kind=kind) + groups, rules = TeamGroups(), TeamRules() by_name = {g.get("group_name"): g["id"] for g in c.groups.iter_user_groups(location_id)} for f, gname in TEAM_GROUPS.items(): - setattr(team.groups, f, by_name.get(gname)) - rules = {r.get("name"): r["id"] for r in c.first_alert.iter_alert_rules(location_id)} + setattr(groups, f, by_name.get(gname)) + found = {r.get("name"): r["id"] for r in c.first_alert.iter_alert_rules(location_id)} for key, d in RULES.items(): - setattr(team.rules, key, rules.get(d.name)) + setattr(rules, key, found.get(d.name)) + return groups, rules + + def _read_team(self, location_id: str, name: str, kind: str) -> Team: + team = Team(location_id=location_id, name=name, kind=kind) + team.groups, team.rules = self._read_groups_rules(location_id) self._read_connector(team) + team._read_in_call = getattr(self._local, "call", None) # type: ignore[attr-defined] return team def _read_connector(self, team: Team) -> None: @@ -622,7 +631,7 @@ def create_customer(self, spec: CustomerSpec) -> Customer: _check_connector_local(spec.connector) for f in ("reseller_id", "company_code", "company_id", "sso_domain"): if _str(getattr(spec, f), f, required=False) and f in ("reseller_id", "company_id"): - check_path_value(getattr(spec, f).strip(), f) + check_path_value(getattr(spec, f), f) for f in ("mfa_off", "reactivate"): if not isinstance(getattr(spec, f), bool): raise InvalidRequestError(f"{f}: True or False") @@ -877,7 +886,7 @@ def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Cust the end, once everything else is built), else None.""" name = cs.name or f"{team.name} phone system" conns = self._c.connectors - config = dict(cs.config) + config = _Config(cs.config) # sent as given; printed (and in tracebacks) with its secrets hidden found = self._find_connector(team.location_id, cs, name) label = f"connector:{team.name}" if found is not None: @@ -1255,7 +1264,9 @@ def list_members(self, customer: CustomerRef, *, license: Optional[str] = None, if isinstance(customer, Customer) and team is not None: self._team(customer, team) self._require_admin() - cust = self._resolve(customer) + return self._members(self._resolve(customer), license, team) + + def _members(self, cust: Customer, license: Optional[str], team: Optional[TeamRef]) -> List[Member]: lid = self._team(cust, team).location_id if team is not None else None out = [] for p in self._index(cust).values(): @@ -1271,7 +1282,7 @@ def license_report(self, customer: CustomerRef) -> Dict[str, Any]: _check_customer_ref(customer) self._require_admin() cust = self._resolve(customer) - members = self.list_members(cust) + members = self._members(cust, None, None) # the customer is read once by: Dict[str, List[Member]] = {k: [] for k in LICENSES} for m in members: by[m.license].append(m) @@ -2119,7 +2130,7 @@ def _check_connector_local(cs: Optional[ConnectorSpec], required: bool = False) return if not isinstance(cs, ConnectorSpec): raise InvalidRequestError("connector must be a ConnectorSpec") - _str(cs.type, "connector.type") + _str(cs.type, "connector.type") # its value is checked by the API's own type list, not the spec _str(cs.name, "connector.name", required=False) if isinstance(cs.timeout, bool) or not isinstance(cs.timeout, (int, float)) or cs.timeout < 0: raise InvalidRequestError("connector.timeout: a number of seconds") @@ -2132,9 +2143,9 @@ def _check_customer_ref(customer: Any) -> None: if isinstance(customer, Customer): check_path_value(customer.company_id, "customer.company_id") return - if not isinstance(customer, str) or not customer.strip(): + if not isinstance(customer, str): raise InvalidRequestError("customer: a Customer or a company id") - check_path_value(customer.strip(), "customer") + check_path_value(customer, "customer") # nothing trimmed def _check_team_ref(team: Any, required: bool = True) -> None: @@ -2175,7 +2186,7 @@ def _check_invite(invite: Any) -> None: def _check_user_id(user_id: Any) -> None: - check_path_value(_str(user_id, "user_id"), "user_id") + check_path_value(user_id, "user_id") # nothing trimmed def _dedupe_teams(teams: List[Team]) -> List[Team]: diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index af37393..2b25c45 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -16,6 +16,7 @@ from . import _spec from ._base import Page from ._version import __version__ +from ._redact import RedactedDict from .auth import MemoryTokenStore, Tokens, TokenStore from .errors import ( NetworkError, @@ -78,7 +79,7 @@ def parse_retry_after(value: Optional[str]) -> Optional[float]: (``[0-9]+(.[0-9]+)?``, at most 9 digits before the point) count. Anything else (an HTTP date, "INF", "NaN", "1e2", a negative number, an empty value) is treated as if the header were absent (None), so the client's own backoff applies.""" - if value is None or not _RETRY_AFTER_RE.match(value): + if value is None or not _RETRY_AFTER_RE.fullmatch(value): return None return float(value) @@ -229,11 +230,12 @@ def _login_locked(self) -> Dict[str, Any]: if not self._email or not self._password: text = "No credentials: pass email and password to Client" raise AuthError(401, None, text, public_message=text) - body = {"email": self._email, "password": self._password} + body = RedactedDict(email=self._email, password=self._password) # prints with the password hidden waited = False while True: resp = self._send_with_retries("POST", "/auth/login", op_id="login", json_body=body, - auth=False, retry_429=False, retry_failures=True) + auth=False, retry_429=False, retry_failures=True, only_unsent=True, + retry_5xx=True) if resp.status_code == 429 and not waited and self._login_wait > 0: # Wait once, but only when the server's Retry-After fits the configured wait: a longer # one fails at once with RateLimitError.retry_after instead of blocking first. @@ -295,15 +297,15 @@ def _renew_locked(self, tokens: Tokens) -> None: request left, an unreadable response) may have used it: it is never sent again, and the client signs in instead. Sending a used refresh token ends every session of the login. """ - refresh_token = tokens.refresh_token - if refresh_token in self._spent_refresh_tokens: + # The refresh token stays inside ``tokens`` (whose printed form hides it), never in a bare local. + if tokens.refresh_token in self._spent_refresh_tokens: self._login_locked() return attempt = 0 while True: try: resp = self._send_with_retries("POST", "/auth/refresh", op_id="refresh", - json_body={"refresh_token": refresh_token}, auth=False, + json_body=RedactedDict(refresh_token=tokens.refresh_token), auth=False, retry_429=False, retry_failures=True, only_unsent=True) except NetworkError: resp = None @@ -313,7 +315,7 @@ def _renew_locked(self, tokens: Tokens) -> None: if attempt >= self._max_retries or wait is None or not self._wait(wait): self._raise(resp, "refresh") attempt += 1 - self._spent_refresh_tokens.add(refresh_token) + self._spent_refresh_tokens.add(tokens.refresh_token) if resp is not None and resp.status_code == 200: data = _spec.project_response("refresh", 200, self._json(resp)) if isinstance(data, dict) and data.get("access_token") and data.get("refresh_token"): @@ -339,7 +341,7 @@ def _url(self, path: str) -> str: def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Tokens] = None, params: Optional[Mapping[str, str]] = None, json_body: Any = None, headers: Optional[Mapping[str, str]] = None) -> httpx.Response: - h = {"Accept": "application/json", "X-Request-ID": str(uuid.uuid4())} + h = RedactedDict({"Accept": "application/json", "X-Request-ID": str(uuid.uuid4())}) # Authorization hidden if headers: h.update(headers) if tokens is not None: @@ -365,7 +367,7 @@ def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Toke def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, json_body=None, headers: Optional[Dict[str, str]] = None, auth: bool = True, retry_429: bool = True, retry_failures: Optional[bool] = None, - only_unsent: bool = False) -> httpx.Response: + only_unsent: bool = False, retry_5xx: Optional[bool] = None) -> httpx.Response: """Send with the retry policy (README "Retries"): network failures and 5xx are retried up to ``max_retries`` with backoff for idempotent requests (reads, updates, deletes, user create with its idempotency key) and for sign-in and token renewal (``retry_failures``; renewal retries a @@ -397,8 +399,8 @@ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, self._renew(tokens) # type: ignore[arg-type] continue # only_unsent (token renewal): a 5xx may come after the server used the request, so never resend - retryable = ((resp.status_code == 429 and retry_429) - or (resp.status_code >= 500 and idempotent and not only_unsent)) + five = (idempotent and not only_unsent) if retry_5xx is None else retry_5xx + retryable = (resp.status_code == 429 and retry_429) or (resp.status_code >= 500 and five) if retryable and attempt < self._max_retries: wait = self._backoff(attempt, resp.headers.get("Retry-After")) if wait is None or not self._wait(wait): @@ -517,7 +519,8 @@ def _request(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any] self._writes += 1 with self._budget(): resp = self._send_with_retries(op["method"], url_path, op_id=op_id, params=params, - json_body=dict(body) if body is not None else None, headers=headers) + json_body=RedactedDict(body) if body is not None else None, + headers=headers) if resp.status_code >= 400: self._raise(resp, op_id) return resp diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py index 513edf7..d77d1bb 100644 --- a/src/intelligence_cloud/conversations.py +++ b/src/intelligence_cloud/conversations.py @@ -193,9 +193,8 @@ class Reference: def _id(value: Any, name: str) -> str: - if not isinstance(value, str) or not value.strip(): - raise InvalidRequestError(f"{name}: a non-empty id") - return check_path_value(value.strip(), name) + """An id argument: the path rule, with nothing trimmed (" a" is a caller bug and is refused).""" + return check_path_value(value, name) def _check_team(team: Any) -> None: @@ -212,7 +211,7 @@ def _check_due(due: Any) -> None: """A date or "YYYY-MM-DD", the same on every Python version (3.11 also parses "20261102").""" if due is None or (isinstance(due, date) and not isinstance(due, datetime)): return - if isinstance(due, str) and _DATE_RE.match(due): + if isinstance(due, str) and _DATE_RE.fullmatch(due): try: date.fromisoformat(due) return @@ -244,7 +243,7 @@ def _mask_name(self, name: Optional[str]) -> Optional[str]: return mask_name(name) if self._c.mask_numbers else name def _link(self, kind: str, item_id: str) -> Optional[str]: - if not isinstance(item_id, str) or not ID_RE.match(item_id): + if not isinstance(item_id, str) or not ID_RE.fullmatch(item_id): return None # only plain ids go into an app link page = "after-call-copilot/calls" if kind == "call" else "first-alert-copilot/alerts" return f"{self._c.app_url}/{page}/{quote(item_id, safe='')}" @@ -554,11 +553,11 @@ def reference(self, call_or_alert: Union[CallBrief, AlertBrief, FirstAlertEvent, kind, item = "alert", call_or_alert.id elif isinstance(call_or_alert, FirstAlertEvent): kind, item = "alert", call_or_alert.alert_id - elif isinstance(call_or_alert, str) and call_or_alert.strip(): - kind, item = "call", call_or_alert.strip() + elif isinstance(call_or_alert, str) and call_or_alert: + kind, item = "call", call_or_alert else: raise InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") - if not ID_RE.match(item): + if not ID_RE.fullmatch(item): raise InvalidRequestError("reference: an id of letters, digits, '-' and '_' (at most 128)") return Reference(kind=kind, id=item, link=self._link(kind, item)) diff --git a/src/intelligence_cloud/intelligence.py b/src/intelligence_cloud/intelligence.py index aa3f5d8..c0777ba 100644 --- a/src/intelligence_cloud/intelligence.py +++ b/src/intelligence_cloud/intelligence.py @@ -7,6 +7,7 @@ from . import _spec from ._base import Namespace, Page, unwrap +from ._redact import RedactedDict, SecretURL from .errors import FrontlineRequiredError, InvalidRequestError if TYPE_CHECKING: # pragma: no cover @@ -178,7 +179,7 @@ def iter_alerts(self, alert_name: Optional[str] = None, numbers: Optional[Sequen def get_alert(self, alert_id: str, with_call: bool = False) -> Optional[Dict[str, Any]]: """One alert by id (searched by id, no date window). With ``with_call`` the call detail is added under ``call``. Returns None when the alert is not visible.""" - aid = _spec.check_path_value(_spec.check_text(alert_id, "alert_id"), "alert_id").lower() + aid = _spec.check_path_value(alert_id, "alert_id").lower() self.require_frontline() page = self._c.alerts.list_alerts(search=aid, limit=10) alert = next((a for a in page.items if a.get("id") == aid), None) @@ -268,8 +269,13 @@ def get_after_call_webhook(self, location_id: str) -> Optional[Dict[str, Any]]: def set_after_call_webhook(self, location_id: str, url: str, enabled: bool = True) -> Dict[str, Any]: """Set the After Call webhook (HTTPS). It receives every call at the location. Pause with ``enabled=False``; there is no delete.""" + _spec.check_path_value(location_id, "location_id") _https(url) - return unwrap(self._c.webhooks.save_after_call_webhook(location_id, {"webhook_url": url, "enabled": enabled})) + if not isinstance(enabled, bool): + raise InvalidRequestError("enabled: True or False") + url = SecretURL(url) # its path is the secret: printed (and in tracebacks) with the path hidden + return unwrap(self._c.webhooks.save_after_call_webhook( + location_id, RedactedDict(webhook_url=url, enabled=enabled))) def test_after_call_webhook(self, location_id: str) -> WebhookTestResult: """Send the test payload to the saved URL.""" @@ -282,15 +288,17 @@ def get_first_alert_webhook(self, location_id: str) -> Optional[str]: def set_first_alert_webhook(self, location_id: str, url: Optional[str]) -> Dict[str, Any]: """Set (or clear with None) the First Alert location webhook. Monitored numbers are kept.""" + _spec.check_path_value(location_id, "location_id") if url is not None: _https(url) + url = SecretURL(url) fa = self._c.first_alert cfg = unwrap(fa.get_first_alert_config(location_id)) or {} from .resources import merge_mappings mappings: List[Dict[str, Any]] = [] for m in cfg.get("connector_mappings") or []: mappings = merge_mappings(mappings, m["connector_id"], add=m.get("monitored_numbers") or []) - return unwrap(fa.save_first_alert_config(location_id, {"webhook_url": url, "connector_mappings": mappings})) + return unwrap(fa.save_first_alert_config(location_id, RedactedDict(webhook_url=url, connector_mappings=mappings))) def test_first_alert_webhook(self, location_id: str, url: Optional[str] = None) -> WebhookTestResult: """Send a test to ``url`` (default: the saved URL).""" @@ -298,7 +306,8 @@ def test_first_alert_webhook(self, location_id: str, url: Optional[str] = None) if not target: raise InvalidRequestError("No First Alert webhook URL is set for this location") _https(target) - data = unwrap(self._c.first_alert.test_first_alert_webhook(location_id, {"url": target})) or {} + target = SecretURL(target) + data = unwrap(self._c.first_alert.test_first_alert_webhook(location_id, RedactedDict(url=target))) or {} return WebhookTestResult(bool(data.get("success")), data.get("status_code")) diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index 1c4c749..34c70b9 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -147,6 +147,7 @@ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], raise WebhookPayloadError("body is not JSON") from None if not isinstance(body, Mapping): raise WebhookPayloadError("body is not a JSON object") + check_depth(body) if body.get("type") != AFTER_CALL_EVENT_TYPE: typ, ver = body.get("type"), body.get("version") return UnknownEvent(type=typ if isinstance(typ, str) else None, @@ -154,11 +155,11 @@ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], data = _spec.project(dict(body), _spec.schema_by_name("AfterCallSummaryEvent")) version = _req(data, "version", str, "event") is_test = _req(data, "is_test", bool, "event") - location_id = _req(data, "location_id", str, "event") + location_id = _plain_req(_req(data, "location_id", str, "event"), "location_id") stamp = _req(data, "timestamp", str, "event") call = _req(data, "call", dict, "event") loc = _req(data, "location", dict, "event") - call_id = _req(call, "id", str, "call") + call_id = _plain_req(_req(call, "id", str, "call"), "call.id") call_type = _req(call, "call_type", str, "call") duration = _req(call, "duration_seconds", int, "call") call_date_text = _req(call, "call_date", str, "call") @@ -241,10 +242,49 @@ def _no_constant(name: str) -> Any: raise WebhookPayloadError(f"body has {name}, which is not JSON") +MAX_DEPTH = 64 # the same in every SDK: an event nested deeper is refused + + +def _check_text_depth(text: str) -> None: + """Refuse JSON text nested deeper than MAX_DEPTH, scanning without recursion (so a hostile body + cannot exhaust the stack). The top-level object or array is depth 1.""" + depth, in_string, escaped = 0, False, False + for ch in text: + if in_string: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + elif ch == '"': + in_string = True + elif ch in "[{": + depth += 1 + if depth > MAX_DEPTH: + raise WebhookPayloadError(f"body is nested deeper than {MAX_DEPTH} levels") + elif ch in "]}": + depth -= 1 + + +def check_depth(value: Any) -> None: + """Refuse a parsed value nested deeper than MAX_DEPTH, without recursion.""" + stack = [(value, 1)] + while stack: + v, d = stack.pop() + if isinstance(v, (Mapping, list, tuple)): + if d > MAX_DEPTH: + raise WebhookPayloadError(f"body is nested deeper than {MAX_DEPTH} levels") + children = v.values() if isinstance(v, Mapping) else v + stack.extend((c, d + 1) for c in children if isinstance(c, (Mapping, list, tuple))) + + def loads_ijson(raw: Union[bytes, str]) -> Any: """Parse a delivery body as I-JSON: UTF-8 (a leading byte-order mark is ignored), no duplicate object - keys, no NaN or Infinity. Lone surrogates are refused when the value is canonicalised.""" + keys, no NaN or Infinity, nested at most 64 levels. Lone surrogates are refused when the value is + canonicalised.""" text = raw.decode("utf-8-sig") if isinstance(raw, (bytes, bytearray)) else raw.lstrip("\ufeff") + _check_text_depth(text) return json.loads(text, object_pairs_hook=_no_duplicates, parse_constant=_no_constant) @@ -347,8 +387,15 @@ def canonical_json(value: Any) -> bytes: return "".join(out).encode("utf-8") +def _plain_req(value: str, where: str) -> str: + """An id used as a key (call.id, location_id): the plain-id rule, whole value, nothing trimmed.""" + if not ID_RE.fullmatch(value): + raise WebhookPayloadError(f"{where} is not a plain id (letters, digits, '-' and '_', at most 128)") + return value + + def _plain_id(value: Optional[str]) -> Optional[str]: - return value if value is not None and ID_RE.match(value) else None + return value if value is not None and ID_RE.fullmatch(value) else None def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping[str, Any]: @@ -365,6 +412,7 @@ def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping raise WebhookPayloadError("body is not JSON") from None if not isinstance(body, Mapping): raise WebhookPayloadError("body is not a JSON object") + check_depth(body) return body @@ -389,8 +437,8 @@ def sub(key: str) -> Mapping[str, Any]: raw_id = alert.get("id") else: raw_id = data.get("id") - alert_id = raw_id.strip() if isinstance(raw_id, str) else None - if not alert_id or not ID_RE.match(alert_id): + alert_id = raw_id if isinstance(raw_id, str) else None # nothing trimmed + if not alert_id or not ID_RE.fullmatch(alert_id): raise WebhookPayloadError("event has no valid alert id (letters, digits, '-' and '_', at most 128)") stamp = _first_str(data.get("timestamp"), data.get("fired_at"), data.get("created_at"), alert.get("created_at")) try: @@ -452,6 +500,8 @@ def _as_event(item: Any) -> Any: body = _load(item, MAX_EVENT_BYTES) ev = parse_after_call_event(body) if isinstance(ev, UnknownEvent): + if "alert_id" in body or isinstance(body.get("alert"), Mapping): + return parse_first_alert_event(body) # a First Alert body: an invalid id is refused, not "unknown" try: return parse_first_alert_event(body) except WebhookPayloadError: @@ -482,7 +532,8 @@ def delivery_key(event: Any) -> str: return f"{ev.type}:{ev.location_id}:{ev.call.id}:{_canonical_hash(ev.raw)}" if isinstance(ev, FirstAlertEvent): return f"first_alert:{ev.alert_id}:{_canonical_hash(ev.raw)}" - return f"{ev.type}:{_canonical_hash(ev.raw)}" + prefix = ev.type if isinstance(ev.type, str) else "unknown" # the same literal in every SDK + return f"{prefix}:{_canonical_hash(ev.raw)}" class Deduplicator: diff --git a/src/intelligence_cloud/testing/_fake.py b/src/intelligence_cloud/testing/_fake.py index d1466ff..4211c6b 100644 --- a/src/intelligence_cloud/testing/_fake.py +++ b/src/intelligence_cloud/testing/_fake.py @@ -13,6 +13,7 @@ from .. import _spec from ..client import Client +from .._redact import redact from ..errors import InvalidRequestError RESELLER = "00000000-0000-4000-8000-0000000000aa" @@ -191,7 +192,7 @@ def auth_log(self) -> List[Tuple[str, str]]: def count(self, method: str, pattern: str) -> int: """How many requests matched ``method`` and the path regex ``pattern`` (without /api/v1).""" rx = re.compile("^" + pattern + "$") - return sum(1 for r in self.requests if r.method == method and rx.match(r.path)) + return sum(1 for r in self.requests if r.method == method and rx.fullmatch(r.path)) def reset_log(self) -> None: """Forget the request log and the auth log (state is kept).""" @@ -248,7 +249,7 @@ def deco(fn): def _operation(self, method: str, path: str) -> Optional[str]: for m, rx, op_id in self._ops: - if m == method and rx.match(path): + if m == method and rx.fullmatch(path): return op_id return None @@ -311,7 +312,7 @@ def _use_refresh(self, token: Any) -> Optional[Tuple[str, str]]: def _take_failure(self, method: str, path: str) -> Optional[Dict[str, Any]]: for i, f in enumerate(self._next_failures): - if (f["method"] is None or f["method"] == method) and (f["path"] is None or f["path"].match(path)): + if (f["method"] is None or f["method"] == method) and (f["path"] is None or f["path"].fullmatch(path)): return self._next_failures.pop(i) return None @@ -391,7 +392,7 @@ def __call__(self, request: httpx.Request) -> httpx.Response: return _error(status, "FAKE_FAILURE", "Failed on purpose by FakeAPI.fail_write") self._fail = (left - 1, status) for method, rx, fn in self._routes: - m = rx.match(full) + m = rx.fullmatch(full) if m and method == request.method: try: out = fn(request, body, *m.groups()) @@ -958,16 +959,10 @@ def _loc_user(self, u: Dict[str, Any], lid: str) -> Dict[str, Any]: if g["location_id"] == lid and u["id"] in g["members"]]} -_MASK_WORDS = ("key", "secret", "token", "password", "passwd", "pwd", "credential", "auth") - - def _masked(value: Any) -> Any: - """A copy with the values of secret-named fields replaced by "***", at any depth.""" - if isinstance(value, dict): - return {k: ("***" if any(w in str(k).lower() for w in _MASK_WORDS) else _masked(v)) for k, v in value.items()} - if isinstance(value, list): - return [_masked(v) for v in value] - return value + """A copy safe to log: secret-named values as "***" and URL fields with their path hidden, at any + depth (the SDK's own redaction rule).""" + return redact(value) NETWORK_FAILURES = ("connect", "read_timeout", "write_timeout", "undecodable") @@ -992,15 +987,15 @@ def _real_date(y: str, m: str, d: str) -> bool: def _format_problem(fmt: Optional[str], value: str) -> Optional[str]: - if fmt == "uuid" and not UUID_RE.match(value): + if fmt == "uuid" and not UUID_RE.fullmatch(value): return "not a UUID (hyphenated, all lower or all upper case)" if fmt == "date-time": - m = DATE_TIME_RE.match(value) + m = DATE_TIME_RE.fullmatch(value) if (not m or not _real_date(*m.group(1, 2, 3)) or int(m.group(4)) > 23 or int(m.group(5)) > 59 or int(m.group(6)) > 59 or (m.group(9) and (int(m.group(9)) > 23 or int(m.group(10)) > 59))): return "not an RFC 3339 date-time (YYYY-MM-DDTHH:MM:SS, then Z or +HH:MM)" if fmt == "date": - m = DATE_RE.match(value) + m = DATE_RE.fullmatch(value) if not m or not _real_date(*m.groups()): return "not a date (YYYY-MM-DD)" return None @@ -1049,7 +1044,7 @@ def _query_problem(q: Mapping[str, Any], raw: str) -> Optional[str]: for v in values: it = item.get("type") if it == "integer": - if not INTEGER_RE.match(v): + if not INTEGER_RE.fullmatch(v): return "must be a whole number" n = int(v) if "minimum" in item and n < item["minimum"] or "maximum" in item and n > item["maximum"]: diff --git a/tests/unit/fixtures/after_call_parse_vectors.json b/tests/unit/fixtures/after_call_parse_vectors.json index 5d64b87..d91a1d9 100644 --- a/tests/unit/fixtures/after_call_parse_vectors.json +++ b/tests/unit/fixtures/after_call_parse_vectors.json @@ -167,6 +167,48 @@ "result": "unknown", "reason": "UnknownEvent: answer 2xx" }, + { + "name": "call.id ''", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id must be a plain id: [A-Za-z0-9_-]{1,128}, whole value, not trimmed" + }, + { + "name": "call.id '..'", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"..\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id must be a plain id: [A-Za-z0-9_-]{1,128}, whole value, not trimmed" + }, + { + "name": "call.id 'a/b'", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"a/b\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id must be a plain id: [A-Za-z0-9_-]{1,128}, whole value, not trimmed" + }, + { + "name": "call.id 'a\\n'", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"a\\n\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id must be a plain id: [A-Za-z0-9_-]{1,128}, whole value, not trimmed" + }, + { + "name": "call.id ' a'", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \" a\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "call.id must be a plain id: [A-Za-z0-9_-]{1,128}, whole value, not trimmed" + }, + { + "name": "location_id 'a/b'", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"a/b\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "location_id must be a plain id" + }, + { + "name": "nested deeper than 64 levels", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": true, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}, \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "result": "refused", + "reason": "at most 64 levels" + }, { "name": "a JSON array", "raw": "[1, 2]", diff --git a/tests/unit/fixtures/delivery_key_vectors.json b/tests/unit/fixtures/delivery_key_vectors.json index ea615ae..76035e4 100644 --- a/tests/unit/fixtures/delivery_key_vectors.json +++ b/tests/unit/fixtures/delivery_key_vectors.json @@ -185,6 +185,78 @@ "key": "first_alert:fa-keys:8762e801a9de2c84a9edfe7b353b6d296ad929d2c0fbc1868230a2919ab56b81", "error": false }, + { + "name": "an event with no type: prefix \"unknown\"", + "raw": "{\"version\": \"2.0\", \"data\": {\"a\": 1}}", + "key": "unknown:ae69b727b12a187017c859c643c800a931e9d11e1d4fdcd0db61523ad9b8d8e4", + "error": false + }, + { + "name": "an event whose type is not a string: prefix \"unknown\"", + "raw": "{\"type\": 5, \"data\": 1}", + "key": "unknown:026efacb3fb0c6f89a73b6e4d94eb3fefd3c6e823d5e23bbdccd3a02ae7b847f", + "error": false + }, + { + "name": "nested 64 levels (accepted)", + "raw": "{\"alert_id\": \"fa-depth\", \"p\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}", + "key": "first_alert:fa-depth:cd6e953b649a17de0271d7e0e8fc81de4a9235ab1aa1f344217606987fe33971", + "error": false + }, + { + "name": "call.id '' (refused: not a plain id)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "call.id '..' (refused: not a plain id)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"..\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "call.id 'a/b' (refused: not a plain id)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"a/b\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "call.id 'a\\n' (refused: not a plain id)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"a\\n\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "call.id ' a' (refused: not a plain id)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"11111111-2222-4333-8444-555555555555\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \" a\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "location_id 'a/b' (refused: not a plain id)", + "raw": "{\"version\": \"1.0\", \"type\": \"end_of_call_summary\", \"is_test\": false, \"location_id\": \"a/b\", \"timestamp\": \"2026-11-02T16:46:12Z\", \"call\": {\"id\": \"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\", \"call_type\": \"inbound\", \"duration_seconds\": 184, \"call_date\": \"2026-11-02\", \"caller_name\": \"Jordan Example\", \"caller_number\": \"5555550142\", \"callee_name\": \"Riverbend Service Desk\", \"callee_number\": \"2001\", \"platform\": \"netsapiens\"}, \"summary\": {\"text\": \"The caller asked to move a service appointment to Thursday morning. The agent confirmed the new time and sent a reminder.\", \"sentiment\": \"positive\"}, \"location\": {\"id\": \"11111111-2222-4333-8444-555555555555\", \"company_id\": \"66666666-7777-4888-8999-aaaaaaaaaaaa\", \"connector_id\": \"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}}", + "key": null, + "error": true + }, + { + "name": "nested 65 levels (refused)", + "raw": "{\"alert_id\": \"fa-depth\", \"p\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {\"x\": {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}", + "key": null, + "error": true + }, + { + "name": "nested 5000 levels (refused, without a recursion error)", + "raw": "{\"alert_id\": \"fa-deep\", \"p\": [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}", + "key": null, + "error": true + }, + { + "name": "First Alert id with a trailing newline (refused)", + "raw": "{\"alert_id\": \"fa-1\\n\"}", + "key": null, + "error": true + }, { "name": "lone surrogate (refused)", "raw": "{\"alert_id\": \"fa-bad\", \"text\": \"\\ud800\"}", diff --git a/tests/unit/fixtures/path_argument_vectors.json b/tests/unit/fixtures/path_argument_vectors.json new file mode 100644 index 0000000..ebeae8f --- /dev/null +++ b/tests/unit/fixtures/path_argument_vectors.json @@ -0,0 +1,147 @@ +[ + { + "value": "..", + "accepted": false, + "trimmed_first": false + }, + { + "value": ".", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a/b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a%2Fb", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a?b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a#b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a\\b", + "accepted": false, + "trimmed_first": false + }, + { + "value": " a", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a ", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a\n", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a\r", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a\tb", + "accepted": false, + "trimmed_first": false + }, + { + "value": "", + "accepted": false, + "trimmed_first": false + }, + { + "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "accepted": true, + "trimmed_first": false + }, + { + "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "accepted": false, + "trimmed_first": false + }, + { + "value": "0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02", + "accepted": true, + "trimmed_first": false + }, + { + "value": "a…b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a
b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "a b", + "accepted": false, + "trimmed_first": false + }, + { + "value": "😀", + "accepted": true, + "trimmed_first": false + }, + { + "value": "x😀y", + "accepted": true, + "trimmed_first": false + }, + { + "value": "..a", + "accepted": true, + "trimmed_first": false + }, + { + "value": "a.b", + "accepted": true, + "trimmed_first": false + }, + { + "value": "user_1-2", + "accepted": true, + "trimmed_first": false + }, + { + "value": "é", + "accepted": true, + "trimmed_first": false + }, + { + "value": "a:b", + "accepted": true, + "trimmed_first": false + }, + { + "value": "a@b", + "accepted": true, + "trimmed_first": false + } +] diff --git a/tests/unit/fixtures/retry_after_vectors.json b/tests/unit/fixtures/retry_after_vectors.json index 9a71bf4..e32bf41 100644 --- a/tests/unit/fixtures/retry_after_vectors.json +++ b/tests/unit/fixtures/retry_after_vectors.json @@ -7,6 +7,10 @@ "header": "5", "seconds": 5.0 }, + { + "header": "5\n", + "seconds": null + }, { "header": "1.5", "seconds": 1.5 diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index 2549a51..b4172ec 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -244,29 +244,40 @@ def test_connector_spec_hides_secrets(): assert "pbx.example.com" in text and cs.config["client_secret"] == "S3CRET" -def test_connector_of_another_type_from_type_and_config(caplog): - # The published spec lists only "netsapiens", so strict mode would refuse another type: this test is - # about the SDK's generic path (a type the API adds later), so the fake runs without strictness. - api = FakeAPI(strict=False) +def test_connector_config_is_sent_as_given_and_its_secrets_stay_hidden(caplog): + api = FakeAPI() caplog.set_level(logging.DEBUG) - other = ic.ConnectorSpec(type="examplepbx", config={"host": "pbx.example.com", "domain": "rb.example", - "api_token": "T0KEN-SECRET"}) + spec_with_extra = ic.ConnectorSpec(type="netsapiens", config={ + "api_url": "https://pbx.example.com/ns-api/v2", "domain": "rb.example", "api_key": "T0KEN-SECRET", + "region": "us-central"}) c = api.client() - cust = c.accounts.create_customer(spec(connector=other)) - assert {x["type"] for x in api._connectors.values()} == {"examplepbx"} - assert all(x["config"]["host"] == "pbx.example.com" for x in api._connectors.values()) - assert api._secrets_sent[0] == {"host": "pbx.example.com", "domain": "rb.example", "api_token": "T0KEN-SECRET"} - assert "T0KEN-SECRET" not in repr(cust) + caplog.text + cust = c.accounts.create_customer(spec(connector=spec_with_extra)) + assert all(x["config"]["region"] == "us-central" for x in api._connectors.values()) + assert api._secrets_sent[0]["api_key"] == "T0KEN-SECRET" and api._secrets_sent[0]["region"] == "us-central" + assert "T0KEN-SECRET" not in repr(cust) + caplog.text + repr(api.requests) start = len(api._calls) - c.accounts.create_customer(spec(connector=other, company_id=cust.company_id)) + c.accounts.create_customer(spec(connector=spec_with_extra, company_id=cust.company_id)) assert api.writes_since(start) == [] -def test_unknown_connector_type_is_refused_before_any_write(api, client): +def test_a_connector_type_the_spec_does_not_list_still_reaches_the_request(): + # The platform decides which types exist (the API's /connector-types list); the SDK passes any other + # type through as type plus settings. Only the testing module's strict mode checks the spec's enum. + api = FakeAPI(strict=False) + other = ic.ConnectorSpec(type="examplepbx", config={"host": "pbx.example.com", "api_token": "T0KEN-SECRET"}) + cust = api.client().accounts.create_customer(spec(connector=other)) + assert {x["type"] for x in api._connectors.values()} == {"examplepbx"} + assert api._secrets_sent[0] == {"host": "pbx.example.com", "api_token": "T0KEN-SECRET"} + assert "T0KEN-SECRET" not in repr(cust) + repr(api.requests) + + +def test_an_unknown_connector_type_is_refused_by_the_platform_not_the_sdk(): + api = FakeAPI(strict=False) # the fake, like the platform, answers 422 for a type it does not have bad = ic.ConnectorSpec(type="nosuchpbx", config={"api_key": "K-SECRET"}) - with pytest.raises(ic.InvalidRequestError) as e: - client.accounts.create_customer(spec(connector=bad)) - assert "K-SECRET" not in str(e.value) and api.writes_since() == [] + with pytest.raises(ic.AccountError) as e: + api.client().accounts.create_customer(spec(connector=bad)) + assert isinstance(e.value.find(ic.ValidationError), ic.ValidationError) and "K-SECRET" not in str(e.value) + assert api.count("GET", "/connector-types") == 0 def create_with_connector_stop(c, s): diff --git a/tests/unit/test_final_030.py b/tests/unit/test_final_030.py new file mode 100644 index 0000000..40bae54 --- /dev/null +++ b/tests/unit/test_final_030.py @@ -0,0 +1,241 @@ +"""Final 0.3.0 cross-language rules: whole-value patterns, depth limit, plain event ids, the "unknown" +prefix, top-level body types, sign-in retries, secrets kept out of traceback locals, masked webhook URLs.""" +from __future__ import annotations + +import json +import traceback +from pathlib import Path + +import httpx +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.receiver import delivery_key +from intelligence_cloud.testing import FakeAPI + +SAMPLE = json.loads((Path(__file__).resolve().parents[2] / "examples" / "after-call-sample.json").read_text()) +LID = "0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02" + + +class Count: + def __init__(self): + self.n = 0 + + def __call__(self, r): + self.n += 1 + raise httpx.ConnectError("down", request=r) + + +def offline(): + t = Count() + return ic.Client("a@example.com", "pw", transport=httpx.MockTransport(t), sleep=lambda s: None, max_retries=0), t + + +# ---------------------------------------------------------------------- 1. whole-value patterns + + +@pytest.mark.parametrize("bad", ["a\n", "a\r", " a", "a ", "a", "a\u0085"]) +def test_an_id_with_a_trailing_newline_or_space_is_refused_with_no_request(bad): + c, t = offline() + for call in (lambda: c.users.deactivate_company_user("c1", bad), lambda: c.companies.deactivate_company(bad), + lambda: c.accounts.get_customer(bad), lambda: c.intelligence.set_first_alert_webhook(bad, None), + lambda: c.intelligence.get_call(bad), lambda: c.conversations.reference(bad)): + with pytest.raises(ic.InvalidRequestError): + call() + assert t.n == 0 + with pytest.raises(ic.WebhookPayloadError): + ic.parse_first_alert_event({"alert_id": bad}) + + +def test_retry_after_and_dates_need_the_whole_value(): + from intelligence_cloud.client import parse_retry_after + assert parse_retry_after("5\n") is None and parse_retry_after("5") == 5.0 + c, t = offline() + with pytest.raises(ic.InvalidRequestError): + c.conversations.open_tasks(due="2026-11-02\n") + assert t.n == 0 + + +# ---------------------------------------------------------------------- 2. depth + + +def nested(depth, leaf): + """A First Alert body whose deepest object sits at ``depth`` (the top-level object is depth 1).""" + value = leaf + for _ in range(depth - 1): + value = {"x": value} + return {"alert_id": "fa-deep", "payload": value} if depth > 1 else dict(leaf, alert_id="fa-deep") + + +def test_depth_64_is_accepted_and_65_refused(): + ok, deep = nested(63, {}), nested(64, {}) # payload adds one level: 64 and 65 in all + assert ic.parse_first_alert_event(json.dumps(ok)).alert_id == "fa-deep" + for body in (deep, json.dumps(deep), json.dumps(deep).encode()): + with pytest.raises(ic.WebhookPayloadError): + ic.parse_first_alert_event(body) + with pytest.raises(ic.WebhookPayloadError): + ic.Deduplicator().seen(body) + ac = json.loads(json.dumps(SAMPLE)) + ac["summary"]["text"] = nested(64, {}) + with pytest.raises(ic.WebhookPayloadError): + ic.parse_after_call_event(json.dumps(ac)) + + +def test_very_deep_bodies_fail_cleanly_without_recursion_errors(): + text = '{"alert_id": "fa-deep", "p": ' + "[" * 5000 + "]" * 5000 + "}" + for parse in (ic.parse_first_alert_event, ic.parse_after_call_event, ic.Deduplicator().seen): + with pytest.raises(ic.WebhookPayloadError): + parse(text) + value: dict = {} + for _ in range(5000): + value = {"x": value} + with pytest.raises(ic.WebhookPayloadError): + ic.parse_first_alert_event({"alert_id": "fa-deep", "p": value}) + + +# ---------------------------------------------------------------------- 3 + 4. event ids and the prefix + + +@pytest.mark.parametrize("bad", ["", "..", "a/b", "a\n", " a"]) +def test_event_ids_used_as_keys_must_be_plain(bad): + for field in ("call_id", "location_id"): + e = json.loads(json.dumps(SAMPLE)) + if field == "call_id": + e["call"]["id"] = bad + else: + e["location_id"] = bad + with pytest.raises(ic.WebhookPayloadError): + ic.parse_after_call_event(json.dumps(e)) + with pytest.raises(ic.WebhookPayloadError): + delivery_key(json.dumps(e)) + + +def test_an_event_without_a_string_type_has_the_unknown_prefix(): + assert delivery_key('{"version": "2.0", "data": 1}').startswith("unknown:") + assert delivery_key('{"type": 5, "data": 1}').startswith("unknown:") + assert delivery_key('{"type": "something_new"}').startswith("something_new:") + + +# ---------------------------------------------------------------------- 5. top-level body types + + +@pytest.mark.parametrize("bad", [123, "5", None, 1.5]) +def test_top_level_body_types_are_checked_before_sending(bad): + c, t = offline() + with pytest.raises(ic.InvalidRequestError): + c.intelligence.set_after_call_webhook(LID, "https://hooks.example.com/ic/" + "x" * 32, enabled=bad) + with pytest.raises(ic.InvalidRequestError): + c.webhooks.save_after_call_webhook(LID, {"webhook_url": "https://hooks.example.com/x", "enabled": bad}) + with pytest.raises(ic.InvalidRequestError): + c.insights_hub.update_insights_hub_config(LID, {"monitor_all_numbers": bad if bad is not None else "yes"}) + assert t.n == 0 + + +def test_allowed_values_are_left_to_the_platform(): + # No client-side enum check: a value the spec does not list still reaches the request. + api = FakeAPI(strict=False) + s = api.seed_customer(people=False) + api.client(role="admin").connectors.create_connector( + s.customer.teams[0].location_id, {"name": "x", "type": "examplepbx", "config": {"host": "pbx.example.com"}}, + wait=False) + assert api.requests[-1].body["type"] == "examplepbx" + + +# ---------------------------------------------------------------------- 6. sign-in retries + + +@pytest.mark.parametrize("cls", [httpx.ReadTimeout, httpx.WriteTimeout, httpx.RemoteProtocolError]) +def test_sign_in_is_not_retried_after_the_request_left(cls): + sent = [] + + def h(r): + sent.append(r.url.path) + raise cls("hung", request=r) + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(h), sleep=lambda s: None, deadline=2) + with pytest.raises(ic.NetworkError): + c.login() + assert sent == ["/api/v1/auth/login"] + + +def test_sign_in_is_retried_after_a_5xx_and_a_connection_that_never_opened(): + state = {"n": 0} + + def h(r): + state["n"] += 1 + if state["n"] == 1: + return httpx.Response(503, json={}) + if state["n"] == 2: + raise httpx.ConnectError("refused", request=r) + return httpx.Response(200, json={"access_token": "A", "refresh_token": "R", "expires_in": 900, + "user": {"id": "u", "role": "frontline_user"}}) + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(h), sleep=lambda s: None) + c.login() + assert state["n"] == 3 + + +# ---------------------------------------------------------------------- 7. secrets in traceback locals + +PASSWORD, REFRESH, CONN_KEY, HOOK_TOKEN = "pw-SECRET-7f3a", "rt-SECRET-91bc", "KEY-SECRET-55aa", "hooktoken0123456789abcdef0123456789ab" + + +def locals_text(exc: BaseException) -> str: + return "".join(traceback.TracebackException.from_exception(exc, capture_locals=True).format()) + + +def assert_clean(exc): + text = locals_text(exc) + for secret in (PASSWORD, REFRESH, CONN_KEY, HOOK_TOKEN): + assert secret not in text, secret + + +def test_no_secret_in_traceback_locals_for_sign_in_renewal_connector_and_webhook(): + def failing_login(r): + return httpx.Response(401, json={"error": {"code": "UNAUTHORIZED", "message": "bad"}}) + c = ic.Client("a@example.com", PASSWORD, transport=httpx.MockTransport(failing_login), sleep=lambda s: None) + with pytest.raises(ic.AuthError) as e: + c.login() + assert_clean(e.value) + + def renewal(r): + if r.url.path.endswith("/auth/refresh"): + return httpx.Response(502, json={}) + if r.url.path.endswith("/auth/login"): + return httpx.Response(401, json={}) + return httpx.Response(401, json={}) + c = ic.Client("a@example.com", PASSWORD, transport=httpx.MockTransport(renewal), sleep=lambda s: None, + token_store=ic.MemoryTokenStore(ic.Tokens("A-SECRET", REFRESH, expires_at=0))) + with pytest.raises(ic.AuthError) as e: + c.account.get_me() + assert_clean(e.value) + + api = FakeAPI(connector_outcome="error") + s = api.seed_customer(people=False) + with pytest.raises(ic.AccountError) as e: + api.client(role="admin").accounts.add_team( + s.customer, ic.TeamSpec("Riverbend - East", "9 Lake St", "Springfield", "IL", "US", "62702", + "service-providers"), + ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "east.example.com", CONN_KEY)) + assert_clean(e.value) + + api = FakeAPI() + s = api.seed_customer(people=False) + admin = api.client(role="admin") + api.fail_next(422, path=r"/locations/[^/]+/after-call/automation") + with pytest.raises(ic.ValidationError) as e: + admin.intelligence.set_after_call_webhook(s.customer.teams[0].location_id, + "https://hooks.example.com/ic/" + HOOK_TOKEN) + assert_clean(e.value) + + +# ---------------------------------------------------------------------- 8. masked webhook URLs in the log + + +def test_the_fake_log_hides_webhook_paths(): + api = FakeAPI() + s = api.seed_customer(people=False) + lid = s.customer.teams[0].location_id + admin = api.client(role="admin") + admin.intelligence.set_after_call_webhook(lid, "https://hooks.example.com/ic/" + HOOK_TOKEN) + admin.intelligence.set_first_alert_webhook(lid, "https://hooks.example.com/fa/" + HOOK_TOKEN) + text = repr(api.requests) + assert HOOK_TOKEN not in text and "https://hooks.example.com/***" in text diff --git a/tests/unit/test_request_counts.py b/tests/unit/test_request_counts.py index 9fb9449..7b01500 100644 --- a/tests/unit/test_request_counts.py +++ b/tests/unit/test_request_counts.py @@ -9,13 +9,18 @@ # helper -> (1-team customer, 10-team customer); each measured with a fresh client, so GET /me is included EXPECTED = { - "create_customer": (35, 35), - "add_team (2nd team)": (None, 25), - "add_team (10th team)": (None, 25), - "create_customer, re-run": (19, 19), + "create_customer": (34, 34), + "add_team (2nd team)": (None, 23), + "add_team (10th team)": (None, 23), + "create_customer, re-run": (18, 18), "add_base_user": (36, 90), - "add_base_manager (every team)": (33, 168), - "activate_alerts": (18, 117), + "add_base_manager (every team)": (32, 158), + "activate_alerts (Customer)": (17, 107), + "activate_alerts (company id)": (21, 120), + "sync_lines (Customer)": (11, 65), + "sync_lines (company id)": (19, 100), + "license_report (Customer)": (8, 35), + "license_report (company id)": (16, 70), "calls (one page)": (2, 2), "brief": (3, 3), } @@ -64,7 +69,19 @@ def measure(teams: int) -> dict: out["add_base_manager (every team)"] = len(api.requests) - start start = len(api.requests) api.client(role="admin").accounts.activate_alerts(seeded.customer) - out["activate_alerts"] = len(api.requests) - start + out["activate_alerts (Customer)"] = len(api.requests) - start + + for label, call in ( + ("activate_alerts (company id)", lambda a, sc: a.activate_alerts(sc.company_id)), + ("sync_lines (Customer)", lambda a, sc: a.sync_lines(sc.customer)), + ("sync_lines (company id)", lambda a, sc: a.sync_lines(sc.company_id)), + ("license_report (Customer)", lambda a, sc: a.license_report(sc.customer)), + ("license_report (company id)", lambda a, sc: a.license_report(sc.company_id))): + fresh = FakeAPI() + sc = fresh.seed_customer(teams=teams) + start = len(fresh.requests) + call(fresh.client(role="admin").accounts, sc) + out[label] = len(fresh.requests) - start ids = api.seed_calls(3) start = len(api.requests) diff --git a/tests/unit/test_shared_vectors.py b/tests/unit/test_shared_vectors.py index a3ae4a3..a1d7546 100644 --- a/tests/unit/test_shared_vectors.py +++ b/tests/unit/test_shared_vectors.py @@ -252,3 +252,14 @@ def test_a_hand_built_customer_with_another_companys_ids_is_refused(): with pytest.raises(ic.InvalidRequestError): api.client(role="admin").accounts.activate_alerts(forged) assert api.writes_since(start) == [] + + +@pytest.mark.parametrize("v", load("path_argument_vectors.json"), ids=lambda v: repr(v["value"])) +def test_path_argument_vectors(v): + from intelligence_cloud._spec import check_path_value + assert v["trimmed_first"] is False + if v["accepted"]: + assert check_path_value(v["value"], "id") == v["value"] + else: + with pytest.raises(ic.InvalidRequestError): + check_path_value(v["value"], "id") diff --git a/tools/make_shared_vectors.py b/tools/make_shared_vectors.py index a4b4d20..f807a76 100644 --- a/tools/make_shared_vectors.py +++ b/tools/make_shared_vectors.py @@ -103,7 +103,30 @@ def fa(payload): fa({"ア": "half-width katakana", "a": "ascii", "דּ": "hebrew presentation form", "alert_id": "fa-keys", "\U0001F600": "emoji (surrogates D83D DE00)"})) assert k1 == k2 - for name, raw in (("lone surrogate (refused)", '{"alert_id": "fa-bad", "text": "\\ud800"}'), + add("an event with no type: prefix \"unknown\"", '{"version": "2.0", "data": {"a": 1}}') + assert v[-1]["key"].startswith("unknown:") + add("an event whose type is not a string: prefix \"unknown\"", '{"type": 5, "data": 1}') + assert v[-1]["key"].startswith("unknown:") + + def depth(n): # a First Alert body nested exactly n levels (the top-level object is level 1) + inner = "{}" + for _ in range(n - 2): + inner = '{"x": ' + inner + "}" + return '{"alert_id": "fa-depth", "p": ' + inner + "}" + add("nested 64 levels (accepted)", depth(64)) + assert not v[-1]["error"] + for bad in ("", "..", "a/b", "a\n", " a"): + raw = ac(lambda e, bad=bad: e["call"].update(id=bad)) + assert key_of(raw)[1], bad + v.append({"name": f"call.id {bad!r} (refused: not a plain id)", "raw": raw, "key": None, "error": True}) + raw = ac(lambda e: e.update(location_id="a/b")) + assert key_of(raw)[1] + v.append({"name": "location_id 'a/b' (refused: not a plain id)", "raw": raw, "key": None, "error": True}) + for name, raw in (("nested 65 levels (refused)", depth(65)), + ("nested 5000 levels (refused, without a recursion error)", + '{"alert_id": "fa-deep", "p": ' + "[" * 5000 + "]" * 5000 + "}"), + ("First Alert id with a trailing newline (refused)", '{"alert_id": "fa-1\\n"}'), + ("lone surrogate (refused)", '{"alert_id": "fa-bad", "text": "\\ud800"}'), ("lone low surrogate in an After Call field (refused)", ac(lambda e: e["summary"].update(text="x")).replace('"x"', '"\\udc00"')), ("duplicate object keys (refused)", '{"alert_id": "fa-dup", "alert_id": "fa-dup2"}'), @@ -154,7 +177,7 @@ def canonical_vectors(): def retry_after_vectors(): - headers = ["0", "5", "1.5", "120", "007", "999999999", "999999999.25", "1234567890", "-1", "", " 5", "5 ", "1e2", + headers = ["0", "5", "5\n", "1.5", "120", "007", "999999999", "999999999.25", "1234567890", "-1", "", " 5", "5 ", "1e2", "INF", "NaN", "Infinity", "Wed, 21 Oct 2015 07:28:00 GMT", "1.", ".5", "+5", "0x10", "1,5", "5s"] return [{"header": h, "seconds": parse_retry_after(h)} for h in headers] @@ -205,6 +228,16 @@ def add(name, mutate=None, raw=None, reason=""): assert add("an unknown field", lambda e: e.update(extra=1), reason="unknown fields are dropped") == "ok" assert add("another event type", lambda e: e.update(type="something_new"), reason="UnknownEvent: answer 2xx") == "unknown" assert add("type missing", lambda e: e.pop("type"), reason="UnknownEvent: answer 2xx") == "unknown" + for bad in ("", "..", "a/b", "a\n", " a"): + assert add(f"call.id {bad!r}", lambda e, bad=bad: e["call"].update(id=bad), + reason="call.id must be a plain id: [A-Za-z0-9_-]{1,128}, whole value, not trimmed") == "refused" + assert add("location_id 'a/b'", lambda e: e.update(location_id="a/b"), reason="location_id must be a plain id") == "refused" + deep = copy.deepcopy(s) + inner: dict = {} + for _ in range(64): + inner = {"x": inner} + deep["summary"]["text"] = inner + assert add("nested deeper than 64 levels", raw=dumps(deep), reason="at most 64 levels") == "refused" assert add("a JSON array", raw="[1, 2]", reason="not an object") == "refused" assert add("not JSON", raw="{", reason="not JSON") == "refused" return out @@ -247,6 +280,28 @@ def strictness_vectors(): return [{"name": n, "method": m, "path": p, "query": qq, "body": b, "status": st} for n, m, p, qq, b, st in q] +def path_vectors(): + from intelligence_cloud._spec import check_path_value + from intelligence_cloud.errors import InvalidRequestError + values = ["..", ".", "a/b", "a%2Fb", "a?b", "a#b", "a\\b", " a", "a ", "a\n", "a\r", "a\tb", "", "a" * 128, + "a" * 129, "0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02", "a\u0085b", "\ufeffa", "a\u00a0b", "a\u2028b", + "a\u3000b", "\U0001F600", "x\U0001F600y", "..a", "a.b", "user_1-2", "é", "a:b", "a@b"] + out = [] + for value in values: + try: + check_path_value(value, "id") + accepted = True + except InvalidRequestError: + accepted = False + out.append({"value": value, "accepted": accepted, "trimmed_first": False}) + expect_refused = {"..", ".", "a/b", "a%2Fb", "a?b", "a#b", "a\\b", " a", "a ", "a\n", "a\r", "a\tb", "", "a" * 129, + "a\u0085b", "\ufeffa", "a\u00a0b", "a\u2028b", "a\u3000b"} + for e in out: + if (e["value"] in expect_refused) == e["accepted"]: + raise SystemExit(f"path rule mismatch for {e['value']!r}") + return out + + def main() -> None: files = { "delivery_key_vectors.json": delivery_vectors(), @@ -254,12 +309,17 @@ def main() -> None: "retry_after_vectors.json": retry_after_vectors(), "after_call_parse_vectors.json": parse_vectors(), "fake_strictness_vectors.json": strictness_vectors(), + "path_argument_vectors.json": path_vectors(), } dirs = [OUT] + [pathlib.Path(a) for a in sys.argv[1:]] for d in dirs: d.mkdir(parents=True, exist_ok=True) for name, data in files.items(): (d / name).write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + counts = (HERE / "tests" / "unit" / "test_request_counts.py").read_text().split("\n\n\ndef _spec")[0] + for d in dirs[1:]: + (d / "request_counts_reference.py.txt").write_text(counts + "\n", encoding="utf-8") + (d / "SHARED_VECTORS_VERSION").write_text("3\n", encoding="utf-8") for name, data in files.items(): print(f"{name}: {len(data)} entries") From ec78e2e935cfa0946cad82211c23676e1136dea8 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 20:27:27 -0700 Subject: [PATCH 07/11] Tests: the reference vector folder comes from IC_SHARED_VECTORS_DIR, not a local path; README names no product for the shared store Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- tests/unit/test_shared_vectors.py | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 992277c..7e6c3fa 100644 --- a/README.md +++ b/README.md @@ -340,7 +340,7 @@ admin.intelligence.test_first_alert_webhook(location_id) - Treat an event as a notification. Before you write anything from it into another system, read the call with `get_call(event.call.id)` using your frontline integration user; a `NotFoundError` means drop the event. - **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsert_key(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before. - **Check, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse → if `seen(event)`: answer 2xx → upsert under `upsert_key(event)` → `remember(event)` → answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. An exact re-delivery is the same event type, location and call id with the same content: the SHA-256 of the **RFC 8785 (JSON Canonicalization Scheme)** form of the event as the SDK reads it (numbers as doubles, keys in UTF-16 order), because the payload carries no version marker. A later delivery with newer data is not seen. Bodies that are not I-JSON (duplicate keys, NaN, a lone surrogate) are refused with `WebhookPayloadError`. Two things follow: two identical deliveries arriving at the same moment can both be "not seen" (harmless, because storing is an upsert by call id); and a delivery that differs only in a field the SDK does not document counts as a re-delivery, because the event is read through the published schema before hashing. It takes an event, a parsed body or the raw bytes; a plain id is refused, because an id alone cannot tell newer data apart. -- Its default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)`, for example `Deduplicator(store=RedisStore(r))` where `has` is `return bool(r.exists("ic:" + key))` and `add` is `r.set("ic:" + key, 1, ex=86400)`. +- Its default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)`, for example `Deduplicator(store=SharedStore(kv))` over a key-value store your workers share, where `has` is `return bool(kv.exists("ic:" + key))` and `add` is `kv.set("ic:" + key, 1, ex=86400)`; `kv` is your own client. - To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test` (from the source distribution). FastAPI: diff --git a/tests/unit/test_shared_vectors.py b/tests/unit/test_shared_vectors.py index a1d7546..e764e89 100644 --- a/tests/unit/test_shared_vectors.py +++ b/tests/unit/test_shared_vectors.py @@ -2,6 +2,7 @@ rule, free-text arguments, masked request logs and stale Customer objects.""" from __future__ import annotations +import os import json import math from datetime import datetime, timezone @@ -109,10 +110,12 @@ def test_fake_strictness_vectors(v): assert set(r.json()["error"]) >= {"code", "message"} -def test_vector_copies_match_the_shared_folder_when_present(): - shared = Path("/private/tmp/claude-501/-Users-robertgalop-Dev/7ebbbd38-ce89-42da-b25d-ac8d3f58f6de/scratchpad/shared-vectors") - if not shared.exists(): - pytest.skip("the shared folder is not on this machine") +def test_vector_copies_match_the_shared_folder_when_given(): + """The three SDKs carry identical copies. Set IC_SHARED_VECTORS_DIR to a folder holding the reference copies.""" + folder = os.environ.get("IC_SHARED_VECTORS_DIR") + if not folder: + pytest.skip("IC_SHARED_VECTORS_DIR is not set") + shared = Path(folder) for f in FIX.glob("*.json"): assert (shared / f.name).read_bytes() == f.read_bytes(), f.name From 6b39d419add6f6105d24bfe41753a3fed8e1bf38 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 20:45:06 -0700 Subject: [PATCH 08/11] Live suite: a re-used company keeps its rules on; only a rule created in this run must be off Co-Authored-By: Claude Fable 5.2 --- tests/live/test_live.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/live/test_live.py b/tests/live/test_live.py index 9116c67..7029ece 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -241,7 +241,9 @@ def test_create_customer(admin, customer): if SSO_DOMAIN: assert customer.sso_txt_record and customer.sso_txt_record["name"] == "_ic-verify." + SSO_DOMAIN low = unwrap(admin.first_alert.get_alert_rule(team.location_id, team.rules.low_sentiment)) - assert low["enabled"] is False and [g["id"] for g in low["groups"]] == [team.groups.low_sentiment_calls] + assert [g["id"] for g in low["groups"]] == [team.groups.low_sentiment_calls] + if f"rule:{team.name}:Low Sentiment" in customer.created: # a company kept from an earlier run has its rules on + assert low["enabled"] is False setup = unwrap(admin.insights_hub.get_insights_hub_setup(team.location_id)) assert team.groups.insights_hub_access in setup["group_access"] _no_monitor_all_no_rules_at_management(admin, customer) From 499ad47d44925ed22af0fae5283f7325336f1406 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 20:57:45 -0700 Subject: [PATCH 09/11] README: alert activation covers every team; request count from the measured table Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7e6c3fa..7bfc693 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ team = customer.teams[0] admin.accounts.add_base_user(customer, PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), team=team, line="2101") admin.accounts.add_base_manager(customer, PersonSpec("dana.cho@example.com", "Dana", "Cho"), teams=[team], line="2001") -admin.accounts.activate_alerts(customer) # once each team has a manager in its alert groups +admin.accounts.activate_alerts(customer) # every team; a team with no manager is listed in the result ``` - **Phrase lists come from you.** The SDK holds none; ask your Tresic contact for them. A customer can be created without them: Low Sentiment and every group are created, `customer.pending` lists `"customer_threat"` and `"upset_customer"`, and `set_alerts` creates those alerts when the lists arrive. From 5b3ce64afcc91601ddd93e2238676ef60ffe9374 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 21:27:19 -0700 Subject: [PATCH 10/11] Developer review: a testing module that models real cases; typed results Testing module: - every request is logged with what answered it; auth_log logs every sign-in and renewal attempt - connector_outcome applies to attempts made after it is set; settle_connector settles a waiting connector - client(as_user=...) signs in as a seeded person (scope follows their license); seed_customer returns people; seed_calls(recording, topics) - fail_next(sign_in=...) for MFA, expired password, bad credentials - strict=False lets an unlisted connector type through - fake_behaviour_vectors.json: shared scenarios with a neutral format; line_vectors.json; SHARED_VECTORS_VERSION 4 SDK: - typed, frozen results for license_report, activate_alerts, sync_lines, remove_user and offboard_customer, still readable by key - lines must match +?[0-9*#]{1,32}; messages name the caller's parameters; Member.teams lists every team; teams() puts Management last - is_older and a receiver flow that never stores older data over newer - a connector still settling on a re-run is checked and restarted once - README: upgrading section, test hooks, set_alerts cost, the ten-team total, activate_alerts measured under the stated conditions Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + README.md | 67 +- examples/webhook_receiver.py | 44 +- src/intelligence_cloud/__init__.py | 13 +- src/intelligence_cloud/accounts.py | 232 ++++- src/intelligence_cloud/conversations.py | 17 +- src/intelligence_cloud/intelligence.py | 20 +- src/intelligence_cloud/receiver.py | 26 + src/intelligence_cloud/testing/__init__.py | 4 +- src/intelligence_cloud/testing/_fake.py | 320 +++++-- tests/unit/behaviour_runner.py | 131 +++ .../unit/fixtures/fake_behaviour_vectors.json | 807 ++++++++++++++++++ tests/unit/fixtures/line_vectors.json | 78 ++ tests/unit/test_accounts.py | 2 +- tests/unit/test_developer_round.py | 244 ++++++ tests/unit/test_request_counts.py | 41 +- tests/unit/test_review_030.py | 3 +- tests/unit/test_review_fixes.py | 19 +- tools/make_shared_vectors.py | 152 +++- 19 files changed, 2053 insertions(+), 176 deletions(-) create mode 100644 tests/unit/behaviour_runner.py create mode 100644 tests/unit/fixtures/fake_behaviour_vectors.json create mode 100644 tests/unit/fixtures/line_vectors.json create mode 100644 tests/unit/test_developer_round.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3342a98..952d0fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,12 @@ - **Sign-in is not retried after a timeout or reset once the request was sent** (still after a failure that never left, a 5xx, or a 429 within the wait limit). - **Secrets stay out of tracebacks:** request bodies, headers and webhook addresses travel in types whose printed form hides secret-named values and URL paths; the refresh token stays inside `Tokens`. - `license_report` reads the customer once; a team read earlier in the same helper call is not read again. +- **Typed account results:** `license_report`, `activate_alerts`, `sync_lines`, `remove_user` and `offboard_customer` return frozen dataclasses (`LicenseReport`, `AlertActivation` with `NoManagerTeam`, `LineSyncReport` with `TeamLines` and `LineDiff`, `RemovalSummary`, `OffboardSummary`) with the same field names in every SDK; they still support `result["key"]`, `"key" in result`, `.get()` and equality with a dict, and `to_dict()`. +- **Lines** must be the whole value `+?[0-9*#]{1,32}`; anything else (a space, a dash) raises `InvalidRequestError` before any request. +- **Out-of-order deliveries:** `is_older(event, stored)` compares the events' own timestamps; the receiver flow is parse, seen, compare with what is stored, upsert, remember. When two deliveries carry the same timestamp, the later arrival wins. +- `Member.teams` lists every team the person is on after the call; `conversations.teams()` lists teams first (in name order) and Management last; error messages name the parameters as the caller wrote them (`number`/`search` for `calls`). +- A connector found still settling when a helper runs again is checked again and restarted once if it does not settle. +- Testing module: `requests` logs every request with what answered it (`answer`); `auth_log` logs every sign-in and renewal attempt; `connector_outcome` applies to connection attempts made after it is set, and `settle_connector` settles a waiting one; `client(as_user=...)` signs in as a seeded person (`seed_customer` returns `people`); `seed_calls(recording=..., topics=...)`; `fail_next(sign_in=...)`; strict mode off lets an unlisted connector type through. Shared behaviour scenarios in `fake_behaviour_vectors.json`. - Connector waits count the check intervals as well as the clock, so a replaced `sleep` (tests) cannot spin for the whole timeout. - README: "Retries" with worst-case blocking time, "Testing your code", "Running helpers from more than one process", "How many requests" (pinned by a test), the error tree. SDK documentation links now point to the SDK pages (https://docs.intelligence.cloud/sdk/, /sdk/quick-start, /sdk/reference, /sdk/events, /sdk/configuration, /sdk/downloads); API links stay https://docs.intelligence.cloud/api and https://docs.intelligence.cloud/reference. The examples ship in the source distribution, not the wheel, and the README says so. Package metadata links to the SDK pages, with "Changelog" on https://docs.intelligence.cloud/sdk/downloads. - Examples use one fictional customer, Riverbend Auto Group, and the variables `IC_ADMIN_EMAIL` / `IC_ADMIN_PASSWORD` and `IC_USER_EMAIL` / `IC_USER_PASSWORD` (`IC_DATA_*` still read by the examples as a fallback). @@ -37,6 +43,9 @@ | `MfaRequiredError` derived from `IntelligenceCloudError` only | It is an `AuthError` (status 200, code `mfa_required`): an `except AuthError` now catches it | | `ConnectorTimeoutError` was not a `ConnectorError` | It is: an `except ConnectorError` now catches timeouts too (put `except ConnectorTimeoutError` first to tell them apart) | | `FrontlineRequiredError` derived from `IntelligenceCloudError` only | It is a `WrongLoginError` | +| `activate_alerts`, `license_report`, `sync_lines`, `remove_user` and `offboard_customer` returned dicts | Typed results; reading them by key still works, but code that mutates them or checks `isinstance(result, dict)` breaks | +| A line with a space or a dash was sent | Refused before sending | +| `conversations.teams()` listed Management first | Teams first, Management last | | `Deduplicator.is_duplicate(event_or_call_id)` checked and recorded in one call, keyed on the call id | Removed, with no alias: `seen(event)` checks, `remember(event)` records after your write. A plain id raises `InvalidRequestError` | | A custom `DedupStore` needed `add(key) -> bool` | It needs `has(key) -> bool` and `add(key)` | | No overall time limit | `deadline=120` seconds per API request (sign-in, renewal, retries and waits included); raise it for long Retry-After waits | diff --git a/README.md b/README.md index 7bfc693..072c4a9 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ admin = Client(os.environ["IC_ADMIN_EMAIL"], os.environ["IC_ADMIN_PASSWORD"]) data = Client(os.environ["IC_USER_EMAIL"], os.environ["IC_USER_PASSWORD"]) ``` -`Client(email, password, *, base_url="https://app.intelligence.cloud/api/v1", token_store=None, timeout=30, ...)`: email and password first (by position or keyword), everything else by keyword; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"), and `deadline=120` (see "Retries"; `clock=` replaces the clock for tests). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. +`Client(email, password, *, base_url="https://app.intelligence.cloud/api/v1", token_store=None, timeout=30, ...)`: email and password first (by position or keyword), everything else by keyword; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"), and `deadline=120` (see "Retries"). Two options are **test hooks**: `sleep=` (default `time.sleep`) is called for every wait (retries, Retry-After, connector checks), and `clock=` (default `time.monotonic`) is read for the deadline; pass your own to run waits instantly or drive time in a test (`intelligence_cloud.testing` passes a no-op `sleep`). `timeout=` is the per-attempt HTTP timeout; it is not the connector settle timeout, which `ConnectorSpec.timeout` sets. `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. ### Sign-in, tokens and sign-out @@ -120,13 +120,15 @@ admin.accounts.activate_alerts(customer) # every team; a team with no manager | `change_license(customer, user_id, to, *, teams=None, line=None)` | `"base_manager"` or `"base_user"`, moving their own line between the team and Management | `Member` | | `move_user(customer, user_id, *, from_team, to_team)` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` | | `change_line(customer, user_id, old, new)` | A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | `Member` | -| `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | summary | -| `activate_alerts(customer, *, team=None)` | Switches alerts on for every team. Returns a dict: `switched_on` (rule ids) and `no_manager` (teams whose alert groups have no manager, so their alerts show in the app only) | `{"switched_on", "no_manager"}` | +| `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | `RemovalSummary` (`user_id`, `license`, `released_lines`, `deactivated`, `notes`) | +| `activate_alerts(customer, *, team=None)` | Switches alerts on for every team: `switched_on` (rule ids) and `no_manager` (`NoManagerTeam`: teams whose alert groups have no manager, so their alerts show in the app only) | `AlertActivation` | | `send_invitations(customer, *, user_ids=None)` | Sends invitations not yet sent or expired; re-sends to `user_ids` | user ids | | `list_members(customer, *, license=None, team=None)` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `list[Member]` | -| `license_report(customer)` | People by license and the number of teams (Management not counted) | counts and members | -| `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | changes | -| `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary | +| `license_report(customer)` | People by license and the number of teams (Management not counted) | `LicenseReport` (`base_user`, `base_manager`, `integration`, `other`, `teams`, `members`) | +| `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | `LineSyncReport` (`teams`: `TeamLines` by location id, `applied`) | +| `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | `OffboardSummary` | + +These results are frozen dataclasses with the same field names in every SDK. They also read like the 0.2 dicts (`result["switched_on"]`, `"applied" in result`, `result.get(...)`, equality with a dict), and `result.to_dict()` gives a plain copy. A `Member` lists **every** team the person is on after the call, not only the teams named in it. A line (extension or number) must be the whole value `+?[0-9*#]{1,32}`: `"21 10"` or `"21-10"` raises `InvalidRequestError` before any request. Every helper that takes `customer` also takes a company id. **A `Customer` is a snapshot the helpers keep current**: each helper first reads the company's location list once and compares it with the object's teams and Management (ids and active state); when anything differs it re-reads the whole layout and updates the object in place (`refreshed_at` says when). Group and rule ids for the teams a helper touches are always read live in that call, never taken from the object; a missing group stops the helper before it writes. A `Customer` carrying a location its company does not have is refused (`InvalidRequestError`). `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only. A line another location already holds reaches you as **`AccountError` → `ExtensionMappingError` → `ConflictError`** (message "Extension is already monitored at another location.", the clashing numbers on `.extensions`). Use `AccountError.find` instead of walking the chain: @@ -151,12 +153,13 @@ for brief in me.conversations.calls(): # today, newest first history = me.conversations.caller_history("5555550142", limit=5) detail = me.conversations.brief(call_id) # summary, key points, tasks, sentiment, topics, alerts tasks = me.conversations.open_tasks() -board = me.conversations.team_view(team_id) # for a manager: counts, alerts, open tasks, briefs +my_team = next(t for t in me.conversations.teams() if t.kind == "team") # teams first, Management last +board = me.conversations.team_view(my_team) # for a manager: counts, alerts, open tasks, briefs ``` | Helper | Returns | Limits | |---|---|---| -| `me()`, `teams()` | Who is signed in and the teams they can see. `me().lines` is `None`: the API gives a user login no way to read its own lines | | +| `me()`, `teams()` | Who is signed in and the teams they can see: `kind == "team"` first in name order, Management last. `me().lines` is `None`: the API gives a user login no way to read its own lines | | | `calls(*, day=None, since=None, until=None, team=None, number=None, search=None, limit=50)` | `list[CallBrief]`, newest first; default today | window at most 31 days, `limit` at most 200 | | `brief(call_id)` | One `CallBrief` with key points, tasks, topics and the alerts it raised (read from one page of that day's alerts, so a day with more than 100 alerts can miss some) | no transcript, no recording | | `transcript(call_id)` | The transcript of one call | one call per request | @@ -339,7 +342,7 @@ admin.intelligence.test_first_alert_webhook(location_id) - `parse_after_call_event` refuses bodies over 256 KB (`PayloadTooLargeError`: answer 413) and returns `UnknownEvent` for event types it doesn't handle: answer 2xx and ignore them. It refuses an event (`WebhookPayloadError`: answer 400) exactly when a field the published schema marks required is missing or has the wrong JSON type (`version`, `type`, `is_test`, `location_id`, `timestamp`, `call` with `id`, `call_type`, `duration_seconds`, `call_date`, and `location`); other fields may be absent and read as None when they have the wrong type; unknown fields are dropped; an integer is a whole-number JSON number. `call_date` and `timestamp` read as None when their text is not a date. Answer 404 for a wrong token. - Treat an event as a notification. Before you write anything from it into another system, read the call with `get_call(event.call.id)` using your frontline integration user; a `NotFoundError` means drop the event. - **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsert_key(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before. -- **Check, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse → if `seen(event)`: answer 2xx → upsert under `upsert_key(event)` → `remember(event)` → answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. An exact re-delivery is the same event type, location and call id with the same content: the SHA-256 of the **RFC 8785 (JSON Canonicalization Scheme)** form of the event as the SDK reads it (numbers as doubles, keys in UTF-16 order), because the payload carries no version marker. A later delivery with newer data is not seen. Bodies that are not I-JSON (duplicate keys, NaN, a lone surrogate) are refused with `WebhookPayloadError`. Two things follow: two identical deliveries arriving at the same moment can both be "not seen" (harmless, because storing is an upsert by call id); and a delivery that differs only in a field the SDK does not document counts as a re-delivery, because the event is read through the published schema before hashing. It takes an event, a parsed body or the raw bytes; a plain id is refused, because an id alone cannot tell newer data apart. +- **Check, compare, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse → if `seen(event)`: answer 2xx → load what is stored under `upsert_key(event)` → if `is_older(event, stored)`: `remember(event)` and answer 2xx without storing → else upsert → `remember(event)` → answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. `is_older` compares the events' own `timestamp` fields (false when either has none). **Ordering relies on the event's timestamp; when two deliveries carry the same timestamp, the later arrival wins.** Without the comparison, a v1 that failed to store and is retried after v2 was stored would overwrite newer data with older. An exact re-delivery is the same event type, location and call id with the same content: the SHA-256 of the **RFC 8785 (JSON Canonicalization Scheme)** form of the event as the SDK reads it (numbers as doubles, keys in UTF-16 order), because the payload carries no version marker. A later delivery with newer data is not seen. Bodies that are not I-JSON (duplicate keys, NaN, a lone surrogate) are refused with `WebhookPayloadError`. Two things follow: two identical deliveries arriving at the same moment can both be "not seen" (harmless, because storing is an upsert by call id); and a delivery that differs only in a field the SDK does not document counts as a re-delivery, because the event is read through the published schema before hashing. It takes an event, a parsed body or the raw bytes; a plain id is refused, because an id alone cannot tell newer data apart. - Its default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)`, for example `Deduplicator(store=SharedStore(kv))` over a key-value store your workers share, where `has` is `return bool(kv.exists("ic:" + key))` and `add` is `kv.set("ic:" + key, 1, ex=86400)`; `kv` is your own client. - To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test` (from the source distribution). @@ -351,7 +354,7 @@ import os from fastapi import BackgroundTasks, FastAPI, HTTPException, Request from intelligence_cloud import (AfterCallEvent, Deduplicator, PayloadTooLargeError, WebhookPayloadError, - parse_after_call_event, upsert_key) + is_older, parse_after_call_event, upsert_key) app = FastAPI() dedup = Deduplicator() @@ -372,6 +375,10 @@ async def after_call(token: str, request: Request, background: BackgroundTasks): if not isinstance(event, AfterCallEvent) or event.is_test or dedup.seen(event): return {"ok": True} # other types, tests and exact re-deliveries try: + stored = store.get(upsert_key(event)) # what you stored for this call, or None + if stored is not None and is_older(event, stored["timestamp"]): + dedup.remember(event) # an older delivery arriving late: keep the newer data + return {"ok": True} store.upsert(upsert_key(event), event.raw) # durable, keyed on the call id: newer data replaces older except StorageError: raise HTTPException(status_code=503) # not remembered: the sender's retry is processed @@ -489,19 +496,40 @@ def test_resumes_after_a_stop(): | `FakeAPI` | Does | |---|---| | `FakeAPI(*, connector_outcome="active", role="admin", strict=True)` | A new, empty fake | -| `client(role=None, **client_options)` | A real `Client` (role "admin" or "user"); waits do not sleep | -| `seed_customer(*, teams=1, people=True)` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `company_id`, `base_users`, `managers`) | -| `seed_calls(n=3, *, location_id=None, day=None, alerts=True, tasks=True)` | Fictional calls with details, tasks and alerts (555-01xx numbers). Returns the call ids, newest first | -| `connector_outcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connectors created from now on | -| `fail_next(status=None, *, network=None, method=None, path=None, retry_after=None, after_processing=False)` | The next matching request fails once: an HTTP status, or `network="connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"undecodable"`. By default the failure comes before the platform acts (a renewal's token stays unused); `after_processing=True` applies the request first (a write lands, a refresh token is rotated) and loses the answer | +| `client(role=None, *, as_user=None, **client_options)` | A real `Client` (role "admin" or "user"); waits do not sleep. `as_user` (role "user"): the id or email of a seeded person, so their calls, alerts, tasks and Insights Hub access follow their license and teams; clients for the same person share that login's sessions | +| `seed_customer(*, teams=1, people=True)` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `company_id`, `base_users`, `managers`, `people`: `SeededPerson(user_id, email, license, teams, lines)`) | +| `seed_calls(n=3, *, location_id=None, day=None, alerts=True, tasks=True, recording=False, topics=False)` | Fictional calls with details, tasks and alerts (555-01xx numbers), each reaching a seeded Base User's line in turn. `recording=True` adds a recording link (example.com, expires in two hours); `topics=True` fills topic volumes and rising topics. Returns the call ids, newest first | +| `connector_outcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connection attempts made after it is set (a connector created or restarted later); it does not change connectors already waiting | +| `settle_connector(connector_id_or_location, outcome="active")` | Settle connectors that are waiting: the one with this id, or every waiting one at this location ("active", "connected" or "error") | +| `fail_next(status=None, *, network=None, sign_in=None, method=None, path=None, retry_after=None, after_processing=False)` | The next matching request fails once: an HTTP status; `network="connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"undecodable"`; or the next sign-in answers `sign_in="mfa_required"`, `"password_expired"` or `"invalid_credentials"`. By default the failure comes before the platform acts (a renewal's token stays unused); `after_processing=True` applies the request first (a write lands, a refresh token is rotated) and loses the answer | | `fail_write(nth=1, status=400)`, `network_down(down=True)`, `rate_limit(count=1, retry_after=1)`, `expire_access_tokens()` | Simpler knobs: the nth write fails; no network; 429s; every access token expires (the next call renews) | -| `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()`, `auth_log` | The request log (sign-in and renewal are in `auth_log`: "login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) | +| `requests`, `writes`, `writes_since(start)`, `count(method, path_regex)`, `reset_log()`, `auth_log` | The request log: **every** request the fake received, including those a knob answered, each with `answer` (the HTTP status, or `"network:connect"` and the like), so retries can be counted. Sign-in and renewal attempts are in `auth_log` ("login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) | | `products(uid, lid)`, `numbers(uid, connector_id=None)`, `fa_numbers(lid)`, `ih_numbers(lid)`, `group_members(lid, name)` | State to assert on | That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore and may change. `client(transport=...)` is refused. The request log masks secret-named values and shows URL fields (`url`, `webhook_url`, any `*_url`) with their path hidden (`https://hooks.example.com/***`), as the SDK does in its own printed forms and tracebacks. **Strict mode** (`strict=True`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type, outside its enum or range, or not in its format (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). Formats use explicit patterns, the same in every SDK: whole number `-?(0|[1-9][0-9]*)`; date `YYYY-MM-DD` on a real calendar day; date-time RFC 3339 with seconds, `T`, and `Z` or `±HH:MM`; uuid hyphenated, all lower or all upper case. Body enums and formats come from the bundled spec. It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states (for example the spec gives no list of user roles). Code that passes against it still needs one run against a test company before release. +## Upgrading from 0.2 + +- `Client(email, password, *, ...)`: only email and password by position. +- **Connectors in account helpers:** a connector that does not settle, or ends in error, arrives as `AccountError` (step `"connectors"`) whose cause is `ConnectorTimeoutError` or `ConnectorError`, once everything else is built. A 0.2-style `except ConnectorTimeoutError` around `add_team` no longer catches it: + +```python +try: + admin.accounts.add_team(customer, team, connector) +except AccountError as err: + if err.find(ConnectorTimeoutError): # still settling: run add_team again later + ... + elif err.find(ConnectorError): # ended in error: check state_reason, fix the key, run again + ... +``` + + The settle timeout is `ConnectorSpec.timeout` (600 s). The client's `timeout=` and the `timeout=` argument of the low-level `connectors.create_connector`, `reactivate_connector` and `deactivate_connector` methods apply only to those methods and HTTP attempts. +- `Deduplicator.is_duplicate` is gone: `seen(event)` checks, `remember(event)` records after your write (see "Receive"). +- Account results are typed (`AlertActivation`, `LicenseReport`, ...) but still read like the 0.2 dicts. +- See `CHANGELOG.md` for every breaking change. + ## Running helpers from more than one process Account helpers read, merge and write whole lists. Two processes changing the same customer at once can each read the old list and write back their own version, and one change is lost; two runs of `create_customer` for a new customer can create it twice. Run at most one account helper per customer at a time. On one machine, a file lock is enough: @@ -550,13 +578,16 @@ Measured against `intelligence_cloud.testing` with a fresh client (one `GET /me` | `create_customer`, re-run | 18 | 18 | | `add_base_user` (customer passed as a company id) | 36 | 90 | | `add_base_manager` (on every team, Customer object) | 32 | 158 | -| `activate_alerts` (Customer object; company id) | 17; 21 | 107; 120 | +| `activate_alerts` (Customer object; company id), rules off before the call | 15; 21 | 105; 120 | +| `set_alerts` (both phrase alerts, Customer object) | 8 | 62 | | `sync_lines` (Customer object; company id) | 11; 19 | 65; 100 | | `license_report` (Customer object; company id) | 8; 16 | 35; 70 | | `calls` (one page) | 2 | 2 | | `brief` | 3 | 3 | -A helper given a company id reads the whole layout first (for a 1-team customer 9 requests: the company, its locations, and each location's groups, rules and connectors, plus the domains); given a `Customer` object it reads only the location list it checks the object against (1 request), plus the groups and rules of each team whose ids it uses (2 per team), so passing the object saves 8 requests on a 1-team customer and 35 on a 10-team one for `sync_lines` and `license_report`. The counts assume two Base Users per team and one manager, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. +A helper given a company id reads the whole layout first (for a 1-team customer 9 requests: the company, its locations, and each location's groups, rules and connectors, plus the domains); given a `Customer` object it reads only the location list it checks the object against (1 request), plus the groups and rules of each team whose ids it uses (2 per team), so passing the object saves 8 requests on a 1-team customer and 35 on a 10-team one for `sync_lines` and `license_report`. **Worked total:** setting up a ten-team customer end to end with a `Customer` object (create, nine `add_team`, both phrase alerts, one manager per team, three Base Users per team, activate) takes **2,497 requests**, about **8.3 minutes** at 5 requests a second (a test pins it). + +The counts assume a freshly seeded customer with two Base Users per team and one manager, alert rules off before `activate_alerts`, a connector that settles at its first check, and the customer passed as an object to `add_team`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `add_base_manager` takes about 30 seconds; the client's retries absorb short 429 bursts. ## Examples diff --git a/examples/webhook_receiver.py b/examples/webhook_receiver.py index 99ac195..dc334d2 100644 --- a/examples/webhook_receiver.py +++ b/examples/webhook_receiver.py @@ -17,10 +17,15 @@ write succeeded, so a delivery whose write failed (answered 503) is processed when it is retried. Its default store is per process: with several workers pass Deduplicator(store=...) a shared store (has/add), or rely on the queue's upsert alone. +- Deliveries can arrive out of order (a failed v1 is retried after v2 was stored): the queue keeps each + call's event timestamp, and a delivery older than the stored one (is_older) is remembered and + acknowledged without overwriting newer data. Ordering relies on the event's timestamp; when two + deliveries carry the same timestamp, the later arrival wins. - A worker reads each queued call with the person's login (the event is only a notification) and then upserts your copy on call.id. A 404 means drop it. -Pass --self-test to post the sample event twice and then a changed copy, without reading the API, and exit. +Pass --self-test to post the sample event twice, a newer copy, then the older one again, without reading +the API, and exit. """ import hmac import json @@ -39,6 +44,7 @@ MAX_EVENT_BYTES, AfterCallEvent, Deduplicator, + is_older, NotFoundError, PayloadTooLargeError, WebhookPayloadError, @@ -61,14 +67,20 @@ class CallQueue: def __init__(self, path: str): self._db = sqlite3.connect(path, check_same_thread=False, isolation_level=None) - self._db.execute("CREATE TABLE IF NOT EXISTS calls (call_id TEXT PRIMARY KEY, received REAL, done INTEGER DEFAULT 0)") + self._db.execute("CREATE TABLE IF NOT EXISTS calls (call_id TEXT PRIMARY KEY, received REAL, " + "event_time TEXT, done INTEGER DEFAULT 0)") self._lock = threading.Lock() - def put(self, call_id: str) -> None: - with self._lock: # a repeat after processing re-opens the entry: it may carry newer data - self._db.execute("INSERT INTO calls (call_id, received) VALUES (?, ?) " - "ON CONFLICT(call_id) DO UPDATE SET done = 0, received = excluded.received", - (call_id, time.time())) + def put(self, call_id: str, event_time: str) -> None: + with self._lock: # a newer delivery re-opens the entry: it may carry newer data + self._db.execute("INSERT INTO calls (call_id, received, event_time) VALUES (?, ?, ?) " + "ON CONFLICT(call_id) DO UPDATE SET done = 0, received = excluded.received, " + "event_time = excluded.event_time", (call_id, time.time(), event_time)) + + def stored_time(self, call_id: str): + with self._lock: + row = self._db.execute("SELECT event_time FROM calls WHERE call_id = ?", (call_id,)).fetchone() + return row[0] if row else None def next(self): with self._lock: @@ -110,11 +122,17 @@ def do_POST(self): except WebhookPayloadError: return self._answer(400) if isinstance(event, AfterCallEvent) and not event.is_test: + key = dedup.upsert_key(event) if dedup.seen(event): # an exact re-delivery we already stored - print(f"call {dedup.upsert_key(event)}: exact re-delivery, skipped") + print(f"call {key}: exact re-delivery, skipped") return self._answer(204) try: - calls.put(dedup.upsert_key(event)) # upsert by call id: the durable write + stored = calls.stored_time(key) + if stored is not None and is_older(event, stored): + print(f"call {key}: older than the stored delivery, not stored") + dedup.remember(event) + return self._answer(204) + calls.put(key, event.timestamp.isoformat() if event.timestamp else "") # the durable write except sqlite3.Error: return self._answer(503) # not remembered: the sender's retry is processed dedup.remember(event) # only after the write succeeded @@ -157,8 +175,12 @@ def worker(fetch: bool) -> None: sample["is_test"] = False newer = json.loads(json.dumps(sample)) newer["summary"]["text"] = "The refund was approved." - # the same delivery twice (the second is skipped), then newer data for the same call (stored again) - for body in (sample, sample, newer): + newer["timestamp"] = "2026-11-02T16:50:00Z" + older = json.loads(json.dumps(sample)) + older["summary"]["text"] = "An earlier summary." + older["timestamp"] = "2026-11-02T16:40:00Z" + # the same delivery twice (the second is skipped), newer data (stored), then an older delivery (not stored) + for body in (sample, sample, newer, older): req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", headers={"Content-Type": "application/json"}) print("delivery answered", urllib.request.urlopen(req).status) diff --git a/src/intelligence_cloud/__init__.py b/src/intelligence_cloud/__init__.py index f88f9ff..eaa17f8 100644 --- a/src/intelligence_cloud/__init__.py +++ b/src/intelligence_cloud/__init__.py @@ -7,6 +7,14 @@ from ._base import Page, unwrap from ._version import __version__ from .accounts import ( + AlertActivation, + LicenseReport, + LineDiff, + LineSyncReport, + NoManagerTeam, + OffboardSummary, + RemovalSummary, + TeamLines, AlertSetting, AlertSettings, ConnectorSpec, @@ -68,6 +76,7 @@ parse_after_call_event, parse_first_alert_event, upsert_key, + is_older, ) __all__ = [ @@ -78,9 +87,11 @@ "FrontlineRequiredError", "ConnectorError", "ConnectorTimeoutError", "ExtensionMappingError", "AccountError", "WrongLoginError", "WebhookPayloadError", "PayloadTooLargeError", "WebhookTestResult", "RecordingLink", "AfterCallEvent", "AfterCallCall", "AfterCallSummary", "AfterCallLocation", "UnknownEvent", - "parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event", "upsert_key", + "parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event", "upsert_key", "is_older", "Deduplicator", "DedupStore", "MemoryDedupStore", "CustomerSpec", "TeamSpec", "ConnectorSpec", "PersonSpec", "AlertSetting", "AlertSettings", "Customer", "Team", "TeamGroups", "TeamRules", "Member", + "AlertActivation", "NoManagerTeam", "LineSyncReport", "TeamLines", "LineDiff", "LicenseReport", + "RemovalSummary", "OffboardSummary", "CallBrief", "AlertBrief", "TaskBrief", "TeamRef", "TeamView", "TopicsView", "Reference", "Me", "mask_number", ] diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index 4901b29..de46c50 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -20,6 +20,8 @@ """ from __future__ import annotations +import dataclasses +import re from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union @@ -261,7 +263,9 @@ class Member: user_id: str email: str license: str # "base_user", "base_manager", "integration" or "other" - teams: List[str] = field(default_factory=list) # location ids (Management not listed) + # Location ids of EVERY team the person is on after the call (Management not listed), not only the + # teams named in it: helpers that return a Member read the person's teams back. + teams: List[str] = field(default_factory=list) lines: List[str] = field(default_factory=list) created: bool = False invited: bool = False # an invitation was emailed by this call @@ -283,8 +287,16 @@ def _uniq(values: Iterable[str]) -> List[str]: return out +LINE_RE = re.compile(r"\+?[0-9*#]{1,32}") + + def _line(value: Any, name: str = "line") -> str: - return _str(value, name) + """A line (extension or number): the whole value matches ``\\+?[0-9*#]{1,32}``, nothing trimmed, + the same in every SDK. Anything else (a space, a dash, letters) is refused before any request.""" + if not isinstance(value, str) or not LINE_RE.fullmatch(value): + raise InvalidRequestError(f"{name}: an extension or number of 1 to 32 digits, * or # " + "(an optional leading +), with no spaces or other characters") + return value def _str(value: Any, name: str, required: bool = True) -> Optional[str]: @@ -410,10 +422,11 @@ def active(self) -> bool: class _Run: - def __init__(self, client: Any, result: Any): + def __init__(self, client: Any, result: Any, convert: Any = None): self.client = client self.start = client._writes self.result = result + self.convert = convert # turns a partial dict result into the helper's result type self.step = "start" @@ -439,14 +452,15 @@ def _require_admin(self) -> Dict[str, Any]: raise WrongLoginError(self._me.get("role"), "admin") return self._me - def _run(self, result: Any) -> _Run: - return _Run(self._c, result) + def _run(self, result: Any, convert: Any = None) -> _Run: + return _Run(self._c, result, convert) def _stop(self, run: _Run, exc: BaseException) -> None: """Re-raise ``exc`` as it is when nothing was written yet; otherwise as AccountError.""" if isinstance(exc, AccountError) or self._c._writes == run.start: raise exc - raise AccountError(run.step, run.result, exc) from exc + result = run.convert(run.result) if run.convert else run.result + raise AccountError(run.step, result, exc) from exc def _resolve(self, customer: CustomerRef) -> Customer: """The customer for this helper call. Starts a new call: teams read from here on count as live.""" @@ -893,11 +907,30 @@ def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Cust have = found.get("config") or {} unchanged = found.get("name") == name and all( have.get(k) == v for k, v in config.items() if k in have and not _is_secret(k)) - if found.get("status") in (*RUNNING, "connecting") and unchanged: + if found.get("status") in RUNNING and unchanged: if result is not None: result.existing.append(label) self._set_conn(team, found) return None + if found.get("status") == "connecting" and unchanged: + # Found still settling (an earlier run stopped at "connectors"): check it again, and restart + # it once if it does not settle in time. + if result is not None: + result.existing.append(label) + try: + conn = conns.wait_for_status(team.location_id, found["id"], (*RUNNING, "error"), cs.timeout, + raise_on_error=False) + except ConnectorTimeoutError: + conn = {"status": "connecting"} + try: + if conn.get("status") not in RUNNING: + conns.deactivate_connector(team.location_id, found["id"], timeout=cs.timeout) + conn = unwrap(conns.reactivate_connector(team.location_id, found["id"], timeout=cs.timeout)) + except (ConnectorError, ConnectorTimeoutError) as exc: + self._set_conn(team, exc.connector) + return exc + self._set_conn(team, conn) + return None try: if found is not None: # In error, stopped or changed: apply the settings (and key) given now, then restart. @@ -996,10 +1029,10 @@ def set_alerts(self, customer: CustomerRef, alerts: AlertSettings, *, team: Opti _check_customer_ref(customer) _check_team_ref(team, required=False) if alerts is None: - raise InvalidRequestError("alerts is required") + raise InvalidRequestError("alerts: required") alerts = _check_alerts(alerts) if all(getattr(alerts, k) is None for k in RULES): - raise InvalidRequestError("alerts sets nothing: give at least one AlertSetting") + raise InvalidRequestError("alerts: sets nothing, give at least one AlertSetting") if isinstance(customer, Customer) and team is not None: self._team(customer, team) self._require_admin() @@ -1064,7 +1097,7 @@ def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, _raise_connector_failure(failures, targets) return targets - def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = None) -> Dict[str, Any]: + def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = None) -> "AlertActivation": """Switch the rules on for every team. A team does not need a manager: its alerts then show in the app only, and the team is listed under ``no_manager`` with the alert groups that have none. @@ -1078,7 +1111,7 @@ def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = No out: Dict[str, Any] = {"switched_on": [], "no_manager": []} people = self._index(cust) managers = {p.id for p in people.values() if p.license == "base_manager"} - run = self._run(out) + run = self._run(out, _to_activation) targets = [self._live(t) for t in self._teams(cust, team)] try: for t in targets: @@ -1104,7 +1137,7 @@ def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = No out["switched_on"].append(rid) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) - return out + return _to_activation(out) # ------------------------------------------------------------------ people: reading @@ -1132,8 +1165,14 @@ def _index(self, cust: Customer, include_inactive: bool = False) -> Dict[str, _P if p.active: p.mappings = unwrap(c.users.get_user_number_mappings(cust.company_id, p.id)) or [] self._classify(cust, p) + self._local.last_index = people # what the latest read in this call saw (for Member.teams) return people + def _current_teams(self, uid: str, fallback: List[str]) -> List[str]: + """All of the person's teams as the latest read in this call saw them.""" + people = getattr(self._local, "last_index", None) or {} + return list(people[uid].teams) if uid in people else fallback + @staticmethod def _classify(cust: Customer, p: _Person) -> None: team_ids = [t.location_id for t in cust.teams] @@ -1277,7 +1316,7 @@ def _members(self, cust: Customer, license: Optional[str], team: Optional[TeamRe out.append(self._member(p)) return out - def license_report(self, customer: CustomerRef) -> Dict[str, Any]: + def license_report(self, customer: CustomerRef) -> "LicenseReport": """People by license and the number of teams (Management not counted).""" _check_customer_ref(customer) self._require_admin() @@ -1286,9 +1325,9 @@ def license_report(self, customer: CustomerRef) -> Dict[str, Any]: by: Dict[str, List[Member]] = {k: [] for k in LICENSES} for m in members: by[m.license].append(m) - return {"base_user": len(by["base_user"]), "base_manager": len(by["base_manager"]), - "integration": len(by["integration"]), "other": len(by["other"]), - "teams": len(cust.teams), "members": by} + return LicenseReport(base_user=len(by["base_user"]), base_manager=len(by["base_manager"]), + integration=len(by["integration"]), other=len(by["other"]), + teams=len(cust.teams), members=by) # ------------------------------------------------------------------ people: low-level steps @@ -1508,6 +1547,7 @@ def add_base_user(self, customer: CustomerRef, person: PersonSpec, *, team: Team self._attach_line(cust, t, line, self._index(cust), exclude=[uid]) run.step = "invitation" result.invited = self._invite(cust, uid, invite) + result.teams = self._current_teams(uid, result.teams) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) return result @@ -1553,6 +1593,7 @@ def add_base_manager(self, customer: CustomerRef, person: PersonSpec, *, teams: uid, created, detail = self._ensure_user(cust, person, [t.location_id for t in ts] + [cust.management.location_id]) result.user_id, result.created = uid, created result.lines = self._manager_setup(cust, uid, ts, own, company_reports, created, detail.get("status"), run) + result.teams = self._current_teams(uid, result.teams) # every team they run, not only these run.step = "invitation" result.invited = self._invite(cust, uid, invite) except (IntelligenceCloudError, httpx.HTTPError) as exc: @@ -1567,7 +1608,7 @@ def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, inv _check_customer_ref(customer) _check_person(person) if person.auth_method != "password": - raise InvalidRequestError("An integration user signs in with a password: set auth_method='password'") + raise InvalidRequestError("person.auth_method: an integration user signs in with a password, set 'password'") _check_invite(invite) self._require_admin() cust = self._resolve(customer) @@ -1856,7 +1897,7 @@ def change_line(self, customer: CustomerRef, user_id: str, old: str, new: str) - _check_user_id(user_id) old, new = _line(old, "old"), _line(new, "new") if old == new: - raise InvalidRequestError("old and new are the same line") + raise InvalidRequestError("old, new: they are the same line") self._require_admin() cust = self._resolve(customer) p, people = self._person(cust, user_id) @@ -1912,7 +1953,7 @@ def swap(have: List[str]) -> List[str]: self._stop(run, exc) return result - def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = False) -> Dict[str, Any]: + def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = False) -> "RemovalSummary": """Take the person out of every group, release a Base User's line (unless ``keep_lines``, and only when no other Base User of the team holds it), clear their lines, then deactivate them. Removing a Base Manager or an integration user never takes a line off anyone else. ``notes`` names any @@ -1928,7 +1969,7 @@ def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = self._classify(cust, p) out: Dict[str, Any] = {"user_id": user_id, "license": p.license, "released_lines": [], "deactivated": False, "notes": self._emptied_groups(cust, people, p.id, p.teams) if p.active else []} - run = self._run(out) + run = self._run(out, _to_removal) try: run.step = "groups" for t in self._locations(cust): @@ -1953,7 +1994,7 @@ def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = pass # already deactivated except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) - return out + return _to_removal(out) def send_invitations(self, customer: CustomerRef, *, user_ids: Optional[Sequence[str]] = None) -> List[str]: """Email invitations to people who have not signed in. Without ``user_ids``: everyone who was @@ -1988,7 +2029,7 @@ def send_invitations(self, customer: CustomerRef, *, user_ids: Optional[Sequence # ------------------------------------------------------------------ lines - def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[str, Any]: + def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> "LineSyncReport": """Make the line lists match the people: every Base User's line is on their team's First Alert and Insights Hub lists and on its holders; Base Managers and integration users hold exactly their teams' lines on each team's connector; nothing else is listed. ``dry_run=True`` returns the @@ -2028,8 +2069,8 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st diff["teams"][t.location_id] = d plans.append((t, lines, d)) if dry_run: - return diff - run = self._run(diff) + return _to_sync(diff) + run = self._run(diff, _to_sync) try: for t, lines, d in plans: run.step = f"sync:{t.name}" @@ -2043,11 +2084,11 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) diff["applied"] = True - return diff + return _to_sync(diff) # ------------------------------------------------------------------ offboarding - def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = True) -> Dict[str, Any]: + def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = True) -> "OffboardSummary": """Stop everything for a customer who leaves, at every team and at Management, in this order: pause each After Call webhook (its address is kept; it can't be deleted), clear each First Alert webhook, stop each connector (ends the phone-system subscription), deactivate the integration @@ -2060,7 +2101,7 @@ def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = out: Dict[str, Any] = {"webhooks_paused": [], "first_alert_webhooks_cleared": [], "connectors_deactivated": [], "integration_users_deactivated": [], "company_deactivated": False} - run = self._run(out) + run = self._run(out, _to_offboard) try: locs = self._locations(cust) run.step = "webhooks" @@ -2102,7 +2143,140 @@ def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = pass # already inactive except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) - return out + return _to_offboard(out) + + +# ---------------------------------------------------------------------- result types + + +def _plain(value: Any) -> Any: + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return {f.name: _plain(getattr(value, f.name)) for f in dataclasses.fields(value)} + if isinstance(value, Mapping): + return {k: _plain(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_plain(v) for v in value] + return value + + +class _ReadAsDict: + """Read access by key, as the plain dicts of 0.2.x: ``result["switched_on"]``, ``"key" in result``, + ``result.get(...)``. A result also equals a dict with the same content.""" + + def __getitem__(self, key: str) -> Any: + if key in self.keys(): + return getattr(self, key) + raise KeyError(key) + + def __contains__(self, key: object) -> bool: + return key in self.keys() + + def get(self, key: str, default: Any = None) -> Any: + return getattr(self, key) if key in self.keys() else default + + def keys(self) -> List[str]: + return [f.name for f in dataclasses.fields(self)] # type: ignore[arg-type] + + def to_dict(self) -> Dict[str, Any]: + """A plain-dict copy, nested results included.""" + return _plain(self) + + def __eq__(self, other: object) -> bool: + if isinstance(other, Mapping) or type(other) is type(self): + return _plain(self) == _plain(other) + return NotImplemented + + __hash__ = None # type: ignore[assignment] + + +@dataclass(frozen=True, eq=False) +class NoManagerTeam(_ReadAsDict): + location_id: str + team: str + missing: List[str] + + +@dataclass(frozen=True, eq=False) +class AlertActivation(_ReadAsDict): + """What ``activate_alerts`` did: the rule ids it switched on, and the teams whose alert groups have no + Base Manager (their alerts show in the app only).""" + + switched_on: List[str] = field(default_factory=list) + no_manager: List[NoManagerTeam] = field(default_factory=list) + + +@dataclass(frozen=True, eq=False) +class LineDiff(_ReadAsDict): + add: List[str] = field(default_factory=list) + remove: List[str] = field(default_factory=list) + + +@dataclass(frozen=True, eq=False) +class TeamLines(_ReadAsDict): + team: str + lines: List[str] + other: List[str] # people who own a line here but read back as "other" + first_alert: LineDiff + insights_hub: LineDiff + holders: Dict[str, LineDiff] # user id -> changes to their lines on this team's connector + + +@dataclass(frozen=True, eq=False) +class LineSyncReport(_ReadAsDict): + """What ``sync_lines`` found (and changed unless ``applied`` is False): per team, by location id.""" + + teams: Dict[str, TeamLines] = field(default_factory=dict) + applied: bool = False + + +@dataclass(frozen=True, eq=False) +class LicenseReport(_ReadAsDict): + base_user: int + base_manager: int + integration: int + other: int + teams: int # Management not counted + members: Dict[str, List[Member]] # by license + + +@dataclass(frozen=True, eq=False) +class RemovalSummary(_ReadAsDict): + user_id: str + license: str + released_lines: List[str] = field(default_factory=list) + deactivated: bool = False + notes: List[str] = field(default_factory=list) + + +@dataclass(frozen=True, eq=False) +class OffboardSummary(_ReadAsDict): + webhooks_paused: List[str] = field(default_factory=list) + first_alert_webhooks_cleared: List[str] = field(default_factory=list) + connectors_deactivated: List[str] = field(default_factory=list) + integration_users_deactivated: List[str] = field(default_factory=list) + company_deactivated: bool = False + + +def _to_activation(d: Mapping[str, Any]) -> AlertActivation: + return AlertActivation(switched_on=list(d["switched_on"]), + no_manager=[NoManagerTeam(**x) for x in d["no_manager"]]) + + +def _to_sync(d: Mapping[str, Any]) -> LineSyncReport: + teams = {} + for lid, t in d["teams"].items(): + teams[lid] = TeamLines(team=t["team"], lines=list(t["lines"]), other=list(t["other"]), + first_alert=LineDiff(**t["first_alert"]), insights_hub=LineDiff(**t["insights_hub"]), + holders={u: LineDiff(**h) for u, h in t["holders"].items()}) + return LineSyncReport(teams=teams, applied=bool(d["applied"])) + + +def _to_removal(d: Mapping[str, Any]) -> RemovalSummary: + return RemovalSummary(**d) + + +def _to_offboard(d: Mapping[str, Any]) -> OffboardSummary: + return OffboardSummary(**d) def _raise_connector_failure(failures: Sequence[BaseException], result: Any) -> None: @@ -2126,7 +2300,7 @@ def norm(ms: Sequence[Mapping[str, Any]]) -> Dict[str, List[str]]: def _check_connector_local(cs: Optional[ConnectorSpec], required: bool = False) -> None: if cs is None: if required: - raise InvalidRequestError("A connector is required: pass a ConnectorSpec") + raise InvalidRequestError("connector: required, a ConnectorSpec") return if not isinstance(cs, ConnectorSpec): raise InvalidRequestError("connector must be a ConnectorSpec") diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py index d77d1bb..562fe0e 100644 --- a/src/intelligence_cloud/conversations.py +++ b/src/intelligence_cloud/conversations.py @@ -294,9 +294,9 @@ def _window(self, day: Optional[Union[date, datetime]], since: Optional[When], u else: start = _local_midnight(end.astimezone().date()) if end <= start: - raise InvalidRequestError("until must be after since") + raise InvalidRequestError("until: must be after since") if end - start > timedelta(days=MAX_WINDOW_DAYS): - raise InvalidRequestError(f"The window is at most {MAX_WINDOW_DAYS} days") + raise InvalidRequestError(f"since/until: the window is at most {MAX_WINDOW_DAYS} days") return start, end def _team_id(self, team: Optional[Union[str, TeamRef]]) -> Optional[str]: @@ -376,14 +376,15 @@ def me(self) -> Me: company_id=me.get("company_id"), teams=self.teams()) def teams(self) -> List[TeamRef]: - """The teams (locations) this person can see. Management is listed with ``kind="management"``.""" + """The teams (locations) this person can see: those with ``kind == "team"`` first, in name order, then + Management (``kind == "management"``) last. Pick "my team" by ``kind == "team"``.""" self._require_user() out = [] for loc in self._c.account.iter_visible_locations(): name = loc.get("location_name") or "" out.append(TeamRef(location_id=loc.get("id") or "", name=name, kind="management" if name.endswith(" - Management") else "team")) - return out + return sorted(out, key=lambda t: (t.kind != "team", t.name)) # ------------------------------------------------------------------ calls @@ -394,7 +395,7 @@ def calls(self, *, day: Optional[Union[date, datetime]] = None, since: Optional[ most 200. ``number`` and ``search`` share the API's one search field: pass one or the other.""" limit = self._limit(limit, MAX_LIMIT) start, end = self._window(day, since, until) - term = _search_term(number, search) + term = _search_term(number, search, ("number", "search")) _check_team(team) self._require_user() lid = self._team_id(team) @@ -445,7 +446,7 @@ def recording_link(self, call_id: str) -> Optional[RecordingLink]: def caller_history(self, number: str, *, limit: int = 10) -> List[CallBrief]: """Recent briefs for one caller (the last 31 days), for use before a callback. ``limit`` at most 50.""" limit = self._limit(limit, MAX_HISTORY) - term = _search_term(check_text(number, "number", min_len=2), None) + term = _search_term(check_text(number, "number", min_len=2), None, ("number", "search")) start, end = self._window(None, None, None, default_days=MAX_WINDOW_DAYS) self._require_user() rows = self._pages(lambda n, cur: self._c.calls.list_calls( @@ -556,9 +557,9 @@ def reference(self, call_or_alert: Union[CallBrief, AlertBrief, FirstAlertEvent, elif isinstance(call_or_alert, str) and call_or_alert: kind, item = "call", call_or_alert else: - raise InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") + raise InvalidRequestError("call_or_alert: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") if not ID_RE.fullmatch(item): - raise InvalidRequestError("reference: an id of letters, digits, '-' and '_' (at most 128)") + raise InvalidRequestError("call_or_alert: an id of letters, digits, '-' and '_' (at most 128)") return Reference(kind=kind, id=item, link=self._link(kind, item)) @staticmethod diff --git a/src/intelligence_cloud/intelligence.py b/src/intelligence_cloud/intelligence.py index c0777ba..db5a57a 100644 --- a/src/intelligence_cloud/intelligence.py +++ b/src/intelligence_cloud/intelligence.py @@ -34,19 +34,21 @@ class WebhookTestResult: http_status: Optional[int] -def _search_term(phone: Optional[str], text: Optional[str]) -> Optional[str]: +def _search_term(phone: Optional[str], text: Optional[str], names: tuple = ("phone", "text")) -> Optional[str]: + """One search term from two arguments (``names`` as the caller wrote them).""" if phone is not None and text is not None: - raise InvalidRequestError("Pass phone or text, not both: the API has one search field") + raise InvalidRequestError(f"Pass {names[0]} or {names[1]}, not both: the API has one search field") term = phone if phone is not None else text if term is None: return None + name = names[0] if phone is not None else names[1] if not isinstance(term, str): - raise InvalidRequestError("search terms must be strings") + raise InvalidRequestError(f"{name}: a string") term = term.strip() if len(term) < 2: - raise InvalidRequestError("search terms need at least 2 characters (shorter ones are ignored by the API)") + raise InvalidRequestError(f"{name}: at least 2 characters (shorter ones are ignored by the API)") if len(term) > _spec.MAX_TEXT: - raise InvalidRequestError(f"search terms: at most {_spec.MAX_TEXT} characters") + raise InvalidRequestError(f"{name}: at most {_spec.MAX_TEXT} characters") return term @@ -210,7 +212,7 @@ def list_tasks(self, status: Optional[str] = None, call_id: Optional[str] = None limit: Optional[int] = None, cursor: Optional[str] = None) -> Page: """One page of follow-up tasks. ``date_from``/``date_to`` filter on creation time; no default window.""" f = self._task_filters(dict(status=status, call_id=call_id, task_id=task_id, due_on=due_on, - date_from=date_from, date_to=date_to, search=_search_term(None, search), + date_from=date_from, date_to=date_to, search=_search_term(None, search, ("search", "search")), location_ids=location_ids, today_start=today_start, company_id=company_id)) return self._c.tasks.list_tasks(limit=limit, cursor=cursor, **f) @@ -221,7 +223,7 @@ def iter_tasks(self, status: Optional[str] = None, call_id: Optional[str] = None today_start: Optional[When] = None, company_id: Optional[str] = None) -> Iterator[Dict[str, Any]]: f = self._task_filters(dict(status=status, call_id=call_id, task_id=task_id, due_on=due_on, - date_from=date_from, date_to=date_to, search=_search_term(None, search), + date_from=date_from, date_to=date_to, search=_search_term(None, search, ("search", "search")), location_ids=location_ids, today_start=today_start, company_id=company_id)) return self._c.tasks.iter_tasks(**f) @@ -246,7 +248,7 @@ def list_topic_calls(self, slug: str, date_from: Optional[When] = None, date_to: _spec.check_path_value(slug, 'slug') self.require_frontline() return self._c.insights.list_topic_calls(slug, date_from=date_from, date_to=date_to, sentiment=sentiment, - outcome=outcome, search=_search_term(None, search), + outcome=outcome, search=_search_term(None, search, ("search", "search")), location_id=location_ids, company_id=company_id, limit=limit, cursor=cursor) @@ -257,7 +259,7 @@ def iter_topic_calls(self, slug: str, date_from: Optional[When] = None, date_to: _spec.check_path_value(slug, 'slug') self.require_frontline() return self._c.insights.iter_topic_calls(slug, date_from=date_from, date_to=date_to, sentiment=sentiment, - outcome=outcome, search=_search_term(None, search), + outcome=outcome, search=_search_term(None, search, ("search", "search")), location_id=location_ids, company_id=company_id) # ------------------------------------------------------------------ webhook configuration (admin) diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index 34c70b9..503a217 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -520,6 +520,32 @@ def upsert_key(event: Union[AfterCallEvent, FirstAlertEvent, bytes, str, Mapping raise WebhookPayloadError("not an After Call or First Alert event") +def _event_time(value: Any) -> Optional[datetime]: + """The event's own ``timestamp`` (as the schema defines it), from an event, a parsed body, raw bytes, + a datetime or an RFC 3339 string; None when there is none.""" + if value is None: + return None + if isinstance(value, datetime): + return value if value.tzinfo else None + if isinstance(value, (AfterCallEvent, FirstAlertEvent)): + return value.timestamp + if isinstance(value, str) and not value.lstrip("\ufeff \t\r\n").startswith("{"): + return _ts(value, "timestamp") if value.strip() else None + try: + ev = _as_event(value) + except WebhookPayloadError: + return None + return ev.timestamp if isinstance(ev, (AfterCallEvent, FirstAlertEvent)) else None + + +def is_older(event: Any, stored: Any) -> bool: + """True when ``event`` is older than what you stored for the same key (``stored``: the stored event, its + body, or its timestamp). Compares the events' own ``timestamp`` fields; False when either has none, + and False when they are equal (the later arrival wins).""" + new, old = _event_time(event), _event_time(stored) + return new is not None and old is not None and new < old + + def delivery_key(event: Any) -> str: """The identity of one exact delivery: event type, location, call (or alert) id, and a SHA-256 of the canonical JSON body. A re-delivery of the same content has the same key; a later delivery with diff --git a/src/intelligence_cloud/testing/__init__.py b/src/intelligence_cloud/testing/__init__.py index ca6bafe..301b3f3 100644 --- a/src/intelligence_cloud/testing/__init__.py +++ b/src/intelligence_cloud/testing/__init__.py @@ -16,6 +16,6 @@ fake keeps its state in memory, refuses requests the published spec does not define, and has knobs for the failures your code must handle. It is supported: its names follow the SDK's version. """ -from ._fake import CONNECTOR_OUTCOMES, FakeAPI, FakeRequest, SeededCustomer, new_id +from ._fake import CONNECTOR_OUTCOMES, FakeAPI, FakeRequest, SeededCustomer, SeededPerson, new_id -__all__ = ["FakeAPI", "FakeRequest", "SeededCustomer", "CONNECTOR_OUTCOMES", "new_id"] +__all__ = ["FakeAPI", "FakeRequest", "SeededCustomer", "SeededPerson", "CONNECTOR_OUTCOMES", "new_id"] diff --git a/src/intelligence_cloud/testing/_fake.py b/src/intelligence_cloud/testing/_fake.py index 4211c6b..08ace7c 100644 --- a/src/intelligence_cloud/testing/_fake.py +++ b/src/intelligence_cloud/testing/_fake.py @@ -43,13 +43,26 @@ def _error(status: int, code: str, message: str) -> httpx.Response: @dataclass class FakeRequest: - """One request the fake received (sign-in and token renewal are not logged).""" + """One request the fake received, whatever answered it (sign-in and token renewal are in + ``auth_log`` instead). Secret-named body values and URL paths are masked.""" method: str path: str # without the /api/v1 prefix query: Dict[str, str] body: Any - operation: Optional[str] # the operationId it matched in the published spec + operation: Optional[str] # the operationId it matched in the published spec, or None + answer: Any = None # the HTTP status it got, or "network:connect" | "network:read_timeout" | ... + + +@dataclass(frozen=True) +class SeededPerson: + """One person ``seed_customer`` created: sign in as them with ``client(role="user", as_user=...)``.""" + + user_id: str + email: str + license: str # "base_user" or "base_manager" + teams: List[str] # location ids of their teams (Management not listed) + lines: List[str] @dataclass @@ -57,8 +70,9 @@ class SeededCustomer: """What ``FakeAPI.seed_customer`` built: the customer and the people's ids by email.""" customer: Any # intelligence_cloud.Customer - base_users: Dict[str, str] = field(default_factory=dict) - managers: Dict[str, str] = field(default_factory=dict) + base_users: Dict[str, str] = field(default_factory=dict) # email -> user id + managers: Dict[str, str] = field(default_factory=dict) # email -> user id + people: List[SeededPerson] = field(default_factory=list) @property def company_id(self) -> str: @@ -103,8 +117,8 @@ class FakeAPI: and sorts; its data is simpler than the platform's. Run once against a test company before release. **Supported surface** (everything else is internal and may change): the constructor, :meth:`client`, - :meth:`seed_customer`, :meth:`seed_calls`, ``connector_outcome``, :meth:`fail_next`, - :meth:`fail_write`, :meth:`network_down`, :meth:`rate_limit`, :meth:`expire_access_tokens`, the + :meth:`seed_customer`, :meth:`seed_calls`, ``connector_outcome``, :meth:`settle_connector`, + :meth:`fail_next`, :meth:`fail_write`, :meth:`network_down`, :meth:`rate_limit`, :meth:`expire_access_tokens`, the request log (:attr:`requests`, :attr:`writes`, :meth:`writes_since`, :meth:`count`, :meth:`reset_log`, :attr:`auth_log`) and the readers :meth:`products`, :meth:`numbers`, :meth:`fa_numbers`, :meth:`ih_numbers`, :meth:`group_members`. @@ -150,6 +164,7 @@ def __init__(self, *, connector_outcome: str = "active", role: str = "admin", st self._logins: Dict[str, str] = {} # email -> role self._token_n = 0 self._request_role = self._role + self._request_email: Optional[str] = None self._fail: Optional[Tuple[int, int]] = None # (writes left before the failing one, status) self._next_failures: List[Dict[str, Any]] = [] self._down = False @@ -160,16 +175,27 @@ def __init__(self, *, connector_outcome: str = "active", role: str = "admin", st # ------------------------------------------------------------------ public surface - def client(self, role: Optional[str] = None, **client_options: Any) -> Client: + def client(self, role: Optional[str] = None, *, as_user: Optional[str] = None, **client_options: Any) -> Client: """A real Client wired to this fake. ``role``: "admin" (an administrator login) or "user" (a - person's own login); default the role given to FakeAPI. Other options go to Client, for example - ``mask_numbers=False``. Waits (retries, connector checks) do not sleep unless you pass ``sleep``.""" + person's own login); default the role given to FakeAPI. ``as_user`` (with role "user"): the user id + or email of a person ``seed_customer`` created; the client signs in as them, so the calls, alerts, + tasks and Insights Hub it sees follow their license and teams. Clients for the same person share + that login's sessions. Other options go to Client, for example ``mask_numbers=False``. Waits + (retries, connector checks) do not sleep unless you pass ``sleep``.""" if "transport" in client_options: raise InvalidRequestError("FakeAPI.client() wires the fake as the transport: do not pass transport=") if role is not None and role not in ROLES and role not in ROLES.values(): raise InvalidRequestError('role: "admin" or "user"') r = ROLES.get(role, role) if role else self._role - email = f"{'admin' if r == 'reseller_admin' else 'user'}.{len(self._logins) + 1}@example.com" + if as_user is not None: + if r != "frontline_user": + raise InvalidRequestError('as_user needs role="user"') + user = next((u for u in self._users.values() if as_user in (u["id"], u["email"])), None) + if user is None: + raise InvalidRequestError("as_user: the user id or email of a person seed_customer created") + email = user["email"] + else: + email = f"{'admin' if r == 'reseller_admin' else 'user'}.{len(self._logins) + 1}@example.com" self._logins[email] = r client_options.setdefault("sleep", lambda s: None) return Client(email, "fake-password", transport=httpx.MockTransport(self), **client_options) @@ -185,8 +211,9 @@ def writes_since(self, start: int = 0) -> List[Tuple[str, str]]: @property def auth_log(self) -> List[Tuple[str, str]]: - """Sign-in and token renewal, oldest first: ("login" | "refresh" | "refresh_reused", email). - "refresh_reused" means a used refresh token was sent again and every session of that login ended.""" + """Every sign-in and renewal request the fake received, whatever answered it, oldest first: + ("login" | "refresh" | "refresh_reused", email). "refresh_reused" is a renewal that sent a used + refresh token: every session of that login ended.""" return list(self._auth_log) def count(self, method: str, pattern: str) -> int: @@ -208,8 +235,8 @@ def fail_write(self, nth: int = 1, status: int = 400) -> None: self._fail = (nth - 1, status) def fail_next(self, status: Optional[int] = None, *, network: Optional[str] = None, - method: Optional[str] = None, path: Optional[str] = None, retry_after: Optional[float] = None, - after_processing: bool = False) -> None: + sign_in: Optional[str] = None, method: Optional[str] = None, path: Optional[str] = None, + retry_after: Optional[float] = None, after_processing: bool = False) -> None: """Make the next request that matches ``method`` and the path regex ``path`` (without /api/v1; sign-in is "/auth/login", renewal "/auth/refresh") fail once: with HTTP ``status``, or with a ``network`` failure: "connect" (never left), "read_timeout" or "write_timeout" (left, no answer), @@ -218,13 +245,20 @@ def fail_next(self, status: Optional[int] = None, *, network: Optional[str] = No By default the failure comes **before** the platform acts on the request: nothing changes and a renewal's refresh token is still unused. With ``after_processing=True`` the platform has acted first (a write is applied, a refresh token is rotated) and the answer is lost, as with a gateway - error after the server. "connect" is always before.""" - if (status is None) == (network is None): - raise ValueError("fail_next: give status or network") + error after the server. "connect" is always before. + + ``sign_in``: the next sign-in answers "mfa_required" (MfaRequiredError), "password_expired" + (PasswordExpiredError) or "invalid_credentials" (AuthError, 401).""" + if sum(x is not None for x in (status, network, sign_in)) != 1: + raise ValueError("fail_next: give one of status, network or sign_in") if network is not None and network not in NETWORK_FAILURES: raise ValueError(f"network: one of {NETWORK_FAILURES}") - self._next_failures.append({"status": status, "network": network, "method": method, - "path": re.compile("^" + path + "$") if path else None, + if sign_in is not None: + if sign_in not in SIGN_IN_OUTCOMES: + raise ValueError(f"sign_in: one of {SIGN_IN_OUTCOMES}") + method, path = "POST", "/auth/login" + self._next_failures.append({"status": status, "network": network, "sign_in": sign_in, "method": method, + "path": re.compile(path) if path else None, "retry_after": retry_after, "after": bool(after_processing)}) def network_down(self, down: bool = True) -> None: @@ -235,6 +269,21 @@ def rate_limit(self, count: int = 1, retry_after: float = 1) -> None: """The next ``count`` requests (sign-in included) answer 429 with ``Retry-After``.""" self._limited = (count, retry_after) + def settle_connector(self, connector_or_location: str, outcome: str = "active") -> int: + """Settle connectors that are waiting ("connecting"): the one with this id, or every waiting one at + this location. ``outcome``: "active", "connected" or "error". Returns how many were settled.""" + if outcome not in ("active", "connected", "error"): + raise ValueError('outcome: "active", "connected" or "error"') + n = 0 + for c in self._connectors.values(): + if connector_or_location in (c["id"], c["location_id"]) and c["status"] == "connecting": + c["status"] = outcome + c["_outcome"] = outcome + if outcome == "error": + c["state_reason"] = "invalid_permissions" + n += 1 + return n + def expire_access_tokens(self) -> None: """Every access token stops working, as when they expire: the next call renews its token.""" self._access.clear() @@ -305,9 +354,7 @@ def _use_refresh(self, token: Any) -> Optional[Tuple[str, str]]: self._used_refresh[token] = owner[1] return owner if token in self._used_refresh: - email = self._used_refresh[token] - self._auth_log.append(("refresh_reused", email)) - self._end_sessions(email) + self._end_sessions(self._used_refresh[token]) return None def _take_failure(self, method: str, path: str) -> Optional[Dict[str, Any]]: @@ -316,80 +363,105 @@ def _take_failure(self, method: str, path: str) -> Optional[Dict[str, Any]]: return self._next_failures.pop(i) return None - @staticmethod - def _failure_response(f: Dict[str, Any], request: httpx.Request) -> httpx.Response: - net = f["network"] - if net == "connect": - raise httpx.ConnectError("connection refused (FakeAPI.fail_next)", request=request) - if net == "read_timeout": - raise httpx.ReadTimeout("read timed out (FakeAPI.fail_next)", request=request) - if net == "write_timeout": - raise httpx.WriteTimeout("write timed out (FakeAPI.fail_next)", request=request) - if net == "undecodable": + def _done(self, rec: Optional[FakeRequest], resp: httpx.Response) -> httpx.Response: + if rec is not None: + rec.answer = resp.status_code + return resp + + def _net(self, rec: Optional[FakeRequest], kind: str, request: httpx.Request) -> httpx.Response: + if rec is not None: + rec.answer = f"network:{kind}" + if kind == "undecodable": return httpx.Response(200, headers={"Content-Encoding": "gzip", "Content-Type": "application/json"}, content=b"this is not gzip") + exc = {"connect": httpx.ConnectError, "read_timeout": httpx.ReadTimeout, + "write_timeout": httpx.WriteTimeout}[kind] + raise exc(f"{kind} (FakeAPI)", request=request) + + def _fail_response(self, rec: Optional[FakeRequest], f: Dict[str, Any], request: httpx.Request) -> httpx.Response: + if f["network"] is not None: + return self._net(rec, f["network"], request) + if f["sign_in"] == "mfa_required": + return self._done(rec, httpx.Response(200, json={"status": "mfa_required"})) + if f["sign_in"] == "password_expired": + body = self._issue(self._role, "expired@example.com") + return self._done(rec, httpx.Response(200, json=dict(body, password_expired=True))) + if f["sign_in"] == "invalid_credentials": + return self._done(rec, _error(401, "UNAUTHORIZED", "Invalid email or password")) headers = {"Retry-After": str(f["retry_after"])} if f["retry_after"] is not None else {} - return httpx.Response(f["status"], headers=headers, - json={"error": {"code": "FAKE_FAILURE", "message": "Failed on purpose by FakeAPI.fail_next", - "request_id": "req-fake"}}) + return self._done(rec, httpx.Response(f["status"], headers=headers, json={"error": { + "code": "FAKE_FAILURE", "message": "Failed on purpose by FakeAPI.fail_next", "request_id": "req-fake"}})) def __call__(self, request: httpx.Request) -> httpx.Response: - if self._down: - raise httpx.ConnectError("the fake network is down", request=request) - count, retry_after = self._limited - if count > 0: - self._limited = (count - 1, retry_after) - return httpx.Response(429, headers={"Retry-After": str(retry_after)}, - json={"error": {"code": "RATE_LIMITED", "message": "Too many requests"}}) full = request.url.path path = full[len("/api/v1"):] if full.startswith("/api/v1") else full - failure = self._take_failure(request.method, path) - if failure is not None and failure["network"] == "connect": - return self._failure_response(failure, request) # never left: nothing happens on the server try: body = json.loads(request.content) if request.content else None + bad_json = False except ValueError: - return _error(400, "VALIDATION_ERROR", "The body is not JSON") + body, bad_json = None, True op_id = self._operation(request.method, path) + auth = path in ("/auth/login", "/auth/refresh") + rec: Optional[FakeRequest] = None + if auth: + who = (body or {}).get("email") if path == "/auth/login" else None + if path == "/auth/refresh": + owner = self._refresh.get((body or {}).get("refresh_token")) + who = owner[1] if owner else self._used_refresh.get((body or {}).get("refresh_token")) + auth_entry = ["login" if path == "/auth/login" else "refresh", str(who)] + self._auth_log.append(tuple(auth_entry)) # type: ignore[arg-type] + elif path != "/auth/logout": + logged = _masked(body) + rec = FakeRequest(request.method, path, dict(request.url.params), logged, op_id) + self.requests.append(rec) + self._calls.append((request.method, full)) + self._bodies.append((request.method, full, logged)) + if self._down: + return self._net(rec, "connect", request) + count, retry_after = self._limited + if count > 0: + self._limited = (count - 1, retry_after) + return self._done(rec, httpx.Response(429, headers={"Retry-After": str(retry_after)}, + json={"error": {"code": "RATE_LIMITED", "message": "Too many requests"}})) + failure = self._take_failure(request.method, path) + if failure is not None and failure["network"] == "connect": + return self._net(rec, "connect", request) # never left: nothing happens on the server + if bad_json: + return self._done(rec, _error(400, "VALIDATION_ERROR", "The body is not JSON")) if self._strict: refused = self._check_strict(op_id, request, path, body) if refused is not None: - return refused + return self._done(rec, refused) elif op_id is None: - return _error(501, "NOT_IMPLEMENTED", f"{request.method} {path} is not served by this fake") - before = failure is not None and not failure["after"] - if before: - return self._failure_response(failure, request) # nothing happens on the server + return self._done(rec, _error(501, "NOT_IMPLEMENTED", f"{request.method} {path} is not served by this fake")) + if failure is not None and not failure["after"]: + return self._fail_response(rec, failure, request) # nothing happens on the server if path == "/auth/login": - email = (body or {}).get("email") - role = self._logins.get(email, self._role) - self._auth_log.append(("login", str(email))) - return httpx.Response(200, json=self._issue(role, str(email))) + email = str((body or {}).get("email")) + return httpx.Response(200, json=self._issue(self._logins.get(email, self._role), email)) if path == "/auth/refresh": - owner = self._use_refresh((body or {}).get("refresh_token")) - if owner is not None: - self._auth_log.append(("refresh", owner[1])) - issued = self._issue(*owner) + token = (body or {}).get("refresh_token") + reused = token in self._used_refresh + owner = self._use_refresh(token) + if reused: # a used refresh token sent again: every session of that login has ended + self._auth_log[-1] = ("refresh_reused", self._used_refresh[token]) + issued = self._issue(*owner) if owner is not None else None if failure is not None: - return self._failure_response(failure, request) # after processing: the token is used already - if owner is None: + return self._fail_response(None, failure, request) # after processing: the token is used already + if issued is None: return _error(401, "UNAUTHORIZED", "Invalid refresh token") return httpx.Response(200, json=issued) if path == "/auth/logout": return httpx.Response(204) token = (request.headers.get("Authorization") or "").replace("Bearer ", "") if token not in self._access: - return _error(401, "UNAUTHORIZED", "The access token is not valid") - self._request_role = self._access[token][0] - logged = _masked(body) - self.requests.append(FakeRequest(request.method, path, dict(request.url.params), logged, op_id)) - self._calls.append((request.method, full)) - self._bodies.append((request.method, full, logged)) + return self._done(rec, _error(401, "UNAUTHORIZED", "The access token is not valid")) + self._request_role, self._request_email = self._access[token] if request.method != "GET" and self._fail is not None: left, status = self._fail if left == 0: self._fail = None - return _error(status, "FAKE_FAILURE", "Failed on purpose by FakeAPI.fail_write") + return self._done(rec, _error(status, "FAKE_FAILURE", "Failed on purpose by FakeAPI.fail_write")) self._fail = (left - 1, status) for method, rx, fn in self._routes: m = rx.fullmatch(full) @@ -397,15 +469,16 @@ def __call__(self, request: httpx.Request) -> httpx.Response: try: out = fn(request, body, *m.groups()) except KeyError: - return _error(404, "NOT_FOUND", "Not found") + return self._done(rec, _error(404, "NOT_FOUND", "Not found")) if failure is not None: # after processing: applied, but the answer is lost - return self._failure_response(failure, request) + return self._fail_response(rec, failure, request) if isinstance(out, httpx.Response): - return out + return self._done(rec, out) status, payload = out - return httpx.Response(status, json=payload) if payload is not None else httpx.Response(status) - return _error(501, "NOT_IMPLEMENTED", f"{op_id or path} is published but this fake does not serve it yet") - + return self._done(rec, httpx.Response(status, json=payload) if payload is not None + else httpx.Response(status)) + return self._done(rec, _error(501, "NOT_IMPLEMENTED", + f"{op_id or path} is published but this fake does not serve it yet")) # ------------------------------------------------------------------ seed data (fictional) @@ -438,12 +511,16 @@ def conn(i: int) -> Any: for i, t in enumerate(cust.teams): for j in (1, 2): email = f"base.user{i + 1}{j}@example.com" + line = f"2{i + 1:02d}{j}" m = acc.add_base_user(cust, PersonSpec(email, "Base", f"User {i + 1}{j}"), team=t, - line=f"2{i + 1:02d}{j}", invite=False) + line=line, invite=False) seeded.base_users[email] = m.user_id + seeded.people.append(SeededPerson(m.user_id, email, "base_user", [t.location_id], [line])) mgr = acc.add_base_manager(cust, PersonSpec("dana.cho@example.com", "Dana", "Cho"), teams=list(cust.teams), line="2001", invite=False) seeded.managers["dana.cho@example.com"] = mgr.user_id + seeded.people.append(SeededPerson(mgr.user_id, "dana.cho@example.com", "base_manager", + [t.location_id for t in cust.teams], ["2001"])) self._visible_locations = [{"id": t.location_id, "location_name": t.name} for t in ([cust.management] if cust.management else []) + cust.teams] finally: @@ -452,10 +529,13 @@ def conn(i: int) -> Any: return seeded def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Optional[Any] = None, - alerts: bool = True, tasks: bool = True) -> List[str]: + alerts: bool = True, tasks: bool = True, recording: bool = False, topics: bool = False) -> List[str]: """Add ``n`` fictional calls (today, or on ``day``) for user logins to read, each with a detail record, an open task and, for every other call, an "Upset Customer" alert. Callers use 555-01xx - numbers. Returns the call ids, newest first.""" + numbers; each call reaches a seeded Base User's line at that location in turn (so a person signed in + with ``as_user`` sees their own). ``recording``: each call has a recording link (an example.com + https address that expires in two hours). ``topics``: topic volumes and rising topics for + ``topics()`` and the Insights Hub dashboard. Returns the call ids, newest first.""" names = ["Morgan Diaz", "Riley Park", "Avery Lane", "Jamie Fox", "Quinn Hale"] lid = location_id or (self._visible_locations[-1]["id"] if self._visible_locations else new_id()) if not self._visible_locations: @@ -464,6 +544,11 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti base = datetime.now(timezone.utc) - timedelta(minutes=5) else: base = datetime.combine(day, dtime(12, 0)).astimezone().astimezone(timezone.utc) + lines = [n for u in self._users.values() if lid in u["_locations"] + for m in self._mappings.get(u["id"], []) for n in m["monitored_numbers"] + if self._connectors.get(m["connector_id"], {}).get("location_id") == lid + and self._users[u["id"]]["_products"].get(lid) == {"after-call-copilot"}] or ["2101"] + expires = (datetime.now(timezone.utc) + timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%SZ") ids: List[str] = [] new_calls: List[Dict[str, Any]] = [] new_tasks: List[Dict[str, Any]] = [] @@ -473,7 +558,7 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti when = (base - timedelta(minutes=i)).strftime("%Y-%m-%dT%H:%M:%SZ") row = {"id": cid, "call_date": when, "call_type": "inbound", "status": "completed", "duration": 120 + i, "caller_name": names[i % len(names)], "caller_number": f"+1555555{100 + i % 100:04d}", - "callee_name": "Riverbend front desk", "callee_number": "2101", "location_id": lid, + "callee_name": "Riverbend front desk", "callee_number": lines[i % len(lines)], "location_id": lid, "summary": "The caller asked about a service appointment.", "sentiment": "neutral", "sentiment_score": 0, "task_count": 1 if tasks else 0} new_calls.append(row) @@ -481,6 +566,9 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti "action_items": ["Call back"]}, "sentiment": {"overall": "neutral"}, "topics": [{"name": "Service"}]}, tasks=[{"id": new_id(), "title": "Call back", "status": "pending", "due_date": None}] if tasks else []) + if recording: + detail["vcon"] = {"recording_url": f"https://media.example.com/recordings/{cid}.wav?sig=example", + "recording_url_expires_at": expires, "recording_mime_type": "audio/wav"} self._call_details[cid] = detail if tasks: new_tasks.append({"id": new_id(), "title": "Call back", "status": "pending", "due_date": None, @@ -493,6 +581,15 @@ def seed_calls(self, n: int = 3, *, location_id: Optional[str] = None, day: Opti "keywords": ["Upset Customer"], "topics": []}) ids.append(cid) self._call_rows[:0] = new_calls # newest first, as the API lists them + if topics: + self._insights = { + "stats": {"total_calls": len(self._call_rows), "answered_calls": len(self._call_rows), "unanswered_calls": 0}, + "topic_call_volumes": [{"name": "Service", "slug": "service", "call_count": n}, + {"name": "Billing", "slug": "billing", "call_count": max(1, n // 2)}], + "trending_topics": [{"name": "Service", "slug": "service", "call_count": n, "previous_call_count": 1, + "percentage_change": 100, "trend_data": []}, + {"name": "Hours", "slug": "hours", "call_count": 1, "previous_call_count": 2, + "percentage_change": -50, "trend_data": []}]} self._task_rows[:0] = new_tasks self._alert_rows[:0] = new_alerts return ids @@ -534,6 +631,13 @@ def _register(self) -> None: # noqa: C901 - a fake server is a long switch @self._route("GET", r"/me") def me(req, body): role = api._request_role + viewer = api._viewer() + if viewer is not None: + return 200, {"data": {"id": viewer["id"], "role": role, "email": viewer["email"], + "first_name": viewer.get("first_name"), "last_name": viewer.get("last_name"), + "company_id": viewer["company_id"], "location_ids": list(viewer["_locations"]), + "enabled_products": sorted(set().union(*viewer["_products"].values())) + if viewer["_products"] else [], "user_type": "company_user"}} return 200, {"data": dict({"id": new_id(), "role": role, "reseller_id": RESELLER if role != "frontline_user" else None, "user_type": "reseller_user" if role != "frontline_user" else "company_user", @@ -695,13 +799,11 @@ def list_conns(req, body, lid): @self._route("POST", r"/locations/([^/]+)/connectors") def create_conn(req, body, lid): - if body["type"] not in [t["key"] for t in CONNECTOR_TYPES]: - return 422, {"error": {"code": "VALIDATION_ERROR", "message": "unknown connector type"}} cid = new_id() api._secrets_sent.append(dict(body["config"])) public = {k: v for k, v in body["config"].items() if not any(w in k.lower() for w in SECRET_WORDS)} api._connectors[cid] = {"id": cid, "location_id": lid, "name": body["name"], "type": body["type"], - "status": "connecting", "_polls": 0, + "status": "connecting", "_polls": 0, "_outcome": api.connector_outcome, "config": dict(public, unexpected_field="redacted")} return 202, {"data": api._connectors[cid]} @@ -709,8 +811,9 @@ def create_conn(req, body, lid): def get_conn(req, body, lid, cid): c = api._connectors[cid] c["_polls"] += 1 - if c["status"] == "connecting" and c["_polls"] >= 2 and api.connector_outcome not in ("stuck", "connecting"): - c["status"] = api.connector_outcome + outcome = c.get("_outcome", api.connector_outcome) # fixed when the connector was created + if c["status"] == "connecting" and c["_polls"] >= 2 and outcome not in ("stuck", "connecting"): + c["status"] = outcome if c["status"] == "error": c["state_reason"] = "invalid_permissions" c["status_message"] = "The key was refused." @@ -737,7 +840,7 @@ def deact_conn(req, body, lid, cid): @self._route("POST", r"/locations/([^/]+)/connectors/([^/]+)/reactivate") def react_conn(req, body, lid, cid): - api._connectors[cid].update(status="connecting", _polls=0) + api._connectors[cid].update(status="connecting", _polls=0, _outcome=api.connector_outcome) # a new attempt return 202, {"data": api._connectors[cid]} # Insights Hub @@ -795,6 +898,7 @@ def create_user(req, body, cid): return 409, {"error": {"code": "CONFLICT", "message": "A user with this email already exists"}} uid = new_id() api._users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], + "first_name": body.get("first_name"), "last_name": body.get("last_name"), "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": {}, "invited_at": None} if body.get("send_invitation"): @@ -893,6 +997,10 @@ def get_prefs(req, body, lid, uid): # conversation data (frontline) @self._route("GET", r"/locations") def visible_locations(req, body): + viewer = api._viewer() + if viewer is not None: + return 200, page([{"id": lid, "location_name": api._locations[lid]["location_name"]} + for lid in viewer["_locations"] if lid in api._locations], "location") return 200, page(api._visible_locations, "location") @self._route("GET", r"/calls") @@ -901,13 +1009,13 @@ def list_calls(req, body): return api._paged(req, [], "calls", {"total_calls": 0, "missed_calls": 0}) lid = req.url.params.get("location_id") q = req.url.params.get("search") - rows = [r for r in api._call_rows if (not lid or r.get("location_id") in lid.split(",")) + rows = [r for r in api._call_rows if api._in_scope(r) and (not lid or r.get("location_id") in lid.split(",")) and (not q or q in (r.get("caller_number") or "") + (r.get("summary") or ""))] return api._paged(req, rows, "calls", {"total_calls": len(rows), "missed_calls": 0}) @self._route("GET", r"/calls/([^/]+)") def get_call(req, body, cid): - if cid not in api._call_details: + if cid not in api._call_details or not api._in_scope(api._call_details[cid]): return 404, {"error": {"code": "NOT_FOUND", "message": "not found"}} return 200, {"data": api._call_details[cid]} @@ -922,8 +1030,8 @@ def list_alerts(req, body): # as published: caller or callee name or number, summary text, or an exact lowercase alert id q = (req.url.params.get("search") or "").lower() fields = ("caller_name", "caller_number", "callee_name", "callee_number", "summary") - rows = [a for a in api._alert_rows if not q or a["id"] == q - or any(q in str(a.get(f) or "").lower() for f in fields)] + rows = [a for a in api._alert_rows if api._alert_in_scope(a) and (not q or a["id"] == q + or any(q in str(a.get(f) or "").lower() for f in fields))] return api._paged(req, rows, "alerts", {"total": len(rows)}) @self._route("GET", r"/tasks") @@ -931,13 +1039,46 @@ def list_tasks(req, body): if api._request_role != "frontline_user": return 200, {"data": [], "meta": {"has_more": False, "next_cursor": None}} st = req.url.params.get("status") - rows = [t for t in api._task_rows if st != "open" or t["status"] in ("pending", "in_progress", "overdue")] + rows = [t for t in api._task_rows if (st != "open" or t["status"] in ("pending", "in_progress", "overdue")) + and api._in_scope(api._call_details.get(t.get("call_id"), {"location_id": t.get("location_id")}))] return 200, {"data": rows, "meta": {"has_more": False, "next_cursor": None}} @self._route("GET", r"/insights/dashboard") def insights(req, body): + viewer = api._viewer() + if viewer is not None and not any("insights-hub" in p for p in viewer["_products"].values()): + return 403, {"error": {"code": "FORBIDDEN", "message": "Insights Hub access is needed"}} return 200, {"data": api._insights} + def _viewer(self) -> Optional[Dict[str, Any]]: + """The seeded person this request signed in as (client(as_user=...)), or None for a generic login.""" + if self._request_role != "frontline_user" or not self._request_email: + return None + return next((u for u in self._users.values() if u["email"] == self._request_email), None) + + def _alert_locations(self, viewer: Dict[str, Any]) -> set: + """Locations where the person is in an alert group (a manager of that team).""" + names = ("Customer Threats", "Upset Customers", "Low Sentiment Calls") + return {g["location_id"] for g in self._groups.values() if g["group_name"] in names and viewer["id"] in g["members"]} + + def _in_scope(self, row: Mapping[str, Any]) -> bool: + """What the platform shows a person: a manager their teams' calls, a Base User their own lines' calls.""" + viewer = self._viewer() + if viewer is None: + return True + if row.get("location_id") in self._alert_locations(viewer): + return True + lines = {n for m in self._mappings.get(viewer["id"], []) for n in m["monitored_numbers"]} + return bool({row.get("callee_number"), row.get("caller_number")} & lines) and \ + row.get("location_id") in viewer["_locations"] + + def _alert_in_scope(self, alert: Mapping[str, Any]) -> bool: + viewer = self._viewer() + if viewer is None: + return True + call = self._call_details.get(alert.get("call_id"), {}) + return call.get("location_id") in self._alert_locations(viewer) + def _paged(self, req: httpx.Request, rows: List[Dict[str, Any]], key: str, summary: Dict[str, Any]): limit = int(req.url.params.get("limit") or 50) start = int(req.url.params.get("cursor") or 0) @@ -965,6 +1106,7 @@ def _masked(value: Any) -> Any: return redact(value) +SIGN_IN_OUTCOMES = ("mfa_required", "password_expired", "invalid_credentials") NETWORK_FAILURES = ("connect", "read_timeout", "write_timeout", "undecodable") _JSON_TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict} diff --git a/tests/unit/behaviour_runner.py b/tests/unit/behaviour_runner.py new file mode 100644 index 0000000..38cce32 --- /dev/null +++ b/tests/unit/behaviour_runner.py @@ -0,0 +1,131 @@ +"""Runs one scenario of fake_behaviour_vectors.json against intelligence_cloud.testing (the reference +interpreter; each SDK port has its own, reading the same file). + +Scenario format (JSON): + name, about + setup: {"strict": bool, "connector_outcome": str, "seed": "none" | "customer" | "customer+calls", + "clients": {"a": {"role": "admin" | "user", "as_user": email | null, "max_retries": int}, ...}} + steps: a list; each step is one of + {"knob": "fail_next", "args": {...}} any FakeAPI knob by name, with its arguments + {"knob": "copy_tokens", "from": "a", "to": "b"} the second client starts from the first's tokens + {"client": "a", "call": , "args": {...}, "expect": {...}} + expect (per call step): {"ok": true, "count": , "connector_status": str} or + {"error": , "request_sent": bool | null, "status": int | null, "cause": }; + for "raw" calls {"status": int} + expect (scenario, after the steps): {"requests": int, "auth_log": [kinds], "counts": [{"method", "path", "count"}], + "connector_status": str} +Placeholders in args and paths: {company_id}, {location_id} (the first team), {email:}. +Neutral call names: login, account.get_me, conversations.calls, groups.create_user_group, +connectors.create_connector, accounts.add_team, raw. +""" +from __future__ import annotations + +import re +from typing import Any, Dict + +import httpx + +import intelligence_cloud as ic +from intelligence_cloud.testing import FakeAPI + + +def _fill(value: Any, ctx: Dict[str, str]) -> Any: + if isinstance(value, str): + return re.sub(r"\{([a-z_]+(?::[^}]+)?)\}", lambda m: ctx.get(m.group(1), m.group(0)), value) + if isinstance(value, dict): + return {k: _fill(v, ctx) for k, v in value.items()} + if isinstance(value, list): + return [_fill(v, ctx) for v in value] + return value + + +def _call(client: ic.Client, name: str, args: Dict[str, Any], api: FakeAPI) -> Any: + if name == "login": + return client.login() + if name == "account.get_me": + return client.account.get_me() + if name == "conversations.calls": + return client.conversations.calls() + if name == "groups.create_user_group": + return client.groups.create_user_group(args["location_id"], args["body"]) + if name == "connectors.create_connector": + return client.connectors.create_connector(args["location_id"], args["body"], wait=bool(args.get("wait"))) + if name == "accounts.add_team": + t, cn = args["team"], args["connector"] + return client.accounts.add_team(args["company_id"], ic.TeamSpec(**t), + ic.ConnectorSpec(type=cn["type"], config=cn["config"], timeout=cn.get("timeout", 600))) + raise ValueError(f"unknown call {name}") + + +def run(scenario: Dict[str, Any]) -> Dict[str, Any]: + """Run a scenario and return what happened (the test compares it with the expectations).""" + setup = scenario.get("setup", {}) + api = FakeAPI(strict=setup.get("strict", True), connector_outcome=setup.get("connector_outcome", "active")) + ctx: Dict[str, str] = {} + seed = setup.get("seed", "none") + if seed.startswith("customer"): + s = api.seed_customer() + ctx["company_id"] = s.company_id + ctx["location_id"] = s.customer.teams[0].location_id + for p in s.people: + ctx["email:" + p.email.split("@")[0]] = p.email + if seed.endswith("+calls"): + api.seed_calls(2, location_id=ctx["location_id"]) + clients: Dict[str, ic.Client] = {} + stores: Dict[str, ic.MemoryTokenStore] = {} + for key, spec in setup.get("clients", {"a": {"role": "user"}}).items(): + stores[key] = ic.MemoryTokenStore() + clients[key] = api.client(role=spec.get("role", "user"), as_user=_fill(spec.get("as_user"), ctx), + max_retries=spec.get("max_retries", 3), token_store=stores[key]) + observed: Dict[str, Any] = {"steps": []} + raw = httpx.Client(base_url="https://app.intelligence.cloud/api/v1", transport=httpx.MockTransport(api)) + for step in scenario["steps"]: + if "knob" in step: + if step["knob"] == "copy_tokens": + stores[step["to"]].set(stores[step["from"]].get()) + elif step["knob"] == "connector_outcome": + api.connector_outcome = step["args"]["value"] + else: + getattr(api, step["knob"])(**_fill(step.get("args", {}), ctx)) + continue + args = _fill(step.get("args", {}), ctx) + if step["call"] == "raw": + token = api._issue("reseller_admin", "raw.caller@example.com")["access_token"] + r = raw.request(args["method"], args["path"], params=args.get("query"), json=args.get("body"), + headers={"Authorization": f"Bearer {token}"}) + observed["steps"].append({"status": r.status_code}) + continue + try: + result = _call(clients[step.get("client", "a")], step["call"], args, api) + out: Dict[str, Any] = {"ok": True} + if isinstance(result, ic.Team): + out["connector_status"] = result.connector_status + if isinstance(result, list): + out["count"] = len(result) + except ic.IntelligenceCloudError as exc: + out = {"error": type(exc).__name__, "request_sent": getattr(exc, "request_sent", None), + "status": getattr(exc, "status", None)} + if isinstance(exc, ic.AccountError): + out["cause"] = type(exc.cause).__name__ + observed["steps"].append(out) + observed["requests"] = len(api.requests) + observed["auth_log"] = [k for k, _ in api.auth_log] + observed["counts"] = [{"method": c["method"], "path": c["path"], "count": api.count(c["method"], _fill(c["path"], ctx))} + for c in scenario.get("expect", {}).get("counts", [])] + return observed + + +def check(scenario: Dict[str, Any]) -> None: + """Assert a scenario's expectations.""" + got = run(scenario) + call_steps = [s for s in scenario["steps"] if "call" in s] + for i, (step, seen) in enumerate(zip(call_steps, got["steps"])): + for k, v in step.get("expect", {}).items(): + assert seen.get(k) == v, f"{scenario['name']}: step {i} ({step['call']}) {k}: {seen.get(k)!r} != {v!r}" + exp = scenario.get("expect", {}) + if "requests" in exp: + assert got["requests"] == exp["requests"], f"{scenario['name']}: requests {got['requests']} != {exp['requests']}" + if "auth_log" in exp: + assert got["auth_log"] == exp["auth_log"], f"{scenario['name']}: auth_log {got['auth_log']} != {exp['auth_log']}" + for want, seen in zip(exp.get("counts", []), got["counts"]): + assert seen["count"] == want["count"], f"{scenario['name']}: {want['method']} {want['path']}: {seen['count']}" diff --git a/tests/unit/fixtures/fake_behaviour_vectors.json b/tests/unit/fixtures/fake_behaviour_vectors.json new file mode 100644 index 0000000..ab65fdd --- /dev/null +++ b/tests/unit/fixtures/fake_behaviour_vectors.json @@ -0,0 +1,807 @@ +[ + { + "name": "connect failure during sign-in: retried, then succeeds", + "setup": { + "seed": "none" + }, + "steps": [ + { + "knob": "fail_next", + "args": { + "network": "connect", + "path": "/auth/login" + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + } + ], + "expect": { + "requests": 1, + "auth_log": [ + "login", + "login" + ] + } + }, + { + "name": "connect failure on a read: retried up to max_retries, then NetworkError (never sent)", + "setup": { + "seed": "none", + "clients": { + "a": { + "role": "user", + "max_retries": 3 + } + } + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "network_down", + "args": {} + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "error": "NetworkError", + "request_sent": false + } + } + ], + "expect": { + "requests": 5, + "auth_log": [ + "login" + ], + "counts": [ + { + "method": "GET", + "path": "/me", + "count": 5 + } + ] + } + }, + { + "name": "503 four times on a read: four requests, then the 503", + "setup": { + "seed": "none", + "clients": { + "a": { + "role": "user", + "max_retries": 3 + } + } + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "fail_next", + "args": { + "status": 503, + "path": "/me" + } + }, + { + "knob": "fail_next", + "args": { + "status": 503, + "path": "/me" + } + }, + { + "knob": "fail_next", + "args": { + "status": 503, + "path": "/me" + } + }, + { + "knob": "fail_next", + "args": { + "status": 503, + "path": "/me" + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "error": "ApiError", + "status": 503 + } + } + ], + "expect": { + "requests": 5, + "counts": [ + { + "method": "GET", + "path": "/me", + "count": 5 + } + ] + } + }, + { + "name": "429 with Retry-After within the limit: waited, then retried", + "setup": { + "seed": "none" + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "fail_next", + "args": { + "status": 429, + "retry_after": 1, + "path": "/me" + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + } + ], + "expect": { + "requests": 3 + } + }, + { + "name": "429 with Retry-After beyond the limit: RateLimitError at once", + "setup": { + "seed": "none" + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "fail_next", + "args": { + "status": 429, + "retry_after": 120, + "path": "/me" + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "error": "RateLimitError", + "status": 429 + } + } + ], + "expect": { + "requests": 2 + } + }, + { + "name": "connect failure on token renewal: the same refresh token is sent again", + "setup": { + "seed": "none" + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "expire_access_tokens", + "args": {} + }, + { + "knob": "fail_next", + "args": { + "network": "connect", + "path": "/auth/refresh" + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + } + ], + "expect": { + "auth_log": [ + "login", + "refresh", + "refresh" + ], + "requests": 3 + } + }, + { + "name": "5xx on renewal before processing: not resent; the client signs in", + "setup": { + "seed": "none" + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "expire_access_tokens", + "args": {} + }, + { + "knob": "fail_next", + "args": { + "status": 502, + "path": "/auth/refresh" + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + } + ], + "expect": { + "auth_log": [ + "login", + "refresh", + "login" + ], + "requests": 3 + } + }, + { + "name": "5xx on renewal after processing (token rotated): not resent, no reuse; the client signs in", + "setup": { + "seed": "none" + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "expire_access_tokens", + "args": {} + }, + { + "knob": "fail_next", + "args": { + "status": 502, + "path": "/auth/refresh", + "after_processing": true + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + } + ], + "expect": { + "auth_log": [ + "login", + "refresh", + "login" + ], + "requests": 3 + } + }, + { + "name": "refresh-token reuse from a second client of the same login ends every session of that login", + "setup": { + "seed": "customer", + "clients": { + "a": { + "role": "user", + "as_user": "{email:base.user11}" + }, + "b": { + "role": "user", + "as_user": "{email:base.user11}" + } + } + }, + "steps": [ + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "knob": "copy_tokens", + "from": "a", + "to": "b" + }, + { + "knob": "expire_access_tokens", + "args": {} + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "client": "b", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + }, + { + "client": "a", + "call": "account.get_me", + "args": {}, + "expect": { + "ok": true + } + } + ], + "expect": { + "auth_log": [ + "login", + "refresh", + "refresh_reused", + "login", + "refresh", + "login" + ] + } + }, + { + "name": "a create after a connect failure is not retried: one request, NetworkError (never sent)", + "setup": { + "seed": "customer", + "clients": { + "a": { + "role": "admin" + } + } + }, + "steps": [ + { + "knob": "fail_next", + "args": { + "network": "connect", + "method": "POST", + "path": "/locations/[^/]+/user-groups" + } + }, + { + "client": "a", + "call": "groups.create_user_group", + "args": { + "location_id": "{location_id}", + "body": { + "group_name": "Night Shift" + } + }, + "expect": { + "error": "NetworkError", + "request_sent": false + } + } + ], + "expect": { + "counts": [ + { + "method": "POST", + "path": "/locations/[^/]+/user-groups", + "count": 1 + } + ] + } + }, + { + "name": "strict: a connector type the spec does not list is refused (422)", + "setup": { + "seed": "customer", + "clients": { + "a": { + "role": "admin" + } + } + }, + "steps": [ + { + "client": "a", + "call": "connectors.create_connector", + "args": { + "location_id": "{location_id}", + "wait": false, + "body": { + "name": "x", + "type": "examplepbx", + "config": { + "host": "pbx.example.com" + } + } + }, + "expect": { + "error": "ValidationError", + "status": 422 + } + } + ] + }, + { + "name": "non-strict: a connector type the spec does not list goes through", + "setup": { + "seed": "customer", + "strict": false, + "clients": { + "a": { + "role": "admin" + } + } + }, + "steps": [ + { + "client": "a", + "call": "connectors.create_connector", + "args": { + "location_id": "{location_id}", + "wait": false, + "body": { + "name": "x", + "type": "examplepbx", + "config": { + "host": "pbx.example.com" + } + } + }, + "expect": { + "ok": true + } + } + ] + }, + { + "name": "strict: an unknown query parameter is refused (400)", + "setup": { + "seed": "customer" + }, + "steps": [ + { + "call": "raw", + "args": { + "method": "GET", + "path": "/calls", + "query": { + "page_size": "10" + } + }, + "expect": { + "status": 400 + } + } + ] + }, + { + "name": "non-strict: an unknown query parameter is ignored", + "setup": { + "seed": "customer", + "strict": false + }, + "steps": [ + { + "call": "raw", + "args": { + "method": "GET", + "path": "/calls", + "query": { + "page_size": "10" + } + }, + "expect": { + "status": 200 + } + } + ] + }, + { + "name": "strict: an unknown body field is refused (422)", + "setup": { + "seed": "customer" + }, + "steps": [ + { + "call": "raw", + "args": { + "method": "PATCH", + "path": "/locations/{location_id}/insights-hub/config", + "body": { + "monitor_all_numbers": false, + "zzz": 1 + } + }, + "expect": { + "status": 422 + } + } + ] + }, + { + "name": "non-strict: an unknown body field is ignored", + "setup": { + "seed": "customer", + "strict": false + }, + "steps": [ + { + "call": "raw", + "args": { + "method": "PATCH", + "path": "/locations/{location_id}/insights-hub/config", + "body": { + "monitor_all_numbers": false, + "zzz": 1 + } + }, + "expect": { + "status": 200 + } + } + ] + }, + { + "name": "connector ends in error, then a re-run with the outcome active completes", + "setup": { + "seed": "customer", + "clients": { + "a": { + "role": "admin" + } + } + }, + "steps": [ + { + "knob": "connector_outcome", + "args": { + "value": "error" + } + }, + { + "client": "a", + "call": "accounts.add_team", + "args": { + "company_id": "{company_id}", + "team": { + "name": "Riverbend - East", + "street": "9 Lake St", + "city": "Springfield", + "state": "IL", + "country": "US", + "zipcode": "62702", + "vertical": "service-providers" + }, + "connector": { + "type": "netsapiens", + "config": { + "api_url": "https://pbx.example.com/ns-api/v2", + "domain": "east.example.com", + "api_key": "example-key" + }, + "timeout": 60 + } + }, + "expect": { + "error": "AccountError", + "cause": "ConnectorError" + } + }, + { + "knob": "connector_outcome", + "args": { + "value": "active" + } + }, + { + "client": "a", + "call": "accounts.add_team", + "args": { + "company_id": "{company_id}", + "team": { + "name": "Riverbend - East", + "street": "9 Lake St", + "city": "Springfield", + "state": "IL", + "country": "US", + "zipcode": "62702", + "vertical": "service-providers" + }, + "connector": { + "type": "netsapiens", + "config": { + "api_url": "https://pbx.example.com/ns-api/v2", + "domain": "east.example.com", + "api_key": "example-key" + }, + "timeout": 60 + } + }, + "expect": { + "ok": true, + "connector_status": "active" + } + } + ] + }, + { + "name": "sign-in answers mfa_required", + "setup": { + "seed": "none" + }, + "steps": [ + { + "knob": "fail_next", + "args": { + "sign_in": "mfa_required" + } + }, + { + "client": "a", + "call": "login", + "args": {}, + "expect": { + "error": "MfaRequiredError" + } + } + ], + "expect": { + "auth_log": [ + "login" + ], + "requests": 0 + } + }, + { + "name": "sign-in answers password_expired", + "setup": { + "seed": "none" + }, + "steps": [ + { + "knob": "fail_next", + "args": { + "sign_in": "password_expired" + } + }, + { + "client": "a", + "call": "login", + "args": {}, + "expect": { + "error": "PasswordExpiredError" + } + } + ] + }, + { + "name": "sign-in answers invalid_credentials (401)", + "setup": { + "seed": "none" + }, + "steps": [ + { + "knob": "fail_next", + "args": { + "sign_in": "invalid_credentials" + } + }, + { + "client": "a", + "call": "login", + "args": {}, + "expect": { + "error": "AuthError", + "status": 401 + } + } + ] + }, + { + "name": "a person sees only their own calls; a manager sees the team's", + "setup": { + "seed": "customer+calls", + "clients": { + "a": { + "role": "user", + "as_user": "{email:base.user11}" + }, + "b": { + "role": "user", + "as_user": "{email:dana.cho}" + } + } + }, + "steps": [ + { + "client": "a", + "call": "conversations.calls", + "args": {}, + "expect": { + "ok": true, + "count": 1 + } + }, + { + "client": "b", + "call": "conversations.calls", + "args": {}, + "expect": { + "ok": true, + "count": 2 + } + } + ] + } +] diff --git a/tests/unit/fixtures/line_vectors.json b/tests/unit/fixtures/line_vectors.json new file mode 100644 index 0000000..02bbd8f --- /dev/null +++ b/tests/unit/fixtures/line_vectors.json @@ -0,0 +1,78 @@ +[ + { + "value": "2101", + "accepted": true + }, + { + "value": "+15555550142", + "accepted": true + }, + { + "value": "*72", + "accepted": true + }, + { + "value": "#9", + "accepted": true + }, + { + "value": "0", + "accepted": true + }, + { + "value": "99999999999999999999999999999999", + "accepted": true + }, + { + "value": "999999999999999999999999999999999", + "accepted": false + }, + { + "value": "21 10", + "accepted": false + }, + { + "value": " 2101", + "accepted": false + }, + { + "value": "2101 ", + "accepted": false + }, + { + "value": "21-10", + "accepted": false + }, + { + "value": "+", + "accepted": false + }, + { + "value": "++1", + "accepted": false + }, + { + "value": "1+2", + "accepted": false + }, + { + "value": "", + "accepted": false + }, + { + "value": "x2101", + "accepted": false + }, + { + "value": "2101\n", + "accepted": false + }, + { + "value": "21", + "accepted": false + }, + { + "value": "٢١", + "accepted": false + } +] diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index b4172ec..e9c2346 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -272,7 +272,7 @@ def test_a_connector_type_the_spec_does_not_list_still_reaches_the_request(): def test_an_unknown_connector_type_is_refused_by_the_platform_not_the_sdk(): - api = FakeAPI(strict=False) # the fake, like the platform, answers 422 for a type it does not have + api = FakeAPI() # strict mode answers 422 for a type the published spec does not list, as the platform does bad = ic.ConnectorSpec(type="nosuchpbx", config={"api_key": "K-SECRET"}) with pytest.raises(ic.AccountError) as e: api.client().accounts.create_customer(spec(connector=bad)) diff --git a/tests/unit/test_developer_round.py b/tests/unit/test_developer_round.py new file mode 100644 index 0000000..b07aed6 --- /dev/null +++ b/tests/unit/test_developer_round.py @@ -0,0 +1,244 @@ +"""The developer-review round: the testing module models what a developer needs, results are typed, +lines are checked, messages name the caller's parameters, Member.teams is complete, teams() puts +Management last, and older deliveries never overwrite newer ones.""" +from __future__ import annotations + +import dataclasses +import json +from pathlib import Path + +import httpx +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.testing import FakeAPI + +from .behaviour_runner import check + +FIX = Path(__file__).resolve().parent / "fixtures" +SAMPLE = json.loads((Path(__file__).resolve().parents[2] / "examples" / "after-call-sample.json").read_text()) +EAST = ic.TeamSpec("Riverbend - East", "9 Lake St", "Springfield", "IL", "US", "62702", "service-providers") + + +# ---------------------------------------------------------------------- shared behaviour scenarios + + +@pytest.mark.parametrize("scenario", json.loads((FIX / "fake_behaviour_vectors.json").read_text()), + ids=lambda s: s["name"]) +def test_fake_behaviour_vectors(scenario): + check(scenario) + + +@pytest.mark.parametrize("v", json.loads((FIX / "line_vectors.json").read_text()), ids=lambda v: repr(v["value"])) +def test_line_vectors(v): + from intelligence_cloud.accounts import _line + if v["accepted"]: + assert _line(v["value"]) == v["value"] + else: + with pytest.raises(ic.InvalidRequestError): + _line(v["value"]) + + +# ---------------------------------------------------------------------- A: the testing module + + +def test_non_strict_lets_an_unlisted_connector_type_through(): + api = FakeAPI(strict=False) + s = api.seed_customer(people=False) + team = api.client(role="admin").accounts.add_team( + s.customer, EAST, ic.ConnectorSpec(type="nosuchpbx", config={"host": "pbx.example.com"}, timeout=60)) + assert team.connector_status == "active" + + +def test_every_request_is_logged_with_what_answered_it(): + api = FakeAPI() + me = api.client(role="user", max_retries=3) + me.account.get_me() + api.reset_log() + for _ in range(4): + api.fail_next(503, path="/me") + with pytest.raises(ic.ApiError): + me.account.get_me() + assert api.count("GET", "/me") == 4 and [r.answer for r in api.requests] == [503] * 4 + api.reset_log() + api.network_down() + with pytest.raises(ic.NetworkError): + me.account.get_me() + assert {r.answer for r in api.requests} == {"network:connect"} and len(api.requests) == 4 + api.network_down(False) + api.reset_log() + api.rate_limit(1, retry_after=1) + me.account.get_me() + assert [r.answer for r in api.requests] == [429, 200] + api.reset_log() + api.fail_write(1) + with pytest.raises(ic.ValidationError): + api.client(role="admin").groups.create_user_group("0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02", {"group_name": "x"}) + assert api.requests[-1].answer == 400 + + +# ---------------------------------------------------------------------- B: modelling people, recordings, topics + + +def test_signing_in_as_a_seeded_person_follows_their_license(): + api = FakeAPI() + s = api.seed_customer() + licenses = {p.email: p.license for p in s.people} + assert licenses["dana.cho@example.com"] == "base_manager" and licenses["base.user11@example.com"] == "base_user" + api.seed_calls(4, location_id=s.customer.teams[0].location_id, recording=True, topics=True) + user = api.client(role="user", as_user="base.user11@example.com") + manager = api.client(role="user", as_user=s.managers["dana.cho@example.com"]) + assert len(user.conversations.calls()) == 2 and len(manager.conversations.calls()) == 4 + assert user.conversations.alerts() == [] and len(manager.conversations.alerts()) == 2 + assert user.conversations.me().email == "base.user11@example.com" + with pytest.raises(ic.ApiError) as e: + user.conversations.topics() # no Insights Hub for a Base User + assert e.value.status == 403 + topics = manager.conversations.topics() + assert topics.rising and topics.rising[0]["slug"] == "service" + brief = manager.conversations.calls()[0] + link = manager.conversations.recording_link(brief.id) + assert link.url.startswith("https://media.example.com/") and link.expires_at is not None + view = manager.conversations.team_view(next(t for t in manager.conversations.teams() if t.kind == "team")) + assert len(view.briefs) == 4 and view.open_tasks + with pytest.raises(ic.InvalidRequestError): + api.client(role="user", as_user="nobody@example.com") + with pytest.raises(ic.InvalidRequestError): + api.client(role="admin", as_user="base.user11@example.com") + + +@pytest.mark.parametrize("outcome,error", [("mfa_required", ic.MfaRequiredError), + ("password_expired", ic.PasswordExpiredError), + ("invalid_credentials", ic.AuthError)]) +def test_sign_in_outcomes(outcome, error): + api = FakeAPI() + api.fail_next(sign_in=outcome) + with pytest.raises(error): + api.client(role="user").login() + + +# ---------------------------------------------------------------------- C8: typed results + + +def test_results_are_typed_and_read_like_dicts(): + api = FakeAPI() + s = api.seed_customer() + acc = api.client(role="admin").accounts + act = acc.activate_alerts(s.customer) + rep = acc.license_report(s.customer) + sync = acc.sync_lines(s.customer, dry_run=True) + rem = acc.remove_user(s.customer, s.base_users["base.user12@example.com"]) + off = acc.offboard_customer(s.customer) + for value, cls in ((act, ic.AlertActivation), (rep, ic.LicenseReport), (sync, ic.LineSyncReport), + (rem, ic.RemovalSummary), (off, ic.OffboardSummary)): + assert isinstance(value, cls) and dataclasses.is_dataclass(value) + with pytest.raises(dataclasses.FrozenInstanceError): + setattr(value, value.keys()[0], None) + assert act["switched_on"] == act.switched_on and "no_manager" in act and "skipped" not in act + assert rep.base_user == rep["base_user"] == 2 and rep.get("missing", 7) == 7 + team = sync.teams[s.customer.teams[0].location_id] + assert isinstance(team, ic.TeamLines) and team["first_alert"] == {"add": [], "remove": []} + assert rem["released_lines"] == rem.released_lines and off.company_deactivated is True + assert rem.to_dict()["user_id"] == rem.user_id + + +# ---------------------------------------------------------------------- C9 / C10 / C11 / C12 + + +class Count: + def __init__(self): + self.n = 0 + + def __call__(self, r): + self.n += 1 + raise httpx.ConnectError("down", request=r) + + +@pytest.mark.parametrize("bad", ["21 10", " 2101", "21-10", "x2101", "", "1" * 33, 2101]) +def test_lines_must_be_digits_star_hash(bad): + t = Count() + c = ic.Client("a@example.com", "pw", transport=httpx.MockTransport(t), sleep=lambda s: None, max_retries=0) + person = ic.PersonSpec("x@example.com", "A", "B") + for call in (lambda: c.accounts.add_base_user("c1", person, team="t", line=bad), + lambda: c.accounts.add_base_manager("c1", person, teams=["t"], line=bad), + lambda: c.accounts.change_line("c1", "u1", bad, "2102"), + lambda: c.accounts.change_line("c1", "u1", "2101", bad), + lambda: c.accounts.change_license("c1", "u1", "base_user", line=bad)): + with pytest.raises(ic.InvalidRequestError): + call() + assert t.n == 0 + + +def test_messages_name_the_callers_parameters(): + c = ic.Client("a@example.com", "pw") + with pytest.raises(ic.InvalidRequestError) as e: + c.conversations.calls(number="5555550142", search="billing") + assert "number" in str(e.value) and "search" in str(e.value) and "phone" not in str(e.value) + with pytest.raises(ic.InvalidRequestError) as e: + c.conversations.calls(search="x") + assert str(e.value).startswith("search:") + with pytest.raises(ic.InvalidRequestError) as e: + c.intelligence.search_calls(phone="5555550142", text="billing") + assert "phone" in str(e.value) and "text" in str(e.value) + + +def test_member_teams_lists_every_team_of_the_person(): + api = FakeAPI() + s = api.seed_customer(people=False) + acc = api.client(role="admin").accounts + east = acc.add_team(s.customer, EAST, ic.ConnectorSpec.netsapiens( + "https://pbx.example.com/ns-api/v2", "east.example.com", "example-key")) + first = acc.add_base_manager(s.customer, ic.PersonSpec("lee.park@example.com", "Lee", "Park"), + teams=[s.customer.teams[0]], invite=False) + assert first.teams == [s.customer.teams[0].location_id] + again = acc.add_base_manager(s.customer, ic.PersonSpec("lee.park@example.com", "Lee", "Park"), + teams=[east], invite=False) + listed = next(m for m in acc.list_members(s.customer) if m.user_id == again.user_id) + assert sorted(again.teams) == sorted(listed.teams) == sorted([s.customer.teams[0].location_id, east.location_id]) + + +def test_teams_lists_teams_first_and_management_last(): + api = FakeAPI() + s = api.seed_customer(teams=2) + teams = api.client(role="user", as_user="dana.cho@example.com").conversations.teams() + assert [t.kind for t in teams] == ["team", "team", "management"] + assert [t.name for t in teams[:2]] == sorted(t.name for t in teams[:2]) + + +# ---------------------------------------------------------------------- C13: out-of-order deliveries + + +def test_an_older_retry_never_overwrites_newer_data(): + dedup, store = ic.Deduplicator(), {} + fail = {"next": True} + + def receive(body: dict) -> int: + ev = ic.parse_after_call_event(json.dumps(body)) + if dedup.seen(ev): + return 204 + try: + if fail["next"]: + fail["next"] = False + raise OSError("store down") + key = ic.upsert_key(ev) + if key in store and ic.is_older(ev, store[key]): + dedup.remember(ev) + return 204 + store[key] = ev + except OSError: + return 503 + dedup.remember(ev) + return 204 + + v1 = json.loads(json.dumps(SAMPLE)) + v1["summary"]["text"], v1["timestamp"] = "first summary", "2026-11-02T16:46:12Z" + v2 = json.loads(json.dumps(SAMPLE)) + v2["summary"]["text"], v2["timestamp"] = "newer summary", "2026-11-02T16:50:00Z" + assert receive(v1) == 503 # v1 fails to store + assert receive(v2) == 204 # v2 is stored + assert receive(v1) == 204 # the sender retries v1: older, so not stored + assert next(iter(store.values())).summary.text == "newer summary" + same_time = json.loads(json.dumps(v2)) + same_time["summary"]["text"] = "same timestamp, later arrival" + assert receive(same_time) == 204 and next(iter(store.values())).summary.text == "same timestamp, later arrival" + assert ic.is_older(v1, None) is False and ic.is_older({"alert_id": "fa-1"}, v2) is False diff --git a/tests/unit/test_request_counts.py b/tests/unit/test_request_counts.py index 7b01500..bdbc219 100644 --- a/tests/unit/test_request_counts.py +++ b/tests/unit/test_request_counts.py @@ -15,7 +15,8 @@ "create_customer, re-run": (18, 18), "add_base_user": (36, 90), "add_base_manager (every team)": (32, 158), - "activate_alerts (Customer)": (17, 107), + "activate_alerts (Customer)": (15, 105), + "set_alerts (both phrase alerts, Customer)": (8, 62), "activate_alerts (company id)": (21, 120), "sync_lines (Customer)": (11, 65), "sync_lines (company id)": (19, 100), @@ -67,12 +68,14 @@ def measure(teams: int) -> dict: api.client(role="admin").accounts.add_base_manager(seeded.customer, ic.PersonSpec("lee.park@example.com", "Lee", "Park"), teams=list(seeded.customer.teams), line="2002") out["add_base_manager (every team)"] = len(api.requests) - start - start = len(api.requests) - api.client(role="admin").accounts.activate_alerts(seeded.customer) - out["activate_alerts (Customer)"] = len(api.requests) - start for label, call in ( + # each on a freshly seeded customer: two Base Users per team, one manager, alert rules off + ("activate_alerts (Customer)", lambda a, sc: a.activate_alerts(sc.customer)), ("activate_alerts (company id)", lambda a, sc: a.activate_alerts(sc.company_id)), + ("set_alerts (both phrase alerts, Customer)", lambda a, sc: a.set_alerts(sc.customer, ic.AlertSettings( + customer_threat=ic.AlertSetting(phrases=["example phrase one"]), + upset_customer=ic.AlertSetting(phrases=["example phrase two"])))), ("sync_lines (Customer)", lambda a, sc: a.sync_lines(sc.customer)), ("sync_lines (company id)", lambda a, sc: a.sync_lines(sc.company_id)), ("license_report (Customer)", lambda a, sc: a.license_report(sc.customer)), @@ -93,6 +96,36 @@ def measure(teams: int) -> dict: return out +def ten_team_setup() -> int: + """A ten-team customer end to end with a Customer object: create, nine add_team, both phrase alerts, + one manager per team, three Base Users per team, activate.""" + api = FakeAPI() + acc = api.client(role="admin").accounts + cust = acc.create_customer(_spec()) + for i in range(1, 10): + acc.add_team(cust, ic.TeamSpec(f"Riverbend - Team {i + 1}", f"{100 + i} River Rd", "Springfield", "IL", "US", + "62701", "service-providers"), + ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", f"riverbend{i + 1}.example.com", + "example-key")) + acc.set_alerts(cust, ic.AlertSettings(customer_threat=ic.AlertSetting(phrases=["example phrase one"]), + upset_customer=ic.AlertSetting(phrases=["example phrase two"]))) + for i, t in enumerate(cust.teams): + acc.add_base_manager(cust, ic.PersonSpec(f"manager{i}@example.com", "Team", f"Manager {i}"), teams=[t], + line=f"20{i:02d}", invite=False) + for j in range(3): + acc.add_base_user(cust, ic.PersonSpec(f"user{i}{j}@example.com", "Base", f"User {i}{j}"), team=t, + line=f"3{i:02d}{j}", invite=False) + acc.activate_alerts(cust) + return len(api.requests) + + +TEN_TEAM_SETUP = 2497 # about 8.3 minutes at the published 5 requests a second + + +def test_ten_team_setup_total(): + assert ten_team_setup() == TEN_TEAM_SETUP + + @pytest.mark.parametrize("col,teams", [(0, 1), (1, 10)]) def test_request_counts(col, teams): got = measure(teams) diff --git a/tests/unit/test_review_030.py b/tests/unit/test_review_030.py index 95a2482..2fa35fc 100644 --- a/tests/unit/test_review_030.py +++ b/tests/unit/test_review_030.py @@ -89,7 +89,7 @@ def test_a_renewal_refused_before_processing_keeps_its_token(failure): api.expire_access_tokens() api.fail_next(**failure, path="/auth/refresh") # before processing (the default): the token is unused assert len(me.conversations.calls()) == 1 - assert [k for k, _ in api.auth_log] == ["refresh"] # the same token, sent again, worked: no reuse, no sign-in + assert [k for k, _ in api.auth_log] == ["refresh", "refresh"] # the same token sent again worked: no reuse, no sign-in def test_the_fake_ends_every_session_when_a_refresh_token_is_reused(): @@ -311,6 +311,7 @@ def test_fake_surface_is_small_and_transport_is_refused(): api.client(role="superuser") public = {n for n in dir(api) if not n.startswith("_")} assert public == {"client", "seed_customer", "seed_calls", "connector_outcome", "fail_next", "fail_write", + "settle_connector", "network_down", "rate_limit", "expire_access_tokens", "requests", "writes", "writes_since", "count", "reset_log", "auth_log", "products", "numbers", "fa_numbers", "ih_numbers", "group_members"} diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py index 8970b23..6a1b9cc 100644 --- a/tests/unit/test_review_fixes.py +++ b/tests/unit/test_review_fixes.py @@ -365,9 +365,24 @@ def test_connector_timeout_stops_at_the_end_and_a_rerun_completes(): assert err.step == "connectors" and isinstance(err.cause, ic.ConnectorTimeoutError) assert err.result.teams[0].rules.low_sentiment and err.result.management.groups.weekly_reports assert err.result.teams[0].connector_status == "connecting" - api.connector_outcome = "active" - done = c.accounts.create_customer(spec(connector=slow, company_id=err.result.company_id)) + api.connector_outcome = "active" # applies to new connection attempts, not to the waiting ones + normal = ic.ConnectorSpec.netsapiens(CONN.config["api_url"], CONN.config["domain"], "test-key-123", timeout=60) + done = c.accounts.create_customer(spec(connector=normal, company_id=err.result.company_id)) assert done.teams[0].connector_status == "active" and done.management.connector_status == "active" + assert api.count("POST", r"/locations/[^/]+/connectors/[^/]+/reactivate") == 2 # each waiting one restarted once + + +def test_connector_outcome_applies_to_new_connectors_and_settle_connector_settles_one(): + api = FakeAPI(connector_outcome="stuck") + c = api.client() + with pytest.raises(ic.AccountError): + c.accounts.create_customer(spec(connector=ic.ConnectorSpec.netsapiens( + CONN.config["api_url"], CONN.config["domain"], "test-key-123", timeout=30))) + api.connector_outcome = "active" + waiting = [x for x in api._connectors.values()] + assert all(x["status"] == "connecting" for x in waiting) # not flipped by the knob + assert api.settle_connector(waiting[0]["id"]) == 1 and api.settle_connector(waiting[1]["location_id"], "error") == 1 + assert [x["status"] for x in waiting] == ["active", "error"] def test_add_team_and_set_connector_stop_on_a_connector_error(): diff --git a/tools/make_shared_vectors.py b/tools/make_shared_vectors.py index f807a76..b251d20 100644 --- a/tools/make_shared_vectors.py +++ b/tools/make_shared_vectors.py @@ -280,6 +280,26 @@ def strictness_vectors(): return [{"name": n, "method": m, "path": p, "query": qq, "body": b, "status": st} for n, m, p, qq, b, st in q] +def line_vectors(): + from intelligence_cloud.accounts import _line + from intelligence_cloud.errors import InvalidRequestError + values = ["2101", "+15555550142", "*72", "#9", "0", "9" * 32, "9" * 33, "21 10", " 2101", "2101 ", "21-10", + "+", "++1", "1+2", "", "x2101", "2101\n", "\uff12\uff11", "٢١"] + out = [] + for v in values: + try: + _line(v) + accepted = True + except InvalidRequestError: + accepted = False + out.append({"value": v, "accepted": accepted}) + want = {"2101", "+15555550142", "*72", "#9", "0", "9" * 32} + for e in out: + if (e["value"] in want) != e["accepted"]: + raise SystemExit(f"line rule mismatch for {e['value']!r}") + return out + + def path_vectors(): from intelligence_cloud._spec import check_path_value from intelligence_cloud.errors import InvalidRequestError @@ -302,6 +322,134 @@ def path_vectors(): return out +def behaviour_vectors(): + """Scenarios of the testing module's behaviour, in the neutral form tests/unit/behaviour_runner.py reads.""" + me = {"client": "a", "call": "account.get_me", "args": {}} + team = {"name": "Riverbend - East", "street": "9 Lake St", "city": "Springfield", "state": "IL", + "country": "US", "zipcode": "62702", "vertical": "service-providers"} + conn = {"type": "netsapiens", "config": {"api_url": "https://pbx.example.com/ns-api/v2", "domain": "east.example.com", + "api_key": "example-key"}, "timeout": 60} + admin = {"a": {"role": "admin"}} + + def ok(step): + return dict(step, expect={"ok": True}) + scenarios = [ + {"name": "connect failure during sign-in: retried, then succeeds", + "setup": {"seed": "none"}, + "steps": [{"knob": "fail_next", "args": {"network": "connect", "path": "/auth/login"}}, ok(me)], + "expect": {"requests": 1, "auth_log": ["login", "login"]}}, + {"name": "connect failure on a read: retried up to max_retries, then NetworkError (never sent)", + "setup": {"seed": "none", "clients": {"a": {"role": "user", "max_retries": 3}}}, + "steps": [ok(me), {"knob": "network_down", "args": {}}, + dict(me, expect={"error": "NetworkError", "request_sent": False})], + "expect": {"requests": 5, "auth_log": ["login"], "counts": [{"method": "GET", "path": "/me", "count": 5}]}}, + {"name": "503 four times on a read: four requests, then the 503", + "setup": {"seed": "none", "clients": {"a": {"role": "user", "max_retries": 3}}}, + "steps": [ok(me)] + [{"knob": "fail_next", "args": {"status": 503, "path": "/me"}}] * 4 + + [dict(me, expect={"error": "ApiError", "status": 503})], + "expect": {"requests": 5, "counts": [{"method": "GET", "path": "/me", "count": 5}]}}, + {"name": "429 with Retry-After within the limit: waited, then retried", + "setup": {"seed": "none"}, + "steps": [ok(me), {"knob": "fail_next", "args": {"status": 429, "retry_after": 1, "path": "/me"}}, ok(me)], + "expect": {"requests": 3}}, + {"name": "429 with Retry-After beyond the limit: RateLimitError at once", + "setup": {"seed": "none"}, + "steps": [ok(me), {"knob": "fail_next", "args": {"status": 429, "retry_after": 120, "path": "/me"}}, + dict(me, expect={"error": "RateLimitError", "status": 429})], + "expect": {"requests": 2}}, + {"name": "connect failure on token renewal: the same refresh token is sent again", + "setup": {"seed": "none"}, + "steps": [ok(me), {"knob": "expire_access_tokens", "args": {}}, + {"knob": "fail_next", "args": {"network": "connect", "path": "/auth/refresh"}}, ok(me)], + "expect": {"auth_log": ["login", "refresh", "refresh"], "requests": 3}}, + {"name": "5xx on renewal before processing: not resent; the client signs in", + "setup": {"seed": "none"}, + "steps": [ok(me), {"knob": "expire_access_tokens", "args": {}}, + {"knob": "fail_next", "args": {"status": 502, "path": "/auth/refresh"}}, ok(me)], + "expect": {"auth_log": ["login", "refresh", "login"], "requests": 3}}, + {"name": "5xx on renewal after processing (token rotated): not resent, no reuse; the client signs in", + "setup": {"seed": "none"}, + "steps": [ok(me), {"knob": "expire_access_tokens", "args": {}}, + {"knob": "fail_next", "args": {"status": 502, "path": "/auth/refresh", "after_processing": True}}, + ok(me)], + "expect": {"auth_log": ["login", "refresh", "login"], "requests": 3}}, + {"name": "refresh-token reuse from a second client of the same login ends every session of that login", + "setup": {"seed": "customer", "clients": {"a": {"role": "user", "as_user": "{email:base.user11}"}, + "b": {"role": "user", "as_user": "{email:base.user11}"}}}, + "steps": [ok(me), {"knob": "copy_tokens", "from": "a", "to": "b"}, {"knob": "expire_access_tokens", "args": {}}, + ok(me), dict(me, client="b", expect={"ok": True}), dict(me, expect={"ok": True})], + "expect": {"auth_log": ["login", "refresh", "refresh_reused", "login", "refresh", "login"]}}, + {"name": "a create after a connect failure is not retried: one request, NetworkError (never sent)", + "setup": {"seed": "customer", "clients": admin}, + "steps": [{"knob": "fail_next", "args": {"network": "connect", "method": "POST", + "path": "/locations/[^/]+/user-groups"}}, + {"client": "a", "call": "groups.create_user_group", + "args": {"location_id": "{location_id}", "body": {"group_name": "Night Shift"}}, + "expect": {"error": "NetworkError", "request_sent": False}}], + "expect": {"counts": [{"method": "POST", "path": "/locations/[^/]+/user-groups", "count": 1}]}}, + {"name": "strict: a connector type the spec does not list is refused (422)", + "setup": {"seed": "customer", "clients": admin}, + "steps": [{"client": "a", "call": "connectors.create_connector", + "args": {"location_id": "{location_id}", "wait": False, + "body": {"name": "x", "type": "examplepbx", "config": {"host": "pbx.example.com"}}}, + "expect": {"error": "ValidationError", "status": 422}}]}, + {"name": "non-strict: a connector type the spec does not list goes through", + "setup": {"seed": "customer", "strict": False, "clients": admin}, + "steps": [{"client": "a", "call": "connectors.create_connector", + "args": {"location_id": "{location_id}", "wait": False, + "body": {"name": "x", "type": "examplepbx", "config": {"host": "pbx.example.com"}}}, + "expect": {"ok": True}}]}, + {"name": "strict: an unknown query parameter is refused (400)", + "setup": {"seed": "customer"}, + "steps": [{"call": "raw", "args": {"method": "GET", "path": "/calls", "query": {"page_size": "10"}}, + "expect": {"status": 400}}]}, + {"name": "non-strict: an unknown query parameter is ignored", + "setup": {"seed": "customer", "strict": False}, + "steps": [{"call": "raw", "args": {"method": "GET", "path": "/calls", "query": {"page_size": "10"}}, + "expect": {"status": 200}}]}, + {"name": "strict: an unknown body field is refused (422)", + "setup": {"seed": "customer"}, + "steps": [{"call": "raw", "args": {"method": "PATCH", "path": "/locations/{location_id}/insights-hub/config", + "body": {"monitor_all_numbers": False, "zzz": 1}}, "expect": {"status": 422}}]}, + {"name": "non-strict: an unknown body field is ignored", + "setup": {"seed": "customer", "strict": False}, + "steps": [{"call": "raw", "args": {"method": "PATCH", "path": "/locations/{location_id}/insights-hub/config", + "body": {"monitor_all_numbers": False, "zzz": 1}}, "expect": {"status": 200}}]}, + {"name": "connector ends in error, then a re-run with the outcome active completes", + "setup": {"seed": "customer", "clients": admin}, + "steps": [{"knob": "connector_outcome", "args": {"value": "error"}}, + {"client": "a", "call": "accounts.add_team", "args": {"company_id": "{company_id}", "team": team, "connector": conn}, + "expect": {"error": "AccountError", "cause": "ConnectorError"}}, + {"knob": "connector_outcome", "args": {"value": "active"}}, + {"client": "a", "call": "accounts.add_team", "args": {"company_id": "{company_id}", "team": team, "connector": conn}, + "expect": {"ok": True, "connector_status": "active"}}]}, + {"name": "sign-in answers mfa_required", + "setup": {"seed": "none"}, + "steps": [{"knob": "fail_next", "args": {"sign_in": "mfa_required"}}, + {"client": "a", "call": "login", "args": {}, "expect": {"error": "MfaRequiredError"}}], + "expect": {"auth_log": ["login"], "requests": 0}}, + {"name": "sign-in answers password_expired", + "setup": {"seed": "none"}, + "steps": [{"knob": "fail_next", "args": {"sign_in": "password_expired"}}, + {"client": "a", "call": "login", "args": {}, "expect": {"error": "PasswordExpiredError"}}]}, + {"name": "sign-in answers invalid_credentials (401)", + "setup": {"seed": "none"}, + "steps": [{"knob": "fail_next", "args": {"sign_in": "invalid_credentials"}}, + {"client": "a", "call": "login", "args": {}, "expect": {"error": "AuthError", "status": 401}}]}, + {"name": "a person sees only their own calls; a manager sees the team's", + "setup": {"seed": "customer+calls", "clients": {"a": {"role": "user", "as_user": "{email:base.user11}"}, + "b": {"role": "user", "as_user": "{email:dana.cho}"}}}, + "steps": [{"client": "a", "call": "conversations.calls", "args": {}, "expect": {"ok": True, "count": 1}}, + {"client": "b", "call": "conversations.calls", "args": {}, "expect": {"ok": True, "count": 2}}]}, + ] + import sys as _sys + _sys.path.insert(0, str(HERE / "tests" / "unit")) + from behaviour_runner import check # noqa: E402 + for sc in scenarios: + check(sc) + return scenarios + + def main() -> None: files = { "delivery_key_vectors.json": delivery_vectors(), @@ -310,6 +458,8 @@ def main() -> None: "after_call_parse_vectors.json": parse_vectors(), "fake_strictness_vectors.json": strictness_vectors(), "path_argument_vectors.json": path_vectors(), + "line_vectors.json": line_vectors(), + "fake_behaviour_vectors.json": behaviour_vectors(), } dirs = [OUT] + [pathlib.Path(a) for a in sys.argv[1:]] for d in dirs: @@ -319,7 +469,7 @@ def main() -> None: counts = (HERE / "tests" / "unit" / "test_request_counts.py").read_text().split("\n\n\ndef _spec")[0] for d in dirs[1:]: (d / "request_counts_reference.py.txt").write_text(counts + "\n", encoding="utf-8") - (d / "SHARED_VECTORS_VERSION").write_text("3\n", encoding="utf-8") + (d / "SHARED_VECTORS_VERSION").write_text("4\n", encoding="utf-8") for name, data in files.items(): print(f"{name}: {len(data)} entries") From 3005ed9267ff9405ab643c2aacd40eac55db2cda Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 21:59:06 -0700 Subject: [PATCH 11/11] Live suite: open a call the list says has tasks or a summary; look for a team with calls Co-Authored-By: Claude Fable 5.2 --- tests/live/test_live.py | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/tests/live/test_live.py b/tests/live/test_live.py index 7029ece..a05af27 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -453,9 +453,16 @@ def test_conversation_layer_on_real_data(frontline): whens = [b.when for b in briefs if b.when] assert whens == sorted(whens, reverse=True) # newest first - first = conv.brief(briefs[0].id) + # Open the call most likely to exercise the detail fields: one the list says has tasks, else one with a summary. + with_tasks = next((b for b in briefs if (b.task_count or 0) > 0), None) + with_summary = next((b for b in briefs if b.summary), None) + chosen = with_tasks or with_summary or briefs[0] + steps["brief chosen"] = "with tasks" if with_tasks else "with summary" if with_summary else "first" + first = conv.brief(chosen.id) _brief_ok(first) - assert first.id == briefs[0].id + assert first.id == chosen.id + if with_tasks: + assert len(first.tasks) >= 1 # the list said this call has tasks: the detail must carry them ref = conv.reference(first) assert (ref.kind, ref.id, ref.link) == ("call", first.id, first.link) transcript = conv.transcript(first.id) @@ -499,14 +506,20 @@ def test_conversation_layer_on_real_data(frontline): assert len(tasks) <= 200 and all(isinstance(t, ic.conversations.TaskBrief) and t.id for t in tasks) steps["open tasks"] = len(tasks) - if teams: - view = conv.team_view(teams[0], since=NOW - timedelta(days=2)) - assert view.team == teams[0].location_id and all(isinstance(v, int) for v in view.counts.values()) - for b in view.briefs: - _brief_ok(b) - for a in view.alerts: - _alert_ok(a) - steps["team view"] = f"ran, {len(view.briefs)} briefs, {len(view.alerts)} alerts" + real_teams = [t for t in teams if t.kind == "team"][:5] + if real_teams: + tried = 0 + for t in real_teams: # up to five teams, stopping at the first with calls in the window + tried += 1 + view = conv.team_view(t, since=NOW - timedelta(days=2)) + assert view.team == t.location_id and all(isinstance(v, int) for v in view.counts.values()) + for b in view.briefs: + _brief_ok(b) + for a in view.alerts: + _alert_ok(a) + if view.briefs: + break + steps["team view"] = f"ran, {len(view.briefs)} briefs, {len(view.alerts)} alerts, {tried} tried" else: steps["team view"] = "no teams"