patch_deliverable_ack.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Record verified upload content and successful App registration for safe cleanup."""
  2. from __future__ import annotations
  3. import ast
  4. from pathlib import Path
  5. import stat
  6. import sys
  7. MARKER = "# FMODE_VERIFIED_DELIVERABLE_ACK_V1"
  8. RESULT = 'res.append({"path": p, "ok": same, "url": url, "did": did, "bytes": len(data), "detail": detail})'
  9. ACK = ' "src_mtime": int(_mtime_or_0(r["path"])), "gc": False,'
  10. HASHED_RESULT = RESULT.replace('"detail": detail', '"sha256": hashlib.sha256(data).hexdigest(), "detail": detail')
  11. VERIFIED_ACK = ACK + '''
  12. "uploadedAt": int(time.time() * 1000),
  13. "cloudAck": True,
  14. "hubRegistered": isinstance(r.get("hub"), dict) and r["hub"].get("ok") is True,
  15. "sha256": r.get("sha256"), # FMODE_VERIFIED_DELIVERABLE_ACK_V1'''
  16. def patch_text(source: str) -> str:
  17. ast.parse(source)
  18. if MARKER in source:
  19. if HASHED_RESULT not in source or VERIFIED_ACK not in source:
  20. raise ValueError("Incomplete verified-deliverable acknowledgment patch")
  21. return source
  22. if source.count(RESULT) != 1 or source.count(ACK) != 1:
  23. raise ValueError("Deliverable hook differs from the verified upload baseline")
  24. tree = ast.parse(source)
  25. if not any(isinstance(node, ast.Import) and any(a.name == "hashlib" for a in node.names)
  26. for node in tree.body):
  27. raise ValueError("Deliverable hook is missing its verified hashlib import")
  28. updated = source.replace(RESULT, HASHED_RESULT, 1).replace(ACK, VERIFIED_ACK, 1)
  29. ast.parse(updated)
  30. return updated
  31. def main() -> None:
  32. if len(sys.argv) != 2:
  33. raise ValueError("Provide one copied App-container deliverable hook path")
  34. target = Path(sys.argv[1]).resolve(strict=True)
  35. root = Path("/opt/fmode-containers").resolve(strict=True)
  36. rel = target.relative_to(root)
  37. if (not rel.parts[0].startswith("agent-node-app-") or
  38. rel.parts[1:] != ("data", "scripts", "fmode-deliverable-hook.py")):
  39. raise ValueError("Only a copied App-container deliverable hook can be patched")
  40. original = target.read_text(encoding="utf-8")
  41. updated = patch_text(original)
  42. if updated != original:
  43. mode = stat.S_IMODE(target.stat().st_mode)
  44. backup = target.with_name(target.name + ".before-verified-ack")
  45. if not backup.exists():
  46. backup.write_text(original, encoding="utf-8")
  47. backup.chmod(mode)
  48. temp = target.with_name(target.name + ".verified-ack.tmp")
  49. temp.write_text(updated, encoding="utf-8")
  50. temp.chmod(mode)
  51. temp.replace(target)
  52. print("Verified deliverable acknowledgments:", rel.parts[0])
  53. if __name__ == "__main__":
  54. main()