Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ export function UsageStatisticsSettings() {
const [state, setState] = useState<UsageStatistics | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
const byocSuspended = state?.blocked_by === "byoc_zero_egress";
const summaryTitle = zh ? "基础使用统计" : "Basic usage statistics";
const summaryStatus = byocSuspended
? (zh ? "BYOC 已暂停发送" : "Paused by BYOC")
: (zh ? "告知后默认开启,可关闭" : "on after notice, optional");
useEffect(() => {
let active = true;
usageStatistics().then(value => { if (active) setState(value); })
Expand All @@ -27,7 +32,7 @@ export function UsageStatisticsSettings() {
finally { setBusy(false); }
}
return <details className="personal-capability-scope-note personal-usage-statistics" data-testid="usage-statistics-settings">
<summary>{zh ? "基础使用统计 · 告知后默认开启,可关闭" : "Basic usage statistics · on after notice, optional"}</summary>
<summary>{state ? `${summaryTitle} · ${summaryStatus}` : summaryTitle}</summary>
<p>{zh
? "用于决定平台支持和改进命令体验。每天向 LoopX 的 Cloudflare 收集服务发送随机安装标识、版本、系统、CPU 架构、Python 版本和安装渠道。原有独立 CLI 汇总不带安装标识,包含固定功能、结果、耗时区间和错误类别;首个命令结果立即尝试发送,之后有活动时每隔至少 15 分钟发送一批。"
: "Helps prioritize platform support and CLI improvements. A daily heartbeat sends a random installation ID, version, OS, CPU architecture, Python version and install channel to the LoopX Cloudflare collector. The existing separate CLI summaries remain ID-free, with fixed feature, result, duration and error counts. The first measured result attempts a send immediately; later activity sends batches at least 15 minutes apart."}</p>
Expand All @@ -43,9 +48,10 @@ export function UsageStatisticsSettings() {
</label>
<p>{zh ? "实际生效:" : "Effective: "}{state.effective_context ?? "unknown"} · {state.context_source ?? "default"}.
{zh ? " 环境变量优先;设置用途不会开启统计或改变安装标识,已记录的每日标签不改写。" : " Environment overrides the device label. This setting does not enable statistics or change the ID; recorded daily labels are not rewritten."}</p>
<label><input type="checkbox" checked={state.consent === "enabled" || (state.consent === "default" && !state.notice_required)} disabled={busy}
<label><input type="checkbox" checked={state.consent === "enabled" || (state.consent === "default" && !state.notice_required)} disabled={busy || byocSuspended}
onChange={event => void update(event.target.checked)} /> {zh ? "允许基础使用统计(整台机器)" : "Allow basic usage statistics (this machine)"}</label>
<p role="status">{state.sending ? (zh ? "已允许发送" : "Sending allowed")
: byocSuspended ? (zh ? "BYOC 零出域模式已暂停统计发送" : "BYOC zero egress suspends usage reporting")
: state.blocked_by === "temporary_path" ? (zh ? "临时环境不发送统计" : "Not sending in a temporary environment")
: state.blocked_by === "notice_required" ? (zh ? "等待首次告知确认;尚未发送" : "Awaiting first-use acknowledgment; not sending")
: (zh ? `当前不发送:${({disabled:"已关闭",CI:"CI 环境",DO_NOT_TRACK:"请勿追踪开关",LOOPX_USAGE_PING:"环境变量已关闭",consent_required:"需要明确同意",invalid_policy:"策略配置无效",invalid_endpoint:"接收地址无效",notice_required:"需要重新告知"} as Record<string,string>)[state.blocked_by ?? ""] ?? "请检查配置"}` : `Not sending: ${state.blocked_by}`)}</p>
Expand Down
8 changes: 8 additions & 0 deletions docs/reference/usage-ping.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,14 @@ Additional payload fields and invalid enum combinations are rejected.

## Disclosure and precedence

Self-hosted deployments can suspend usage reporting with
`LOOPX_BYOC_ZERO_EGRESS=1`. The BYOC runtime requires a verified Linux
loopback-only network boundary. Usage status reports `byoc_zero_egress`
when that deployment setting suppresses sending. The saved device consent
and buffers retain their normal retention policy. See
[the BYOC deployment example](../../examples/byoc-domain-operator-template/README.md)
for activation, Doctor readback, and rollback.

Interactive CLI, unattended scripts/agents and the App use the same
**first disclosure → automatic activation → subsequent measurement** policy.
The first ordinary CLI command prints the recipient, fields, purpose, CLI delivery
Expand Down
68 changes: 68 additions & 0 deletions examples/byoc-domain-operator-template/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Self-hosted Domain Operator example

Run a standalone LoopX extension from a directory outside the Core checkout.
The operator checks three independent conditions on an allocation snapshot.
The state must satisfy the domain schema, match the configured PostgreSQL
store binding, and request at most the reserved quantity. The result carries
the check verdicts and a digest of the submitted state.

## Runtime boundary

Set `LOOPX_BYOC_ZERO_EGRESS=1` when launching a Linux LoopX process in a
loopback-only network namespace. For example, start a prepared LoopX image
with Docker's [none network](https://docs.docker.com/engine/network/drivers/none/),
all capabilities dropped, and privilege elevation disabled.

```sh
docker run --rm --network none --cap-drop ALL \
--security-opt no-new-privileges \
-e LOOPX_BYOC_ZERO_EGRESS=1 your-loopx-image loopx doctor --format json
```

Check `byoc_zero_egress.ready` in Doctor's result. LoopX refuses ordinary
commands when the requested isolation is unavailable. Use the reason field to
correct the launch. Use one isolated namespace for the workload and its
approved local services, with separate data volumes and no host service
sockets or relays. Keep that isolation in place for the lifetime of the
workload and its children. PostgreSQL or its HTTPS authority gateway can
listen on loopback inside that namespace. Continue to use the existing
[RemoteAuthority client](../coordination/remote-authority-client.ts) and its
TLS, credential, and store identity checks when using the remote authority
protocol. Store configuration and credentials belong to that deployment.

Usage reporting is suspended for the BYOC process and its children, including
an installation with saved consent. Restart with the mode unset or set to
`0` to use ordinary networking and the saved telemetry preference.

## Mount the example

Run these commands inside the chosen LoopX environment. The hard-coded
identity and JSON packet below are synthetic. In a real deployment, use a
snapshot obtained from your own store and the configured store identity
established by the authority owner. The extension checks the binding against
the supplied configuration and carries no credentials.

```sh
operator_dir=$(mktemp -d)
cp examples/byoc-domain-operator-template/{extension.toml,loopx-byoc-operator,request.example.json} "$operator_dir"/
export PATH="$operator_dir:$PATH"
export LOOPX_BYOC_EXAMPLE_STORE_ID=postgresql:0123456789abcdef0123456789abcdef

loopx extension install --manifest "$operator_dir/extension.toml" --execute
loopx extension enable loopx-byoc-operator-example --execute
loopx extension doctor loopx-byoc-operator-example --execute --format json
loopx extension run loopx-byoc-operator-example \
--input-json "$operator_dir/request.example.json" --execute --format json
```

Look for a ready provider and `provider_result.accepted: true`. Change the
requested quantity to exceed the reservation to see an allocation rejection.
Set a different canonical store identity to see a binding rejection. Doctor
checks the external executable and the shape of its deployment binding. The
store owner verifies the database connection and selects the authority.
The extension's result remains a local verifier judgment. Core owns Goal
acceptance, leases, and settlement.

Run `loopx extension disable loopx-byoc-operator-example --execute` to
disable the operator. Keep the external executable path available while the
revision is in use. Re-run Extension Doctor after changing deployment inputs.
13 changes: 13 additions & 0 deletions examples/byoc-domain-operator-template/domain-state.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Example order allocation",
"type": "object",
"required": ["order", "requested", "reserved", "store_identity"],
"additionalProperties": false,
"properties": {
"order": {"type": "string", "pattern": "^[a-z0-9][a-z0-9-]{0,63}$"},
"requested": {"type": "integer", "minimum": 0, "maximum": 1000000},
"reserved": {"type": "integer", "minimum": 0, "maximum": 1000000},
"store_identity": {"type": "string", "pattern": "^postgresql:[0-9a-f]{32}$"}
}
}
12 changes: 12 additions & 0 deletions examples/byoc-domain-operator-template/extension.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
schema_version = "loopx_extension_manifest_v0"
id = "loopx-byoc-operator-example"
version = "0.1.0"
requires_loopx_api = ">=1,<2"
permissions = []

[runtime]
protocol = "byoc_domain_operator_example_v0"
entrypoint = "loopx-byoc-operator"
doctor_args = ["--doctor"]
required_permissions = []
timeout_seconds = 5
81 changes: 81 additions & 0 deletions examples/byoc-domain-operator-template/loopx-byoc-operator
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Standalone example that evaluates an allocation snapshot without network I/O."""

import argparse
import hashlib
import json
import os
import re
import sys


PROTOCOL = "byoc_domain_operator_example_v0"
STORE_IDENTITY = re.compile(r"postgresql:[0-9a-f]{32}")
MAX_REQUEST_BYTES = 16_384


def valid_state(state):
return (
isinstance(state, dict)
and set(state) == {"order", "requested", "reserved", "store_identity"}
and isinstance(state["order"], str)
and re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", state["order"]) is not None
and all(type(state[key]) is int and 0 <= state[key] <= 1_000_000
for key in ("requested", "reserved"))
and isinstance(state["store_identity"], str)
and STORE_IDENTITY.fullmatch(state["store_identity"]) is not None
)


def evaluate(request, configured_store):
if (
not isinstance(request, dict)
or set(request) != {"schema_version", "domain_state"}
or request["schema_version"] != PROTOCOL
):
return {"ok": False, "error": "invalid_request"}
state = request["domain_state"]
if not valid_state(state):
return {
"ok": True,
"accepted": False,
"checks": {"shape": "failed", "store_binding": "unavailable", "allocation": "unavailable"},
}
store_matches = state["store_identity"] == configured_store
within_reservation = state["requested"] <= state["reserved"]
frozen_state = json.dumps(state, sort_keys=True, separators=(",", ":")).encode("utf-8")
return {
"ok": True,
"accepted": store_matches and within_reservation,
"candidate_sha": "sha256:" + hashlib.sha256(frozen_state).hexdigest(),
"checks": {
"shape": "passed",
"store_binding": "passed" if store_matches else "failed",
"allocation": "passed" if within_reservation else "failed",
},
}


def main():
parser = argparse.ArgumentParser(prog="loopx-byoc-operator")
parser.add_argument("--doctor", action="store_true")
args = parser.parse_args()
store = os.environ.get("LOOPX_BYOC_EXAMPLE_STORE_ID", "")
if args.doctor:
return 0 if STORE_IDENTITY.fullmatch(store) else 1
if not STORE_IDENTITY.fullmatch(store):
payload = {"ok": False, "error": "store_binding_unavailable"}
else:
try:
data = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
if len(data) > MAX_REQUEST_BYTES:
raise ValueError("oversized")
payload = evaluate(json.loads(data.decode("utf-8")), store)
except (OSError, ValueError, RecursionError):
payload = {"ok": False, "error": "invalid_request"}
print(json.dumps({"schema_version": PROTOCOL, **payload}, ensure_ascii=True))
return 0 if payload["ok"] else 1


if __name__ == "__main__":
raise SystemExit(main())
9 changes: 9 additions & 0 deletions examples/byoc-domain-operator-template/request.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"schema_version": "byoc_domain_operator_example_v0",
"domain_state": {
"order": "synthetic-order",
"requested": 3,
"reserved": 5,
"store_identity": "postgresql:0123456789abcdef0123456789abcdef"
}
}
22 changes: 20 additions & 2 deletions loopx/cli_commands/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Any
from pathlib import Path

from ..control_plane.runtime.byoc_zero_egress import inspect_byoc_zero_egress
from ..doctor import collect_doctor, render_doctor_markdown
from ..host_loop_activation import SUPPORTED_AGENT_TYPES

Expand Down Expand Up @@ -72,6 +73,11 @@ def handle_doctor_command(
}
if host_options and args.agent_type != "zcode":
raise ValueError("ZCode path options require doctor --agent-type zcode.")
output_format = getattr(args, "subcommand_format", None) or args.format
byoc = inspect_byoc_zero_egress()
if byoc is not None and not byoc["ready"]:
print_payload({"ok": False, "byoc_zero_egress": byoc}, output_format, _render_byoc_doctor)
return 1
restart: dict[str, Any] | None = None
if bool(getattr(args, "restart_runtime", False)):
from ..control_plane.effect_runtime import restart_effect_runtime
Expand All @@ -87,6 +93,18 @@ def handle_doctor_command(
)
if restart is not None:
payload["effect_runtime_restart"] = restart
output_format = getattr(args, "subcommand_format", None) or args.format
print_payload(payload, output_format, render_doctor_markdown)
if byoc is not None:
payload["byoc_zero_egress"] = byoc
print_payload(payload, output_format, _render_byoc_doctor if byoc is not None else render_doctor_markdown)
return 0 if payload.get("ok") else 1


def _render_byoc_doctor(payload: dict[str, Any]) -> str:
status = payload["byoc_zero_egress"]
if not status["ready"]:
return (
f"LoopX BYOC zero egress: unavailable ({status['reason']}).\n"
"Use LOOPX_BYOC_ZERO_EGRESS=1 in a Linux loopback-only namespace with all "
"capabilities dropped, no new privileges, and no inherited sockets. Usage statistics are suppressed."
)
return render_doctor_markdown(payload) + "\n\nBYOC zero egress: loopback only. Usage statistics are suppressed."
7 changes: 7 additions & 0 deletions loopx/cli_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1168,6 +1168,13 @@ def main(argv: list[str] | None = None) -> int:
standalone_core=standalone, workspace_installed=standalone and _workspace_installed()), end="")
return 0
command = _top_level_command(raw_argv)
if command != "doctor" and os.environ.get("LOOPX_BYOC_ZERO_EGRESS", "0") != "0":
from .control_plane.runtime.byoc_zero_egress import inspect_byoc_zero_egress

byoc = inspect_byoc_zero_egress()
if byoc is not None and not byoc["ready"]:
print(f"LoopX BYOC runtime blocked ({byoc['reason']}). Run loopx doctor for details.", file=sys.stderr)
return 2
if command is None and _standalone_core():
# The canonical global parser handles version and malformed/missing
# arguments without importing an intentionally omitted command facade.
Expand Down
59 changes: 59 additions & 0 deletions loopx/control_plane/runtime/byoc_zero_egress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""Read the process-isolation facts for the opt-in BYOC runtime."""

from __future__ import annotations

import os
import socket
import sys
from pathlib import Path
from typing import TypedDict


class ByocZeroEgressStatus(TypedDict):
ready: bool
reason: str
telemetry_suppressed: bool


def _process_is_unprivileged() -> bool:
status = {}
for line in Path("/proc/self/status").read_text(encoding="ascii").splitlines():
name, _, value = line.partition(":")
status[name] = value.strip()
capability_fields = ("CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb")
return status["NoNewPrivs"] == "1" and all(int(status[field], 16) == 0 for field in capability_fields)


def _has_inherited_socket() -> bool:
for descriptor in Path("/proc/self/fd").iterdir():
try:
if os.readlink(descriptor).startswith("socket:["):
return True
except FileNotFoundError:
# Enumerating the directory temporarily opens its own descriptor.
continue
return False


def inspect_byoc_zero_egress() -> ByocZeroEgressStatus | None:
"""Require a Linux process with loopback only and no privilege to add egress."""
mode = os.environ.get("LOOPX_BYOC_ZERO_EGRESS", "0")
if mode == "0":
return None
# An invalid value cannot silently disable the network boundary.
if mode != "1":
return {"ready": False, "reason": "invalid_mode", "telemetry_suppressed": True}
if sys.platform != "linux":
return {"ready": False, "reason": "linux_isolation_required", "telemetry_suppressed": True}
try:
if [name for _, name in socket.if_nameindex()] != ["lo"]:
return {"ready": False, "reason": "non_loopback_interface", "telemetry_suppressed": True}
if Path("/sys/class/net/lo/type").read_text(encoding="ascii").strip() != "772":
return {"ready": False, "reason": "loopback_identity_invalid", "telemetry_suppressed": True}
if not _process_is_unprivileged():
return {"ready": False, "reason": "process_can_gain_privileges", "telemetry_suppressed": True}
if _has_inherited_socket():
return {"ready": False, "reason": "inherited_socket", "telemetry_suppressed": True}
except (OSError, ValueError, KeyError):
return {"ready": False, "reason": "isolation_observation_unavailable", "telemetry_suppressed": True}
return {"ready": True, "reason": "loopback_only", "telemetry_suppressed": True}
1 change: 1 addition & 0 deletions loopx/control_plane/runtime/usage_statistics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ function automaticNoticeRequired(state: State, ctx: Context, path: string): bool
}
export function blockedBy(state: State, ctx: Context, path: string): string | null {
const env = ctx.env;
if (env.LOOPX_BYOC_ZERO_EGRESS !== undefined && env.LOOPX_BYOC_ZERO_EGRESS !== "0") return "byoc_zero_egress";
if (["0", "false", "no", "off"].includes((env.LOOPX_USAGE_PING ?? "").trim().toLowerCase())) return "LOOPX_USAGE_PING";
if (!["", "0"].includes((env.DO_NOT_TRACK ?? "").trim())) return "DO_NOT_TRACK";
if (!["", "0", "false"].includes((env.CI ?? "").trim().toLowerCase())) return "CI";
Expand Down
2 changes: 1 addition & 1 deletion loopx/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def main(argv: list[str] | None = None) -> int:
if raw_argv == ["--version"]:
print(f"loopx {__version__}")
return 0
if argv is None:
if argv is None and os.environ.get("LOOPX_BYOC_ZERO_EGRESS", "0") == "0":
try:
native_argv = _native_scheduler_followup_argv(raw_argv)
except RuntimeError as exc:
Expand Down
3 changes: 2 additions & 1 deletion loopx/usage_ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ def _environment_suppressed(environment: Mapping[str, str] | None = None) -> boo
whitespace = (" \t\n\r\v\f\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005"
"\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff")
return (
env.get("LOOPX_USAGE_PING", "").strip(whitespace).lower() in {"0", "false", "no", "off"}
env.get("LOOPX_BYOC_ZERO_EGRESS", "0") != "0"
or env.get("LOOPX_USAGE_PING", "").strip(whitespace).lower() in {"0", "false", "no", "off"}
or env.get("DO_NOT_TRACK", "").strip(whitespace) not in {"", "0"}
or env.get("CI", "").strip(whitespace).lower() not in {"", "0", "false"}
)
Expand Down
Loading
Loading