awlert 0.1.0__py3-none-any.whl
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.
- awlert/__init__.py +38 -0
- awlert/cli.py +206 -0
- awlert/crypto.py +144 -0
- awlert/delivery.py +421 -0
- awlert/store.py +415 -0
- awlert/watcher.py +469 -0
- awlert-0.1.0.dist-info/METADATA +33 -0
- awlert-0.1.0.dist-info/RECORD +11 -0
- awlert-0.1.0.dist-info/WHEEL +5 -0
- awlert-0.1.0.dist-info/entry_points.txt +2 -0
- awlert-0.1.0.dist-info/top_level.txt +1 -0
awlert/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""awlert — verifiable, Ed25519-sealed, AES-256-GCM encrypted fleet alerts.
|
|
2
|
+
|
|
3
|
+
Composes:
|
|
4
|
+
- ``awdit`` (tamper-evident hash-chained audit trail)
|
|
5
|
+
- ``awseal`` (Ed25519 cryptographic provenance)
|
|
6
|
+
- ``awshare`` (content-addressed, sealed incident bundles)
|
|
7
|
+
- ``awtunnel`` (TLS tunnel exposure & ingress validation)
|
|
8
|
+
- ``awrelay`` (agent/fleet relay delivery) + Discord ``#ops``
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from awlert.crypto import (
|
|
13
|
+
decrypt_envelope,
|
|
14
|
+
derive_transport_key,
|
|
15
|
+
encrypt_envelope,
|
|
16
|
+
ensure_seal_key,
|
|
17
|
+
sign_alert,
|
|
18
|
+
verify_alert,
|
|
19
|
+
)
|
|
20
|
+
from awlert.delivery import BatchingSink, MultiSink
|
|
21
|
+
from awlert.store import AlertEvent, AlertStore, format_batch
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"AlertEvent",
|
|
27
|
+
"AlertStore",
|
|
28
|
+
"BatchingSink",
|
|
29
|
+
"MultiSink",
|
|
30
|
+
"__version__",
|
|
31
|
+
"decrypt_envelope",
|
|
32
|
+
"derive_transport_key",
|
|
33
|
+
"encrypt_envelope",
|
|
34
|
+
"ensure_seal_key",
|
|
35
|
+
"format_batch",
|
|
36
|
+
"sign_alert",
|
|
37
|
+
"verify_alert",
|
|
38
|
+
]
|
awlert/cli.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""CLI entrypoint for ``awlert``.
|
|
2
|
+
|
|
3
|
+
Exit codes match the aw* contract:
|
|
4
|
+
0 = ok / verified
|
|
5
|
+
1 = real verification failure / tamper detected
|
|
6
|
+
2 = could not judge (missing log, bad input)
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import awshare
|
|
20
|
+
|
|
21
|
+
from awlert.crypto import (
|
|
22
|
+
decrypt_envelope,
|
|
23
|
+
derive_transport_key,
|
|
24
|
+
encrypt_envelope,
|
|
25
|
+
ensure_seal_key,
|
|
26
|
+
verify_alert,
|
|
27
|
+
)
|
|
28
|
+
from awlert.delivery import BatchingSink, MultiSink, create_receiver_server
|
|
29
|
+
from awlert.store import AlertEvent, AlertStore
|
|
30
|
+
from awlert.watcher import LifecycleWatcher
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _self_test() -> int:
|
|
34
|
+
"""Prove awdit + awseal + awshare + AES-256-GCM encryption + tamper detection."""
|
|
35
|
+
tmp = Path(tempfile.mkdtemp(prefix="awlert-selftest-"))
|
|
36
|
+
try:
|
|
37
|
+
key_path = tmp / "seal.key"
|
|
38
|
+
store = AlertStore(tmp / "state", key_path=key_path)
|
|
39
|
+
ev = AlertEvent(
|
|
40
|
+
kind="updated",
|
|
41
|
+
service="aither-selftest",
|
|
42
|
+
message="self-test atomic roll",
|
|
43
|
+
old_image="aaaa1111bbbb",
|
|
44
|
+
new_image="cccc2222dddd",
|
|
45
|
+
revision="deadbeef",
|
|
46
|
+
)
|
|
47
|
+
rec = store.record(ev, bundle=True, journal_lines=["line 1", "line 2"])
|
|
48
|
+
ver = verify_alert(rec["envelope"])
|
|
49
|
+
assert ver["ok"] and ver["signature_ok"] and ver["content_ok"], f"seal failed: {ver}"
|
|
50
|
+
|
|
51
|
+
# Tamper detection
|
|
52
|
+
bad = json.loads(json.dumps(rec["envelope"]))
|
|
53
|
+
bad["payload"]["message"] = "tampered"
|
|
54
|
+
assert verify_alert(bad)["ok"] is False, "tamper was not caught!"
|
|
55
|
+
|
|
56
|
+
# AES-256-GCM encryption round-trip
|
|
57
|
+
tkey = derive_transport_key("awlert-self-test-key")
|
|
58
|
+
wire = encrypt_envelope(rec["envelope"], tkey)
|
|
59
|
+
assert wire["kind"] == "awlert.encrypted"
|
|
60
|
+
plain = decrypt_envelope(wire, tkey)
|
|
61
|
+
assert verify_alert(plain, expect_key=ver["pubkey"])["ok"] is True
|
|
62
|
+
|
|
63
|
+
# awdit chain verify
|
|
64
|
+
ch = store.verify()
|
|
65
|
+
assert ch["ok"] is True and ch["code"] == 0, f"awdit failed: {ch}"
|
|
66
|
+
|
|
67
|
+
# awshare sealed bundle fetch + verify
|
|
68
|
+
fetch_dest = tmp / "fetched"
|
|
69
|
+
awshare.fetch(Path(ev.bundle_manifest), fetch_dest, expect_key=ver["pubkey"])
|
|
70
|
+
assert (fetch_dest / "event.json").exists()
|
|
71
|
+
|
|
72
|
+
print(json.dumps({
|
|
73
|
+
"self_test": "PASS",
|
|
74
|
+
"awdit": "ok",
|
|
75
|
+
"awseal": ver["pubkey"][:16] + "...",
|
|
76
|
+
"awshare_bundle": ev.bundle_sha256[:16] + "...",
|
|
77
|
+
"aes256_gcm": "ok",
|
|
78
|
+
}, indent=2))
|
|
79
|
+
return 0
|
|
80
|
+
finally:
|
|
81
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def main(argv=None) -> int:
|
|
85
|
+
ap = argparse.ArgumentParser(
|
|
86
|
+
prog="awlert",
|
|
87
|
+
description="Verifiable, Ed25519-sealed, encrypted fleet lifecycle alerts (awdit + awseal + awshare + awtunnel + awrelay)",
|
|
88
|
+
)
|
|
89
|
+
ap.add_argument("--self-test", action="store_true", help="Prove awdit + awseal + awshare + encryption rules hold")
|
|
90
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
91
|
+
|
|
92
|
+
p_emit = sub.add_parser("emit", help="Sign, audit-log, and deliver one lifecycle alert")
|
|
93
|
+
p_emit.add_argument("kind", help="restarting|restarted|updated|started|stopped|failed|migrated|atomic_staged|info")
|
|
94
|
+
p_emit.add_argument("service", help="Service or node name (e.g. awdiscord)")
|
|
95
|
+
p_emit.add_argument("message", nargs="?", default="lifecycle event")
|
|
96
|
+
p_emit.add_argument("--severity", default="info", choices=["info", "warn", "crit"])
|
|
97
|
+
p_emit.add_argument("--bundle", action="store_true", help="Also publish a sealed awshare incident bundle")
|
|
98
|
+
p_emit.add_argument("--no-deliver", action="store_true", help="Only sign & append to awdit without sending to sinks")
|
|
99
|
+
|
|
100
|
+
p_watch = sub.add_parser("watch", help="Watch systemd PID 1 + podman + awnix bootc atomic updates forever")
|
|
101
|
+
p_watch.add_argument(
|
|
102
|
+
"--batch-window",
|
|
103
|
+
type=float,
|
|
104
|
+
default=float(os.getenv("AWLERT_BATCH_WINDOW_S", "300")),
|
|
105
|
+
help="Coalesce Discord/relay alerts into one bulk digest every N seconds (0 = immediate, default 300)",
|
|
106
|
+
)
|
|
107
|
+
p_watch.add_argument(
|
|
108
|
+
"--batch-max",
|
|
109
|
+
type=int,
|
|
110
|
+
default=int(os.getenv("AWLERT_BATCH_MAX_EVENTS", "50")),
|
|
111
|
+
help="Flush bulk digest early once N alerts are queued (default 50)",
|
|
112
|
+
)
|
|
113
|
+
sub.add_parser("verify", help="Verify the awdit hash chain (exit 0 ok, 1 problem, 2 missing)")
|
|
114
|
+
|
|
115
|
+
p_tail = sub.add_parser("tail", help="Show the last N alerts from the awdit chain")
|
|
116
|
+
p_tail.add_argument("-n", type=int, default=15)
|
|
117
|
+
|
|
118
|
+
sub.add_parser("status", help="Show awdit status, awseal pubkey, and configured sinks")
|
|
119
|
+
|
|
120
|
+
p_listen = sub.add_parser("listen", help="Run a verified/decrypting alert receiver (optionally via awtunnel)")
|
|
121
|
+
p_listen.add_argument("--host", default="127.0.0.1")
|
|
122
|
+
p_listen.add_argument("--port", type=int, default=8395)
|
|
123
|
+
p_listen.add_argument("--expect-key", default="", help="Pin sender Ed25519 pubkey hex")
|
|
124
|
+
p_listen.add_argument("--tunnel", action="store_true", help="Expose receiver over TLS via awtunnel up")
|
|
125
|
+
|
|
126
|
+
args = ap.parse_args(argv)
|
|
127
|
+
if args.self_test:
|
|
128
|
+
return _self_test()
|
|
129
|
+
if not args.cmd:
|
|
130
|
+
ap.print_help()
|
|
131
|
+
return 2
|
|
132
|
+
|
|
133
|
+
store = AlertStore()
|
|
134
|
+
|
|
135
|
+
if args.cmd == "emit":
|
|
136
|
+
ev = AlertEvent(kind=args.kind, service=args.service, message=args.message, severity=args.severity)
|
|
137
|
+
rec = store.record(ev, bundle=args.bundle)
|
|
138
|
+
deliveries = [] if args.no_deliver else MultiSink().deliver(rec)
|
|
139
|
+
print(json.dumps({
|
|
140
|
+
"seq": rec["seq"],
|
|
141
|
+
"event_id": ev.event_id,
|
|
142
|
+
"sha256": rec["envelope"]["sha256"][:16],
|
|
143
|
+
"pubkey": rec["envelope"]["pubkey"][:16],
|
|
144
|
+
"bundle_manifest": ev.bundle_manifest or None,
|
|
145
|
+
"deliveries": deliveries,
|
|
146
|
+
"formatted": rec["formatted"],
|
|
147
|
+
}, indent=2))
|
|
148
|
+
return 0
|
|
149
|
+
|
|
150
|
+
if args.cmd == "verify":
|
|
151
|
+
res = store.verify()
|
|
152
|
+
print(json.dumps(res, indent=2))
|
|
153
|
+
return int(res["code"])
|
|
154
|
+
|
|
155
|
+
if args.cmd == "tail":
|
|
156
|
+
rows = store.tail(args.n)
|
|
157
|
+
for r in rows:
|
|
158
|
+
print(json.dumps(r))
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
if args.cmd == "status":
|
|
162
|
+
pub = ensure_seal_key(store.key_path)
|
|
163
|
+
ver = store.verify()
|
|
164
|
+
print(json.dumps({
|
|
165
|
+
"root": str(store.root),
|
|
166
|
+
"log_path": str(store.log_path),
|
|
167
|
+
"awdit_ok": ver["ok"],
|
|
168
|
+
"awdit_records": ver.get("records"),
|
|
169
|
+
"awseal_pubkey": pub,
|
|
170
|
+
"awrelay_configured": bool(os.getenv("AWRELAY_URL") and os.getenv("AWRELAY_TOKEN")),
|
|
171
|
+
"webhook_configured": bool(os.getenv("AWLERT_WEBHOOK_URL")),
|
|
172
|
+
"encryption_enabled": bool(os.getenv("AWLERT_ENCRYPT_KEY")),
|
|
173
|
+
"batch_window_s": float(os.getenv("AWLERT_BATCH_WINDOW_S", "300")),
|
|
174
|
+
"batch_max_events": int(os.getenv("AWLERT_BATCH_MAX_EVENTS", "50")),
|
|
175
|
+
}, indent=2))
|
|
176
|
+
return 0
|
|
177
|
+
|
|
178
|
+
if args.cmd == "watch":
|
|
179
|
+
ensure_seal_key(store.key_path)
|
|
180
|
+
multi = MultiSink()
|
|
181
|
+
sink = BatchingSink(multi, window_s=args.batch_window, max_events=args.batch_max) if args.batch_window > 0 else multi
|
|
182
|
+
watcher = LifecycleWatcher(store, sink)
|
|
183
|
+
return watcher.run_forever()
|
|
184
|
+
|
|
185
|
+
if args.cmd == "listen":
|
|
186
|
+
srv = create_receiver_server(
|
|
187
|
+
store,
|
|
188
|
+
host=args.host,
|
|
189
|
+
port=args.port,
|
|
190
|
+
encrypt_secret=os.getenv("AWLERT_ENCRYPT_KEY", ""),
|
|
191
|
+
expect_key=args.expect_key,
|
|
192
|
+
)
|
|
193
|
+
if args.tunnel and shutil.which("awtunnel"):
|
|
194
|
+
subprocess.Popen(["awtunnel", "up", "--port", str(args.port)])
|
|
195
|
+
print(f"awlert receiver listening on http://{args.host}:{args.port}/ingest", flush=True)
|
|
196
|
+
try:
|
|
197
|
+
srv.serve_forever()
|
|
198
|
+
except KeyboardInterrupt:
|
|
199
|
+
pass
|
|
200
|
+
return 0
|
|
201
|
+
|
|
202
|
+
return 2
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
raise SystemExit(main())
|
awlert/crypto.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Cryptographic provenance (awseal Ed25519) + confidentiality (AES-256-GCM).
|
|
2
|
+
|
|
3
|
+
Honors awseal's three rules:
|
|
4
|
+
1. No default/constant signing key.
|
|
5
|
+
2. Sign the canonical bytes of the full alert payload, never a summary.
|
|
6
|
+
3. Verification reports ``signature_ok``, ``content_ok``, and ``key_match`` separately.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import secrets
|
|
15
|
+
import threading
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, Optional
|
|
18
|
+
|
|
19
|
+
import awseal
|
|
20
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
21
|
+
|
|
22
|
+
ENVELOPE_VERSION = 1
|
|
23
|
+
ENCRYPTED_VERSION = 1
|
|
24
|
+
_AAD = b"awlert:v1"
|
|
25
|
+
_KEYGEN_LOCK = threading.Lock()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def canonical_bytes(obj: Any) -> bytes:
|
|
29
|
+
"""Deterministic UTF-8 JSON representation for signing & hashing."""
|
|
30
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def default_key_path() -> Optional[Path]:
|
|
34
|
+
raw = (os.getenv("AWLERT_KEY_PATH") or os.getenv("AWSEAL_KEY_PATH") or "").strip()
|
|
35
|
+
return Path(raw) if raw else None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def ensure_seal_key(key_path: Optional[Path] = None) -> str:
|
|
39
|
+
"""Ensure an Ed25519 awseal key exists and return its public key hex."""
|
|
40
|
+
kp = key_path or default_key_path()
|
|
41
|
+
try:
|
|
42
|
+
return awseal.public_key_hex(path=kp)
|
|
43
|
+
except Exception:
|
|
44
|
+
with _KEYGEN_LOCK:
|
|
45
|
+
try:
|
|
46
|
+
return awseal.public_key_hex(path=kp)
|
|
47
|
+
except Exception:
|
|
48
|
+
if kp is not None:
|
|
49
|
+
kp.parent.mkdir(parents=True, exist_ok=True)
|
|
50
|
+
awseal.keygen(kp)
|
|
51
|
+
return awseal.public_key_hex(path=kp)
|
|
52
|
+
awseal.keygen()
|
|
53
|
+
return awseal.public_key_hex()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def sign_alert(payload: Dict[str, Any], *, key_path: Optional[Path] = None) -> Dict[str, Any]:
|
|
57
|
+
"""Sign ``payload`` with the node's awseal Ed25519 private key."""
|
|
58
|
+
kp = key_path or default_key_path()
|
|
59
|
+
ensure_seal_key(kp)
|
|
60
|
+
priv = awseal.load_private_key(kp) if kp is not None else awseal.load_private_key()
|
|
61
|
+
pub_hex = awseal.public_key_hex(priv)
|
|
62
|
+
raw = canonical_bytes(payload)
|
|
63
|
+
digest = hashlib.sha256(raw).hexdigest()
|
|
64
|
+
sig = priv.sign(raw).hex()
|
|
65
|
+
return {
|
|
66
|
+
"version": ENVELOPE_VERSION,
|
|
67
|
+
"kind": "awlert.envelope",
|
|
68
|
+
"payload": payload,
|
|
69
|
+
"sha256": digest,
|
|
70
|
+
"pubkey": pub_hex,
|
|
71
|
+
"signature": sig,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def verify_alert(envelope: Dict[str, Any], *, expect_key: str = "") -> Dict[str, Any]:
|
|
76
|
+
"""Verify an awlert signed envelope (digest + Ed25519 signature + optional key pin)."""
|
|
77
|
+
from cryptography.exceptions import InvalidSignature
|
|
78
|
+
|
|
79
|
+
payload = envelope.get("payload")
|
|
80
|
+
claimed_sha = str(envelope.get("sha256") or "")
|
|
81
|
+
pubkey_hex = str(envelope.get("pubkey") or "")
|
|
82
|
+
sig_hex = str(envelope.get("signature") or "")
|
|
83
|
+
|
|
84
|
+
raw = canonical_bytes(payload)
|
|
85
|
+
actual_sha = hashlib.sha256(raw).hexdigest()
|
|
86
|
+
content_ok = bool(claimed_sha and actual_sha == claimed_sha)
|
|
87
|
+
key_match = (not expect_key) or (pubkey_hex.lower() == expect_key.strip().lower())
|
|
88
|
+
|
|
89
|
+
signature_ok = False
|
|
90
|
+
try:
|
|
91
|
+
pub = awseal.load_public_key(pubkey_hex)
|
|
92
|
+
pub.verify(bytes.fromhex(sig_hex), raw)
|
|
93
|
+
signature_ok = True
|
|
94
|
+
except (InvalidSignature, ValueError, Exception):
|
|
95
|
+
signature_ok = False
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
"ok": bool(content_ok and signature_ok and key_match),
|
|
99
|
+
"content_ok": content_ok,
|
|
100
|
+
"signature_ok": signature_ok,
|
|
101
|
+
"key_match": key_match,
|
|
102
|
+
"pubkey": pubkey_hex,
|
|
103
|
+
"sha256": actual_sha,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def derive_transport_key(secret: str) -> bytes:
|
|
108
|
+
"""Derive a 256-bit AES-GCM transport key from a passphrase or hex secret."""
|
|
109
|
+
s = (secret or "").strip()
|
|
110
|
+
if not s:
|
|
111
|
+
raise ValueError("encryption secret must not be empty")
|
|
112
|
+
if len(s) == 64:
|
|
113
|
+
try:
|
|
114
|
+
return bytes.fromhex(s)
|
|
115
|
+
except ValueError:
|
|
116
|
+
pass
|
|
117
|
+
return hashlib.sha256(s.encode("utf-8")).digest()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def encrypt_envelope(envelope: Dict[str, Any], key: bytes) -> Dict[str, Any]:
|
|
121
|
+
"""Encrypt a signed awlert envelope with AES-256-GCM (fresh 96-bit nonce)."""
|
|
122
|
+
if len(key) != 32:
|
|
123
|
+
raise ValueError("AES-256-GCM requires a 32-byte key")
|
|
124
|
+
nonce = secrets.token_bytes(12)
|
|
125
|
+
pt = canonical_bytes(envelope)
|
|
126
|
+
ct = AESGCM(key).encrypt(nonce, pt, _AAD)
|
|
127
|
+
return {
|
|
128
|
+
"version": ENCRYPTED_VERSION,
|
|
129
|
+
"kind": "awlert.encrypted",
|
|
130
|
+
"alg": "AES-256-GCM",
|
|
131
|
+
"nonce": base64.b64encode(nonce).decode("ascii"),
|
|
132
|
+
"ciphertext": base64.b64encode(ct).decode("ascii"),
|
|
133
|
+
"pubkey": str(envelope.get("pubkey") or ""),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def decrypt_envelope(wire: Dict[str, Any], key: bytes) -> Dict[str, Any]:
|
|
138
|
+
"""Decrypt an AES-256-GCM awlert wire message back to the signed envelope."""
|
|
139
|
+
if len(key) != 32:
|
|
140
|
+
raise ValueError("AES-256-GCM requires a 32-byte key")
|
|
141
|
+
nonce = base64.b64decode(str(wire["nonce"]))
|
|
142
|
+
ct = base64.b64decode(str(wire["ciphertext"]))
|
|
143
|
+
pt = AESGCM(key).decrypt(nonce, ct, _AAD)
|
|
144
|
+
return json.loads(pt.decode("utf-8"))
|