pusharmor 0.0.45__tar.gz → 0.0.47__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.47
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.47
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.47
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.47"
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,6 +956,7 @@ 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
962
  TOO_OLD = "This version of PushArmor is too old. " + UPDATE_REQUIRED
@@ -1561,15 +1563,28 @@ def ntfy_open(url, timeout):
1561
1563
  raise OSError(str(e)) from e
1562
1564
 
1563
1565
 
1566
+ def is_cert_error(e):
1567
+ """True for a TLS certificate failure, bare or wrapped in URLError.reason."""
1568
+ return isinstance(e, ssl.SSLCertVerificationError) or isinstance(getattr(e, "reason", None), ssl.SSLCertVerificationError)
1569
+
1570
+
1571
+ def _why(e):
1572
+ return e.reason() if isinstance(e, ApiError) else str(e)
1573
+
1574
+
1575
+ RETRY_WAITS = (1, 3) # seconds slept before the 2nd and 3rd try of a 5xx or network failure
1576
+
1577
+
1564
1578
  class Api:
1565
1579
  def __init__(self, server, keys=None):
1566
1580
  self.base = server.rstrip("/")
1567
1581
  self.keys = keys
1568
1582
  self.skew_ms = 0
1569
1583
  self.push_missing = False
1584
+ self.sleep = lambda s: time.sleep(s) # injectable; tests replace it
1570
1585
 
1571
1586
  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;
1587
+ """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
1588
  other non-2xx raise ApiError. One retry after a clock skew 401, PA-Time resynced from PA-Epoch."""
1574
1589
  raw = json.dumps(body, separators=(",", ":")).encode() if body is not None else b""
1575
1590
  skewed, attempt = False, 0
@@ -1585,7 +1600,9 @@ class Api:
1585
1600
  h["PA-ID"] = self.keys["id"]
1586
1601
  try:
1587
1602
  status, hdrs, data = http_request(method, self.base + path, h, raw or None)
1588
- except OSError:
1603
+ except OSError as e:
1604
+ if is_cert_error(e):
1605
+ raise TempFail(CERT_BAD, 0) # a retry cannot fix it
1589
1606
  status, hdrs, data = 0, {}, b""
1590
1607
  try:
1591
1608
  j = json.loads(data) if data else {}
@@ -1603,7 +1620,7 @@ class Api:
1603
1620
  attempt += 1
1604
1621
  if attempt < tries:
1605
1622
  ra = j.get("retry_after")
1606
- time.sleep(min(ra if type(ra) is int and ra > 0 else 2 ** attempt, 60))
1623
+ self.sleep(min(ra if type(ra) is int and ra > 0 else RETRY_WAITS[attempt - 1], 60))
1607
1624
  continue
1608
1625
  if status == 0:
1609
1626
  raise TempFail(UNREACHABLE, 0)
@@ -1625,6 +1642,29 @@ NTFY_LINE_CAP = 65536 # far above the largest push; a longer line is skipped, n
1625
1642
  MAX_REPLY = 1 << 20 # a longer relay server reply counts as a network failure
1626
1643
 
1627
1644
 
1645
+ def read_line(resp, cap):
1646
+ """resp.readline(cap). On Windows a blocked read ignores Ctrl+C until its timeout, so the read runs in a
1647
+ daemon thread and the main thread waits in short slices, where Ctrl+C is seen at once."""
1648
+ if os.name != "nt":
1649
+ return resp.readline(cap)
1650
+ box = []
1651
+
1652
+ def run():
1653
+ try:
1654
+ box.append((True, resp.readline(cap)))
1655
+ except BaseException as e:
1656
+ box.append((False, e))
1657
+
1658
+ t = threading.Thread(target=run, daemon=True)
1659
+ t.start()
1660
+ while t.is_alive():
1661
+ t.join(0.2)
1662
+ ok, v = box[0]
1663
+ if not ok:
1664
+ raise v
1665
+ return v
1666
+
1667
+
1628
1668
  class Stream:
1629
1669
  def __init__(self, ntfy, topic, keys, since, timeout, poll=False):
1630
1670
  self.url = ntfy.rstrip("/") + "/" + topic + "/json"
@@ -1661,7 +1701,7 @@ class Stream:
1661
1701
  self.delay = True
1662
1702
  continue
1663
1703
  try:
1664
- line = self.resp.readline(NTFY_LINE_CAP)
1704
+ line = read_line(self.resp, NTFY_LINE_CAP)
1665
1705
  except (TimeoutError, socket.timeout):
1666
1706
  self.close(False)
1667
1707
  continue
@@ -1673,7 +1713,6 @@ class Stream:
1673
1713
  if self.poll:
1674
1714
  return None
1675
1715
  continue
1676
- self.backoff = 1
1677
1716
  was_long, self.in_long_line = self.in_long_line, not line.endswith(b"\n")
1678
1717
  if was_long or self.in_long_line:
1679
1718
  continue
@@ -1683,6 +1722,7 @@ class Stream:
1683
1722
  continue
1684
1723
  if not isinstance(ev, dict) or ev.get("event") != "message":
1685
1724
  continue
1725
+ self.backoff = 1
1686
1726
  if isinstance(ev.get("id"), str):
1687
1727
  self.since = ev["id"]
1688
1728
  try:
@@ -1819,8 +1859,10 @@ class Ctx:
1819
1859
 
1820
1860
  def refresh_soon(self):
1821
1861
  if time.time() - self.last_fetch >= FETCH_GAP_S:
1822
- with contextlib.suppress(ApiError, TempFail):
1862
+ try:
1823
1863
  self.refresh()
1864
+ except (ApiError, TempFail) as e:
1865
+ log("warning", "Could not refresh the device list: %s" % _why(e))
1824
1866
 
1825
1867
 
1826
1868
  def _ids(xs):
@@ -1910,6 +1952,7 @@ def reconcile_allow(cx):
1910
1952
  if e.status == 401:
1911
1953
  raise
1912
1954
  if e.status != 400:
1955
+ log("warning", "Could not withdraw a device from the allow list: %s" % _why(e))
1913
1956
  continue
1914
1957
  with cx.store.state() as d:
1915
1958
  d["my_allow"] = [x for x in d["my_allow"] if x != i]
@@ -2211,7 +2254,7 @@ def on_open(cx, d, e, p, o, notes):
2211
2254
  def post_pair(cx, x, kind, c):
2212
2255
  """POST /v1/pair/X once -> result word (sent, denied, not listening, ...)."""
2213
2256
  try:
2214
- j = cx.api.call("POST", "/v1/pair/" + x, {"k": kind, "c": c}, tries=1)
2257
+ j = cx.api.call("POST", "/v1/pair/" + x, {"k": kind, "c": c})
2215
2258
  except TempFail as e:
2216
2259
  return "network" if e.status == 0 else str(e.status)
2217
2260
  except ApiError as e:
@@ -2339,7 +2382,8 @@ def sweep(cx):
2339
2382
  with cx.store.state(write=False) as d:
2340
2383
  ok = d["peers"].get(x, {}).get("approve_verified")
2341
2384
  i["resend"] = "200_c_verified" if ok else "200_other"
2342
- except (TempFail, ApiError, ValueError):
2385
+ except (TempFail, ApiError, ValueError) as err:
2386
+ log("warning", "Could not resend the pairing approval: %s" % _why(err))
2343
2387
  i["resend"] = "offline"
2344
2388
  a = pair_timeout(i)
2345
2389
  if a in ("keep_waiting", "resend"):
@@ -2523,7 +2567,7 @@ def register(cx, code):
2523
2567
  cx.topic = new_topic()
2524
2568
  ntfy = cx.settings.get("ntfy", DEFAULT_NTFY)
2525
2569
  d0 = {"ntfy": ntfy, "topic": cx.topic}
2526
- stream = Stream(ntfy, cx.topic, k, "", WAIT_TIMEOUT_S)
2570
+ 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
2571
  try:
2528
2572
  stream.connect()
2529
2573
  except OSError:
@@ -2540,7 +2584,7 @@ def register_with(cx, code, stream, push, ntfy):
2540
2584
  "push": push}
2541
2585
  while True:
2542
2586
  try:
2543
- j = cx.api.call("POST", "/v1/peers", body, with_id=False, tries=1)
2587
+ j = cx.api.call("POST", "/v1/peers", body, with_id=False)
2544
2588
  break
2545
2589
  except ApiError as e:
2546
2590
  if e.status != 409 or e.error != "peer limit" or not isinstance(e.body.get("ticket"), str):
@@ -2676,7 +2720,7 @@ def resolve_peer(cx, text, with_self=False):
2676
2720
 
2677
2721
  def peer_status(p, e):
2678
2722
  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 "")
2723
+ return "paired" + (", logged out" if p["logged_out"] else ", not listening" if not p["listening"] else "")
2680
2724
  if e and e["state"] == "shown" and not e["approved"]:
2681
2725
  return "compare fingerprint " + e["fingerprint"]
2682
2726
  if p["pinned"] and p["ruling"] == "approved":
@@ -2949,7 +2993,7 @@ def cmd_send(cx, args):
2949
2993
  # /v1/send, /v1/pair, and /v1/approve result word -> reason for one device (%s: its name).
2950
2994
  SEND_WHY = {"gone": '"%s" needs attention. Open PushArmor on it to resolve.',
2951
2995
  "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.',
2996
+ "not listening": '"%s" has not listened recently. Run `pusharmor listen` on it.',
2953
2997
  "unapproved": '"%s" is not paired with this device. Pair with it to send it messages.',
2954
2998
  "denied": '"%s" is not paired with this device.', "unknown": '"%s" is no longer on this account.'}
2955
2999
  SEND_FAILED = 'The push service of "%s" did not accept the message. Try again later.' # failed:CODE
@@ -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 = []
@@ -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