Files
tinker_tickets/tests/api/test_api.py
T

260 lines
16 KiB
Python
Raw Normal View History

"""API contract tests for the Bearer endpoints automated reporters use
(gandalf, hwmonDaemon, thor): create_ticket_api.php dedup and recurrence
(#116, #123, #126), lookup by dedup_key, the source filter and the link API.
Runs against a Tinker instance started by tests/ui/stack.sh on a throwaway
database (name starting with tinker_ui) with keys from tests/api/fixtures.php:
tests/ui/stack.sh . 8400 tinker_ui_api
php tests/api/fixtures.php /tmp/api-keys.json
python3 tests/api/test_api.py
Environment (defaults in brackets):
TINKER_API_URL the instance [http://127.0.0.1:8400]
TINKER_API_DB its database, must start with tinker_ui [tinker_ui_api]
TINKER_API_KEYS the keys file fixtures.php wrote [/tmp/api-keys.json]
TINKER_CACHE_DIR the server's temp dir, for the workflow cache [/tmp]
The database is read and changed directly with the mariadb client over the
local socket (as root in CI). Every check runs under three Workflow Designer
setups for Closed -> Open: "prod" (admin + comment, as on production), "open"
(no requirements) and "none" (no such transition: noted, stays Closed).
Synthetic data only.
"""
import concurrent.futures
import hashlib
import json
import os
import pathlib
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
BASE = os.environ.get("TINKER_API_URL", "http://127.0.0.1:8400")
DB = os.environ.get("TINKER_API_DB", "tinker_ui_api")
KEYS = json.loads(pathlib.Path(os.environ.get("TINKER_API_KEYS", "/tmp/api-keys.json")).read_text())
CACHE = pathlib.Path(os.environ.get("TINKER_CACHE_DIR", "/tmp")) / "tinker_tickets_cache"
ROOT = pathlib.Path(__file__).resolve().parents[2]
if not DB.startswith("tinker_ui"):
sys.exit("refusing: TINKER_API_DB must start with tinker_ui")
results = []
def check(name, ok, detail=""):
results.append(ok)
print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" {detail}"), flush=True)
def call(method, path, body=None, key="thor"):
req = urllib.request.Request(BASE + path, method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Authorization": f"Bearer {KEYS[key]}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw)
except ValueError:
return e.code, raw.decode()
def sql(q):
out = subprocess.run(["mariadb", "-N", "-B", DB, "-e", q], capture_output=True, text=True, check=True).stdout
return [line.split("\t") for line in out.strip().splitlines()] if out.strip() else []
def one(q):
rows = sql(q)
return rows[0][0] if rows else None
def create(title, key="thor", **extra):
return call("POST", "/create_ticket_api.php", {"title": title, "description": "synthetic test", "priority": 3,
"category": "Hardware", "type": "Issue", **extra}, key)
def legacy_hash(title):
php = f"require {json.dumps(str(ROOT / 'helpers/TicketHash.php'))}; echo TicketHash::generate(['title' => {json.dumps(title)}]);"
return subprocess.run(["php", "-r", php], capture_output=True, text=True, check=True).stdout
def run_mode(MODE):
"""One pass of every check under one Closed -> Open workflow setup."""
print(f"== workflow: {MODE}", flush=True)
REOPEN = "recurrence_noted" if MODE == "none" else "reopened"
# The app caches workflow transitions for 10 minutes in its temp dir.
shutil.rmtree(CACHE, ignore_errors=True)
# clean slate for this test's data, and the workflow for this mode
sql("DELETE FROM status_transitions WHERE from_status='Closed'")
sql("INSERT INTO status_transitions (from_status,to_status,requires_comment,requires_admin,is_active) VALUES "
"('Closed','In Progress',0,1,1),('Closed','Open',%d,%d,%d)" % ((0, 0, 1) if MODE == "open" else (1, 1, 0 if MODE == "none" else 1)))
sql("DELETE FROM ticket_dependencies WHERE ticket_id IN (SELECT ticket_id FROM tickets WHERE description='synthetic test') "
"OR depends_on_id IN (SELECT ticket_id FROM tickets WHERE description='synthetic test')")
sql("DELETE FROM ticket_comments WHERE ticket_id IN (SELECT ticket_id FROM tickets WHERE description='synthetic test')")
sql("DELETE FROM tickets WHERE description='synthetic test' OR dedup_key LIKE 'cluster:ceph:%'")
KEY = "host:test-node-01:oom"
T = "[test-node-01][auto][thor][software] Out of memory: CT 999 [single-node][production][issue]"
# 1. keyed create
st, r = create(T, dedup_key=KEY)
A = r.get("ticket_id")
check("keyed create -> created", st == 200 and r.get("action") == "created", r)
row = sql(f"SELECT source, dedup_key, hash, recurrence_of FROM tickets WHERE ticket_id='{A}'")[0]
check("source, dedup_key and key hash stored",
row[:2] == ["thor", KEY] and row[2] == hashlib.sha256(("key:" + KEY).encode()).hexdigest() and row[3] == "NULL", row)
# 2. same key, different title, higher severity -> escalation on the same ticket, comment by thor
st, r = create("[test-node-01][auto][thor][software] Out of memory again, worse", dedup_key=KEY, priority=2)
check("same key, new title -> same ticket updated", r.get("ticket_id") == A and r.get("action") == "updated", r)
c = sql(f"SELECT user_name, comment_text FROM ticket_comments WHERE ticket_id='{A}' ORDER BY comment_id DESC LIMIT 1")
check("escalation comment is by thor and names thor", c and c[0][0] == "thor" and c[0][1].startswith("**thor raised priority"), c)
# 3. invalid key
st, r = create(T, dedup_key="Host:Bad Key!")
check("invalid dedup_key -> 400", st == 400, (st, r))
# 4. legacy keyless create by gandalf
LT = "[test-node-02][auto][production][issue][network][single-node] Interface eth9 link-down"
st, r = create(LT, key="gandalf")
G = r.get("ticket_id")
row = sql(f"SELECT source, dedup_key, hash FROM tickets WHERE ticket_id='{G}'")[0]
check("keyless create keeps the legacy hash, source gandalf",
row[0] == "gandalf" and row[1] == "NULL" and row[2] == legacy_hash(LT), row)
# 5. closed 2 days ago -> reopened, comment by thor
sql(f"UPDATE tickets SET status='Closed', closed_at=NOW() - INTERVAL 2 DAY, created_at=NOW() - INTERVAL 25 DAY WHERE ticket_id='{A}'")
st, r = create(T, dedup_key=KEY)
check(f"closed 2 days ago -> {REOPEN}", r.get("ticket_id") == A and r.get("action") == REOPEN, r)
check("status after that report", one(f"SELECT status FROM tickets WHERE ticket_id='{A}'") == ("Closed" if MODE == "none" else "Open"))
c = sql(f"SELECT user_name, comment_text FROM ticket_comments WHERE ticket_id='{A}' ORDER BY comment_id DESC LIMIT 1")
check("recurrence comment by thor", c and c[0][0] == "thor" and "thor detected this condition again" in c[0][1], c)
if MODE == "none":
check("note says the ticket stays Closed", c and c[0][1].startswith("**Issue recurred; the ticket stays Closed.**"), c)
n_before = one(f"SELECT COUNT(*) FROM ticket_comments WHERE ticket_id='{A}'")
st, r = create(T, dedup_key=KEY)
check("second report while Closed -> recurrence_noted again", r.get("action") == "recurrence_noted", r)
check("no second note in the same closed period", one(f"SELECT COUNT(*) FROM ticket_comments WHERE ticket_id='{A}'") == n_before)
check("both reports audited", one(f"SELECT COUNT(*) FROM audit_log WHERE entity_id='{A}' AND details LIKE '%recurrence detected but%'") == "2")
else:
check("reopen audit names the workflow skip",
"skips the Workflow Designer" in (one(f"SELECT details FROM audit_log WHERE entity_type='ticket' AND entity_id='{A}' ORDER BY audit_id DESC LIMIT 1") or ""))
# 6. closed 10 days ago -> new_recurrence
sql(f"UPDATE tickets SET status='Closed', closed_at=NOW() - INTERVAL 10 DAY WHERE ticket_id='{A}'")
st, r = create(T, dedup_key=KEY)
B = r.get("ticket_id")
check("closed 10 days ago -> new_recurrence", st == 200 and r.get("action") == "new_recurrence" and r.get("previous_ticket_id") == A and B != A, r)
check("old ticket gave up the hash, kept its key",
sql(f"SELECT hash, dedup_key, status FROM tickets WHERE ticket_id='{A}'")[0] == ["NULL", KEY, "Closed"])
check("new ticket holds hash, key, source, recurrence_of",
sql(f"SELECT dedup_key, source, recurrence_of, hash FROM tickets WHERE ticket_id='{B}'")[0]
== [KEY, "thor", A, hashlib.sha256(("key:" + KEY).encode()).hexdigest()])
check("relates_to link new -> old",
one(f"SELECT COUNT(*) FROM ticket_dependencies WHERE ticket_id='{B}' AND depends_on_id='{A}' AND dependency_type='relates_to'") == "1")
h = sql(f"SELECT user_name, comment_text FROM ticket_comments WHERE ticket_id='{B}'")
# chain: A created 25 days ago, auto-reopened today (step 5), B created today
# ("none": two noted reports instead of one reopen)
W, M = (3, 4) if MODE == "none" else (2, 3)
check(f"history comment: recurrence of A, {W} in 7 days, {M} in 30 days",
len(h) == 1 and h[0][0] == "thor" and h[0][1].startswith(f"**Recurrence of #{A}.**")
and f"Seen {W} times in the last 7 days and {M} times in the last 30 days" in h[0][1], h)
check("old ticket audit says where it continued",
f"continued in {B}" in (one(f"SELECT details FROM audit_log WHERE entity_type='ticket' AND entity_id='{A}' ORDER BY audit_id DESC LIMIT 1") or ""))
st, r = create(T, dedup_key=KEY)
check("next report dedups onto the new ticket", r.get("ticket_id") == B and r.get("action") in ("deduplicated", "updated"), r)
# 7. legacy (keyless) recurrence too
sql(f"UPDATE tickets SET status='Closed', closed_at=NOW() - INTERVAL 30 DAY WHERE ticket_id='{G}'")
st, r = create(LT, key="gandalf")
G2 = r.get("ticket_id")
check("keyless report after the window -> new_recurrence",
r.get("action") == "new_recurrence" and r.get("previous_ticket_id") == G, r)
check("keyless recurrence: hash moved, no key", sql(f"SELECT hash, dedup_key, recurrence_of FROM tickets WHERE ticket_id='{G2}'")[0]
== [legacy_hash(LT), "NULL", G] and one(f"SELECT hash FROM tickets WHERE ticket_id='{G}'") == "NULL")
# 7b. closed_at missing: falls back to updated_at
sql(f"UPDATE tickets SET status='Closed', closed_at=NULL, updated_at=NOW() - INTERVAL 1 DAY WHERE ticket_id='{G2}'")
st, r = create(LT, key="gandalf")
check(f"closed without closed_at, updated yesterday -> {REOPEN}", r.get("ticket_id") == G2 and r.get("action") == REOPEN, r)
# 8. concurrency: 8 identical new keyed reports at once -> one ticket
CK = "host:test-node-03:disk"
with concurrent.futures.ThreadPoolExecutor(8) as ex:
outs = list(ex.map(lambda _: create("[test-node-03][auto][thor][storage] Disk full", dedup_key=CK), range(8)))
ids = {o[1].get("ticket_id") for o in outs}
check("8 concurrent identical creates -> 1 ticket, all 200",
len(ids) == 1 and all(o[0] == 200 for o in outs) and one(f"SELECT COUNT(*) FROM tickets WHERE dedup_key='{CK}'") == "1",
[o for o in outs])
# 8b. upper case keys are allowed and case-sensitive
UK = "cluster:ceph:BLUESTORE_SLOW_OP_ALERT"
st, r1 = create("[proxmox-cluster][auto][thor][ceph] BlueStore slow ops", dedup_key=UK)
st2, r2 = create("[proxmox-cluster][auto][thor][ceph] BlueStore slow ops", dedup_key=UK.lower())
check("upper case key accepted; lower-case variant is a different key",
st == 200 and st2 == 200 and r1.get("action") == "created" and r2.get("action") == "created"
and r1.get("ticket_id") != r2.get("ticket_id"), (r1, r2))
st, r = call("GET", f"/api/tickets_api.php?dedup_key={UK}", key="reader")
check("lookup is case-sensitive", st == 200 and r["ticket"]["ticket_id"] == r1.get("ticket_id"), (st, r))
# 9. lookup by key
st, r = call("GET", f"/api/tickets_api.php?dedup_key={KEY}", key="reader")
check("lookup by key (read key) -> newest ticket + recurrences",
st == 200 and r["ticket"]["ticket_id"] == B and r["recurrences"] == [A] and r["ticket"]["source"] == "thor", (st, r if st != 200 else r["recurrences"]))
st, r = call("GET", "/api/tickets_api.php?dedup_key=host:nothing:here", key="reader")
check("lookup miss -> 404", st == 404, (st, r))
st, r = call("GET", "/api/tickets_api.php?dedup_key=BAD%20KEY", key="reader")
check("lookup invalid key -> 400", st == 400, (st, r))
sql(f"UPDATE tickets SET visibility='confidential' WHERE ticket_id='{B}'")
st, r = call("GET", f"/api/tickets_api.php?dedup_key={KEY}", key="reader")
check("confidential match, public-only key -> 404", st == 404, (st, r))
st, r = call("GET", f"/api/tickets_api.php?dedup_key={KEY}", key="allseeing")
check("confidential match, see-all key -> 200", st == 200 and r["ticket"]["ticket_id"] == B, st)
# 10. source filter on the list
st, r = call("GET", "/api/tickets_api.php?status=Open,Closed&source=gandalf&limit=100", key="allseeing")
srcs = {t["source"] for t in r.get("tickets", [])}
check("list ?source=gandalf only returns gandalf tickets", st == 200 and srcs == {"gandalf"}, (st, srcs))
# 11. link API
C = ids.pop()
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "blocks"})
check("link A blocks C -> 200", st == 200 and r == {"success": True, "ticket_id": A, "relation": "blocks", "other_ticket_id": C}, (st, r))
check("link audit records the key name",
'"api_key":"thor"' in (one("SELECT details FROM audit_log WHERE entity_type='dependency' AND action_type='create' ORDER BY audit_id DESC LIMIT 1") or ""))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "blocks"})
check("same link again -> 409", st == 409, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": C, "other_ticket_id": A, "relation": "blocked_by"})
check("inverse of an existing link -> 409", st == 409, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": C, "other_ticket_id": A, "relation": "blocks"})
check("circular blocking -> 409", st == 409, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": C, "other_ticket_id": A, "relation": "blocked_by", "action": "unlink"})
check("unlink stated from the other side -> removed", st == 200 and r.get("removed") is True, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "blocks", "action": "unlink"})
check("unlink again -> 404", st == 404, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": B, "other_ticket_id": C, "relation": "relates_to"})
check("link to a confidential ticket, public-only key -> 404 not found", st == 404 and r.get("error") == f"Ticket {B} not found", (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": B, "other_ticket_id": C, "relation": "relates_to"}, key="allseeing")
check("same with a see-all key -> 200", st == 200, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "relates_to"}, key="reader")
check("read-only key -> 403", st == 403, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "causes"})
check("bad relation -> 400", st == 400, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": A, "relation": "relates_to"})
check("self link -> 400", st == 400, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": "999999999", "relation": "relates_to"})
check("missing ticket -> 404", st == 404 and r.get("error") == "Ticket 999999999 not found", (st, r))
st, r = call("GET", "/api/ticket_link_api.php")
check("GET -> 405", st == 405, (st, r))
for mode in ("prod", "open", "none"):
run_mode(mode)
print(f"\n{sum(results)} passed, {len(results) - sum(results)} failed")
sys.exit(0 if results and all(results) else 1)