avrel 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.
avrel/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """Avrel from Python: the test-data platform for hardware teams, with release authority built in.
2
+
3
+ import avrel
4
+
5
+ client = avrel.Client() # AVREL_URL and AVREL_KEY from the environment
6
+ client.get_site() # any tool your key can use, as a method
7
+ gate = client.gate(release="v1.4.2", sha="3f2c9e1")
8
+ if gate.blocked:
9
+ raise SystemExit(gate.summary())
10
+
11
+ Every call goes through Avrel's control plane with an agent key, so it is checked against the
12
+ key's access and the role of the person who made the key, and it is written to the audit log.
13
+ """
14
+
15
+ from .approvals import Approval, ApprovalRefused, verify_approval
16
+ from .client import Client, Gate, ToolInfo, to_dataframe
17
+ from .errors import AuthError, AvrelError, ConnectionFailed, Refused, UnknownTool
18
+ from .readings import read_file
19
+
20
+ __version__ = "0.1.0"
21
+ __all__ = ["Approval", "ApprovalRefused", "verify_approval", "Client", "Gate", "ToolInfo", "to_dataframe", "read_file", "AvrelError", "AuthError", "ConnectionFailed",
22
+ "Refused", "UnknownTool", "__version__"]
avrel/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
avrel/approvals.py ADDED
@@ -0,0 +1,272 @@
1
+ """Check a signed release approval on the device, before installing a build. No network needed.
2
+
3
+ from avrel.approvals import verify_approval, ApprovalRefused
4
+
5
+ try:
6
+ approval = verify_approval("avrel-approval.json",
7
+ organization="acme-robotics", # your organization's ID in Avrel
8
+ public_keys=["MCowBQYDK2VwAyEA..."], # pinned: GET /api/release-approvals/keys
9
+ artifact="firmware.bin") # the file you are about to install
10
+ except ApprovalRefused as exc:
11
+ sys.exit(f"Not installing: {exc}")
12
+
13
+ An approval file is ``{format, algorithm, key_id, payload, signature}``: payload is base64 of the exact JSON
14
+ bytes Avrel signed with Ed25519, so any language can check it the same way (decode the payload, verify the
15
+ signature over those bytes with the pinned public key, then read the fields). Avrel never sees what the
16
+ device decides; the check runs only here.
17
+
18
+ Uses the ``cryptography`` package when it is installed, otherwise a small pure-Python Ed25519 check
19
+ (RFC 8032), so the updater needs nothing beyond the standard library.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import base64
25
+ from dataclasses import dataclass, field
26
+ import hashlib
27
+ import json
28
+ import os
29
+ import time
30
+ from typing import Any, Iterable, Mapping, Union
31
+ import urllib.parse
32
+ import urllib.request
33
+
34
+ from .errors import AvrelError
35
+
36
+ FORMAT = "avrel.release-approval.v1"
37
+ _SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100") # Ed25519 SubjectPublicKeyInfo header (RFC 8410)
38
+
39
+
40
+ class ApprovalRefused(AvrelError):
41
+ """The build must not be installed: the approval is missing, forged, for something else, or withdrawn."""
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Approval:
46
+ """A signed release approval that checked out."""
47
+
48
+ id: str
49
+ organization: str
50
+ release: str
51
+ build: str
52
+ artifacts: list = field(default_factory=list)
53
+ issued_by: str = ""
54
+ issued_at: float = 0.0
55
+ expires_at: Union[float, None] = None
56
+ key_id: str = ""
57
+ status_url: str = ""
58
+ payload: dict = field(default_factory=dict)
59
+
60
+
61
+ # ── Ed25519 (RFC 8032, verification only) ────────────────────────────────
62
+ _P = 2 ** 255 - 19
63
+ _L = 2 ** 252 + 27742317777372353535851937790883648493
64
+ _D = -121665 * pow(121666, _P - 2, _P) % _P
65
+ _I = pow(2, (_P - 1) // 4, _P)
66
+
67
+
68
+ def _add(a, b):
69
+ x1, y1, z1, t1 = a
70
+ x2, y2, z2, t2 = b
71
+ A = (y1 - x1) * (y2 - x2) % _P
72
+ B = (y1 + x1) * (y2 + x2) % _P
73
+ C = 2 * t1 * t2 * _D % _P
74
+ D = 2 * z1 * z2 % _P
75
+ E, F, G, H = B - A, D - C, D + C, B + A
76
+ return (E * F % _P, G * H % _P, F * G % _P, E * H % _P)
77
+
78
+
79
+ def _mul(s, pt):
80
+ q = (0, 1, 1, 0)
81
+ while s:
82
+ if s & 1:
83
+ q = _add(q, pt)
84
+ pt = _add(pt, pt)
85
+ s >>= 1
86
+ return q
87
+
88
+
89
+ def _equal(a, b):
90
+ return (a[0] * b[2] - b[0] * a[2]) % _P == 0 and (a[1] * b[2] - b[1] * a[2]) % _P == 0
91
+
92
+
93
+ def _decompress(s: bytes):
94
+ if len(s) != 32:
95
+ return None
96
+ y = int.from_bytes(s, "little")
97
+ sign = y >> 255
98
+ y &= (1 << 255) - 1
99
+ if y >= _P:
100
+ return None
101
+ x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P
102
+ if x2 == 0:
103
+ if sign:
104
+ return None
105
+ x = 0
106
+ else:
107
+ x = pow(x2, (_P + 3) // 8, _P)
108
+ if (x * x - x2) % _P:
109
+ x = x * _I % _P
110
+ if (x * x - x2) % _P:
111
+ return None
112
+ if (x & 1) != sign:
113
+ x = _P - x
114
+ return (x, y, 1, x * y % _P)
115
+
116
+
117
+ _GY = 4 * pow(5, _P - 2, _P) % _P
118
+ _G = _decompress(_GY.to_bytes(32, "little"))
119
+
120
+
121
+ def _pure_verify(public: bytes, signature: bytes, message: bytes) -> bool:
122
+ if len(signature) != 64:
123
+ return False
124
+ a = _decompress(public)
125
+ r = _decompress(signature[:32])
126
+ s = int.from_bytes(signature[32:], "little")
127
+ if a is None or r is None or s >= _L:
128
+ return False
129
+ h = int.from_bytes(hashlib.sha512(signature[:32] + public + message).digest(), "little") % _L
130
+ return _equal(_mul(s, _G), _add(r, _mul(h, a)))
131
+
132
+
133
+ def ed25519_verify(public: bytes, signature: bytes, message: bytes) -> bool:
134
+ """True when signature is a valid Ed25519 signature of message by the 32-byte public key."""
135
+ try:
136
+ from cryptography.exceptions import InvalidSignature
137
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
138
+ except ImportError:
139
+ return _pure_verify(public, signature, message)
140
+ try:
141
+ Ed25519PublicKey.from_public_bytes(public).verify(signature, message)
142
+ return True
143
+ except (InvalidSignature, ValueError):
144
+ return False
145
+
146
+
147
+ # ── Keys ─────────────────────────────────────────────────────────────────
148
+ def _raw_key(key: Union[str, bytes, Mapping[str, Any]]) -> bytes:
149
+ """A public key as 32 raw bytes, from base64 of the raw key, a PEM block, or a {public_key} entry."""
150
+ if isinstance(key, Mapping):
151
+ key = key.get("public_key") or key.get("pem") or ""
152
+ if isinstance(key, bytes):
153
+ key = key.decode("ascii", "replace") if len(key) != 32 else key
154
+ if isinstance(key, bytes):
155
+ return key
156
+ text = str(key).strip()
157
+ if "BEGIN PUBLIC KEY" in text:
158
+ text = "".join(line for line in text.splitlines() if "-----" not in line)
159
+ raw = base64.b64decode(text)
160
+ if len(raw) == 44 and raw.startswith(_SPKI_PREFIX):
161
+ raw = raw[len(_SPKI_PREFIX):]
162
+ if len(raw) != 32:
163
+ raise ApprovalRefused("A pinned public key is not an Ed25519 key")
164
+ return raw
165
+
166
+
167
+ def key_id(raw: bytes) -> str:
168
+ return hashlib.sha256(raw).hexdigest()[:16]
169
+
170
+
171
+ def fetch_public_keys(url: str = "", timeout: float = 10) -> list:
172
+ """The public keys from an Avrel server (default $AVREL_URL), to pin when the updater is built, not at install."""
173
+ base = (url or os.environ.get("AVREL_URL") or "https://app.getavrel.com").rstrip("/")
174
+ with urllib.request.urlopen(f"{base}/api/release-approvals/keys", timeout=timeout) as r: # noqa: S310
175
+ return json.loads(r.read().decode("utf-8")).get("keys") or []
176
+
177
+
178
+ # ── The check ────────────────────────────────────────────────────────────
179
+ def _load(document: Any) -> dict:
180
+ if isinstance(document, Mapping):
181
+ return dict(document)
182
+ if isinstance(document, bytes):
183
+ return json.loads(document.decode("utf-8"))
184
+ text = str(document)
185
+ if text.lstrip().startswith("{"):
186
+ return json.loads(text)
187
+ with open(text, encoding="utf-8") as fh:
188
+ return json.load(fh)
189
+
190
+
191
+ def sha256_file(path: str) -> str:
192
+ h = hashlib.sha256()
193
+ with open(path, "rb") as fh:
194
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
195
+ h.update(chunk)
196
+ return h.hexdigest()
197
+
198
+
199
+ def check_status(approval: Approval, timeout: float = 10) -> str:
200
+ """Ask Avrel whether the approval still stands: valid, expired, revoked or unknown. Needs the network."""
201
+ url = approval.status_url
202
+ if not url:
203
+ raise ApprovalRefused("The approval has no status address to check")
204
+ if urllib.parse.urlparse(url).scheme != "https":
205
+ raise ApprovalRefused("The approval's status address is not https")
206
+ with urllib.request.urlopen(url, timeout=timeout) as r: # noqa: S310 - https only, checked above
207
+ return str(json.loads(r.read().decode("utf-8")).get("state") or "unknown")
208
+
209
+
210
+ def verify_approval(document: Any, *, organization: str, public_keys: Iterable[Any], build: str = "",
211
+ artifact: Union[str, None] = None, artifact_sha256: str = "", now: Union[float, None] = None,
212
+ online: bool = False) -> Approval:
213
+ """Check a signed release approval and return it, or raise ApprovalRefused saying why not to install.
214
+
215
+ document the approval file: a path, its JSON text or bytes, or the parsed dict
216
+ organization your organization's ID in Avrel; an approval for anyone else is refused
217
+ public_keys the pinned keys (base64, PEM, or entries from /api/release-approvals/keys)
218
+ build the build ID you are about to install, when you know it
219
+ artifact path of the file you are about to install: its SHA-256 must be the build ID or a listed digest
220
+ online also ask Avrel whether the approval was revoked since (refused if Avrel cannot be reached)
221
+ """
222
+ try:
223
+ doc = _load(document)
224
+ except (OSError, ValueError) as exc:
225
+ raise ApprovalRefused(f"No readable approval file ({exc})") from None
226
+ if doc.get("format") != FORMAT or doc.get("algorithm") != "Ed25519":
227
+ raise ApprovalRefused(f"Not an Avrel release approval (format must be {FORMAT})")
228
+ try:
229
+ raw = base64.b64decode(str(doc.get("payload") or ""), validate=True)
230
+ signature = base64.b64decode(str(doc.get("signature") or ""), validate=True)
231
+ payload = json.loads(raw.decode("utf-8"))
232
+ except ValueError:
233
+ raise ApprovalRefused("The approval file is damaged") from None
234
+ keys = {key_id(k): k for k in (_raw_key(x) for x in public_keys)}
235
+ if not keys:
236
+ raise ApprovalRefused("No public key is pinned")
237
+ pub = keys.get(str(doc.get("key_id") or ""))
238
+ if pub is None:
239
+ raise ApprovalRefused("It was signed with a key that is not pinned here")
240
+ if not ed25519_verify(pub, signature, raw):
241
+ raise ApprovalRefused("The signature does not verify: the file was changed or Avrel did not sign it")
242
+ if payload.get("format") != FORMAT or payload.get("key_id") != doc.get("key_id"):
243
+ raise ApprovalRefused("The signed payload does not match its envelope")
244
+ if payload.get("organization") != organization:
245
+ raise ApprovalRefused(f"It approves a build for organization {payload.get('organization')!r}, not {organization!r}")
246
+ if build and payload.get("build") != build:
247
+ raise ApprovalRefused(f"It approves build {payload.get('build')}, not {build}")
248
+ if artifact or artifact_sha256:
249
+ digest = (artifact_sha256 or sha256_file(str(artifact))).lower()
250
+ allowed = {str(a.get("sha256") or "").lower() for a in payload.get("artifacts") or []}
251
+ allowed.add(str(payload.get("build") or "").lower())
252
+ if digest not in allowed:
253
+ raise ApprovalRefused(f"The file's SHA-256 {digest[:16]}... is not one this approval names")
254
+ t = time.time() if now is None else now
255
+ expires = payload.get("expires_at")
256
+ if expires is not None and t >= float(expires):
257
+ raise ApprovalRefused("The approval has expired")
258
+ approval = Approval(id=str(payload.get("id") or ""), organization=organization, release=str(payload.get("release") or ""),
259
+ build=str(payload.get("build") or ""), artifacts=list(payload.get("artifacts") or []),
260
+ issued_by=str(payload.get("issued_by") or ""), issued_at=float(payload.get("issued_at") or 0),
261
+ expires_at=expires, key_id=str(doc.get("key_id")), status_url=str(payload.get("status_url") or ""),
262
+ payload=payload)
263
+ if online:
264
+ try:
265
+ state = check_status(approval)
266
+ except ApprovalRefused:
267
+ raise
268
+ except Exception as exc: # noqa: BLE001 - online was asked for, so not knowing is a refusal
269
+ raise ApprovalRefused(f"Could not ask Avrel whether the approval still stands ({type(exc).__name__})") from None
270
+ if state != "valid":
271
+ raise ApprovalRefused(f"Avrel says the approval is {state}")
272
+ return approval
avrel/cli.py ADDED
@@ -0,0 +1,309 @@
1
+ """The avrel command: the release gate in CI, history import, and any tool from a terminal.
2
+
3
+ export AVREL_URL=https://app.getavrel.com
4
+ export AVREL_KEY=ava_... # Settings > AI assistants > Create key
5
+
6
+ avrel gate --release v1.4.2 --sha "$GITHUB_SHA" # exit 1 when the gate blocks
7
+ avrel record-release --release v1.4.2 --sha "$GITHUB_SHA"
8
+ avrel approval v1.4.2 -o avrel-approval.json # the signed approval, to ship with the build
9
+ avrel verify-approval avrel-approval.json --org acme --key-file avrel-keys.json --artifact fw.bin
10
+ avrel import readings.csv --source "logger export 2026"
11
+ avrel upload flight-14.mcap --unit-id UAV-03 # keep every reading, as a full-rate recording
12
+ avrel upload drive.blf --dbc car.dbc --unit-id CAR-02 # also .ulg, ArduPilot .bin, ROS 1 .bag
13
+ avrel tools # what this key can do
14
+ avrel call get_telemetry unit_id=RIG-01 from:=1790000000
15
+
16
+ Exit codes: 0 done (gate approved, approval valid), 1 the gate blocked the release or the approval is
17
+ refused, 2 the gate has no checks yet, 3 a usage, key or server error.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import sys
26
+ import textwrap
27
+ import time
28
+ from typing import Any
29
+
30
+ from . import __version__
31
+ from .client import Client
32
+ from .errors import AvrelError
33
+
34
+ EXIT_OK, EXIT_BLOCKED, EXIT_NO_CHECKS, EXIT_ERROR = 0, 1, 2, 3
35
+
36
+
37
+ def _client(args: argparse.Namespace) -> Client:
38
+ return Client(args.url, args.key)
39
+
40
+
41
+ def _summary(lines: list[str]) -> None:
42
+ """Also write to the job summary on GitHub Actions."""
43
+ path = os.environ.get("GITHUB_STEP_SUMMARY")
44
+ if path:
45
+ with open(path, "a", encoding="utf-8") as fh:
46
+ fh.write("\n".join(lines) + "\n")
47
+
48
+
49
+ def _print_json(data: Any) -> None:
50
+ print(json.dumps(data, indent=2, ensure_ascii=False, default=str))
51
+
52
+
53
+ def cmd_gate(args: argparse.Namespace) -> int:
54
+ g = _client(args).gate(release=args.release, sha=args.sha, rollback_sha=args.rollback_sha)
55
+ if args.json:
56
+ _print_json(g.raw)
57
+ else:
58
+ print(g.summary())
59
+ md = [f"### Avrel release gate: {g.verdict}", "",
60
+ f"{g.passed} of {g.total} checks pass for {g.target or 'the release now recorded'}.", "",
61
+ "| | Check | Detail |", "| --- | --- | --- |"]
62
+ for c in g.checks:
63
+ mark = {"ok": "PASS", "crit": "FAIL", "warn": "WARN", "skip": "SKIP"}.get(c.get("status"), str(c.get("status")))
64
+ md.append(f"| {mark} | {c.get('name')} | {str(c.get('detail') or '').replace('|', '/')} |")
65
+ _summary(md)
66
+ if g.approved:
67
+ return EXIT_OK
68
+ if g.blocked:
69
+ print("The release gate blocks this release.", file=sys.stderr)
70
+ return EXIT_BLOCKED
71
+ print("The release gate has no checks that can run yet, so it cannot approve this release.", file=sys.stderr)
72
+ return EXIT_OK if args.allow_no_checks else EXIT_NO_CHECKS
73
+
74
+
75
+ def cmd_record(args: argparse.Namespace) -> int:
76
+ r = _client(args).call("record_release", release=args.release, sha=args.sha, rollback_sha=args.rollback_sha,
77
+ override_reason=args.override_reason)
78
+ rel = r.get("release") or {}
79
+ print(f"Recorded release {rel.get('release', args.release)} ({rel.get('sha', args.sha)}) "
80
+ f"with gate verdict {rel.get('hil_badge', 'unknown')}.")
81
+ dev = r.get("deviation")
82
+ if dev: # never a failure: the deploy happened, and Avrel keeps it as a deviation for a person to accept
83
+ print(f"Deviation {dev.get('id')} opened ({dev.get('state')}): this release shipped although the release gate "
84
+ "did not approve it." + ("" if dev.get("reason") else " Give --override-reason, or explain it in Avrel."),
85
+ file=sys.stderr)
86
+ return EXIT_OK
87
+
88
+
89
+ def cmd_approval(args: argparse.Namespace) -> int:
90
+ out = _client(args).call("get_release_approval", release=args.release)
91
+ doc = out.get("document") or {}
92
+ text = json.dumps(doc, indent=2) + "\n"
93
+ if args.output and args.output != "-":
94
+ with open(args.output, "w", encoding="utf-8") as fh:
95
+ fh.write(text)
96
+ print(f"Wrote the signed approval {out.get('id')} of {(out.get('release') or {}).get('name')} to {args.output}.")
97
+ else:
98
+ sys.stdout.write(text)
99
+ if args.keys:
100
+ with open(args.keys, "w", encoding="utf-8") as fh:
101
+ json.dump({"keys": out.get("keys") or []}, fh, indent=2)
102
+ return EXIT_OK
103
+
104
+
105
+ def cmd_verify_approval(args: argparse.Namespace) -> int:
106
+ from .approvals import ApprovalRefused, fetch_public_keys, verify_approval
107
+
108
+ keys: list[Any] = list(args.public_key or [])
109
+ for path in args.key_file or []:
110
+ with open(path, encoding="utf-8") as fh:
111
+ text = fh.read()
112
+ keys.extend((json.loads(text).get("keys") or []) if text.lstrip().startswith("{") else [text])
113
+ if not keys and args.fetch_keys:
114
+ keys = fetch_public_keys(args.url or "")
115
+ if not keys:
116
+ print("avrel: pin a public key with --public-key or --key-file (see /api/release-approvals/keys)", file=sys.stderr)
117
+ return EXIT_ERROR
118
+ try:
119
+ a = verify_approval(args.file, organization=args.org, public_keys=keys, build=args.build or "",
120
+ artifact=args.artifact, online=args.online)
121
+ except ApprovalRefused as exc:
122
+ print(f"Refused: {exc}", file=sys.stderr)
123
+ return EXIT_BLOCKED
124
+ print(f"Approved: {a.release} (build {a.build}) by Avrel approval {a.id}, issued {time.strftime('%d %b %Y', time.gmtime(a.issued_at))}"
125
+ f"{f' by {a.issued_by}' if a.issued_by else ''}.")
126
+ return EXIT_OK
127
+
128
+
129
+ def cmd_import(args: argparse.Namespace) -> int:
130
+ from .readings import read_file
131
+
132
+ columns = {"unit_id": args.unit_column, "timestamp": args.time_column, "name": args.name_column,
133
+ "value": args.value_column, "unit": args.unit_of_measure_column}
134
+ c = None if args.dry_run else _client(args)
135
+ total = stored = 0
136
+ for path in args.files:
137
+ source = args.source or os.path.basename(path)
138
+ rows = read_file(path, unit_id=args.unit_id, columns=columns, format=args.format)
139
+ if c is None:
140
+ total += sum(1 for _ in rows)
141
+ continue
142
+ done = {"readings": 0, "stored": 0}
143
+
144
+ def progress(t: dict[str, int], source: str = source, done: dict[str, int] = done) -> None:
145
+ done.update(t)
146
+ print(f"{source}: {total + t['readings']} readings sent, {stored + t['stored']} new times stored", flush=True)
147
+
148
+ c.import_readings(rows, source, progress=progress)
149
+ total += done["readings"]
150
+ stored += done["stored"]
151
+ if c is None:
152
+ print(f"Dry run: {total} readings would be sent. Nothing was imported.")
153
+ else:
154
+ print(f"Done: {total} readings sent, {stored} new times stored (the rest were already imported).")
155
+ return EXIT_OK
156
+
157
+
158
+ def cmd_upload(args: argparse.Namespace) -> int:
159
+ c = _client(args)
160
+ for path in args.files:
161
+ def progress(sent: int, total: int, path: str = path) -> None:
162
+ print(f"{os.path.basename(path)}: {round(100 * sent / max(1, total))}% sent", flush=True)
163
+
164
+ r = c.upload_recording(path, unit_id=args.unit_id, source=args.source, dbc=args.dbc,
165
+ start_time=args.start_time, progress=progress)
166
+ for d in r.get("recordings") or []:
167
+ print(f"{d['id']}: {d['readings']} readings from {d['unit_id']} kept at full rate "
168
+ f"({len(d['channels'])} names)")
169
+ for note in r.get("notes") or []:
170
+ print(note)
171
+ return EXIT_OK
172
+
173
+
174
+ def cmd_tools(args: argparse.Namespace) -> int:
175
+ tools = sorted(_client(args).tools(), key=lambda t: t.name)
176
+ if args.json:
177
+ _print_json([{"name": t.name, "title": t.title, "read_only": t.read_only, "description": t.description,
178
+ "input_schema": t.input_schema} for t in tools])
179
+ return EXIT_OK
180
+ for t in tools:
181
+ kind = "read" if t.read_only else "change"
182
+ print(f"{t.name:32} {kind:7} {t.title}")
183
+ if args.verbose:
184
+ print(textwrap.indent(textwrap.fill(" ".join(t.description.split()), 96), " "))
185
+ print(f" {t.signature()}\n")
186
+ return EXIT_OK
187
+
188
+
189
+ def _parse_pairs(pairs: list[str]) -> dict[str, Any]:
190
+ """name=text sets a string; name:=json sets any JSON value (a number, true, a list, an object)."""
191
+ out: dict[str, Any] = {}
192
+ for p in pairs:
193
+ if ":=" in p and ("=" not in p or p.index(":=") < p.index("=")):
194
+ k, v = p.split(":=", 1)
195
+ try:
196
+ out[k] = json.loads(v)
197
+ except ValueError:
198
+ raise AvrelError(f"{k}:= needs a JSON value, e.g. {k}:=42 or {k}:='[\"a\"]'") from None
199
+ elif "=" in p:
200
+ k, v = p.split("=", 1)
201
+ out[k] = v
202
+ else:
203
+ raise AvrelError(f"Arguments are name=text or name:=json, not {p!r}")
204
+ return out
205
+
206
+
207
+ def cmd_call(args: argparse.Namespace) -> int:
208
+ arguments: dict[str, Any] = {}
209
+ if args.input:
210
+ with (sys.stdin if args.input == "-" else open(args.input, encoding="utf-8")) as fh:
211
+ loaded = json.load(fh)
212
+ if not isinstance(loaded, dict):
213
+ raise AvrelError("--input must hold a JSON object of arguments")
214
+ arguments.update(loaded)
215
+ arguments.update(_parse_pairs(args.arguments))
216
+ _print_json(_client(args).call(args.tool, arguments))
217
+ return EXIT_OK
218
+
219
+
220
+ def build_parser() -> argparse.ArgumentParser:
221
+ p = argparse.ArgumentParser(prog="avrel", description="Avrel from a terminal or a CI pipeline.")
222
+ p.add_argument("--version", action="version", version=f"avrel {__version__}")
223
+ p.add_argument("--url", help="Avrel address (default: $AVREL_URL)")
224
+ p.add_argument("--key", help="Agent key (default: $AVREL_KEY; prefer the variable, so the key stays out of logs)")
225
+ sub = p.add_subparsers(dest="cmd", required=True)
226
+
227
+ g = sub.add_parser("gate", help="Check a release. Exit 1 when the gate blocks it. Needs Read access.")
228
+ g.add_argument("--release", help="Release name, e.g. v1.4.2")
229
+ g.add_argument("--sha", help="Commit or build ID of the candidate")
230
+ g.add_argument("--rollback-sha", help="The build you would roll back to")
231
+ g.add_argument("--allow-no-checks", action="store_true", help="Pass when the gate has no checks yet")
232
+ g.add_argument("--json", action="store_true", help="Print the gate's full answer as JSON")
233
+ g.set_defaults(fn=cmd_gate)
234
+
235
+ r = sub.add_parser("record-release", help="Record the release now running. Needs Operate access.")
236
+ r.add_argument("--release", required=True)
237
+ r.add_argument("--sha", required=True)
238
+ r.add_argument("--rollback-sha")
239
+ r.add_argument("--override-reason", help="Why it ships although the release gate blocks it")
240
+ r.set_defaults(fn=cmd_record)
241
+
242
+ a = sub.add_parser("approval", help="Download a release's signed approval, to ship with the build. Needs Read access.")
243
+ a.add_argument("release", help="Release name, build ID or id (rel_...)")
244
+ a.add_argument("-o", "--output", default="-", help="Where to write it (default: standard output)")
245
+ a.add_argument("--keys", help="Also write the public keys to pin to this file")
246
+ a.set_defaults(fn=cmd_approval)
247
+
248
+ v = sub.add_parser("verify-approval", help="Check a signed approval on the device. Exit 1 when it is refused.",
249
+ description="Check a signed release approval offline: the signature against a pinned public key, "
250
+ "the organization, and optionally the build ID or the file about to be installed. "
251
+ "Needs no Avrel key.")
252
+ v.add_argument("file", help="The approval file")
253
+ v.add_argument("--org", required=True, help="Your organization's ID in Avrel")
254
+ v.add_argument("--public-key", action="append", help="A pinned public key (base64); may repeat")
255
+ v.add_argument("--key-file", action="append", help="A pinned key file: the JSON from /api/release-approvals/keys, or PEM")
256
+ v.add_argument("--fetch-keys", action="store_true", help="Fetch the keys from --url instead of pinning them (testing only)")
257
+ v.add_argument("--build", help="The build ID about to be installed")
258
+ v.add_argument("--artifact", help="The file about to be installed; its SHA-256 must be approved")
259
+ v.add_argument("--online", action="store_true", help="Also ask Avrel whether the approval was revoked since")
260
+ v.set_defaults(fn=cmd_verify_approval)
261
+
262
+ i = sub.add_parser("import", help="Import archived readings as history. Needs Operate access.")
263
+ i.add_argument("files", nargs="+", help="CSV or JSON Lines files, optionally .gz; - reads standard input")
264
+ i.add_argument("--source", help="Where the readings come from (default: the file name)")
265
+ i.add_argument("--format", choices=("csv", "jsonl"))
266
+ i.add_argument("--unit-id", help="System ID for every reading, when the file has no unit_id column")
267
+ i.add_argument("--unit-column", default="unit_id")
268
+ i.add_argument("--time-column", default="timestamp")
269
+ i.add_argument("--name-column", default="name")
270
+ i.add_argument("--value-column", default="value")
271
+ i.add_argument("--unit-of-measure-column", default="unit")
272
+ i.add_argument("--dry-run", action="store_true", help="Read the files and count readings without sending them")
273
+ i.set_defaults(fn=cmd_import)
274
+
275
+ u = sub.add_parser("upload", help="Upload files as full-rate recordings, kept as they are. Needs Operate access.")
276
+ u.add_argument("files", nargs="+", help="CSV or JSON Lines (optionally .gz), Parquet, MCAP, TDMS, PX4 ULog, "
277
+ "ArduPilot Dataflash, ROS 1 bag or CAN log (candump, BLF, ASC, TRC) files")
278
+ u.add_argument("--unit-id", help="System ID for readings without a unit_id")
279
+ u.add_argument("--dbc", metavar="FILE", help="DBC file that describes the messages in a CAN log")
280
+ u.add_argument("--start-time", metavar="TIME", help="UTC time the log started, for flight logs without GPS time "
281
+ "and CAN logs that count from zero, e.g. 2026-11-30T09:15:00Z")
282
+ u.add_argument("--source", help="Where the readings come from (default: the file name)")
283
+ u.set_defaults(fn=cmd_upload)
284
+
285
+ t = sub.add_parser("tools", help="List the tools this key can use")
286
+ t.add_argument("-v", "--verbose", action="store_true", help="Also show what each does and its arguments")
287
+ t.add_argument("--json", action="store_true")
288
+ t.set_defaults(fn=cmd_tools)
289
+
290
+ c = sub.add_parser("call", help="Call any tool and print its answer as JSON",
291
+ description="Call any tool. Arguments are name=text, or name:=json for numbers, "
292
+ "lists and objects, e.g.: avrel call get_telemetry unit_id=RIG-01 from:=1790000000")
293
+ c.add_argument("tool")
294
+ c.add_argument("arguments", nargs="*", metavar="name=value")
295
+ c.add_argument("--input", help="A JSON file of arguments (- reads standard input)")
296
+ c.set_defaults(fn=cmd_call)
297
+ return p
298
+
299
+
300
+ def main(argv: list[str] | None = None) -> int:
301
+ args = build_parser().parse_args(argv)
302
+ try:
303
+ return args.fn(args)
304
+ except AvrelError as exc:
305
+ print(f"avrel: {exc}", file=sys.stderr)
306
+ return EXIT_ERROR
307
+ except OSError as exc:
308
+ print(f"avrel: {exc}", file=sys.stderr)
309
+ return EXIT_ERROR