pusharmor 0.0.45__tar.gz → 0.0.48__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pusharmor
3
- Version: 0.0.45
3
+ Version: 0.0.48
4
4
  Summary: PushArmor command-line client
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://pusharmor.com
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pusharmor
3
- Version: 0.0.45
3
+ Version: 0.0.48
4
4
  Summary: PushArmor command-line client
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://pusharmor.com
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- # PushArmor command-line client, version 0.0.45
2
+ # PushArmor command-line client, version 0.0.48
3
3
  """PushArmor command-line client.
4
4
 
5
5
  The top part is the core layer: encodings, keys, signed requests, HPKE,
@@ -42,7 +42,7 @@ except BaseException: # missing, or broken: no _cffi_backend is ImportError, a
42
42
  sys.stderr.write("error: " + CRYPTO_MISSING + "\n")
43
43
  sys.exit(1)
44
44
 
45
- VERSION = "0.0.45"
45
+ VERSION = "0.0.48"
46
46
  USER_AGENT = "PushArmor-CLI/" + VERSION
47
47
 
48
48
  # ---- encodings ----
@@ -906,6 +906,7 @@ import secrets
906
906
  import shlex
907
907
  import shutil
908
908
  import socket
909
+ import ssl
909
910
  import stat
910
911
  import string
911
912
  import subprocess
@@ -946,7 +947,7 @@ LINK_LIFE_S = 600
946
947
  PROBE_WAIT_S = 30
947
948
  PAIR_WAIT_S = 600
948
949
  LISTEN_TIMEOUT_S = 120 # ntfy sends a keepalive every 45 s
949
- WAIT_TIMEOUT_S = 15 # login and pair: short reads, so a wait ends on time
950
+ WAIT_TIMEOUT_S = 60 # login and pair: above the 45 s keepalive, so an idle read is not cut short
950
951
  LISTEN_REPORT_S = 86400
951
952
  FETCH_GAP_S = 60
952
953
  PLATFORMS = {"android": "Android", "ios": "iPhone", "chrome": "Chrome", "firefox": "Firefox", "cli": "Command line"}
@@ -955,9 +956,11 @@ REC_KEYS = ("from", "name", "platform", "type", "body", "date")
955
956
  NOT_LOGGED_IN = "This device is not logged in. Run: `pusharmor login`"
956
957
  LOGGED_OUT = "This device is logged out. Log in to resume."
957
958
  REMOVED = "This device was removed from the account. Log in again."
959
+ CERT_BAD = "The relay server's certificate could not be verified. Check this device's date and time, proxy, and CA certificates."
958
960
  UNREACHABLE = "The relay server could not be reached. Check your internet connection and try again."
959
961
  SERVER_DOWN = "The relay server is not working right now. Try again later."
960
- TOO_OLD = "This version of PushArmor is too old. " + UPDATE_REQUIRED
962
+ TOO_OLD = ("This version of PushArmor is too old. " + UPDATE_REQUIRED + " "
963
+ "Update: pipx upgrade pusharmor (or download it from https://pusharmor.com/download)")
961
964
  CLOCK_OFF = "This device's clock is off by more than 5 minutes. Fix the clock and try again."
962
965
  REFUSED = "The relay server refused the request (HTTP %d)."
963
966
  BAD_LINK = "The login link is not valid. Request a new code and try again."
@@ -1561,15 +1564,28 @@ def ntfy_open(url, timeout):
1561
1564
  raise OSError(str(e)) from e
1562
1565
 
1563
1566
 
1567
+ def is_cert_error(e):
1568
+ """True for a TLS certificate failure, bare or wrapped in URLError.reason."""
1569
+ return isinstance(e, ssl.SSLCertVerificationError) or isinstance(getattr(e, "reason", None), ssl.SSLCertVerificationError)
1570
+
1571
+
1572
+ def _why(e):
1573
+ return e.reason() if isinstance(e, ApiError) else str(e)
1574
+
1575
+
1576
+ RETRY_WAITS = (1, 3) # seconds slept before the 2nd and 3rd try of a 5xx or network failure
1577
+
1578
+
1564
1579
  class Api:
1565
1580
  def __init__(self, server, keys=None):
1566
1581
  self.base = server.rstrip("/")
1567
1582
  self.keys = keys
1568
1583
  self.skew_ms = 0
1569
1584
  self.push_missing = False
1585
+ self.sleep = lambda s: time.sleep(s) # injectable; tests replace it
1570
1586
 
1571
1587
  def call(self, method, path, body=None, with_id=True, signed=True, tries=3):
1572
- """Signed JSON call -> reply object. 426 and network/5xx/429 (after tries) raise Fail;
1588
+ """Pass tries=1 for a call that is not safe to repeat. Signed JSON call -> reply object. 426 and network/5xx/429 (after tries) raise Fail;
1573
1589
  other non-2xx raise ApiError. One retry after a clock skew 401, PA-Time resynced from PA-Epoch."""
1574
1590
  raw = json.dumps(body, separators=(",", ":")).encode() if body is not None else b""
1575
1591
  skewed, attempt = False, 0
@@ -1585,7 +1601,9 @@ class Api:
1585
1601
  h["PA-ID"] = self.keys["id"]
1586
1602
  try:
1587
1603
  status, hdrs, data = http_request(method, self.base + path, h, raw or None)
1588
- except OSError:
1604
+ except OSError as e:
1605
+ if is_cert_error(e):
1606
+ raise TempFail(CERT_BAD, 0) # a retry cannot fix it
1589
1607
  status, hdrs, data = 0, {}, b""
1590
1608
  try:
1591
1609
  j = json.loads(data) if data else {}
@@ -1603,7 +1621,7 @@ class Api:
1603
1621
  attempt += 1
1604
1622
  if attempt < tries:
1605
1623
  ra = j.get("retry_after")
1606
- time.sleep(min(ra if type(ra) is int and ra > 0 else 2 ** attempt, 60))
1624
+ self.sleep(min(ra if type(ra) is int and ra > 0 else RETRY_WAITS[attempt - 1], 60))
1607
1625
  continue
1608
1626
  if status == 0:
1609
1627
  raise TempFail(UNREACHABLE, 0)
@@ -1625,6 +1643,29 @@ NTFY_LINE_CAP = 65536 # far above the largest push; a longer line is skipped, n
1625
1643
  MAX_REPLY = 1 << 20 # a longer relay server reply counts as a network failure
1626
1644
 
1627
1645
 
1646
+ def read_line(resp, cap):
1647
+ """resp.readline(cap). On Windows a blocked read ignores Ctrl+C until its timeout, so the read runs in a
1648
+ daemon thread and the main thread waits in short slices, where Ctrl+C is seen at once."""
1649
+ if os.name != "nt":
1650
+ return resp.readline(cap)
1651
+ box = []
1652
+
1653
+ def run():
1654
+ try:
1655
+ box.append((True, resp.readline(cap)))
1656
+ except BaseException as e:
1657
+ box.append((False, e))
1658
+
1659
+ t = threading.Thread(target=run, daemon=True)
1660
+ t.start()
1661
+ while t.is_alive():
1662
+ t.join(0.2)
1663
+ ok, v = box[0]
1664
+ if not ok:
1665
+ raise v
1666
+ return v
1667
+
1668
+
1628
1669
  class Stream:
1629
1670
  def __init__(self, ntfy, topic, keys, since, timeout, poll=False):
1630
1671
  self.url = ntfy.rstrip("/") + "/" + topic + "/json"
@@ -1661,7 +1702,7 @@ class Stream:
1661
1702
  self.delay = True
1662
1703
  continue
1663
1704
  try:
1664
- line = self.resp.readline(NTFY_LINE_CAP)
1705
+ line = read_line(self.resp, NTFY_LINE_CAP)
1665
1706
  except (TimeoutError, socket.timeout):
1666
1707
  self.close(False)
1667
1708
  continue
@@ -1673,7 +1714,6 @@ class Stream:
1673
1714
  if self.poll:
1674
1715
  return None
1675
1716
  continue
1676
- self.backoff = 1
1677
1717
  was_long, self.in_long_line = self.in_long_line, not line.endswith(b"\n")
1678
1718
  if was_long or self.in_long_line:
1679
1719
  continue
@@ -1683,6 +1723,7 @@ class Stream:
1683
1723
  continue
1684
1724
  if not isinstance(ev, dict) or ev.get("event") != "message":
1685
1725
  continue
1726
+ self.backoff = 1
1686
1727
  if isinstance(ev.get("id"), str):
1687
1728
  self.since = ev["id"]
1688
1729
  try:
@@ -1819,8 +1860,10 @@ class Ctx:
1819
1860
 
1820
1861
  def refresh_soon(self):
1821
1862
  if time.time() - self.last_fetch >= FETCH_GAP_S:
1822
- with contextlib.suppress(ApiError, TempFail):
1863
+ try:
1823
1864
  self.refresh()
1865
+ except (ApiError, TempFail) as e:
1866
+ log("warning", "Could not refresh the device list: %s" % _why(e))
1824
1867
 
1825
1868
 
1826
1869
  def _ids(xs):
@@ -1910,6 +1953,7 @@ def reconcile_allow(cx):
1910
1953
  if e.status == 401:
1911
1954
  raise
1912
1955
  if e.status != 400:
1956
+ log("warning", "Could not withdraw a device from the allow list: %s" % _why(e))
1913
1957
  continue
1914
1958
  with cx.store.state() as d:
1915
1959
  d["my_allow"] = [x for x in d["my_allow"] if x != i]
@@ -2211,7 +2255,7 @@ def on_open(cx, d, e, p, o, notes):
2211
2255
  def post_pair(cx, x, kind, c):
2212
2256
  """POST /v1/pair/X once -> result word (sent, denied, not listening, ...)."""
2213
2257
  try:
2214
- j = cx.api.call("POST", "/v1/pair/" + x, {"k": kind, "c": c}, tries=1)
2258
+ j = cx.api.call("POST", "/v1/pair/" + x, {"k": kind, "c": c})
2215
2259
  except TempFail as e:
2216
2260
  return "network" if e.status == 0 else str(e.status)
2217
2261
  except ApiError as e:
@@ -2339,7 +2383,8 @@ def sweep(cx):
2339
2383
  with cx.store.state(write=False) as d:
2340
2384
  ok = d["peers"].get(x, {}).get("approve_verified")
2341
2385
  i["resend"] = "200_c_verified" if ok else "200_other"
2342
- except (TempFail, ApiError, ValueError):
2386
+ except (TempFail, ApiError, ValueError) as err:
2387
+ log("warning", "Could not resend the pairing approval: %s" % _why(err))
2343
2388
  i["resend"] = "offline"
2344
2389
  a = pair_timeout(i)
2345
2390
  if a in ("keep_waiting", "resend"):
@@ -2523,7 +2568,7 @@ def register(cx, code):
2523
2568
  cx.topic = new_topic()
2524
2569
  ntfy = cx.settings.get("ntfy", DEFAULT_NTFY)
2525
2570
  d0 = {"ntfy": ntfy, "topic": cx.topic}
2526
- stream = Stream(ntfy, cx.topic, k, "", WAIT_TIMEOUT_S)
2571
+ stream = Stream(ntfy, cx.topic, k, str(int(time.time()) - 30), WAIT_TIMEOUT_S) # since: a probe sent just before the connect is kept
2527
2572
  try:
2528
2573
  stream.connect()
2529
2574
  except OSError:
@@ -2540,7 +2585,7 @@ def register_with(cx, code, stream, push, ntfy):
2540
2585
  "push": push}
2541
2586
  while True:
2542
2587
  try:
2543
- j = cx.api.call("POST", "/v1/peers", body, with_id=False, tries=1)
2588
+ j = cx.api.call("POST", "/v1/peers", body, with_id=False)
2544
2589
  break
2545
2590
  except ApiError as e:
2546
2591
  if e.status != 409 or e.error != "peer limit" or not isinstance(e.body.get("ticket"), str):
@@ -2676,7 +2721,7 @@ def resolve_peer(cx, text, with_self=False):
2676
2721
 
2677
2722
  def peer_status(p, e):
2678
2723
  if p["pinned"] and p["ruling"] == "approved" and p["approves_me"]:
2679
- return "paired" + (", logged out" if p["logged_out"] else ", send only" if not p["listening"] else "")
2724
+ return "paired" + (", logged out" if p["logged_out"] else ", not listening" if not p["listening"] else "")
2680
2725
  if e and e["state"] == "shown" and not e["approved"]:
2681
2726
  return "compare fingerprint " + e["fingerprint"]
2682
2727
  if p["pinned"] and p["ruling"] == "approved":
@@ -2949,7 +2994,7 @@ def cmd_send(cx, args):
2949
2994
  # /v1/send, /v1/pair, and /v1/approve result word -> reason for one device (%s: its name).
2950
2995
  SEND_WHY = {"gone": '"%s" needs attention. Open PushArmor on it to resolve.',
2951
2996
  "logged out": '"%s" is logged out. Log in on it to receive messages.',
2952
- "not listening": '"%s" is set to send only. It does not receive messages.',
2997
+ "not listening": '"%s" has not listened recently. Run `pusharmor listen` on it.',
2953
2998
  "unapproved": '"%s" is not paired with this device. Pair with it to send it messages.',
2954
2999
  "denied": '"%s" is not paired with this device.', "unknown": '"%s" is no longer on this account.'}
2955
3000
  SEND_FAILED = 'The push service of "%s" did not accept the message. Try again later.' # failed:CODE
@@ -343,7 +343,7 @@ def test_426_update(monkeypatch):
343
343
  monkeypatch.setattr(pa, "http_request", lambda *a: (426, {}, b'{"error":"update required"}'))
344
344
  with pytest.raises(pa.Fail) as e:
345
345
  pa.Api("https://r.example", {"id": "x", "sign": pa.new_key()[0]}).call("GET", "/v1/peers")
346
- assert str(e.value) == "This version of PushArmor is too old. Update PushArmor to continue." and e.value.code == 1
346
+ assert str(e.value) == "This version of PushArmor is too old. Update PushArmor to continue. Update: pipx upgrade pusharmor (or download it from https://pusharmor.com/download)" and e.value.code == 1
347
347
 
348
348
 
349
349
  def test_clock_skew_resync(monkeypatch):
@@ -361,6 +361,37 @@ def test_clock_skew_resync(monkeypatch):
361
361
  assert len(seen) == 2 and abs(seen[1] - 2000000000000) < 5000 and len(str(seen[1])) == 13
362
362
 
363
363
 
364
+ def test_certificate_failure_named(monkeypatch):
365
+ import ssl
366
+ import urllib.error
367
+ calls = []
368
+
369
+ def bad(*a):
370
+ calls.append(1)
371
+ raise urllib.error.URLError(ssl.SSLCertVerificationError("certificate verify failed"))
372
+
373
+ monkeypatch.setattr(pa, "http_request", bad)
374
+ with pytest.raises(pa.TempFail) as e:
375
+ pa.Api("https://r.example", {"id": "x", "sign": pa.new_key()[0]}).call("GET", "/v1/peers")
376
+ assert str(e.value) == pa.CERT_BAD and "internet" not in str(e.value) and len(calls) == 1
377
+ assert pa.is_cert_error(ssl.SSLCertVerificationError("x")) and not pa.is_cert_error(OSError("x"))
378
+
379
+
380
+ def test_read_line_windows_waits_in_slices(monkeypatch):
381
+ class Slow:
382
+ def readline(self, cap):
383
+ time.sleep(0.3)
384
+ return b"x\n"
385
+
386
+ class Os:
387
+ name = "nt"
388
+
389
+ monkeypatch.setattr(pa, "os", Os)
390
+ assert pa.read_line(Slow(), 10) == b"x\n"
391
+ monkeypatch.undo()
392
+ assert pa.WAIT_TIMEOUT_S >= 60
393
+
394
+
364
395
  def test_temporary_failures(monkeypatch):
365
396
  monkeypatch.setattr(pa.time, "sleep", lambda s: None)
366
397
  calls = []
@@ -1821,7 +1852,7 @@ def _offline(*a):
1821
1852
  ((429, {"error": "rate limited", "retry_after": 120}), pa.EXIT_TEMP, "Too many tries. Try again in 2 minutes."),
1822
1853
  ((429, {"error": "rate limited", "retry_after": 30}), pa.EXIT_TEMP, "Too many tries. Try again in 30 seconds."),
1823
1854
  ((426, {"error": "update required"}), pa.EXIT_ERR,
1824
- "This version of PushArmor is too old. Update PushArmor to continue."),
1855
+ "This version of PushArmor is too old. Update PushArmor to continue. Update: pipx upgrade pusharmor (or download it from https://pusharmor.com/download)"),
1825
1856
  ((401, {"error": "clock skew"}), pa.EXIT_ERR,
1826
1857
  "This device's clock is off by more than 5 minutes. Fix the clock and try again."),
1827
1858
  ((401, {"error": "logged out"}), pa.EXIT_LOGIN, "This device is logged out. Log in to resume."),
@@ -1857,7 +1888,7 @@ def test_not_logged_in_is_one_line(tmp_path, capsys):
1857
1888
  @pytest.mark.parametrize("word, line", [
1858
1889
  ("gone", '"%s" needs attention. Open PushArmor on it to resolve.'),
1859
1890
  ("logged out", '"%s" is logged out. Log in on it to receive messages.'),
1860
- ("not listening", '"%s" is set to send only. It does not receive messages.'),
1891
+ ("not listening", '"%s" has not listened recently. Run `pusharmor listen` on it.'),
1861
1892
  ("unapproved", '"%s" is not paired with this device. Pair with it to send it messages.'),
1862
1893
  ("denied", '"%s" is not paired with this device.'),
1863
1894
  ("unknown", '"%s" is no longer on this account.'),
@@ -2355,3 +2386,86 @@ def test_requests_send_user_agent():
2355
2386
 
2356
2387
  def test_api_error_426_says_update():
2357
2388
  assert pa.ApiError(426, "", {}).reason() == pa.TOO_OLD
2389
+
2390
+
2391
+ def test_retry_schedule_1s_3s_injected_sleeper(monkeypatch):
2392
+ monkeypatch.setattr(pa.time, "sleep", lambda s: pytest.fail("real sleep"))
2393
+ monkeypatch.setattr(pa, "http_request", lambda *a: (503, {}, b""))
2394
+ api = pa.Api("https://r.example", {"id": "x", "sign": pa.new_key()[0]})
2395
+ waits = []
2396
+ api.sleep = waits.append
2397
+ with pytest.raises(pa.TempFail):
2398
+ api.call("POST", "/v1/send", {"v": 1})
2399
+ assert waits == [1, 3]
2400
+ waits.clear()
2401
+ with pytest.raises(pa.TempFail):
2402
+ api.call("POST", "/v1/send", {"v": 1}, tries=1)
2403
+ assert waits == []
2404
+
2405
+
2406
+ def test_pair_and_register_calls_retry(monkeypatch):
2407
+ calls = []
2408
+
2409
+ def down(*a):
2410
+ calls.append(1)
2411
+ return 500, {}, b""
2412
+
2413
+ monkeypatch.setattr(pa, "http_request", down)
2414
+ api = pa.Api("https://r.example", {"id": "x", "sign": pa.new_key()[0]})
2415
+ api.sleep = lambda s: None
2416
+
2417
+ class Cx:
2418
+ pass
2419
+
2420
+ cx = Cx()
2421
+ cx.api = api
2422
+ assert pa.post_pair(cx, "x", "a", "c") == "500"
2423
+ assert len(calls) == 3
2424
+
2425
+
2426
+ def _stream_with(monkeypatch, lines):
2427
+ st = pa.Stream("https://n.example", "t", {}, None, 5)
2428
+ it = iter(lines)
2429
+
2430
+ class R:
2431
+ def readline(self, n):
2432
+ return next(it, b"")
2433
+
2434
+ def close(self):
2435
+ pass
2436
+
2437
+ st.resp = R()
2438
+ monkeypatch.setattr(pa.time, "sleep", lambda s: None)
2439
+ return st
2440
+
2441
+
2442
+ def test_stream_backoff_resets_only_on_message(monkeypatch):
2443
+ st = _stream_with(monkeypatch, [b'{"event":"open"}\n', b'{"event":"keepalive"}\n'])
2444
+ st.backoff = 8
2445
+ st.poll = True
2446
+ assert st.next() is None
2447
+ assert st.backoff == 8
2448
+ st = _stream_with(monkeypatch, [b'{"event":"message","message":"x"}\n'])
2449
+ st.backoff = 8
2450
+ st.poll = True
2451
+ st.next()
2452
+ assert st.backoff == 1
2453
+
2454
+
2455
+ def test_reconcile_failure_is_reported(monkeypatch, capsys):
2456
+ cx = type("Cx", (), {})()
2457
+
2458
+ class St:
2459
+ def state(self, write=True):
2460
+ import contextlib
2461
+ d = {"my_allow": ["a"], "peers": {}}
2462
+ return contextlib.nullcontext(d)
2463
+
2464
+ cx.store = St()
2465
+
2466
+ def boom(*a, **k):
2467
+ raise pa.ApiError(500, "oops", {})
2468
+
2469
+ cx.api = type("A", (), {"call": staticmethod(boom)})()
2470
+ pa.reconcile_allow(cx)
2471
+ assert "warning: Could not withdraw" in capsys.readouterr().err
File without changes
File without changes
File without changes