Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T00:34:07.010Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

verify-omega-identity

416 lines · 15.2 KB · text
1#!/usr/bin/env bash
2
3set -euo pipefail
4
5script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6repository_root="${OMEGA_IDENTITY_VERIFY_ROOT:-$(cd "${script_dir}/.." && pwd)}"
7
8python3 - "${repository_root}" <<'PY'
9from __future__ import annotations
10
11import hashlib
12import json
13import re
14import sys
15from pathlib import Path
16from typing import Optional
17
18
19ROOT = Path(sys.argv[1]).resolve()
20BUZZ_SOURCE_COMMIT = "acfbb1bb6af54cb29cb152496ff43b8285dcb8cf"
21PUBLIC_VECTOR_SHA256 = "1e25670b072cdd500bdd65e1c0215b62068cfd26a98284e23a90c781fef0bba6"
22LOCKED_PACKAGES = {
23    "atomic-write-file": (
24        "0.3.0",
25        "84790c55b5704b0d35130bf16a4ce22a8e70eb0ea773522557524d9a4852663d",
26    ),
27    "keyring": (
28        "3.6.3",
29        "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c",
30    ),
31    "nostr": (
32        "0.44.4",
33        "98cf5d15d70d1f8f4059e5f79923ac15891eb691d2843d01191e0585fb064d70",
34    ),
35}
36FORBIDDEN_PUBLIC_FIELD_NAMES = {
37    "mnemonic",
38    "nsec",
39    "privatekey",
40    "secret",
41    "secretkey",
42    "seed",
43    "wallet",
44}
45
46failures: list[str] = []
47
48
49def fail(message: str) -> None:
50    failures.append(message)
51
52
53def public_field_is_forbidden(field_name: str) -> bool:
54    normalized = re.sub(r"[^a-z0-9]", "", field_name.lower())
55    return (
56        normalized in FORBIDDEN_PUBLIC_FIELD_NAMES
57        or normalized.startswith("secret")
58        or "privatekey" in normalized
59        or "secretkey" in normalized
60        or normalized.startswith("wallet")
61    )
62
63
64def read_bytes(relative_path: str) -> bytes:
65    path = ROOT / relative_path
66    try:
67        return path.read_bytes()
68    except OSError as error:
69        fail(f"{relative_path}: cannot read required file: {error}")
70        return b""
71
72
73def read_text(relative_path: str) -> str:
74    return read_bytes(relative_path).decode("utf-8", errors="replace")
75
76
77def toml_section(source: str, heading: str) -> str:
78    match = re.search(
79        rf"(?ms)^\[{re.escape(heading)}\]\s*$\n(.*?)(?=^\[|\Z)",
80        source,
81    )
82    return "" if match is None else match.group(1)
83
84
85workspace_manifest = read_text("Cargo.toml")
86workspace_dependencies = toml_section(workspace_manifest, "workspace.dependencies")
87for package_name, (version, _) in LOCKED_PACKAGES.items():
88    expected = f"={version}"
89    dependency_match = re.search(
90        rf'(?m)^{re.escape(package_name)}\s*=\s*(?:"([^"]+)"|\{{[^}}]*\bversion\s*=\s*"([^"]+)"[^}}]*\}})\s*$',
91        workspace_dependencies,
92    )
93    actual = None if dependency_match is None else next(
94        (value for value in dependency_match.groups() if value is not None),
95        None,
96    )
97    if actual != expected:
98        fail(
99            f"Cargo.toml: workspace dependency {package_name!r} must be pinned "
100            f"to {expected!r}, found {actual!r}"
101        )
102
103identity_manifest = read_text("crates/omega_identity/Cargo.toml")
104identity_dependencies = toml_section(identity_manifest, "dependencies")
105for package_name in ("atomic-write-file", "nostr"):
106    inherited = re.search(
107        rf"(?m)^{re.escape(package_name)}\.workspace\s*=\s*true\s*$",
108        identity_dependencies,
109    ) or re.search(
110        rf'(?m)^{re.escape(package_name)}\s*=\s*\{{[^}}]*\bworkspace\s*=\s*true\b[^}}]*\}}\s*$',
111        identity_dependencies,
112    )
113    if not inherited:
114        fail(
115            "crates/omega_identity/Cargo.toml: "
116            f"{package_name!r} must inherit the locked workspace dependency"
117        )
118
119keyring_lines = re.findall(r"(?m)^keyring\s*=\s*(.+)$", identity_manifest)
120if not keyring_lines or any(
121    re.search(r"\bworkspace\s*=\s*true\b", specification) is None
122    for specification in keyring_lines
123):
124    fail(
125        "crates/omega_identity/Cargo.toml: every target-specific keyring dependency "
126        "must inherit the locked workspace dependency"
127    )
128
129lockfile = read_text("Cargo.lock")
130lock_packages = re.findall(
131    r"(?ms)^\[\[package\]\]\s*$\n(.*?)(?=^\[\[package\]\]|\Z)",
132    lockfile,
133)
134for package_name, (version, checksum) in LOCKED_PACKAGES.items():
135    matches = [
136        package_block
137        for package_block in lock_packages
138        if re.search(
139            rf'(?m)^name\s*=\s*"{re.escape(package_name)}"\s*$',
140            package_block,
141        )
142    ]
143    if len(matches) != 1:
144        fail(
145            f"Cargo.lock: expected exactly one {package_name!r} package, "
146            f"found {len(matches)}"
147        )
148        continue
149    package = matches[0]
150    version_match = re.search(r'(?m)^version\s*=\s*"([^"]+)"\s*$', package)
151    actual_version = None if version_match is None else version_match.group(1)
152    if actual_version != version:
153        fail(
154            f"Cargo.lock: {package_name!r} must resolve to {version}, "
155            f"found {actual_version!r}"
156        )
157    checksum_match = re.search(r'(?m)^checksum\s*=\s*"([^"]+)"\s*$', package)
158    actual_checksum = None if checksum_match is None else checksum_match.group(1)
159    if actual_checksum != checksum:
160        fail(
161            f"Cargo.lock: {package_name!r} {version} checksum changed; "
162            "review the supply-chain update before changing this proof"
163        )
164    source_match = re.search(r'(?m)^source\s*=\s*"([^"]+)"\s*$', package)
165    actual_source = None if source_match is None else source_match.group(1)
166    if actual_source != "registry+https://github.com/rust-lang/crates.io-index":
167        fail(f"Cargo.lock: {package_name!r} must resolve from the crates.io registry")
168
169contract_source = read_text("crates/omega_identity/src/contract.rs")
170commit_match = re.search(
171    r'pub const BUZZ_SOURCE_COMMIT:\s*&str\s*=\s*"([0-9a-f]{40})";',
172    contract_source,
173)
174if commit_match is None or commit_match.group(1) != BUZZ_SOURCE_COMMIT:
175    fail(
176        "crates/omega_identity/src/contract.rs: BUZZ_SOURCE_COMMIT must remain "
177        f"pinned to {BUZZ_SOURCE_COMMIT}"
178    )
179
180vector_relative_path = "crates/omega_identity/fixtures/omega_nostr_identity_v1.json"
181vector_bytes = read_bytes(vector_relative_path)
182if vector_bytes:
183    vector_digest = hashlib.sha256(vector_bytes).hexdigest()
184    if vector_digest != PUBLIC_VECTOR_SHA256:
185        fail(
186            f"{vector_relative_path}: public vector SHA-256 changed; "
187            "review and deliberately update the proof"
188        )
189    try:
190        vector = json.loads(vector_bytes)
191    except json.JSONDecodeError as error:
192        fail(f"{vector_relative_path}: invalid JSON: {error}")
193        vector = {}
194    if vector.get("source_commit") != BUZZ_SOURCE_COMMIT:
195        fail(f"{vector_relative_path}: source_commit does not match Buzz provenance")
196
197    def inspect_public_json(value: object, location: str) -> None:
198        if isinstance(value, dict):
199            for key, child in value.items():
200                if public_field_is_forbidden(key):
201                    fail(f"{vector_relative_path}: forbidden public field at {location}.{key}")
202                inspect_public_json(child, f"{location}.{key}")
203        elif isinstance(value, list):
204            for index, child in enumerate(value):
205                inspect_public_json(child, f"{location}[{index}]")
206
207    inspect_public_json(vector, "$")
208
209
210def struct_body(source: str, struct_name: str) -> Optional[str]:
211    declaration = re.search(rf"\bpub struct {re.escape(struct_name)}\s*\{{", source)
212    if declaration is None:
213        return None
214    opening_brace = source.find("{", declaration.start())
215    depth = 0
216    for index in range(opening_brace, len(source)):
217        if source[index] == "{":
218            depth += 1
219        elif source[index] == "}":
220            depth -= 1
221            if depth == 0:
222                return source[opening_brace + 1 : index]
223    return None
224
225
226manifest_body = struct_body(contract_source, "IdentityManifest")
227if manifest_body is None:
228    fail("crates/omega_identity/src/contract.rs: IdentityManifest declaration not found")
229else:
230    for field_name in re.findall(r"(?m)^\s*(?:pub(?:\([^)]*\))?\s+)?([a-zA-Z_]\w*)\s*:", manifest_body):
231        if public_field_is_forbidden(field_name):
232            fail(
233                "crates/omega_identity/src/contract.rs: IdentityManifest has "
234                f"forbidden secret-bearing field {field_name!r}"
235            )
236
237
238def code_only(source: str) -> str:
239    output = list(source)
240    index = 0
241    while index < len(source):
242        if source.startswith("//", index):
243            end = source.find("\n", index)
244            end = len(source) if end == -1 else end
245            output[index:end] = " " * (end - index)
246            index = end
247        elif source.startswith("/*", index):
248            depth = 1
249            cursor = index + 2
250            while cursor < len(source) and depth:
251                if source.startswith("/*", cursor):
252                    depth += 1
253                    cursor += 2
254                elif source.startswith("*/", cursor):
255                    depth -= 1
256                    cursor += 2
257                else:
258                    cursor += 1
259            output[index:cursor] = " " * (cursor - index)
260            index = cursor
261        elif source[index] == '"':
262            cursor = index + 1
263            while cursor < len(source):
264                if source[cursor] == "\\":
265                    cursor += 2
266                elif source[cursor] == '"':
267                    cursor += 1
268                    break
269                else:
270                    cursor += 1
271            output[index:cursor] = " " * (cursor - index)
272            index = cursor
273        elif source[index] == "'":
274            match = re.match(r"'(?:\\.|[^'\\])'", source[index:])
275            if match:
276                cursor = index + len(match.group(0))
277                output[index:cursor] = " " * (cursor - index)
278                index = cursor
279            else:
280                index += 1
281        elif source[index] == "r":
282            match = re.match(r'r(#{0,255})"', source[index:])
283            if not match:
284                index += 1
285                continue
286            hashes = match.group(1)
287            terminator = '"' + hashes
288            cursor = source.find(terminator, index + len(match.group(0)))
289            cursor = len(source) if cursor == -1 else cursor + len(terminator)
290            output[index:cursor] = " " * (cursor - index)
291            index = cursor
292        else:
293            index += 1
294    return "".join(output)
295
296
297def without_test_modules(source: str) -> str:
298    output = list(source)
299    searchable = code_only(source)
300    pattern = re.compile(
301        r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]\s*mod\s+[a-zA-Z_]\w*\s*\{"
302    )
303    cursor = 0
304    while match := pattern.search(searchable, cursor):
305        opening_brace = searchable.find("{", match.start())
306        depth = 0
307        end = len(source)
308        for index in range(opening_brace, len(searchable)):
309            if searchable[index] == "{":
310                depth += 1
311            elif searchable[index] == "}":
312                depth -= 1
313                if depth == 0:
314                    end = index + 1
315                    break
316        output[match.start():end] = " " * (end - match.start())
317        cursor = end
318    return "".join(output)
319
320
321production_sources: list[tuple[Path, str]] = []
322source_roots = (
323    ROOT / "crates/omega_identity/src",
324    ROOT / "crates/onboarding/src",
325    ROOT / "crates/workspace/src",
326    ROOT / "crates/zed/src",
327)
328source_paths: list[Path] = []
329for source_root in source_roots:
330    if source_root.is_dir():
331        source_paths.extend(source_root.rglob("*.rs"))
332    else:
333        fail(f"{source_root.relative_to(ROOT)}: source directory not found")
334for path in source_paths:
335    if path.is_file():
336        relative_parts = path.relative_to(ROOT).parts
337        if "tests" in relative_parts or path.name.endswith("_test.rs"):
338            continue
339        try:
340            source = path.read_text(encoding="utf-8")
341        except OSError as error:
342            fail(f"{path.relative_to(ROOT)}: cannot scan source: {error}")
343            continue
344        production_sources.append((path, without_test_modules(source)))
345    else:
346        fail(f"{path.relative_to(ROOT)}: required source file not found")
347
348for path, source in production_sources:
349    relative_path = path.relative_to(ROOT)
350    source_without_comments = code_only(source)
351    if re.search(r"\bget_nsec\s*\(", source_without_comments):
352        fail(f"{relative_path}: renderer-visible get_nsec API is forbidden")
353
354    comments_removed_but_strings_preserved = source
355    for match in re.finditer(r"//[^\n]*|/\*.*?\*/", source, flags=re.DOTALL):
356        comments_removed_but_strings_preserved = (
357            comments_removed_but_strings_preserved[: match.start()]
358            + " " * (match.end() - match.start())
359            + comments_removed_but_strings_preserved[match.end() :]
360        )
361    for forbidden_literal, reason in (
362        ("BUZZ_PRIVATE_KEY", "environment-secret fallback"),
363        ("identity.key", "plaintext identity-file fallback"),
364    ):
365        if forbidden_literal in comments_removed_but_strings_preserved:
366            fail(f"{relative_path}: forbidden {reason} {forbidden_literal!r}")
367
368secret_source = without_test_modules(read_text("crates/omega_identity/src/secret.rs"))
369if re.search(r"\b(?:serde::)?Serialize\b", code_only(secret_source)):
370    fail(
371        "crates/omega_identity/src/secret.rs: secret custody types must not implement "
372        "or derive serialization"
373    )
374
375renderer_roots = (
376    ROOT / "crates/onboarding/src",
377    ROOT / "crates/workspace/src",
378    ROOT / "crates/zed/src",
379)
380secret_identifier = r"(?:mnemonic|nsec|private_key|secret_key|seed)"
381for path, source in production_sources:
382    if not any(path.is_relative_to(root) for root in renderer_roots):
383        continue
384    renderer_code = code_only(source)
385    serialization_patterns = (
386        rf"(?s)#\s*\[\s*derive\s*\([^\]]*\bSerialize\b[^\]]*\)\s*\]"
387        rf"\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+\w+\s*\{{[^}}]*\b{secret_identifier}\b",
388        rf"\bserde_json::to_(?:string|string_pretty|value|vec)\s*\([^;\n]*\b{secret_identifier}\b",
389    )
390    if any(re.search(pattern, renderer_code) for pattern in serialization_patterns):
391        fail(f"{path.relative_to(ROOT)}: renderer secret serialization is forbidden")
392
393startup_relative_path = "crates/onboarding/src/identity_startup.rs"
394startup_code = code_only(without_test_modules(read_text(startup_relative_path)))
395startup_mint_patterns = (
396    r"\bIdentityService\s*::\s*(?:create|generate|import)\s*\(",
397    r"\b(?:service|backend|identity_service)\s*\.\s*(?:create|generate|import)\s*\(",
398    r"\bSecretKeyMaterial\s*::\s*generate\s*\(",
399)
400if any(re.search(pattern, startup_code) for pattern in startup_mint_patterns):
401    fail(f"{startup_relative_path}: startup identity minting is forbidden")
402if "inspect_for_process_start" not in startup_code:
403    fail(f"{startup_relative_path}: startup must inspect custody without minting an identity")
404
405if failures:
406    print("Omega identity verification failed:", file=sys.stderr)
407    for failure in failures:
408        print(f"  - {failure}", file=sys.stderr)
409    raise SystemExit(1)
410
411print(
412    "Omega identity verification passed: dependency locks, Buzz provenance, "
413    "public vector, and secret-boundary tripwires are intact."
414)
415PY
416
Served at tenant.openagents/omega Member data and write actions are omitted.