diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..da11c06 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +*.py text eol=lf +*.sh text eol=lf +*.bash text eol=lf diff --git a/.github/workflows/ha-plugin-candidate.yml b/.github/workflows/ha-plugin-candidate.yml new file mode 100644 index 0000000..936f61f --- /dev/null +++ b/.github/workflows/ha-plugin-candidate.yml @@ -0,0 +1,116 @@ +name: Build signed Home Assistant plugin candidate + +on: + workflow_call: + inputs: + version: + description: Plugin version, for example 1.0.0 + required: true + type: string + connector_commit: + description: Full reviewed Home Assistant connector commit + required: true + type: string + sdk_tag: + description: Published connector SDK tag used by the connector + required: true + type: string + sdk_commit: + description: Full commit referenced by the SDK tag + required: true + type: string + installer_commit: + description: Full reviewed installer commit containing this workflow and its build inputs + required: true + type: string + secrets: + TP_PLUGIN_CATALOG_SIGNING_KEY: + required: true + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-24.04 + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.installer_commit }} + - name: Validate release inputs + env: + VERSION: ${{ inputs.version }} + CONNECTOR_COMMIT: ${{ inputs.connector_commit }} + SDK_TAG: ${{ inputs.sdk_tag }} + SDK_COMMIT: ${{ inputs.sdk_commit }} + run: | + set -euo pipefail + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$CONNECTOR_COMMIT" =~ ^[0-9a-f]{40}$ ]] + [[ "$SDK_COMMIT" =~ ^[0-9a-f]{40}$ ]] + [[ "$SDK_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + git ls-remote --tags https://github.com/ThingsPanel/device-connector-sdk-go.git "refs/tags/$SDK_TAG" "refs/tags/$SDK_TAG^{}" > "$RUNNER_TEMP/sdk-ref" + actual=$(awk '/\^\{\}$/ {print $1; found=1} END {if (!found) {}}' "$RUNNER_TEMP/sdk-ref") + if [ -z "$actual" ]; then actual=$(awk 'NR==1 {print $1}' "$RUNNER_TEMP/sdk-ref"); fi + test "$actual" = "$SDK_COMMIT" + - uses: actions/checkout@v4 + with: + repository: ThingsPanel/thingspanel-device-connector-homeassistant + ref: ${{ inputs.connector_commit }} + path: ha-connector + - uses: actions/setup-go@v5 + with: + go-version: '1.24.x' + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - name: Build architecture-specific Agent and connector image + env: + ARCH: ${{ matrix.arch }} + VERSION: ${{ inputs.version }} + CONNECTOR_COMMIT: ${{ inputs.connector_commit }} + SDK_TAG: ${{ inputs.sdk_tag }} + run: | + set -euo pipefail + test "$(git -C ha-connector rev-parse HEAD)" = "$CONNECTOR_COMMIT" + test -z "$(git -C ha-connector status --porcelain)" + python3 -c 'import pathlib,sys; s=pathlib.Path("ha-connector/go.mod").read_text(); assert "replace github.com/thingspanel/device-connector-sdk-go" not in s; assert ("github.com/thingspanel/device-connector-sdk-go " + sys.argv[1]) in s' "$SDK_TAG" + mkdir -p out + (cd agent && GOOS=linux GOARCH="$ARCH" CGO_ENABLED=0 go build -trimpath -buildvcs=false -o "../out/tp-agent-linux-$ARCH" ./cmd/tp-agent) + docker buildx build --platform "linux/$ARCH" --provenance=false --load --tag "thingspanel/homeassistant-connector:$VERSION-$ARCH" ha-connector + docker image inspect "thingspanel/homeassistant-connector:$VERSION-$ARCH" > "$RUNNER_TEMP/image.json" + python3 -c 'import json,os,pathlib; i=json.loads(pathlib.Path(os.environ["RUNNER_TEMP"],"image.json").read_text())[0]; assert i["Os"]=="linux" and i["Architecture"]==os.environ["ARCH"]; assert not (i.get("Config",{}).get("Labels") or i.get("Config",{}).get("Volumes") or i.get("Config",{}).get("OnBuild")); pathlib.Path(os.environ["RUNNER_TEMP"],"image-id").write_text(i["Id"])' + docker save -o "out/ha-image-linux-$ARCH.tar" "thingspanel/homeassistant-connector:$VERSION-$ARCH" + - name: Sign and verify the catalog + env: + ARCH: ${{ matrix.arch }} + VERSION: ${{ inputs.version }} + CONNECTOR_COMMIT: ${{ inputs.connector_commit }} + SDK_COMMIT: ${{ inputs.sdk_commit }} + INSTALLER_COMMIT: ${{ inputs.installer_commit }} + SIGNING_KEY: ${{ secrets.TP_PLUGIN_CATALOG_SIGNING_KEY }} + run: | + set -euo pipefail + test -n "$SIGNING_KEY" + umask 077 + key="$RUNNER_TEMP/plugin-signing-key.pem" + trap 'rm -f "$key"' EXIT + printf '%s\n' "$SIGNING_KEY" > "$key" + export IMAGE_ID="$(cat "$RUNNER_TEMP/image-id")" + export IMAGE_SHA="$(sha256sum "out/ha-image-linux-$ARCH.tar" | cut -d' ' -f1)" + export AGENT_SHA="$(sha256sum "out/tp-agent-linux-$ARCH" | cut -d' ' -f1)" + python3 -c 'import json,os,pathlib; e=json.loads(pathlib.Path("plugins/homeassistant.json").read_text()); e.update(version=os.environ["VERSION"], image_id=os.environ["IMAGE_ID"], image_platform="linux/"+os.environ["ARCH"], image_archive_sha256=os.environ["IMAGE_SHA"], source_commit=os.environ["CONNECTOR_COMMIT"], sdk_commit=os.environ["SDK_COMMIT"], installer_commit=os.environ["INSTALLER_COMMIT"]); pathlib.Path(os.environ["RUNNER_TEMP"],"homeassistant.json").write_text(json.dumps(e,sort_keys=True,indent=2)+"\n")' + python3 tools/plugin_catalog.py publish --key "$key" --out "$RUNNER_TEMP/catalog" --version "$VERSION" --valid-days 3650 --plugin-file "$RUNNER_TEMP/homeassistant.json" --target-platform "linux/$ARCH" --release-tag "plugin-ha-v$VERSION" --agent-sha256 "$AGENT_SHA" + python3 tools/plugin_catalog.py verify --trust-root config/native/plugin_catalog_trust.pem --catalog "$RUNNER_TEMP/catalog/plugin-catalog.json" + cp "$RUNNER_TEMP/catalog/plugin-catalog.json" "out/catalog-linux-$ARCH.json" + cp "$RUNNER_TEMP/catalog/plugin-catalog.json.sig" "out/catalog-linux-$ARCH.json.sig" + - uses: actions/upload-artifact@v4 + with: + name: homeassistant-plugin-linux-${{ matrix.arch }} + path: out/* + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 72bec6d..a26e5f0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,6 +18,9 @@ concurrency: jobs: + update-transaction: + uses: ./.github/workflows/update-transaction.yml + # ── 确定版本号 ────────────────────────────────────────────────────────────── prepare: runs-on: ubuntu-latest @@ -52,9 +55,13 @@ jobs: TP_AUTOMATION_TOKEN=syntax-check-only TP_MQTT_USER=syntax-check-only TP_MQTT_PASSWORD=syntax-check-only + TP_PROTOCOL_MQTT_USER=syntax-check-only + TP_PROTOCOL_MQTT_PASSWORD=syntax-check-only TP_NATIVE_DB_PASSWORD=syntax-check-only TP_NOTIFICATION_KEYRING_B64=syntax-check-only + TP_THINGSVIS_AUTH_SECRET=syntax-check-only-not-a-runtime-auth-secret EOF + python3 config/native/prepare.py - name: Validate docker-compose syntax run: docker compose config --quiet @@ -68,6 +75,7 @@ jobs: --add-host thingsvis-studio:127.0.0.1 \ --add-host encore-api:127.0.0.1 \ --add-host notification-core:127.0.0.1 \ + -v "$PWD/config/native:/run/config:ro" \ -v "$PWD/niginx.conf:/etc/nginx/nginx.conf:ro" \ nginx:alpine nginx -t fi @@ -81,7 +89,7 @@ jobs: build-windows: runs-on: windows-latest - needs: [prepare, validate] + needs: [prepare, validate, update-transaction] steps: - uses: actions/checkout@v4 @@ -117,7 +125,7 @@ jobs: build-macos: runs-on: macos-latest - needs: [prepare, validate] + needs: [prepare, validate, update-transaction] steps: - uses: actions/checkout@v4 @@ -169,9 +177,36 @@ jobs: sha256sum ../install.sh >> SHA256SUMS.txt cat SHA256SUMS.txt + # The signing key is a repository secret (an ECDSA P-256 private key, PEM). Without + # it no manifest is produced and installers keep their unsigned behaviour. + # The matching public key is the trust root installers receive out of band; it is never + # taken from this repository or from the payload. + - name: Sign release manifest + id: sign + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + run: | + if [ -z "$RELEASE_SIGNING_KEY" ]; then + echo "::warning::RELEASE_SIGNING_KEY is not configured; the release manifest is not signed" + echo "signed=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + umask 077 + key="$RUNNER_TEMP/release-key.pem" + printf '%s\n' "$RELEASE_SIGNING_KEY" > "$key" + mkdir -p dist/signed + git archive HEAD | tar -x -C dist/signed + python3 tools/sign_release.py --payload dist/signed --key "$key" \ + --version "${{ needs.prepare.outputs.version }}" --commit "$GITHUB_SHA" \ + --publisher "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/.github/workflows/release.yml" + shred -u "$key" 2>/dev/null || rm -f "$key" + cp dist/signed/release-manifest.json dist/signed/release-manifest.json.sig dist/ + echo "signed=true" >> "$GITHUB_OUTPUT" + - name: Create Release uses: softprops/action-gh-release@v2 with: + fail_on_unmatched_files: false tag_name: ${{ needs.prepare.outputs.version }} name: "ThingsPanel All-in-One ${{ needs.prepare.outputs.version }}" body: | @@ -196,6 +231,8 @@ jobs: draft: false prerelease: ${{ contains(needs.prepare.outputs.version, 'rc') || contains(needs.prepare.outputs.version, 'beta') }} files: | + dist/release-manifest.json + dist/release-manifest.json.sig dist/windows/*.exe dist/macos/*.pkg dist/SHA256SUMS.txt diff --git a/.github/workflows/update-transaction.yml b/.github/workflows/update-transaction.yml new file mode 100644 index 0000000..3b51d43 --- /dev/null +++ b/.github/workflows/update-transaction.yml @@ -0,0 +1,28 @@ +name: Installer update transaction + +on: + workflow_call: + +jobs: + transaction: + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Test staged update, recovery and locking without Docker or network + run: python -m unittest discover -s tests -v + - name: Parse PowerShell entrypoints without executing installation + if: runner.os == 'Windows' + shell: pwsh + run: | + foreach ($path in @('install.core.ps1', 'upgrade.ps1')) { + $tokens = $null + $errors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile((Join-Path $PWD $path), [ref]$tokens, [ref]$errors) + if ($errors.Count -gt 0) { throw "PowerShell parse failed: $path" } + } diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 4f47c77..313b192 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -15,11 +15,16 @@ on: - 'uninstall.ps1' - '*.bash' - 'config/native/**' + - 'tests/**' - 'packaging/**' - '.github/workflows/validate.yml' + - '.github/workflows/update-transaction.yml' - '.github/workflows/release.yml' jobs: + update-transaction: + uses: ./.github/workflows/update-transaction.yml + validate: runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index caf143f..649341c 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,11 @@ Desktop.ini packaging/macos/.build/ *.bak *.bak.* +.thingspanel-update/ +__pycache__/ +# Isolated regression temporary roots (sandbox tempfile may choose cwd). +tp-stage-synthetic-*/ +tp-update-unit-*/ # IDE .vscode/settings.json diff --git a/agent/README.md b/agent/README.md new file mode 100644 index 0000000..e41e4d6 --- /dev/null +++ b/agent/README.md @@ -0,0 +1,188 @@ +# Agent local state and create-only Docker adapter (candidate) + +This Linux-only package has a persistent state kernel and a bounded local +`DockerPreparer.Prepare` / `Query` adapter. It can create an **unstarted** Docker +container and recover its original receipt. It never starts, execs, restarts, +activates or removes a workload. There is no service main, network control API, +user authentication, A08 wiring, SDK binding fence, or business execution path. +Activation and deployment as a full Agent remain disabled. + +## Prepare/query contract + +An authenticated control-plane integration must supply the existing instance +identity and accept its generation before calling this package. The adapter does +not enroll a host, invent a generation, or interpret local generation state as a +cross-host execution fence. It reuses `HostID`, `Requests`, `Resources` and +`MaxGeneration` in the original state file. `preparations` is an optional map in +that same journal; it is not a second resource owner or installation ledger. + +The trusted service configuration defines an allowlist of profile names mapped +to an exact local `sha256:`, a fixed absolute entrypoint and fixed args. +Requests can select a configured profile but cannot supply image tags, commands, +environment, ports, networks, mounts, devices or credentials. The adapter does +not pull images. A local image ID proves immutable local content, not the plugin +catalogue/signature/withdrawal trust chain; that chain remains an upstream gate. + +`NewUnixDockerEngine` requires an explicit operator-selected local Unix socket. +It ignores `DOCKER_HOST` and registry credentials. Its only runtime actions are +image inspect, container inspect and container create through Docker Engine API +v1.44. Unsupported daemons return an error without falling back to a mutable tag +or another endpoint. The narrow versioned transport is based on the official +[Docker Engine API reference](https://docs.docker.com/reference/api/engine/). + +The create policy fixes non-root UID/GID `65534:65534`, read-only rootfs, network +`none`, no added capabilities, `no-new-privileges`, no restart policy, disabled +healthcheck, no application environment other than a fixed PATH, and bounded +memory/CPU/PIDs. No volumes, port bindings, devices or secrets are supplied. +Images with inherited volumes, exposed ports, labels, non-PATH environment or +OnBuild instructions are rejected before intent/create. These deliberate image +restrictions require an explicitly reviewed compatible preparation image. + +The existing OS file lock spans generation recheck, durable intent, one create +attempt, inspection and receipt persistence. The original instance/key +determines the container name; the request digest includes the host, generation +and immutable profile. Changed parameters conflict with the same key. A single +runtime resource is held by the host/instance across keys and generations, so +changing a key cannot create another container for an unresolved instance. +Different instances retain different names even for the same image/version/key. + +A daemon request may finish after a client timeout; the local lock cannot cancel +it. `AcceptGeneration` therefore refuses a higher generation while the instance +has an intent or unknown preparation. A known prepared old container also retains +its exclusive runtime resource until a future approved cleanup/takeover flow. +No newer generation can reuse that resource through the generic state API. + +- `prepared` means the exact original container exists in Docker's `created` + state, has never started according to its inspected state, and matches the + recorded ID, image, ownership labels and restricted configuration. `active` + is always `false`. It is not an activation grant. +- `unknown` means the original intent cannot yet be confirmed. A timeout, + process death, failed receipt write, missing container after intent, changed + container or uncertain Docker response never causes another create attempt. + Repeating Prepare on an existing intent only inspects the original name. +- `not_observed` means Query found no local committed intent for that identity. + It does not establish global absence or authorize an unrelated new key. + +Intent and the existing resource reservation are written together before create. +A successful inspection becomes a receipt only after the updated state is +persisted. If receipt persistence fails, the caller receives an error/unknown +result. A restarted process queries the original container instead of guessing +that the effect failed. Containers without the original local durable intent +are never adopted, including after local state loss. + +Generic `Release` and `ReconcileRelease` refuse resources with a preparation +record. Forgetting a local reservation must not orphan or transfer a real +container. Container removal and stale-generation takeover require a future +explicit owner-reviewed recovery implementation; this adapter provides neither. +Once a preparation record exists, older kernels reject its new field rather +than silently discard it. Downgrade to an older state writer is unsupported. + +## Persistent state assumptions + +Explicit host enrollment must precede `Open`; a missing or corrupt state is +an error. The installer or control plane must independently authenticate the +host identity and resolve lost state rather than silently initialize it again. +Call `AcceptGeneration` before `Reserve`. Request identities persist after +release; a replay of a released request does not re-acquire its resource. +Older holds remain reserved after a generation change until reconciliation. + +`ReconcileRelease` accepts an injected verifier but does not authenticate it. +Its two-phase local check prevents a stale local snapshot from releasing a +changed reservation; it cannot fence external writers or prove that a remote +instance has stopped. Integration requires a trusted verifier, external +execution fencing, and safe proof/ownership rules. Until then, do not wire +this package to an externally callable operation. + +Resource identifiers are opaque strings and are not canonicalized. Adapters +must define and validate stable canonical identities (including port address +and protocol, hardware identity, and capacity semantics) before using them. +The state directory and all of its ancestors must be controlled by trusted +users. The code checks ownership and write permissions of the final directory, +and checks the final state and lock files for ownership, permissions, regular +file type and symlinks. It does not pin or validate ancestor directories, or +defend against replacement by another process with the same service UID. +Host identity anchored outside this file has not yet been implemented. Missing +local state requires reconciliation, not an +automatic reset. Persistence uses a same-directory temporary file, file sync, +rename and directory sync. Process death and original-key recovery are covered +by the tests below; power-loss and fsync-failure injection remain unverified. + +The package has no database connection. Platform install records, installer +migration ledgers and business resources retain their existing owners. A local +Docker administrator or another process able to replace this service's state +or socket is outside this local fence. Even a prepared container cannot be +enabled for business until the real platform identity/current-binding and SDK +receiver fence are connected. + +## Validation and remaining integration + +Run the complete Linux module tests with: + +```sh +go test -race -count=1 -v ./... +``` + +The tests exercise the actual state/adapter methods, same-key digest conflict, +distinct instances, current generation, restricted image/config inspection, +unknown outcomes, real state-file rename failures, two OS processes and SIGKILL +before/after a create side effect. The default Unix socket daemon is an explicit +HTTP fixture. It proves protocol and process recovery behavior, not real Docker +container creation. No environment restriction is silently converted to a pass. + +The separate real Docker tests require a reviewed **already present** image and +an explicit local socket: + +```sh +TP_AGENT_REAL_DOCKER=1 \ +TP_AGENT_DOCKER_SOCKET=/var/run/docker.sock \ +TP_AGENT_DOCKER_IMAGE_ID='sha256:' \ +go test -race -count=1 -v -run '^TestPreparationRealDocker' ./... +``` + +They drop a real create response, reopen the original state, run two processes, +and kill a preparing process after the real daemon accepted create but before +receipt persistence. The test host identity is unique and starts with +`tp-takeover-b-installer-agent-`. Product container names remain deterministic +`tp-agent-prepared-`. Cleanup occurs only for each test's +original persisted intent after a complete ownership/config/state check, with +non-forced removal of a still-unstarted container. Failed ownership checks leave +the object for explicit review. Production code has no removal operation. + +Real Docker tests skip explicitly without those variables. Their presence does +not imply execution in this candidate. Windows, a real authenticated Agent +service, connector activation/pause/upgrade/revoke, receiver-side business +fencing, full artifact trust, and J-G1 through J-G4 remain separate acceptance +work. This adapter must not be used to lift those guards. + +## Activation, revocation and the service (added on `wp/i1-pg-profiles`) + +`activate.go` adds the only path that starts a prepared container, and `service.go` / +`cmd/tp-agent` expose it. This closes the "no service main, no activation" gap, but it is **not** +the finished product: there is no enrolment of the host with the platform, no marketinstall/A08/SDK +wiring, and the bearer token is provisioned out of band. + +* A prepared container stays `created` until a control plane with the token issues + `/v1/grant` for the accepted generation (a lease of up to 24 h) and calls `/v1/activate`. +* Everything is re-checked under one lock: accepted generation, key, lease and revocation. + An old generation (`409`), a revoked generation, an expired lease and an ungranted instance never start. +* `/v1/revoke` is durable before anything is stopped and is permanent for that generation. +* The sweeper (`-sweep-interval`) stops instances whose lease ended or whose generation was superseded. +* `/v1/retire` removes a stopped, superseded container (never forced) and releases the exclusive resource + so the newer generation can prepare; a still-running or current generation is refused. +* A container that has ever started is never queried through the create-only adapter (that would + rewrite its receipt as unknown); the activation ledger answers instead. +* API: POST JSON over the Unix socket (`0600`), `Authorization: Bearer `: + `/v1/accept-generation /v1/prepare /v1/grant /v1/activate /v1/revoke /v1/retire /v1/status /v1/sweep`. + +Real-Docker evidence (opt-in, Linux): `TP_AGENT_REAL_DOCKER=1 TP_AGENT_DOCKER_IMAGE_ID= TP_AGENT_DOCKER_SOCKET=` +for the package tests and `TP_AGENT_E2E_BIN` for `cmd/tp-agent`; the image needs a program at `/pluginstub`. + +### Plugin profiles that need the platform (added later) + +A trusted profile may carry three optional fields, never accepted from an API request: `network` +(an existing user-defined Docker network; `none`, `host`, `bridge`, `default` are refused), `env` +(fixed `KEY=VALUE` pairs; `PATH` cannot be overridden) and `reviewed_image_metadata` (accept the pinned +image's own exposed-port and environment declarations; volumes, labels and OnBuild stay forbidden and +nothing is ever published). All three default to off, so existing profiles and ledgers are unchanged. +The profiles file holds secrets and must be mode 0600. `tp-agentctl` posts one request to the socket +(`tp-agentctl -socket S -token-file F /v1/status instance=x generation=1`). diff --git a/agent/activate.go b/agent/activate.go new file mode 100644 index 0000000..4f852d0 --- /dev/null +++ b/agent/activate.go @@ -0,0 +1,568 @@ +//go:build linux + +package agent + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "time" +) + +// Activation is the only place an Agent-prepared container is ever started. +// +// A prepared container stays "created" until a control plane that owns the +// instance issues an explicit, time-limited grant for exactly one accepted +// generation. Every later step re-checks that generation, the grant lease and +// the revocation flag under one lock. Revocation is written before anything is +// stopped and is permanent for that generation: a new execution needs a newer +// accepted generation. Lease expiry and a newer accepted generation both stop +// the container, so an instance that lost its control plane or was superseded +// cannot keep producing effects. +var ( + ErrNotPrepared = errors.New("container is not in the prepared state for this generation") + ErrNotGranted = errors.New("no activation grant for this instance, generation and request key") + ErrLeaseExpired = errors.New("activation lease has expired; a newer generation is required") + ErrRevoked = errors.New("activation was revoked for this generation; a newer generation is required") + ErrActivationUnresolved = errors.New("an earlier start or stop outcome is unresolved; owner review is required") +) + +const ( + activationVersion = 1 + maxGrantTTL = 24 * time.Hour +) + +type activationEngine interface { + inspectContainer(ctx context.Context, name string) (dockerContainer, bool, error) + startContainer(ctx context.Context, id string) error + stopContainer(ctx context.Context, id string) error + removeContainer(ctx context.Context, id string) error +} + +// ActivationRecord is the durable per-instance activation receipt. +type ActivationRecord struct { + Instance string `json:"instance"` + Generation uint64 `json:"generation"` + RequestKey string `json:"request_key"` + ContainerName string `json:"container_name"` + ContainerID string `json:"container_id"` + GrantID string `json:"grant_id"` + LeaseExpires int64 `json:"lease_expires_unix"` + Revoked bool `json:"revoked"` + RevokeReason string `json:"revoke_reason,omitempty"` + StartIntent bool `json:"start_intent"` + Started bool `json:"started"` + StopIntent bool `json:"stop_intent"` +} + +type activationDisk struct { + Version int `json:"version"` + Instances map[string]*ActivationRecord `json:"instances"` +} + +type Activator struct { + store *Store + preparer *DockerPreparer + engine activationEngine + path string + now func() time.Time +} + +func NewActivator(store *Store, preparer *DockerPreparer, engine *UnixDockerEngine) (*Activator, error) { + if store == nil || preparer == nil || engine == nil { + return nil, ErrPreparationPolicy + } + return newActivator(store, preparer, engine), nil +} + +func newActivator(store *Store, preparer *DockerPreparer, engine activationEngine) *Activator { + return &Activator{store: store, preparer: preparer, engine: engine, path: store.path + ".activation", now: time.Now} +} + +func (engine *UnixDockerEngine) startContainer(ctx context.Context, id string) error { + if !validHexID(id) { + return ErrPreparationPolicy + } + status, err := engine.call(ctx, http.MethodPost, "/containers/"+id+"/start", nil, nil) + if err != nil { + return err + } + if status != http.StatusNoContent && status != http.StatusNotModified { + return fmt.Errorf("Docker start result unconfirmed (status %d)", status) + } + return nil +} + +func (engine *UnixDockerEngine) stopContainer(ctx context.Context, id string) error { + if !validHexID(id) { + return ErrPreparationPolicy + } + status, err := engine.call(ctx, http.MethodPost, "/containers/"+id+"/stop?t=5", nil, nil) + if err != nil { + return err + } + if status != http.StatusNoContent && status != http.StatusNotModified { + return fmt.Errorf("Docker stop result unconfirmed (status %d)", status) + } + return nil +} + +func (engine *UnixDockerEngine) removeContainer(ctx context.Context, id string) error { + if !validHexID(id) { + return ErrPreparationPolicy + } + // Never forced: a running or otherwise busy container is a refusal, not a kill. + status, err := engine.call(ctx, http.MethodDelete, "/containers/"+id+"?force=false&v=false", nil, nil) + if err != nil { + return err + } + if status != http.StatusNoContent && status != http.StatusNotFound { + return fmt.Errorf("Docker remove result unconfirmed (status %d)", status) + } + return nil +} + +func (a *Activator) loadLocked() (activationDisk, error) { + disk := activationDisk{Version: activationVersion, Instances: map[string]*ActivationRecord{}} + raw, err := os.ReadFile(a.path) + if errors.Is(err, os.ErrNotExist) { + return disk, nil + } + if err != nil { + return disk, err + } + if err := json.Unmarshal(raw, &disk); err != nil || disk.Version != activationVersion || disk.Instances == nil { + return activationDisk{}, ErrInvalidState + } + return disk, nil +} + +func (a *Activator) saveLocked(disk activationDisk) error { + raw, err := json.Marshal(disk) + if err != nil { + return err + } + temp, err := os.CreateTemp(filepath.Dir(a.path), ".activation-*") + if err != nil { + return err + } + name := temp.Name() + defer os.Remove(name) + if err := temp.Chmod(0600); err != nil { + temp.Close() + return err + } + if _, err := temp.Write(raw); err != nil { + temp.Close() + return err + } + if err := temp.Sync(); err != nil { + temp.Close() + return err + } + if err := temp.Close(); err != nil { + return err + } + if err := os.Rename(name, a.path); err != nil { + return err + } + dir, err := os.Open(filepath.Dir(a.path)) + if err != nil { + return err + } + defer dir.Close() + return dir.Sync() +} + +func (a *Activator) accepted(instance string, generation uint64) error { + _, generations, _, err := a.store.Snapshot() + if err != nil { + return err + } + current := generations[instance] + switch { + case generation == 0 || current == 0: + return ErrGenerationNotAccepted + case generation < current: + return ErrGenerationStale + case generation > current: + return ErrGenerationNotAccepted + } + return nil +} + +// Grant lets exactly one accepted generation of a prepared container start +// until now+ttl. It never starts anything. +func (a *Activator) Grant(ctx context.Context, instance string, generation uint64, key, grantID string, ttl time.Duration) (ActivationRecord, error) { + var out ActivationRecord + if !valid(instance) || !valid(key) || !valid(grantID) || ttl <= 0 || ttl > maxGrantTTL { + return out, ErrPreparationPolicy + } + if err := a.accepted(instance, generation); err != nil { + return out, err + } + // A container that was ever started must never be queried through the create-only + // adapter: that check would rewrite its ledger entry as unknown. The activation + // ledger answers first. + if existing, err := a.Status(instance); err != nil { + return out, err + } else if existing.Generation == generation && (existing.Revoked || existing.StartIntent || existing.Started) { + if existing.Revoked { + return out, ErrRevoked + } + return out, ErrActivationUnresolved + } else if existing.Generation > generation { + return out, ErrGenerationStale + } + observation, err := a.preparer.Query(ctx, instance, generation, key) + if err != nil { + return out, err + } + if observation.State != PreparationPrepared || observation.ContainerID == "" { + return out, ErrNotPrepared + } + err = withLock(a.path, func() error { + disk, err := a.loadLocked() + if err != nil { + return err + } + if existing := disk.Instances[instance]; existing != nil { + switch { + case existing.Generation > generation: + return ErrGenerationStale + case existing.Generation == generation && existing.Revoked: + return ErrRevoked + case existing.Generation == generation && (existing.StartIntent || existing.StopIntent) && existing.RequestKey != key: + return ErrActivationUnresolved + } + } + record := &ActivationRecord{Instance: instance, Generation: generation, RequestKey: key, ContainerName: observation.ContainerName, + ContainerID: observation.ContainerID, GrantID: grantID, LeaseExpires: a.now().Add(ttl).Unix()} + if existing := disk.Instances[instance]; existing != nil && existing.Generation == generation { + record.StartIntent, record.Started = existing.StartIntent, existing.Started + } + disk.Instances[instance] = record + out = *record + return a.saveLocked(disk) + }) + return out, err +} + +// Renew extends the lease of the accepted generation that is already running. It never starts, stops or re-grants: +// a revoked, stale, unstarted or unknown generation, or a different request key, is refused. (Grant is for the +// first start; after the start it correctly answers "unresolved".) +func (a *Activator) Renew(instance string, generation uint64, key, grantID string, ttl time.Duration) (ActivationRecord, error) { + var out ActivationRecord + if !valid(instance) || !valid(key) || !valid(grantID) || ttl <= 0 || ttl > maxGrantTTL { + return out, ErrPreparationPolicy + } + err := withLock(a.path, func() error { + if err := a.accepted(instance, generation); err != nil { + return err + } + disk, err := a.loadLocked() + if err != nil { + return err + } + record := disk.Instances[instance] + switch { + case record == nil || record.Generation != generation || record.RequestKey != key: + return ErrNotGranted + case record.Revoked: + return ErrRevoked + case !record.Started || record.StopIntent: + return ErrNotGranted + case record.LeaseExpires == 0 || a.now().Unix() >= record.LeaseExpires: + return ErrLeaseExpired + } + record.LeaseExpires = a.now().Add(ttl).Unix() + out = *record + return a.saveLocked(disk) + }) + return out, err +} + +// Activate starts the prepared container if, and only if, the grant is still valid. +func (a *Activator) Activate(ctx context.Context, instance string, generation uint64, key string) (ActivationRecord, error) { + var out ActivationRecord + if !valid(instance) || !valid(key) { + return out, ErrPreparationPolicy + } + err := withLock(a.path, func() error { + if err := a.accepted(instance, generation); err != nil { + return err + } + disk, err := a.loadLocked() + if err != nil { + return err + } + record := disk.Instances[instance] + switch { + case record == nil || record.Generation != generation || record.RequestKey != key: + return ErrNotGranted + case record.Revoked: + return ErrRevoked + case record.StopIntent: + return ErrActivationUnresolved + case a.now().Unix() >= record.LeaseExpires: + return ErrLeaseExpired + } + if record.Started { + out = *record + return nil + } + if !record.StartIntent { + // The preparation must still be the untouched create-only container. + observation, err := a.preparer.Query(ctx, instance, generation, key) + if err != nil { + return err + } + if observation.State != PreparationPrepared || observation.ContainerID != record.ContainerID { + return ErrNotPrepared + } + } + // Intent is durable before the daemon call: a lost reply is then resolved by + // inspection, never by a blind second start. + record.StartIntent = true + if err := a.saveLocked(disk); err != nil { + return err + } + startErr := a.engine.startContainer(ctx, record.ContainerID) + container, exists, inspectErr := a.engine.inspectContainer(ctx, record.ContainerName) + if inspectErr != nil || !exists || container.ID != record.ContainerID { + return ErrActivationUnresolved + } + if container.State.Running { + record.Started = true + out = *record + return a.saveLocked(disk) + } + if startErr != nil { + return startErr + } + return ErrActivationUnresolved + }) + return out, err +} + +// Revoke permanently ends the generation. The revocation is durable before the +// container is stopped, so a crash between the two can only leave a stopped-late +// container that Sweep (or a repeated Revoke) stops, never a re-activation. +func (a *Activator) Revoke(ctx context.Context, instance string, generation uint64, reason string) (ActivationRecord, error) { + var out ActivationRecord + if !valid(instance) || generation == 0 { + return out, ErrPreparationPolicy + } + err := withLock(a.path, func() error { + disk, err := a.loadLocked() + if err != nil { + return err + } + record := disk.Instances[instance] + if record != nil && record.Generation > generation { + return ErrGenerationStale + } + if record == nil || record.Generation < generation { + record = &ActivationRecord{Instance: instance, Generation: generation} + disk.Instances[instance] = record + } + record.Revoked, record.RevokeReason = true, strings.TrimSpace(reason) + record.StopIntent = record.StartIntent || record.Started + if err := a.saveLocked(disk); err != nil { + return err + } + out = *record + return a.stopLocked(ctx, &disk, record) + }) + if err == nil { + out, _ = a.Status(instance) + } + return out, err +} + +func (a *Activator) stopLocked(ctx context.Context, disk *activationDisk, record *ActivationRecord) error { + if !record.StopIntent || record.ContainerID == "" { + return nil + } + stopErr := a.engine.stopContainer(ctx, record.ContainerID) + container, exists, inspectErr := a.engine.inspectContainer(ctx, record.ContainerName) + if inspectErr != nil { + return ErrActivationUnresolved + } + if exists && container.ID == record.ContainerID && container.State.Running { + if stopErr != nil { + return stopErr + } + return ErrActivationUnresolved + } + record.StopIntent, record.Started = false, false + return a.saveLocked(*disk) +} + +// Sweep stops every container whose lease expired or whose generation is no +// longer the accepted one, and finishes interrupted stops. It is safe to repeat. +func (a *Activator) Sweep(ctx context.Context) ([]string, error) { + var stopped []string + _, generations, _, err := a.store.Snapshot() + if err != nil { + return nil, err + } + err = withLock(a.path, func() error { + disk, err := a.loadLocked() + if err != nil { + return err + } + names := make([]string, 0, len(disk.Instances)) + for name := range disk.Instances { + names = append(names, name) + } + sort.Strings(names) + var firstErr error + for _, name := range names { + record := disk.Instances[name] + expired := record.LeaseExpires != 0 && a.now().Unix() >= record.LeaseExpires + superseded := generations[name] > record.Generation + if !record.Revoked && (expired || superseded) && (record.StartIntent || record.Started) { + record.Revoked = true + if superseded { + record.RevokeReason = "superseded by a newer accepted generation" + } else { + record.RevokeReason = "lease expired" + } + record.StopIntent = true + if err := a.saveLocked(disk); err != nil { + return err + } + } + if record.StopIntent { + if err := a.stopLocked(ctx, &disk, record); err != nil && firstErr == nil { + firstErr = err + } else if err == nil { + stopped = append(stopped, name) + } + } + } + return firstErr + }) + return stopped, err +} + +// Status reports the durable activation receipt for an instance. +func (a *Activator) Status(instance string) (ActivationRecord, error) { + var out ActivationRecord + err := withLock(a.path, func() error { + disk, err := a.loadLocked() + if err != nil { + return err + } + if record := disk.Instances[instance]; record != nil { + out = *record + } + return nil + }) + return out, err +} + +// HasStarted reports whether preparation Query/Prepare must be bypassed for this +// generation: querying a started container through the create-only adapter would +// rewrite its ledger entry as unknown. +func (a *Activator) HasStarted(instance string, generation uint64) bool { + record, err := a.Status(instance) + return err == nil && record.Generation == generation && (record.StartIntent || record.Started) +} + +// Retire is the approved takeover step the preparation ledger waits for: once a +// newer generation is accepted and the older container is provably not running, +// the older container is removed (never forced) and its exclusive runtime +// resource is released, so the newer generation can prepare its own container. +func (a *Activator) Retire(ctx context.Context, instance string, oldGeneration uint64) error { + if !valid(instance) || oldGeneration == 0 { + return ErrPreparationPolicy + } + _, generations, _, err := a.store.Snapshot() + if err != nil { + return err + } + if generations[instance] <= oldGeneration { + return ErrGenerationNotAccepted // only a superseded generation can be retired + } + return withLock(a.path, func() error { + disk, err := a.loadLocked() + if err != nil { + return err + } + record := disk.Instances[instance] + if record != nil && record.Generation == oldGeneration && (record.StopIntent || (record.Started && !record.Revoked)) { + return ErrActivationUnresolved // still running or being stopped: sweep or revoke first + } + var prepared containerPreparation + var key string + err = withLock(a.store.path, func() error { + d, e := load(a.store.path) + if e != nil { + return e + } + for identity, candidate := range d.Preparations { + if candidate.Instance == instance && candidate.Generation == oldGeneration { + key, prepared = identity, candidate + } + } + if key == "" { + return ErrNotPrepared + } + return nil + }) + if err != nil { + return err + } + if prepared.ContainerID != "" { + container, exists, err := a.engine.inspectContainer(ctx, prepared.ContainerName) + if err != nil { + return err + } + if exists { + if container.ID != prepared.ContainerID || container.State.Running || container.State.Restarting { + return ErrActivationUnresolved + } + if err := a.engine.removeContainer(ctx, container.ID); err != nil { + return err + } + } + if _, stillThere, err := a.engine.inspectContainer(ctx, prepared.ContainerName); err != nil || stillThere { + return ErrActivationUnresolved + } + } + return withLock(a.store.path, func() error { + d, e := load(a.store.path) + if e != nil { + return e + } + if d.MaxGeneration[instance] <= oldGeneration { + return ErrGenerationNotAccepted + } + current, found := d.Preparations[key] + if !found || current.ContainerID != prepared.ContainerID { + return ErrInvalidState + } + resource := preparationResource(d.HostID, instance) + held, reserved := d.Resources[resource] + if reserved && (held.Instance != instance || held.Generation != oldGeneration) { + return ErrNotOwner + } + delete(d.Preparations, key) + if reserved { + delete(d.Resources, resource) + delete(d.ReconciliationRequired, resource) + held.State = "released" + d.Requests[key] = held + } + return writeState(a.store.path, d) + }) + }) +} diff --git a/agent/activate_real_test.go b/agent/activate_real_test.go new file mode 100644 index 0000000..fbb8245 --- /dev/null +++ b/agent/activate_real_test.go @@ -0,0 +1,269 @@ +//go:build linux + +package agent + +import ( + "context" + "errors" + "net/http" + "testing" + "time" +) + +// Opt-in like the preparation tests: TP_AGENT_REAL_DOCKER=1 with a reviewed local image ID. +func activationFixture(t *testing.T) (*Activator, *DockerPreparer, *Store, *UnixDockerEngine) { + t.Helper() + store, _, engine, profile := realPreparationFixture(t) + // The reviewed fixture image contains one inert program; the fixed entrypoint is that program. + profile.Entrypoint = "/pluginstub" + profile.Args = []string{} + preparer, err := NewDockerPreparer(store, engine, []PreparationProfile{profile}) + if err != nil { + t.Fatal(err) + } + activator, err := NewActivator(store, preparer, engine) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + // Runs before the preparation fixture's own cleanup: stop and remove what this test started. + disk, err := load(store.path) + if err != nil { + return + } + for _, record := range disk.Preparations { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + container, exists, err := engine.inspectContainer(ctx, record.ContainerName) + if err == nil && exists && container.ID == record.ContainerID { + _ = engine.stopContainer(ctx, container.ID) + engine.call(ctx, http.MethodDelete, "/containers/"+container.ID+"?force=false&v=false", nil, nil) + } + cancel() + } + }) + return activator, preparer, store, engine +} + +func prepareInstance(t *testing.T, preparer *DockerPreparer, profile string, instance string, generation uint64, key string) PreparationObservation { + t.Helper() + observation, err := preparer.Prepare(context.Background(), PrepareContainerRequest{Instance: instance, Generation: generation, RequestKey: key, Profile: profile}) + if err != nil || observation.State != PreparationPrepared { + t.Fatalf("prepare %s gen %d: %v %+v", instance, generation, err, observation) + } + return observation +} + +func containerState(t *testing.T, engine *UnixDockerEngine, observation PreparationObservation) (string, bool) { + t.Helper() + container, exists, err := engine.inspectContainer(context.Background(), observation.ContainerName) + if err != nil || !exists { + t.Fatalf("inspect: exists=%v err=%v", exists, err) + } + return container.State.Status, container.State.Running +} + +func profileName(preparer *DockerPreparer) string { + for name := range preparer.profiles { + return name + } + return "" +} + +func TestActivationWithoutGrantNeverStartsRealDocker(t *testing.T) { + activator, preparer, _, engine := activationFixture(t) + observation := prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k1") + if _, err := activator.Activate(context.Background(), "instance-a", 1, "k1"); !errors.Is(err, ErrNotGranted) { + t.Fatalf("activate without grant must be refused, got %v", err) + } + if status, running := containerState(t, engine, observation); status != "created" || running { + t.Fatalf("an unactivated instance must stay created, got %s running=%v", status, running) + } +} + +func TestActivationGrantStartRevokeIsPermanentRealDocker(t *testing.T) { + activator, preparer, _, engine := activationFixture(t) + ctx := context.Background() + observation := prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k1") + if _, err := activator.Grant(ctx, "instance-a", 1, "k1", "grant-1", time.Minute); err != nil { + t.Fatal(err) + } + if status, running := containerState(t, engine, observation); status != "created" || running { + t.Fatalf("a grant alone must not start anything, got %s running=%v", status, running) + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k1"); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, observation); !running { + t.Fatal("granted instance must be running") + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k1"); err != nil { + t.Fatalf("repeating a granted activation must be idempotent: %v", err) + } + if _, err := activator.Revoke(ctx, "instance-a", 1, "operator revoked"); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, observation); running { + t.Fatal("revoked instance must be stopped") + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k1"); !errors.Is(err, ErrRevoked) { + t.Fatalf("a revoked generation must not start again, got %v", err) + } + if _, err := activator.Grant(ctx, "instance-a", 1, "k1", "grant-2", time.Minute); !errors.Is(err, ErrRevoked) { + t.Fatalf("a revoked generation must not be re-granted, got %v", err) + } + if _, running := containerState(t, engine, observation); running { + t.Fatal("no refused call may restart the container") + } +} + +func TestActivationOldGenerationHasNoEffectRealDocker(t *testing.T) { + activator, preparer, store, engine := activationFixture(t) + ctx := context.Background() + old := prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k-old") + if _, err := activator.Grant(ctx, "instance-a", 1, "k-old", "grant-old", time.Minute); err != nil { + t.Fatal(err) + } + if err := store.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + // A queued task from the old generation arrives late. + if _, err := activator.Activate(ctx, "instance-a", 1, "k-old"); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("old generation activation must be refused as stale, got %v", err) + } + if _, err := activator.Grant(ctx, "instance-a", 1, "k-old", "grant-late", time.Minute); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("old generation grant must be refused as stale, got %v", err) + } + if status, running := containerState(t, engine, old); status != "created" || running { + t.Fatalf("a stale task must not change the container, got %s running=%v", status, running) + } + // Taking over: the superseded container is removed (not forced) and its resource released. + if err := activator.Retire(ctx, "instance-a", 1); err != nil { + t.Fatal(err) + } + if _, exists, err := engine.inspectContainer(ctx, old.ContainerName); err != nil || exists { + t.Fatalf("the retired container must be gone: exists=%v err=%v", exists, err) + } + // The newer generation proceeds independently. + fresh := prepareInstance(t, preparer, profileName(preparer), "instance-a", 2, "k-new") + if _, err := activator.Grant(ctx, "instance-a", 2, "k-new", "grant-new", time.Minute); err != nil { + t.Fatal(err) + } + if _, err := activator.Activate(ctx, "instance-a", 2, "k-new"); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, fresh); !running { + t.Fatal("new generation must run") + } +} + +func TestActivationSupersededRunningInstanceIsStoppedRealDocker(t *testing.T) { + activator, preparer, store, engine := activationFixture(t) + ctx := context.Background() + old := prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k-old") + if _, err := activator.Grant(ctx, "instance-a", 1, "k-old", "grant-old", time.Minute); err != nil { + t.Fatal(err) + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k-old"); err != nil { + t.Fatal(err) + } + if err := store.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, old); !running { + t.Fatal("precondition: old instance runs until swept") + } + if _, err := activator.Sweep(ctx); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, old); running { + t.Fatal("a superseded instance must be stopped by the sweep") + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k-old"); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("superseded generation must stay refused, got %v", err) + } + if err := activator.Retire(ctx, "instance-a", 1); err != nil { + t.Fatal(err) + } + fresh := prepareInstance(t, preparer, profileName(preparer), "instance-a", 2, "k-new") + if _, err := activator.Grant(ctx, "instance-a", 2, "k-new", "grant-new", time.Minute); err != nil { + t.Fatal(err) + } + if _, err := activator.Activate(ctx, "instance-a", 2, "k-new"); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, fresh); !running { + t.Fatal("takeover generation must run") + } +} + +func TestActivationRunningInstanceCannotBeRetiredRealDocker(t *testing.T) { + activator, preparer, store, engine := activationFixture(t) + ctx := context.Background() + old := prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k-old") + if _, err := activator.Grant(ctx, "instance-a", 1, "k-old", "g", time.Minute); err != nil { + t.Fatal(err) + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k-old"); err != nil { + t.Fatal(err) + } + if err := activator.Retire(ctx, "instance-a", 1); !errors.Is(err, ErrGenerationNotAccepted) { + t.Fatalf("the current generation cannot be retired, got %v", err) + } + if err := store.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + if err := activator.Retire(ctx, "instance-a", 1); err == nil { + t.Fatal("a still-running superseded instance must not be removed before it is stopped") + } + if _, running := containerState(t, engine, old); !running { + t.Fatal("a refused retire must not touch the container") + } +} + +func TestActivationLostControlPlaneLeaseStopsInstanceRealDocker(t *testing.T) { + activator, preparer, _, engine := activationFixture(t) + ctx := context.Background() + observation := prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k1") + if _, err := activator.Grant(ctx, "instance-a", 1, "k1", "grant-1", time.Minute); err != nil { + t.Fatal(err) + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k1"); err != nil { + t.Fatal(err) + } + // The control plane goes silent: no renewal arrives before the lease ends. + base := time.Now() + activator.now = func() time.Time { return base.Add(2 * time.Minute) } + if _, err := activator.Sweep(ctx); err != nil { + t.Fatal(err) + } + if _, running := containerState(t, engine, observation); running { + t.Fatal("an instance whose lease expired must be stopped") + } + if _, err := activator.Activate(ctx, "instance-a", 1, "k1"); !errors.Is(err, ErrRevoked) { + t.Fatalf("an expired instance must need a newer generation, got %v", err) + } +} + +func TestActivationStatusSurvivesRestartRealDocker(t *testing.T) { + activator, preparer, store, _ := activationFixture(t) + ctx := context.Background() + prepareInstance(t, preparer, profileName(preparer), "instance-a", 1, "k1") + if _, err := activator.Grant(ctx, "instance-a", 1, "k1", "grant-1", time.Minute); err != nil { + t.Fatal(err) + } + if _, err := activator.Revoke(ctx, "instance-a", 1, "before restart"); err != nil { + t.Fatal(err) + } + reopened, err := newActivatorFor(store, preparer) + if err != nil { + t.Fatal(err) + } + record, err := reopened.Status("instance-a") + if err != nil || !record.Revoked || record.Generation != 1 { + t.Fatalf("revocation must survive a restart: %+v %v", record, err) + } +} + +func newActivatorFor(store *Store, preparer *DockerPreparer) (*Activator, error) { + return &Activator{store: store, preparer: preparer, engine: preparer.engine.(activationEngine), path: store.path + ".activation", now: time.Now}, nil +} diff --git a/agent/catalog.go b/agent/catalog.go new file mode 100644 index 0000000..bf18ac5 --- /dev/null +++ b/agent/catalog.go @@ -0,0 +1,329 @@ +//go:build linux + +package agent + +import ( + "crypto/ecdsa" + "crypto/sha256" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "net/url" + "os" + "regexp" + "sort" + "strings" + "time" +) + +const catalogSchema = "thingspanel.plugin-catalog.v1" + +var ErrCatalog = errors.New("plugin catalog is not trusted") + +type CatalogUserField struct { + Required bool `json:"required"` + Secret bool `json:"secret"` + Description string `json:"description"` + Validate string `json:"validate,omitempty"` + Pattern string `json:"pattern,omitempty"` + Default string `json:"default,omitempty"` +} + +type CatalogServicePlugin struct { + Name string `json:"name"` + ServiceType int32 `json:"service_type"` + Description string `json:"description"` + Config map[string]string `json:"config"` +} + +// CatalogEntry is the signed catalog entry (same file the Python publisher writes). Only the fields the Agent acts +// on are read; the public projection is what the control plane sees. +type CatalogEntry struct { + ID string `json:"id"` + Version string `json:"version"` + Description string `json:"description"` + ImageID string `json:"image_id"` + Entrypoint string `json:"entrypoint"` + Args []string `json:"args"` + Env []string `json:"env"` + EnvFromStack map[string]string `json:"env_from_stack"` + EnvGenerated map[string]int `json:"env_generated"` + EnvUser map[string]CatalogUserField `json:"env_user"` + Health *struct { + Port int `json:"port"` + Path string `json:"path"` + } `json:"health"` + Identity struct { + TokenEnv string `json:"token_env"` + } `json:"identity"` + Platform struct { + Binding string `json:"binding"` + ServiceIdentifier string `json:"service_identifier"` + ProtocolType string `json:"protocol_type"` + NetworkAlias string `json:"network_alias"` + HTTPPort int `json:"http_port"` + ServicePlugin *CatalogServicePlugin `json:"service_plugin"` + } `json:"platform"` +} + +type PublicEntry struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Version string `json:"version"` + Description string `json:"description"` + ServiceIdentifier string `json:"service_identifier"` + NetworkAlias string `json:"network_alias"` + HTTPPort int `json:"http_port"` + Health map[string]any `json:"health,omitempty"` + ServicePlugin *CatalogServicePlugin `json:"service_plugin,omitempty"` + EnvUser map[string]CatalogUserField `json:"env_user"` +} + +var aliasPattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`) + +func (e CatalogEntry) ServiceIdentifier() string { + if e.Platform.ServiceIdentifier != "" { + return e.Platform.ServiceIdentifier + } + return e.Platform.ProtocolType +} + +func (e CatalogEntry) NetworkAlias() string { + if e.Platform.NetworkAlias != "" { + return e.Platform.NetworkAlias + } + return "tp-plugin-" + e.ID +} + +func (e CatalogEntry) tokenEnv() string { + if e.Identity.TokenEnv != "" { + return e.Identity.TokenEnv + } + return "TP_PLUGIN_RUNTIME_TOKEN" +} + +func (e CatalogEntry) Public() PublicEntry { + out := PublicEntry{ID: e.ID, DisplayName: e.ID, Version: e.Version, Description: e.Description, ServiceIdentifier: e.ServiceIdentifier(), + NetworkAlias: e.NetworkAlias(), HTTPPort: e.Platform.HTTPPort, EnvUser: e.EnvUser} + if out.EnvUser == nil { + out.EnvUser = map[string]CatalogUserField{} + } + if sp := e.Platform.ServicePlugin; sp != nil { + c := *sp + if c.ServiceType == 0 { + c.ServiceType = 2 + } + out.ServicePlugin, out.DisplayName = &c, c.Name + } + if e.Health != nil { + out.Health = map[string]any{"port": e.Health.Port, "path": e.Health.Path} + } + return out +} + +// valid is the Agent's own re-check of a verified entry (defence in depth, design 11.3): only what it needs to build +// a safe profile, not the publisher's full schema. +func (e CatalogEntry) validate() error { + if !valid(e.ID) || len(e.ID) > 64 || !aliasPattern.MatchString(e.ID) || e.Version == "" || !validImageID(e.ImageID) || + !strings.HasPrefix(e.Entrypoint, "/") || e.Platform.Binding != "none" || e.ServiceIdentifier() == "" || !aliasPattern.MatchString(e.NetworkAlias()) { + return ErrCatalog + } + for key := range e.EnvUser { + if !validEnvKey(key) { + return ErrCatalog + } + } + return nil +} + +// CatalogSource re-verifies the signed catalog file on every use, so a republished catalog takes effect without a +// restart and a tampered or expired file is refused immediately. +type CatalogSource struct { + path string + trust *ecdsa.PublicKey + now func() time.Time +} + +func NewCatalogSource(catalogPath, trustRootPath string) (*CatalogSource, error) { + raw, err := os.ReadFile(trustRootPath) + if err != nil { + return nil, err + } + block, _ := pem.Decode(raw) + if block == nil || block.Type != "PUBLIC KEY" { + return nil, ErrCatalog + } + key, err := x509.ParsePKIXPublicKey(block.Bytes) + pub, ok := key.(*ecdsa.PublicKey) + if err != nil || !ok || pub.Curve.Params().Name != "P-256" { + return nil, ErrCatalog + } + return &CatalogSource{path: catalogPath, trust: pub, now: time.Now}, nil +} + +func (c *CatalogSource) Entries() ([]CatalogEntry, error) { + raw, err := os.ReadFile(c.path) + if err != nil { + return nil, ErrCatalog + } + sig, err := os.ReadFile(c.path + ".sig") + if err != nil { + return nil, ErrCatalog + } + digest := sha256.Sum256(raw) + if !ecdsa.VerifyASN1(c.trust, digest[:], sig) { + return nil, ErrCatalog + } + var doc struct { + Schema string `json:"schema"` + ExpiresAt int64 `json:"expires_at"` + Plugins []CatalogEntry `json:"plugins"` + } + if json.Unmarshal(raw, &doc) != nil || doc.Schema != catalogSchema || c.now().Unix() >= doc.ExpiresAt { + return nil, ErrCatalog + } + out := doc.Plugins[:0] + seen := map[string]bool{} + for _, e := range doc.Plugins { + if e.validate() != nil || seen[e.ID] { + continue // an entry the Agent will not run is simply not offered + } + seen[e.ID] = true + out = append(out, e) + } + return out, nil +} + +func (c *CatalogSource) Entry(id string) (CatalogEntry, error) { + entries, err := c.Entries() + if err != nil { + return CatalogEntry{}, err + } + for _, e := range entries { + if e.ID == id { + return e, nil + } + } + return CatalogEntry{}, ErrPreparationPolicy +} + +// ProfileBuilder turns a verified entry plus the control plane's request into a preparation profile. Everything +// secret becomes an "@secret:" placeholder resolved only when the container is created or verified. +type ProfileBuilder struct { + Secrets *SecretStore + Network string + StackEnv func() (map[string]string, error) +} + +func (b ProfileBuilder) Build(e CatalogEntry, instance string, generation uint64, values map[string]string, token string) (PreparationProfile, error) { + if instance != e.ID || generation == 0 || token == "" || b.Secrets == nil { + return PreparationProfile{}, ErrPreparationPolicy + } + env := append([]string{}, e.Env...) + targets := make([]string, 0, len(e.EnvFromStack)) + for t := range e.EnvFromStack { + targets = append(targets, t) + } + sort.Strings(targets) + if len(targets) > 0 { + stack, err := b.StackEnv() + if err != nil { + return PreparationProfile{}, ErrPreparationPolicy + } + for _, t := range targets { + v, ok := stack[e.EnvFromStack[t]] + if !ok || b.Secrets.Put(instance, "stack/"+t, v) != nil { + return PreparationProfile{}, ErrPreparationPolicy + } + env = append(env, t+"="+secretPrefix+"stack/"+t) + } + } + generated := make([]string, 0, len(e.EnvGenerated)) + for k := range e.EnvGenerated { + generated = append(generated, k) + } + sort.Strings(generated) + for _, k := range generated { + if _, err := b.Secrets.GetOrCreateHex(instance, "generated/"+k, max(e.EnvGenerated[k]/2, 8)); err != nil { + return PreparationProfile{}, err + } + env = append(env, k+"="+secretPrefix+"generated/"+k) + } + user := make([]string, 0, len(e.EnvUser)) + for k := range e.EnvUser { + user = append(user, k) + } + sort.Strings(user) + for _, k := range user { + spec := e.EnvUser[k] + if spec.Secret { + if _, ok := b.Secrets.Get(instance, "config/"+k); !ok { + if spec.Required { + return PreparationProfile{}, fmt.Errorf("%w: missing %s", ErrPreparationPolicy, k) + } + continue + } + env = append(env, k+"="+secretPrefix+"config/"+k) + continue + } + v := values[k] + if v == "" { + v = spec.Default + } + if v == "" { + if spec.Required { + return PreparationProfile{}, fmt.Errorf("%w: missing %s", ErrPreparationPolicy, k) + } + continue + } + if err := checkUserValue(spec, v); err != nil { + return PreparationProfile{}, err + } + env = append(env, k+"="+v) + } + if err := b.Secrets.Put(instance, fmt.Sprintf("identity/%d", generation), token); err != nil { + return PreparationProfile{}, err + } + env = append(env, e.tokenEnv()+"="+secretPrefix+fmt.Sprintf("identity/%d", generation), "TP_PLUGIN_SERVICE_IDENTIFIER="+e.ServiceIdentifier()) + profile := PreparationProfile{Name: fmt.Sprintf("%s.g%d", e.ID, generation), ImageID: e.ImageID, Entrypoint: e.Entrypoint, + Args: append([]string{}, e.Args...), Network: b.Network, NetworkAlias: e.NetworkAlias(), Env: env, ReviewedImageMetadata: true} + if !validPreparationProfile(profile) { + return PreparationProfile{}, ErrPreparationPolicy + } + return profile, nil +} + +func checkUserValue(spec CatalogUserField, v string) error { + if strings.ContainsAny(v, "\r\n\x00") { + return ErrPreparationPolicy + } + if spec.Validate == "url" { + u, err := url.Parse(v) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return ErrPreparationPolicy + } + } + if spec.Pattern != "" { + if ok, _ := regexp.MatchString("^(?:"+spec.Pattern+")$", v); !ok { + return ErrPreparationPolicy + } + } + return nil +} + +// ReadEnvFile parses KEY=VALUE lines (the stack's .env). +func ReadEnvFile(path string) (map[string]string, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + out := map[string]string{} + for _, line := range strings.Split(string(raw), "\n") { + if k, v, ok := strings.Cut(line, "="); ok && !strings.HasPrefix(line, "#") { + out[k] = strings.TrimRight(v, "\r") + } + } + return out, nil +} diff --git a/agent/catalog_test.go b/agent/catalog_test.go new file mode 100644 index 0000000..ddf6c71 --- /dev/null +++ b/agent/catalog_test.go @@ -0,0 +1,226 @@ +//go:build linux + +package agent + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/json" + "encoding/pem" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +const ( + testSecret = "fixture-secret-value" + identityToken = "pri_0123456789abcdef.0123456789abcdef0123456789abcdef0123456789abcdef" + mqttPass = "mqtt-pass-123" +) + +func catalogJSON(expires int64) []byte { + doc := map[string]any{"schema": catalogSchema, "version": 1, "expires_at": expires, "plugins": []any{map[string]any{ + "id": "homeassistant", "version": "1.0.0", "kind": "service", "image_id": "sha256:" + strings.Repeat("a", 64), + "entrypoint": "/usr/local/bin/homeassistant-service", "env": []string{"LOG_LEVEL=info"}, + "env_from_stack": map[string]string{"TP_MQTT_PASS": "TP_PROTOCOL_MQTT_PASSWORD"}, + "env_user": map[string]any{ + "SITE_BASE_URL": map[string]any{"required": true, "secret": false, "validate": "url"}, + "SITE_ACCESS_SECRET": map[string]any{"required": true, "secret": true}, + }, + "health": map[string]any{"port": 9001, "path": "/health"}, + "identity": map[string]any{"token_env": "TP_PLUGIN_RUNTIME_TOKEN"}, + "platform": map[string]any{"binding": "none", "service_identifier": "homeassistant", "http_port": 9001, + "service_plugin": map[string]any{"name": "Home Assistant", "service_type": 2, "config": map[string]any{"http_address": "{alias}:{http_port}"}}}, + }}} + raw, _ := json.Marshal(doc) + return raw +} + +func signedCatalog(t *testing.T, expires int64) (catalog, root string, key *ecdsa.PrivateKey) { + t.Helper() + dir := t.TempDir() + key, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) + root = filepath.Join(dir, "root.pem") + os.WriteFile(root, pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}), 0600) + catalog = filepath.Join(dir, "plugin-catalog.json") + raw := catalogJSON(expires) + digest := sha256.Sum256(raw) + sig, _ := ecdsa.SignASN1(rand.Reader, key, digest[:]) + os.WriteFile(catalog, raw, 0600) + os.WriteFile(catalog+".sig", sig, 0600) + return +} + +func TestCatalogVerifiesSignatureExpiryAndTampering(t *testing.T) { + catalog, root, _ := signedCatalog(t, time.Now().Add(time.Hour).Unix()) + source, err := NewCatalogSource(catalog, root) + if err != nil { + t.Fatal(err) + } + entries, err := source.Entries() + if err != nil || len(entries) != 1 || entries[0].Public().DisplayName != "Home Assistant" || entries[0].Public().NetworkAlias != "tp-plugin-homeassistant" { + t.Fatalf("%v %+v", err, entries) + } + raw, _ := os.ReadFile(catalog) + os.WriteFile(catalog, []byte(strings.Replace(string(raw), "1.0.0", "9.9.9", 1)), 0600) + if _, err := source.Entries(); err != ErrCatalog { + t.Fatalf("tampered catalog accepted: %v", err) + } + expired, root2, _ := signedCatalog(t, time.Now().Add(-time.Hour).Unix()) + s2, _ := NewCatalogSource(expired, root2) + if _, err := s2.Entries(); err != ErrCatalog { + t.Fatalf("expired catalog accepted: %v", err) + } + other, _, _ := signedCatalog(t, time.Now().Add(time.Hour).Unix()) + s3, _ := NewCatalogSource(other, root) // signed by a different key than the pinned root + if _, err := s3.Entries(); err != ErrCatalog { + t.Fatalf("catalog signed by another key accepted: %v", err) + } +} + +func catalogFixture(t *testing.T) (*CatalogSource, *SecretStore, ProfileBuilder) { + catalog, root, _ := signedCatalog(t, time.Now().Add(time.Hour).Unix()) + source, err := NewCatalogSource(catalog, root) + if err != nil { + t.Fatal(err) + } + secrets, err := OpenSecretStore(filepath.Join(t.TempDir(), "secrets.json")) + if err != nil { + t.Fatal(err) + } + return source, secrets, ProfileBuilder{Secrets: secrets, Network: "tp_net", StackEnv: func() (map[string]string, error) { + return map[string]string{"TP_PROTOCOL_MQTT_PASSWORD": mqttPass}, nil + }} +} + +func TestCatalogInstallKeepsSecretsOutOfStateAndInjectsThemIntoTheContainer(t *testing.T) { + source, secrets, builder := catalogFixture(t) + entry, err := source.Entry("homeassistant") + if err != nil { + t.Fatal(err) + } + if _, err := builder.Build(entry, "homeassistant", 1, map[string]string{"SITE_BASE_URL": "http://site:8123"}, identityToken); err == nil { + t.Fatal("a required secret that was never stored must fail the build") + } + if err := secrets.Put("homeassistant", "config/SITE_ACCESS_SECRET", testSecret); err != nil { + t.Fatal(err) + } + if _, err := builder.Build(entry, "homeassistant", 1, map[string]string{"SITE_BASE_URL": "ftp://x"}, identityToken); err == nil { + t.Fatal("a bad URL must be refused") + } + profile, err := builder.Build(entry, "homeassistant", 1, map[string]string{"SITE_BASE_URL": "http://site:8123"}, identityToken) + if err != nil { + t.Fatal(err) + } + for _, e := range profile.Env { + if strings.Contains(e, testSecret) || strings.Contains(e, identityToken) || strings.Contains(e, mqttPass) { + t.Fatalf("profile carries a secret: %s", e) + } + } + + store, statePath := initialized(t) + if err := store.AcceptGeneration("homeassistant", 1); err != nil { + t.Fatal(err) + } + engine := newPreparationFixtureEngine() + preparer, err := newDockerPreparer(store, engine, nil) + if err != nil { + t.Fatal(err) + } + preparer.SetSecrets(secrets) + if err := preparer.SetProfile(profile); err != nil { + t.Fatal(err) + } + obs, err := preparer.Prepare(context.Background(), PrepareContainerRequest{Instance: "homeassistant", Generation: 1, RequestKey: "install-1", Profile: profile.Name}) + if err != nil || obs.State != PreparationPrepared { + t.Fatalf("%v %+v", err, obs) + } + var env []string + for _, c := range engine.containers { + env = c.Config.Env + } + joined := strings.Join(env, "\n") + for _, want := range []string{"SITE_ACCESS_SECRET=" + testSecret, "TP_PLUGIN_RUNTIME_TOKEN=" + identityToken, "TP_MQTT_PASS=" + mqttPass, "SITE_BASE_URL=http://site:8123", "TP_PLUGIN_SERVICE_IDENTIFIER=homeassistant"} { + if !strings.Contains(joined, want) { + t.Fatalf("container env lacks %s", strings.SplitN(want, "=", 2)[0]) + } + } + // nothing secret in the Agent's journal or its receipts + files, _ := filepath.Glob(statePath + "*") + for _, f := range files { + raw, _ := os.ReadFile(f) + for _, s := range []string{testSecret, identityToken, mqttPass} { + if strings.Contains(string(raw), s) { + t.Fatalf("%s contains a secret", filepath.Base(f)) + } + } + } + mode, _ := os.Stat(secrets.path) + if mode.Mode().Perm() != 0600 { + t.Fatalf("secret store mode %v", mode.Mode().Perm()) + } + // repeating the prepare is the same operation, not a second container + if _, err := preparer.Prepare(context.Background(), PrepareContainerRequest{Instance: "homeassistant", Generation: 1, RequestKey: "install-1", Profile: profile.Name}); err != nil || engine.createCount() != 1 { + t.Fatalf("%v creates=%d", err, engine.createCount()) + } + // after an Agent restart the recorded profile is adopted only because the signed catalog vouches for it + again, err := newDockerPreparer(store, engine, nil) + if err != nil { + t.Fatal(err) + } + again.SetSecrets(secrets) + if _, err := again.Query(context.Background(), "homeassistant", 1, "install-1"); err == nil { + t.Fatal("an unknown profile must not be trusted before adoption") + } + if err := again.AdoptRecorded(func(p PreparationProfile) bool { return false }); err != nil { + t.Fatal(err) + } + if _, err := again.Query(context.Background(), "homeassistant", 1, "install-1"); err == nil { + t.Fatal("a profile the catalog does not vouch for must stay untrusted") + } + if err := again.AdoptRecorded(func(p PreparationProfile) bool { return p.ImageID == entry.ImageID && p.Entrypoint == entry.Entrypoint }); err != nil { + t.Fatal(err) + } + if obs, err := again.Query(context.Background(), "homeassistant", 1, "install-1"); err != nil || obs.State != PreparationPrepared { + t.Fatalf("%v %+v", err, obs) + } +} + +func TestConfigEndpointsOnlyAcceptDeclaredSecrets(t *testing.T) { + source, secrets, builder := catalogFixture(t) + s := &Service{catalog: source, builder: builder} + ctx := context.Background() + for _, bad := range []apiRequest{ + {Instance: "homeassistant", Key: "SITE_BASE_URL", Value: "x"}, // declared but not secret + {Instance: "homeassistant", Key: "PATH", Value: "x"}, // undeclared + {Instance: "unknown-plugin", Key: "SITE_ACCESS_SECRET", Value: "x"}, // not in the catalog + {Instance: "homeassistant", Key: "SITE_ACCESS_SECRET", Value: "a\nb"}, + {Instance: "homeassistant", Key: "SITE_ACCESS_SECRET", Value: ""}, + } { + if _, err := s.configPut(ctx, bad); err == nil { + t.Fatalf("accepted %+v", bad) + } + } + if _, err := s.configPut(ctx, apiRequest{Instance: "homeassistant", Key: "SITE_ACCESS_SECRET", Value: testSecret}); err != nil { + t.Fatal(err) + } + keys, _ := s.configKeys(ctx, apiRequest{Instance: "homeassistant"}) + raw, _ := json.Marshal(keys) + if string(raw) != `{"ok":false,"keys":["SITE_ACCESS_SECRET"]}` || strings.Contains(string(raw), testSecret) { + t.Fatalf("%s", raw) + } + secrets.Put("homeassistant", "identity/3", identityToken) + if _, err := s.configClear(ctx, apiRequest{Instance: "homeassistant"}); err != nil { + t.Fatal(err) + } + if k := secrets.Keys("homeassistant", ""); len(k) != 0 { + t.Fatalf("left behind: %v", k) + } +} diff --git a/agent/cmd/tp-agent/e2e_real_test.go b/agent/cmd/tp-agent/e2e_real_test.go new file mode 100644 index 0000000..bccc5ef --- /dev/null +++ b/agent/cmd/tp-agent/e2e_real_test.go @@ -0,0 +1,133 @@ +//go:build linux + +package main + +import ( + "bytes" + "context" + "encoding/json" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// Opt-in end to end: the real tp-agent binary, a real Unix socket and the real Docker Engine. +// TP_AGENT_E2E_BIN is the built tp-agent; TP_AGENT_DOCKER_IMAGE_ID a reviewed local image whose only +// program is /pluginstub; TP_AGENT_DOCKER_SOCKET the engine socket. +func TestServiceEndToEndRealDocker(t *testing.T) { + bin, image, dockerSocket := os.Getenv("TP_AGENT_E2E_BIN"), os.Getenv("TP_AGENT_DOCKER_IMAGE_ID"), os.Getenv("TP_AGENT_DOCKER_SOCKET") + if bin == "" || image == "" || dockerSocket == "" { + t.Skip("TP_AGENT_E2E_BIN, TP_AGENT_DOCKER_IMAGE_ID and TP_AGENT_DOCKER_SOCKET are required") + } + dir := t.TempDir() + if err := os.Chmod(dir, 0700); err != nil { + t.Fatal(err) + } + state, socket, tokenFile, profilesFile := filepath.Join(dir, "state.json"), filepath.Join(dir, "agent.sock"), filepath.Join(dir, "token"), filepath.Join(dir, "profiles.json") + token := "0123456789abcdef0123456789abcdef-e2e" + os.WriteFile(tokenFile, []byte(token), 0600) + profile := []map[string]any{{"name": "stub", "image_id": image, "entrypoint": "/pluginstub", "args": []string{}}} + raw, _ := json.Marshal(profile) + os.WriteFile(profilesFile, raw, 0600) + if out, err := exec.Command(bin, "-state", state, "-init", "e2e-host-"+time.Now().Format("150405")).CombinedOutput(); err != nil { + t.Fatalf("init: %v %s", err, out) + } + cmd := exec.Command(bin, "-state", state, "-socket", socket, "-token-file", tokenFile, "-profiles", profilesFile, "-docker-socket", dockerSocket, "-sweep-interval", "1s") + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) + client := &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, "unix", socket) + }}, Timeout: 90 * time.Second} + deadline := time.Now().Add(10 * time.Second) + for { + if conn, err := net.Dial("unix", socket); err == nil { + conn.Close() + break + } + if time.Now().After(deadline) { + t.Fatal("agent did not start listening") + } + time.Sleep(100 * time.Millisecond) + } + call := func(path, bearer string, body map[string]any) (int, map[string]any) { + payload, _ := json.Marshal(body) + request, _ := http.NewRequest(http.MethodPost, "http://agent"+path, bytes.NewReader(payload)) + if bearer != "" { + request.Header.Set("Authorization", "Bearer "+bearer) + } + response, err := client.Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var out map[string]any + json.NewDecoder(response.Body).Decode(&out) + return response.StatusCode, out + } + req := func(gen int, key string) map[string]any { + return map[string]any{"instance": "plugin-1", "generation": gen, "request_key": key, "profile": "stub", "grant_id": "g-" + key, "ttl_seconds": 120} + } + if code, _ := call("/v1/status", "", req(1, "k1")); code != http.StatusUnauthorized { + t.Fatalf("a request without the token must be unauthorized, got %d", code) + } + if code, _ := call("/v1/status", "wrong-token-wrong-token-wrong-token-xx", req(1, "k1")); code != http.StatusUnauthorized { + t.Fatalf("a wrong token must be unauthorized, got %d", code) + } + steps := []struct { + path string + gen int + key string + want int + }{ + {"/v1/accept-generation", 1, "k1", 200}, + {"/v1/prepare", 1, "k1", 200}, + {"/v1/activate", 1, "k1", 409}, // not granted yet: nothing may start + {"/v1/grant", 1, "k1", 200}, + {"/v1/activate", 1, "k1", 200}, + {"/v1/accept-generation", 2, "k2", 200}, + {"/v1/activate", 1, "k1", 409}, // old generation task arrives late + {"/v1/grant", 1, "k1", 409}, + } + for i, step := range steps { + code, body := call(step.path, token, req(step.gen, step.key)) + if code != step.want { + t.Fatalf("step %d %s gen %d: want %d got %d %v", i, step.path, step.gen, step.want, code, body) + } + } + // The sweeper stops the superseded, still-running generation 1 without any call. + stopped := false + for i := 0; i < 20 && !stopped; i++ { + time.Sleep(500 * time.Millisecond) + _, body := call("/v1/status", token, req(1, "k1")) + if activation, ok := body["activation"].(map[string]any); ok && activation["revoked"] == true && activation["started"] == false { + stopped = true + } + } + if !stopped { + t.Fatal("the sweeper must stop and revoke the superseded instance") + } + if code, body := call("/v1/retire", token, req(1, "k1")); code != 200 { + t.Fatalf("retire: %d %v", code, body) + } + for _, step := range []struct { + path string + want int + }{{"/v1/prepare", 200}, {"/v1/grant", 200}, {"/v1/activate", 200}} { + if code, body := call(step.path, token, req(2, "k2")); code != step.want { + t.Fatalf("generation 2 %s: want %d got %d %v", step.path, step.want, code, body) + } + } + if code, body := call("/v1/revoke", token, req(2, "k2")); code != 200 { + t.Fatalf("revoke: %d %v", code, body) + } + if code, _ := call("/v1/activate", token, req(2, "k2")); code != 409 { + t.Fatalf("a revoked generation must not start again, got %d", code) + } +} diff --git a/agent/cmd/tp-agent/main.go b/agent/cmd/tp-agent/main.go new file mode 100644 index 0000000..4dac284 --- /dev/null +++ b/agent/cmd/tp-agent/main.go @@ -0,0 +1,158 @@ +//go:build linux + +// tp-agent is the host Agent service: prepare, grant, activate, revoke and retire plugin containers +// for instances whose generation the control plane has accepted. It listens on a private Unix socket only. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "strings" + "syscall" + "time" + + agent "thingspanel-installer-agent-state" +) + +func main() { + statePath := flag.String("state", "", "private state file (created with -init)") + initState := flag.String("init", "", "initialize the state file with this host id and exit") + socket := flag.String("socket", "", "Unix socket to serve the control API on") + tokenFile := flag.String("token-file", "", "file holding the control-plane bearer token (mode 0600, >= 32 bytes)") + dockerSocket := flag.String("docker-socket", "/var/run/docker.sock", "local Docker Engine socket") + profilesFile := flag.String("profiles", "", "JSON array of reviewed preparation profiles") + catalogFile := flag.String("catalog", "", "signed plugin catalog (plugin-catalog.json, with .sig beside it): enables the catalog install API") + trustRoot := flag.String("trust-root", "", "ECDSA P-256 public key (PEM) that must have signed the catalog") + secretsFile := flag.String("secrets", "", "secret store file (mode 0600); default: secrets.json next to the state file") + stackEnv := flag.String("stack-env", "", "the stack's .env file; catalog env_from_stack values are read from it") + network := flag.String("network", "", "existing user-defined Docker network the catalog plugins join") + sweep := flag.Duration("sweep-interval", 5*time.Second, "lease/generation sweep cadence") + flag.Parse() + if *initState != "" { + if *statePath == "" { + log.Fatal("-state is required with -init") + } + if err := agent.Initialize(*statePath, *initState); err != nil { + log.Fatal(err) + } + return + } + if *statePath == "" || *socket == "" || *tokenFile == "" || (*profilesFile == "" && *catalogFile == "") { + log.Fatal("-state, -socket, -token-file and one of -profiles or -catalog are required") + } + token, err := readToken(*tokenFile) + if err != nil { + log.Fatal(err) + } + var profiles []agent.PreparationProfile + if *profilesFile != "" { + raw, err := os.ReadFile(*profilesFile) + if err != nil || json.Unmarshal(raw, &profiles) != nil { + log.Fatal("profiles file is missing or invalid") + } + } + store, err := agent.Open(*statePath) + if err != nil { + log.Fatal(err) + } + engine, err := agent.NewUnixDockerEngine(*dockerSocket) + if err != nil { + log.Fatal(err) + } + preparer, err := agent.NewDockerPreparer(store, engine, profiles) + if err != nil { + log.Fatal(err) + } + activator, err := agent.NewActivator(store, preparer, engine) + if err != nil { + log.Fatal(err) + } + service, err := agent.NewService(store, preparer, activator, token) + if err != nil { + log.Fatal(err) + } + if *catalogFile != "" { + if *trustRoot == "" || *network == "" { + log.Fatal("-catalog needs -trust-root and -network") + } + source, err := agent.NewCatalogSource(*catalogFile, *trustRoot) + if err != nil { + log.Fatalf("catalog trust root: %v", err) + } + secretsPath := *secretsFile + if secretsPath == "" { + secretsPath = filepath.Join(filepath.Dir(*statePath), "secrets.json") + } + secrets, err := agent.OpenSecretStore(secretsPath) + if err != nil { + log.Fatalf("secret store: %v", err) + } + builder := agent.ProfileBuilder{Secrets: secrets, Network: *network, StackEnv: func() (map[string]string, error) { + if *stackEnv == "" { + return nil, fmt.Errorf("-stack-env is not configured") + } + return agent.ReadEnvFile(*stackEnv) + }} + service.EnableCatalog(source, builder) + if entries, err := source.Entries(); err == nil { + vouched := map[string]agent.CatalogEntry{} + for _, e := range entries { + vouched[e.ID] = e + } + _ = preparer.AdoptRecorded(func(p agent.PreparationProfile) bool { + id, _, _ := strings.Cut(p.Name, ".g") + e, ok := vouched[id] + return ok && e.ImageID == p.ImageID && e.Entrypoint == p.Entrypoint + }) + } else { + log.Printf("catalog is not usable yet: %v", err) + } + } + if info, err := os.Lstat(*socket); err == nil && info.Mode()&os.ModeSocket != 0 { + _ = os.Remove(*socket) // stale socket of a previous run of this Agent + } + oldMask := syscall.Umask(0177) + listener, err := net.Listen("unix", *socket) + syscall.Umask(oldMask) + if err != nil { + log.Fatal(err) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + go service.RunSweeper(ctx, *sweep, func(err error) { log.Printf("sweep: %v", err) }) + server := &http.Server{Handler: service.Handler(), ReadHeaderTimeout: 10 * time.Second} + go func() { + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) + }() + log.Printf("tp-agent listening on %s", *socket) + if err := server.Serve(listener); err != nil && err != http.ErrServerClosed { + log.Fatal(err) + } +} + +func readToken(path string) (string, error) { + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { + return "", fmt.Errorf("token file must be a regular file with mode 0600") + } + raw, err := os.ReadFile(path) + if err != nil { + return "", err + } + token := strings.TrimSpace(string(raw)) + if len(token) < 32 { + return "", fmt.Errorf("token must be at least 32 characters") + } + return token, nil +} diff --git a/agent/cmd/tp-agentctl/main.go b/agent/cmd/tp-agentctl/main.go new file mode 100644 index 0000000..a2edc67 --- /dev/null +++ b/agent/cmd/tp-agentctl/main.go @@ -0,0 +1,64 @@ +//go:build linux + +// tp-agentctl posts one request to the local tp-agent socket: tp-agentctl -socket S -token-file F /v1/status instance=x generation=1 +package main + +import ( + "bytes" + "context" + "encoding/json" + "flag" + "fmt" + "io" + "net" + "net/http" + "os" + "strconv" + "strings" + "time" +) + +func main() { + socket := flag.String("socket", "", "tp-agent Unix socket") + tokenFile := flag.String("token-file", "", "bearer token file") + flag.Parse() + if flag.NArg() < 1 || *socket == "" || *tokenFile == "" { + fmt.Fprintln(os.Stderr, "usage: tp-agentctl -socket S -token-file F /v1/ [key=value ...]") + os.Exit(2) + } + raw, err := os.ReadFile(*tokenFile) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + body := map[string]any{} + for _, pair := range flag.Args()[1:] { + key, value, ok := strings.Cut(pair, "=") + if !ok { + fmt.Fprintln(os.Stderr, "arguments must be key=value") + os.Exit(2) + } + if number, err := strconv.ParseUint(value, 10, 64); err == nil && (key == "generation" || key == "ttl_seconds") { + body[key] = number + } else { + body[key] = value + } + } + payload, _ := json.Marshal(body) + client := &http.Client{Timeout: 90 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, "unix", *socket) + }}} + request, _ := http.NewRequest(http.MethodPost, "http://agent"+flag.Arg(0), bytes.NewReader(payload)) + request.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(raw))) + response, err := client.Do(request) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + defer response.Body.Close() + out, _ := io.ReadAll(response.Body) + fmt.Printf("%d %s", response.StatusCode, out) + if response.StatusCode != http.StatusOK { + os.Exit(1) + } +} diff --git a/agent/docker_prepare.go b/agent/docker_prepare.go new file mode 100644 index 0000000..037cf10 --- /dev/null +++ b/agent/docker_prepare.go @@ -0,0 +1,260 @@ +//go:build linux + +package agent + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "time" +) + +const ( + preparationMemory int64 = 64 * 1024 * 1024 + preparationNanoCPUs int64 = 100000000 + preparationPids int64 = 16 + preparationPath = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + dockerPreparationAPI = "/v1.44" +) + +// UnixDockerEngine speaks only to an operator-selected local Unix socket. +// There are no exported generic requests, registry pulls, start/exec, removal, +// network, volume, or device operations. Unsupported API versions fail closed. +type UnixDockerEngine struct{ client *http.Client } + +func NewUnixDockerEngine(socketPath string) (*UnixDockerEngine, error) { + if !filepath.IsAbs(socketPath) { + return nil, errors.New("an absolute trusted Docker socket is required") + } + resolved, err := filepath.EvalSymlinks(socketPath) + if err != nil { + return nil, errors.New("Docker socket is unavailable") + } + info, err := os.Lstat(resolved) + if err != nil || info.Mode()&os.ModeSocket == 0 || info.Mode().Perm()&0002 != 0 { + return nil, errors.New("Docker endpoint must be a non-world-writable local socket") + } + dialer := &net.Dialer{Timeout: 5 * time.Second} + transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return dialer.DialContext(ctx, "unix", resolved) + }, DisableKeepAlives: true} + return &UnixDockerEngine{client: &http.Client{Transport: transport, Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil +} + +type dockerHealthcheck struct{ Test []string } +type dockerConfig struct { + Image string + User string + WorkingDir string + Entrypoint []string + Cmd []string + Env []string + Labels map[string]string + Volumes map[string]json.RawMessage + ExposedPorts map[string]json.RawMessage + OnBuild []string + Healthcheck dockerHealthcheck + NetworkDisabled bool + Tty bool + OpenStdin bool + AttachStdin bool + AttachStdout bool + AttachStderr bool +} +type dockerImage struct { + ID string `json:"Id"` + OS string `json:"Os"` + Config dockerConfig +} +type dockerRestartPolicy struct { + Name string + MaximumRetryCount int +} +type dockerLogConfig struct { + Type string + Config map[string]string +} +type dockerHostConfig struct { + NetworkMode string + ReadonlyRootfs bool + Privileged bool + AutoRemove bool + PublishAllPorts bool + CapDrop []string + CapAdd []string + SecurityOpt []string + RestartPolicy dockerRestartPolicy + IpcMode string + PidMode string + UTSMode string + UsernsMode string + CgroupnsMode string + Memory int64 + NanoCPUs int64 + PidsLimit int64 + LogConfig dockerLogConfig + Binds []string + Mounts []json.RawMessage + Devices []json.RawMessage + DeviceRequests []json.RawMessage + DeviceCgroupRules []string + VolumesFrom []string + PortBindings map[string]json.RawMessage + Links []string + ExtraHosts []string + GroupAdd []string + Tmpfs map[string]string + Sysctls map[string]string +} +type dockerEndpointConfig struct { + Aliases []string `json:",omitempty"` +} +type dockerNetworkingConfig struct { + EndpointsConfig map[string]dockerEndpointConfig +} +type dockerCreateRequest struct { + dockerConfig + HostConfig dockerHostConfig + NetworkingConfig *dockerNetworkingConfig `json:",omitempty"` +} +type dockerContainer struct { + ID string `json:"Id"` + Name string + Image string + Config dockerConfig + HostConfig dockerHostConfig + RestartCount int + State struct { + Status string + Running bool + Paused bool + Restarting bool + Dead bool + StartedAt string + } + Mounts []json.RawMessage + NetworkSettings struct { + Ports map[string]json.RawMessage + Networks map[string]struct{ Aliases []string } + } +} + +func preparationCreate(record containerPreparation, host string) dockerCreateRequest { + request := preparationCreateBase(record, host) + if alias := record.Profile.NetworkAlias; alias != "" { + request.NetworkingConfig = &dockerNetworkingConfig{EndpointsConfig: map[string]dockerEndpointConfig{record.Profile.Network: {Aliases: []string{alias}}}} + } + return request +} + +func preparationCreateBase(record containerPreparation, host string) dockerCreateRequest { + return dockerCreateRequest{ + dockerConfig: dockerConfig{Image: record.Profile.ImageID, User: "65534:65534", WorkingDir: "/", Entrypoint: []string{record.Profile.Entrypoint}, Cmd: append([]string{}, record.Profile.Args...), Env: append([]string{preparationPath}, record.Profile.Env...), Labels: record.labels(host), Volumes: map[string]json.RawMessage{}, ExposedPorts: map[string]json.RawMessage{}, Healthcheck: dockerHealthcheck{Test: []string{"NONE"}}, NetworkDisabled: record.Profile.Network == ""}, + HostConfig: dockerHostConfig{NetworkMode: preparedNetwork(record.Profile), ReadonlyRootfs: true, CapDrop: []string{"ALL"}, SecurityOpt: []string{"no-new-privileges:true"}, RestartPolicy: dockerRestartPolicy{Name: "no"}, IpcMode: "none", CgroupnsMode: "private", Memory: preparationMemory, NanoCPUs: preparationNanoCPUs, PidsLimit: preparationPids, LogConfig: dockerLogConfig{Type: "none"}, Binds: []string{}, Mounts: []json.RawMessage{}, Devices: []json.RawMessage{}, DeviceRequests: []json.RawMessage{}, PortBindings: map[string]json.RawMessage{}}, + } +} + +func (engine *UnixDockerEngine) inspectImage(ctx context.Context, imageID string) (dockerImage, error) { + var image dockerImage + if !validImageID(imageID) { + return image, ErrPreparationPolicy + } + status, err := engine.call(ctx, http.MethodGet, "/images/"+url.PathEscape(imageID)+"/json", nil, &image) + if err != nil { + return image, err + } + if status != http.StatusOK { + return image, fmt.Errorf("Docker image inspection returned status %d", status) + } + return image, nil +} + +func validPreparationName(name string) bool { + if !strings.HasPrefix(name, "tp-agent-prepared-") || len(name) != len("tp-agent-prepared-")+40 { + return false + } + for _, c := range strings.TrimPrefix(name, "tp-agent-prepared-") { + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { + return false + } + } + return true +} + +func (engine *UnixDockerEngine) inspectContainer(ctx context.Context, name string) (dockerContainer, bool, error) { + var container dockerContainer + if !validPreparationName(name) { + return container, false, ErrPreparationPolicy + } + status, err := engine.call(ctx, http.MethodGet, "/containers/"+name+"/json", nil, &container) + if err != nil { + return container, false, err + } + if status == http.StatusNotFound { + return container, false, nil + } + if status != http.StatusOK { + return container, false, fmt.Errorf("Docker container inspection returned status %d", status) + } + return container, true, nil +} + +func (engine *UnixDockerEngine) createContainer(ctx context.Context, name string, request dockerCreateRequest) (string, error) { + if !validPreparationName(name) || !validImageID(request.Image) { + return "", ErrPreparationPolicy + } + var created struct { + ID string `json:"Id"` + } + status, err := engine.call(ctx, http.MethodPost, "/containers/create?"+url.Values{"name": {name}}.Encode(), request, &created) + if err != nil { + return "", err + } + if status != http.StatusCreated || !validHexID(created.ID) { + return "", fmt.Errorf("Docker create result unconfirmed (status %d)", status) + } + return created.ID, nil +} + +func (engine *UnixDockerEngine) call(ctx context.Context, method, path string, input, output any) (int, error) { + var body io.Reader + if input != nil { + raw, err := json.Marshal(input) + if err != nil { + return 0, err + } + body = bytes.NewReader(raw) + } + request, err := http.NewRequestWithContext(ctx, method, "http://docker"+dockerPreparationAPI+path, body) + if err != nil { + return 0, errors.New("invalid Docker preparation request") + } + request.Header.Set("Content-Type", "application/json") + response, err := engine.client.Do(request) + if err != nil { + return 0, errors.New("Docker preparation response is unknown") + } + defer response.Body.Close() + // Error bodies may contain daemon paths or workload data; never propagate + // them. Only successful responses are parsed, with a strict size bound. + if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { + return response.StatusCode, nil + } + raw, err := io.ReadAll(io.LimitReader(response.Body, 1024*1024+1)) + if err != nil || len(raw) > 1024*1024 { + return response.StatusCode, errors.New("Docker preparation response is incomplete or oversized") + } + if err := json.Unmarshal(raw, output); err != nil { + return response.StatusCode, errors.New("Docker preparation response is invalid") + } + return response.StatusCode, nil +} diff --git a/agent/docker_prepare_real_test.go b/agent/docker_prepare_real_test.go new file mode 100644 index 0000000..1f0cd43 --- /dev/null +++ b/agent/docker_prepare_real_test.go @@ -0,0 +1,259 @@ +//go:build linux + +package agent + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// Opt-in only. No image pull or build occurs here: the operator must supply a +// reviewed existing image ID satisfying the create-only profile restrictions. +func realPreparationFixture(t *testing.T) (*Store, string, *UnixDockerEngine, PreparationProfile) { + t.Helper() + if os.Getenv("TP_AGENT_REAL_DOCKER") != "1" { + t.Skip("TP_AGENT_REAL_DOCKER=1 plus explicit trusted socket/image ID required; not Docker acceptance") + } + imageID, socket := os.Getenv("TP_AGENT_DOCKER_IMAGE_ID"), os.Getenv("TP_AGENT_DOCKER_SOCKET") + if !validImageID(imageID) || socket == "" { + t.Fatal("an immutable reviewed image ID and explicit local socket are required") + } + engine, err := NewUnixDockerEngine(socket) + if err != nil { + t.Fatal(err) + } + random := make([]byte, 16) + if _, err := rand.Read(random); err != nil { + t.Fatal(err) + } + host := "tp-takeover-b-installer-agent-" + hex.EncodeToString(random) + path := filepath.Join(t.TempDir(), "state.json") + if err := Initialize(path, host); err != nil { + t.Fatal(err) + } + store, err := Open(path) + if err != nil { + t.Fatal(err) + } + if err := store.AcceptGeneration("instance-a", 1); err != nil { + t.Fatal(err) + } + profile := preparationFixtureProfile() + profile.ImageID = imageID + t.Cleanup(func() { + // Test-only cleanup: never force removal, never remove a running, + // unowned or altered container, and never infer ownership from a name. + disk, err := load(path) + if err != nil { + t.Errorf("fixture ledger needs owner review before cleanup: %v", err) + return + } + for _, record := range disk.Preparations { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + container, exists, err := engine.inspectContainer(ctx, record.ContainerName) + if err != nil { + cancel() + t.Errorf("fixture inspect before cleanup: %v", err) + continue + } + if !exists { + cancel() + continue + } + if disk.HostID != host || !safePreparedContainer(container, record, host) { + cancel() + t.Errorf("fixture container %s changed; owner review required, no cleanup attempted", record.ContainerName) + continue + } + status, err := engine.call(ctx, http.MethodDelete, "/containers/"+container.ID+"?force=false&v=false", nil, nil) + cancel() + if err != nil || status != http.StatusNoContent { + t.Errorf("fixture container cleanup status=%d error=%v", status, err) + } + } + }) + return store, path, engine, profile +} + +type preparationRoundTripFunc func(*http.Request) (*http.Response, error) + +func (call preparationRoundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { + return call(request) +} + +func TestPreparationRealDockerLostReplyAndRestart(t *testing.T) { + store, path, engine, profile := realPreparationFixture(t) + base := engine.client.Transport + var createCalls atomic.Int64 + interrupted := &UnixDockerEngine{client: &http.Client{Transport: preparationRoundTripFunc(func(request *http.Request) (*http.Response, error) { + response, err := base.RoundTrip(request) + if request.Method == http.MethodPost && request.URL.Path == dockerPreparationAPI+"/containers/create" { + createCalls.Add(1) + if err == nil && response.StatusCode == http.StatusCreated { + io.Copy(io.Discard, response.Body) + response.Body.Close() + return nil, errors.New("fixture dropped actual Docker create reply") + } + } + return response, err + }), Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} + preparer, err := NewDockerPreparer(store, interrupted, []PreparationProfile{profile}) + if err != nil { + t.Fatal(err) + } + request := PrepareContainerRequest{Instance: "instance-a", Generation: 1, RequestKey: "original-key", Profile: profile.Name} + first, err := preparer.Prepare(context.Background(), request) + if err != nil || first.State != PreparationPrepared || first.Active || first.ImageID != profile.ImageID || createCalls.Load() != 1 { + t.Fatalf("real Docker lost response was not reconciled: %#v creates=%d error=%v", first, createCalls.Load(), err) + } + reopened, err := Open(path) + if err != nil { + t.Fatal(err) + } + restarted, err := NewDockerPreparer(reopened, interrupted, []PreparationProfile{profile}) + if err != nil { + t.Fatal(err) + } + second, err := restarted.Prepare(context.Background(), request) + if err != nil || first != second || createCalls.Load() != 1 { + t.Fatalf("restart repeated Docker create or changed receipt: %#v creates=%d %v", second, createCalls.Load(), err) + } + container, exists, err := engine.inspectContainer(context.Background(), first.ContainerName) + if err != nil || !exists || container.State.Status != "created" || container.State.Running || container.Image != profile.ImageID { + t.Fatalf("prepared instance executed or changed: exists=%v state=%s running=%v error=%v", exists, container.State.Status, container.State.Running, err) + } + t.Logf("actual Docker immutable image=%s original container=%s state=created active=false", profile.ImageID, first.ContainerID) +} + +// The proxy forwards to the real daemon, then withholds its successful create +// reply. It does not simulate the container. The child process's state remains +// an intent while a real container already exists; SIGKILL tests that boundary. +func realPreparationReplyProxy(t *testing.T, engine *UnixDockerEngine, entered chan<- struct{}, release <-chan struct{}, creates *atomic.Int64) string { + t.Helper() + dir, err := os.MkdirTemp("", "tp-agent-real-proxy-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + socket := filepath.Join(dir, "docker.sock") + listener, err := net.Listen("unix", socket) + if err != nil { + t.Fatal(err) + } + if err := os.Chmod(socket, 0600); err != nil { + t.Fatal(err) + } + var once sync.Once + server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + isRead := r.Method == http.MethodGet && (strings.HasPrefix(r.URL.Path, dockerPreparationAPI+"/images/") || strings.HasPrefix(r.URL.Path, dockerPreparationAPI+"/containers/")) && strings.HasSuffix(r.URL.Path, "/json") + isCreate := r.Method == http.MethodPost && r.URL.Path == dockerPreparationAPI+"/containers/create" + if !isRead && !isCreate { + t.Errorf("unexpected real-daemon proxy action %s %s", r.Method, r.URL.Path) + w.WriteHeader(403) + return + } + forward := r.Clone(r.Context()) + forward.RequestURI = "" + forward.URL.Scheme = "http" + forward.URL.Host = "docker" + response, err := engine.client.Do(forward) + if err != nil { + w.WriteHeader(503) + return + } + defer response.Body.Close() + if isCreate { + creates.Add(1) + if response.StatusCode == http.StatusCreated { + once.Do(func() { close(entered) }) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(response.StatusCode) + _, _ = io.Copy(w, io.LimitReader(response.Body, 1024*1024+1)) + })} + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Close() }) + return socket +} + +func TestPreparationRealDockerTwoProcessesAndSIGKILL(t *testing.T) { + for _, kill := range []bool{false, true} { + name := "two-processes" + if kill { + name = "sigkill" + } + t.Run(name, func(t *testing.T) { + _, state, engine, profile := realPreparationFixture(t) + entered, release := make(chan struct{}), make(chan struct{}) + var creates atomic.Int64 + socket := realPreparationReplyProxy(t, engine, entered, release, &creates) + firstPath := filepath.Join(t.TempDir(), "first.json") + first, firstOutput := startPreparationChild(t, state, socket, firstPath, "prepare", profile.ImageID) + select { + case <-entered: + case <-time.After(15 * time.Second): + t.Fatal("real Docker create did not reach durable-intent/lost-reply boundary") + } + disk, err := load(state) + if err != nil { + t.Fatal(err) + } + if record := disk.Preparations["instance-a\x00original-key"]; record.State != "intent" { + t.Fatal("receipt was committed before the withheld real reply") + } + secondPath := filepath.Join(t.TempDir(), "second.json") + if kill { + if err := first.Process.Kill(); err != nil { + t.Fatal(err) + } + if err := first.Wait(); err == nil { + t.Fatal("expected actual SIGKILL of preparing process") + } + close(release) + } else { + // Start another process while the original state lock spans the + // real create. Both processes must converge to the same receipt. + second, secondOutput := startPreparationChild(t, state, socket, secondPath, "prepare", profile.ImageID) + close(release) + if err := first.Wait(); err != nil { + t.Fatalf("first process: %v %s", err, firstOutput.String()) + } + if err := second.Wait(); err != nil { + t.Fatalf("second process: %v %s", err, secondOutput.String()) + } + if a, b := readPreparationChild(t, firstPath), readPreparationChild(t, secondPath); a != b { + t.Fatalf("real two-process receipts differ: %#v %#v", a, b) + } + } + if kill { + restarted, restartedOutput := startPreparationChild(t, state, socket, secondPath, "prepare", profile.ImageID) + if err := restarted.Wait(); err != nil { + t.Fatalf("restarted process: %v %s", err, restartedOutput.String()) + } + } + result := readPreparationChild(t, secondPath) + if result.State != PreparationPrepared || result.Active || result.ImageID != profile.ImageID || creates.Load() != 1 { + t.Fatalf("real process recovery guessed or recreated: %#v creates=%d", result, creates.Load()) + } + t.Logf("actual Docker image=%s container=%s create_calls=1 state=created active=false", profile.ImageID, result.ContainerID) + }) + } +} diff --git a/agent/docker_prepare_test.go b/agent/docker_prepare_test.go new file mode 100644 index 0000000..cc40c31 --- /dev/null +++ b/agent/docker_prepare_test.go @@ -0,0 +1,289 @@ +//go:build linux + +package agent + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// This is a wire-protocol/process fixture, not a real Docker daemon. Separate +// opt-in real Docker tests must pass before recording runtime preparation proof. +func preparationUnixFixture(t *testing.T, engine *preparationFixtureEngine, beforeCreate, afterCreate func(context.Context) bool) string { + t.Helper() + dir, err := os.MkdirTemp("", "tp-agent-socket-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + socket := filepath.Join(dir, "docker.sock") + listener, err := net.Listen("unix", socket) + if err != nil { + t.Fatal(err) + } + if err := os.Chmod(socket, 0600); err != nil { + t.Fatal(err) + } + server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, dockerPreparationAPI+"/images/") && strings.HasSuffix(r.URL.Path, "/json"): + image, err := engine.inspectImage(r.Context(), preparationFixtureProfile().ImageID) + if err != nil { + w.WriteHeader(503) + return + } + _ = json.NewEncoder(w).Encode(image) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, dockerPreparationAPI+"/containers/") && strings.HasSuffix(r.URL.Path, "/json"): + name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, dockerPreparationAPI+"/containers/"), "/json") + container, exists, err := engine.inspectContainer(r.Context(), name) + if err != nil { + w.WriteHeader(503) + return + } + if !exists { + w.WriteHeader(404) + return + } + _ = json.NewEncoder(w).Encode(container) + case r.Method == http.MethodPost && r.URL.Path == dockerPreparationAPI+"/containers/create": + var request dockerCreateRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Error(err) + w.WriteHeader(400) + return + } + if request.Image != preparationFixtureProfile().ImageID || request.HostConfig.NetworkMode != "none" || len(request.HostConfig.Binds) != 0 || len(request.HostConfig.Mounts) != 0 || len(request.HostConfig.Devices) != 0 || len(request.HostConfig.PortBindings) != 0 || !request.HostConfig.ReadonlyRootfs || request.HostConfig.Privileged || !equalStrings(request.Env, []string{preparationPath}) { + t.Error("transport changed bounded create configuration") + w.WriteHeader(400) + return + } + if beforeCreate != nil && !beforeCreate(r.Context()) { + return + } + id, err := engine.createContainer(r.Context(), r.URL.Query().Get("name"), request) + if err != nil { + w.WriteHeader(503) + return + } + if afterCreate != nil && !afterCreate(r.Context()) { + return + } + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]string{"Id": id}) + default: + t.Errorf("forbidden/unexpected Docker method: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusForbidden) + } + })} + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Close() }) + return socket +} + +func TestPreparationUnixTransportCreatesWithoutStarting(t *testing.T) { + store, _, _, fixture, request := preparedFixture(t) + socket := preparationUnixFixture(t, fixture, nil, nil) + engine, err := NewUnixDockerEngine(socket) + if err != nil { + t.Fatal(err) + } + preparer, err := NewDockerPreparer(store, engine, []PreparationProfile{preparationFixtureProfile()}) + if err != nil { + t.Fatal(err) + } + first, err := preparer.Prepare(context.Background(), request) + if err != nil || first.State != PreparationPrepared || first.Active || fixture.createCount() != 1 { + t.Fatalf("wire preparation: %#v %v", first, err) + } + second, err := preparer.Query(context.Background(), request.Instance, 1, request.RequestKey) + if err != nil || second != first || fixture.createCount() != 1 { + t.Fatalf("wire original query: %#v %v", second, err) + } + if _, err := NewUnixDockerEngine("tcp://untrusted:2375"); err == nil { + t.Fatal("non-local endpoint accepted") + } +} + +type preparationChildResult struct { + Observation PreparationObservation + Error string +} + +func TestPreparationProcessChild(t *testing.T) { + if os.Getenv("TP_AGENT_PREPARATION_CHILD") != "1" { + return + } + store, err := Open(os.Getenv("TP_AGENT_PREPARATION_STATE")) + if err != nil { + t.Fatal(err) + } + engine, err := NewUnixDockerEngine(os.Getenv("TP_AGENT_PREPARATION_SOCKET")) + if err != nil { + t.Fatal(err) + } + profile := preparationFixtureProfile() + if image := os.Getenv("TP_AGENT_PREPARATION_IMAGE"); image != "" { + profile.ImageID = image + } + preparer, err := NewDockerPreparer(store, engine, []PreparationProfile{profile}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + request := PrepareContainerRequest{Instance: "instance-a", Generation: 1, RequestKey: "original-key", Profile: profile.Name} + var result PreparationObservation + if os.Getenv("TP_AGENT_PREPARATION_MODE") == "query" { + result, err = preparer.Query(ctx, request.Instance, 1, request.RequestKey) + } else { + result, err = preparer.Prepare(ctx, request) + } + output := preparationChildResult{Observation: result} + if err != nil { + output.Error = err.Error() + } + raw, _ := json.Marshal(output) + if err := os.WriteFile(os.Getenv("TP_AGENT_PREPARATION_RESULT"), raw, 0600); err != nil { + t.Fatal(err) + } + if err != nil { + t.Fatal(err) + } +} + +func startPreparationChild(t *testing.T, state, socket, result, mode, image string) (*exec.Cmd, *bytes.Buffer) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPreparationProcessChild$", "-test.v") + command.Env = append(os.Environ(), "TP_AGENT_PREPARATION_CHILD=1", "TP_AGENT_PREPARATION_STATE="+state, "TP_AGENT_PREPARATION_SOCKET="+socket, "TP_AGENT_PREPARATION_RESULT="+result, "TP_AGENT_PREPARATION_MODE="+mode, "TP_AGENT_PREPARATION_IMAGE="+image) + output := new(bytes.Buffer) + command.Stdout, command.Stderr = output, output + if err := command.Start(); err != nil { + t.Fatal(err) + } + return command, output +} + +func readPreparationChild(t *testing.T, path string) PreparationObservation { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var result preparationChildResult + if err := json.Unmarshal(raw, &result); err != nil { + t.Fatal(err) + } + if result.Error != "" { + t.Fatalf("child error: %s", result.Error) + } + return result.Observation +} + +func TestPreparationTwoProcessesReuseOneDurableOperation(t *testing.T) { + _, state, _, fixture, _ := preparedFixture(t) + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + socket := preparationUnixFixture(t, fixture, nil, func(ctx context.Context) bool { + once.Do(func() { close(entered) }) + select { + case <-release: + return true + case <-ctx.Done(): + return false + } + }) + firstPath, secondPath := filepath.Join(t.TempDir(), "first.json"), filepath.Join(t.TempDir(), "second.json") + first, firstOutput := startPreparationChild(t, state, socket, firstPath, "prepare", "") + select { + case <-entered: + case <-time.After(10 * time.Second): + t.Fatal("first process did not reach create") + } + second, secondOutput := startPreparationChild(t, state, socket, secondPath, "prepare", "") + close(release) + if err := first.Wait(); err != nil { + t.Fatalf("first process: %v %s", err, firstOutput.String()) + } + if err := second.Wait(); err != nil { + t.Fatalf("second process: %v %s", err, secondOutput.String()) + } + a, b := readPreparationChild(t, firstPath), readPreparationChild(t, secondPath) + fixture.mu.Lock() + creates := fixture.creates + fixture.mu.Unlock() + if a.State != PreparationPrepared || a.Active || a != b || creates != 1 { + t.Fatalf("two-process receipt diverged: %#v %#v creates=%d", a, b, creates) + } +} + +func TestPreparationSIGKILLRecoversOriginalIntentWithoutRecreate(t *testing.T) { + for _, afterSideEffect := range []bool{false, true} { + t.Run(fmt.Sprintf("after-side-effect-%t", afterSideEffect), func(t *testing.T) { + _, state, _, fixture, request := preparedFixture(t) + entered := make(chan struct{}) + var once sync.Once + var createRequests atomic.Int64 + block := func(ctx context.Context) bool { + createRequests.Add(1) + once.Do(func() { close(entered) }) + <-ctx.Done() + return false + } + var before, after func(context.Context) bool + if afterSideEffect { + after = block + } else { + before = block + } + socket := preparationUnixFixture(t, fixture, before, after) + killed, killedOutput := startPreparationChild(t, state, socket, filepath.Join(t.TempDir(), "killed.json"), "prepare", "") + select { + case <-entered: + case <-time.After(10 * time.Second): + t.Fatal("child did not reach durable create boundary") + } + disk, err := load(state) + if err != nil { + t.Fatal(err) + } + intent := disk.Preparations[request.Instance+"\x00"+request.RequestKey] + if intent.State != "intent" || disk.Requests[request.Instance+"\x00"+request.RequestKey].State != "held" { + t.Fatal("Docker create preceded durable original intent") + } + if err := killed.Process.Kill(); err != nil { + t.Fatal(err) + } + if err := killed.Wait(); err == nil { + t.Fatalf("child unexpectedly succeeded: %s", killedOutput.String()) + } + resultPath := filepath.Join(t.TempDir(), "restarted.json") + restarted, restartedOutput := startPreparationChild(t, state, socket, resultPath, "prepare", "") + if err := restarted.Wait(); err != nil { + t.Fatalf("restart: %v %s", err, restartedOutput.String()) + } + result := readPreparationChild(t, resultPath) + want := PreparationUnknown + if afterSideEffect { + want = PreparationPrepared + } + if result.State != want || result.Active || createRequests.Load() != 1 { + t.Fatalf("SIGKILL recovery recreated/guessed outcome: %#v create requests=%d", result, createRequests.Load()) + } + }) + } +} diff --git a/agent/go.mod b/agent/go.mod new file mode 100644 index 0000000..4481b43 --- /dev/null +++ b/agent/go.mod @@ -0,0 +1,3 @@ +module thingspanel-installer-agent-state + +go 1.22 diff --git a/agent/network_alias_test.go b/agent/network_alias_test.go new file mode 100644 index 0000000..04dc295 --- /dev/null +++ b/agent/network_alias_test.go @@ -0,0 +1,86 @@ +//go:build linux + +package agent + +import ( + "context" + "testing" +) + +func aliasProfile() PreparationProfile { + p := preparationFixtureProfile() + p.Network, p.NetworkAlias = "stack_net", "tp-plugin-homeassistant" + return p +} + +func TestNetworkAliasProfileValidation(t *testing.T) { + if !validPreparationProfile(aliasProfile()) { + t.Fatal("valid alias rejected") + } + for _, alias := range []string{"-bad", "bad-", "Upper", "has space", "a.b", "x_y"} { + p := aliasProfile() + p.NetworkAlias = alias + if validPreparationProfile(p) { + t.Fatalf("alias %q accepted", alias) + } + } + p := preparationFixtureProfile() // alias without a network is meaningless + p.NetworkAlias = "tp-plugin-x" + if validPreparationProfile(p) { + t.Fatal("alias without network accepted") + } +} + +func TestNetworkAliasIsStableAcrossGenerationsAndChecked(t *testing.T) { + profile := aliasProfile() + one := preparationCreate(containerPreparation{Instance: "i", Generation: 1, Profile: profile}, "h") + two := preparationCreate(containerPreparation{Instance: "i", Generation: 2, Profile: profile}, "h") + for _, request := range []dockerCreateRequest{one, two} { + got := request.NetworkingConfig.EndpointsConfig["stack_net"].Aliases + if len(got) != 1 || got[0] != "tp-plugin-homeassistant" { + t.Fatalf("alias not set: %#v", got) + } + } + if preparationCreate(containerPreparation{Profile: preparationFixtureProfile()}, "h").NetworkingConfig != nil { + t.Fatal("no alias must not add a networking config") + } +} + +func TestPreparedContainerWithoutAliasIsNotTrusted(t *testing.T) { + for _, test := range []struct { + name string + aliases []string + trusted bool + }{ + {"with-alias", []string{"tp-plugin-homeassistant", "abc"}, true}, + {"without-alias", []string{"abc"}, false}, + } { + t.Run(test.name, func(t *testing.T) { + store, _ := initialized(t) + engine := newPreparationFixtureEngine() + profile := aliasProfile() + preparer, err := newDockerPreparer(store, engine, []PreparationProfile{profile}) + if err != nil { + t.Fatal(err) + } + request := PrepareContainerRequest{Instance: "instance-a", Generation: 1, RequestKey: "k", Profile: profile.Name} + if err := store.AcceptGeneration(request.Instance, 1); err != nil { + t.Fatal(err) + } + original, err := preparer.Prepare(context.Background(), request) + if err != nil || original.State != PreparationPrepared { + t.Fatal(err) + } + c := engine.containers[original.ContainerName] + c.NetworkSettings.Networks = map[string]struct{ Aliases []string }{"stack_net": {Aliases: test.aliases}} + engine.containers[original.ContainerName] = c + observation, err := preparer.Query(context.Background(), request.Instance, 1, request.RequestKey) + if err != nil { + t.Fatal(err) + } + if got := observation.State == PreparationPrepared; got != test.trusted { + t.Fatalf("trusted=%v want %v: %#v", got, test.trusted, observation) + } + }) + } +} diff --git a/agent/prepare.go b/agent/prepare.go new file mode 100644 index 0000000..a734ece --- /dev/null +++ b/agent/prepare.go @@ -0,0 +1,601 @@ +//go:build linux + +package agent + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "sync" +) + +var ( + ErrPreparationRecoveryRequired = errors.New("prepared container needs owner-reviewed recovery; generic release is forbidden") + ErrPreparationPolicy = errors.New("container preparation is outside the configured allowlist") +) + +const ( + PreparationPrepared = "prepared" + PreparationUnknown = "unknown" + PreparationNotObserved = "not_observed" +) + +// PreparationProfile is trusted service configuration, never an API request. +// Only local immutable image IDs and fixed commands are accepted. Nothing in +// this adapter starts the command; the profile has no network/mount/secret knobs. +type PreparationProfile struct { + Name string `json:"name"` + ImageID string `json:"image_id"` + Entrypoint string `json:"entrypoint"` + Args []string `json:"args"` + // The three fields below are reviewed operator configuration for plugins that must talk to the + // platform. They never come from an API request and are all off by default. Network names an + // existing user-defined Docker network (no host/bridge/none/container networks); Env is a fixed + // list of KEY=VALUE pairs; ReviewedImageMetadata accepts the pinned image's own exposed-port and + // environment declarations (volumes, labels and OnBuild stay forbidden, nothing is ever published). + Network string `json:"network,omitempty"` + Env []string `json:"env,omitempty"` + ReviewedImageMetadata bool `json:"reviewed_image_metadata,omitempty"` + // NetworkAlias is a stable DNS alias on Network (e.g. tp-plugin-homeassistant), so the address the + // platform registers survives container replacement across generations. Requires Network. + NetworkAlias string `json:"network_alias,omitempty"` +} + +type PrepareContainerRequest struct { + Instance string + Generation uint64 + RequestKey string + Profile string +} + +type PreparationObservation struct { + State string `json:"state"` + Active bool `json:"active"` // always false; never an execution grant + Instance string `json:"instance"` + Generation uint64 `json:"generation"` + RequestKey string `json:"request_key"` + PayloadHash string `json:"payload_hash,omitempty"` + ImageID string `json:"image_id,omitempty"` + ContainerName string `json:"container_name,omitempty"` + ContainerID string `json:"container_id,omitempty"` + ErrorCode string `json:"error_code,omitempty"` +} + +type containerPreparation struct { + Version int `json:"version"` + Instance string `json:"instance"` + Generation uint64 `json:"generation"` + RequestKey string `json:"request_key"` + Profile PreparationProfile `json:"profile"` + PayloadHash string `json:"payload_hash"` + ContainerName string `json:"container_name"` + ContainerID string `json:"container_id,omitempty"` + State string `json:"state"` // intent | unknown | prepared + ErrorCode string `json:"error_code,omitempty"` +} + +type preparationEngine interface { + inspectImage(context.Context, string) (dockerImage, error) + inspectContainer(context.Context, string) (dockerContainer, bool, error) + createContainer(context.Context, string, dockerCreateRequest) (string, error) +} + +type DockerPreparer struct { + store *Store + engine preparationEngine + profiles map[string]PreparationProfile + profMu sync.RWMutex + secrets *SecretStore +} + +// SetSecrets enables "@secret:" placeholders in profile environments (resolved only at create/verify time). +func (p *DockerPreparer) SetSecrets(s *SecretStore) { p.secrets = s } + +func (p *DockerPreparer) profile(name string) (PreparationProfile, bool) { + p.profMu.RLock() + defer p.profMu.RUnlock() + profile, ok := p.profiles[name] + return profile, ok +} + +// SetProfile registers a profile built by the Agent from the verified catalog. Names are unique per generation. +func (p *DockerPreparer) SetProfile(profile PreparationProfile) error { + if !validPreparationProfile(profile) { + return ErrPreparationPolicy + } + p.profMu.Lock() + defer p.profMu.Unlock() + if existing, found := p.profiles[profile.Name]; found && !reflect.DeepEqual(existing, profile) { + return ErrResourceConflict + } + profile.Args = append([]string{}, profile.Args...) + p.profiles[profile.Name] = profile + return nil +} + +// AdoptRecorded re-registers, after an Agent restart, the profiles of preparations that were recorded earlier, but +// only those the verified catalog still vouches for (same image and entrypoint) and whose recorded digest still +// matches; anything else stays unknown and therefore untrusted. +func (p *DockerPreparer) AdoptRecorded(vouches func(PreparationProfile) bool) error { + return withLock(p.store.path, func() error { + disk, err := load(p.store.path) + if err != nil { + return err + } + for _, record := range disk.Preparations { + if _, known := p.profile(record.Profile.Name); known || !vouches(record.Profile) { + continue + } + if preparationDigest(disk.HostID, record.request(), record.Profile) != record.PayloadHash { + continue + } + _ = p.SetProfile(record.Profile) + } + return nil + }) +} + +// resolved returns the record with secret placeholders replaced, for the create request and for verification only. +func (p *DockerPreparer) resolved(record containerPreparation) (containerPreparation, error) { + if !hasPlaceholder(record.Profile.Env) { + return record, nil + } + if p.secrets == nil { + return record, ErrPreparationPolicy + } + env, err := p.secrets.ResolveEnv(record.Instance, record.Profile.Env) + if err != nil { + return record, err + } + record.Profile.Env = env + return record, nil +} + +// NewDockerPreparer enables only the bounded local Docker transport. There is +// no user-controlled URL or generic command runner and no automatic enrollment. +func NewDockerPreparer(store *Store, engine *UnixDockerEngine, profiles []PreparationProfile) (*DockerPreparer, error) { + if engine == nil { + return nil, ErrPreparationPolicy + } + return newDockerPreparer(store, engine, profiles) +} + +func newDockerPreparer(store *Store, engine preparationEngine, profiles []PreparationProfile) (*DockerPreparer, error) { + if store == nil || engine == nil || len(profiles) > 64 { + return nil, ErrPreparationPolicy + } + if _, err := store.HostID(); err != nil { + return nil, err + } + out := &DockerPreparer{store: store, engine: engine, profiles: map[string]PreparationProfile{}} + for _, profile := range profiles { + if !validPreparationProfile(profile) { + return nil, ErrPreparationPolicy + } + if _, duplicate := out.profiles[profile.Name]; duplicate { + return nil, ErrPreparationPolicy + } + profile.Args = append([]string{}, profile.Args...) + out.profiles[profile.Name] = profile + } + return out, nil +} + +func validPreparationProfile(p PreparationProfile) bool { + if p.NetworkAlias != "" && (p.Network == "" || !validNetworkAlias(p.NetworkAlias)) { + return false + } + if !valid(p.Name) || len(p.Name) > 128 || !validImageID(p.ImageID) || !strings.HasPrefix(p.Entrypoint, "/") || !valid(p.Entrypoint) || len(p.Entrypoint) > 1024 || len(p.Args) > 32 { + return false + } + total := 0 + for _, arg := range p.Args { + if strings.ContainsRune(arg, '\x00') { + return false + } + total += len(arg) + } + if total > 8192 { + return false + } + if p.Network != "" && !validPreparationNetwork(p.Network) { + return false + } + if len(p.Env) > 64 { + return false + } + seen := map[string]bool{} + envTotal := 0 + for _, entry := range p.Env { + key, _, found := strings.Cut(entry, "=") + if !found || !validEnvKey(key) || key == "PATH" || seen[key] || strings.ContainsRune(entry, '\x00') { + return false + } + seen[key] = true + envTotal += len(entry) + } + return envTotal <= 16384 +} + +func validEnvKey(key string) bool { + if key == "" || len(key) > 128 || (key[0] >= '0' && key[0] <= '9') { + return false + } + for _, r := range key { + if !(r == '_' || (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')) { + return false + } + } + return true +} + +func validPreparationNetwork(name string) bool { + switch name { + case "none", "host", "bridge", "default": + return false + } + if len(name) > 128 || name[0] == '-' || name[0] == '.' || name[0] == '_' { + return false + } + for _, r := range name { + if !(r == '_' || r == '-' || r == '.' || (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')) { + return false + } + } + return true +} + +func validImageID(value string) bool { + return strings.HasPrefix(value, "sha256:") && validHexID(strings.TrimPrefix(value, "sha256:")) +} + +func validHexID(value string) bool { + if len(value) != 64 || strings.ToLower(value) != value { + return false + } + _, err := hex.DecodeString(value) + return err == nil +} + +func preparationHash(value any) string { + raw, _ := json.Marshal(value) + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} + +func preparationName(host, instance, key string) string { + return "tp-agent-prepared-" + preparationHash([]string{host, instance, key})[:40] +} + +func preparationResource(host, instance string) string { + // A caller cannot evade an unresolved operation by choosing another key. + // The runtime instance owns one held resource across requests/generations. + return "docker-instance:" + preparationHash([]string{host, instance}) +} + +func preparationDigest(host string, request PrepareContainerRequest, profile PreparationProfile) string { + return "sha256:" + preparationHash(struct { + Version int + Host string + Request PrepareContainerRequest + Profile PreparationProfile + }{1, host, request, profile}) +} + +func (record containerPreparation) request() PrepareContainerRequest { + return PrepareContainerRequest{Instance: record.Instance, Generation: record.Generation, RequestKey: record.RequestKey, Profile: record.Profile.Name} +} + +func (record containerPreparation) labels(host string) map[string]string { + return map[string]string{ + "io.thingspanel.agent.protocol": "create-only-v1", + "io.thingspanel.agent.host": preparationHash(host), + "io.thingspanel.agent.instance": preparationHash(record.Instance), + "io.thingspanel.agent.operation": preparationHash(record.RequestKey), + "io.thingspanel.agent.generation": strconv.FormatUint(record.Generation, 10), + "io.thingspanel.agent.payload": record.PayloadHash, + } +} + +func (record containerPreparation) observation() PreparationObservation { + state := record.State + if state == "intent" { + state = PreparationUnknown + } + return PreparationObservation{State: state, Active: false, Instance: record.Instance, Generation: record.Generation, RequestKey: record.RequestKey, PayloadHash: record.PayloadHash, ImageID: record.Profile.ImageID, ContainerName: record.ContainerName, ContainerID: record.ContainerID, ErrorCode: record.ErrorCode} +} + +// Prepare never starts or execs a container. The existing OS state lock spans +// durable intent, the one allowed create call, and receipt persistence. Thus an +// accepted generation change cannot overtake an older local create operation. +// A pre-existing intent is query-only, even when Docker reports absence: a lost +// create response may still have an outcome, so this method never retries it. +func (p *DockerPreparer) Prepare(ctx context.Context, request PrepareContainerRequest) (PreparationObservation, error) { + observation := PreparationObservation{State: PreparationUnknown, Active: false} + if ctx == nil || !valid(request.Instance) || !valid(request.RequestKey) || len(request.Instance) > 256 || len(request.RequestKey) > 128 || request.Generation == 0 { + return observation, ErrPreparationPolicy + } + profile, allowed := p.profile(request.Profile) + if !allowed { + return observation, ErrPreparationPolicy + } + err := withLock(p.store.path, func() error { + disk, err := load(p.store.path) + if err != nil { + return err + } + if err = preparationGeneration(disk, request.Instance, request.Generation); err != nil { + return err + } + key := request.Instance + "\x00" + request.RequestKey + digest := preparationDigest(disk.HostID, request, profile) + if existing, found := disk.Preparations[key]; found { + if existing.PayloadHash != digest { + return ErrResourceConflict + } + observation, err = p.queryLocked(ctx, &disk, key) + return err + } + if _, reserved := disk.Requests[key]; reserved { + return ErrResourceConflict + } + name := preparationName(disk.HostID, request.Instance, request.RequestKey) + resource := preparationResource(disk.HostID, request.Instance) + if _, reserved := disk.Resources[resource]; reserved { + return ErrResourceConflict + } + image, err := p.engine.inspectImage(ctx, profile.ImageID) + if err != nil { + return err + } + if !safePreparationImage(image, profile) { + return ErrPreparationPolicy + } + // A container without this local durable intent is never adopted, even + // when its name/labels appear plausible (including after lost state). + if _, exists, err := p.engine.inspectContainer(ctx, name); err != nil { + return err + } else if exists { + return ErrResourceConflict + } + if err := ctx.Err(); err != nil { + return err + } + record := containerPreparation{Version: 1, Instance: request.Instance, Generation: request.Generation, RequestKey: request.RequestKey, Profile: profile, PayloadHash: digest, ContainerName: name, State: "intent"} + resolvedRecord, resolveErr := p.resolved(record) // before any state is written: a missing secret must not poison the request key + if resolveErr != nil { + return resolveErr + } + reservation := Reservation{Resource: resource, Instance: request.Instance, Generation: request.Generation, RequestKey: request.RequestKey, PayloadHash: digest, State: "held"} + if disk.Preparations == nil { + disk.Preparations = map[string]containerPreparation{} + } + disk.Preparations[key], disk.Requests[key], disk.Resources[resource] = record, reservation, reservation + if err := writeState(p.store.path, disk); err != nil { + return err + } + // No retry is issued on any create error, including timeout/409/5xx. + id, createErr := p.engine.createContainer(ctx, name, preparationCreate(resolvedRecord, disk.HostID)) + if createErr == nil && validHexID(id) { + record.ContainerID = id + disk.Preparations[key] = record + } + observation, err = p.queryLocked(ctx, &disk, key) + return err + }) + if err != nil { + observation.State, observation.Active = PreparationUnknown, false + } + return observation, err +} + +// Query recovers by the original identity only; it cannot submit or create. +// An absent local record is an observation, never permission to use a new key. +func (p *DockerPreparer) Query(ctx context.Context, instance string, generation uint64, key string) (PreparationObservation, error) { + observation := PreparationObservation{State: PreparationUnknown, Active: false, Instance: instance, Generation: generation, RequestKey: key} + if ctx == nil || !valid(instance) || !valid(key) || len(instance) > 256 || len(key) > 128 || generation == 0 { + return observation, ErrPreparationPolicy + } + err := withLock(p.store.path, func() error { + disk, err := load(p.store.path) + if err != nil { + return err + } + if err = preparationGeneration(disk, instance, generation); err != nil { + return err + } + identity := instance + "\x00" + key + record, exists := disk.Preparations[identity] + if !exists { + if _, reserved := disk.Requests[identity]; reserved { + return ErrResourceConflict + } + observation.State = PreparationNotObserved + return nil + } + if record.Generation != generation { + return ErrResourceConflict + } + profile, allowed := p.profile(record.Profile.Name) + if !allowed || preparationDigest(disk.HostID, record.request(), profile) != record.PayloadHash { + return ErrPreparationPolicy + } + observation, err = p.queryLocked(ctx, &disk, identity) + return err + }) + if err != nil { + observation.State, observation.Active = PreparationUnknown, false + } + return observation, err +} + +func preparationGeneration(disk diskState, instance string, generation uint64) error { + if generation < disk.MaxGeneration[instance] { + return ErrGenerationStale + } + if generation > disk.MaxGeneration[instance] { + return ErrGenerationNotAccepted + } + return nil +} + +func (p *DockerPreparer) queryLocked(ctx context.Context, disk *diskState, key string) (PreparationObservation, error) { + record := disk.Preparations[key] + container, exists, err := p.engine.inspectContainer(ctx, record.ContainerName) + record.State, record.ErrorCode = PreparationUnknown, "CONTAINER_RESULT_UNKNOWN" + if err == nil && !exists { + record.ErrorCode = "CONTAINER_NOT_OBSERVED_AFTER_INTENT" + } + if err == nil && exists { + if checked, resolveErr := p.resolved(record); resolveErr == nil && safePreparedContainer(container, checked, disk.HostID) { + record.State, record.ErrorCode, record.ContainerID = PreparationPrepared, "", container.ID + } else { + record.ErrorCode = "CONTAINER_REQUIRES_OWNER_REVIEW" + } + } + disk.Preparations[key] = record + if err := writeState(p.store.path, *disk); err != nil { + return PreparationObservation{State: PreparationUnknown, Active: false}, fmt.Errorf("preparation receipt persistence failed: %w", err) + } + return record.observation(), nil +} + +func validatePreparations(disk diskState) error { + for key, record := range disk.Preparations { + request := record.request() + if record.Version != 1 || key != record.Instance+"\x00"+record.RequestKey || !valid(record.Instance) || !valid(record.RequestKey) || record.Generation == 0 || !validPreparationProfile(record.Profile) || record.ContainerName != preparationName(disk.HostID, record.Instance, record.RequestKey) || record.PayloadHash != preparationDigest(disk.HostID, request, record.Profile) { + return errors.New("invalid preparation identity") + } + if record.State != "intent" && record.State != PreparationUnknown && record.State != PreparationPrepared { + return errors.New("invalid preparation state") + } + if record.ContainerID != "" && !validHexID(record.ContainerID) { + return errors.New("invalid prepared container ID") + } + if record.State == PreparationPrepared && (record.ContainerID == "" || record.ErrorCode != "") { + return errors.New("incomplete prepared receipt") + } + reservation := Reservation{Resource: preparationResource(disk.HostID, record.Instance), Instance: record.Instance, Generation: record.Generation, RequestKey: record.RequestKey, PayloadHash: record.PayloadHash, State: "held"} + if disk.Requests[key] != reservation || disk.Resources[reservation.Resource] != reservation { + return errors.New("preparation lost its original resource ownership") + } + } + return nil +} + +func safePreparationImage(image dockerImage, profile PreparationProfile) bool { + if image.ID != profile.ImageID || image.OS != "linux" || len(image.Config.Volumes) != 0 || len(image.Config.OnBuild) != 0 || len(image.Config.Labels) != 0 { + return false + } + if profile.ReviewedImageMetadata { + // The pinned image ID is the review: its declared ports and environment are accepted, + // but this adapter still publishes nothing and adds only the profile's own environment. + return true + } + if len(image.Config.ExposedPorts) != 0 { + return false + } + // Docker merges image environment into create requests. Reject any inherited + // application variable; this adapter supplies only a fixed non-secret PATH. + for _, env := range image.Config.Env { + if !strings.HasPrefix(env, "PATH=") { + return false + } + } + return true +} + +func safePreparedContainer(container dockerContainer, record containerPreparation, host string) bool { + if !validHexID(container.ID) || (record.ContainerID != "" && container.ID != record.ContainerID) || container.Name != "/"+record.ContainerName || container.Image != record.Profile.ImageID || container.State.Status != "created" || container.State.Running || container.State.Paused || container.State.Restarting || container.State.Dead || container.RestartCount != 0 { + return false + } + if container.State.StartedAt != "" && container.State.StartedAt != "0001-01-01T00:00:00Z" { + return false + } + expected := preparationCreate(record, host) + config, limits := container.Config, container.HostConfig + if config.Image != expected.Image || config.User != expected.User || config.WorkingDir != expected.WorkingDir || !reflect.DeepEqual(config.Entrypoint, expected.Entrypoint) || !equalStrings(config.Cmd, expected.Cmd) || !preparedEnvMatches(config.Env, expected.Env, record.Profile) || !reflect.DeepEqual(config.Labels, expected.Labels) || config.Tty || config.OpenStdin || config.AttachStdin || config.AttachStdout || config.AttachStderr || len(config.Volumes) != 0 || (len(config.ExposedPorts) != 0 && !record.Profile.ReviewedImageMetadata) || !equalStrings(config.Healthcheck.Test, []string{"NONE"}) { + return false + } + if limits.NetworkMode != preparedNetwork(record.Profile) || !limits.ReadonlyRootfs || limits.Privileged || limits.AutoRemove || limits.PublishAllPorts || !equalStrings(limits.CapDrop, []string{"ALL"}) || len(limits.CapAdd) != 0 || !equalStrings(limits.SecurityOpt, []string{"no-new-privileges:true"}) || limits.RestartPolicy.Name != "no" || limits.RestartPolicy.MaximumRetryCount != 0 || limits.IpcMode != "none" || limits.PidMode != "" || limits.UTSMode != "" || limits.UsernsMode != "" || limits.CgroupnsMode != "private" || limits.Memory != preparationMemory || limits.NanoCPUs != preparationNanoCPUs || limits.PidsLimit != preparationPids || limits.LogConfig.Type != "none" { + return false + } + if len(limits.Binds) != 0 || len(limits.Mounts) != 0 || len(limits.Devices) != 0 || len(limits.DeviceRequests) != 0 || len(limits.DeviceCgroupRules) != 0 || len(limits.VolumesFrom) != 0 || len(limits.PortBindings) != 0 || len(limits.Links) != 0 || len(limits.ExtraHosts) != 0 || len(limits.GroupAdd) != 0 || len(limits.Tmpfs) != 0 || len(limits.Sysctls) != 0 || len(container.Mounts) != 0 || len(container.NetworkSettings.Ports) != 0 { + return false + } + for network, endpoint := range container.NetworkSettings.Networks { + if network != preparedNetwork(record.Profile) { + return false + } + if alias := record.Profile.NetworkAlias; alias != "" && !containsString(endpoint.Aliases, alias) { + return false + } + } + return true +} + +func containsString(list []string, want string) bool { + for _, item := range list { + if item == want { + return true + } + } + return false +} + +// validNetworkAlias accepts a conservative DNS label. +func validNetworkAlias(alias string) bool { + if alias == "" || len(alias) > 63 { + return false + } + for i, c := range alias { + ok := c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' && i > 0 && i < len(alias)-1 + if !ok { + return false + } + } + return true +} + +func preparedNetwork(profile PreparationProfile) string { + if profile.Network != "" { + return profile.Network + } + return "none" +} + +// preparedEnvMatches keeps the original exact comparison unless the profile reviewed the image's own +// environment; then every variable this adapter set must be present with its exact value. +func preparedEnvMatches(actual, expected []string, profile PreparationProfile) bool { + if !profile.ReviewedImageMetadata { + return equalStrings(actual, expected) + } + have := map[string]bool{} + for _, entry := range actual { + have[entry] = true + } + for _, entry := range expected { + if !have[entry] { + return false + } + } + return true +} + +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/agent/prepare_consistency_test.go b/agent/prepare_consistency_test.go new file mode 100644 index 0000000..cb02e2b --- /dev/null +++ b/agent/prepare_consistency_test.go @@ -0,0 +1,62 @@ +//go:build linux + +package agent + +import ( + "context" + "encoding/json" + "errors" + "os" + "strings" + "testing" +) + +func TestPreparationStateRejectsReceiptIdentityAndOwnershipTampering(t *testing.T) { + for _, test := range []struct { + name string + mutate func(*diskState, string) + }{ + {"digest", func(d *diskState, key string) { + r := d.Preparations[key] + r.PayloadHash = "sha256:" + strings.Repeat("0", 64) + d.Preparations[key] = r + }}, + {"profile", func(d *diskState, key string) { + r := d.Preparations[key] + r.Profile.Args = []string{"different"} + d.Preparations[key] = r + }}, + {"missing-container-id", func(d *diskState, key string) { r := d.Preparations[key]; r.ContainerID = ""; d.Preparations[key] = r }}, + {"reservation-released", func(d *diskState, key string) { + r := d.Requests[key] + r.State = "released" + d.Requests[key] = r + delete(d.Resources, r.Resource) + }}, + } { + t.Run(test.name, func(t *testing.T) { + _, path, preparer, engine, request := preparedFixture(t) + if result, err := preparer.Prepare(context.Background(), request); err != nil || result.State != PreparationPrepared { + t.Fatal(err) + } + disk, err := load(path) + if err != nil { + t.Fatal(err) + } + test.mutate(&disk, request.Instance+"\x00"+request.RequestKey) + raw, err := json.Marshal(disk) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, raw, 0600); err != nil { + t.Fatal(err) + } + if _, err := Open(path); !errors.Is(err, ErrInvalidState) { + t.Fatalf("corrupt preparation accepted: %v", err) + } + if result, err := preparer.Prepare(context.Background(), request); err == nil || result.State == PreparationPrepared || engine.createCount() != 1 { + t.Fatalf("corrupt preparation reached effects: %#v %v", result, err) + } + }) + } +} diff --git a/agent/prepare_test.go b/agent/prepare_test.go new file mode 100644 index 0000000..2682fd9 --- /dev/null +++ b/agent/prepare_test.go @@ -0,0 +1,384 @@ +//go:build linux + +package agent + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +type preparationFixtureEngine struct { + mu sync.Mutex + image dockerImage + containers map[string]dockerContainer + creates int + createError error + omitCreate bool + onCreate func() + onAbsent func() +} + +func (engine *preparationFixtureEngine) createCount() int { + engine.mu.Lock() + defer engine.mu.Unlock() + return engine.creates +} + +func preparationFixtureProfile() PreparationProfile { + return PreparationProfile{Name: "reviewed-fixture", ImageID: "sha256:" + strings.Repeat("a", 64), Entrypoint: "/bin/true", Args: []string{}} +} + +func newPreparationFixtureEngine() *preparationFixtureEngine { + p := preparationFixtureProfile() + return &preparationFixtureEngine{image: dockerImage{ID: p.ImageID, OS: "linux", Config: dockerConfig{Env: []string{preparationPath}}}, containers: map[string]dockerContainer{}} +} + +func (engine *preparationFixtureEngine) inspectImage(context.Context, string) (dockerImage, error) { + engine.mu.Lock() + defer engine.mu.Unlock() + return engine.image, nil +} +func (engine *preparationFixtureEngine) inspectContainer(_ context.Context, name string) (dockerContainer, bool, error) { + engine.mu.Lock() + value, exists := engine.containers[name] + hook := engine.onAbsent + engine.mu.Unlock() + if !exists && hook != nil { + hook() + } + return value, exists, nil +} +func (engine *preparationFixtureEngine) createContainer(_ context.Context, name string, request dockerCreateRequest) (string, error) { + engine.mu.Lock() + engine.creates++ + id := preparationHash("container:" + name) + if !engine.omitCreate { + container := dockerContainer{ID: id, Name: "/" + name, Image: request.Image, Config: request.dockerConfig, HostConfig: request.HostConfig} + container.State.Status = "created" + container.State.StartedAt = "0001-01-01T00:00:00Z" + engine.containers[name] = container + } + hook, resultErr := engine.onCreate, engine.createError + engine.mu.Unlock() + if hook != nil { + hook() + } + return id, resultErr +} + +func preparedFixture(t *testing.T) (*Store, string, *DockerPreparer, *preparationFixtureEngine, PrepareContainerRequest) { + t.Helper() + store, path := initialized(t) + request := PrepareContainerRequest{Instance: "instance-a", Generation: 1, RequestKey: "original-key", Profile: preparationFixtureProfile().Name} + if err := store.AcceptGeneration(request.Instance, request.Generation); err != nil { + t.Fatal(err) + } + engine := newPreparationFixtureEngine() + preparer, err := newDockerPreparer(store, engine, []PreparationProfile{preparationFixtureProfile()}) + if err != nil { + t.Fatal(err) + } + return store, path, preparer, engine, request +} + +func TestPreparationOriginalKeyAndIndependentInstances(t *testing.T) { + store, path, preparer, engine, request := preparedFixture(t) + first, err := preparer.Prepare(context.Background(), request) + if err != nil || first.State != PreparationPrepared || first.Active || !validHexID(first.ContainerID) || engine.createCount() != 1 { + t.Fatalf("prepare: %#v %v", first, err) + } + host, err := store.HostID() + if err != nil { + t.Fatal(err) + } + if err := store.Release(request.Instance, 1, preparationResource(host, request.Instance)); !errors.Is(err, ErrPreparationRecoveryRequired) { + t.Fatalf("generic release discarded prepared ownership: %v", err) + } + reopened, err := Open(path) + if err != nil { + t.Fatal(err) + } + restarted, err := newDockerPreparer(reopened, engine, []PreparationProfile{preparationFixtureProfile()}) + if err != nil { + t.Fatal(err) + } + for _, query := range []bool{false, true} { + var observed PreparationObservation + if query { + observed, err = restarted.Query(context.Background(), request.Instance, request.Generation, request.RequestKey) + } else { + observed, err = restarted.Prepare(context.Background(), request) + } + if err != nil || observed != first || engine.createCount() != 1 { + t.Fatalf("replay changed receipt/created again: %#v %v", observed, err) + } + } + changed := preparationFixtureProfile() + changed.Args = []string{"changed"} + different, err := newDockerPreparer(reopened, engine, []PreparationProfile{changed}) + if err != nil { + t.Fatal(err) + } + if _, err := different.Prepare(context.Background(), request); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("same key changed payload: %v", err) + } + request.Instance = "instance-b" + if err := store.AcceptGeneration(request.Instance, 1); err != nil { + t.Fatal(err) + } + second, err := preparer.Prepare(context.Background(), request) + if err != nil || second.State != PreparationPrepared || second.Active || second.ContainerID == first.ContainerID || second.ContainerName == first.ContainerName || engine.createCount() != 2 { + t.Fatalf("instance identity collapsed: %#v %v", second, err) + } +} + +func TestPreparationUnknownNeverBlindlyCreatesAgain(t *testing.T) { + store, path, preparer, engine, request := preparedFixture(t) + engine.createError, engine.omitCreate = errors.New("lost response"), true + first, err := preparer.Prepare(context.Background(), request) + if err != nil || first.State != PreparationUnknown || first.Active || first.ErrorCode != "CONTAINER_NOT_OBSERVED_AFTER_INTENT" || engine.createCount() != 1 { + t.Fatalf("unknown create: %#v %v", first, err) + } + reopened, err := Open(path) + if err != nil { + t.Fatal(err) + } + restarted, err := newDockerPreparer(reopened, engine, []PreparationProfile{preparationFixtureProfile()}) + if err != nil { + t.Fatal(err) + } + engine.createError, engine.omitCreate = nil, false + for i := 0; i < 3; i++ { + observed, err := restarted.Prepare(context.Background(), request) + if err != nil || observed.State != PreparationUnknown || engine.createCount() != 1 { + t.Fatalf("unknown original intent retried create: %#v creates=%d %v", observed, engine.createCount(), err) + } + } + changedKey := request + changedKey.RequestKey = "another-key-for-same-instance" + if _, err := restarted.Prepare(context.Background(), changedKey); !errors.Is(err, ErrResourceConflict) || engine.createCount() != 1 { + t.Fatalf("new key bypassed unresolved instance ownership: %v", err) + } + if err := store.AcceptGeneration(request.Instance, 2); !errors.Is(err, ErrPreparationRecoveryRequired) { + t.Fatalf("generation advanced while dispatched create outcome remained unknown: %v", err) + } + _, generations, _, err := store.Snapshot() + if err != nil || generations[request.Instance] != 1 { + t.Fatalf("refused generation was persisted: %#v %v", generations, err) + } + if missing, err := restarted.Query(context.Background(), request.Instance, 1, "never-submitted"); err != nil || missing.State != PreparationNotObserved || missing.Active { + t.Fatalf("original-key absence: %#v %v", missing, err) + } +} + +func TestPreparationLostReplyUsesInspectAndUnownedContainerIsNotAdopted(t *testing.T) { + _, _, preparer, engine, request := preparedFixture(t) + engine.createError = errors.New("created but reply lost") + first, err := preparer.Prepare(context.Background(), request) + if err != nil || first.State != PreparationPrepared || engine.createCount() != 1 { + t.Fatalf("inspect did not recover actual original container: %#v %v", first, err) + } + store, path := initialized(t) + if err := store.AcceptGeneration(request.Instance, 1); err != nil { + t.Fatal(err) + } + other, err := newDockerPreparer(store, engine, []PreparationProfile{preparationFixtureProfile()}) + if err != nil { + t.Fatal(err) + } + // The fixture has the same reviewed host ID but a distinct empty ledger. + // Even an exactly labelled prior container is not adopted after lost state. + if _, err := other.Prepare(context.Background(), request); !errors.Is(err, ErrResourceConflict) || engine.createCount() != 1 { + t.Fatalf("container adopted without durable original intent: %v", err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if _, err := other.Prepare(context.Background(), request); err == nil || engine.createCount() != 1 { + t.Fatal("missing state recreated or adopted workload") + } +} + +func TestPreparationGenerationLockAndGenericReleaseRemainClosed(t *testing.T) { + store, path, preparer, engine, request := preparedFixture(t) + entered, release := make(chan struct{}), make(chan struct{}) + engine.onCreate = func() { close(entered); <-release } + prepared := make(chan error, 1) + go func() { _, err := preparer.Prepare(context.Background(), request); prepared <- err }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("create was not reached") + } + newGeneration := make(chan error, 1) + go func() { newGeneration <- store.AcceptGeneration(request.Instance, 2) }() + select { + case err := <-newGeneration: + t.Fatalf("generation overtook in-flight create: %v", err) + case <-time.After(100 * time.Millisecond): + } + close(release) + if err := <-prepared; err != nil { + t.Fatal(err) + } + if err := <-newGeneration; err != nil { + t.Fatal(err) + } + if _, err := preparer.Prepare(context.Background(), request); !errors.Is(err, ErrGenerationStale) || engine.createCount() != 1 { + t.Fatalf("old generation created: %v", err) + } + if _, err := preparer.Query(context.Background(), request.Instance, 1, request.RequestKey); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("old generation confirmed current preparation: %v", err) + } + disk, err := load(path) + if err != nil { + t.Fatal(err) + } + record := disk.Preparations[request.Instance+"\x00"+request.RequestKey] + resource := preparationResource(disk.HostID, record.Instance) + if err := store.ReconcileRelease(request.Instance, 2, resource, func(Reservation) error { return nil }); !errors.Is(err, ErrPreparationRecoveryRequired) { + t.Fatalf("generic proof forgot actual container: %v", err) + } + if !disk.ReconciliationRequired[resource] { + t.Fatal("new generation lost old container reconciliation marker") + } + newer := request + newer.Generation, newer.RequestKey = 2, "new-generation-key" + if _, err := preparer.Prepare(context.Background(), newer); !errors.Is(err, ErrResourceConflict) || engine.createCount() != 1 { + t.Fatalf("new generation stole existing instance resource: %v", err) + } +} + +func TestPreparationInspectRejectsChangedExecutionOrOwnership(t *testing.T) { + for _, test := range []struct { + name string + mutate func(*dockerContainer) + }{ + {"running", func(c *dockerContainer) { c.State.Status = "running"; c.State.Running = true }}, + {"previously-started", func(c *dockerContainer) { c.State.StartedAt = "2026-11-02T00:00:00Z" }}, + {"different-id", func(c *dockerContainer) { c.ID = strings.Repeat("b", 64) }}, + {"different-image", func(c *dockerContainer) { c.Image = "sha256:" + strings.Repeat("b", 64) }}, + {"different-owner", func(c *dockerContainer) { c.Config.Labels["io.thingspanel.agent.instance"] = "other" }}, + {"network", func(c *dockerContainer) { c.HostConfig.NetworkMode = "bridge" }}, + {"mount", func(c *dockerContainer) { c.Mounts = []json.RawMessage{json.RawMessage(`{"Source":"/secret"}`)} }}, + {"device", func(c *dockerContainer) { + c.HostConfig.Devices = []json.RawMessage{json.RawMessage(`{"PathOnHost":"/dev/test"}`)} + }}, + {"secret-env", func(c *dockerContainer) { c.Config.Env = append(c.Config.Env, "TOKEN=forbidden") }}, + {"privileged", func(c *dockerContainer) { c.HostConfig.Privileged = true }}, + } { + t.Run(test.name, func(t *testing.T) { + _, _, preparer, engine, request := preparedFixture(t) + original, err := preparer.Prepare(context.Background(), request) + if err != nil || original.State != PreparationPrepared { + t.Fatal(err) + } + container := engine.containers[original.ContainerName] + test.mutate(&container) + engine.containers[original.ContainerName] = container + observation, err := preparer.Query(context.Background(), request.Instance, 1, request.RequestKey) + if err != nil || observation.State != PreparationUnknown || observation.Active || observation.ErrorCode != "CONTAINER_REQUIRES_OWNER_REVIEW" || engine.createCount() != 1 { + t.Fatalf("untrusted container became prepared: %#v %v", observation, err) + } + }) + } +} + +func TestPreparationRejectsImageInheritedResourcesAndUnacceptedGeneration(t *testing.T) { + for _, test := range []struct { + name string + mutate func(*dockerImage) + }{ + {"image-id", func(i *dockerImage) { i.ID = "sha256:" + strings.Repeat("b", 64) }}, + {"anonymous-volume", func(i *dockerImage) { i.Config.Volumes = map[string]json.RawMessage{"/data": json.RawMessage(`{}`)} }}, + {"exposed-port", func(i *dockerImage) { + i.Config.ExposedPorts = map[string]json.RawMessage{"1883/tcp": json.RawMessage(`{}`)} + }}, + {"inherited-env", func(i *dockerImage) { i.Config.Env = []string{"TOKEN=not-permitted"} }}, + {"inherited-label", func(i *dockerImage) { + i.Config.Labels = map[string]string{"application": "not-approved-by-this-profile"} + }}, + } { + t.Run(test.name, func(t *testing.T) { + _, _, preparer, engine, request := preparedFixture(t) + test.mutate(&engine.image) + if _, err := preparer.Prepare(context.Background(), request); !errors.Is(err, ErrPreparationPolicy) || engine.createCount() != 0 { + t.Fatalf("unsafe image created: %v", err) + } + }) + } + _, _, preparer, engine, request := preparedFixture(t) + request.Generation = 2 + if _, err := preparer.Prepare(context.Background(), request); !errors.Is(err, ErrGenerationNotAccepted) || engine.createCount() != 0 { + t.Fatalf("unaccepted generation created: %v", err) + } +} + +func TestPreparationReceiptFilesystemFailureDoesNotReturnPrepared(t *testing.T) { + _, path, preparer, engine, request := preparedFixture(t) + backup := path + ".intent-preserved" + engine.onCreate = func() { + if err := os.Rename(path, backup); err != nil { + t.Error(err) + return + } + if err := os.Mkdir(path, 0700); err != nil { + t.Error(err) + return + } + if err := os.WriteFile(filepath.Join(path, "refuse-replace"), []byte("fixture"), 0600); err != nil { + t.Error(err) + } + } + result, err := preparer.Prepare(context.Background(), request) + if err == nil || result.State == PreparationPrepared || result.Active || engine.createCount() != 1 { + t.Fatalf("receipt write failure returned completed preparation: %#v %v", result, err) + } + if err := os.Remove(filepath.Join(path, "refuse-replace")); err != nil { + t.Fatal(err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Rename(backup, path); err != nil { + t.Fatal(err) + } + result, err = preparer.Query(context.Background(), request.Instance, 1, request.RequestKey) + if err != nil || result.State != PreparationPrepared || engine.createCount() != 1 { + t.Fatalf("original intent did not recover existing container: %#v %v", result, err) + } +} + +func TestPreparationIntentFilesystemFailurePreventsCreate(t *testing.T) { + _, path, preparer, engine, request := preparedFixture(t) + backup := path + ".before-intent" + engine.onAbsent = func() { + if err := os.Rename(path, backup); err != nil { + t.Error(err) + return + } + if err := os.Mkdir(path, 0700); err != nil { + t.Error(err) + } + } + result, err := preparer.Prepare(context.Background(), request) + if err == nil || result.State == PreparationPrepared || engine.createCount() != 0 { + t.Fatalf("uncommitted intent reached Docker create: %#v creates=%d %v", result, engine.createCount(), err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Rename(backup, path); err != nil { + t.Fatal(err) + } + if _, exists, err := preparer.store.Query(request.Instance, request.RequestKey); err != nil || exists { + t.Fatalf("failed intent changed reservation: exists=%v %v", exists, err) + } +} diff --git a/agent/renew_test.go b/agent/renew_test.go new file mode 100644 index 0000000..8b77af0 --- /dev/null +++ b/agent/renew_test.go @@ -0,0 +1,51 @@ +//go:build linux + +package agent + +import ( + "testing" + "time" +) + +func TestRenewOnlyExtendsARunningAcceptedGeneration(t *testing.T) { + store, _ := initialized(t) + if err := store.AcceptGeneration("i", 1); err != nil { + t.Fatal(err) + } + a := newActivator(store, nil, nil) + now := time.Unix(1_000_000, 0) + a.now = func() time.Time { return now } + save := func(r *ActivationRecord) { + d, _ := a.loadLocked() + d.Instances["i"] = r + if err := a.saveLocked(d); err != nil { + t.Fatal(err) + } + } + if _, err := a.Renew("i", 1, "k", "g", time.Hour); err != ErrNotGranted { + t.Fatalf("unknown instance: %v", err) + } + save(&ActivationRecord{Instance: "i", Generation: 1, RequestKey: "k", Started: false}) + if _, err := a.Renew("i", 1, "k", "g", time.Hour); err != ErrNotGranted { + t.Fatalf("never started: %v", err) + } + save(&ActivationRecord{Instance: "i", Generation: 1, RequestKey: "k", GrantID: "original-grant", Started: true, LeaseExpires: now.Unix() + 10}) + if _, err := a.Renew("i", 1, "other", "g", time.Hour); err != ErrNotGranted { + t.Fatalf("other key: %v", err) + } + got, err := a.Renew("i", 1, "k", "g2", time.Hour) + if err != nil || got.LeaseExpires != now.Add(time.Hour).Unix() || got.GrantID != "original-grant" || !got.Started { + t.Fatalf("%v %+v", err, got) + } + save(&ActivationRecord{Instance: "i", Generation: 1, RequestKey: "k", Started: true, LeaseExpires: now.Unix()}) + if _, err := a.Renew("i", 1, "k", "g3", time.Hour); err != ErrLeaseExpired { + t.Fatalf("expired lease must not be renewed: %v", err) + } + save(&ActivationRecord{Instance: "i", Generation: 1, RequestKey: "k", Started: true, Revoked: true}) + if _, err := a.Renew("i", 1, "k", "g4", time.Hour); err != ErrRevoked { + t.Fatalf("revoked: %v", err) + } + if _, err := a.Renew("i", 2, "k", "g4", time.Hour); err == nil { + t.Fatal("an unaccepted generation must be refused") + } +} diff --git a/agent/secrets.go b/agent/secrets.go new file mode 100644 index 0000000..b4ce5aa --- /dev/null +++ b/agent/secrets.go @@ -0,0 +1,196 @@ +//go:build linux + +package agent + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" +) + +// SecretStore keeps values the control plane must never persist elsewhere: site secrets typed in the UI, the +// per-generation runtime identity token, generated plugin keys and the stack's MQTT credentials. It is one file +// (mode 0600, written atomically) owned by the Agent. Profiles and the state journal only ever hold the placeholder +// "@secret:", so no secret reaches profiles.json, state.json, a label or a log line. +type SecretStore struct { + path string + mu sync.Mutex +} + +const secretPrefix = "@secret:" + +var secretKey = regexp.MustCompile(`^[A-Za-z0-9_./-]{1,128}$`) + +func OpenSecretStore(path string) (*SecretStore, error) { + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return nil, err + } + s := &SecretStore{path: path} + if _, err := os.Stat(path); os.IsNotExist(err) { + return s, s.write(map[string]map[string]string{}) + } + if _, err := s.read(); err != nil { + return nil, err + } + return s, nil +} + +func (s *SecretStore) read() (map[string]map[string]string, error) { + info, err := os.Lstat(s.path) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { + return nil, ErrPreparationPolicy + } + raw, err := os.ReadFile(s.path) + if err != nil { + return nil, err + } + out := map[string]map[string]string{} + if len(raw) > 0 { + if err := json.Unmarshal(raw, &out); err != nil { + return nil, err + } + } + return out, nil +} + +func (s *SecretStore) write(data map[string]map[string]string) error { + raw, _ := json.Marshal(data) + tmp, err := os.CreateTemp(filepath.Dir(s.path), ".secrets-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if err := tmp.Chmod(0600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(raw); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), s.path) +} + +func (s *SecretStore) Put(ns, key, value string) error { + if !valid(ns) || len(ns) > 256 || !secretKey.MatchString(key) || len(value) == 0 || len(value) > 8192 || strings.ContainsAny(value, "\x00\r\n") { + return ErrPreparationPolicy + } + s.mu.Lock() + defer s.mu.Unlock() + data, err := s.read() + if err != nil { + return err + } + if data[ns] == nil { + data[ns] = map[string]string{} + } + data[ns][key] = value + return s.write(data) +} + +func (s *SecretStore) Get(ns, key string) (string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + data, err := s.read() + if err != nil { + return "", false + } + v, ok := data[ns][key] + return v, ok +} + +// Keys lists the key names (never values) under a prefix, prefix stripped. +func (s *SecretStore) Keys(ns, prefix string) []string { + s.mu.Lock() + defer s.mu.Unlock() + data, err := s.read() + out := []string{} + if err != nil { + return out + } + for k := range data[ns] { + if strings.HasPrefix(k, prefix) { + out = append(out, strings.TrimPrefix(k, prefix)) + } + } + sort.Strings(out) + return out +} + +func (s *SecretStore) DeleteKey(ns, key string) error { + s.mu.Lock() + defer s.mu.Unlock() + data, err := s.read() + if err != nil { + return err + } + delete(data[ns], key) + return s.write(data) +} + +func (s *SecretStore) DeletePrefix(ns, prefix string) error { + s.mu.Lock() + defer s.mu.Unlock() + data, err := s.read() + if err != nil { + return err + } + for k := range data[ns] { + if strings.HasPrefix(k, prefix) { + delete(data[ns], k) + } + } + return s.write(data) +} + +// GetOrCreateHex returns the stored value or stores size random bytes (hex) once. +func (s *SecretStore) GetOrCreateHex(ns, key string, size int) (string, error) { + if v, ok := s.Get(ns, key); ok { + return v, nil + } + raw := make([]byte, size) + if _, err := rand.Read(raw); err != nil { + return "", err + } + v := hex.EncodeToString(raw) + return v, s.Put(ns, key, v) +} + +// ResolveEnv replaces KEY=@secret:name by KEY=value. A missing secret fails closed. +func (s *SecretStore) ResolveEnv(instance string, env []string) ([]string, error) { + out := make([]string, 0, len(env)) + for _, entry := range env { + key, value, _ := strings.Cut(entry, "=") + if strings.HasPrefix(value, secretPrefix) { + secret, ok := s.Get(instance, strings.TrimPrefix(value, secretPrefix)) + if !ok { + return nil, ErrPreparationPolicy + } + entry = key + "=" + secret + } + out = append(out, entry) + } + return out, nil +} + +func hasPlaceholder(env []string) bool { + for _, entry := range env { + if _, value, _ := strings.Cut(entry, "="); strings.HasPrefix(value, secretPrefix) { + return true + } + } + return false +} diff --git a/agent/service.go b/agent/service.go new file mode 100644 index 0000000..c4a10f9 --- /dev/null +++ b/agent/service.go @@ -0,0 +1,307 @@ +//go:build linux + +package agent + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +// Service is the Agent's control API. It is served only over a private Unix socket and every +// request needs the bearer token that the operator provisioned out of band. The caller supplies the +// instance identity and generation; the Agent never invents either, and never lets a generation that +// is not the accepted one change a container. +type Service struct { + store *Store + preparer *DockerPreparer + activator *Activator + token []byte + catalog *CatalogSource + builder ProfileBuilder +} + +// EnableCatalog turns on the catalog-driven install path: the Agent verifies the signed catalog itself, builds the +// container profile from the verified entry, and keeps all secrets in its own store. The caller (control plane) can +// only name a catalog id, hand over site values and a one-shot identity token. +func (s *Service) EnableCatalog(catalog *CatalogSource, builder ProfileBuilder) { + s.catalog, s.builder = catalog, builder + s.preparer.SetSecrets(builder.Secrets) +} + +func NewService(store *Store, preparer *DockerPreparer, activator *Activator, token string) (*Service, error) { + if store == nil || preparer == nil || activator == nil || len(token) < 32 { + return nil, ErrPreparationPolicy + } + return &Service{store: store, preparer: preparer, activator: activator, token: []byte(token)}, nil +} + +type apiRequest struct { + Instance string `json:"instance"` + Generation uint64 `json:"generation"` + RequestKey string `json:"request_key"` + Profile string `json:"profile"` + GrantID string `json:"grant_id"` + TTLSeconds int64 `json:"ttl_seconds"` + Reason string `json:"reason"` + + // Catalog install path only. + Key string `json:"key"` + Value string `json:"value"` + Values map[string]string `json:"values"` + IdentityToken string `json:"identity_token"` + ServiceIdentifier string `json:"service_identifier"` +} + +type apiResponse struct { + OK bool `json:"ok"` + Error string `json:"error,omitempty"` + Preparation *PreparationObservation `json:"preparation,omitempty"` + Activation *ActivationRecord `json:"activation,omitempty"` + Stopped []string `json:"stopped,omitempty"` + Catalog []PublicEntry `json:"catalog,omitempty"` + Keys []string `json:"keys,omitempty"` +} + +func (s *Service) Handler() http.Handler { + mux := http.NewServeMux() + routes := map[string]func(context.Context, apiRequest) (apiResponse, error){ + "/v1/accept-generation": s.acceptGeneration, + "/v1/prepare": s.prepare, + "/v1/grant": s.grant, + "/v1/activate": s.activate, + "/v1/renew": s.renew, + "/v1/revoke": s.revoke, + "/v1/retire": s.retire, + "/v1/status": s.status, + "/v1/sweep": s.sweep, + "/v1/catalog": s.listCatalog, + "/v1/config-put": s.configPut, + "/v1/config-keys": s.configKeys, + "/v1/config-clear": s.configClear, + } + for path, handle := range routes { + handle := handle + mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(r) { + write(w, http.StatusUnauthorized, apiResponse{Error: "unauthorized"}) + return + } + if r.Method != http.MethodPost { + write(w, http.StatusMethodNotAllowed, apiResponse{Error: "POST required"}) + return + } + var request apiRequest + decoder := json.NewDecoder(io.LimitReader(r.Body, 64*1024)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&request); err != nil { + write(w, http.StatusBadRequest, apiResponse{Error: "invalid request"}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) + defer cancel() + response, err := handle(ctx, request) + if err != nil { + write(w, statusFor(err), apiResponse{Error: err.Error(), Preparation: response.Preparation, Activation: response.Activation}) + return + } + response.OK = true + write(w, http.StatusOK, response) + }) + } + return mux +} + +func (s *Service) authorized(r *http.Request) bool { + header := r.Header.Get("Authorization") + const prefix = "Bearer " + if !strings.HasPrefix(header, prefix) { + return false + } + return subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(header, prefix)), s.token) == 1 +} + +func write(w http.ResponseWriter, status int, body apiResponse) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} + +func statusFor(err error) int { + switch { + case errors.Is(err, ErrGenerationStale), errors.Is(err, ErrGenerationNotAccepted), errors.Is(err, ErrRevoked), + errors.Is(err, ErrLeaseExpired), errors.Is(err, ErrNotGranted), errors.Is(err, ErrNotPrepared), + errors.Is(err, ErrResourceConflict), errors.Is(err, ErrActivationUnresolved), errors.Is(err, ErrPreparationRecoveryRequired): + return http.StatusConflict + case errors.Is(err, ErrPreparationPolicy), errors.Is(err, ErrCatalog): + return http.StatusBadRequest + } + return http.StatusInternalServerError +} + +func (s *Service) acceptGeneration(_ context.Context, r apiRequest) (apiResponse, error) { + return apiResponse{}, s.store.AcceptGeneration(r.Instance, r.Generation) +} + +// prepare and status answer from the activation ledger first for a started generation: asking the +// create-only adapter about a container that has run would rewrite its receipt as unknown. +func (s *Service) prepare(ctx context.Context, r apiRequest) (apiResponse, error) { + if s.activator.HasStarted(r.Instance, r.Generation) { + record, err := s.activator.Status(r.Instance) + return apiResponse{Activation: &record}, err + } + if r.IdentityToken != "" { + if s.catalog == nil { + return apiResponse{}, ErrPreparationPolicy + } + entry, err := s.catalog.Entry(r.Profile) + if err != nil { + return apiResponse{}, ErrPreparationPolicy + } + profile, err := s.builder.Build(entry, r.Instance, r.Generation, r.Values, r.IdentityToken) + if err != nil { + return apiResponse{}, err + } + if err := s.preparer.SetProfile(profile); err != nil { + return apiResponse{}, err + } + r.Profile = profile.Name + } + observation, err := s.preparer.Prepare(ctx, PrepareContainerRequest{Instance: r.Instance, Generation: r.Generation, RequestKey: r.RequestKey, Profile: r.Profile}) + return apiResponse{Preparation: &observation}, err +} + +func (s *Service) grant(ctx context.Context, r apiRequest) (apiResponse, error) { + record, err := s.activator.Grant(ctx, r.Instance, r.Generation, r.RequestKey, r.GrantID, time.Duration(r.TTLSeconds)*time.Second) + return apiResponse{Activation: &record}, err +} + +func (s *Service) renew(_ context.Context, r apiRequest) (apiResponse, error) { + record, err := s.activator.Renew(r.Instance, r.Generation, r.RequestKey, r.GrantID, time.Duration(r.TTLSeconds)*time.Second) + return apiResponse{Activation: &record}, err +} + +func (s *Service) activate(ctx context.Context, r apiRequest) (apiResponse, error) { + record, err := s.activator.Activate(ctx, r.Instance, r.Generation, r.RequestKey) + return apiResponse{Activation: &record}, err +} + +func (s *Service) revoke(ctx context.Context, r apiRequest) (apiResponse, error) { + record, err := s.activator.Revoke(ctx, r.Instance, r.Generation, r.Reason) + return apiResponse{Activation: &record}, err +} + +func (s *Service) retire(ctx context.Context, r apiRequest) (apiResponse, error) { + err := s.activator.Retire(ctx, r.Instance, r.Generation) + if err == nil && s.builder.Secrets != nil { + _ = s.builder.Secrets.DeleteKey(r.Instance, fmt.Sprintf("identity/%d", r.Generation)) // the old generation's token is no longer needed + } + return apiResponse{}, err +} + +func (s *Service) listCatalog(_ context.Context, _ apiRequest) (apiResponse, error) { + if s.catalog == nil { + return apiResponse{}, ErrPreparationPolicy + } + entries, err := s.catalog.Entries() + if err != nil { + return apiResponse{}, ErrCatalog + } + out := make([]PublicEntry, 0, len(entries)) + for _, e := range entries { + out = append(out, e.Public()) + } + return apiResponse{Catalog: out}, nil +} + +// declaredSecret checks that the instance is a catalog plugin and the key is one of its declared secret fields: +// nothing else can be written into the secret store through the API. +func (s *Service) declaredSecret(instance, key string) error { + if s.catalog == nil || s.builder.Secrets == nil { + return ErrPreparationPolicy + } + entry, err := s.catalog.Entry(instance) + if err != nil { + return ErrPreparationPolicy + } + if spec, ok := entry.EnvUser[key]; !ok || !spec.Secret { + return ErrPreparationPolicy + } + return nil +} + +func (s *Service) configPut(_ context.Context, r apiRequest) (apiResponse, error) { + if err := s.declaredSecret(r.Instance, r.Key); err != nil { + return apiResponse{}, err + } + if err := checkSecretValue(r.Value); err != nil { + return apiResponse{}, err + } + return apiResponse{}, s.builder.Secrets.Put(r.Instance, "config/"+r.Key, r.Value) +} + +func checkSecretValue(v string) error { + if v == "" || len(v) > 8192 || strings.ContainsAny(v, "\r\n\x00") { + return ErrPreparationPolicy + } + return nil +} + +func (s *Service) configKeys(_ context.Context, r apiRequest) (apiResponse, error) { + if s.catalog == nil || s.builder.Secrets == nil || !valid(r.Instance) { + return apiResponse{}, ErrPreparationPolicy + } + return apiResponse{Keys: s.builder.Secrets.Keys(r.Instance, "config/")}, nil +} + +// configClear removes the site secrets and every identity token of the instance (uninstall). Generated keys and the +// stack credentials stay: a reinstall must keep the same generated template secret. +func (s *Service) configClear(_ context.Context, r apiRequest) (apiResponse, error) { + if s.catalog == nil || s.builder.Secrets == nil || !valid(r.Instance) { + return apiResponse{}, ErrPreparationPolicy + } + if err := s.builder.Secrets.DeletePrefix(r.Instance, "config/"); err != nil { + return apiResponse{}, err + } + return apiResponse{}, s.builder.Secrets.DeletePrefix(r.Instance, "identity/") +} + +func (s *Service) status(ctx context.Context, r apiRequest) (apiResponse, error) { + record, err := s.activator.Status(r.Instance) + response := apiResponse{Activation: &record} + if err == nil && record.Generation == 0 && r.Generation != 0 && valid(r.RequestKey) { + var observation PreparationObservation + observation, err = s.preparer.Query(ctx, r.Instance, r.Generation, r.RequestKey) + response.Preparation = &observation + } + return response, err +} + +func (s *Service) sweep(ctx context.Context, _ apiRequest) (apiResponse, error) { + stopped, err := s.activator.Sweep(ctx) + return apiResponse{Stopped: stopped}, err +} + +// RunSweeper stops expired or superseded instances on a fixed cadence until ctx ends. +func (s *Service) RunSweeper(ctx context.Context, every time.Duration, report func(error)) { + ticker := time.NewTicker(every) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + sweepCtx, cancel := context.WithTimeout(ctx, 60*time.Second) + if _, err := s.activator.Sweep(sweepCtx); err != nil && report != nil { + report(err) + } + cancel() + } + } +} diff --git a/agent/state.go b/agent/state.go new file mode 100644 index 0000000..9ae735e --- /dev/null +++ b/agent/state.go @@ -0,0 +1,475 @@ +//go:build linux + +// Package agent implements local host state and a create-only Docker adapter. +// It never starts workloads and has no public control or activation API. +package agent + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "syscall" +) + +var ( + ErrAlreadyInitialized = errors.New("state already exists; refusing reinitialization") + ErrStateMissing = errors.New("state missing; explicit host identity review required") + ErrInvalidState = errors.New("state missing, corrupt, or inconsistent; refusing automatic recovery") + ErrGenerationStale = errors.New("execution generation is lower than persisted maximum") + ErrGenerationNotAccepted = errors.New("execution generation has not been explicitly accepted") + ErrResourceConflict = errors.New("resource is reserved by another owner or generation") + ErrNotOwner = errors.New("release owner or generation does not match reservation") +) + +type Reservation struct { + Resource string `json:"resource"` + Instance string `json:"instance"` + Generation uint64 `json:"generation"` + RequestKey string `json:"request_key"` + PayloadHash string `json:"payload_hash"` + State string `json:"state"` // held | released; request identities are never reusable +} + +type Request struct { + Instance string + Generation uint64 + RequestKey string + Resource string + PayloadHash string +} + +type diskState struct { + SchemaVersion int `json:"schema_version"` + HostID string `json:"host_id"` + MaxGeneration map[string]uint64 `json:"max_generation"` + Requests map[string]Reservation `json:"requests"` + Resources map[string]Reservation `json:"resources"` + ReconciliationRequired map[string]bool `json:"reconciliation_required"` + Preparations map[string]containerPreparation `json:"preparations,omitempty"` +} + +type Store struct{ path string } + +// Initialize creates a new host identity and empty state exactly once. The +// caller must supply a reviewed identity; this function never generates one. +// If the state file or its directory is later missing, Open fails closed; only a +// separate reviewed registration process may decide whether to reinitialize. +func Initialize(path, hostID string) error { + if !valid(hostID) { + return fmt.Errorf("invalid host identity") + } + return withLock(path, func() error { + if _, err := os.Lstat(path); err == nil { + return ErrAlreadyInitialized + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + return writeState(path, diskState{SchemaVersion: 1, HostID: hostID, MaxGeneration: map[string]uint64{}, Requests: map[string]Reservation{}, Resources: map[string]Reservation{}, ReconciliationRequired: map[string]bool{}}) + }) +} + +// Open refuses absent or malformed state; it never silently initializes. +func Open(path string) (*Store, error) { + err := withLock(path, func() error { _, e := load(path); return e }) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, ErrStateMissing + } + if errors.Is(err, ErrInvalidState) { + return nil, err + } + return nil, fmt.Errorf("%w: %v", ErrInvalidState, err) + } + return &Store{path: path}, nil +} + +// AcceptGeneration persists task acceptance before any resource reservation. +// A higher accepted generation fences stale state operations even if subsequent +// reservation fails. This is NOT a side-effect execution fence; future executors +// must re-check under an instance lock immediately before each external effect. +func (s *Store) AcceptGeneration(instance string, generation uint64) error { + if !valid(instance) || generation == 0 { + return errors.New("invalid generation acceptance") + } + return withLock(s.path, func() error { + d, err := load(s.path) + if err != nil { + return err + } + current := d.MaxGeneration[instance] + if generation < current { + return ErrGenerationStale + } + if generation > current { + // A timed-out Docker create can still complete after its client + // releases the local lock. Do not accept a new generation while an + // original preparation result is unresolved; local epoch changes + // cannot cancel an already-dispatched daemon request. + for _, preparation := range d.Preparations { + if preparation.Instance == instance && preparation.State != PreparationPrepared { + return ErrPreparationRecoveryRequired + } + } + d.MaxGeneration[instance] = generation + for resource, held := range d.Resources { + if held.Instance == instance && held.Generation < generation { + d.ReconciliationRequired[resource] = true + } + } + return writeState(s.path, d) + } + return nil + }) +} + +func (s *Store) HostID() (string, error) { + var out string + err := withLock(s.path, func() error { + d, e := load(s.path) + if e == nil { + out = d.HostID + } + return e + }) + return out, err +} + +// Reserve persists the maximum generation and exclusive resource ownership. +// A repeated identical request is idempotent; changing its contents conflicts. +// This watermark alone is bookkeeping, not an execution fence. Effect adapters +// must re-check generation while holding the same local state lock. The bounded +// DockerPreparer does that for its create-only operation; Reserve has no effects. +func (s *Store) Reserve(r Request) (Reservation, error) { + var result Reservation + if !valid(r.Instance) || !valid(r.Resource) || !valid(r.RequestKey) || !valid(r.PayloadHash) || r.Generation == 0 { + return result, errors.New("invalid reservation request") + } + err := withLock(s.path, func() error { + d, e := load(s.path) + if e != nil { + return e + } + reqID := r.Instance + "\x00" + r.RequestKey + if r.Generation < d.MaxGeneration[r.Instance] { + return ErrGenerationStale + } + if r.Generation > d.MaxGeneration[r.Instance] { + return ErrGenerationNotAccepted + } + candidate := Reservation{Resource: r.Resource, Instance: r.Instance, Generation: r.Generation, RequestKey: r.RequestKey, PayloadHash: r.PayloadHash, State: "held"} + if old, ok := d.Requests[reqID]; ok { + if old.Resource != candidate.Resource || old.Instance != candidate.Instance || old.Generation != candidate.Generation || old.RequestKey != candidate.RequestKey || old.PayloadHash != candidate.PayloadHash { + return ErrResourceConflict + } + result = old + return nil + } + if _, ok := d.Resources[r.Resource]; ok { + return ErrResourceConflict + } + d.Requests[reqID] = candidate + d.Resources[r.Resource] = candidate + result = candidate + return writeState(s.path, d) + }) + return result, err +} + +// Resource ownership is strict: a newer generation or different instance cannot +// take over a held resource. Release requires the exact owner and generation. It does not lower +// the persisted generation watermark, so stale requests remain rejected. +func (s *Store) Release(instance string, generation uint64, resource string) error { + if !valid(instance) || !valid(resource) || generation == 0 { + return errors.New("invalid release request") + } + return withLock(s.path, func() error { + d, e := load(s.path) + if e != nil { + return e + } + h, ok := d.Resources[resource] + if !ok || h.Instance != instance || h.Generation != generation || d.MaxGeneration[instance] != generation { + return ErrNotOwner + } + if _, prepared := d.Preparations[instance+"\x00"+h.RequestKey]; prepared { + return ErrPreparationRecoveryRequired + } + delete(d.Resources, resource) + h.State = "released" + d.Requests[instance+"\x00"+h.RequestKey] = h + return writeState(s.path, d) + }) +} + +// ReconcileRelease is a two-phase reconciliation. The injected verifier must +// have a trusted identity and independently verify external reality; neither +// its identity nor a fence against external writers is provided here. It runs +// outside the state lock. Re-checking the local snapshot prevents stale local +// decisions, but does not fence external side effects. Without a real trusted +// verifier and executor-side fencing, this candidate must not be deployed. +func (s *Store) ReconcileRelease(instance string, currentGeneration uint64, resource string, verify func(Reservation) error) error { + if !valid(instance) || !valid(resource) || currentGeneration == 0 || verify == nil { + return errors.New("current generation and trusted verifier are required") + } + var host string + var snapshot Reservation + err := withLock(s.path, func() error { + d, e := load(s.path) + if e != nil { + return e + } + if d.MaxGeneration[instance] != currentGeneration { + return ErrGenerationStale + } + held, ok := d.Resources[resource] + if !ok || held.Instance != instance || held.Generation >= currentGeneration || !d.ReconciliationRequired[resource] { + return ErrNotOwner + } + if _, prepared := d.Preparations[instance+"\x00"+held.RequestKey]; prepared { + return ErrPreparationRecoveryRequired + } + host = d.HostID + snapshot = held + return nil + }) + if err != nil { + return err + } + // No file lock is held while calling external/trusted verification code. + if err = verify(snapshot); err != nil { + return fmt.Errorf("reconciliation verification failed: %w", err) + } + return withLock(s.path, func() error { + d, e := load(s.path) + if e != nil { + return e + } + if d.HostID != host { + return ErrInvalidState + } + if d.MaxGeneration[instance] != currentGeneration { + return ErrGenerationStale + } + held, ok := d.Resources[resource] + if !ok || held != snapshot || !d.ReconciliationRequired[resource] { + return ErrNotOwner + } + delete(d.Resources, resource) + delete(d.ReconciliationRequired, resource) + held.State = "released" + d.Requests[instance+"\x00"+held.RequestKey] = held + return writeState(s.path, d) + }) +} + +func (s *Store) Query(instance, requestKey string) (Reservation, bool, error) { + var r Reservation + var ok bool + err := withLock(s.path, func() error { + d, e := load(s.path) + if e != nil { + return e + } + r, ok = d.Requests[instance+"\x00"+requestKey] + return nil + }) + return r, ok, err +} + +func valid(s string) bool { + return s != "" && strings.TrimSpace(s) == s && !strings.ContainsRune(s, '\x00') +} +func lockPath(path string) string { return path + ".lock" } + +func withLock(path string, fn func() error) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + if err := checkDirectory(dir); err != nil { + return err + } + flags := os.O_CREATE | os.O_RDWR + flags |= syscall.O_NOFOLLOW + f, err := os.OpenFile(lockPath(path), flags, 0600) + if err != nil { + return err + } + defer f.Close() + if err = checkPrivateRegularFile(f); err != nil { + return fmt.Errorf("unsafe lock file: %w", err) + } + if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + return err + } + defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + return fn() +} + +func checkDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + return errors.New("state directory must be a real directory") + } + if info.Mode().Perm()&0022 != 0 { + return errors.New("state directory must not be group/other writable") + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok || int(st.Uid) != os.Geteuid() { + return errors.New("state directory must be owned by current service user") + } + return nil +} + +func checkPrivateRegularFile(f *os.File) error { + info, err := f.Stat() + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return errors.New("must be a regular file") + } + if info.Mode().Perm()&0077 != 0 { + return errors.New("file must have no group/other permissions") + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok || int(st.Uid) != os.Geteuid() { + return errors.New("file must be owned by current service user") + } + return nil +} + +func load(path string) (diskState, error) { + var d diskState + err := readState(path, &d) + if err != nil { + return d, err + } + if err = validateState(d); err != nil { + return d, fmt.Errorf("%w: %v", ErrInvalidState, err) + } + return d, nil +} +func readState(path string, v any) error { + // Opening a FIFO for read can block before fstat rejects its type. + f, e := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) + if e != nil { + return e + } + defer f.Close() + if e = checkPrivateRegularFile(f); e != nil { + return fmt.Errorf("unsafe state file: %w", e) + } + b, e := io.ReadAll(f) + if e != nil { + return e + } + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + if e = dec.Decode(v); e != nil { + return e + } + if e = dec.Decode(new(any)); e != io.EOF { + return errors.New("trailing state data") + } + return nil +} +func validateState(d diskState) error { + if d.SchemaVersion != 1 || !valid(d.HostID) || d.MaxGeneration == nil || d.Requests == nil || d.Resources == nil || d.ReconciliationRequired == nil { + return errors.New("invalid state header") + } + for instance, generation := range d.MaxGeneration { + if !valid(instance) || generation == 0 { + return errors.New("invalid maximum generation") + } + } + for key, r := range d.Requests { + if key != r.Instance+"\x00"+r.RequestKey || !valid(r.Instance) || !valid(r.RequestKey) || !valid(r.Resource) || !valid(r.PayloadHash) || r.Generation == 0 || d.MaxGeneration[r.Instance] < r.Generation || (r.State != "held" && r.State != "released") { + return errors.New("invalid request record") + } + if r.State == "held" { + if d.Resources[r.Resource] != r { + return errors.New("held request missing resource index") + } + } else if h, ok := d.Resources[r.Resource]; ok && h.Instance == r.Instance && h.RequestKey == r.RequestKey { + return errors.New("released request still owns resource") + } + } + for resource, r := range d.Resources { + if resource != r.Resource || r.State != "held" || d.Requests[r.Instance+"\x00"+r.RequestKey] != r { + return errors.New("invalid resource record") + } + if d.MaxGeneration[r.Instance] > r.Generation && !d.ReconciliationRequired[resource] { + return errors.New("stale reservation missing reconciliation marker") + } + } + for resource, required := range d.ReconciliationRequired { + held, ok := d.Resources[resource] + if !required || !ok || held.Generation >= d.MaxGeneration[held.Instance] { + return errors.New("invalid reconciliation marker") + } + } + return validatePreparations(d) +} +func writeState(path string, d diskState) error { + b, e := json.MarshalIndent(d, "", " ") + if e != nil { + return e + } + b = append(b, '\n') + tmp, e := os.CreateTemp(filepath.Dir(path), ".agent-state-*") + if e != nil { + return e + } + name := tmp.Name() + defer os.Remove(name) + if e = tmp.Chmod(0600); e == nil { + _, e = tmp.Write(b) + } + if e == nil { + e = tmp.Sync() + } + ce := tmp.Close() + if e == nil { + e = ce + } + if e != nil { + return e + } + if e = os.Rename(name, path); e != nil { + return e + } + dir, e := os.Open(filepath.Dir(path)) + if e != nil { + return e + } + defer dir.Close() + return dir.Sync() +} + +// Snapshot returns a deterministic read-only view useful to local diagnostics. +func (s *Store) Snapshot() (host string, generations map[string]uint64, reservations []Reservation, err error) { + err = withLock(s.path, func() error { + d, e := load(s.path) + if e != nil { + return e + } + host = d.HostID + generations = d.MaxGeneration + for _, r := range d.Resources { + reservations = append(reservations, r) + } + sort.Slice(reservations, func(i, j int) bool { return reservations[i].Resource < reservations[j].Resource }) + return nil + }) + return +} diff --git a/agent/state_consistency_test.go b/agent/state_consistency_test.go new file mode 100644 index 0000000..bc8d4da --- /dev/null +++ b/agent/state_consistency_test.go @@ -0,0 +1,68 @@ +//go:build linux + +package agent + +import ( + "encoding/json" + "errors" + "os" + "testing" +) + +func TestOpenRejectsImpossibleGenerationState(t *testing.T) { + cases := []struct { + name string + mutate func(*diskState) + }{ + {"empty instance", func(d *diskState) { d.MaxGeneration[""] = 1 }}, + {"zero generation", func(d *diskState) { d.MaxGeneration["other-instance"] = 0 }}, + {"current generation marked for reconciliation", func(d *diskState) { d.ReconciliationRequired["port:fixture"] = true }}, + {"false reconciliation marker", func(d *diskState) { d.ReconciliationRequired["port:fixture"] = false }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, path := initialized(t) + if err := s.AcceptGeneration("instance-a", 1); err != nil { + t.Fatal(err) + } + if _, err := s.Reserve(req(1, "fixture-request", "port:fixture", "fixture-hash")); err != nil { + t.Fatal(err) + } + var state diskState + if err := readState(path, &state); err != nil { + t.Fatal(err) + } + tc.mutate(&state) + encoded, err := json.Marshal(state) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(path, encoded, 0600); err != nil { + t.Fatal(err) + } + if _, err = Open(path); !errors.Is(err, ErrInvalidState) { + t.Fatalf("inconsistent state must fail closed: %v", err) + } + }) + } +} + +func TestOpenPreservesValidStaleHoldForReconciliation(t *testing.T) { + s, path := initialized(t) + if err := s.AcceptGeneration("instance-a", 1); err != nil { + t.Fatal(err) + } + if _, err := s.Reserve(req(1, "fixture-request", "port:fixture", "fixture-hash")); err != nil { + t.Fatal(err) + } + if err := s.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + reopened, err := Open(path) + if err != nil { + t.Fatal(err) + } + if err := reopened.ReconcileRelease("instance-a", 2, "port:fixture", func(Reservation) error { return nil }); err != nil { + t.Fatalf("valid stale hold should remain reconcilable: %v", err) + } +} diff --git a/agent/state_test.go b/agent/state_test.go new file mode 100644 index 0000000..e646fdb --- /dev/null +++ b/agent/state_test.go @@ -0,0 +1,534 @@ +//go:build linux + +package agent + +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +func initialized(t *testing.T) (*Store, string) { + t.Helper() + p := filepath.Join(t.TempDir(), "state.json") + if err := Initialize(p, "host-reviewed-01"); err != nil { + t.Fatal(err) + } + s, err := Open(p) + if err != nil { + t.Fatal(err) + } + return s, p +} + +func TestFIFOStateIsRejectedWithoutBlocking(t *testing.T) { + p := filepath.Join(t.TempDir(), "state.json") + if err := syscall.Mkfifo(p, 0600); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { _, err := Open(p); done <- err }() + select { + case err := <-done: + if !errors.Is(err, ErrInvalidState) { + t.Fatalf("FIFO was not rejected: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("opening FIFO blocked") + } +} +func req(gen uint64, key, resource, hash string) Request { + return Request{Instance: "instance-a", Generation: gen, RequestKey: key, Resource: resource, PayloadHash: hash} +} +func reserveAccepted(t *testing.T, s *Store, r Request) (Reservation, error) { + t.Helper() + if err := s.AcceptGeneration(r.Instance, r.Generation); err != nil { + return Reservation{}, err + } + return s.Reserve(r) +} + +func TestExplicitInitAndFailClosedMissingOrCorrupt(t *testing.T) { + p := filepath.Join(t.TempDir(), "state.json") + if _, err := Open(p); !errors.Is(err, ErrStateMissing) { + t.Fatalf("missing open: %v", err) + } + if err := Initialize(p, "host-1"); err != nil { + t.Fatal(err) + } + if err := Initialize(p, "host-2"); !errors.Is(err, ErrAlreadyInitialized) { + t.Fatalf("reinit: %v", err) + } + if err := os.WriteFile(p, []byte("{broken"), 0600); err != nil { + t.Fatal(err) + } + if _, err := Open(p); !errors.Is(err, ErrInvalidState) { + t.Fatalf("corrupt open: %v", err) + } +} +func TestReserveRequiresExplicitGenerationAcceptance(t *testing.T) { + s, p := initialized(t) + r := req(5, "unaccepted", "volume:x", "hash") + if _, err := s.Reserve(r); !errors.Is(err, ErrGenerationNotAccepted) { + t.Fatalf("unaccepted generation: %v", err) + } + _, gens, records, err := s.Snapshot() + if err != nil || gens["instance-a"] != 0 || len(records) != 0 { + t.Fatalf("rejected request mutated state: %#v %#v %v", gens, records, err) + } + reopened, err := Open(p) + if err != nil { + t.Fatal(err) + } + _, gens, records, err = reopened.Snapshot() + if err != nil || gens["instance-a"] != 0 || len(records) != 0 { + t.Fatalf("rejected request persisted state: %#v %#v %v", gens, records, err) + } +} + +func TestIdempotencyGenerationAndExclusiveResource(t *testing.T) { + s, _ := initialized(t) + a := req(4, "req-1", "docker:service-x", "abc") + first, err := reserveAccepted(t, s, a) + if err != nil { + t.Fatal(err) + } + again, err := reserveAccepted(t, s, a) + if err != nil || first != again { + t.Fatalf("replay %v %v", again, err) + } + if _, err = reserveAccepted(t, s, req(4, "req-1", "docker:service-x", "changed")); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("changed request: %v", err) + } + if _, err = reserveAccepted(t, s, req(3, "req-2", "docker:other", "def")); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("stale gen: %v", err) + } + if _, err = reserveAccepted(t, s, Request{Instance: "instance-b", Generation: 1, RequestKey: "req-b", Resource: "docker:service-x", PayloadHash: "x"}); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("resource conflict: %v", err) + } + if err = s.Release("instance-b", 4, "docker:service-x"); !errors.Is(err, ErrNotOwner) { + t.Fatalf("wrong release: %v", err) + } + if err = s.Release("instance-a", 4, "docker:service-x"); err != nil { + t.Fatal(err) + } + if _, err = reserveAccepted(t, s, req(3, "req-3", "docker:service-x", "ghi")); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("watermark lowered: %v", err) + } + if _, err = reserveAccepted(t, s, req(5, "req-5", "docker:service-x", "jkl")); err != nil { + t.Fatalf("new generation after explicit release: %v", err) + } +} +func TestRejectsAliasOverwriteOldReleaseAndReleasedReplay(t *testing.T) { + s, _ := initialized(t) + if _, err := reserveAccepted(t, s, req(1, "first", "volume:shared", "h1")); err != nil { + t.Fatal(err) + } + if _, err := reserveAccepted(t, s, req(1, "alias", "volume:shared", "h2")); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("same owner alias overwrote: %v", err) + } + if _, err := reserveAccepted(t, s, req(2, "next", "volume:other", "h3")); err != nil { + t.Fatal(err) + } + if err := s.Release("instance-a", 1, "volume:shared"); !errors.Is(err, ErrNotOwner) { + t.Fatalf("old generation released resource: %v", err) + } + if err := s.Release("instance-a", 2, "volume:other"); err != nil { + t.Fatal(err) + } + // Old generation is rejected before its prior request can be replayed. + if _, err := reserveAccepted(t, s, req(1, "first", "volume:shared", "h1")); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("stale replay accepted: %v", err) + } + // Same generation/request remains terminal after release; it cannot claim the resource again. + if _, err := reserveAccepted(t, s, req(2, "next", "volume:other", "h3")); err != nil { + t.Fatalf("identical terminal replay: %v", err) + } + if _, ok, err := s.Query("instance-a", "next"); err != nil || !ok { + t.Fatalf("released terminal request lost: %v %v", ok, err) + } + if _, err := reserveAccepted(t, s, req(2, "next", "volume:other", "different")); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("released identity reused with changed content: %v", err) + } + newOwner := Request{Instance: "instance-b", Generation: 1, RequestKey: "new-request", Resource: "volume:other", PayloadHash: "h4"} + if _, err := reserveAccepted(t, s, newOwner); err != nil { + t.Fatalf("released resource should be available to a new request: %v", err) + } + // A repeated old terminal request remains released and cannot overwrite the new owner. + if got, err := reserveAccepted(t, s, req(2, "next", "volume:other", "h3")); err != nil || got.State != "released" { + t.Fatalf("terminal replay changed state: %#v %v", got, err) + } + _, _, reservations, err := s.Snapshot() + var matched int + for _, held := range reservations { + if held.Resource == "volume:other" && held.Instance == "instance-b" && held.RequestKey == "new-request" { + matched++ + } + } + if err != nil || len(reservations) != 2 || matched != 1 { + t.Fatalf("old replay overwrote new reservation: %#v %v", reservations, err) + } +} + +func TestAcceptedGenerationFencesOldTaskEvenWhenReservationConflicts(t *testing.T) { + s, _ := initialized(t) + if _, err := reserveAccepted(t, s, req(1, "old", "volume:held", "h1")); err != nil { + t.Fatal(err) + } + if err := s.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + if _, err := reserveAccepted(t, s, req(2, "new", "volume:held", "h2")); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("expected reservation conflict: %v", err) + } + if _, err := reserveAccepted(t, s, req(1, "old", "volume:held", "h1")); !errors.Is(err, ErrGenerationStale) { + t.Fatalf("old task not fenced after failed reserve: %v", err) + } + if err := s.Release("instance-a", 1, "volume:held"); !errors.Is(err, ErrNotOwner) { + t.Fatalf("old owner released after newer accept: %v", err) + } +} + +func TestReconciliationRequiredNeedsTrustedProof(t *testing.T) { + s, _ := initialized(t) + if _, err := reserveAccepted(t, s, req(1, "old", "volume:held", "h1")); err != nil { + t.Fatal(err) + } + if err := s.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + if _, ok, err := s.Query("instance-a", "old"); err != nil || !ok { + t.Fatalf("old claim must remain inspectable: %v %v", ok, err) + } + if err := s.ReconcileRelease("instance-a", 2, "volume:held", nil); err == nil { + t.Fatal("missing proof accepted") + } + denied := errors.New("external owner not confirmed") + if err := s.ReconcileRelease("instance-a", 2, "volume:held", func(Reservation) error { return denied }); !errors.Is(err, denied) { + t.Fatalf("failed proof accepted: %v", err) + } + if _, err := reserveAccepted(t, s, req(2, "new", "volume:held", "h2")); !errors.Is(err, ErrResourceConflict) { + t.Fatalf("resource transferred without proof: %v", err) + } + if err := s.ReconcileRelease("instance-a", 2, "volume:held", func(r Reservation) error { + if r.Generation != 1 { + return errors.New("wrong stale owner") + } + return nil + }); err != nil { + t.Fatal(err) + } + if _, err := reserveAccepted(t, s, req(2, "new", "volume:held", "h2")); err != nil { + t.Fatalf("new owner after verified reconciliation: %v", err) + } +} + +func TestReconcileVerifierCanReadSnapshotWithoutDeadlock(t *testing.T) { + s, _ := initialized(t) + if _, err := reserveAccepted(t, s, req(1, "old", "volume:verify", "h1")); err != nil { + t.Fatal(err) + } + if err := s.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + done <- s.ReconcileRelease("instance-a", 2, "volume:verify", func(r Reservation) error { + _, _, _, err := s.Snapshot() + if err != nil { + return err + } + if r.Generation != 1 { + return errors.New("unexpected snapshot") + } + return nil + }) + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("verifier Snapshot deadlocked under store lock") + } +} + +func TestReconcileRejectsLocalGenerationOrResourceChangesDuringVerify(t *testing.T) { + t.Run("generation changed", func(t *testing.T) { + s, _ := initialized(t) + if _, err := reserveAccepted(t, s, req(1, "old", "volume:generation", "h1")); err != nil { + t.Fatal(err) + } + if err := s.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + err := s.ReconcileRelease("instance-a", 2, "volume:generation", func(Reservation) error { return s.AcceptGeneration("instance-a", 3) }) + if !errors.Is(err, ErrGenerationStale) { + t.Fatalf("generation change accepted: %v", err) + } + }) + t.Run("resource changed", func(t *testing.T) { + s, _ := initialized(t) + if _, err := reserveAccepted(t, s, req(1, "old", "volume:resource", "h1")); err != nil { + t.Fatal(err) + } + if err := s.AcceptGeneration("instance-a", 2); err != nil { + t.Fatal(err) + } + err := s.ReconcileRelease("instance-a", 2, "volume:resource", func(Reservation) error { + return s.ReconcileRelease("instance-a", 2, "volume:resource", func(Reservation) error { return nil }) + }) + if !errors.Is(err, ErrNotOwner) { + t.Fatalf("resource change accepted: %v", err) + } + }) +} + +func TestPersistenceAcrossReopen(t *testing.T) { + s, p := initialized(t) + if _, err := reserveAccepted(t, s, req(9, "req-9", "port:1234", "hash")); err != nil { + t.Fatal(err) + } + s2, err := Open(p) + if err != nil { + t.Fatal(err) + } + got, ok, err := s2.Query("instance-a", "req-9") + if err != nil || !ok || got.Generation != 9 { + t.Fatalf("query after reopen %#v %v %v", got, ok, err) + } + _, gens, _, err := s2.Snapshot() + if err != nil || gens["instance-a"] != 9 { + t.Fatalf("generation after reopen %v %v", gens, err) + } +} + +func TestLockHelperProcess(t *testing.T) { + mode := os.Getenv("AGENT_HELPER") + if mode != "1" && mode != "compete" { + return + } + path := os.Getenv("AGENT_STATE") + s, e := Open(path) + if e == nil { + instance := "instance-a" + gen := uint64(22) + key := "same-request" + resource := "volume:data" + hash := "same-hash" + if mode == "compete" { + instance = os.Getenv("AGENT_INSTANCE") + gen = 1 + key = "claim-" + instance + resource = "volume:race" + hash = "payload-" + instance + } + e = s.AcceptGeneration(instance, gen) + if e == nil { + _, e = s.Reserve(Request{Instance: instance, Generation: gen, RequestKey: key, Resource: resource, PayloadHash: hash}) + } + } + if e == nil { + os.Exit(0) + } + if mode == "compete" && errors.Is(e, ErrResourceConflict) { + os.Exit(3) + } + os.Exit(2) +} + +func TestCrossProcessAtomicIdempotentReserve(t *testing.T) { + _, p := initialized(t) + const n = 12 + var wg sync.WaitGroup + errs := make(chan error, n) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + c := exec.Command(os.Args[0], "-test.run=^TestLockHelperProcess$") + c.Env = append(os.Environ(), "AGENT_HELPER=1", "AGENT_STATE="+p) + b, e := c.CombinedOutput() + if e != nil { + errs <- fmt.Errorf("helper: %w: %s", e, strings.TrimSpace(string(b))) + } + }() + } + wg.Wait() + close(errs) + for e := range errs { + t.Error(e) + } + s, e := Open(p) + if e != nil { + t.Fatal(e) + } + _, ok, e := s.Query("instance-a", "same-request") + if e != nil || !ok { + t.Fatalf("missing record after contenders: %v %v", ok, e) + } + _, _, rs, e := s.Snapshot() + if e != nil || len(rs) != 1 { + t.Fatalf("expected one reservation: %d %v", len(rs), e) + } +} + +func TestHundredConcurrentSameRequestHasOneLogicalResult(t *testing.T) { + s, _ := initialized(t) + const n = 100 + var wg sync.WaitGroup + errs := make(chan error, n) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, err := reserveAccepted(t, s, req(7, "same", "volume:100", "payload")) + if err != nil { + errs <- err + } + }() + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + _, _, rs, err := s.Snapshot() + if err != nil || len(rs) != 1 { + t.Fatalf("expected one logical reservation, got %d: %v", len(rs), err) + } +} + +func TestCrossProcessDifferentInstancesCompeteForOneResource(t *testing.T) { + _, p := initialized(t) + const n = 2 + var wg sync.WaitGroup + results := make(chan error, n) + for _, instance := range []string{"instance-a", "instance-b"} { + instance := instance + wg.Add(1) + go func() { + defer wg.Done() + c := exec.Command(os.Args[0], "-test.run=^TestLockHelperProcess$") + c.Env = append(os.Environ(), "AGENT_HELPER=compete", "AGENT_STATE="+p, "AGENT_INSTANCE="+instance) + b, err := c.CombinedOutput() + if err != nil { + if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 3 { + results <- ErrResourceConflict + } else { + results <- fmt.Errorf("%s: %w (%s)", instance, err, strings.TrimSpace(string(b))) + } + } else { + results <- nil + } + }() + } + wg.Wait() + close(results) + wins, conflicts := 0, 0 + for err := range results { + if err == nil { + wins++ + } else if errors.Is(err, ErrResourceConflict) { + conflicts++ + } else { + t.Error(err) + } + } + if wins != 1 || conflicts != 1 { + t.Fatalf("expected one winner and one resource conflict; wins=%d conflicts=%d", wins, conflicts) + } +} + +func TestPrivateStateDirectoryAndFilesAccepted(t *testing.T) { + s, p := initialized(t) + if _, err := s.HostID(); err != nil { + t.Fatal(err) + } + for _, path := range []string{filepath.Dir(p), p, lockPath(p)} { + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm()&0077 != 0 && path != filepath.Dir(p) { + t.Fatalf("state file is not private: %s %o", path, info.Mode().Perm()) + } + } +} + +func TestRejectsSymlinkStateAndLockFiles(t *testing.T) { + t.Run("state symlink", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state.json") + real := filepath.Join(dir, "real.json") + if err := Initialize(real, "host-1"); err != nil { + t.Fatal(err) + } + if err := os.Symlink(real, path); err != nil { + t.Fatal(err) + } + if _, err := Open(path); err == nil { + t.Fatal("state symlink accepted") + } + }) + t.Run("lock symlink", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state.json") + target := filepath.Join(dir, "target") + if err := os.WriteFile(target, []byte(""), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, lockPath(path)); err != nil { + t.Fatal(err) + } + if err := Initialize(path, "host-1"); err == nil { + t.Fatal("lock symlink accepted") + } + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("state created through unsafe lock: %v", err) + } + }) +} + +func TestRejectsInsecureDirectoryAndStateFileModes(t *testing.T) { + t.Run("directory writable by group", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state.json") + if err := os.Chmod(dir, 0770); err != nil { + t.Fatal(err) + } + if err := Initialize(path, "host-1"); err == nil { + t.Fatal("group-writable state directory accepted") + } + }) + t.Run("state readable by others", func(t *testing.T) { + _, path := initialized(t) + if err := os.Chmod(path, 0644); err != nil { + t.Fatal(err) + } + if _, err := Open(path); err == nil { + t.Fatal("world-readable state file accepted") + } + }) + t.Run("lock readable by group", func(t *testing.T) { + _, path := initialized(t) + if err := os.Chmod(lockPath(path), 0640); err != nil { + t.Fatal(err) + } + s, err := Open(path) + if err == nil { + t.Fatal("group-readable lock accepted") + } + if s != nil { + t.Fatal("store opened with insecure lock") + } + }) +} diff --git a/config/native/README.md b/config/native/README.md index 6dfff06..7fb1b0c 100644 --- a/config/native/README.md +++ b/config/native/README.md @@ -20,9 +20,13 @@ HTTP/Modbus 使用安装时生成的独立协议服务账号。新装没有设 ```sh python3 config/native/prepare.py --refresh-devices -docker compose restart broker-owner mosquitto backend http_adapter modbus_service +docker compose restart broker-owner +docker compose restart mosquitto +docker compose restart backend http_adapter modbus_service frontend ``` +先重启 broker-owner,再重启 mosquitto(它与 broker-owner 共用网络);同一条命令里一起重启会让 mosquitto 退出。重启 backend 后要同时重启 frontend,否则前端的反向代理仍指向旧地址并返回 502。 + 单个服务允许列表最多 256 个设备;超出需规划独立服务身份。以上是当前 Broker 的设备范围管理要求,不是安装步骤。 查看运行状态和错误: diff --git a/config/native/UPDATE-SAFETY.md b/config/native/UPDATE-SAFETY.md new file mode 100644 index 0000000..b22690c --- /dev/null +++ b/config/native/UPDATE-SAFETY.md @@ -0,0 +1,61 @@ +# 正式安装入口的配置更新与恢复边界 + +## 使用方式 + +原有 `install.sh` / `install.ps1` 一行安装入口保持不变。`install.bash`、`install.core.ps1`、`upgrade.sh`、`upgrade.ps1` 调用同一个 Python 标准库实现 `update.py`;它是现有安装器的内部模块,不是另一套部署入口。需要 Python 3.8 或更新版本;需要创建 native TLS 证书时,沿用 `prepare.py` 的 OpenSSL 依赖,并在配置替换之前检查该命令存在。Windows 仍使用原正式 Compose,服务初始化与 POSIX 采用同一 native 流程。移除了 Windows 安装中的 `compose down --remove-orphans`,正常更新不会清理已有栈。 + +macOS pkg 和 Windows Inno 包只落地 bootstrap/install 入口及原有 UI launcher,不在脚本启动前直接复制 Compose、native 配置或 upgrade/uninstall。它们同样交给上述事务提交;macOS postinstall 也只修改其安装入口的执行权限,不先修改旧管理脚本。发布构建依赖三平台事务测试,避免打包路径绕过入口保护。 + +四个入口固定校验 updater 的 SHA-256。本地对应文件摘要相符时直接使用;否则先在临时目录完整下载并核对,摘要不符立即退出。发布时必须同时发布 updater、四个入口和其余负载。升级脚本声明的 updater 摘要必须与本次受信任 updater 相符,否则拒绝提交配置。HTTPS 分发仍是负载内容的信任来源;本改动没有声称实现插件制品签名或独立的发布包签名体系。 + +## 下载、提交和激活 + +每次操作在安装目录创建私有 `.thingspanel-update`。同一内核文件锁覆盖旧状态恢复、备份、下载、校验、替换及 native 激活全过程。进程退出或被杀后内核自动释放锁;不按 PID 删除所谓陈旧锁,也不允许第二个安装过程越过锁。 + +替换组包含:正式 `docker-compose.yml`、`niginx.conf`、5 个既有 native 文件、当前平台的 upgrade/uninstall 脚本,以及经过入口摘要校验的 updater。全部远端文件下载并校验完成前,不修改原文件内容或模式。原文件完整备份;原来不存在的文件记录为空状态。`.env`、`plugin-token` 作为受监视输入保留,不进入下载覆盖组。目录、文件和 journal 使用写入刷新及同目录原子替换;恢复保留原 POSIX mode/uid/gid。 + +可信 updater 自己解析 JSON、Python 语法、Compose 和 PG/unknown 守卫,不导入或运行下载中的 `prepare.py`。暂存 Compose 通过原安装目录作为 `--project-directory`、原 `.env` 作为 `--env-file` 校验;传入的 `COMPOSE_FILE` 等不能把 native 子进程引到另一套配置。显式指定组件版本时,还要求暂存 Compose 的 backend 镜像 tag 相符,不会下载当前配置却宣称安装了另一个版本。 + +每次替换前再次比较原文件与预检快照;`.env`、token 或待替换文件变化会停止更新。激活前再次确认整个替换组仍是已校验的新内容。不要在安装过程内另开不遵守锁的配置编辑器;检查可发现预检后的修改,但不能把普通文件系统的检查与替换宣称为对任意外部写者的原子比较交换。 + +| journal 阶段 | 含义 | 下次运行 | +| --- | --- | --- | +| `prepared` / `applying` | 尚未激活;可能已替换部分文件 | 先恢复原组,再开始新操作 | +| `config_committed` | 配置已替换,尚未开始 native 激活 | 仍可恢复原组 | +| `recovering` | 配置恢复中途被中断 | 校验备份与当前内容,继续幂等恢复 | +| `activation_started` | 已准备调用 native 配置、迁移或服务操作 | 阻止自动更新/恢复,保留现场,交由负责人核对数据库和服务状态 | +| `complete` / `recovered` | 操作完成或配置已恢复 | 允许下一次操作 | + +`activation_started` 在调用 native 代码之前持久化,因此即使激活尚未发生、进程恰好被杀,也会保守要求复核。失败后不能删除 journal 来“重试”,也不能称恢复 Compose 为数据库或业务回滚。原 `prepare.py` 的配置生成、pull、bootstrap、refresh、compose up、verify 顺序继续由同一个持锁进程调用;外部效果的协调恢复属于单独的迁移/业务收尾流程。 + +## 仅恢复尚未激活的配置 + +正常 install/upgrade 会先尝试处理前次未完成的配置事务。也可以用同版本、已审阅的 updater 显式恢复,命令不会下载文件或启动服务: + +```sh +python3 /path/to/reviewed/config/native/update.py --root /opt/thingspanel --recover-config-only +``` + +```powershell +python C:\reviewed-installer\config\native\update.py --root C:\ThingsPanel --recover-config-only +``` + +恢复前先检查整个文件组。当前文件只允许与记录中的旧版本或新版本完全一致;一旦发现人工修改、符号链接、损坏 journal、缺失或变化的备份,停止恢复并保留现场,不自动覆盖第三方内容。原来不存在的文件只在内容/模式与本次写入一致时删除;新增目录只尝试删除空目录,不递归清理。恢复本身再次被中断,也可再次执行同一命令。 + +`.thingspanel-update` 可能含旧配置与凭据,不得提交、公开上传或作为无脱敏附件发送。本实现不自动清理历史操作备份,以免删除故障恢复证据;已完成记录的保留期管理另行处理。支持范围是本机文件系统上的单安装目录;不得假定网络共享目录或存储设备掉电行为等同于本机文件系统。Windows 代码使用系统文件锁和写穿替换,但本轮 Linux 测试不构成 Windows/NTFS 或真实 PowerShell 安装验收。 + +## ThingsVis 身份与 activation 的 `.env` 记录 + +`prepare.py` 为部署生成并持久保留 `TP_THINGSVIS_AUTH_SECRET`,以及三份相互独立的安装 provider、ThingsVis identity、ThingsVis import 服务凭证。重复 prepare 和通常升级复用已保存值;环境覆盖与已有服务凭证不一致时拒绝,不打印凭据。broker 的只读 JSON 使用同一 updater 的原子替换工具写入,避免非 root 的第二次 prepare 因旧文件为 `0440` 而失败。 + +安全 SSO 切换必须由发布负责人显式选择 `TP_THINGSVIS_IMAGE` 并设置 `TP_THINGSVIS_AUTH_POLICY_TARGET=verified-sso-v1`,所选制品需对应已验收的源码和镜像锁。默认 `v1.0.23` 不能取得此标记。首次跨越该策略边界会轮换 AUTH_SECRET,即使旧值很强也不能复用,因为旧 accept-all SSO 可以签发不可信会话;用户需重新登录。新 secret 与 `TP_THINGSVIS_AUTH_POLICY=verified-sso-v1` 同一次原子 `.env` 写入,之后重复运行保留该身份。未知 policy、丢失的已受保护身份及隐式策略降级均拒绝。 + +标记仅记录该次配置意图,不证明容器已经切换。`.env` 在配置 commit 前仍是不可修改的 watched input;activation 时,同一个 journal 的 `activation_files` 先记录原 `.env` 备份、原/新摘要和未完成意图,再原子替换,最后记录 `applied`。完成外层事务会保留这份回执。若意图或文件替换后进程被杀,journal 仍为 `activation_started`,恢复会要求核对实际服务,不猜测旧/新 secret 哪个已生效,也不自动还原数据库或会话状态。 + +broker 的 `plugin-token`、`owner-tokens.json`、`services.json` 迁入最小专属目录 `config/native/broker`,Compose 只将该目录挂到 `/run/secrets`。逐文件 bind mount 会固定旧 inode,而目录挂载允许原子替换后的新文件被再次打开读取。首次迁移保留旧 token、owner 列表与 services 数据,旧路径文件保持原样;身份不一致时拒绝。三份新文件的原不存在状态、旧/新摘要和新建目录意图同样进入 `activation_files` / `activation_dirs`。旧容器须由同一正式 Compose 变更受控重建;配置生成成功不等于原进程已经采用新挂载。 + +只有当前持锁 updater 传入相同操作标识的 prepare 子进程可继续 activation;普通 prepare 不能以内容已经相同为由绕过未知安装状态。该标识用于本机进程关联,不是远端身份或安全围栏。已完成安装之后,原有显式 `--refresh-devices` 仍可在同一内核锁下原子更新 `broker/services.json` 这一资源投影;它不更换身份、不重开安装操作、不把未知安装改成成功。 + +`TP_THINGSVIS_IMAGE` 支持隔离验收使用的本地镜像选择;本机 image ID 不是远程 registry manifest digest。当前 formal release 仍缺少具有独立信任根的整组签名 manifest;仅 HTTPS 和 updater hash 不证明全部 payload 的发布身份。旧已安装入口对 updater 的固定 pin 也不会自动授权不同字节的新 updater。此类跨 updater 版本升级必须经已审阅的新 bootstrap 或补齐正式签名发布协议,不能以放宽 hash 检查自动重试。 + +隔离环境使用已有本地制品时,另设置 `TP_THINGSVIS_LOCAL_IMAGE_ID` 为完整 Docker `sha256:...` image ID。native pull 先核对该 ID 与 Compose 实际选择一致,然后只对这一 ThingsVis 镜像跳过 registry pull;其他组件保持原规则。ID 不符或镜像缺失立即失败,不回退下载另一个版本。生产 registry 引用应使用发布清单对应的远程摘要,不能把本机 image ID 填成 registry digest。 diff --git a/config/native/plugin_catalog_trust.pem b/config/native/plugin_catalog_trust.pem new file mode 100644 index 0000000..aa1f5ae --- /dev/null +++ b/config/native/plugin_catalog_trust.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEx5sN5wE3uKMeQNg/GfwdgdECr3Dl +HwERLCSb0Ng2n3l4djp5nlaxGQdYZFcwGZJ0UhdPyohfgnwpGnu6eZKicw== +-----END PUBLIC KEY----- diff --git a/config/native/prepare.py b/config/native/prepare.py index 4843d5c..e1543d3 100644 --- a/config/native/prepare.py +++ b/config/native/prepare.py @@ -8,46 +8,337 @@ import socket import subprocess import hashlib +import importlib.util import re import tempfile import time import urllib.request import urllib.error +from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[2] CONFIG = ROOT / 'config/native' CELL = 'community' INSTANCE = 'community-mosquitto' CLIENT = 'tp-community-backend' +_UPDATE_FILES = None +# Extra community migrations the backend's own startup does not apply. Each group is tied to the marker (source directory in the +# same image) of the feature that ships it: marker present => every file of the group must be in the image. To add a migration, +# add a line here (sql/33.sql: plugin runtime identities (T4); sql/34.sql + 35.sql: plugin installation records and tenant menu). +EXTRA_SQL_REQUIREMENTS = ( + ('internal/pluginidentity', ('33.sql',)), + ('internal/plugininstall', ('34.sql', '35.sql')), +) +EXTRA_COMMUNITY_SQL = tuple(name for _, names in EXTRA_SQL_REQUIREMENTS for name in names) +EXTRA_COMMUNITY_COMPONENT = 'community-ext' +# VERSION_NUMBER is not usable as the marker (it stays 25 while 33.sql exists) and image tags may be arbitrary local tags. def command(*args, data=None): result = subprocess.run(args, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=ROOT) if result.returncode: - errors = result.stderr.decode(errors='replace').splitlines() - detail = next((line for line in errors if 'ERROR:' in line or 'FATAL:' in line), '') - raise RuntimeError('Native preparation command failed: ' + ' '.join(args[:4]) + ('; ' + detail if detail else '')) + # Child output and arguments may contain interpolated credentials (for + # example a database URL). Do not propagate either into installer logs. + raise RuntimeError(f'Native preparation command failed (exit {result.returncode})') return result.stdout.decode().strip() +def image_has_marker(container, marker): + """True/False when the image clearly has/lacks the marker; raises if that cannot be determined.""" + with tempfile.TemporaryDirectory(prefix='tp-marker-') as temp: + result = subprocess.run(['docker', 'cp', container + ':/go/src/app/' + marker, temp + '/m'], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=ROOT) + if result.returncode == 0: return True + if b'could not find the file' in result.stderr.lower() or b'no such file' in result.stderr.lower(): return False + raise RuntimeError('Cannot tell whether the backend image ships ' + marker + ' (marker probe failed); refusing to guess') + + +def image_markers(container): + return {marker for marker, _ in EXTRA_SQL_REQUIREMENTS if image_has_marker(container, marker)} + + +def required_extra_sql(community, markers, image, requirements=EXTRA_SQL_REQUIREMENTS): + """Return the extra migration files to apply. For each group whose marker is in `markers` (the image has that feature) every + file must exist, otherwise fail. A group whose marker is absent is skipped with a log line; files that exist are still applied.""" + problems, present = [], [] + for marker, names in requirements: + for name in names: + if (community / name).is_file(): + present.append(community / name) + elif marker in markers: + problems.append('sql/' + name + ' (image contains ' + marker + ')') + else: + print('Backend image ' + image + ' predates ' + marker + '; skipping sql/' + name, flush=True) + if problems: + raise RuntimeError('Backend image ' + image + ' is missing required migration ' + ', '.join(problems) + + '; the image was packaged incorrectly. Refusing to continue.') + return present + + +def validate_thingsvis_database(config): + """Reject unsupported datasource before generating credentials or starting services. + + This guard covers the current ThingsVis service only; it does not certify a + platform storage profile or inspect any external database. + """ + service = config.get('services', {}).get('thingsvis-server') + if not isinstance(service, dict): + raise RuntimeError('ThingsVis service is missing from the selected Compose configuration') + environment = service.get('environment') + if isinstance(environment, list): + values = [entry.partition('=') for entry in environment if isinstance(entry, str)] + matches = [value for key, separator, value in values if key == 'DATABASE_URL' and separator] + if len(matches) != 1: + raise RuntimeError('ThingsVis DATABASE_URL is missing or ambiguous in the selected Compose configuration') + environment = {'DATABASE_URL': matches[0]} + if not isinstance(environment, dict): + raise RuntimeError('ThingsVis database configuration is missing from the selected Compose configuration') + database_url = environment.get('DATABASE_URL') + if not isinstance(database_url, str): + raise RuntimeError('ThingsVis DATABASE_URL is missing from the selected Compose configuration') + # Do not echo DATABASE_URL: it can contain credentials. + parsed_url = urlsplit(database_url) + if parsed_url.scheme not in ('postgres', 'postgresql') or not parsed_url.hostname or '$' in parsed_url.hostname: + raise RuntimeError('ThingsVis currently supports only a PostgreSQL datasource in this installer') + + +def validate_supported_backend_database(config): + """Conservative guard for the currently shipped PG backend configuration. + + This does not certify the complete platform profile or an external server. + New provider configuration requires an explicit reviewed contract. + """ + services = config.get('services', {}) + backend = services.get('backend') if isinstance(services, dict) else None + if not isinstance(backend, dict): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + env = backend.get('environment') + if isinstance(env, list): + parsed = {} + for item in env: + if not isinstance(item, str) or '=' not in item: + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + key, value = item.split('=', 1) + if key in parsed: + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + parsed[key] = value + env = parsed + if not isinstance(env, dict): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + # Keep accepting legacy-only installed Compose files during upgrade preflight. + # New defaults carry both contracts until the published v1.3.0 image is retired. + legacy_required = ('GOTP_DB_PSQL_HOST', 'GOTP_DB_PSQL_PORT', 'GOTP_DB_PSQL_USERNAME', 'GOTP_DB_PSQL_DBNAME') + if any(not isinstance(env.get(key), (str, int)) or not str(env[key]).strip() or '$' in str(env[key]) for key in legacy_required): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + if env['GOTP_DB_PSQL_HOST'] == 'postgres' and not isinstance(services.get('postgres'), dict): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + relational_required = ( + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST', 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE', 'GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD', + ) + relational_keys = [key for key in env if key.startswith('GOTP_RELATIONAL_')] + if relational_keys: + # Compose's --no-interpolate preflight is used before generated .env + # secrets exist. The provider, host, port, database and user must still + # be concrete; only the password may remain an interpolation expression + # because its value does not change the selected storage contract. + unresolved = [ + key for key in relational_required[:-1] + if not isinstance(env.get(key), (str, int)) + or not str(env[key]).strip() + or '$' in str(env[key]) + ] + password = env.get('GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD') + if (env.get('GOTP_RELATIONAL_DRIVER') != 'postgres' or unresolved + or not isinstance(password, (str, int)) or not str(password).strip()): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + if env['GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST'] == 'postgres' and not isinstance(services.get('postgres'), dict): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + for key, value in env.items(): + upper = str(key).upper() + if upper.startswith(('GOTP_DB_MYSQL_', 'GOTP_DB_MARIADB_')) and value not in (None, ''): + raise RuntimeError('A MySQL backend is not supported by this installer') + if upper in ('GOTP_RELATIONAL_DRIVER', 'GOTP_DB_PSQL_DBTYPE', 'GOTP_DB_DRIVER', 'GOTP_DB_PROVIDER', 'GOTP_DB_TYPE', 'DB_DRIVER', 'DB_PROVIDER', 'DB_TYPE', 'DATABASE_TYPE', 'DATABASE_PROVIDER', 'DATABASE_DRIVER') and str(value).lower() not in ('postgres', 'postgresql', 'pg'): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + if upper == 'DATABASE_URL' and (not isinstance(value, str) or urlsplit(value).scheme not in ('postgres', 'postgresql')): + raise RuntimeError('Cannot confirm the supported PostgreSQL backend configuration') + + +def check_thingsvis_database(uninterpolated=False): + args = ['docker', 'compose', 'config'] + try: + rendered = command(*args, '--format', 'json') + except RuntimeError: + if not uninterpolated: + raise + rendered = command(*args, '--no-interpolate', '--format', 'json') + config = json.loads(rendered) + validate_thingsvis_database(config) + validate_supported_backend_database(config) + + def sql(database, statement): return command('docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-U', 'postgres', '-d', database, '-v', 'ON_ERROR_STOP=1', data=statement.encode()) -def save(name, value, broker=False): - path = CONFIG / name - path.write_text(json.dumps(value, indent=2) + '\n', encoding='utf-8') - path.chmod(0o440 if broker else 0o600) +def update_files(): + """Load the existing reviewed updater only after datasource preflight.""" + global _UPDATE_FILES + if _UPDATE_FILES is None: + spec = importlib.util.spec_from_file_location('tp_native_update_files', Path(__file__).with_name('update.py')) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + _UPDATE_FILES = module + return _UPDATE_FILES + + +def save(name, value, broker=False, lock_held=False): + # Formal install/upgrade holds the updater's process lock. Reuse its + # durable replacement implementation: writing an existing 0440 broker + # file in place fails for supported non-root Docker Desktop installs. + files = update_files() + path = files.safe_target(CONFIG, ('broker/' if broker else '') + name) + original = files.file_info(path) + ownership = original if broker and os.name == 'posix' and os.geteuid() == 0: - os.chown(path, 1883, 1883) + ownership = {'uid': 1883, 'gid': 1883} + write_configuration_file(path, (json.dumps(value, indent=2) + '\n').encode('utf-8'), + 0o440 if broker else 0o600, ownership, lock_held=lock_held) + + +def write_configuration_file(path, content, mode, ownership=None, lock_held=False): + files = update_files() + original = files.file_info(path) + owner = ownership if ownership is not None else original + # Avoid unnecessary inode changes for configuration that is already exact. + if original is not None and path.read_bytes() == content and original['mode'] == mode: + if owner is None or os.name == 'nt' or (original['uid'], original['gid']) == (owner['uid'], owner['gid']): + return + if (ROOT / '.thingspanel-update/journal.json').exists(): + transaction = files.Transaction(ROOT) + relative = path.relative_to(ROOT).as_posix() + data = transaction.load() + if data and data['phase'] == 'activation_started' and os.environ.get('TP_INSTALLER_ACTIVE_OPERATION') == data['operation']: + transaction.write_activation_file(relative, content, mode, owner) + elif data and data['phase'] in ('complete', 'recovered') and relative == 'config/native/broker/services.json': + # Preserve the existing explicit device-scope refresh command. + # This is one atomic resource projection, not an install retry or + # identity change; serialize it against any new installer run. + if lock_held: + latest = transaction.load() + if latest is None or latest['phase'] not in ('complete', 'recovered'): + raise RuntimeError('Installation state changed; broker refresh was not applied') + files.durable_bytes(path, content, mode, owner) + else: + with files.update_lock(transaction.state): + latest = transaction.load() + if latest is None or latest['phase'] not in ('complete', 'recovered'): + raise RuntimeError('Installation state changed; broker refresh was not applied') + files.durable_bytes(path, content, mode, owner) + else: + raise RuntimeError('Configuration requires an active installer operation; preserve unresolved installation state') + else: + files.durable_bytes(path, content, mode, owner) + + +def secret_value(value, key, from_dotenv=False): + if value is None: + return None + if from_dotenv: + value = value.strip() + literal = value.startswith("'") and value.endswith("'") + if len(value) >= 2 and value[0] == value[-1] and value[0] in ('\"', "'"): + value = value[1:-1] + if ('$' in value and not literal) or '\\' in value or ' #' in value: + raise RuntimeError(key + ' must be a stable literal .env value; existing configuration was not changed') + if len(value) < 32 or any(character in value for character in ('\n', '\r', '\x00')): + raise RuntimeError(key + ' must contain at least 32 characters; existing configuration was not changed') + return value + + +def deployment_secret(current, key): + """Keep a deployment service credential stable across install and upgrade.""" + saved = current.get(key) + supplied = os.environ.get(key) + + saved_value, supplied_value = secret_value(saved, key, True), secret_value(supplied, key) + if saved_value is not None and supplied_value is not None and saved_value != supplied_value: + raise RuntimeError(key + ' conflicts with the existing deployment; existing configuration was not changed') + if saved is not None: + return saved # Preserve quoting; removing it can enable Compose interpolation. + if supplied_value is not None: + if re.fullmatch(r'[A-Za-z0-9_+=./-]+', supplied_value) is None: + raise RuntimeError(key + ' needs an unambiguous .env encoding; existing configuration was not changed') + return supplied_value + return secrets.token_hex(32) + + +def thingsvis_auth_settings(current): + """Rotate once only when the verified-SSO artifact is explicitly selected. + + The target is a release-owner assertion bound to its reviewed image lock; + it is not a claim that this installer has verified a registry signature. + """ + policy = 'verified-sso-v1' + recorded = current.get('TP_THINGSVIS_AUTH_POLICY', '') + target = os.environ.get('TP_THINGSVIS_AUTH_POLICY_TARGET', current.get('TP_THINGSVIS_AUTH_POLICY_TARGET', '')) + selected = os.environ.get('TP_THINGSVIS_IMAGE', current.get('TP_THINGSVIS_IMAGE', '')) + local_id = os.environ.get('TP_THINGSVIS_LOCAL_IMAGE_ID', current.get('TP_THINGSVIS_LOCAL_IMAGE_ID', '')) + if local_id and (not selected or re.fullmatch(r'sha256:[0-9a-f]{64}', local_id) is None): + raise RuntimeError('A local ThingsVis image requires its exact Docker image ID and selected image') + selection = {'TP_THINGSVIS_IMAGE': selected} if selected else {} + if local_id or 'TP_THINGSVIS_LOCAL_IMAGE_ID' in current or 'TP_THINGSVIS_LOCAL_IMAGE_ID' in os.environ: + selection['TP_THINGSVIS_LOCAL_IMAGE_ID'] = local_id + if recorded not in ('', policy) or target not in ('', policy): + raise RuntimeError('Unknown ThingsVis auth policy; preserve the existing deployment') + if recorded and target != policy: + raise RuntimeError('A secured ThingsVis deployment cannot silently downgrade its auth policy') + if target == policy: + if not selected or selected.split('@', 1)[0].endswith(':v1.0.23'): + raise RuntimeError('Select the reviewed secure ThingsVis image before upgrading the auth policy') + # Prior accept-all SSO could mint signed tokens even with a strong + # custom key. No old key is safe to carry across this policy boundary. + if not recorded: + if 'TP_THINGSVIS_AUTH_SECRET' in os.environ: + raise RuntimeError('An exported auth secret would override the rotated .env identity; remove that override before the policy upgrade') + values = {'TP_THINGSVIS_AUTH_SECRET': secrets.token_hex(32), + 'TP_THINGSVIS_AUTH_POLICY': policy, 'TP_THINGSVIS_AUTH_POLICY_TARGET': policy} + values.update(selection) + return values + if not current.get('TP_THINGSVIS_AUTH_SECRET'): + raise RuntimeError('The secured ThingsVis auth identity is missing; preserve the deployment') + values = {'TP_THINGSVIS_AUTH_SECRET': deployment_secret(current, 'TP_THINGSVIS_AUTH_SECRET')} + values.update(selection) + return values def configure(): + if (ROOT / '.thingspanel-update/journal.json').exists(): + transaction = update_files().Transaction(ROOT) + data = transaction.load() + active = data and data['phase'] == 'activation_started' and os.environ.get('TP_INSTALLER_ACTIVE_OPERATION') == data['operation'] + if not active and (data is None or data['phase'] not in ('complete', 'recovered')): + raise RuntimeError('Native preparation requires the active installer operation; preserve unresolved installation state') CONFIG.mkdir(parents=True, exist_ok=True) envfile = ROOT / '.env' text = envfile.read_text(encoding='utf-8') if envfile.exists() else '' current = dict(line.split('=', 1) for line in text.splitlines() if '=' in line and not line.startswith('#')) + auth_keys = ('TP_THINGSVIS_AUTH_SECRET', 'TP_THINGSVIS_AUTH_POLICY', 'TP_THINGSVIS_AUTH_POLICY_TARGET', 'TP_THINGSVIS_IMAGE', 'TP_THINGSVIS_LOCAL_IMAGE_ID') + for key in auth_keys: + matches = [line.split('=', 1)[1] for line in text.splitlines() + if '=' in line and line.split('=', 1)[0].strip() == key] + if len(matches) > 1: + raise RuntimeError('Ambiguous ThingsVis auth configuration; existing configuration was not changed') + if matches: + current[key] = matches[0] + auth = thingsvis_auth_settings(current) + integration_keys = ('TP_MARKETINSTALL_PROVIDER_TOKEN', 'TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN', + 'TP_MARKETINSTALL_THINGSVIS_TOKEN') + integration = {key: deployment_secret(current, key) for key in integration_keys} + if len({secret_value(value, key, True) for key, value in integration.items()}) != len(integration): + raise RuntimeError('Market installation service credentials must be distinct; existing configuration was not changed') defaults = {'TP_DATABASE_PASSWORD': 'postgresThingsPanel', 'TP_NATIVE_DB_PASSWORD': current.get('TP_DATABASE_PASSWORD', 'postgresThingsPanel'), 'TP_BROKER_DATABASE_DSN': 'host=postgres user=postgres password=' + current.get('TP_DATABASE_PASSWORD', 'postgresThingsPanel') + ' dbname=ThingsPanel port=5432 sslmode=disable', 'TP_JWT_KEY': secrets.token_hex(32), 'TP_AUTOMATION_TOKEN': secrets.token_hex(32), @@ -55,22 +346,48 @@ def configure(): 'TP_PROTOCOL_MQTT_USER': 'tp-community-protocols', 'TP_PROTOCOL_MQTT_PASSWORD': secrets.token_hex(32), 'TP_DEPLOYMENT_ID': 'community', 'TP_BROKER_CELL': CELL, 'TP_BROKER_INSTANCE': INSTANCE, 'TP_MQTT_CLIENT_ID': CLIENT, 'TP_NOTIFICATION_KEYRING_B64': base64.b64encode(json.dumps({'main': base64.b64encode(secrets.token_bytes(32)).decode()}).encode()).decode()} - with envfile.open('a', encoding='utf-8') as output: - if text and not text.endswith('\n'): output.write('\n') - for key, value in defaults.items(): - if key not in current: - output.write(key + '=' + value + '\n') - current[key] = value - envfile.chmod(0o600) - tokenfile = CONFIG / 'plugin-token' - if not tokenfile.exists(): - tokenfile.write_text(secrets.token_hex(32), encoding='ascii') - tokenfile.chmod(0o440) - if os.name == 'posix' and os.geteuid() == 0: os.chown(tokenfile, 1883, 1883) - save('owner-tokens.json', [{'token': tokenfile.read_text().strip(), 'broker_cell': current['TP_BROKER_CELL'], 'broker_instance': current['TP_BROKER_INSTANCE']}], True) + defaults.update(auth) + defaults.update(integration) + lines = text.splitlines() + for key, value in defaults.items(): + if key not in current: + lines.append(key + '=' + value) + current[key] = value + elif key in auth and current[key] != value: + lines = [key + '=' + value if '=' in line and line.split('=', 1)[0].strip() == key else line for line in lines] + current[key] = value + updated = ('\n'.join(lines) + '\n').encode('utf-8') + files = update_files() + tokenfile = files.safe_target(CONFIG, 'broker/plugin-token') + legacy_token = files.safe_target(CONFIG, 'plugin-token') + token_source = tokenfile if files.file_info(tokenfile) is not None else legacy_token + token = token_source.read_text(encoding='ascii').strip() if files.file_info(token_source) is not None else secrets.token_hex(32) + if len(token) < 32 or any(ch.isspace() for ch in token): + raise RuntimeError('Existing broker identity is invalid; preserve it for review') + services_file = files.safe_target(CONFIG, 'broker/services.json') + legacy_services = files.safe_target(CONFIG, 'services.json') + services_source = services_file if files.file_info(services_file) is not None else legacy_services + initial_services = json.loads(services_source.read_text(encoding='utf-8')) if files.file_info(services_source) is not None else [service(current, [])] + if not isinstance(initial_services, list): + raise RuntimeError('Existing broker services configuration is invalid; preserve it for review') + owners_file = files.safe_target(CONFIG, 'broker/owner-tokens.json') + legacy_owners = files.safe_target(CONFIG, 'owner-tokens.json') + owners_source = owners_file if files.file_info(owners_file) is not None else legacy_owners + owners = json.loads(owners_source.read_text(encoding='utf-8')) if files.file_info(owners_source) is not None else [ + {'token': token, 'broker_cell': current['TP_BROKER_CELL'], 'broker_instance': current['TP_BROKER_INSTANCE']}] + matching = [item for item in owners if isinstance(item, dict) and item.get('token') == token] if isinstance(owners, list) else [] + if len(matching) != 1 or matching[0].get('broker_cell') != current['TP_BROKER_CELL'] or matching[0].get('broker_instance') != current['TP_BROKER_INSTANCE']: + raise RuntimeError('Existing broker owner identity conflicts with configuration; preserve it for review') + if updated != text.encode('utf-8'): + write_configuration_file(envfile, updated, 0o600) + else: + envfile.chmod(0o600) + token_owner = {'uid': 1883, 'gid': 1883} if os.name == 'posix' and os.geteuid() == 0 else files.file_info(tokenfile) + write_configuration_file(tokenfile, token.encode('ascii'), 0o440, token_owner) + save('owner-tokens.json', owners, True) # An empty initial scope only subscribes; it cannot issue unscoped commands. - if not (CONFIG / 'services.json').exists(): - save('services.json', [service(current, [])], True) + if files.file_info(services_file) is None: + save('services.json', initial_services, True) certificate = CONFIG / 'internal.crt' if not certificate.exists(): command('openssl', 'req', '-x509', '-nodes', '-newkey', 'rsa:2048', '-days', '3650', @@ -95,11 +412,20 @@ def service(env, targets): 'policy_version': 'installer-v1', 'mapping_version': 'standard-v1'} -def refresh(env): - targets = json.loads(sql('ThingsPanel', "SELECT coalesce(json_agg(t),'[]') FROM (SELECT d.id,d.tenant_id FROM devices d LEFT JOIN device_configs c ON c.id=d.device_config_id AND c.tenant_id=d.tenant_id WHERE d.is_enabled='enabled' AND d.activate_flag='active' AND (d.parent_id IS NULL OR d.parent_id='') AND (d.service_access_id IS NULL OR d.service_access_id='') AND coalesce(d.access_way,'A')<>'B' AND coalesce(c.protocol_type,'MQTT') IN ('MQTT','') ORDER BY d.id)t;")) - if len(targets) > 256: raise RuntimeError('Broker service target scope exceeds 256; provision separate reviewed service identities') - plugins = json.loads(sql('ThingsPanel', "SELECT coalesce(json_agg(t),'[]') FROM (SELECT d.id,d.tenant_id FROM devices d LEFT JOIN device_configs c ON c.id=d.device_config_id AND c.tenant_id=d.tenant_id WHERE d.is_enabled='enabled' AND d.activate_flag='active' AND ((d.service_access_id IS NOT NULL AND d.service_access_id<>'') OR (c.protocol_type IS NOT NULL AND c.protocol_type NOT IN ('MQTT',''))) ORDER BY d.id)t;")) - if len(plugins) > 256: raise RuntimeError('Protocol plugin scope exceeds 256 devices') +def scope_services(env, targets, plugins): + """Broker service identities for the given device scopes (pure; no I/O). + + The platform account issues commands to MQTT devices *and* to plugin (service + access) devices: a command for a plugin device is published by the Broker owner + on the plugin's prefixed topic, and the owner silently drops it when the device + is not in the platform account's scope (T7b finding 3). The protocol account + only ever covers plugin devices. + """ + platform_scope, seen = [], set() + for item in list(targets) + list(plugins): + if item['id'] not in seen: + seen.add(item['id']) + platform_scope.append(item) plugin = service(env, []) plugin.update(username=env['TP_PROTOCOL_MQTT_USER'], password=env['TP_PROTOCOL_MQTT_PASSWORD'], allowed_client_ids=[], allow_any_client_id=True, plugin_socket=True, @@ -107,8 +433,93 @@ def refresh(env): allowed_tenant_ids=sorted({item['tenant_id'] for item in plugins})) plugin['principal']['device_id'] = 'community-protocols' plugin['policy']['subscribe'] = [] - save('services.json', [service(env, targets), plugin], True) - print('MQTT command allowlist refreshed for ' + str(len(targets)) + ' devices; restart broker-owner and mosquitto to load it.') + return [service(env, platform_scope), plugin] + + +def query_scopes(): + targets = json.loads(sql('ThingsPanel', "SELECT coalesce(json_agg(t),'[]') FROM (SELECT d.id,d.tenant_id FROM devices d LEFT JOIN device_configs c ON c.id=d.device_config_id AND c.tenant_id=d.tenant_id WHERE d.is_enabled='enabled' AND d.activate_flag='active' AND (d.parent_id IS NULL OR d.parent_id='') AND (d.service_access_id IS NULL OR d.service_access_id='') AND coalesce(d.access_way,'A')<>'B' AND coalesce(c.protocol_type,'MQTT') IN ('MQTT','') ORDER BY d.id)t;")) + if len(targets) > 256: raise RuntimeError('Broker service target scope exceeds 256; provision separate reviewed service identities') + plugins = json.loads(sql('ThingsPanel', "SELECT coalesce(json_agg(t),'[]') FROM (SELECT d.id,d.tenant_id FROM devices d LEFT JOIN device_configs c ON c.id=d.device_config_id AND c.tenant_id=d.tenant_id WHERE d.is_enabled='enabled' AND d.activate_flag='active' AND ((d.service_access_id IS NOT NULL AND d.service_access_id<>'') OR (c.protocol_type IS NOT NULL AND c.protocol_type NOT IN ('MQTT',''))) ORDER BY d.id)t;")) + if len(plugins) > 256: raise RuntimeError('Protocol plugin scope exceeds 256 devices') + return targets, plugins + + +def refresh(env): + targets, plugins = query_scopes() + save('services.json', scope_services(env, targets, plugins), True) + print('MQTT command allowlist refreshed for ' + str(len(targets)) + ' devices and ' + str(len(plugins)) + ' plugin devices; restart broker-owner and mosquitto to load it.') + + +def current_services(): + files = update_files() + path = files.safe_target(CONFIG, 'broker/services.json') + if files.file_info(path) is None: + path = files.safe_target(CONFIG, 'services.json') + return json.loads(path.read_text(encoding='utf-8')) if files.file_info(path) is not None else None + + +def sync_scope(env, restart=None): + """Refresh the Broker device scope; only when it changed, restart broker-owner and then mosquitto. + + mosquitto shares broker-owner's network namespace, so the order is fixed: + owner first (it reads services.json at start), mosquitto second. Returns True when something changed. + """ + restart = restart or (lambda service_name: command('docker', 'compose', 'restart', service_name)) + files = update_files() + state = ROOT / '.thingspanel-update' + files.private_directory(state) + # Serialize the full compare/write/restart/ack sequence with installer + # activation and other scope workers. The watcher retries a busy lock. + with files.update_lock(state): + targets, plugins = query_scopes() + wanted = scope_services(env, targets, plugins) + current = current_services() + changed = current != wanted + fingerprint = hashlib.sha256(json.dumps(wanted, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + pending = read_scope_restart_pending(files) + if not changed and pending is None: + print('Broker device scope unchanged (' + str(len(targets)) + ' devices, ' + str(len(plugins)) + ' plugin devices).') + return False + + if changed or pending != fingerprint: + # Record intent before changing services.json. A process crash or + # partial Docker restart leaves this marker for the next watcher pass. + write_scope_restart_pending(files, fingerprint) + if changed: + save('services.json', wanted, True, lock_held=True) + print('Broker device scope changed (' + str(len(targets)) + ' devices, ' + str(len(plugins)) + ' plugin devices); restarting broker-owner, then mosquitto.', flush=True) + else: + print('Retrying pending Broker scope restarts.', flush=True) + for name in ('broker-owner', 'mosquitto'): + restart(name) + clear_scope_restart_pending(files) + return changed + + +def read_scope_restart_pending(files=None): + files = files or update_files() + path = files.safe_target(ROOT, 'config/native/broker/.scope-sync-restart.json') + if files.file_info(path) is None: + return None + value = json.loads(path.read_text(encoding='utf-8')) + fingerprint = value.get('sha256') if isinstance(value, dict) else None + if not isinstance(fingerprint, str) or re.fullmatch(r'[0-9a-f]{64}', fingerprint) is None: + raise RuntimeError('Invalid pending Broker scope restart record') + return fingerprint + + +def write_scope_restart_pending(files, fingerprint): + path = files.safe_target(ROOT, 'config/native/broker/.scope-sync-restart.json') + files.durable_bytes(path, + (json.dumps({'sha256': fingerprint}, sort_keys=True) + '\n').encode(), 0o600) + + +def clear_scope_restart_pending(files): + path = files.safe_target(ROOT, 'config/native/broker/.scope-sync-restart.json') + if files.file_info(path) is None: + return + path.unlink() + files.fsync_directory(path.parent) def bootstrap(): @@ -120,6 +531,7 @@ def bootstrap(): image = json.loads(image)['services']['backend']['image'] container = command('docker', 'create', '--entrypoint', '/bin/true', image) try: + markers = image_markers(container) for source, target in [('sql', 'community'), ('encore-api/automation/migrations', 'automation'), ('encore-api/devicemetadata/migrations', 'device_metadata'), ('encore-api/l3-core/notification/migrations', 'notification'), ('pkg/global/global.go', 'global.go')]: @@ -136,6 +548,9 @@ def bootstrap(): for number in range(current + 1, target_version + 1): content = (stage / 'community' / (str(number) + '.sql')).read_text() sql('ThingsPanel', "BEGIN; SET LOCAL lock_timeout='30s';\n" + content + "\nUPDATE sys_version SET version_number=" + str(number) + ",version='v1.3.0'; COMMIT;") + # Schema files newer than sys_version's VERSION_NUMBER that the backend does not apply by itself at startup. + # Idempotent (CREATE ... IF NOT EXISTS) and checksum-recorded. Old image: skip + log. New image missing it: fail. + apply_migrations('ThingsPanel', EXTRA_COMMUNITY_COMPONENT, required_extra_sql(stage / 'community', markers, image)) apply_migrations('ThingsPanel', 'broker', sorted((stage / 'community/broker').glob('[0-9]*.sql'), key=lambda p: int(p.name.split('_')[0]))) for database in ['device_metadata', 'automation', 'notification']: if sql('postgres', "SELECT count(*) FROM pg_database WHERE datname='" + database + "'") == '0': @@ -153,10 +568,38 @@ def bootstrap(): print('Community, Broker and native database migrations are ready.') -def pull_images(): +def pull_images(configured=None): config = json.loads(command('docker', 'compose', 'config', '--format', 'json')) + configured = configured or {} + local_id = configured.get('TP_THINGSVIS_LOCAL_IMAGE_ID') + local_image = None + if local_id: + local_image = config['services'].get('thingsvis-server', {}).get('image') + if local_image != configured.get('TP_THINGSVIS_IMAGE') or re.fullmatch(r'sha256:[0-9a-f]{64}', local_id) is None: + raise RuntimeError('Local ThingsVis image selection does not match the reviewed configuration') + if command('docker', 'image', 'inspect', '--format', '{{.Id}}', local_image) != local_id: + raise RuntimeError('Local ThingsVis image identity differs; no registry fallback was attempted') + # Reviewed local images for the backend and the TDengine profile follow the + # same rule: an exact image ID is pinned, and a mismatch never falls back to a registry. + pinned = {} + for image_key, id_key in (('TP_BACKEND_IMAGE', 'TP_BACKEND_LOCAL_IMAGE_ID'), ('TP_TDENGINE_IMAGE', 'TP_TDENGINE_LOCAL_IMAGE_ID')): + identity = configured.get(id_key) + if not identity: + continue + reference = configured.get(image_key) + if not reference or re.fullmatch(r'sha256:[0-9a-f]{64}', identity) is None: + raise RuntimeError('Local image selection does not match the reviewed configuration: ' + id_key) + if command('docker', 'image', 'inspect', '--format', '{{.Id}}', reference) != identity: + raise RuntimeError('Local image identity differs; no registry fallback was attempted') + pinned[reference] = identity images = dict.fromkeys(service['image'] for service in config['services'].values()) for image in images: + if image == local_image: + print('Using the explicitly selected local ThingsVis image identity.', flush=True) + continue + if image in pinned: + print('Using the pinned local image ' + image, flush=True) + continue print('Pulling ' + image, flush=True) for attempt in range(3): result = subprocess.run(['docker', 'pull', image], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) @@ -169,7 +612,7 @@ def pull_images(): def apply_migrations(database, component, paths): sql(database, 'CREATE TABLE IF NOT EXISTS installer_migrations(component text NOT NULL,version int NOT NULL,checksum text NOT NULL,PRIMARY KEY(component,version))') for path in paths: - number = int(path.name.split('_')[0]) + number = int(re.match(r'\d+', path.name).group()) content = path.read_text().replace('\r\n', '\n') checksum = hashlib.sha256(content.encode()).hexdigest() recorded = sql(database, "SELECT checksum FROM installer_migrations WHERE component='" + component + "' AND version=" + str(number)) @@ -177,7 +620,7 @@ def apply_migrations(database, component, paths): if recorded != checksum: raise RuntimeError('Migration checksum mismatch: ' + component + '/' + path.name) continue # A pre-existing native database without this installer's ledger needs its native version respected. - if component != 'broker' and sql(database, "SELECT to_regclass('public.schema_migrations') IS NOT NULL") == 't': + if component not in ('broker', EXTRA_COMMUNITY_COMPONENT) and sql(database, "SELECT to_regclass('public.schema_migrations') IS NOT NULL") == 't': native_version = sql(database, 'SELECT coalesce(max(version),0) FROM schema_migrations WHERE dirty=false') if int(native_version) >= number: sql(database, "INSERT INTO installer_migrations VALUES('" + component + "'," + str(number) + ",'" + checksum + "')") @@ -218,13 +661,19 @@ def verify(): if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--refresh-devices', action='store_true') + parser.add_argument('--sync-scope', action='store_true', help='refresh the Broker device scope and restart broker-owner, mosquitto only if it changed') parser.add_argument('--bootstrap', action='store_true') parser.add_argument('--verify', action='store_true') parser.add_argument('--pull', action='store_true') args = parser.parse_args() + # A fresh install has no generated secrets yet, so required Compose + # interpolation cannot run until configure() has created the .env file. + check_thingsvis_database(uninterpolated=True) env = configure() - if args.pull: pull_images() + check_thingsvis_database() + if args.pull: pull_images(env) if args.bootstrap: bootstrap() if args.refresh_devices: refresh(env) + if args.sync_scope: sync_scope(env) if args.verify: verify() print('Native service configuration prepared. Credentials remain in local .env and config/native/.') diff --git a/config/native/release_manifest.py b/config/native/release_manifest.py new file mode 100644 index 0000000..5664d79 --- /dev/null +++ b/config/native/release_manifest.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +"""Verify a signed ThingsPanel release manifest before any payload is used. + +The manifest is signed once the payload is frozen; the payload never embeds the +manifest's own digest, so installer, updater and management scripts do not +depend on each other circularly. + +Trust model +----------- +* The only trust anchor is an ECDSA P-256 public key supplied by the caller + (a pinned PEM file). Nothing inside the manifest or payload can introduce or + replace it. +* No root key ships with this repository. Without a configured root every + verification fails closed with ``TrustRootNotConfigured``. +* A valid signature is necessary but not sufficient: the publisher, version, + validity window, revocation list, and the exact set of files (path, size, + SHA-256) must all match. + +Signature format: DER ECDSA over SHA-256 of the exact manifest bytes, as produced by +``openssl dgst -sha256 -sign key.pem manifest.json > manifest.json.sig``. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path, PurePosixPath + +SCHEMA = "thingspanel.release-manifest.v1" +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_COMMIT = re.compile(r"^[0-9a-f]{40}$") +_CHUNK = 1024 * 1024 + + +class ManifestError(Exception): + """The manifest, its signature, or the payload cannot be trusted.""" + + def __init__(self, reason: str, detail: str = ""): + super().__init__(f"{reason}: {detail}" if detail else reason) + self.reason = reason + + +class TrustRootNotConfigured(ManifestError): + def __init__(self, detail: str = ""): + super().__init__("trust_root_not_configured", detail) + + +def _openssl() -> str: + path = shutil.which("openssl") + if not path: + raise ManifestError("openssl_unavailable", "openssl is required to verify release signatures") + return path + + +def load_trust_root(path: os.PathLike | str | None) -> Path: + """Return the pinned root key path, or fail closed when none is configured.""" + if not path: + raise TrustRootNotConfigured("no release trust root was provided") + root = Path(path) + if not root.is_file(): + raise TrustRootNotConfigured(f"trust root file not found: {root}") + text = root.read_text(encoding="utf-8", errors="replace") + if "BEGIN PUBLIC KEY" not in text: + raise TrustRootNotConfigured("trust root is not a PEM public key") + proc = subprocess.run( + [_openssl(), "pkey", "-pubin", "-in", str(root), "-text", "-noout"], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0: + raise TrustRootNotConfigured("trust root is not a readable public key") + if "prime256v1" not in proc.stdout and "P-256" not in proc.stdout: + raise TrustRootNotConfigured("trust root must be an ECDSA P-256 public key") + return root + + +def verify_signature(manifest: bytes, signature: bytes, root: Path) -> None: + with tempfile.TemporaryDirectory(prefix="tp-manifest-") as tmp: + manifest_path = Path(tmp) / "manifest" + signature_path = Path(tmp) / "signature" + manifest_path.write_bytes(manifest) + signature_path.write_bytes(signature) + proc = subprocess.run( + [_openssl(), "dgst", "-sha256", "-verify", str(root), "-signature", str(signature_path), str(manifest_path)], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0 or "Verified OK" not in proc.stdout: + raise ManifestError("bad_signature", "manifest signature does not verify against the pinned trust root") + + +def _parse(manifest: bytes) -> dict: + try: + doc = json.loads(manifest.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ManifestError("malformed_manifest", str(exc)) from exc + if not isinstance(doc, dict) or doc.get("schema") != SCHEMA: + raise ManifestError("malformed_manifest", "unsupported schema") + release = doc.get("release") + files = doc.get("files") + if not isinstance(release, dict) or not isinstance(files, list) or not files: + raise ManifestError("malformed_manifest", "release and a non-empty files list are required") + for key in ("version", "publisher"): + if not isinstance(release.get(key), str) or not release[key]: + raise ManifestError("malformed_manifest", f"release.{key} is required") + if not isinstance(release.get("commit"), str) or not _COMMIT.match(release["commit"]): + raise ManifestError("malformed_manifest", "release.commit must be a 40-hex commit id") + for key in ("not_before", "expires_at"): + if not isinstance(release.get(key), int) or isinstance(release.get(key), bool): + raise ManifestError("malformed_manifest", f"release.{key} must be an integer epoch") + return doc + + +def _clean_path(raw: object) -> str: + if not isinstance(raw, str) or not raw or "\\" in raw or "\x00" in raw: + raise ManifestError("bad_path", f"invalid payload path: {raw!r}") + pure = PurePosixPath(raw) + if pure.is_absolute() or any(part in ("", ".", "..") for part in pure.parts) or str(pure) != raw: + raise ManifestError("bad_path", f"payload path must be a clean relative path: {raw!r}") + return raw + + +def _sha256(path: Path) -> tuple[str, int]: + digest = hashlib.sha256() + size = 0 + with path.open("rb") as handle: + while True: + chunk = handle.read(_CHUNK) + if not chunk: + break + digest.update(chunk) + size += len(chunk) + return digest.hexdigest(), size + + +def _walk(payload: Path) -> set[str]: + found: set[str] = set() + for current, dirs, names in os.walk(payload, followlinks=False): + for name in list(dirs) + names: + if (Path(current) / name).is_symlink(): + raise ManifestError("unexpected_symlink", f"symlink in payload: {Path(current) / name}") + for name in names: + found.add(Path(current, name).relative_to(payload).as_posix()) + return found + + +def _verify_header(manifest, signature, trust_root, *, expected_publisher, expected_version, revoked_versions, now): + """Signature, identity, validity window and parsed file table (path -> (sha256, size)).""" + root = load_trust_root(trust_root) + verify_signature(manifest, signature, root) + doc = _parse(manifest) + release = doc["release"] + + if release["publisher"] != expected_publisher: + raise ManifestError("wrong_publisher", f"manifest publisher {release['publisher']!r} is not the expected one") + if expected_version is not None and release["version"] != expected_version: + raise ManifestError("version_mismatch", f"manifest version {release['version']!r} != {expected_version!r}") + if release["version"] in revoked_versions or release["version"] in set(doc.get("revoked_versions") or []): + raise ManifestError("revoked", f"release {release['version']!r} has been withdrawn") + current = int(time.time()) if now is None else now + if current < release["not_before"]: + raise ManifestError("not_yet_valid", "release is not valid yet") + if current >= release["expires_at"]: + raise ManifestError("expired", "release manifest has expired") + + expected: dict[str, tuple[str, int]] = {} + for entry in doc["files"]: + if not isinstance(entry, dict): + raise ManifestError("malformed_manifest", "file entries must be objects") + rel = _clean_path(entry.get("path")) + digest, size = entry.get("sha256"), entry.get("size") + if not isinstance(digest, str) or not _HEX64.match(digest) or not isinstance(size, int) or isinstance(size, bool) or size < 0: + raise ManifestError("malformed_manifest", f"bad digest or size for {rel}") + if rel in expected: + raise ManifestError("malformed_manifest", f"duplicate path {rel}") + expected[rel] = (digest, size) + return doc, expected + + +def verify_release( + manifest: bytes, + signature: bytes, + trust_root: os.PathLike | str | None, + payload_dir: os.PathLike | str, + *, + expected_publisher: str, + expected_version: str | None = None, + revoked_versions: frozenset[str] | set[str] = frozenset(), + now: int | None = None, +) -> dict: + """Verify signature, identity, validity window and the exact payload contents. + + Returns the parsed manifest. Raises ``ManifestError`` (or ``TrustRootNotConfigured``) + on any mismatch; callers must not run or install payload files in that case. + """ + doc, expected = _verify_header( + manifest, signature, trust_root, + expected_publisher=expected_publisher, expected_version=expected_version, + revoked_versions=revoked_versions, now=now, + ) + payload = Path(payload_dir) + if not payload.is_dir(): + raise ManifestError("missing_payload", f"payload directory not found: {payload}") + actual = _walk(payload) + missing = sorted(set(expected) - actual) + if missing: + raise ManifestError("missing_file", ", ".join(missing)) + extra = sorted(actual - set(expected)) + if extra: + raise ManifestError("unlisted_file", ", ".join(extra)) + for rel, (digest, size) in sorted(expected.items()): + got_digest, got_size = _sha256(payload / rel) + if got_size != size or got_digest != digest: + raise ManifestError("digest_mismatch", rel) + return doc + + +def verify_files( + manifest: bytes, + signature: bytes, + trust_root: os.PathLike | str | None, + files: dict[str, os.PathLike | str], + *, + expected_publisher: str, + expected_version: str | None = None, + revoked_versions: frozenset[str] | set[str] = frozenset(), + now: int | None = None, +) -> dict: + """Verify a subset of a release: every given file must be listed with matching size and SHA-256. + + ``files`` maps a manifest path to the local copy (for example an updater's staged files). A file the + manifest does not list, or a symlink, is rejected; listed files that are not given are not checked. + """ + doc, expected = _verify_header( + manifest, signature, trust_root, + expected_publisher=expected_publisher, expected_version=expected_version, + revoked_versions=revoked_versions, now=now, + ) + if not files: + raise ManifestError("malformed_manifest", "no files were given to verify") + for rel in sorted(files): + _clean_path(rel) + local = Path(files[rel]) + if rel not in expected: + raise ManifestError("unlisted_file", rel) + if local.is_symlink() or not local.is_file(): + raise ManifestError("missing_file", rel) + digest, size = expected[rel] + got_digest, got_size = _sha256(local) + if got_size != size or got_digest != digest: + raise ManifestError("digest_mismatch", rel) + return doc + + +def _main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description="Verify a signed ThingsPanel release manifest") + parser.add_argument("--trust-root", required=False, help="pinned ECDSA P-256 public key (PEM)") + parser.add_argument("--manifest", required=True) + parser.add_argument("--signature", required=True) + parser.add_argument("--payload", required=True) + parser.add_argument("--publisher", required=True) + parser.add_argument("--version") + parser.add_argument("--revoked", action="append", default=[]) + args = parser.parse_args(argv) + try: + doc = verify_release( + Path(args.manifest).read_bytes(), + Path(args.signature).read_bytes(), + args.trust_root, + args.payload, + expected_publisher=args.publisher, + expected_version=args.version, + revoked_versions=set(args.revoked), + ) + except ManifestError as exc: + print(f"release verification failed: {exc}", file=sys.stderr) + return 2 + print(f"release {doc['release']['version']} verified ({len(doc['files'])} files)") + return 0 + + +if __name__ == "__main__": + sys.exit(_main(sys.argv[1:])) diff --git a/config/native/test_backend_database_guard_candidate.py b/config/native/test_backend_database_guard_candidate.py new file mode 100644 index 0000000..08d146f --- /dev/null +++ b/config/native/test_backend_database_guard_candidate.py @@ -0,0 +1,192 @@ +"""Focused tests for the native pre-bootstrap backend datasource guard.""" +import copy +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('native_prepare_guard', ROOT / 'config/native/prepare.py') +prepare = importlib.util.module_from_spec(spec) +spec.loader.exec_module(prepare) + + +def render(): + text = (ROOT / 'docker-compose.yml').read_text() + env = os.environ.copy() + for name in re.findall(r'\$\{([A-Z0-9_]+):\?', text): + env[name] = 'synthetic-fixture' + proc = subprocess.run(['docker', 'compose', 'config', '--format', 'json'], cwd=ROOT, + env=env, text=True, capture_output=True, check=True) + return json.loads(proc.stdout) + + +class BackendDatabaseGuard(unittest.TestCase): + @classmethod + def setUpClass(cls): cls.config = render() + + def check(self, cfg): + with patch.object(prepare, 'command', return_value=json.dumps(cfg)): + prepare.check_thingsvis_database() + + def test_shipped_pg_compose_is_accepted(self): + self.check(self.config) + + def test_shipped_backend_has_matching_a1_postgres_settings(self): + env = self.config['services']['backend']['environment'] + self.assertEqual(env['GOTP_RELATIONAL_DRIVER'], 'postgres') + self.assertEqual(env['GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST'], 'postgres') + self.assertEqual(env['GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT'], '5432') + self.assertEqual(env['GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE'], 'ThingsPanel') + self.assertEqual(env['GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME'], 'postgres') + + def test_a1_profile_missing_required_setting_is_rejected(self): + cfg = copy.deepcopy(self.config) + del cfg['services']['backend']['environment']['GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST'] + with self.assertRaisesRegex(RuntimeError, 'Cannot confirm'): + self.check(cfg) + + def test_legacy_only_compose_remains_upgrade_compatible(self): + cfg = copy.deepcopy(self.config) + env = cfg['services']['backend']['environment'] + for key in tuple(env): + if key.startswith('GOTP_RELATIONAL_'): + del env[key] + self.check(cfg) + + def test_explicit_mysql_backend_with_pg_vis_is_rejected(self): + cfg = copy.deepcopy(self.config) + cfg['services']['backend']['environment']['GOTP_DB_MYSQL_HOST'] = 'synthetic-mysql' + with self.assertRaisesRegex(RuntimeError, 'MySQL backend'): self.check(cfg) + + def test_mysql_driver_with_pg_fields_is_rejected(self): + for selector in ('GOTP_DB_DRIVER', 'DB_TYPE', 'GOTP_DB_TYPE', 'DATABASE_TYPE', 'GOTP_DB_PSQL_DBTYPE'): + with self.subTest(selector=selector): + cfg = copy.deepcopy(self.config) + cfg['services']['backend']['environment'][selector] = 'mysql' + with self.assertRaisesRegex(RuntimeError, 'Cannot confirm'): self.check(cfg) + + def test_unrelated_mysql_environment_does_not_override_pg(self): + cfg = copy.deepcopy(self.config) + cfg['services']['backend']['environment']['MYSQL_EXPORTER_NOTE'] = 'synthetic' + self.check(cfg) + + def test_unresolved_host_is_not_treated_as_external_pg(self): + cfg = copy.deepcopy(self.config) + cfg['services']['backend']['environment']['GOTP_DB_PSQL_HOST'] = '${DATABASE_HOST}' + with self.assertRaisesRegex(RuntimeError, 'Cannot confirm'): + self.check(cfg) + + def test_upgrade_rejects_symlinked_compose_before_download(self): + with tempfile.TemporaryDirectory(prefix='tp-b-symlink-guard-') as directory: + root = Path(directory) + script = root / 'upgrade.sh' + script.write_bytes((ROOT / 'upgrade.sh').read_bytes()) + real = root / 'original-compose' + real.write_text('synthetic original') + (root / 'docker-compose.yml').symlink_to(real) + curl = root / 'curl' + curl.write_text('#!/bin/sh\necho called > "$TP_FIXTURE_CURL_LOG"\nexit 42\n') + curl.chmod(0o755) + env = os.environ.copy() + env.update(PATH=str(root) + os.pathsep + env['PATH'], TP_FIXTURE_CURL_LOG=str(root / 'curl.log')) + proc = subprocess.run(['bash', str(script), 'v-test'], cwd=root, env=env, capture_output=True, text=True, timeout=30) + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(real.read_text(), 'synthetic original') + self.assertFalse((root / 'curl.log').exists()) + + def test_install_rejects_symlinked_install_directory(self): + with tempfile.TemporaryDirectory(prefix='tp-b-rootlink-guard-') as directory: + root = Path(directory) + script = root / 'install.bash' + script.write_bytes((ROOT / 'install.bash').read_bytes()) + target = root / 'real' + target.mkdir() + link = root / 'install-link' + link.symlink_to(target, target_is_directory=True) + docker = root / 'docker' + docker.write_text('#!/bin/sh\nif [ "$1" = version ]; then echo 25.0.0; exit 0; fi\nif [ "$1" = compose ] && [ "$2" = version ]; then echo 2.20.0; exit 0; fi\nexit 99\n') + docker.chmod(0o755) + env = os.environ.copy() + env.update(PATH=str(root) + os.pathsep + env['PATH'], INSTALL_DIR=str(link)) + proc = subprocess.run(['bash', str(script)], cwd=root, env=env, capture_output=True, text=True, timeout=30) + self.assertNotEqual(proc.returncode, 0) + self.assertIn('旧配置未修改', proc.stderr) + self.assertEqual(list(target.iterdir()), []) + + def test_missing_pg_backend_or_required_postgres_service_rejected(self): + for change in ('backend', 'postgres'): + with self.subTest(missing=change): + cfg=copy.deepcopy(self.config); del cfg['services'][change] + with self.assertRaisesRegex(RuntimeError, 'Cannot confirm'): self.check(cfg) + + def test_external_pg_host_not_rejected_merely_for_missing_local_service(self): + cfg=copy.deepcopy(self.config) + cfg['services']['backend']['environment']['GOTP_DB_PSQL_HOST']='synthetic-external-pg' + cfg['services']['backend']['environment']['GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST']='synthetic-external-pg' + del cfg['services']['postgres'] + self.check(cfg) + + def test_mysql_thingsvis_still_rejected_without_leaking_url(self): + cfg=copy.deepcopy(self.config) + cfg['services']['thingsvis-server']['environment']['DATABASE_URL']='mysql://synthetic-secret@fixture/database' + with self.assertRaises(RuntimeError) as error:self.check(cfg) + self.assertNotIn('synthetic-secret',str(error.exception)) + + def test_duplicate_list_environment_rejected(self): + cfg=copy.deepcopy(self.config); values=cfg['services']['backend']['environment'] + cfg['services']['backend']['environment']=[f'{key}={value}' for key,value in values.items()]+['GOTP_DB_PSQL_HOST=other'] + with self.assertRaisesRegex(RuntimeError, 'Cannot confirm'): self.check(cfg) + + def test_cli_rejects_backend_before_creating_configuration(self): + cfg = copy.deepcopy(self.config) + cfg['services']['backend']['environment']['GOTP_DB_MYSQL_HOST'] = 'synthetic-mysql' + with tempfile.TemporaryDirectory(prefix='tp-b-backend-guard-') as directory: + root = Path(directory) + script = root / 'config/native/prepare.py' + script.parent.mkdir(parents=True) + script.write_bytes((ROOT / 'config/native/prepare.py').read_bytes()) + docker = root / 'docker' + docker.write_text('#!/bin/sh\nprintf "%s" "$TP_FIXTURE_COMPOSE"\n') + docker.chmod(0o755) + env = os.environ.copy() + env.update(PATH=str(root) + os.pathsep + env['PATH'], TP_FIXTURE_COMPOSE=json.dumps(cfg)) + proc = subprocess.run(['python3', str(script), '--bootstrap'], cwd=root, + env=env, capture_output=True, text=True, timeout=30) + self.assertNotEqual(proc.returncode, 0) + self.assertIn('MySQL backend', proc.stderr) + self.assertFalse((root / '.env').exists()) + self.assertFalse((root / 'config/native/plugin-token').exists()) + + def test_linux_entries_reject_old_mysql_backend_before_download_or_overwrite(self): + cfg = copy.deepcopy(self.config) + cfg['services']['backend']['environment']['DB_TYPE'] = 'mysql' + for entry in ('install.bash', 'upgrade.sh'): + with self.subTest(entry=entry), tempfile.TemporaryDirectory(prefix='tp-b-entry-guard-') as directory: + root = Path(directory) + target = root / entry + target.write_bytes((ROOT / entry).read_bytes()) + compose = root / 'docker-compose.yml' + compose.write_text('existing synthetic compose\n') + before = compose.read_bytes() + docker = root / 'docker' + docker.write_text('#!/bin/sh\nif [ "$1" = version ]; then echo 25.0.0; exit 0; fi\nif [ "$1" = compose ] && [ "$2" = version ]; then echo 2.20.0; exit 0; fi\nif [ "$1" = compose ] && [ "$2" = config ]; then printf "%s" "$TP_FIXTURE_COMPOSE"; exit 0; fi\nexit 99\n') + docker.chmod(0o755) + curl = root / 'curl' + curl.write_text('#!/bin/sh\necho called >> "$TP_FIXTURE_CURL_LOG"\nexit 42\n') + curl.chmod(0o755) + env = os.environ.copy() + env.update(PATH=str(root) + os.pathsep + env['PATH'], INSTALL_DIR=str(root), TMPDIR=str(root), + TP_FIXTURE_COMPOSE=json.dumps(cfg), TP_FIXTURE_CURL_LOG=str(root/'curl.log')) + args=['bash',str(target)] + (['v-test'] if entry == 'upgrade.sh' else []) + proc=subprocess.run(args,cwd=root,env=env,capture_output=True,text=True,timeout=30) + self.assertNotEqual(proc.returncode,0) + self.assertEqual(compose.read_bytes(),before) + self.assertFalse((root/'curl.log').exists()) + +if __name__ == '__main__': unittest.main() diff --git a/config/native/test_prepare_command_redaction.py b/config/native/test_prepare_command_redaction.py new file mode 100644 index 0000000..eea59f5 --- /dev/null +++ b/config/native/test_prepare_command_redaction.py @@ -0,0 +1,26 @@ +import subprocess +import unittest +from unittest import mock + +from config.native import prepare + + +class CommandRedactionTest(unittest.TestCase): + def test_error_does_not_expose_subprocess_arguments_or_stderr(self): + secret = 'fixture-password-do-not-use' + result = subprocess.CompletedProcess([], 17, stdout=b'', stderr=f'FATAL: database URL postgres://user:{secret}@host/db'.encode()) + with mock.patch.object(prepare.subprocess, 'run', return_value=result): + with self.assertRaises(RuntimeError) as caught: + prepare.command('docker', 'compose', secret, 'config') + self.assertNotIn(secret, str(caught.exception)) + self.assertNotIn('postgres://', str(caught.exception)) + self.assertIn('17', str(caught.exception)) + + def test_success_returns_command_output(self): + result = subprocess.CompletedProcess([], 0, stdout=b'output\n', stderr=b'') + with mock.patch.object(prepare.subprocess, 'run', return_value=result): + self.assertEqual(prepare.command('fixture'), 'output') + + +if __name__ == '__main__': + unittest.main() diff --git a/config/native/test_thingsvis_profile.py b/config/native/test_thingsvis_profile.py new file mode 100644 index 0000000..57a7e92 --- /dev/null +++ b/config/native/test_thingsvis_profile.py @@ -0,0 +1,194 @@ +import importlib.util +import json +import os +import re +from pathlib import Path +import shutil +import shlex +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).with_name('prepare.py') +spec = importlib.util.spec_from_file_location('native_prepare', SCRIPT) +prepare = importlib.util.module_from_spec(spec) +spec.loader.exec_module(prepare) + + +class ThingsVisDatabaseGuardTest(unittest.TestCase): + def configuration(self, url): + # The existing entry guards now require both platform and ThingsVis + # datasource evidence. A ThingsVis-only fixture is unknown, not PG. + return {'services': {'thingsvis-server': {'environment': {'DATABASE_URL': url}}, + 'backend': {'environment': {'GOTP_DB_PSQL_HOST': 'postgres', + 'GOTP_DB_PSQL_PORT': '5432', 'GOTP_DB_PSQL_USERNAME': 'postgres', + 'GOTP_DB_PSQL_DBNAME': 'ThingsPanel'}}, 'postgres': {}}} + + def test_postgresql_schemes_are_allowed(self): + for url in ('postgres://example/db', 'postgresql://example/db?schema=thingsvis'): + with self.subTest(url=url): + prepare.validate_thingsvis_database(self.configuration(url)) + + + def test_mysql_and_missing_configuration_are_rejected_without_echoing_values(self): + for config in (self.configuration('mysql://example-secret@example/db'), + self.configuration(None), {'services': {}}): + with self.subTest(config=config): + with self.assertRaises(RuntimeError) as result: + prepare.validate_thingsvis_database(config) + self.assertNotIn('example-secret', str(result.exception)) + + def test_actual_compose_renders_a_supported_url(self): + root = SCRIPT.parents[2] + result = subprocess.run(['docker', 'compose', '-f', str(root / 'docker-compose.yml'), + 'config', '--no-interpolate', '--format', 'json'], check=True, capture_output=True, text=True) + prepare.validate_thingsvis_database(json.loads(result.stdout)) + + env = os.environ.copy() + for key in ('TP_AUTOMATION_TOKEN', 'TP_MQTT_USER', 'TP_MQTT_PASSWORD', + 'TP_JWT_KEY', 'TP_BROKER_DATABASE_DSN', 'TP_NATIVE_DB_PASSWORD', + 'TP_PROTOCOL_MQTT_USER', 'TP_PROTOCOL_MQTT_PASSWORD', + 'TP_NOTIFICATION_KEYRING_B64', 'TP_THINGSVIS_AUTH_SECRET', 'TP_MARKETINSTALL_PROVIDER_TOKEN', + 'TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN', 'TP_MARKETINSTALL_THINGSVIS_TOKEN'): + env[key] = 'synthetic-test-value' + resolved = subprocess.run(['docker', 'compose', '-f', str(root / 'docker-compose.yml'), + 'config', '--format', 'json'], check=True, capture_output=True, text=True, env=env) + prepare.validate_thingsvis_database(json.loads(resolved.stdout)) + + def test_cli_rejects_mysql_before_creating_configuration(self): + with tempfile.TemporaryDirectory(prefix='thingsvis-guard-test-') as directory: + root = Path(directory) + script = root / 'config' / 'native' / 'prepare.py' + script.parent.mkdir(parents=True) + shutil.copyfile(SCRIPT, script) + fake_docker = root / 'docker' + fake_docker.write_text('#!/bin/sh\nprintf "%s" "$TP_TEST_COMPOSE_JSON"\n') + fake_docker.chmod(0o755) + env = os.environ.copy() + env['PATH'] = str(root) + os.pathsep + env['PATH'] + env['TP_TEST_COMPOSE_JSON'] = json.dumps(self.configuration('mysql://private-value@example/db')) + result = subprocess.run(['python3', str(script), '--bootstrap'], env=env, + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('only a PostgreSQL datasource', result.stderr) + self.assertNotIn('private-value', result.stderr + result.stdout) + self.assertFalse((root / '.env').exists()) + self.assertFalse((root / 'config' / 'native' / 'plugin-token').exists()) + + def test_unix_install_and_upgrade_check_old_compose_before_network_or_backup(self): + repo = SCRIPT.parents[2] + for entry in ('install.bash', 'upgrade.sh'): + for scheme in ('mysql', 'postgresql'): + with self.subTest(entry=entry, scheme=scheme), tempfile.TemporaryDirectory(prefix='tp-entry-guard-') as directory: + root = Path(directory) + target = root / entry + shutil.copyfile(repo / entry, target) + compose = root / 'docker-compose.yml' + compose.write_text('synthetic old compose - must be retained\n') + before = compose.read_bytes() + bin_dir = root / 'bin' + bin_dir.mkdir() + docker = bin_dir / 'docker' + docker.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$TP_TEST_DOCKER_LOG"\n' + 'if [ "$1" = version ]; then echo 25.0.0; exit 0; fi\n' + 'if [ "$1" = compose ] && [ "$2" = version ]; then echo 2.20.0; exit 0; fi\n' + 'if [ "$1" = compose ] && [ "$2" = config ]; then printf "%s" "$TP_TEST_COMPOSE_JSON"; exit 0; fi\n' + 'exit 99\n') + docker.chmod(0o755) + curl = bin_dir / 'curl' + curl.write_text('#!/bin/sh\nprintf "called\\n" >> "$TP_TEST_CURL_LOG"\nexit 42\n') + curl.chmod(0o755) + env = os.environ.copy() + env.update(PATH=str(bin_dir) + os.pathsep + env['PATH'], INSTALL_DIR=str(root), TMPDIR=str(root), + TP_TEST_DOCKER_LOG=str(root / 'docker.log'), TP_TEST_CURL_LOG=str(root / 'curl.log'), + TP_TEST_COMPOSE_JSON=json.dumps(self.configuration(scheme + '://sensitive-marker@example/db'))) + args = ['bash', str(target)] + (['v-test'] if entry == 'upgrade.sh' else []) + result = subprocess.run(args, env=env, cwd=root, capture_output=True, text=True, timeout=30) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(compose.read_bytes(), before) + self.assertNotIn('sensitive-marker', result.stdout + result.stderr) + calls = (root / 'docker.log').read_text().splitlines() + self.assertTrue(any(line.startswith('compose config ') for line in calls)) + self.assertFalse(any(line.startswith(('compose up', 'compose down', 'pull')) for line in calls)) + if scheme == 'mysql': + self.assertFalse((root / 'curl.log').exists()) + self.assertFalse(list(root.glob('docker-compose.yml.bak.*'))) + else: + self.assertTrue((root / 'curl.log').exists(), 'valid PostgreSQL should pass the guard') + + def test_unix_entries_with_historical_compose_and_mysql_variant(self): + repo = SCRIPT.parents[2] + real_docker = shutil.which('docker') + self.assertIsNotNone(real_docker) + for tag in ('v1.1.13.6', 'v1.2.12.1'): + original = subprocess.run(['git', '-C', str(repo), 'show', tag + ':docker-compose.yml'], + check=True, capture_output=True, text=True).stdout + url_pattern = r'(DATABASE_URL\s*(?:=|:\s*))postgresql://' + self.assertRegex(original, url_pattern) + for scheme in ('postgresql', 'mysql'): + content = re.sub(url_pattern, lambda match: match.group(1) + scheme + '://', original) + for entry in ('install.bash', 'upgrade.sh'): + with self.subTest(tag=tag, scheme=scheme, entry=entry), tempfile.TemporaryDirectory(prefix='tp-history-guard-') as directory: + root = Path(directory) + script = root / entry + shutil.copyfile(repo / entry, script) + compose = root / 'docker-compose.yml' + compose.write_text(content) + bin_dir = root / 'bin' + bin_dir.mkdir() + docker = bin_dir / 'docker' + docker.write_text('#!/bin/sh\n' + 'if [ "$1" = version ]; then echo 25.0.0; exit 0; fi\n' + 'if [ "$1" = compose ] && [ "$2" = version ]; then echo 2.20.0; exit 0; fi\n' + 'if [ "$1" = compose ] && [ "$2" = config ]; then exec ' + shlex.quote(real_docker) + ' "$@"; fi\n' + 'exit 99\n') + docker.chmod(0o755) + curl = bin_dir / 'curl' + curl.write_text('#!/bin/sh\nprintf "called\\n" >> "$TP_TEST_CURL_LOG"\nexit 42\n') + curl.chmod(0o755) + env = os.environ.copy() + env.pop('COMPOSE_FILE', None) + env.update(PATH=str(bin_dir) + os.pathsep + env['PATH'], INSTALL_DIR=str(root), TMPDIR=str(root), + POSTGRES_PASSWORD='synthetic-test-password', TP_TEST_CURL_LOG=str(root / 'curl.log')) + for required in re.findall(r'\$\{([A-Z0-9_]+):\?', content): + env[required] = 'synthetic-test-value' + args = ['bash', str(script)] + (['v-test'] if entry == 'upgrade.sh' else []) + result = subprocess.run(args, env=env, cwd=root, capture_output=True, text=True, timeout=30) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(compose.read_text(), content) + self.assertNotIn('synthetic-test-password', result.stdout + result.stderr) + if scheme == 'mysql': + self.assertFalse((root / 'curl.log').exists()) + self.assertFalse(list(root.glob('docker-compose.yml.bak.*'))) + else: + self.assertTrue((root / 'curl.log').exists(), 'historical PostgreSQL must pass the guard') + + +class BackendDatabaseGuardTest(unittest.TestCase): + def configuration(self, *, host='postgres', password='postgresThingsPanel'): + env = { + 'GOTP_DB_PSQL_HOST': host, + 'GOTP_DB_PSQL_PORT': '5432', + 'GOTP_DB_PSQL_USERNAME': 'postgres', + 'GOTP_DB_PSQL_DBNAME': 'ThingsPanel', + 'GOTP_RELATIONAL_DRIVER': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST': host, + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT': '5432', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE': 'ThingsPanel', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD': password, + } + return {'services': {'backend': {'environment': env}, 'postgres': {}}} + + def test_unresolved_password_is_allowed_before_generated_env_secrets_exist(self): + prepare.validate_supported_backend_database( + self.configuration(password='${TP_DATABASE_PASSWORD:-postgresThingsPanel}')) + + def test_unresolved_database_location_is_not_allowed(self): + with self.assertRaisesRegex(RuntimeError, 'supported PostgreSQL'): + prepare.validate_supported_backend_database(self.configuration(host='${DATABASE_HOST:-postgres}')) + + +if __name__ == '__main__': + unittest.main() diff --git a/config/native/update.py b/config/native/update.py new file mode 100644 index 0000000..c73c483 --- /dev/null +++ b/config/native/update.py @@ -0,0 +1,1356 @@ +#!/usr/bin/env python3 +"""One configuration transaction for the existing ThingsPanel installer. + +The reviewed entry points pin this file's SHA-256 before executing it. Payload +downloads retain the installer's HTTPS distribution trust; this is not a new +package-signing system. Never execute a downloaded prepare.py to validate it. +Configuration recovery ends at activation: database and service effects are +deliberately not called a rollback of files. +""" +import argparse +import ast +import contextlib +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import sys +import tempfile +from urllib.parse import urlsplit +import uuid +import urllib.request +import urllib.error + + +class UpdateError(RuntimeError): + pass + + +# Signed release verification (optional until a release trust root is supplied). +# The verifier is loaded only if its SHA-256 equals this pin, which is itself +# covered by the entry points' pin of this file. +RELEASE_VERIFIER = 'config/native/release_manifest.py' +RELEASE_VERIFIER_SHA256 = "717abbe4a5a52e949042913d5aec5ea349ce41ce1afab814965eecae717b9374" +RELEASE_MANIFEST = 'release-manifest.json' +DEFAULT_RELEASE_PUBLISHER = 'https://github.com/ThingsPanel/thingspanel-installer/.github/workflows/release.yml' + +# Independent plugin trust anchor, reviewed with the installer source. The +# signed plugin catalog is never allowed to introduce or replace this key. +PLUGIN_TRUST_PEM = b'''-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEx5sN5wE3uKMeQNg/GfwdgdECr3Dl +HwERLCSb0Ng2n3l4djp5nlaxGQdYZFcwGZJ0UhdPyohfgnwpGnu6eZKicw== +-----END PUBLIC KEY----- +''' +# Helpers are independently pinned by the entry-point-pinned updater. Keep old +# profiles here when changing helper code so an offline last-good bundle can +# still be restored by a later updater. +PLUGIN_HELPER_PROFILES = ({ + 'tools/plugin_bundle.py': 'a8fa326430c7433b20dc2cc699b115063be5e498a6a45f533dcf395a34a0ecfa', + 'tools/plugin_catalog.py': 'fe0c4c4cb5ab9af8bfb08d0003e112c07d87680e62d8017b3d0996fdae0cca21', + 'config/native/release_manifest.py': '717abbe4a5a52e949042913d5aec5ea349ce41ce1afab814965eecae717b9374', + 'tools/agent_host.py': '037dd423bab55cf48b56b27eca736e28eb1e05a6cd75e4a425586b3ac56705f9', + 'tools/scope_sync.py': 'f995ff0d2fdc23225aadceb9be78709493fd1a5f8f6094173086d63e8cf5e4c1', +},) + + +COMMON = ( + ('docker-compose.yml', 0o644), ('niginx.conf', 0o644), + ('config/native/prepare.py', 0o644), + ('config/native/runtime.encore.json', 0o644), + ('config/native/runtime.notification.json', 0o644), + ('config/native/tick.sh', 0o644), ('config/native/README.md', 0o644), +) +LEGACY_WATCHED = ('.env', 'config/native/plugin-token') +ACTIVATION_FILES = ('.env', 'config/native/broker/plugin-token', + 'config/native/broker/owner-tokens.json', 'config/native/broker/services.json') +WATCHED = LEGACY_WATCHED + ('config/native/owner-tokens.json', 'config/native/services.json') + ACTIVATION_FILES[1:] + + +def make_directories(path, mode=0o755): + """Persist each new directory entry, including the stage/backup parents.""" + missing = [] + current = path + while not current.exists(): + missing.append(current) + current = current.parent + for current in reversed(missing): + current.mkdir(mode=mode) + fsync_directory(current.parent) + + +def fsync_directory(path): + if os.name == 'nt': + # Windows replacements use MOVEFILE_WRITE_THROUGH below. File content + # is flushed before each replacement. POSIX directory fds are not + # supported on Windows; do not pretend os.fsync(open(directory)) works. + return + fd = os.open(str(path), os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0)) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def replace(source, destination): + if os.name == 'nt': + import ctypes + move = ctypes.WinDLL('kernel32', use_last_error=True).MoveFileExW + move.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint] + move.restype = ctypes.c_int + previous_mode = None + if destination.exists(): + previous_mode = stat.S_IMODE(destination.stat().st_mode) + if not previous_mode & stat.S_IWRITE: + # Windows represents the broker's POSIX 0440 mode as the + # read-only file attribute. Clear it only for the atomic + # replacement and restore it if replacement fails. + os.chmod(destination, previous_mode | stat.S_IWRITE) + if not move(str(source), str(destination), 0x1 | 0x8): + error_code = ctypes.get_last_error() + if previous_mode is not None and not previous_mode & stat.S_IWRITE: + os.chmod(destination, previous_mode) + raise ctypes.WinError(error_code) + else: + os.replace(source, destination) + fsync_directory(destination.parent) + + +def private_directory(path): + if path.exists() or path.is_symlink(): + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or path.is_symlink(): + raise UpdateError('Update state path is not a real directory') + if os.name != 'nt' and (info.st_mode & 0o077): + raise UpdateError('Update state directory must be private') + else: + path.mkdir(mode=0o700) + fsync_directory(path.parent) + + +def file_info(path): + """Read a regular file without following its final symlink; no bytes logged.""" + try: + before = path.lstat() + except FileNotFoundError: + return None + if not stat.S_ISREG(before.st_mode) or stat.S_ISLNK(before.st_mode): + raise UpdateError('A managed file is not a regular file: ' + path.name) + fd = os.open(str(path), os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + try: + opened = os.fstat(fd) + if (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino): + raise UpdateError('A managed file changed while being read: ' + path.name) + digest = hashlib.sha256() + while True: + block = os.read(fd, 1024 * 1024) + if not block: + break + digest.update(block) + after = os.fstat(fd) + if (opened.st_size, opened.st_mtime_ns, opened.st_mode) != (after.st_size, after.st_mtime_ns, after.st_mode): + raise UpdateError('A managed file changed while being read: ' + path.name) + return {'sha256': digest.hexdigest(), 'size': after.st_size, + 'mode': stat.S_IMODE(after.st_mode), 'uid': after.st_uid, + 'gid': after.st_gid} + finally: + os.close(fd) + + +def same(actual, expected): + if actual is None or expected is None: + return actual is expected + keys = ('sha256', 'size', 'mode') if os.name == 'nt' else ('sha256', 'size', 'mode', 'uid', 'gid') + return all(actual[key] == expected[key] for key in keys) + + +def safe_target(root, relative): + parts = relative.split('/') + if not parts or any(p in ('', '.', '..') for p in parts) or '\\' in relative: + raise UpdateError('Invalid managed path') + target = root + for part in parts[:-1]: + target = target / part + if target.is_symlink() or (target.exists() and not target.is_dir()): + raise UpdateError('A managed parent is not a real directory') + return target / parts[-1] + + +def durable_bytes(path, content, mode=0o600, ownership=None): + make_directories(path.parent) + fd, temporary = tempfile.mkstemp(prefix='.write-', dir=path.parent) + temporary = Path(temporary) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(content) + stream.flush() + # Keep the source writable until MoveFileExW has consumed it. + # Windows maps POSIX 0440 to a read-only attribute, which blocks + # both replacement and cleanup; apply the requested mode afterward. + if os.name != 'nt': + os.fchmod(stream.fileno(), mode) if hasattr(os, 'fchmod') else os.chmod(temporary, mode) + if ownership is not None and os.name != 'nt': + info = os.fstat(stream.fileno()) + if (info.st_uid, info.st_gid) != (ownership['uid'], ownership['gid']): + os.fchown(stream.fileno(), ownership['uid'], ownership['gid']) + os.fsync(stream.fileno()) + replace(temporary, path) + if os.name == 'nt': + os.chmod(path, mode) + finally: + if temporary.exists(): + temporary.unlink() + + +@contextlib.contextmanager +def update_lock(state): + path = state / 'lock' + if path.is_symlink() or (path.exists() and not path.is_file()): + raise UpdateError('Invalid update lock') + fd = os.open(str(path), os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0), 0o600) + try: + if os.name == 'nt': + import msvcrt + if os.fstat(fd).st_size == 0: + os.write(fd, b'0') + os.fsync(fd) + os.lseek(fd, 0, os.SEEK_SET) + try: + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + except OSError: + raise UpdateError('Another installer operation is active') from None + else: + import fcntl + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + raise UpdateError('Another installer operation is active') from None + yield + finally: + os.close(fd) # Kernel releases the lock even after process termination. + + +def command_environment(root): + # Every Compose invocation, including those in the existing prepare.py, + # must use the same reviewed Compose file and the original project .env. + # Preserve ordinary interpolation variables and COMPOSE_PROJECT_NAME. + env = os.environ.copy() + env['COMPOSE_FILE'] = str(root / 'docker-compose.yml') + env.pop('COMPOSE_ENV_FILES', None) + env.pop('COMPOSE_DISABLE_ENV_FILE', None) + return env + + +def run_command(args, root, *, data=None, extra_env=None): + env = command_environment(root) + if extra_env: + env.update(extra_env) + try: + result = subprocess.run(args, cwd=root, input=data, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, check=False, + env=env) + except OSError: + raise UpdateError('Required installer command could not be started') from None + if result.returncode: + # Compose/prepare errors can include an interpolated password or URL. + raise UpdateError('Installer command failed (exit %d)' % result.returncode) + return result.stdout + + +def environment(value): + if isinstance(value, dict): + return value + if isinstance(value, list): + result = {} + for item in value: + if not isinstance(item, str) or '=' not in item: + raise UpdateError('Cannot confirm supported PostgreSQL configuration') + key, val = item.split('=', 1) + if key in result: + raise UpdateError('Duplicate environment field') + result[key] = val + return result + raise UpdateError('Cannot confirm supported PostgreSQL configuration') + + +def validate_config(config): + """Keep the reviewed PG/unknown guard; no downloaded module is imported.""" + try: + services = config['services'] + vis = environment(services['thingsvis-server']['environment']) + backend_service = services['backend'] + backend = environment(backend_service['environment']) + url = vis['DATABASE_URL'] + parsed = urlsplit(url) + if parsed.scheme not in ('postgres', 'postgresql') or not parsed.hostname or '$' in parsed.hostname: + raise ValueError() + required = ('GOTP_DB_PSQL_HOST', 'GOTP_DB_PSQL_PORT', 'GOTP_DB_PSQL_USERNAME', 'GOTP_DB_PSQL_DBNAME') + if any(not isinstance(backend.get(k), (str, int)) or not str(backend[k]).strip() or '$' in str(backend[k]) for k in required): + raise ValueError() + if backend['GOTP_DB_PSQL_HOST'] == 'postgres' and not isinstance(services.get('postgres'), dict): + raise ValueError() + relational_required = ('GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST', 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE', 'GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD') + relational_keys = [key for key in backend if key.startswith('GOTP_RELATIONAL_')] + if relational_keys: + if backend.get('GOTP_RELATIONAL_DRIVER') != 'postgres': + raise ValueError() + if any(not isinstance(backend.get(k), (str, int)) or not str(backend[k]).strip() or '$' in str(backend[k]) for k in relational_required): + raise ValueError() + if backend['GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST'] == 'postgres' and not isinstance(services.get('postgres'), dict): + raise ValueError() + selectors = ('GOTP_RELATIONAL_DRIVER', 'GOTP_DB_PSQL_DBTYPE', 'GOTP_DB_DRIVER', 'GOTP_DB_PROVIDER', 'GOTP_DB_TYPE', + 'DB_DRIVER', 'DB_PROVIDER', 'DB_TYPE', 'DATABASE_TYPE', 'DATABASE_PROVIDER', 'DATABASE_DRIVER') + for key, value in backend.items(): + name = str(key).upper() + if name.startswith(('GOTP_DB_MYSQL_', 'GOTP_DB_MARIADB_')) and value not in (None, ''): + raise ValueError() + if name in selectors and str(value).lower() not in ('postgres', 'postgresql', 'pg'): + raise ValueError() + if name == 'DATABASE_URL' and (not isinstance(value, str) or urlsplit(value).scheme not in ('postgres', 'postgresql')): + raise ValueError() + except (KeyError, TypeError, ValueError, AttributeError): + raise UpdateError('Cannot confirm supported PostgreSQL backend and ThingsVis configuration') from None + + +def compose_config(root, compose, *, interpolate=True): + args = ['docker', 'compose', '--project-directory', str(root), '-f', str(compose)] + if (root / '.env').is_file(): + args += ['--env-file', str(root / '.env')] + args += ['config'] + if not interpolate: + args += ['--no-interpolate'] + args += ['--format', 'json'] + try: + value = json.loads(run_command(args, root)) + except (ValueError, UnicodeError): + raise UpdateError('Compose did not return valid JSON') from None + validate_config(value) + return value + + +def render_with_fallback(root, compose): + try: + return compose_config(root, compose) + except UpdateError: + return compose_config(root, compose, interpolate=False) + + +def download(url, path): + make_directories(path.parent) + if shutil.which('curl'): + args = ['curl', '-fsSL', '--connect-timeout', '15', '--max-time', '180', url, '-o', str(path)] + elif shutil.which('wget'): + args = ['wget', '-q', '--timeout=180', '-O', str(path), url] + else: + # Windows installations with Python but no curl.exe/wget do not need a + # second downloader dependency. Tests never reach a real network. + try: + with urllib.request.urlopen(url, timeout=180) as response, path.open('wb') as output: + size = 0 + while True: + block = response.read(1024 * 1024) + if not block: + break + size += len(block) + if size > 16 * 1024 * 1024: + raise UpdateError('Downloaded installer file is too large') + output.write(block) + except (urllib.error.URLError, OSError): + raise UpdateError('Installer file download failed') from None + args = None + if args is not None: + run_command(args, path.parent) + info = file_info(path) + if info is None or info['size'] == 0 or info['size'] > 16 * 1024 * 1024: + raise UpdateError('Downloaded installer file is empty or too large') + with path.open('rb+') as stream: + os.fsync(stream.fileno()) + fsync_directory(path.parent) + + +class Transaction: + def __init__(self, root, *, platform=None, downloader=download, + validator=None, checkpoint=None, release_policy=None): + # release_policy: None (no signature check) or a dict with 'trust_root', + # 'publisher' and 'revoked'. A policy without a usable trust root fails closed. + self.release_policy = release_policy + self.root = Path(os.path.abspath(root)) + if self.root.is_symlink() or (self.root.exists() and not self.root.is_dir()): + raise UpdateError('Install directory must be a real directory') + make_directories(self.root) + self.state = self.root / '.thingspanel-update' + private_directory(self.state) + self.journal = self.state / 'journal.json' + self.platform = platform or ('windows' if os.name == 'nt' else 'posix') + if self.platform not in ('windows', 'posix'): + raise UpdateError('Unsupported installer platform') + self.artifacts = list(COMMON) + ([(x, 0o644) for x in ('upgrade.ps1', 'uninstall.ps1')] + if self.platform == 'windows' else [(x, 0o755) for x in ('upgrade.sh', 'uninstall.sh')]) + self.artifacts += [('config/native/update.py', 0o644)] + self.downloader = downloader + self.validator = validator or self.validate + self.checkpoint = checkpoint or (lambda event: None) + + def save(self, data): + durable_bytes(self.journal, (json.dumps(data, sort_keys=True) + '\n').encode()) + + def load(self): + if file_info(self.journal) is None: + return None + try: + data = json.loads(self.journal.read_text(encoding='utf-8')) + if data['version'] != 1 or not isinstance(data['files'], list) or not isinstance(data['root'], str): + raise ValueError() + if data['root'] != str(self.root): + # A finished installation may be relocated; an unresolved one is + # bound to the path whose files and services it describes. + if data['phase'] not in ('complete', 'recovered'): + raise ValueError() + data['root'] = str(self.root) + if not isinstance(data['operation'], str) or uuid.UUID(data['operation']).hex != data['operation']: + raise ValueError() + expected = {p for p, _ in self.artifacts} + paths = [entry['path'] for entry in data['files']] + if len(paths) != len(set(paths)) or set(paths) != expected: + raise ValueError() + if data['phase'] not in ('prepared', 'applying', 'config_committed', 'activation_started', 'complete', 'recovering', 'recovered'): + raise ValueError() + def fingerprint(value, nullable=False): + if value is None and nullable: + return + if not isinstance(value, dict) or set(value) != {'sha256', 'size', 'mode', 'uid', 'gid'}: + raise ValueError() + if not isinstance(value['sha256'], str) or re.fullmatch(r'[0-9a-f]{64}', value['sha256']) is None: + raise ValueError() + for key in ('size', 'mode', 'uid', 'gid'): + if type(value[key]) is not int or value[key] < 0: + raise ValueError() + if value['mode'] > 0o7777: + raise ValueError() + if not isinstance(data['watched'], dict) or set(data['watched']) not in (set(WATCHED), set(LEGACY_WATCHED)): + raise ValueError() + for value in data['watched'].values(): + fingerprint(value, nullable=True) + activation_files = data.get('activation_files', {}) + if not isinstance(activation_files, dict) or any(p not in ACTIVATION_FILES for p in activation_files): + raise ValueError() + if activation_files and data['phase'] not in ('activation_started', 'complete'): + raise ValueError() + activation_dirs = data.get('activation_dirs', []) + if not isinstance(activation_dirs, list) or len(activation_dirs) != len(set(activation_dirs)) or any(p not in ('config', 'config/native', 'config/native/broker') for p in activation_dirs): + raise ValueError() + if activation_dirs and data['phase'] not in ('activation_started', 'complete'): + raise ValueError() + for relative, entry in activation_files.items(): + if not isinstance(entry, dict) or set(entry) != {'old', 'new', 'applied'} or type(entry['applied']) is not bool: + raise ValueError() + fingerprint(entry['old'], nullable=True) + fingerprint(entry['new']) + if relative not in data['watched'] or entry['old'] != data['watched'][relative]: + raise ValueError() + if data['phase'] == 'complete' and not entry['applied']: + raise ValueError() + safe_target(self.root, relative) + if not isinstance(data['created_dirs'], list) or any(p not in ('config', 'config/native') for p in data['created_dirs']): + raise ValueError() + if len(data['created_dirs']) != len(set(data['created_dirs'])): + raise ValueError() + if data.get('intent') is not None and data['intent'] not in expected: + raise ValueError() + for entry in data['files']: + safe_target(self.root, entry['path']) + fingerprint(entry['old'], nullable=True) + fingerprint(entry['new']) + if type(entry['mode']) is not int or entry['mode'] != entry['new']['mode']: + raise ValueError() + if entry['old'] is not None and entry['mode'] != entry['old']['mode']: + raise ValueError() + # Stage and backup data must stay inside this real operation dir. + for prefix in ('stage', 'backup'): + safe_target(self.state, data['operation'] + '/' + prefix + '/placeholder') + return data + except (KeyError, TypeError, ValueError, UnicodeError, AttributeError): + raise UpdateError('Update journal is invalid; preserve it for recovery') from None + + def validate(self, stage, expected_version): + for relative, _ in self.artifacts: + path = stage / relative + try: + text = path.read_text(encoding='utf-8-sig') + if '\x00' in text or not text.strip(): + raise ValueError() + if path.suffix == '.json' and not isinstance(json.loads(text), dict): + raise ValueError() + if path.suffix == '.py': + ast.parse(text) + except (ValueError, UnicodeError, SyntaxError): + raise UpdateError('Invalid staged installer file: ' + relative) from None + # Do not publish a management entry point that expects a different + # updater. The reviewed updater itself is copied into this transaction. + entrypoint = stage / ('upgrade.ps1' if self.platform == 'windows' else 'upgrade.sh') + pins = re.findall(r'UPDATE_ENGINE_SHA256\s*=\s*"([0-9a-f]{64})"', entrypoint.read_text(encoding='utf-8-sig')) + if pins != [hashlib.sha256(Path(__file__).read_bytes()).hexdigest()]: + raise UpdateError('Staged management script and reviewed updater are from different releases') + config = render_with_fallback(self.root, stage / 'docker-compose.yml') + if expected_version: + image = config.get('services', {}).get('backend', {}).get('image', '') + # Without interpolation the reviewed default is the part after ':-'. + default = re.fullmatch(r'\$\{TP_BACKEND_IMAGE:-([^${}]+)\}', image) + if default: + image = default.group(1) + if '@' in image or ':' not in image or image.rsplit(':', 1)[-1] != expected_version: + raise UpdateError('Requested version does not match the staged Compose backend image') + + def check_unchanged(self, data, *, before_apply=False): + for relative, original in data['watched'].items(): + if not same(file_info(safe_target(self.root, relative)), original): + raise UpdateError('Install configuration changed during update: ' + relative) + if before_apply: + for entry in data['files']: + if not same(file_info(safe_target(self.root, entry['path'])), entry['old']): + raise UpdateError('Managed file changed after preflight: ' + entry['path']) + + def load_release_verifier(self, source, directory): + sibling = Path(__file__).resolve().with_name('release_manifest.py') + candidate = sibling + if file_info(sibling) is None or hashlib.sha256(sibling.read_bytes()).hexdigest() != RELEASE_VERIFIER_SHA256: + candidate = directory / 'verifier' / 'release_manifest.py' + self.downloader(source.rstrip('/') + '/' + RELEASE_VERIFIER, candidate) + content = candidate.read_bytes() + if hashlib.sha256(content).hexdigest() != RELEASE_VERIFIER_SHA256: + raise UpdateError('Release verifier does not match the digest pinned by this updater') + spec = importlib.util.spec_from_loader('tp_release_manifest', loader=None) + module = importlib.util.module_from_spec(spec) + exec(compile(content, str(candidate), 'exec'), module.__dict__) + return module + + def verify_signed_release(self, source, directory, stage, data, expected_version): + policy = self.release_policy + verifier = self.load_release_verifier(source, directory) + release = directory / 'release' + private_directory(release) + base = source.rstrip('/') + '/' + RELEASE_MANIFEST + self.downloader(base, release / 'manifest.json') + self.downloader(base + '.sig', release / 'manifest.json.sig') + files = {entry['path']: stage / entry['path'] for entry in data['files']} + try: + verifier.verify_files( + (release / 'manifest.json').read_bytes(), (release / 'manifest.json.sig').read_bytes(), + policy.get('trust_root'), files, + expected_publisher=policy.get('publisher') or DEFAULT_RELEASE_PUBLISHER, + expected_version=expected_version or None, + revoked_versions=frozenset(policy.get('revoked') or ())) + except verifier.ManifestError as error: + # Only the machine-readable reason; never echo manifest content. + raise UpdateError('Signed release verification failed: ' + error.reason) from None + + def prepare(self, source, expected_version): + parsed = urlsplit(source) + if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.query or parsed.fragment: + raise UpdateError('An HTTPS installer distribution base is required') + if (self.root / 'docker-compose.yml').exists(): + render_with_fallback(self.root, self.root / 'docker-compose.yml') + operation = uuid.uuid4().hex + directory = self.state / operation + private_directory(directory) + stage = directory / 'stage' + backups = directory / 'backup' + stage.mkdir(mode=0o700) + backups.mkdir(mode=0o700) + fsync_directory(directory) + data = {'version': 1, 'root': str(self.root), 'operation': operation, + 'phase': 'prepared', 'files': [], 'watched': {}, 'created_dirs': []} + for relative in WATCHED: + data['watched'][relative] = file_info(safe_target(self.root, relative)) + for relative, default_mode in self.artifacts: + target = safe_target(self.root, relative) + original = file_info(target) + entry = {'path': relative, 'old': original, 'new': None, 'mode': original['mode'] if original else default_mode} + data['files'].append(entry) + if original is not None: + durable_bytes(backups / relative, target.read_bytes(), original['mode'], original) + if not same(file_info(backups / relative), original) or not same(file_info(target), original): + raise UpdateError('Managed file changed during backup: ' + relative) + try: + for entry in data['files']: + path = stage / entry['path'] + if entry['path'] == 'config/native/update.py': + durable_bytes(path, Path(__file__).read_bytes(), entry['mode'], entry['old']) + else: + self.downloader(source.rstrip('/') + '/' + entry['path'], path) + # Preserve existing permissions and ownership, including + # private generated runtime files, through the update. + durable_bytes(path, path.read_bytes(), entry['mode'], entry['old']) + entry['new'] = file_info(path) + if os.name == 'nt': + # Windows chmod exposes read-only/writable, not POSIX rwx. + entry['mode'] = entry['new']['mode'] + if self.release_policy is not None: + self.verify_signed_release(source, directory, stage, data, expected_version) + self.validator(stage, expected_version) + self.checkpoint('validated') + self.check_unchanged(data, before_apply=True) + self.save(data) + self.checkpoint('prepared') + return data + except BaseException: + # No managed target was written. Keep only this transaction's + # private stage/backup for diagnosis; never clean an existing stack. + raise + + def apply(self, data): + self.check_unchanged(data, before_apply=True) + data['phase'] = 'applying' + self.save(data) + for entry in data['files']: + relative = entry['path'] + target = safe_target(self.root, relative) + self.check_unchanged(data) + if not same(file_info(target), entry['old']): + raise UpdateError('Managed file changed before replacement: ' + relative) + missing = [] + parent = target.parent + while parent != self.root and not parent.exists(): + missing.append(parent) + parent = parent.parent + for parent in reversed(missing): + rel = parent.relative_to(self.root).as_posix() + if rel not in data['created_dirs']: + data['created_dirs'].append(rel) + self.save(data) # Write intent before creating anything. + parent.mkdir(mode=0o755, exist_ok=True) + fsync_directory(parent.parent) + data['intent'] = relative + self.save(data) + self.checkpoint('before-replace:' + relative) + self.check_unchanged(data) + if not same(file_info(target), entry['old']): + raise UpdateError('Managed file changed before replacement: ' + relative) + source = self.state / data['operation'] / 'stage' / relative + if not same(file_info(source), entry['new']): + raise UpdateError('Staged file changed before replacement: ' + relative) + durable_bytes(target, source.read_bytes(), entry['mode'], entry['old']) + self.checkpoint('after-replace:' + relative) + data['intent'] = None + self.save(data) + data['phase'] = 'config_committed' + self.save(data) + self.checkpoint('config_committed') + + def recover(self, data): + if data['phase'] in ('complete', 'recovered'): + return + if data['phase'] == 'activation_started': + raise UpdateError('Previous activation may have changed databases or services; inspect the journal and reconcile before another update. No database rollback was attempted') + # Inspect *all* targets first. Neither a later user edit nor an unknown + # replacement is silently overwritten during recovery. + for entry in data['files']: + current = file_info(safe_target(self.root, entry['path'])) + if not same(current, entry['old']) and not same(current, entry['new']): + raise UpdateError('Recovery requires review of an externally changed file: ' + entry['path']) + if entry['old'] is not None: + backup = self.state / data['operation'] / 'backup' / entry['path'] + if not same(file_info(backup), entry['old']): + raise UpdateError('Recovery backup is missing or changed: ' + entry['path']) + data['phase'] = 'recovering' + self.save(data) + for entry in reversed(data['files']): + target = safe_target(self.root, entry['path']) + current = file_info(target) + if same(current, entry['old']): + continue + if not same(current, entry['new']): + raise UpdateError('File changed during recovery: ' + entry['path']) + if entry['old'] is None: + target.unlink() + fsync_directory(target.parent) + else: + backup = self.state / data['operation'] / 'backup' / entry['path'] + durable_bytes(target, backup.read_bytes(), entry['old']['mode'], entry['old']) + self.checkpoint('recovered-file:' + entry['path']) + for relative in reversed(data.get('created_dirs', [])): + directory = safe_target(self.root, relative + '/placeholder').parent + try: + directory.rmdir() # Never recursive; preserve foreign contents. + fsync_directory(directory.parent) + except (FileNotFoundError, OSError): + pass + data['phase'] = 'recovered' + self.save(data) + + def write_activation_environment(self, content): + self.write_activation_file('.env', content, 0o600) + + def write_activation_file(self, relative, content, mode, ownership=None): + """Journal the native .env effect; never infer service/DB rollback. + + The formal entrypoint holds update_lock while its prepare child uses + this method. Before activation .env remains a watched input. During + activation its original backup and intended new bytes are recorded in + the same private transaction before the atomic target replacement. + """ + data = self.load() + if data is None or data['phase'] != 'activation_started' or relative not in ACTIVATION_FILES or relative not in data['watched']: + raise UpdateError('Configuration changes require the active installation journal and a known file') + target = safe_target(self.root, relative) + actual = file_info(target) + prior = data.get('activation_files', {}).get(relative) + if prior is not None: + if not prior['applied'] or not same(actual, prior['new']): + raise UpdateError('Previous configuration activation is unresolved; preserve the journal') + elif not same(actual, data['watched'][relative]): + raise UpdateError('Configuration changed before native activation') + original = data['watched'][relative] + directory = self.state / data['operation'] + backup = directory / 'backup' / relative + if prior is None and original is not None: + durable_bytes(backup, target.read_bytes(), original['mode'], original) + if original is not None and not same(file_info(backup), original): + raise UpdateError('Configuration activation backup is missing or changed') + staged = directory / 'stage' / relative + owner = ownership if ownership is not None else original + durable_bytes(staged, content, mode, owner) + entry = {'old': original, 'new': file_info(staged), 'applied': False} + data.setdefault('activation_files', {})[relative] = entry + missing = [] + parent = target.parent + while parent != self.root and not parent.exists(): + missing.append(parent.relative_to(self.root).as_posix()) + parent = parent.parent + for path in reversed(missing): + if path not in data.setdefault('activation_dirs', []): + data['activation_dirs'].append(path) + self.save(data) + self.checkpoint('activation-env-prepared' if relative == '.env' else 'activation-file-prepared:' + relative) + expected = prior['new'] if prior is not None else original + if not same(file_info(target), expected) or not same(file_info(staged), entry['new']): + raise UpdateError('Configuration changed during native activation') + durable_bytes(target, staged.read_bytes(), mode, owner) + self.checkpoint('activation-env-written' if relative == '.env' else 'activation-file-written:' + relative) + entry['applied'] = True + self.save(data) + + def reconcile_activation(self, plugin_trust_root=None, *, enable_plugin_bundle=False): + """Resume an unresolved activation only by re-running its idempotent tail + (migration bootstrap, compose up, verification). + + The journal stays ``activation_started`` unless services come up and + native verification passes; nothing is rolled back or re-applied. + """ + agent_started = False + with update_lock(self.state): + data = self.load() + if data is None or data['phase'] != 'activation_started': + raise UpdateError('There is no unresolved activation to reconcile') + for relative, entry in data.get('activation_files', {}).items(): + if not entry['applied'] or not same(file_info(safe_target(self.root, relative)), entry['new']): + raise UpdateError('Activation configuration is not in its recorded state; manual review is required: ' + relative) + # The managed public flow uses the reviewed embedded trust anchor + # and last-good bundle. Do not let an old partial root-level bundle + # prevent recovery of the ThingsPanel core or the managed Agent. + catalog = False if enable_plugin_bundle else verify_plugin_agent_bundle(self.root, plugin_trust_root) + managed = None + if catalog: + preload_homeassistant_image(self.root, catalog) + elif enable_plugin_bundle: + managed = optional_plugin_for_activation(self.root, plugin_trust_root, allow_download=False) + if managed: + try: + preload_homeassistant_image(managed[0], managed[2]) + except Exception as error: # noqa: BLE001 - leave an untrusted bundle inactive. + print('[WARN] Plugin image rejected (%s); platform recovery continues.' % type(error).__name__, file=sys.stderr) + managed = None + context = {'TP_INSTALLER_ACTIVE_OPERATION': data['operation']} + prepare = [sys.executable, str(self.root / 'config/native/prepare.py')] + run_command(prepare + ['--bootstrap', '--refresh-devices'], self.root, extra_env=context) + if managed: + try: + agent_started = start_plugin_agent(self.root, managed[1], verified_catalog=managed[2], bundle_root=managed[0]) + if agent_started and managed[3]: + record_active_plugin(self.root, managed[0]) + clear_pending_plugin(self.root) + except Exception as error: # noqa: BLE001 - recover the platform even when the optional Agent fails. + print('[WARN] Plugin Agent could not start (%s); platform recovery continues.' % type(error).__name__, file=sys.stderr) + agent_started = False + else: + agent_started = start_plugin_agent(self.root, plugin_trust_root, verified_catalog=catalog) + run_command(['docker', 'compose', 'up', '-d', '--wait', '--wait-timeout', '240'], self.root) + restart_services_with_replaced_mounts(self.root) + run_command(prepare + ['--verify'], self.root, extra_env=context) + data['phase'] = 'complete' + self.save(data) + if agent_started: + start_scope_watcher_after_activation(self.root) + return agent_started + + def run(self, source, *, expected_version='', activate=None, recovery_only=False): + agent_started = False + with update_lock(self.state): + old = self.load() + if old is not None: + self.recover(old) + if recovery_only: + return + data = self.prepare(source, expected_version) + try: + self.apply(data) + if activate is not None: + self.check_unchanged(data) + for entry in data['files']: + if not same(file_info(safe_target(self.root, entry['path'])), entry['new']): + raise UpdateError('Managed file changed before activation: ' + entry['path']) + data['phase'] = 'activation_started' + self.save(data) + self.checkpoint('activation_started') + agent_started = bool(activate(self.root)) + # Native preparation records its .env effect in this same + # journal. Preserve it when committing the outer result. + activated = self.load() + if activated is None or activated['operation'] != data['operation'] or activated['phase'] != 'activation_started': + raise UpdateError('Activation journal changed unexpectedly') + data = activated + data['phase'] = 'complete' + self.save(data) + except BaseException: + if data['phase'] != 'activation_started': + self.recover(data) + raise + if agent_started: + start_scope_watcher_after_activation(self.root) + return agent_started + + +def restart_services_with_replaced_mounts(root): + """Restart services whose single-file bind mounts were replaced after they started. + + Managed files are replaced atomically (a new inode); a running container keeps + the old inode, and some services then fail every request until restarted. + """ + config = json.loads(run_command(['docker', 'compose', 'config', '--format', 'json'], root)) + base = os.path.realpath(str(root)) + stale = [] + for name, service in sorted(config.get('services', {}).items()): + newest = 0.0 + for volume in service.get('volumes', []): + source = volume.get('source') if isinstance(volume, dict) and volume.get('type') == 'bind' else None + if not source or not os.path.isfile(source) or not os.path.realpath(source).startswith(base + os.sep): + continue + newest = max(newest, os.stat(source).st_mtime) + if not newest: + continue + container = run_command(['docker', 'compose', 'ps', '-q', name], root).decode('utf-8', 'replace').strip().split('\n')[0] + if not container: + continue + started = run_command(['docker', 'inspect', '--format', '{{.State.Running}} {{.State.StartedAt}}', container], root).decode().strip().split() + if len(started) != 2 or started[0] != 'true': + continue + timestamp = started[1] + match = re.fullmatch(r'(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?Z', timestamp) + if match is None: + continue + from datetime import datetime, timezone + begun = datetime.strptime(match.group(1), '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc).timestamp() + if newest > begun: + stale.append(name) + if stale: + print('Restarting services whose mounted files were replaced: ' + ', '.join(stale), flush=True) + run_command(['docker', 'compose', 'restart'] + stale, root) + # Services sharing another service's network namespace need to follow it. + run_command(['docker', 'compose', 'up', '-d', '--wait', '--wait-timeout', '240'], root) + return stale + + +def plugin_bundle_parent(root): + root = Path(root).resolve() + state = root / '.thingspanel-update' + private_directory(state) + parent = state / 'plugin-bundles' + private_directory(parent) + return parent + + +def plugin_trust_root(root, supplied=None): + """Use an operator root or materialize the installer's pinned public root outside the payload.""" + root = Path(root).resolve() + if supplied: + key = Path(supplied) + if not key.is_absolute() or not key.is_file() or key.is_symlink(): + raise UpdateError('Plugin trust root is unavailable or invalid') + key = key.resolve() + try: + key.relative_to(root) + except ValueError: + return key + raise UpdateError('Plugin trust root must be outside the installer payload') + key = root.parent / ('.' + root.name + '-plugin-trust.pem') + try: + fd = os.open(str(key), os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o644) + except FileExistsError: + info = file_info(key) + if info is None or key.read_bytes() != PLUGIN_TRUST_PEM: + raise UpdateError('Existing plugin trust root does not match the installer pin') + else: + with os.fdopen(fd, 'wb') as out: + out.write(PLUGIN_TRUST_PEM) + out.flush() + os.fsync(out.fileno()) + fsync_directory(key.parent) + return key.resolve() + + +def load_plugin_helpers(helper_root): + """Load only helper files matching an updater-pinned complete profile.""" + helper_root = Path(helper_root) + if helper_root.is_symlink() or not helper_root.is_dir(): + raise UpdateError('Plugin helper directory is invalid') + matched = False + for profile in PLUGIN_HELPER_PROFILES: + if all((info := file_info(safe_target(helper_root, name))) is not None and info['sha256'] == digest + for name, digest in profile.items()): + matched = True + break + if not matched: + raise UpdateError('Plugin helper files do not match the installer pin') + previous = sys.modules.get('plugin_catalog') + try: + catalog_spec = importlib.util.spec_from_file_location('plugin_catalog', helper_root / 'tools/plugin_catalog.py') + catalog_module = importlib.util.module_from_spec(catalog_spec) + sys.modules['plugin_catalog'] = catalog_module + catalog_spec.loader.exec_module(catalog_module) + spec = importlib.util.spec_from_file_location('tp_plugin_bundle_bootstrap', helper_root / 'tools/plugin_bundle.py') + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + finally: + if previous is None: + sys.modules.pop('plugin_catalog', None) + else: + sys.modules['plugin_catalog'] = previous + + +def active_plugin_directory(root): + """Read a private last-good pointer without following paths or symlinks.""" + return plugin_directory_from_pointer(root, 'current.json', 'Last-good') + + +def pending_plugin_directory(root): + """Read a durably staged first-install bundle awaiting Agent activation.""" + return plugin_directory_from_pointer(root, 'pending.json', 'Pending') + + +def plugin_directory_from_pointer(root, filename, label): + parent = plugin_bundle_parent(root) + pointer = parent / filename + if file_info(pointer) is None: + return None + try: + value = json.loads(pointer.read_text(encoding='utf-8')) + name = value['directory'] + if not isinstance(name, str) or re.fullmatch(r'tp-plugin-bundle-[A-Za-z0-9_-]+', name) is None: + raise ValueError() + directory = parent / name + if directory.is_symlink() or not directory.is_dir(): + raise ValueError() + return directory + except (KeyError, TypeError, ValueError, OSError): + raise UpdateError(label + ' plugin bundle pointer is invalid') from None + + +def record_active_plugin(root, bundle): + write_plugin_pointer(root, bundle, 'current.json', 'activated') + + +def record_pending_plugin(root, bundle): + write_plugin_pointer(root, bundle, 'pending.json', 'pending') + + +def write_plugin_pointer(root, bundle, filename, label): + parent = plugin_bundle_parent(root) + bundle = Path(bundle) + if bundle.parent != parent or bundle.is_symlink() or not bundle.is_dir() or re.fullmatch(r'tp-plugin-bundle-[A-Za-z0-9_-]+', bundle.name) is None: + raise UpdateError('Plugin bundle cannot be recorded outside its private directory') + pointer = parent / filename + file_info(pointer) # Refuse an existing symlink or non-regular pointer. + durable_bytes(pointer, (json.dumps({'directory': bundle.name}, sort_keys=True) + '\n').encode(), 0o600) + + +def clear_pending_plugin(root): + pointer = plugin_bundle_parent(root) / 'pending.json' + if file_info(pointer) is not None: + pointer.unlink() + fsync_directory(pointer.parent) + + +def prepare_optional_plugin(root, supplied_trust_root=None, *, allow_download=False, + source='https://install.thingspanel.io'): + """Verify an active bundle, or stage a new one without touching the active pointer.""" + root = Path(root).resolve() + parent = plugin_bundle_parent(root) + active = active_plugin_directory(root) + pending = pending_plugin_directory(root) if active is None else None + if active is None and pending is None and not allow_download: + return None + trust = plugin_trust_root(root, supplied_trust_root) + platform = normalize_platform(run_command(['docker', 'info', '--format', '{{.OSType}}/{{.Architecture}}'], root).decode().strip()) + if active is not None: + if pending_plugin_directory(root) == active: + clear_pending_plugin(root) + helpers = load_plugin_helpers(active) + catalog = helpers.verify_active_bundle(active, trust, platform) + return active, trust, catalog, False + if pending is not None: + helpers = load_plugin_helpers(pending) + try: + catalog = helpers.verify_active_bundle(pending, trust, platform, require_unexpired=True) + except Exception as error: # noqa: BLE001 - only an authenticated expired marker is eligible for refresh. + if 'pending catalog expired before activation' not in str(error) or not allow_download: + raise + # This pointer was created by this updater but never activated. Keep + # the expired bundle intact for diagnosis; remove only its pointer, + # then stage the current independently signed release. + clear_pending_plugin(root) + pending = None + else: + return pending, trust, catalog, True + helper_root = Path(tempfile.mkdtemp(prefix='tp-plugin-helpers-', dir=parent)) + os.chmod(helper_root, 0o700) + try: + for relative, digest in PLUGIN_HELPER_PROFILES[0].items(): + target = safe_target(helper_root, relative) + download(source.rstrip('/') + '/' + relative, target) + info = file_info(target) + if info is None or info['sha256'] != digest: + raise UpdateError('Downloaded plugin helper does not match the installer pin: ' + relative) + helpers = load_plugin_helpers(helper_root) + staged = helpers.stage_plugin_bundle(platform, trust_root=trust, stage_parent=parent) + bundle = helpers.arrange_staged_bundle(staged) + # Move only the helper files we just downloaded and pinned; no active bundle is touched. + for relative in PLUGIN_HELPER_PROFILES[0]: + destination = safe_target(bundle, relative) + make_directories(destination.parent, 0o700) + os.replace(safe_target(helper_root, relative), destination) + helpers = load_plugin_helpers(bundle) + catalog = helpers.verify_active_bundle(bundle, trust, platform, require_unexpired=True) + # Persist the candidate before Docker/Agent side effects so activation can + # resume after a host crash without downloading or creating a new instance. + record_pending_plugin(root, bundle) + return bundle, trust, catalog, True + finally: + shutil.rmtree(helper_root, ignore_errors=True) + + +def optional_plugin_for_activation(root, supplied_trust_root=None, *, allow_download=False, + source='https://install.thingspanel.io'): + """Plugin delivery is optional: a rejected bundle must not stop the platform itself.""" + try: + return prepare_optional_plugin(root, supplied_trust_root, allow_download=allow_download, source=source) + except Exception as error: # noqa: BLE001 - never execute/load a rejected optional bundle. + print('[WARN] Plugin bundle unavailable (%s); platform startup continues.' % type(error).__name__, file=sys.stderr) + return None + + +def activate_native(root, plugin_trust_root=None, *, enable_plugin_bundle=False, + source='https://install.thingspanel.io'): + """Existing native entry point, after commit, under the same process lock.""" + prepare = [sys.executable, str(root / 'config/native/prepare.py')] + current = Transaction(root).load() + if current is None or current['phase'] != 'activation_started': + raise UpdateError('Native activation requires its persistent operation') + # New install/upgrade flow uses the pinned managed bundle. Older root-level + # files may be partial or require an obsolete out-of-band key; they remain + # untouched and cannot block the current platform activation. + catalog = False if enable_plugin_bundle else verify_plugin_agent_bundle(root, plugin_trust_root) + managed = None + if catalog: + preload_homeassistant_image(root, catalog) + elif enable_plugin_bundle: + managed = optional_plugin_for_activation(root, plugin_trust_root, allow_download=True, source=source) + if managed: + try: + preload_homeassistant_image(managed[0], managed[2]) + except Exception as error: # noqa: BLE001 - do not activate a rejected optional image. + print('[WARN] Plugin image rejected (%s); platform startup continues.' % type(error).__name__, file=sys.stderr) + managed = None + context = {'TP_INSTALLER_ACTIVE_OPERATION': current['operation']} + + def native(*args): + return run_command(prepare + list(args), root, extra_env=context) + + print('Preparing native configuration (configuration rollback ends here).', flush=True) + native() + archive = root / 'images.tar' + parts = sorted(root.glob('images.tar.part-*')) + loaded = False + if archive.is_file(): + try: + run_command(['docker', 'load', '-i', str(archive)], root) + loaded = True + except UpdateError: + print('Offline image load failed; trying the configured registry.', flush=True) + elif parts: + # Stream parts instead of creating a second multi-GB archive. + process = subprocess.Popen(['docker', 'load'], cwd=root, stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + for part in parts: + with part.open('rb') as stream: + shutil.copyfileobj(stream, process.stdin) + process.stdin.close() + loaded = process.wait() == 0 + except (OSError, BrokenPipeError): + if process.stdin: + process.stdin.close() + process.wait() + if not loaded: + print('Offline image load failed; trying the configured registry.', flush=True) + if not loaded: + print('Pulling the selected component images.', flush=True) + native('--pull') + print('Applying the existing native migration and service preparation.', flush=True) + native('--bootstrap', '--refresh-devices') + if managed: + try: + agent_started = start_plugin_agent(root, managed[1], verified_catalog=managed[2], bundle_root=managed[0]) + if agent_started and managed[3]: + record_active_plugin(root, managed[0]) + clear_pending_plugin(root) + except Exception as error: # noqa: BLE001 - keep platform startup independent of the optional plugin. + print('[WARN] Plugin Agent could not start (%s); platform startup continues.' % type(error).__name__, file=sys.stderr) + agent_started = False + else: + agent_started = start_plugin_agent(root, plugin_trust_root, verified_catalog=catalog) + run_command(['docker', 'compose', 'up', '-d', '--wait', '--wait-timeout', '240'], root) + restart_services_with_replaced_mounts(root) + native('--verify') + return agent_started + + +def load_verified_plugin_catalog(root, trust_root): + """Load the exact signed catalog through the same verifier used by the Agent.""" + path = Path(root) / 'tools/plugin_catalog.py' + spec = importlib.util.spec_from_file_location('tp_installer_plugin_catalog', path) + if spec is None or spec.loader is None: + raise UpdateError('Plugin catalog verifier is unavailable; backend was not started') + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + try: + return module.load_verified(Path(root) / 'plugins/plugin-catalog.json', trust_root) + except Exception as error: # noqa: BLE001 - fail closed at the installer boundary + raise UpdateError('Plugin catalog signature or contents are invalid; backend was not started') from error + + +def normalize_platform(value): + """Normalize Docker and Go architecture names to catalog platform names.""" + parts = value.strip().lower().split('/') + if len(parts) != 2: + return '' + aliases = {'aarch64': 'arm64', 'x86_64': 'amd64'} + parts[1] = aliases.get(parts[1], parts[1]) + return '/'.join(parts) + + +def preload_homeassistant_image(root, catalog): + """Load and verify the signed HA image before the Agent or backend can start.""" + entries = [entry for entry in catalog.get('plugins', []) if entry.get('id') == 'homeassistant'] + if not entries: + return False + if len(entries) != 1: + raise UpdateError('Home Assistant catalog entry is ambiguous; backend was not started') + entry = entries[0] + image_id = entry.get('image_id', '') + target = normalize_platform(entry.get('image_platform', '')) + archive_sha256 = entry.get('image_archive_sha256', '') + if not image_id.startswith('sha256:') or len(image_id) != 71 or not target.startswith('linux/'): + raise UpdateError('Home Assistant catalog image identity or target platform is invalid; backend was not started') + if not isinstance(archive_sha256, str) or re.fullmatch(r'[0-9a-f]{64}', archive_sha256) is None: + raise UpdateError('Home Assistant catalog image archive digest is invalid; backend was not started') + + archive = Path(root) / 'plugins/homeassistant-image.tar' + if not archive.is_file() or archive.is_symlink(): + raise UpdateError('Home Assistant image archive is missing or invalid; backend was not started') + + try: + digest = hashlib.sha256() + with archive.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + except OSError: + raise UpdateError('Unable to verify Home Assistant image archive; backend was not started') from None + if digest.hexdigest() != archive_sha256: + raise UpdateError('Home Assistant image archive digest does not match the signed catalog; backend was not started') + + try: + docker_platform = run_command( + ['docker', 'info', '--format', '{{.OSType}}/{{.Architecture}}'], root + ).decode().strip() + except (UpdateError, OSError): + raise UpdateError('Unable to determine Docker target platform; backend was not started') from None + if normalize_platform(docker_platform) != target: + raise UpdateError('Home Assistant image target platform does not match Docker; backend was not started') + + run_command(['docker', 'load', '-i', str(archive)], root) + try: + inspected = run_command( + ['docker', 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image_id], root + ).decode().strip().split() + except (UpdateError, OSError): + raise UpdateError('Loaded Home Assistant image is unavailable; backend was not started') from None + if len(inspected) != 2 or inspected[0] != image_id or normalize_platform(inspected[1]) != target: + raise UpdateError('Loaded Home Assistant image digest or platform does not match the signed catalog; backend was not started') + return True + + +def verify_plugin_agent_bundle(root, plugin_trust_root=None): + """Verify an optional plugin Agent bundle before any migration or service startup.""" + root = Path(root).resolve() + agent_bin = root / 'bin/tp-agent' + catalog = root / 'plugins/plugin-catalog.json' + signature = root / 'plugins/plugin-catalog.json.sig' + bundle = (agent_bin, catalog, signature) + present = tuple(path.is_file() for path in bundle) + if not any(present): + return False + if not all(present): + raise UpdateError('Plugin Agent release bundle is incomplete; backend was not started') + if not plugin_trust_root: + raise UpdateError('Plugin trust root was not supplied out of band; backend was not started') + trust_root = Path(plugin_trust_root) + if not trust_root.is_absolute(): + raise UpdateError('Plugin trust root path must be absolute and supplied out of band') + trust_root = trust_root.resolve() + if not trust_root.is_file(): + raise UpdateError('Plugin trust root is unavailable; backend was not started') + try: + trust_root.relative_to(root) + except ValueError: + pass + else: + raise UpdateError('Plugin trust root must be outside the installer payload') + return load_verified_plugin_catalog(root, trust_root) + + +def start_plugin_agent(root, plugin_trust_root=None, verified_catalog=None, bundle_root=None): + """Start the already-verified plugin Agent after DB/network bootstrap but before the backend.""" + root = Path(root).resolve() + catalog_data = verified_catalog if verified_catalog is not None else verify_plugin_agent_bundle(root, plugin_trust_root) + if not catalog_data: + return False + if verified_catalog is None: + preload_homeassistant_image(root, catalog_data) + bundle = Path(bundle_root).resolve() if bundle_root is not None else root + agent_bin = bundle / 'bin/tp-agent' + catalog = bundle / 'plugins/plugin-catalog.json' + trust_root = Path(plugin_trust_root).resolve() + run_command([ + sys.executable, str(bundle / 'tools/agent_host.py'), 'up', + '--stack-dir', str(root), '--agent-dir', str(root / '.tp-agent'), + '--agent-bin', str(agent_bin), '--catalog', str(catalog), '--trust-root', str(trust_root), + '--defer-scope-watcher', + ], root) + return True + + +def start_scope_watcher_after_activation(root): + """Start the optional Broker scope watcher after the transaction lock is released.""" + root = Path(root).resolve() + try: + active = active_plugin_directory(root) + if active: + load_plugin_helpers(active) + scope_sync_path = (active or root) / 'tools/scope_sync.py' + except Exception as error: # noqa: BLE001 - do not load unverified helper code. + print('[WARN] Plugin scope watcher is unavailable (%s).' % type(error).__name__, file=sys.stderr) + return False + spec = importlib.util.spec_from_file_location('tp_installer_scope_sync', scope_sync_path) + if spec is None or spec.loader is None: + print('[WARN] Plugin Agent is running but its Broker scope watcher could not load; retry with tools/scope_sync.py ensure.', + file=sys.stderr) + return False + module = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(module) + status = module.ensure(root, root / '.tp-agent') + except Exception as error: # noqa: BLE001 - watcher startup is retryable and must not fail platform activation. + print('[WARN] Plugin Agent is running but its Broker scope watcher did not start (%s); retry with tools/scope_sync.py ensure.' % + type(error).__name__, file=sys.stderr) + return False + if status == 'busy': + print('[WARN] Plugin Agent is running but another installer operation holds the lock; retry scope_sync.py ensure.', + file=sys.stderr) + return False + if status not in ('started', 'running'): + print('[WARN] Plugin Agent is running but its Broker scope watcher returned an unexpected status; retry scope_sync.py ensure.', + file=sys.stderr) + return False + return True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', required=True) + parser.add_argument('--base-url', default='https://install.thingspanel.io') + parser.add_argument('--expected-version', default='') + parser.add_argument('--recover-config-only', action='store_true') + parser.add_argument('--reconcile-activation', action='store_true', + help='re-run compose up and verification for an unresolved activation, then close its journal') + parser.add_argument('--plugin-trust-root', default='', + help='absolute out-of-band ECDSA P-256 public key used to verify the plugin catalog') + parser.add_argument('--release-trust-root', default='', help='pinned ECDSA P-256 public key (PEM) for signed releases') + parser.add_argument('--require-signed-release', action='store_true', + help='fail closed unless the release verifies against --release-trust-root') + parser.add_argument('--release-publisher', default=DEFAULT_RELEASE_PUBLISHER) + parser.add_argument('--revoked-version', action='append', default=[]) + args = parser.parse_args() + try: + root = Path(os.path.abspath(args.root)) + if not args.recover_config_only and not (root / 'config/native/internal.crt').is_file() and shutil.which('openssl') is None: + raise UpdateError('OpenSSL is required by native certificate preparation; no configuration was replaced') + policy = None + if args.release_trust_root or args.require_signed_release: + policy = {'trust_root': args.release_trust_root or None, 'publisher': args.release_publisher, + 'revoked': args.revoked_version} + elif not args.recover_config_only: + print('[WARN] No release trust root configured; the release signature is not verified.', file=sys.stderr) + transaction = Transaction(args.root, release_policy=policy) + if args.reconcile_activation: + agent_started = transaction.reconcile_activation(args.plugin_trust_root or None, enable_plugin_bundle=True) + print('Activation reconciled.') + if not agent_started: + print('[WARN] ThingsPanel recovery completed, but the HA plugin Agent is not active. Re-run the installer after fixing the plugin release or host issue.', file=sys.stderr) + return 2 + return 0 + unresolved = None if args.recover_config_only else transaction.load() + if unresolved is not None and unresolved['phase'] == 'activation_started': + print('Resuming the previous interrupted ThingsPanel activation.', flush=True) + agent_started = transaction.reconcile_activation(args.plugin_trust_root or None, enable_plugin_bundle=True) + print('Interrupted activation recovered.') + if not agent_started: + print('[WARN] ThingsPanel recovery completed, but the HA plugin Agent is not active. Fix the plugin or host issue and re-run the installer.', file=sys.stderr) + return 2 + return 0 + agent_started = transaction.run(args.base_url, expected_version=args.expected_version, + activate=lambda install_root: activate_native(install_root, args.plugin_trust_root or None, + enable_plugin_bundle=True, source=args.base_url), + recovery_only=args.recover_config_only) + if not args.recover_config_only and not agent_started: + print('[WARN] ThingsPanel core is running, but the HA plugin Agent is not active. Fix the reported plugin or host issue and re-run the installer.', file=sys.stderr) + return 2 + print('Configuration recovery complete.' if args.recover_config_only else 'Installation operation completed.') + except (UpdateError, OSError) as error: + # Avoid arbitrary subprocess output or URLs in the error channel. + message = str(error) if isinstance(error, UpdateError) else 'Installer filesystem operation failed; preserve the update journal for recovery' + print('[ERROR] ' + message, file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/docker-compose.yml b/docker-compose.yml index c11d88d..51481d5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,7 +34,7 @@ services: volumes: - postgres_data:/var/lib/postgresql/data ports: - - 5555:5432 + - ${TP_PORT_POSTGRES:-5555}:5432 environment: - TZ=Asia/Shanghai - LC_ALL=C.UTF-8 @@ -53,13 +53,32 @@ services: restart: unless-stopped networks: - thingspanel_network + tdengine: + profiles: + - tdengine + image: ${TP_TDENGINE_IMAGE:-tdengine/tdengine:3.3.6.0} + environment: + - TZ=Asia/Shanghai + volumes: + - tdengine_data:/var/lib/taos + healthcheck: + test: + - CMD-SHELL + - curl -sf -u root:${TP_TDENGINE_PASSWORD:-taosdata} -d 'show databases' http://127.0.0.1:6041/rest/sql >/dev/null + interval: 10s + timeout: 5s + retries: 12 + start_period: 20s + restart: unless-stopped + networks: + - thingspanel_network redis: image: registry.cn-hangzhou.aliyuncs.com/thingspanel/redis:6.2.7 command: redis-server --requirepass redis volumes: - redis_data:/data ports: - - 6379:6379 + - ${TP_PORT_REDIS:-6379}:6379 environment: - TZ=Asia/Shanghai healthcheck: @@ -76,17 +95,26 @@ services: networks: - thingspanel_network backend: - image: registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-go:v1.3.0 + image: ${TP_BACKEND_IMAGE:-registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-go:v1.3.0} ports: - - 9999:9999 + - ${TP_PORT_BACKEND:-9999}:9999 environment: - TZ=Asia/Shanghai + # Keep the legacy keys while the published v1.3.0 backend image is in use. + # A1 builds read relational.* and ignore the retired db.psql.* keys. - GOTP_DB_PSQL_HOST=postgres - GOTP_DB_PSQL_PORT=5432 - GOTP_DB_PSQL_USERNAME=postgres - GOTP_DB_PSQL_PASSWORD=${TP_DATABASE_PASSWORD:-postgresThingsPanel} - GOTP_DB_PSQL_DBNAME=ThingsPanel - GOTP_DB_PSQL_LOG_LEVEL=3 + - GOTP_RELATIONAL_DRIVER=postgres + - GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST=postgres + - GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT=5432 + - GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE=ThingsPanel + - GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME=postgres + - GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD=${TP_DATABASE_PASSWORD:-postgresThingsPanel} + - GOTP_RELATIONAL_POSTGRES_PLATFORM_LOG_LEVEL=3 - GOTP_DB_REDIS_ADDR=redis:6379 - GOTP_DB_REDIS_PASSWORD=redis - GOTP_MQTT_SERVER=mosquitto @@ -94,7 +122,17 @@ services: - GOTP_MQTT_BROKER=mosquitto:1883 - GOTP_LOG_LEVEL=error - GOTP_THINGSVIS_PUBLIC_API_BASE_URL=http://thingsvis-server:8000/api/v1 + - TP_MARKETINSTALL_PROVIDER_TOKEN=${TP_MARKETINSTALL_PROVIDER_TOKEN:?generated by native preparation} + - TP_MARKETINSTALL_THINGSVIS_BASE_URL=http://thingsvis-server:8000 + - TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN=${TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN:?generated by native preparation} + - TP_MARKETINSTALL_THINGSVIS_TOKEN=${TP_MARKETINSTALL_THINGSVIS_TOKEN:?generated by native preparation} - GOTP_MQTT_INPUT_PROFILE=ingress_v1 + - GOTP_STORAGE_HISTORY_BACKEND=${TP_HISTORY_BACKEND:-postgres} + - GOTP_STORAGE_TDENGINE_EXPERIMENTAL=${TP_TDENGINE_EXPERIMENTAL:-false} + - GOTP_STORAGE_TDENGINE_URL=http://tdengine:6041 + - GOTP_STORAGE_TDENGINE_USER=root + - GOTP_STORAGE_TDENGINE_PASSWORD=${TP_TDENGINE_PASSWORD:-taosdata} + - GOTP_STORAGE_TDENGINE_DATABASE=thingspanel_history - GOTP_MQTT_BROKER_CELL=${TP_BROKER_CELL:-community} - GOTP_MQTT_BROKER_INSTANCE=${TP_BROKER_INSTANCE:-community-mosquitto} - GOTP_MQTT_CLIENT_ID=${TP_MQTT_CLIENT_ID:-tp-community-backend} @@ -106,6 +144,8 @@ services: - GOTP_AUTOMATION_DEPLOYMENT_ID=${TP_DEPLOYMENT_ID:-community} - TP_THINGMODEL_NATIVE_URL=http://encore-api:14000 - GOTP_JWT_KEY=${TP_JWT_KEY:?set in .env} + - TP_AGENT_SOCKET=/run/tp-agent/agent.sock + - TP_AGENT_TOKEN_FILE=/run/tp-agent/token depends_on: postgres: condition: service_healthy @@ -116,6 +156,7 @@ services: volumes: - go_files:/go/src/app/files - go_configs:/go/src/app/configs + - ./.tp-agent/run:/run/tp-agent:ro restart: unless-stopped networks: - thingspanel_network @@ -130,8 +171,8 @@ services: modbus_service: image: registry.cn-hangzhou.aliyuncs.com/thingspanel/modbus-protocol-plugin:v1.0.6.1 ports: - - 502:502 - - 503:503 + - ${TP_PORT_MODBUS:-502}:502 + - ${TP_PORT_MODBUS2:-503}:503 environment: - MODBUS_THINGSPANEL_ADDRESS=http://backend:9999 - MODBUS_MQTT_BROKER=mosquitto:1883 @@ -148,8 +189,8 @@ services: http_adapter: image: registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-adapter-http:v1.1.0 ports: - - 19090:19090 - - 19091:19091 + - ${TP_PORT_HTTP_ADAPTER:-19090}:19090 + - ${TP_PORT_HTTP_ADAPTER2:-19091}:19091 environment: - TZ=Asia/Shanghai - P_SERVER_PORT=19090 @@ -165,17 +206,23 @@ services: - mosquitto restart: unless-stopped thingsvis-server: - image: registry.cn-hangzhou.aliyuncs.com/thingspanel/thingsvis-server:v1.0.23 - container_name: thingsvis-server + image: ${TP_THINGSVIS_IMAGE:-registry.cn-hangzhou.aliyuncs.com/thingspanel/thingsvis-server:v1.0.23} + container_name: ${TP_THINGSVIS_SERVER_CONTAINER:-thingsvis-server} restart: unless-stopped ports: - - 8000:8000 + - ${TP_PORT_THINGSVIS_API:-8000}:8000 environment: - NODE_ENV=production - HOSTNAME=0.0.0.0 - AUTH_TRUST_HOST=true - DATABASE_URL=postgresql://postgres:${TP_DATABASE_PASSWORD:-postgresThingsPanel}@postgres:5432/ThingsPanel?schema=thingsvis - - AUTH_SECRET=your-super-secret-auth-key + - DATABASE_PROVIDER=postgresql + - AUTH_SECRET=${TP_THINGSVIS_AUTH_SECRET:?generated and persisted by native preparation} + - PLATFORM_API_URL=http://backend:9999 + - MARKET_IDENTITY_INTERNAL_TOKEN=${TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN:?generated by native preparation} + - MARKET_TEMPLATE_INTERNAL_TOKEN=${TP_MARKETINSTALL_THINGSVIS_TOKEN:?generated by native preparation} + - COMMUNITY_MARKET_AUTHORIZATION_URL=http://backend:9999/internal/market-install/authorize + - COMMUNITY_MARKET_AUTHORIZATION_TOKEN=${TP_MARKETINSTALL_PROVIDER_TOKEN:?generated by native preparation} depends_on: postgres: condition: service_healthy @@ -184,17 +231,17 @@ services: healthcheck: test: - CMD-SHELL - - wget -qO- --spider http://127.0.0.1:8000/ + - wget -qO- --spider http://127.0.0.1:8000/api/v1/health interval: 10s timeout: 5s retries: 12 start_period: 120s thingsvis-studio: image: registry.cn-hangzhou.aliyuncs.com/thingspanel/thingsvis-studio:v1.0.23 - container_name: thingsvis-studio + container_name: ${TP_THINGSVIS_STUDIO_CONTAINER:-thingsvis-studio} restart: unless-stopped ports: - - 3000:3000 + - ${TP_PORT_THINGSVIS_STUDIO:-3000}:3000 environment: - STUDIO_PORT=3000 - SERVER_HOST=thingsvis-server @@ -227,8 +274,7 @@ services: TP_BROKER_OWNER_TOKENS_FILE: /run/secrets/owner-tokens.json TP_BROKER_OWNER_SERVICES_FILE: /run/secrets/services.json volumes: - - ./config/native/owner-tokens.json:/run/secrets/owner-tokens.json:ro - - ./config/native/services.json:/run/secrets/services.json:ro + - ./config/native/broker:/run/secrets:ro depends_on: postgres: condition: service_healthy @@ -258,8 +304,7 @@ services: TP_BROKER_INSTANCE: ${TP_BROKER_INSTANCE:-community-mosquitto} volumes: - mosquitto_data:/mosquitto/data - - ./config/native/plugin-token:/run/secrets/plugin-token:ro - - ./config/native/services.json:/run/secrets/services.json:ro + - ./config/native/broker:/run/secrets:ro encore-api: image: registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-encore:v1.3.0 restart: unless-stopped @@ -341,6 +386,7 @@ volumes: go_files: null go_configs: null postgres_data: null + tdengine_data: null redis_data: null mosquitto_data: null networks: diff --git a/docs/backend-datasource-guard-candidate-20261102.md b/docs/backend-datasource-guard-candidate-20261102.md new file mode 100644 index 0000000..603da6e --- /dev/null +++ b/docs/backend-datasource-guard-candidate-20261102.md @@ -0,0 +1,11 @@ +# Installer 后端关系库防护候选(未发布) + +现有 Compose 与固定 ThingsVis v1.0.23 都使用 PG,installer 的既有 ThingsVis URL 检查单独无法识别“平台后端 MySQL、ThingsVis 仍是 PG”。本候选在 native `prepare.py` 和 Linux/Windows 安装/升级旧配置检查中加入后端字段核验:要求已知 `GOTP_DB_PSQL_HOST/PORT/USERNAME/DBNAME`,本地 host 为 `postgres` 时须有对应服务;拒绝已知 MySQL/MariaDB 字段、非 PG 的已知 provider/driver/type 和非 PG 的后端 DATABASE_URL。PG 外部 host 不因不存在本地 postgres 服务而被单独拒绝。异常文案不包含数据库 URL。 + +Linux `install.bash`、`upgrade.sh` 的旧配置检查在网络下载或覆盖前运行;`prepare.py` 在写入配置或拉镜像前运行。Windows 的 `install.core.ps1`、`upgrade.ps1` 同样加入候选检查,但本机没有 PowerShell,尚未运行验证。已有的其它未提交修改保留;本候选还未提交或发布。 + +`PYTHONDONTWRITEBYTECODE=1 python3 -m unittest -v config.native.test_backend_database_guard_candidate`:9 项通过,涵盖实际渲染的当前 PG Compose、外部 PG、显式 MySQL 与非 PG selector、缺服务、重复变量、ThingsVis MySQL 以及 Linux 安装/升级在旧配置检测失败时不下载、不覆盖。`bash -n install.bash`、`bash -n upgrade.sh`、`git diff --check` 通过。未执行此前系统中止的历史测试;本次也没有重新证明历史标签、Windows 或真实完整安装/升级兼容。 + +**本候选不是完整四 profile 认证或无隐藏 PG 保证。** 检查只识别当前已知后端环境字段,不验证实际服务器身份、other services/Encore、所有未来 selector 或 datasource 配置;保留 PG 字段同时以未识别方式启用 MySQL 仍可能绕过。缺项、未知 selector 值或不可解析旧配置可能被拒绝,需真实旧部署兼容验证;`--no-interpolate` fallback 也不等于实测所有历史环境。PowerShell 分支仅静态审阅,须在 Windows PowerShell 与 PowerShell 7 验证。现有通用 `command()` 可能将 Compose stderr 原文中的 ERROR/FATAL 行纳入异常,敏感插值泄漏风险须另查。 + +经用户授权前不得正式启用 MySQL:甲的连接/迁移合同、ThingsVis 字段和登录语义、真正独立 MySQL 客户端/账本及安全预检仍未定;MySQL/TDengine 必须证明没有 PG 可达,MySQL/Timescale 只允许因时序引入已声明 PG。明确配置选择、四 profile 唯一正式 installer 接线、数据搬迁/回退、旧 writer 退出和联合故障测试均未完成。 diff --git a/docs/release-manifest.md b/docs/release-manifest.md new file mode 100644 index 0000000..b0d795c --- /dev/null +++ b/docs/release-manifest.md @@ -0,0 +1,48 @@ +# 签名 release manifest 验签(已接入 bash/PowerShell 入口的更新事务;默认未启用) + +`config/native/release_manifest.py` 在使用任何 payload 之前验证一份已签名的 release manifest。 + +## 做了什么 + +- 信任锚只有调用方给出的 ECDSA P-256 公钥(PEM)。manifest 和 payload 都不能引入或替换它。 +- 仓库**不内置任何根公钥**。未配置、文件缺失、不是公钥或不是 P-256 时,一律以 `trust_root_not_configured` 拒绝(fail closed)。 +- 签名为对 manifest 原始字节的 SHA-256 做 DER ECDSA:`openssl dgst -sha256 -sign key.pem manifest.json > manifest.json.sig`。 +- 签名有效还不够,必须同时满足:发布者等于期望值、版本符合、在有效期内、不在撤回列表、 + payload 目录里的文件与 manifest 完全一致(路径、长度、SHA-256),没有缺文件、多文件、符号链接, + 路径必须是干净的相对路径。 +- manifest 在 payload 冻结后签名,payload 不内嵌 manifest 的摘要,避免 installer、updater 与管理脚本循环互相摘要。 + +## 接入方式 + +- `update.py` 新增 `--release-trust-root PEM`、`--require-signed-release`、`--release-publisher`、`--revoked-version`。 + 暂存全部受管文件之后、校验和应用之前,从 `/release-manifest.json` 与 `.sig` 取 manifest, + 逐个核对暂存文件(路径、长度、SHA-256);任一不符,在改动任何已安装文件之前终止。 +- 验签器 `release_manifest.py` 的 SHA-256 固定在 `update.py` 内,只在摘要一致时加载(旁边没有就按 base-url 下载后再核对)。 + 入口脚本固定的仍是 `update.py` 摘要,因此链条是:入口 → `update.py` → 验签器 → 签名 manifest。 +- 入口脚本从环境变量传入:`TP_RELEASE_TRUST_ROOT`(公钥路径,必须带外提供,不能来自 payload)、 + `TP_REQUIRE_SIGNED_RELEASE=1`(没有可用信任根则失败)、`TP_REVOKED_VERSIONS`(逗号分隔)。 + `install.bash`、`upgrade.sh`、`install.core.ps1`、`upgrade.ps1` 均已传递。 +- 插件 catalog 有独立信任锚:`TP_PLUGIN_TRUST_ROOT` 传给 `update.py --plugin-trust-root`,必须是安装目录外的绝对公钥路径;安装器先验 catalog,再在启动后端前启动 Agent。插件包不能自带并替换这个根。当前仓库没有正式插件信任根或正式签名 catalog。 +- 当前 `plugins/homeassistant.json` 对齐候选 `1.0.0-candidate.20261106-4d8d45b-r2`:`linux/arm64`、镜像 ID `sha256:0747be19506d38d110a61519964c0f5b6617886d5eb475b303a17ff1c8e6a21c`、归档 SHA-256 `5421f8ec4d62c5fabe4b5abd26312d5f13e9f4fe041fe0977dd932265e6bf220`。预加载会先流式核对 `image_archive_sha256`,匹配后才执行 `docker load`,随后仍检查镜像 ID/平台。r1 因镜像带 OCI 标签被 Agent allowlist 拒绝;r2 从同一干净 HA 提交重建且无镜像标签,已在隔离 Agent/容器中安装并通过健康检查。候选包在工作目录外,正式 catalog 签名和匹配的包外官方公钥仍缺。不得用历史 `t7c` 镜像或测试密钥发布。 +- **默认行为不变**:没有配置信任根且未要求签名时,仍只靠入口对 `update.py` 的摘要固定,并向 stderr 打印警告。 + 在发布负责人提供正式信任根并启用 `TP_REQUIRE_SIGNED_RELEASE` 之前,这不是签名信任链。 +- 撤回列表目前来自 manifest 自带的 `revoked_versions`(已签名)和 `--revoked-version`;独立的撤回源尚未设计。 + +## 没做什么 + +- **没有正式发行信任根**:需要发布负责人提供公钥并决定保管方式;测试里的密钥只在每次测试的临时目录里生成。 +- **PowerShell 入口只是传参,未在原生 Windows 上运行**;验签本身由 Python 完成,依赖 `openssl` 可用。 +- 没有 TUF 式目录版本/重放保护,也没有信任根轮换;这些在公开市场上线前仍需单独设计。 + +## 验证 + +```sh +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest tests.test_release_manifest tests.test_signed_update -v +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p 'test_*.py' +``` + +覆盖:有效发布、无信任根、非公钥/RSA 根、他人密钥签名、篡改 manifest、他人发布者、版本不符、过期/未生效、 +撤回、改动文件、缺文件、多文件(混发)、符号链接、路径穿越与绝对路径、重复路径与非法 commit、命令行退出码。 + +事务层集成测试(`tests/test_signed_update.py`):有效签名发布被应用;服务端文件被篡改、他人密钥、清单漏列文件、撤回、过期、他人发布者、 +要求签名却无信任根、验签器被替换均在改动任何已安装文件之前失败;孤立的 `update.py` 会下载并核对验签器;未配置时行为不变。 diff --git a/docs/takeover-installer-validation-20261102.md b/docs/takeover-installer-validation-20261102.md new file mode 100644 index 0000000..793496b --- /dev/null +++ b/docs/takeover-installer-validation-20261102.md @@ -0,0 +1,55 @@ +# Installer 接管与配置恢复复验 + +## 精确基线与责任 + +- 输入仓库:`/Volumes/500G/code/thingspanel-takeover-20261102/installer`。 +- 输入提交:`22d970e4b46d286a9f03a6f0a50a370725732160`。 +- 原候选目录只读。修改由 installer 唯一写入窗口经总负责人校验 before SHA 后集成。 +- 本报告只维护 installer 模块事实;共同门禁与制品清单由总负责人维护。 + +## 已确认结论 + +旧外置下载 harness 没有放入当前入口所固定摘要的 updater,因此第 2~7 个案例停在第一次 bootstrap 摘要拒绝;这不构成后续 payload 边界已经测试。仓库内既有 harness 已修正 bootstrap 前提。本轮又增加逐次 HTTPS 主机、下载 URL 与序号的断言,实际运行安装/升级各 7 个故障边界,并保留独立的 4 个 bootstrap 拒绝案例。没有降低产品摘要校验来适配旧测试。 + +既有整组事务实现可复用,保留原锁、journal、备份、原缺失状态、模式、混发拒绝和 activation unknown 守卫。本轮补充 SIGTERM、双进程进入配置阶段、缺文件 SIGKILL 恢复及完成/恢复状态重启用例。 + +新配置回归定位了原 `prepare.save` 的实际问题:第一次写入 broker JSON 后设为 `0440`,第二次 prepare 仍原地打开写入,普通用户会收到 PermissionError。现复用 `update.py` 的原子替换工具,不临时放宽旧文件权限,不建立第二套配置写入模块。 + +为使原子替换对容器可见,broker 三个专属文件使用最小目录挂载;保留所有旧路径文件,继承旧身份、owner 列表及服务范围。新文件与目录的缺失状态、写入意图进入同一 activation journal。真实 Docker 文件可见性验证入口为: + +```sh +python3 tests/verify_broker_directory_mount.py --image <已在本机且已审阅的镜像> +``` + +脚本只创建一个带唯一 `tp-takeover-b-installer-mount-` 前缀、`--network none`、只读根文件系统的临时容器;使用私有目录,结束删除该容器;不会拉取镜像或触碰业务栈。它同时记录目录挂载与单文件挂载控制组的实际读值。该脚本本地仅做语法验证,实际 Docker 结果须由总负责人补充,不能写成已经验证真实 Broker reload。 + +ThingsVis 不再使用公开默认 AUTH_SECRET。每部署身份与三份独立内部服务 token 持久化并做冲突校验;正式 Compose 接入 provider、identity、import 与当前授权回调。明确选择已验收新镜像和 `verified-sso-v1` 目标后,旧 SSO 身份轮换一次,随后复用。secret 与策略标记在同一原子 `.env` 内容中,由同一 update journal 保存旧/新摘要与原文件备份;未决 activation 一律要求实际服务核对。 + +## 实际执行与证据边界 + +执行平台为云端 Linux、Python 3.12。导入的 46 个基线文件均按远端提供 SHA-256 校验后使用。原样基线 28 方法通过。补丁后的命令为: + +```sh +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p 'test_*.py' -v +``` + +首包 49 个方法通过;配置覆盖/编码 followup 后为 51 个方法通过。包含原 14 个 payload 下载边界、4 个 bootstrap 拒绝、20 个替换前后异常、6 个配置阶段 SIGKILL、恢复再 SIGKILL、3 个 SIGTERM、2 个 activation-env SIGKILL、broker 新目录中断、并发锁及新身份配置用例。子边界不是额外的顶层测试数。证据由总负责人保存并与实际集成 commit 和补丁摘要绑定;本报告不代替该绑定。 + +策略首次轮换前若调用进程导出旧 AUTH_SECRET,会因 Compose 的环境覆盖优先级阻止新 `.env` 生效;现在在任何配置写入之前明确拒绝该覆盖。已有合法加引号的 `.env` secret 保留原编码,不去引号重写触发 `$` 插值;动态值/无法无歧义持久化的输入拒绝且不打印内容。 + +本地 ThingsVis 制品通过 `TP_THINGSVIS_IMAGE` 加 `TP_THINGSVIS_LOCAL_IMAGE_ID` 选择。执行 `docker image inspect` 核对本机身份后,只跳过该镜像的 registry pull;不同 ID 不会自动拉取或换版本。该选择器的正反例采用替身 Docker 输出,真实 Docker 镜像/配置联验仍由总负责人运行。 + +下载与 Docker Compose 输出是明确替身;文件系统、Python/Bash 入口、进程信号、子进程锁和 journal 恢复是真实执行。没有调用网络或 Docker daemon,未启动平台、Agent、插件或数据库。此结果不能标为 Linux 正式服务链、新装/数据库升级、Windows 或 J-G4 通过。 + +## 仍然阻塞的交付 + +| 项目 | 影响与负责人 | 解除条件 | +| --- | --- | --- | +| 整组签名 release manifest 与发行信任根 | installer/发布负责人;当前 HTTPS 和 updater hash 不能证明全部 payload 的独立发布身份 | 固定可信公钥/签名流程;manifest 覆盖 release commit/version、全部相对路径、摘要和长度;验证错误签名、混发、漏文件、过期/撤回策略,禁止用临时测试 key 冒充正式根 | +| 跨 updater 版本升级 | installer/发布负责人;旧已安装脚本的固定 hash 会安全拒绝新 updater,不能报自动升级闭环 | 使用已审阅新 bootstrap,或完成基于独立 trust root 的 manifest 选择与 updater 变更授权;保持无循环摘要依赖 | +| 原生 Windows | 乙 installer;PowerShell AST、真实系统锁、只读文件/NTFS/ACL、包安装均未本轮实跑 | 原生 Windows 的同套测试与实际新装/升级/恢复;不以 Linux 上 artifact 选择或解析替代 | +| activation 外部副作用协调 | 甲迁移 owner + 乙 installer;journal 故意保留 unknown,不自动重做 DB/服务效果 | 实际固定制品上证明迁移原键核对、重启/中断恢复、兼容/不兼容回退 | +| 四 profile 与完整产品链 | 甲存储 owner + 乙安装/ThingsVis;PG/unknown 守卫保留 | 同一固定制品集完成 J-G1~J-G4;MySQL+TDengine 在 PG 不可达时通过 | +| Agent 执行服务 | 乙 Agent;现有 agent/ 仍是本地持久状态内核 | 接入真实可信任务、进程/容器执行与平台围栏,并通过旧实例/重启/失联组合故障 | + +签名方案需由独立公钥验证 manifest;manifest 的签名在 payload 冻结后生成,payload 不内嵌该 manifest 的 hash,从而避免 installer、updater 和管理脚本循环互相摘要。当前仓库提供的 release workflow 只生成部分下载附件的 SHA256SUMS,没有提供可核验的正式签名公钥或相应发布证据;本轮不擅自生成发行身份。 diff --git a/docs/tasks/MVP-config-DONE.md b/docs/tasks/MVP-config-DONE.md new file mode 100644 index 0000000..2c460d7 --- /dev/null +++ b/docs/tasks/MVP-config-DONE.md @@ -0,0 +1,36 @@ +# MVP-config 完成记录 + +日期:2026-11-05 + +仓库:`thingspanel-installer` + +worktree:`/Users/junhong/Downloads/code/thingspanel-installer-develop-review/.claude/worktrees/wp-mvp-config` + +分支:`wp/mvp-config`,基于 installer develop `a540634` + +## 修改 + +- 默认 backend compose 同时提供 A1 的 `GOTP_RELATIONAL_*` PostgreSQL 配置和旧版 `GOTP_DB_PSQL_*` 配置;Redis、MQTT 和 PostgreSQL 数据库/卷设置未改。 +- `prepare.py` 与 `update.py` 在检测到 relational 配置时校验 driver、平台数据库地址、端口、库名、用户和密码字段;缺项、未插值变量或非 PostgreSQL driver 会失败关闭。仅旧键的已安装 compose 仍可通过现有升级预检。 +- `update.py` 对 legacy-only 历史/自定义 compose 继续兼容;出现 `GOTP_RELATIONAL_*` 时严格校验新配置,镜像能力不从 tag 推断。 +- 同步更新四个受 updater 摘要保护的入口脚本固定值。未改数据库迁移或用户数据路径。 + +## 镜像与升级兼容 + +- 安装器默认镜像仍是 `thingspanel-go:v1.3.0`。后端仓库的 `v1.3.0` 源码 `initialize/pg_init.go` 使用 `db.psql.*` 配置,因此 compose 保留旧键供已发布镜像和既有部署继续使用;新增 relational 键供 A1 构建读取。A1 新镜像尚未发布,本任务没有声称 compose 默认镜像已包含 A1 代码。 +- 后端 `v1.3.0` 源码检查只能证明该源码版本读取旧配置键,未在本地拉取/运行已发布镜像验证其摘要和运行行为。实际第一阶段验证 A1 时需用明确标记的本地 A1 镜像覆盖 `TP_BACKEND_IMAGE`;旧安装升级预检接受仅旧键的 compose,新默认 compose 同时满足旧、新两套配置契约。 +- 成功升级会将目标版本的 `docker-compose.yml` 作为受管制品暂存并验证;它在 `COMMON` 文件集内,验证通过后由事务替换。激活路径再执行 bootstrap、`docker compose up -d --wait` 和 verify。若阶段验证失败,旧配置不变;若中途失败,事务依阶段记录恢复或保留 activation journal,不宣称数据库回滚。目标版本可以是历史或自定义 legacy-only artifact,因此 updater 不对所有暂存 compose 强制新增键。 +- 直接把 A1 镜像放进 legacy-only 旧 compose 时,现有配置预检会兼容这份历史配置,无法从镜像 tag 可靠识别 A1 能力,可能放行而缺少 relational env。没有可信镜像能力标记时不猜版本;MVP-RUN 必须使用新默认 compose 或显式补齐 relational 环境变量,并实测启动。新默认 compose 已有 A1 所需变量。 +- `runtime.encore.json`/`runtime.notification.json` 仍指向 compose PostgreSQL 的独立 Encore 数据库;本任务未改变它们,也未给 Encore 服务额外加 driver,因为默认 Encore 资源本身由 runtime 配置连接 PG。 + +## 验证 + +- `python3 config/native/test_backend_database_guard_candidate.py`:16 项通过。覆盖默认 compose 的 A1 字段、缺字段拒绝、旧键-only升级兼容、非 PG 拒绝及凭据不进入错误文本。 +- `python3 tests/test_update_transaction.py ValidatorTests.test_pg_unknown_and_mysql_guards_remain_closed ValidatorTests.test_a1_relational_pg_profile_is_required_when_declared ValidatorTests.test_legacy_only_compose_remains_upgrade_compatible ValidatorTests.test_staged_legacy_only_compose_remains_supported ValidatorTests.test_entrypoint_helper_pins_match_reviewed_bytes`:5 项通过。 +- `git diff --check`:通过。 +- 未启动容器、数据库或真实栈;未验证 A1 镜像运行及迁移结果。 + +## 提交 + +- 当前任务交付提交位于分支 HEAD,标题为 `fix(installer): align default postgres config with A1`。 +- 当前分支提交列表以 `git log --oneline develop..HEAD` 为准。 diff --git a/docs/tasks/P1-DONE.md b/docs/tasks/P1-DONE.md new file mode 100644 index 0000000..9eff70c --- /dev/null +++ b/docs/tasks/P1-DONE.md @@ -0,0 +1,65 @@ +# P1 — HA 接入剩下的机器步骤全部自动化 + +**结论:在新栈上,只做“一条命令安装”和“在平台上选 HA 实体建设备(API 模拟界面)”,没有执行任何手工命令,上行、下行都通过。** 未推送、未合并、未发布镜像。 + +- 仓库:安装器;分支 `wp/p1-auto-steps`(从 develop `4470874` 切出);worktree `/Users/junhong/Downloads/code/thingspanel-installer-wp-p1`。 +- 提交:`7b97e9d`(功能与测试),另有一个提交含本说明和输出行微调(见 `git log wp/p1-auto-steps`)。 +- 证据(不进仓库):`/Volumes/500G/archive/evidence/2026-11-04-P1/`(已 grep:令牌和平台密码为 0 命中)。 + +## 1. 做了什么 + +| 要求 | 实现 | +| --- | --- | +| 自动执行 `sql/33.sql` | `config/native/prepare.py` 的 `bootstrap()` 在 sys_version 循环之后,把后端镜像里的 `sql/33.sql` 当作独立组件 `community-ext` 记账执行(校验和台账,重复执行跳过,文件被改动则拒绝)。**原因**:后端 `VERSION_NUMBER=25`,26–32 由后端启动时自己执行(内嵌),33 没人执行,所以 T7b 要手工跑。旧镜像没有这个文件则跳过。`apply_migrations` 的文件号解析也改成能读 `33.sql`(原来只读 `001_x.sql`)。 | +| 自动执行 `sql/broker/001–017` | 本来就在 `bootstrap()` 里(`broker` 组件)。本卡验证:新栈上 `--bootstrap` 一次到位,17 条记账;重装不重复。安装和升级(`update.py` 的 `activate_native`、`reconcile_activation`)本来就调用 `--bootstrap --refresh-devices`,不需要改入口。 | +| 修正 `--refresh-devices` | 新增纯函数 `scope_services(env, targets, plugins)`:平台账号 `tp-community-platform` 的 `allowed_device_ids/allowed_tenant_ids` = 普通 MQTT 设备 ∪ 插件设备(去重),`publish` 因此非空;协议账号仍只含插件设备。`refresh()` 与新的 `sync_scope()` 共用它,范围只有一个定义。 | +| 新增/删除插件设备后自动刷新并按序重启 | 见 §2。 | +| 单元测试 | `tests/test_p1_auto_steps.py` 20 项,见 §3。 | + +## 2. 触发方式(设计) + +**选择:安装器命令 + 宿主机上的小监视进程**,没有放进 Agent。 + +- `prepare.py --sync-scope`:查询平台设备 → 算出期望范围 → 与现有 `services.json` 比较;**没变化什么也不做**;变化则写文件,然后按 **broker-owner → mosquitto** 的顺序 `docker compose restart`(mosquitto 与 owner 共网络命名空间,必须后重启)。新增和删除设备都是“范围变化”。 +- `tools/scope_sync.py`:`once`(跑一遍)、`watch`(每 20 秒一遍,前台)、`ensure`(没有监视进程就起一个脱离终端的)、`stop`。`watch` 只在结果变化时写日志(`/scope-sync.log`),不含凭据。单次失败(例如安装器正持有更新锁)下一轮重试,不退出。 +- `plugin_install.py install` 结束时先 `once`(失败则报错),再 `ensure`;`renew`(本来就要放进 cron)也调用 `ensure`,**机器重启后下一次 renew 会把监视进程拉起来**。 +- 为什么不放 Agent:Agent 是 Go 容器,没有数据库访问和 compose 重启能力,要加 PG 驱动和 compose 权限;范围逻辑本来就在 `prepare.py`(Python),放在这里只有一份实现。代价见 §5。 +- 反应时间(实测):创建设备后 **约 12 秒** 范围刷新并重启;插件自己每 60 秒同步设备,所以新设备最长约 80 秒后可用。 + +## 3. 测试 + +- 新增 `tests/test_p1_auto_steps.py` 20 项全过:平台范围含插件设备;只有插件设备时 `publish` 仍非空(T7b 发现 3 的回归);无设备时为空范围;去重;协议账号不含 MQTT 设备;范围不变不写不重启;新增/删除都触发;首次无文件;写文件失败时不重启;`--refresh-devices` 同口径;`33.sql` 记账一次、重复跳过、被改动则拒绝;`bootstrap()` 用假 Docker 走一遍,33.sql 在 broker 之前执行,旧镜像无该文件时跳过;监视器 `run_once` 不抛异常、`watch` 失败后继续且只记变化、`ensure` 幂等且不被回收的 pid 欺骗。 +- 回归:`tests/` 全部 107 项 OK(含新增的);`tools/test_plugin_install.py` 18 项 OK;`config/native` 下三个测试文件 21 项 OK。 +- **这些是单元测试,不是端到端验收**;端到端见 §4。 + +## 4. 验收(真实栈,容器名 `p1-stack-*`、`p1-homeassistant`) + +环境(验收脚手架,不是产品步骤): +- 栈用本分支的 `docker-compose.yml`(项目名 `p1-stack`),`docker-compose.override.yml` 只把 broker-owner/mosquitto 换成本机 develop 构建的 `thingspanel-mosquitto:t7b-local`(发行的 v1.3.0 镜像仍过旧,见 §5)。只起 postgres、redis、broker-owner、mosquitto、backend(前端、encore、notification 没起,不影响本链路)。 +- 后端:develop `09fe900a` 交叉编译 linux/arm64,叠在 v1.3.0 镜像上成 `thingspanel-go:p1-local`(带 develop 的 `sql/`、各 `migrations/`、`global.go`,`bootstrap()` 从这里读)。 +- demo HA:`ghcr.io/home-assistant/home-assistant:stable` + demo 集成;本卡自己 onboarding 并建了长期令牌,结束后随容器删除。插件镜像 `thingspanel-homeassistant:p1-arm64`(HA 仓库 `wp/t6-ha-package` `5394d9c`,主机交叉编译;依赖本地 SDK replace)。目录用测试密钥签名。 +- “一条命令” = `/Volumes/500G/p1-stack/p1-install.sh`:与安装器 `activate_native` 同样的调用(`prepare.py`、`--bootstrap --refresh-devices`、`compose up`)加 `plugin_install.py install`。**没有跑 `install.bash`**(它从线上拉发布的镜像,develop 镜像未发布)。 + +| 步 | 结果 | 证据 | +| --- | --- | --- | +| 1 一条命令 | 退出码 0,约 90 秒:`33.sql` 与 17 个 broker 迁移自动记账(`community-ext|33`);服务插件自动登记;generation 1,健康检查(含稳定别名)ok;监视进程已起 | `step1-install.log`、`migration-ledger.txt` | +| 2 平台上选实体建设备(API 模拟 UI) | 建接入点,列出 33 个 HA 实体,选 Bed Light 和 Outside Temperature 批量建设备 | `step2-create-devices.log` | +| (无人干预)范围刷新 | 19:52:52 建设备,19:53:04 监视进程发现变化,写入 `services.json`(平台账号 2 台设备、`publish` 12 条),重启 owner → mosquitto;backend 和插件自动重连,**没有重启插件和后端** | `scope-sync.log`、`mosquitto.log`、`services-scope-summary.txt` | +| 3 上行 | HA 里改温度,平台当前值 `ha_state` = 新值;灯的状态/亮度等多项属性入库 | `step3-uplink.log` | +| 4 下行 | 平台下发 `switch` false→true→false,HA 灯 off/on/off,三次回执 `result:0`、状态 3 | `step4-downlink.log` | +| 5 新增 + 删除设备 | 加 Decorative Lights、删 Outside Temperature:约 12 秒后范围换成 {Bed Light, Decorative Lights},owner → mosquitto 按序重启 | `step5-add-remove.log`、`scope-sync.log` | +| 6 新设备下行/上行 | 第一条命令在插件同步到设备之前发出:**平台显示失败**(状态 4,`device number … is not bound in connector`),命令确实到达了插件,说明范围是对的;约 40 秒后下发 false/true 成功(状态 3,`result:0`),新设备有 `ha_state` 历史 | `step6-new-device-downlink.log` | +| 7 重装 | 再执行一次同一条命令:退出码 0,generation 2,`community-ext` 仍 1 行,监视进程复用(`running`),只有 1 个插件容器 | `step7-reinstall.log` | + +收尾:`p1-stack-*` 容器、卷、网络、`p1-homeassistant`、`tp-agent-p1-stack`、两个 `tp-agent-prepared-*` 容器已删(只含本卡创建的);监视进程已停;HA 令牌、`.env`、broker 凭据、HA 配置已从栈目录删除。栈目录 `/Volumes/500G/p1-stack/`(脚本、二进制、目录、构建物)留给审查,可整个删除。 + +## 5. 没做 / 局限 / 需要知道 + +- **监视进程不是系统服务**:机器重启后它不会自己回来,直到下一次 `plugin_install.py renew`(cron)或再次 `install`。要彻底解决需要 launchd/systemd 单元或把逻辑放进长期运行的容器,未做(要先定平台范围)。如果监视进程停了,新设备的下行会被 Broker 静默丢弃——这正是 P3(后端让命令超时失败可见)要补的另一半。 +- **发行版 Broker 镜像仍须重建**:验收用的是本机的 `thingspanel-mosquitto:t7b-local`;`docker-compose.yml` 里仍写 v1.3.0,新栈用发行镜像仍会 CONNACK 5(P4 发布镜像后改引用)。同理 HA 插件目录里的镜像 ID(`plugins/homeassistant.json`)指向已删的 `t7c` 镜像,验收用的目录是临时重签的。 +- 范围上限沿用原来的:普通设备 ≤256、插件设备 ≤256;HA 实体多于 256 台设备会报错,需另设计多身份。 +- 新设备从创建到可用最长约 80 秒(监视 20 秒 + 插件同步 60 秒);期间下发命令会如实显示失败。 +- 监视进程每 20 秒执行一次 `prepare.py`(会跑 `docker compose config` 和一次查询),开销小但不是零;未做事件驱动。 +- 未改后端(`33.sql` 未被后端自己执行是后端侧的设计,若要改应由后端在启动时执行并记账);未改 Agent;未跑 Windows 路径。 +- `update.py` 在升级中途持有更新锁时,监视进程的那一轮会失败并在下一轮重试(单元测试覆盖了“失败不退出”,没有在真实升级中演练)。 +- Agent 创建的插件容器名 `tp-agent-prepared-*` 是代码固定的,没有 `p1-` 前缀(同 T7c 记录)。 diff --git a/docs/tasks/P1-FIX-DONE.md b/docs/tasks/P1-FIX-DONE.md new file mode 100644 index 0000000..a3ec94d --- /dev/null +++ b/docs/tasks/P1-FIX-DONE.md @@ -0,0 +1,22 @@ +# P1 scope retry and concurrency fix + +**Branch:** `wp/p1-fix-retry-lock`, created from installer `develop` at `27840cdc19e4b50a01aeef44deaac27d95e93cef`. + +**Worktree:** `/Users/junhong/Downloads/code/thingspanel-installer-wp-p1-fix`. + +## Changes + +- `config/native/prepare.py --sync-scope` now holds the installer's cross-process update lock from database scope query through file update, ordered container restarts, and completion acknowledgement. +- A durable pending-restart record is written before updating `services.json`. If either `broker-owner` or `mosquitto` restart fails or the process stops, the record remains. The next pass retries both restarts even when the config file already matches the current database scope. +- `tools/scope_sync.py ensure` uses that same lock around PID validation, watcher creation, and atomic PID write, preventing concurrent installers/renewals from starting duplicate watchers. `plugin_install.py install` and `renew` retry `busy` for up to five minutes, then fail with a nonzero result if the watcher still cannot start; they do not report success with the watcher absent. +- Added regressions for restart failure and retry, overlapping scope runs, concurrent watcher startup, install/renew waiting through a real update-lock conflict, and persistent lock contention returning an error. + +## Validation + +`PYTHONPATH=tests python3 -m unittest tests.test_update_transaction tests.test_prepare_auth_secret tools.test_plugin_install tests.test_p1_auto_steps` + +Result: 93 tests passed. + +## Known migration limitation + +P1's `bootstrap()` still intentionally skips `33.sql` when the selected backend image does not contain it, to preserve old-image compatibility. The installer does not currently distinguish a supported old image from a newer image that was accidentally built without `33.sql`; therefore a missing required migration can still go unnoticed. This task leaves that policy unchanged as requested. diff --git a/docs/tasks/PH1-S2-DONE.md b/docs/tasks/PH1-S2-DONE.md new file mode 100644 index 0000000..1b554ee --- /dev/null +++ b/docs/tasks/PH1-S2-DONE.md @@ -0,0 +1,68 @@ +# PH1-S2 — 安装器识别新镜像漏打包迁移 + +## 判定依据 +用**镜像内标记**:同一个后端镜像里是否存在 `/go/src/app/internal/pluginidentity`(插件身份的 Go 源码,与 `sql/33.sql` 同一功能、同一镜像分发,`Dockerfile` 用 `COPY --from=builder /go/src/app .` 整目录带入,`bootstrap` 本来就从同一路径 `docker cp` 取 `sql/`)。 + +- 有标记 = 新镜像,`sql/33.sql` 必须存在,缺则失败。 +- 明确没有标记 = 旧镜像(如已发布的 v1.3.0),跳过并记日志。 + +为什么不用别的: +- `VERSION_NUMBER`:develop 上仍是 25,而 `33.sql` 已存在(它本来就不走 sys_version),无法区分。 +- 镜像 tag/版本号:本地 A1 镜像用任意 tag 和 image ID 固定,无法解析。 +- 发行清单声明迁移列表:要改后端发布流程和清单格式,改动大。 + +## 改动 +`config/native/prepare.py`:新增 `image_has_marker()`、`required_extra_sql()`;`bootstrap()` 调用它们替换原来的“有就用、没有就悄悄跳过”。报错写明缺的文件(`sql/33.sql`)和镜像名。 + +## 无法判定时的默认行为 +`docker cp` 返回的不是“找不到文件”(例如 Docker 异常)→ **失败**,不猜。理由:中止可以重试,静默跳过会造成无报错的插件故障。 + +## 测试 +新增 `tests/test_migration_guard.py`(7 个):新镜像有文件、新镜像缺文件(失败,信息含文件名和镜像名)、旧镜像无文件(跳过+日志)、旧镜像有文件(照常应用)、标记存在/明确不存在/无法判定(失败)。 +另改了 `tests/test_p1_auto_steps.py` 里 bootstrap 的端到端 mock 测试:新增对 `image_has_marker` 的 mock(有 33.sql 视为新镜像)。 + +全量结果(证据:`/Volumes/KIOXIA/archive/evidence/2026-11-05-PH1-S2/tests.log`): +- `tools/test_plugin_install.py`:20 个,全部通过。 +- `python3 -m unittest discover -s tests`:120 个,**14 个错误,全部在 `tests/test_download_failure.py`**(install/upgrade 的 shell 脚本在本机超过测试内置的 20 秒超时)。**这些错误不是本改动引起**:在未改动的 develop `4a8f286` 干净检出上单独跑同一用例(`test_upgrade_each_download_failure_preserves_old_files`)同样失败(超时)。除这 14 个外,其余 106 个通过,含新增 7 个。 +- 因此任务要求的“全部通过”**未达成**:`test_download_failure` 在本机是已存在的环境性失败,未在这里修。 + +## 真实镜像验证(只读,未起栈,未碰运行中的容器) +脚本对每个镜像 `docker create` → `image_has_marker()` → 取 `/go/src/app/sql` → `required_extra_sql()`;日志:`/Volumes/KIOXIA/archive/evidence/2026-11-05-PH1-S2/real-image-verify.log`。 + +| 镜像 | 标记 | 结果 | +|---|---|---| +| `…/thingspanel-go:v1.3.0` | 无(真实报错 `Could not find the file /go/src/app/internal/pluginidentity in container …`,被正确识别为“不存在”) | 旧镜像,跳过并记日志,应用 `[]` | +| `thingspanel-go:mvp-run-a29fecc` | 有 | 新镜像,取到 `33.sql`,应用 `['33.sql']` | +| `thingspanel-go:p1-local` | **无**(其 `internal/` 里没有 `pluginidentity`,但 `sql/33.sql` 存在) | 判为旧镜像,但因文件存在仍应用 `['33.sql']` | +| 由 mvp-run-a29fecc 派生、删掉 `sql/33.sql` 的临时镜像 | 有 | **失败**:`…contains internal/pluginidentity but is missing required migration sql/33.sql; the image was packaged incorrectly. Refusing to continue.` 临时镜像已删除 | + +**发现的局限(需总监知晓)**:`p1-local` 带 `33.sql` 却没有 `internal/pluginidentity`(只有 SQL,Go 代码是更早的版本)。对它,当前逻辑安全(文件在就应用),但如果将来有“只带旧 Go 代码、却漏了 `33.sql`”的这类中间镜像,会被当成旧镜像静默跳过——标记只能识别带完整插件身份源码的镜像。要覆盖这种情况只能改用发行清单声明迁移列表(需改后端发布流程),本卡未做。 + +## 合并 `wp/pui-agent` 后的修正(语义冲突) +`wp/pui-agent` 加入 `sql/34.sql`、`35.sql`(后端 `internal/plugininstall`)。单一标记会把“只有插件身份、没有插件安装”的镜像(如 `ph1-520a3222`)误判为漏打包。已按要求 **merge(未 rebase)** 并改为“每组迁移各有自己的标记”: + +`EXTRA_SQL_REQUIREMENTS = (('internal/pluginidentity', ('33.sql',)), ('internal/plugininstall', ('34.sql','35.sql')))` + +哪个标记存在,就要求对应那组文件必须在,缺则失败(报错列出缺的文件和镜像,多个一起列);标记不存在的组跳过并逐文件记日志;文件存在则无论标记如何都照常应用。以后加迁移只需在映射表加一行。`EXTRA_COMMUNITY_SQL` 由映射表派生。 + +新增/更新测试(`tests/test_migration_guard.py`,共 7+3 个):只有 identity 标记(只要求 33,34/35 跳过)、两个标记都有(要求 33–35)、有 install 标记缺 34(失败,只报 34)、有 identity 标记缺 33(失败)、旧镜像(全部跳过并记日志)、有文件无标记(照常应用)、标记探测的三种结果。 + +真实镜像核对(只读;`real-image-verify-merged.log`): +- v1.3.0:无标记,无 33–35,全部跳过,应用 `[]`。 +- `ph1-520a3222`:只有 identity 标记,有 `33.sql`,34/35 跳过,应用 `['33.sql']`(不再误判)。 +- `mvp-run-a29fecc`:同上,应用 `['33.sql']`。 +- 附带观察:`thingspanel-go:pui` 有 33、34,没有 35,两个标记都没有(Go 源码目录不在镜像里);因此按“无标记”处理,应用 33、34,跳过 35。这是前述标记局限的又一例,不是 bug,但说明该镜像缺 35 不会被发现。 +- “有 install 标记缺 34”只在单元测试中覆盖,没有为它构造真实镜像。 + +全量测试结果见下方“最终测试结果”。 + +## 没做 +- 未跑完整 `bootstrap()` 端到端(不起栈、不连数据库);探测与取文件逻辑已在真实镜像上验证,见上。 +- 若后端以后重命名/移除 `internal/pluginidentity`,需同步修改 `EXTRA_SQL_MARKER`。 +- 未推送、未合并。 + +## 最终测试结果(合并 pui-agent + 标记映射后) +证据:`/Volumes/KIOXIA/archive/evidence/2026-11-05-PH1-S2/tests-merged.log` +- `python3 -m unittest discover -s tests`:123 个,全部通过(19.6 秒;这次 `test_download_failure` 没有超时,之前的超时应是当时机器负载造成,未再追查)。 +- `tools/test_plugin_install.py`:17 个,全部通过(合并后的版本数量与之前的 20 个不同,来自 pui-agent 分支的改动)。 +- 上文较早的“14 个错误”是合并前的那次运行结果,已被本次取代。 diff --git a/docs/tasks/T5-DONE.md b/docs/tasks/T5-DONE.md new file mode 100644 index 0000000..ea64820 --- /dev/null +++ b/docs/tasks/T5-DONE.md @@ -0,0 +1,57 @@ +# T5 — 安装器与 SDK:签发身份并带上身份 + +未推送、未合并。接口依据:T4 的 `docs/plugin-runtime-identity.md`。 + +## 三个仓库 +| 仓库 | 分支 / 提交 | +| --- | --- | +| 安装器 `/Users/junhong/Downloads/code/thingspanel-installer`(worktree `thingspanel-installer-wp-t5`) | `wp/t5-identity`,基于 `wp/t6-ha-catalog`:`b9639de`(身份/binding none/env_user/uninstall)、`71647da`(HA 条目指向 SDK v0.2.0 镜像)、`d60464b`(卸载后重装接管、回归脚本) | +| SDK(新目录 `/Users/junhong/Downloads/code/thingspanel-device-connector-sdk-go`) | 来源:`go mod download` 取得的 v0.1.0 源码(原仓库 commit 0ee1d177),`git init`,`e3692bb` 为原样导入并 tag `v0.1.0`;`6c744a2` 为本任务改动,tag **`v0.2.0`**(本地,未推送) | +| HA 插件(worktree `.claude/worktrees/t6`) | `wp/t6-ha-package`:`cb6c4de`(SDK→v0.2.0) | + +## 做了什么 +- **签发/吊销(安装器)**:`agent_install` 每次安装/升级用 `generation = 旧值+1` 向 `POST /api/v1/plugin/runtime/identity` 签发;`uninstall` 先让 Agent revoke 再调 `identity/revoke`;代次计数保留在 Agent 插件状态文件里,所以重装一定比任何已吊销代次高。Agent 步骤失败时会尽力吊销刚签发的身份。状态文件丢失导致 409 时给出明确提示。 +- **注入**:身份只通过 Agent profile 的容器环境变量注入:`TP_PLUGIN_RUNTIME_TOKEN`(目录条目可用 `identity.token_env` 改名,http-adapter 用 `P_PLATFORM_API_TOKEN`)和 `TP_PLUGIN_SERVICE_IDENTIFIER`。不进镜像、不打印;`profiles.json` 在容器创建后立即重写为不含令牌(实测 `grep pri_` = 0)。令牌仍在容器配置里(`docker inspect` 可见),这是环境变量方式的固有性质。 +- **`binding: none`**:不创建协议模板,不支持 `--device`(明确报错);有 `health` 时安装结束会探测健康检查。`plugin_catalog.check_entry` 校验 binding 与必填字段。 +- **`env_user`**:`--set KEY=VALUE`(非 secret)→ 同名环境变量 → 条目 `default` → 终端交互提示(secret 用 getpass 不回显);`--non-interactive` 缺项即失败。secret 字段拒绝 `--set`(避免进 ps / shell 历史)。支持 `validate: url`、`pattern`;拒绝换行/NUL。用户值不落盘。 +- **SDK v0.2.0**:新增 `PlatformClient`(`Heartbeat/DeviceConfig/Devices/ServiceAccessList/ServiceAccess/Post`),统一带 `Authorization: Bearer`;无令牌时不发请求(`ErrNoRuntimeIdentity`);503 `PLUGIN_RUNTIME_IDENTITY_REQUIRED`→`ErrIdentityRequired`,403→`ErrScopeDenied`,`IsAuthFailure` 为真即不重试;内置心跳循环收到后只记一条错误并停止。`ConnectorInfo` 带 `RuntimeToken`,`%v/%+v/%#v` 打印脱敏。`FromEnv` 读 `TP_PLUGIN_RUNTIME_TOKEN` / `_FILE`、`TP_PLUGIN_SERVICE_IDENTIFIER`(优先于 `CONNECTOR_SERVICE_IDENTIFIER`)。 +- **HA 插件**:`go.mod` 升到 v0.2.0;`startup_sync` 改用 SDK 的 `Platform()` 客户端,遇身份/越权错误立即停止重试。 + +## 测试与结果 +- SDK:`go vet ./... && go test -count=1 ./...` → ok(含新增 7 个用例:5 入口带 Bearer、无令牌不发请求、503/403 区分、普通 503 可重试、心跳在被拒后只调用 1 次、令牌不进格式化输出、令牌文件)。 +- 安装器:`python3 -m unittest tools/test_plugin_install.py` → 12 项 OK。 +- HA:`go vet ./... && go test ./...` → ok(SDK 走本地 replace)。 +- **回归(真实栈)**:`tools/regress_identity.py`,http-adapter,栈 `t5-stack`(T4 worktree 构建的后端二进制 + timescaledb pg16 + redis + 匿名 mosquitto,已 `compose down -v` 删除;未碰 `tp-develop-local`)。最终日志 `regress-3.log`,全部 PASS: + 1. 安装 → 代次 1 成功;2. 容器环境里有 `pri_.`;3. 带新身份取设备配置 HTTP 200(无身份 503 `PLUGIN_RUNTIME_IDENTITY_REQUIRED`);4. 卸载成功;5. 旧身份 → 503,容器已停;6. 重装 → 代次 2;7. 旧身份 503、新身份 200。 +- **HA 一条命令**(`ha-install.log`):`plugin_install.py install --plugin homeassistant --set HA_BASE_URL=... `(`HA_ACCESS_TOKEN` 走环境变量)→ binding none,容器 `/health` 返回 ok;后端日志显示 HA 的 `plugin/heartbeat`、`plugin/service/access/list` 均 200,库中身份 `homeassistant|homeassistant|1`;随后卸载,身份被吊销。 +- 证据放在 `/Volumes/500G/t5-stack/evidence/`(`regress-1/2/3.log`、`ha-install.log`、`lost-state-409.log`)。`/Volumes/80G` 在本次中途写入卡死(dd 超时),所以没有放进约定的 `/Volumes/80G/archive/evidence/2026-11-04-T5/`(该目录里只有 build/test 日志);需要负责人挪动。 + +## 与 HA 镜像 +- 新镜像(arm64,本机)`sha256:f7a78a7e32ceb6b5f72f3f3de634e32040e695346c519713125d744324e93d08`,tag `thingspanel-homeassistant:t5-arm64`,目录条目 `plugins/homeassistant.json` 已更新(版本 `1.0.0-t5`)。 +- **构建依赖本地 SDK**:`go.mod` 里有 `replace … => ../../../../thingspanel-device-connector-sdk-go`(仅本地开发;SDK 推送并发布 v0.2.0 后必须删除)。镜像用 `Dockerfile.local` 构建: + `docker build --platform linux/arm64 --build-context sdk= -f Dockerfile.local -t thingspanel-homeassistant:t5-arm64 .` + 原 `Dockerfile` 未改,替换 replace 后可继续用。amd64 未构建。 +- 目录用本地测试密钥签名(`/Volumes/500G/t5-stack/keys/`,不入库),正式信任根和 GitHub 签名本期不做。验签通过:`catalog vt5-1 verified: http-adapter@1.2.0-identity, homeassistant@1.0.0-t5`。 + +## 没做 / 注意 +- 后端用的是 T4 worktree(`claude/wp-t4-plugin-identity-3cf9d2`)构建,没有用合入 develop(563e2497)后的代码重测;PG 迁移 `sql/33.sql` 后端启动时**不会**自动执行,回归时手工 `psql < 33.sql`(T4 文档已说明由安装/升级流程执行,目前仍缺这一环)。 +- 没有真实 Home Assistant:HA 插件用假地址/假令牌,只验证了健康检查和平台调用;HA 数据打通属 T7。 +- 心跳不续租:身份 ≤24h,到期前必须再次 `install`(新代次)才能续;`renew` 只延长 Agent 租约,不续身份(后续工作)。 +- 回归没有走 `--device` 路径(它依赖 Broker 重载,本次最小栈没有 broker-owner)。 +- 只在 arm64 验证;Docker 日志驱动为 none,无法读取插件容器日志,插件侧靠健康检查与后端访问日志证明。 +- 事故:排查构建卡死时我执行过 `pkill -f "go build ./..."`,可能误杀其他会话同时运行的 `go build ./...`;其他会话如遇到异常中断,请重跑。 + +## 给 T7(HA 端到端)的用法 +1. 起平台栈(需含 T4 后端、`plugin_runtime_identities` 表已迁移、Broker/MQTT 账号写入栈 `.env` 的 `TP_PROTOCOL_MQTT_USER/PASSWORD`)。 +2. 镜像:本机需有 `sha256:f7a78a7e…`(见上);签名目录用 `tools/plugin_catalog.py publish --key <测试密钥> --out DIR --version N --plugin-file plugins/homeassistant.json`。 +3. 安装(HA 令牌不要写命令行): + ``` + TP_TENANT_EMAIL=... TP_TENANT_PASSWORD=... HA_ACCESS_TOKEN=... \ + python3 tools/plugin_install.py install --catalog DIR/plugin-catalog.json --trust-root trust-root.pem \ + --plugin homeassistant --set HA_BASE_URL=http://:8123 --stack-dir <栈目录> --web-url http://127.0.0.1:<端口> \ + --agent-dir --agent-bin tp-agent --agentctl-bin tp-agentctl + ``` + 终端运行时缺 `HA_*` 会提示输入,secret 不回显;脚本里加 `--non-interactive`。 +4. 卸载:同样参数换 `uninstall --plugin homeassistant`(不需要 catalog/agent-bin)。重装自动使用更高代次。 +5. 升级/续身份:再次 `install`。 +6. 若出现 409「平台已有 ≥N 代次」:Agent 状态文件丢失,需要恢复 `/plugins/homeassistant.json` 或在后端侧清理。 diff --git a/docs/tasks/T6-DONE.md b/docs/tasks/T6-DONE.md new file mode 100644 index 0000000..81065d6 --- /dev/null +++ b/docs/tasks/T6-DONE.md @@ -0,0 +1,22 @@ +# T6 — HA 插件打包进签名目录 + +分支:installer `wp/t6-ha-catalog`(基于 `wp/i1-pg-profiles` @ 6e5f356);HA 插件仓库 `wp/t6-ha-package`(基于 4d8d45b,提交 aff6a16)。未推送。 + +## 做了什么 +- **镜像**(Dockerfile 无需修改,仅加 `.dockerignore`): + - linux/arm64 `sha256:ee93832cc57d93424f050f359e9bc716ff2dddfaff6075ddbb4b20d3132fcbba`(目录条目固定此值) + - linux/amd64 `sha256:fff8b89185a131b2530f1366682cec0940de005ce3760b5c15f28316bb2c6ba4`(已构建,未入目录;多架构需 registry 摘要) + - 镜像仅在本机,未推送 registry。 +- **目录条目** `plugins/homeassistant.json`:端口 9001、健康检查 `/health`;用户必填 `env_user`:`HA_BASE_URL`、`HA_ACCESS_TOKEN`(secret);自动填写 `CONNECTOR_SERVICE_IDENTIFIER=homeassistant`、`CONNECTOR_INSTANCE_ID=homeassistant-1`、`THINGSPANEL_BACKEND_URL=http://backend:9999`、`TP_MQTT_BROKER=tcp://mosquitto:1883`,MQTT 账号来自栈 `.env` 的 `TP_PROTOCOL_MQTT_USER/PASSWORD`。不指向 gmqtt。 +- `platform` 块写成 `{"binding":"none",...}` 仅为通过 `check_entry`(它要求该键存在)。 + +## 验证 +- `plugin_catalog.py publish`(本地测试密钥,未提交)→ `verify`:`catalog vt6-1 verified: homeassistant@1.0.0-t6, http-adapter@1.2.0-identity`。篡改版本号后验签:`bad_signature`。 +- Agent 安装:在隔离 docker 网络 `t6-ha-net` 上,用 `plugin_install.Agent` 走 ensure_running → accept-generation → prepare → grant → activate,generation 1 运行;对容器 `GET :9001/health` 返回 `{"instanceID":"homeassistant-1","serviceIdentifier":"homeassistant","status":"ok"}`。测试容器与网络已删除。 + +## 没做到 / 偏差 +- **没有用 `plugin_install.py install` 一条命令**:它固定创建协议设备模板,并在 `agent_install` 里向 `/api/v1/plugin/runtime/identity` 申请身份(6e5f356 WIP,T4/T5 范围,我没改)。HA 没有协议模板,所以我用同一 Agent 调用序列的草稿脚本(不入库)替代。让一条命令可用需要 install 支持 `binding: none`、`env_user` 提示/校验,建议在 T5 一并做。 +- **没有对接真实平台栈**:本机 `tp-develop-local` 是别人的集成夹具,无 `TP_PROTOCOL_MQTT_*`,网络名不同,不去碰。因此 MQTT 用假账号、HA 地址/令牌是假值;MQTT 连接、取设备配置(预期 503)、与 HA 真实通信均未验证。 +- 只验证了 arm64;amd64 镜像未运行。 +- HA 仓库 main 上有未提交改动(handler.go、ha_client.go、main.go、startup_sync.go、README.md、ha_actions.go、capabilities_test.go),镜像基于已提交的 4d8d45b,不含这些。 +- 未注册 worktree 到 `docs/WORKSPACES.md`(该文件在后端仓库,本任务不改后端);需负责人登记:两个 worktree 路径见上。 diff --git a/docs/tasks/T7-DONE.md b/docs/tasks/T7-DONE.md new file mode 100644 index 0000000..0011f28 --- /dev/null +++ b/docs/tasks/T7-DONE.md @@ -0,0 +1,45 @@ +# T7 — HA 一键安装端到端:数据打通 + +**结论:第 1、2、5、6 步通过;第 3、4 步(上行、下行)没有通过,没有任何数据进入平台。** 根因在后端/Broker 发行物,不在安装器和 HA 插件,按任务规则停下记录,没有扩大范围。未推送、未合并;本任务没有修改任何仓库的代码(只新增这份说明)。 + +证据目录(不进仓库):`/Volumes/500G/archive/evidence/2026-11-04-T7/`(80G 盘写入慢,按总监要求放 500G;需要负责人挪动)。栈目录 `/Volumes/500G/t7-stack/`(只剩 compose 文件和二进制,容器、卷、网络、凭据已删)。 + +## 环境 +- 后端:develop `563e2497` 交叉编译 linux/arm64,挂进 v1.3.0 后端镜像;timescaledb pg16、redis、Home Assistant(`ghcr.io/home-assistant/home-assistant:stable`,demo 集成 + 虚拟实体)。 +- **`sql/33.sql` 是手工 `psql` 执行的**(后端启动不会执行,安装流程也没有这一环);`sql/broker/001–017` 同样手工执行。 +- Broker:先用 `thingspanel-mosquitto:v1.3.0` + broker-owner,带 `TP_PROTOCOL_MQTT_USER/PASSWORD`(见第 3 步)。 +- 安装器 `wp/t5-identity`(`e0102f9`),插件镜像 `thingspanel-homeassistant:t5-arm64`(`sha256:f7a78a7e…`),T5 的测试密钥目录。 +- HA 的 long-lived token 只经环境变量传给安装命令;测试结束已在 HA 里撤销(旧 token 访问返回 401,`ha-token-revoked.log`)。 + +## 逐步结果 +| 步 | 结果 | 证据 | +| --- | --- | --- | +| 1 一条命令安装(只给 HA 地址和 token) | **通过**。generation 1,容器 `/health` 返回 ok;后端日志里 `plugin/heartbeat`、`plugin/service/access/list` 均 200,MQTT 命令桥连上 Broker | `step1-install.log` | +| 2 发现 HA 实体并在平台生成设备 | **通过,但不是自动的**:插件列出 33 个实体,我用平台 API 注册服务插件、建接入点、批量建了 3 台设备(灯 Bed Light、温度、湿度)。安装本身不会建任何平台对象 | `step2-discovered.json`、`step2-create-devices.log` | +| 3 上行(HA 改值 → 平台当前值/历史) | **失败**,平台 0 条遥测 | `step3-real-broker-denied.log` | +| 4 下行(平台开关灯 → HA 变化 → 回执) | **未能测试**:设备/插件在真实 Broker 上连不上,命令发不出去 | 同上 | +| 5 重复安装 | **通过**:generation 升到 2,旧容器被替换,始终只有 1 个插件容器;设备仍是 3 台,接入点 1 个、服务插件行 1 个;旧代次身份已吊销 | `step5-reinstall.log` | +| 6 卸载 | **通过(历史数据部分无法验证)**:身份 1、2 均已吊销,容器 Exited,3 台设备和接入点保留,用旧令牌调心跳返回 503。因为第 3 步没有数据,“历史数据保留”没有被验证 | `step6-uninstall.log` | + +## 第 3、4 步失败的根因(后端 / Broker,不在 1 小时内可修) +1. **发行版 Broker 镜像比 develop 旧,插件设备连不上。** HA 插件的上行是“每台设备用自己的凭据(voucher 里的 username)连 Broker 发 `devices/telemetry`”,命令桥用服务账号订阅 `plugin/homeassistant/devices/command/+/+`。在 `thingspanel-mosquitto:v1.3.0`(构建于 10-29)上: + - 服务账号带设备范围、设备自带凭据,都返回 CONNACK 5(not authorised);去掉设备范围后服务账号能连上,说明是“设备范围解析”被拒。 + - 把 broker-owner 换成用 `563e2497` 构建的 `tp-broker-owner`(含 `7bfaff53`)后,owner 开始正常发放授权(`broker_plugin_contexts`、`broker_transport_bindings` 有新行),但 Mosquitto 仍返回 CONNACK 5。推断是镜像里的 `tp-mosquitto-plugin.so` 也需要用 develop 重建(`deploy/mosquitto-community/Dockerfile.production`)。这是推断,没有重建验证。 +2. **换成不带身份映射的普通 Mosquitto 也不行**:插件发布的 `devices/telemetry` 载荷里没有 `device_id`,后端报 `device_id cannot be empty`。也就是说 HA 插件依赖 Broker 按凭据注入设备身份,不能脱离新 Broker 使用。 +3. 修复需要:用 develop 重新构建并发布 `thingspanel-mosquitto` 镜像(owner + 插件库),安装器的 `config/native/prepare.py` 里服务账号的设备范围(`--refresh-devices`)也要在“建完 HA 设备”之后刷新并重启 broker-owner/mosquitto。这部分属于后端/发行物,交总监决定。 + +## 其他发现(没有修,需要排期) +- **安装不会在平台登记服务插件**:`binding: none` 时平台没有 `service_plugins` 行,必须有人手工建,且 `service_config` 必须带 `sub_topic_prefix: plugin/homeassistant/`(Broker 和下行路由都用它)和 `http_address`。建议安装器在 `binding: none` 的服务型插件上幂等登记。 +- **`http_address` 在重装后失效**:Agent 容器名带代次哈希(`tp-agent-prepared-`),第 2 代起平台里登记的地址指向已删除的容器。需要稳定的网络别名或登记时用别名。 +- **插件只在启动时同步设备**(`startup_sync` 只跑一次):之后在平台新建的设备插件不知道。我为让它看到设备手工 `docker restart` 了一次插件容器。建议插件周期性拉 `service/access/list`。 +- **后端会把 HA token 写进日志和操作日志表**:创建接入点时 voucher 整段进入请求日志,设备列表请求出错时 voucher 被拼进 URL 并打到错误日志。另外 voucher 里的 token 会明文存进 `service_access.voucher`。安装时只给一次 token、平台里又要重输一次,也是体验问题。 +- 后端用字符串拼接把 voucher 放进 URL,不做编码:voucher 必须是紧凑 JSON(无空格),否则插件返回 400。 +- 平台服务接入点列表接口(`service/access/list`)对该租户返回空列表,但创建后可以直接用 ID 操作;没有深究。 +- 第 7 步(TDengine,可选)没做。 + +## 修了什么 +没有修改任何仓库(安装器、SDK、HA 插件、后端都没有新提交)。 + +## 复现/清理 +- 栈:`/Volumes/500G/t7-stack/docker-compose.yml` + `broker.yml`(容器名均带 `t7-`;Agent 创建的插件容器名是 `tp-agent-*`,已一并删除)。 +- 收尾已执行 `compose down -v`、`docker rm -fv`,网络和 `t7-stack_mosquitto_data` 卷已删;`tp-develop-local` 未触碰。 diff --git a/docs/tasks/T7c-DONE.md b/docs/tasks/T7c-DONE.md new file mode 100644 index 0000000..214e745 --- /dev/null +++ b/docs/tasks/T7c-DONE.md @@ -0,0 +1,28 @@ +# T7c — 修复 T7 发现的三处安装体验缺口 + +未推送、未合并。分支:安装器 `wp/t5-identity`;HA 插件 `wp/t6-ha-package`(`5394d9c`)。SDK、后端未改。 + +## 做了什么 +1. **安装器自动登记服务插件**(`tools/plugin_install.py`):目录条目的 `platform.service_plugin`(`name`、`service_type`、`config`)声明要登记的字段,`config` 里可用 `{alias}`、`{http_port}`。`binding: none` 安装时用租户登录经平台现有 API 幂等登记:先分页 `GET /api/v1/service/list` 按 `service_identifier` 精确查找;没有则 `POST /api/v1/service`,有则 `PUT` 刷新声明的字段(保留已有的其他配置键和备注)。HA 条目声明 `sub_topic_prefix=plugin/homeassistant/`、`http_address={alias}:{http_port}`。目录校验:`service_plugin` 只允许 `binding: none`,`http_address` 要求有 `http_port`。 + - **卸载保留这条记录,只吊销身份**(Agent 吊销 + `identity/revoke`)。理由:设备、接入点通过 `service_plugin_id` 引用它,删除会让它们变孤儿;重装可复用同一条记录。已验证卸载后记录仍在。 +2. **稳定地址**:Agent profile 新增 `network_alias`(`agent/prepare.go`、`agent/docker_prepare.go`),创建容器时通过 Docker `NetworkingConfig` 加网络别名,必须同时有 `network`,格式限制为小写 DNS 标签;巡检(`safePreparedContainer`)会校验别名存在,缺失视为不可信。安装器给每个插件用 `tp-plugin-`(可由 `platform.network_alias` 覆盖),安装结束的检查增加“经别名访问健康接口”。平台登记的 `http_address` 只用别名(`tp-plugin-homeassistant:9001`)。 +3. **HA 插件周期同步**(`startup_sync.go`):启动同步后,每 `HA_DEVICE_SYNC_INTERVAL_SECONDS`(默认 60,下限 5,`0` = 只在启动时同步)通过 SDK `ServiceAccessList` 拉取,只对新增设备调 `OnDeviceAdd`、对配置变化的设备调 `OnConfigUpdate`(设备配置来自 access list 里的 `voucher/protocol_config`,与原启动同步一致)。`sdk.IsAuthFailure`(无身份/503 身份/403 越权)→ 记一条错误并永久停止,不重试;其他错误按正常间隔继续,启动阶段沿用“最多重试 5 次”。同步状态(次数、设备数、设备号,无凭据)在 `GET :9002/sync-status`(`HA_STATUS_ADDR`,`off` 关闭),因为插件容器日志驱动是 none,看不到日志。 + +## 测试 +- 安装器 Python:`python3 -m unittest tools/test_plugin_install.py` → 18 项 OK(新增 6 项:别名与配置填充、重复安装只有一行、修复旧地址并保留他人键、不碰其他 identifier、模板型不登记、目录校验)。 +- Agent Go:新增 `agent/network_alias_test.go`(别名校验、跨代次别名一致、缺别名的容器不被信任);整个 agent 包 `GOOS=linux` 编译成测试二进制放进容器里跑(包是 linux 构建标签)→ PASS。 +- HA 插件:`go vet ./... && go test ./...` → ok;新增 `startup_sync_test.go`:新增/变更/不变、空列表、三种身份错误只调用 1 次且状态 stopped、瞬时错误后继续拉取、间隔解析。 +- **最小栈回归**(`tools/regress_t7c.py`,栈 `/Volumes/500G/t7c-stack`:develop 563e2497 后端 + timescaledb + redis + 匿名 mosquitto,无 Broker 数据链路,HA 地址/令牌是假的):`regress-3.log` 全 PASS: + 0 安装前无记录 → 1 一条命令安装 → 2 自动出现 1 条记录且 config 含 `sub_topic_prefix`、`http_address=tp-plugin-homeassistant:9001` → 3 平台用登记地址调插件(`voucher/form`)HTTP 200 → 4 同步在跑 → 5 平台新建设备 **41 秒**后插件感知(`/sync-status` devices=1)→ 6 重装(代次升高)→ 7 记录仍 1 条、id 不变 → 8 换代后地址仍可用 → 9 只有 1 个插件容器 → 10 重装后新建设备 **45 秒**内被感知。 + 另手工验证卸载后记录仍在(`row-after-uninstall.log`)。 +- 证据:`/Volumes/500G/archive/evidence/2026-11-04-T7c/`(日志无令牌,grep 为 0)。 + +## 没做 / 注意 +- 回归没走真实 Broker 和真实 HA(上行/下行属 T7b 之后的事);“感知”以插件 `/sync-status` 为准,不是遥测。 +- 同步不处理设备删除(只增、改);平台删除设备后插件仍保留内存记录。 +- 周期同步是整表拉取,设备很多时每分钟一次,量大时再考虑增量。 +- 安装器的 Agent 二进制必须用本分支重新构建(旧二进制会忽略 `network_alias`,别名不生效,回归中踩过一次);Agent 容器名 `tp-agent-` 和插件容器 `tp-agent-prepared-*` 是代码固定的,没有 `t7c-` 前缀,已全部删除。 +- 回归中途有外部进程对 `tp-agent-prepared-*` 容器执行过 `docker restart`(不是本任务,事件里只有 restart),把已停止的旧代次容器拉起过一次;我已清掉。若这是另一会话的批量操作,请留意它会复活被 Agent 停掉的旧代次容器。 +- `plugins/homeassistant.json` 现指向 `thingspanel-homeassistant:t7c-arm64`(`sha256:43984ca4…`,本机用 `Dockerfile.local` 构建,镜像已随栈清理删除,需要时重建;依赖本地 SDK replace,同 T5)。HA token 仍明文进后端 `service_access.voucher`(T7 已记录,未处理)。 +- 平台服务插件列表接口必须带 `page`/`page_size`,否则报 `Field 'Page' is required`;安装器已分页。 +- 并发安装同一插件有极小概率建出两行(先查后建,无唯一约束);单机一条命令的场景不会出现。 diff --git a/docs/thingsvis-database-guard-candidate-20261102.md b/docs/thingsvis-database-guard-candidate-20261102.md new file mode 100644 index 0000000..bcd86c0 --- /dev/null +++ b/docs/thingsvis-database-guard-candidate-20261102.md @@ -0,0 +1,9 @@ +# ThingsVis 数据源检查候选 + +当前正式 Compose 固定 PostgreSQL URL,尚无 MySQL/TDengine profile 选择或四组合支持。`config/native/prepare.py` 对实际 Compose 的 ThingsVis `DATABASE_URL` 做 scheme 检查,仅允许 `postgres` / `postgresql`;不会输出 URL 或凭据。新安装先用不插值的 Compose 结果检查,在生成缺省凭据后再检查插值结果;不连接数据库、不启动服务。测试用 Docker Compose 渲染和临时替身,不使用已有部署。 + +**覆盖边界:**候选安装和升级入口在覆盖已有 Compose 前,尝试读取有效的 ThingsVis URL;不能确认其使用 PostgreSQL 时停止,旧文件不覆盖。Linux/macOS 的两个入口已用命令替身和临时目录测试;Windows PowerShell 入口已加入对应检查,但本机无 PowerShell,尚未执行。既有 Compose 缺 ThingsVis 服务或 URL 时也会停止,不能将其视为 MySQL:这是保护未知旧配置的保守行为,可能阻止旧版或自定义安装升级,仍须核对已支持的历史版本和迁移方案。先读取插值后的 Compose,失败时用不插值结果;无法判断的变量化 scheme 仍拒绝。直接运行 `docker compose` 绕过入口检查。 + +检查只确认 URL scheme,不证明 PostgreSQL 的数据库/schema、迁移、健康、应用功能或任一完整存储组合。Windows、历史版本、实际完整安装/升级和最低支持 Docker Compose 版本均未实测;不能宣称 installer 全面拒绝所有不支持的组合,更不能据此宣称 MySQL 支持。 + +验证命令:`PYTHONDONTWRITEBYTECODE=1 python3 -m unittest -v config/native/test_thingsvis_profile.py`。测试不启动容器,入口测试使用命令替身;真实完整安装、升级、Windows 和真实数据库均未验证。 diff --git a/install.bash b/install.bash index 102e487..dc7e9f6 100755 --- a/install.bash +++ b/install.bash @@ -11,14 +11,13 @@ set -eu # ── 常量 ────────────────────────────────────────────────────────────────────── -REPO="ThingsPanel/thingspanel-installer" RAW_BASE="https://install.thingspanel.io" INSTALL_DIR="${INSTALL_DIR:-/opt/thingspanel}" HTTP_PORT="${HTTP_PORT:-8080}" MQTT_PORT="${MQTT_PORT:-1883}" MIN_DOCKER_VERSION="20.10" -MIN_COMPOSE_VERSION="2.0" SUDO_CMD="" +UPDATE_ENGINE_SHA256="f371cabfab4d2f5fbb37cc892e5b7e0cfbc9436b7a615d91da67ec341b1291aa" # ── 颜色输出 ────────────────────────────────────────────────────────────────── RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m' @@ -33,6 +32,68 @@ step() { echo -e "\n${BOLD}▶ $*${RESET}"; } # ── 工具函数 ────────────────────────────────────────────────────────────────── command_exists() { command -v "$1" >/dev/null 2>&1; } +check_existing_thingsvis_database() { + command_exists python3 || error "检查已有安装的数据源需要 Python 3;旧配置未修改。" + local old_compose_state + old_compose_state=$(python3 - "$INSTALL_DIR" <<'PY' +import os, stat, sys +try: + root = sys.argv[1] + root_info = os.lstat(root) + if not stat.S_ISDIR(root_info.st_mode): raise ValueError('not a directory') + path = os.path.join(root, 'docker-compose.yml') + metadata = os.lstat(path) + if not stat.S_ISREG(metadata.st_mode): raise ValueError('not a regular file') + with open(path, 'rb') as stream: stream.read(1) + print('present') +except FileNotFoundError: + print('missing') +except (OSError, ValueError): + sys.exit(1) +PY + ) || error "无法读取已有 Compose 配置;旧配置未修改。" + [ "$old_compose_state" = present ] || return 0 + if ! (set -o pipefail; cd "$INSTALL_DIR" && { rendered=$(docker compose config --format json 2>/dev/null) || rendered=$(docker compose config --no-interpolate --format json 2>/dev/null); } && printf '%s' "$rendered" | python3 -c ' +import json, sys +from urllib.parse import urlsplit + +def environment(value): + if isinstance(value, dict): return value + if isinstance(value, list): + result = {} + for item in value: + if not isinstance(item, str) or "=" not in item: raise ValueError() + key, val = item.split("=", 1) + if key in result: raise ValueError() + result[key] = val + return result + raise ValueError() + +try: + services = json.load(sys.stdin)["services"] + vis = environment(services["thingsvis-server"]["environment"]) + backend = environment(services["backend"]["environment"]) + url = vis.get("DATABASE_URL") + if not isinstance(url, str): raise ValueError() + parsed_url = urlsplit(url) + if parsed_url.scheme not in ("postgres", "postgresql") or not parsed_url.hostname or "$" in parsed_url.hostname: raise ValueError() + required = ("GOTP_DB_PSQL_HOST", "GOTP_DB_PSQL_PORT", "GOTP_DB_PSQL_USERNAME", "GOTP_DB_PSQL_DBNAME") + if any(not isinstance(backend.get(key), (str, int)) or not str(backend[key]).strip() or "$" in str(backend[key]) for key in required): raise ValueError() + if backend["GOTP_DB_PSQL_HOST"] == "postgres" and not isinstance(services.get("postgres"), dict): raise ValueError() + selectors = ("GOTP_DB_PSQL_DBTYPE", "GOTP_DB_DRIVER", "GOTP_DB_PROVIDER", "GOTP_DB_TYPE", "DB_DRIVER", "DB_PROVIDER", "DB_TYPE", "DATABASE_TYPE", "DATABASE_PROVIDER", "DATABASE_DRIVER") + for key, value in backend.items(): + name = str(key).upper() + if name.startswith(("GOTP_DB_MYSQL_", "GOTP_DB_MARIADB_")) and value not in (None, ""): raise ValueError() + if name in selectors and str(value).lower() not in ("postgres", "postgresql", "pg"): raise ValueError() + if name == "DATABASE_URL" and (not isinstance(value, str) or urlsplit(value).scheme not in ("postgres", "postgresql")): raise ValueError() + sys.exit(0) +except Exception: + sys.exit(1) +'); then + error "无法确认已有平台和 ThingsVis 使用受支持的 PostgreSQL 配置;旧配置未修改。" + fi +} + version_gte() { printf '%s\n%s\n' "$2" "$1" | sort -V -C } @@ -84,25 +145,54 @@ ensure_install_dir_access() { success "已获得安装目录写入权限" } -download_file() { - local url="$1" - local target="$2" - local mode="$3" - local tmp_file - - tmp_file="$(mktemp "${TMPDIR:-/tmp}/thingspanel.XXXXXX")" - - if command_exists curl; then - curl -fsSL "$url" -o "$tmp_file" - elif command_exists wget; then - wget -qO "$tmp_file" "$url" +run_safe_update() { + command_exists python3 || error "安装需要 Python 3;现有配置未修改。" + python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' || error "安装需要 Python 3.8 或更新版本;现有配置未修改。" + local engine="" temporary="" candidate="" directory="" + if [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ]; then + directory="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + candidate="$directory/config/native/update.py" + fi + if [ -n "$candidate" ] && [ -f "$candidate" ] && python3 - "$candidate" "$UPDATE_ENGINE_SHA256" <<'PY' +import hashlib, pathlib, sys +sys.exit(0 if hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest() == sys.argv[2] else 1) +PY + then + engine="$candidate" else - rm -f "$tmp_file" - error "未找到 curl 或 wget,无法下载安装文件" + temporary="$(mktemp -d "${TMPDIR:-/tmp}/thingspanel-updater.XXXXXX")" + engine="$temporary/update.py" + if command_exists curl; then + curl -fsSL --connect-timeout 15 --max-time 180 "$RAW_BASE/config/native/update.py" -o "$engine" || { rm -rf "$temporary"; error "更新器下载失败;现有配置未修改。"; } + elif command_exists wget; then + wget -q --timeout=180 -O "$engine" "$RAW_BASE/config/native/update.py" || { rm -rf "$temporary"; error "更新器下载失败;现有配置未修改。"; } + else + rm -rf "$temporary" + error "需要 curl 或 wget;现有配置未修改。" + fi + if ! python3 - "$engine" "$UPDATE_ENGINE_SHA256" <<'PY' +import hashlib, pathlib, sys +sys.exit(0 if hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest() == sys.argv[2] else 1) +PY + then + rm -rf "$temporary" + error "更新器内容与本入口固定摘要不一致;现有配置未修改。" + fi fi - - run_privileged install -m "$mode" "$tmp_file" "$target" - rm -f "$tmp_file" + local args=(python3 "$engine" --root "$INSTALL_DIR" --base-url "$RAW_BASE") + if [ -n "${TP_VERSION:-}" ]; then args+=(--expected-version "$TP_VERSION"); fi + if [ -n "${TP_PLUGIN_TRUST_ROOT:-}" ]; then args+=(--plugin-trust-root "$TP_PLUGIN_TRUST_ROOT"); fi + # Signed releases: a trust root is supplied out of band (never from the payload). + if [ -n "${TP_RELEASE_TRUST_ROOT:-}" ]; then args+=(--release-trust-root "$TP_RELEASE_TRUST_ROOT"); fi + if [ "${TP_REQUIRE_SIGNED_RELEASE:-}" = "1" ]; then args+=(--require-signed-release); fi + if [ -n "${TP_REVOKED_VERSIONS:-}" ]; then + for revoked in ${TP_REVOKED_VERSIONS//,/ }; do args+=(--revoked-version "$revoked"); done + fi + if ! run_privileged "${args[@]}"; then + [ -z "$temporary" ] || rm -rf "$temporary" + error "安装未完成;请保留 .thingspanel-update 中的恢复记录。" + fi + [ -z "$temporary" ] || rm -rf "$temporary" } # ── Banner ──────────────────────────────────────────────────────────────────── @@ -123,8 +213,7 @@ check_os() { OS="$(uname -s)" ARCH="$(uname -m)" case "$OS" in - Linux) OS_TYPE="linux" ;; - Darwin) OS_TYPE="macos" ;; + Linux|Darwin) ;; *) error "不支持的操作系统: $OS(请在 Linux 或 macOS 上运行)" ;; esac success "操作系统: $OS ($ARCH)" @@ -187,17 +276,6 @@ check_memory() { fi } -# ── 确定版本 ────────────────────────────────────────────────────────────────── -resolve_version() { - step "确定安装版本" - VERSION=$(python3 -c 'import json,subprocess; c=json.loads(subprocess.check_output(["docker","compose","-f",__import__("sys").argv[1],"config","--format","json"])); print(c["services"]["backend"]["image"].rsplit(":",1)[1])' "${INSTALL_DIR}/docker-compose.yml") - if [ -n "${TP_VERSION:-}" ] && [ "$TP_VERSION" != "$VERSION" ]; then - error "指定版本与当前部署配置不一致:$TP_VERSION / $VERSION" - fi - success "将安装版本: $VERSION" - -} - # ── 创建目录结构 ─────────────────────────────────────────────────────────────── setup_directories() { step "创建目录结构" @@ -205,66 +283,6 @@ setup_directories() { success "目录: $INSTALL_DIR" } -# ── 下载 docker-compose.yml ──────────────────────────────────────────────────── -download_docker_compose() { - step "下载 docker-compose.yml" - local compose_url="${RAW_BASE}/docker-compose.yml" - - download_file "$compose_url" "${INSTALL_DIR}/docker-compose.yml" "0644" - mkdir -p "${INSTALL_DIR}/config/native" - download_file "${RAW_BASE}/niginx.conf" "${INSTALL_DIR}/niginx.conf" "0644" - for native_file in prepare.py runtime.encore.json runtime.notification.json tick.sh README.md; do - download_file "${RAW_BASE}/config/native/${native_file}" "${INSTALL_DIR}/config/native/${native_file}" "0644" - done - command_exists python3 || error "v1.3.0 原生配置准备需要 Python 3,请安装后重试" - python3 "${INSTALL_DIR}/config/native/prepare.py" - success "配置文件已下载到 $INSTALL_DIR" -} - -# ── 下载管理脚本 ──────────────────────────────────────────────────────────────── -download_management_scripts() { - step "下载管理脚本" - for script in upgrade.sh uninstall.sh; do - download_file "${RAW_BASE}/${script}" "${INSTALL_DIR}/${script}" "0755" - done - success "管理脚本已就绪" -} - -# ── 启动服务 ────────────────────────────────────────────────────────────────── -start_services() { - step "启动 ThingsPanel 服务" - cd "$INSTALL_DIR" - - if [ -f "$INSTALL_DIR/images.tar" ]; then - info "发现本地离线镜像 images.tar,正在加载(这可能需要几分钟)..." - docker load -i "$INSTALL_DIR/images.tar" || warn "镜像加载失败,将尝试在线拉取" - success "离线镜像已加载" - elif ls "$INSTALL_DIR"/images.tar.part-* >/dev/null 2>&1; then - info "发现本地离线镜像分片 images.tar.part-*,正在加载(这可能需要几分钟)..." - cat "$INSTALL_DIR"/images.tar.part-* | docker load || warn "镜像加载失败,将尝试在线拉取" - success "离线镜像分片已加载" - else - info "拉取镜像(首次可能需要 3-5 分钟,取决于网速)..." - python3 "${INSTALL_DIR}/config/native/prepare.py" --pull - fi - - info "准备数据库和服务配置..." - python3 "${INSTALL_DIR}/config/native/prepare.py" --bootstrap --refresh-devices - - info "启动服务,等待健康检查通过..." - if ! docker compose up -d --wait --wait-timeout 240 2>&1; then - error "启动失败,请运行以下命令查看日志:\n docker compose -f ${INSTALL_DIR}/docker-compose.yml logs" - fi - success "所有服务已启动" -} - -# ── 验证安装 ────────────────────────────────────────────────────────────────── -verify_installation() { - step "验证安装" - python3 "${INSTALL_DIR}/config/native/prepare.py" --verify - -} - # ── 安装完成提示 ─────────────────────────────────────────────────────────────── print_success() { echo "" @@ -290,15 +308,12 @@ main() { print_banner check_os check_docker + check_existing_thingsvis_database check_ports check_memory ensure_install_dir_access setup_directories - download_docker_compose - resolve_version - download_management_scripts - start_services - verify_installation + run_safe_update print_success } diff --git a/install.core.ps1 b/install.core.ps1 index cb09225..ed6b7f1 100644 --- a/install.core.ps1 +++ b/install.core.ps1 @@ -18,6 +18,7 @@ $REPO = "ThingsPanel/thingspanel-installer" $RAW_BASE = "https://install.thingspanel.io" $INSTALL_DIR = "C:\ThingsPanel" $MIN_DOCKER_VER = "20.10" +$UPDATE_ENGINE_SHA256 = "f371cabfab4d2f5fbb37cc892e5b7e0cfbc9436b7a615d91da67ec341b1291aa" function Write-Info ($m) { Write-Host "[INFO] $m" -ForegroundColor Cyan } function Write-Success ($m) { Write-Host "[OK] $m" -ForegroundColor Green } @@ -25,6 +26,90 @@ function Write-Warn ($m) { Write-Host "[WARN] $m" -ForegroundColor Yellow } function Write-Step ($m) { Write-Host "`n[>>] $m" -ForegroundColor White -BackgroundColor DarkBlue } function Write-Err ($m) { Write-Host "[ERROR] $m" -ForegroundColor Red; exit 1 } +function Invoke-SafeUpdate($Directory, $ExpectedVersion) { + $python = Get-Command python3 -ErrorAction SilentlyContinue + $pythonArgs = @() + if (-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue } + if (-not $python) { $python = Get-Command py -ErrorAction SilentlyContinue; $pythonArgs = @('-3') } + if (-not $python) { throw 'Python 3 is required; existing configuration was not changed.' } + & $python.Source @pythonArgs -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' + if ($LASTEXITCODE -ne 0) { throw 'Python 3.8 or newer is required.' } + $engine = Join-Path $Directory 'config/native/update.py' + if ($PSScriptRoot -and (Test-Path (Join-Path $PSScriptRoot 'config/native/update.py'))) { + $engine = Join-Path $PSScriptRoot 'config/native/update.py' + } + $temporary = $null + try { + if (-not (Test-Path -LiteralPath $engine) -or (Get-FileHash -LiteralPath $engine -Algorithm SHA256).Hash.ToLowerInvariant() -ne $UPDATE_ENGINE_SHA256) { + $temporary = Join-Path ([System.IO.Path]::GetTempPath()) ('thingspanel-updater-' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $temporary | Out-Null + $engine = Join-Path $temporary 'update.py' + $client = New-Object System.Net.WebClient + try { $client.DownloadFile("$RAW_BASE/config/native/update.py", $engine) } finally { $client.Dispose() } + if ((Get-FileHash -LiteralPath $engine -Algorithm SHA256).Hash.ToLowerInvariant() -ne $UPDATE_ENGINE_SHA256) { + throw 'Updater digest mismatch; existing configuration was not changed.' + } + } + $arguments = $pythonArgs + @($engine, '--root', $Directory, '--base-url', $RAW_BASE) + if ($ExpectedVersion) { $arguments += @('--expected-version', $ExpectedVersion) } + if ($env:TP_PLUGIN_TRUST_ROOT) { $arguments += @('--plugin-trust-root', $env:TP_PLUGIN_TRUST_ROOT) } + # Signed releases: a trust root is supplied out of band (never from the payload). + if ($env:TP_RELEASE_TRUST_ROOT) { $arguments += @('--release-trust-root', $env:TP_RELEASE_TRUST_ROOT) } + if ($env:TP_REQUIRE_SIGNED_RELEASE -eq '1') { $arguments += @('--require-signed-release') } + if ($env:TP_REVOKED_VERSIONS) { foreach ($revoked in ($env:TP_REVOKED_VERSIONS -split '[,\s]+' | Where-Object { $_ })) { $arguments += @('--revoked-version', $revoked) } } + & $python.Source @arguments + if ($LASTEXITCODE -ne 0) { throw 'Installation did not complete. Preserve .thingspanel-update for recovery.' } + } finally { + if ($temporary) { Remove-Item -LiteralPath $temporary -Recurse -Force } + } +} + +function Test-ExistingThingsVisDatabase($Directory) { + if (-not (Test-Path (Join-Path $Directory 'docker-compose.yml'))) { return $true } + Push-Location $Directory + try { + $rendered = & docker compose config --format json 2>$null + if ($LASTEXITCODE -ne 0) { $rendered = & docker compose config --no-interpolate --format json 2>$null } + if ($LASTEXITCODE -ne 0) { return $false } + $configuration = ($rendered -join "`n") | ConvertFrom-Json + $variables = $configuration.services.'thingsvis-server'.environment + if ($variables -is [array]) { + $values = @($variables | Where-Object { $_ -is [string] -and $_.StartsWith('DATABASE_URL=') } | ForEach-Object { $_.Substring(13) }) + if ($values.Count -ne 1) { return $false } + $value = $values[0] + } else { + $value = $variables.DATABASE_URL + } + if (-not ($value -is [string] -and $value -match '^(?i:postgres(?:ql)?):')) { return $false } + $backendVariables = $configuration.services.backend.environment + $backend = @{} + if ($backendVariables -is [array]) { + foreach ($item in $backendVariables) { + if ($item -isnot [string] -or -not $item.Contains('=')) { return $false } + $separator = $item.IndexOf('=') + $key = $item.Substring(0, $separator) + if ($backend.ContainsKey($key)) { return $false } + $backend[$key] = $item.Substring($separator + 1) + } + } elseif ($null -ne $backendVariables) { + foreach ($property in $backendVariables.PSObject.Properties) { $backend[$property.Name] = $property.Value } + } else { return $false } + foreach ($required in @('GOTP_DB_PSQL_HOST','GOTP_DB_PSQL_PORT','GOTP_DB_PSQL_USERNAME','GOTP_DB_PSQL_DBNAME')) { + if (-not $backend.ContainsKey($required) -or [string]::IsNullOrWhiteSpace([string]$backend[$required])) { return $false } + } + if ($backend['GOTP_DB_PSQL_HOST'] -eq 'postgres' -and $null -eq $configuration.services.postgres) { return $false } + $selectors = @('GOTP_DB_PSQL_DBTYPE','GOTP_DB_DRIVER','GOTP_DB_PROVIDER','GOTP_DB_TYPE','DB_DRIVER','DB_PROVIDER','DB_TYPE','DATABASE_TYPE','DATABASE_PROVIDER','DATABASE_DRIVER') + foreach ($key in $backend.Keys) { + $name = ([string]$key).ToUpperInvariant() + $entry = $backend[$key] + if (($name.StartsWith('GOTP_DB_MYSQL_') -or $name.StartsWith('GOTP_DB_MARIADB_')) -and $null -ne $entry -and [string]$entry -ne '') { return $false } + if ($selectors -contains $name -and @('postgres','postgresql','pg') -notcontains ([string]$entry).ToLowerInvariant()) { return $false } + if ($name -eq 'DATABASE_URL' -and ($entry -isnot [string] -or $entry -notmatch '^(?i:postgres(?:ql)?):')) { return $false } + } + return $true + } catch { return $false } finally { Pop-Location } +} + Write-Host "" Write-Host " ThingsPanel All-in-One Installer (Windows)" -ForegroundColor White Write-Host "" @@ -49,6 +134,9 @@ try { docker compose version 2>$null } catch { Write-Err "docker compose (v2) not found. Please upgrade Docker Desktop." } Write-Success "Docker Compose v2 available" +if (-not (Test-ExistingThingsVisDatabase $INSTALL_DIR)) { + Write-Err "Cannot confirm that the existing backend and ThingsVis use supported PostgreSQL configurations; existing configuration was not changed." +} # ── 端口检查 ────────────────────────────────────────────────────────────────── Write-Step "Checking port availability" @@ -67,68 +155,20 @@ if ($Version -ne "") { $script:TpVersion = $Version Write-Info "Using specified version: $Version" } else { - try { - $rel = Invoke-RestMethod ` - -Uri "https://api.github.com/repos/$REPO/releases/latest" ` - -Headers @{ "User-Agent" = "ThingsPanel-Installer" } ` - -TimeoutSec 10 - $script:TpVersion = $rel.tag_name - } catch { - $script:TpVersion = "v1.2.12.1" - Write-Warn "Cannot fetch latest version, using default: $($script:TpVersion)" - } + # Component images are selected by the published Compose, not by an + # unrelated installer release tag or a hard-coded historical fallback. + $script:TpVersion = "" + Write-Info "Using the component versions in the published Compose configuration" } -Write-Success "Installing version: $($script:TpVersion)" # ── 创建目录 ────────────────────────────────────────────────────────────────── Write-Step "Creating directory structure" New-Item -ItemType Directory -Force -Path $INSTALL_DIR | Out-Null Write-Success "Directory: $INSTALL_DIR" -# ── 下载配置 ────────────────────────────────────────────────────────────────── -Write-Step "Downloading config files" -$client = New-Object System.Net.WebClient -$client.Headers.Add("User-Agent", "ThingsPanel-Installer") -$client.DownloadFile("$RAW_BASE/docker-compose.yml", "$INSTALL_DIR\docker-compose.yml") -$client.DownloadFile("$RAW_BASE/upgrade.ps1", "$INSTALL_DIR\upgrade.ps1") -$client.DownloadFile("$RAW_BASE/uninstall.ps1", "$INSTALL_DIR\uninstall.ps1") -Write-Success "Config files downloaded to $INSTALL_DIR" - -# ── 启动服务 ────────────────────────────────────────────────────────────────── -Write-Step "Starting ThingsPanel services" -Set-Location $INSTALL_DIR - -$imagesTar = Join-Path $INSTALL_DIR "images.tar" - -if (Test-Path $imagesTar) { - Write-Info "Found local images.tar, loading (may take a few minutes)..." - docker load -i $imagesTar *>&1 | Out-Null - if ($LASTEXITCODE -eq 0) { - Write-Success "Local images loaded" - } else { - Write-Warn "Image load failed, will try online pull" - $imagesTar = $null - } -} - -if (-not (Test-Path $imagesTar)) { - Write-Info "Pulling images (first run may take 3-5 minutes)..." - # 用 cmd /c 包裹,彻底绕过 PowerShell 对 native command 的错误处理 - # 进度文字全部走 cmd 的 stdout,不会触发 PowerShell 的 NativeCommandError - cmd /c "docker compose pull >NUL 2>&1" -} - -Write-Info "Cleaning up any existing services..." -cmd /c "docker compose down --remove-orphans >NUL 2>&1" - -Write-Info "Starting services, waiting for health checks..." -cmd /c "docker compose up -d --wait --timeout 180 >NUL 2>&1" -$exitCode = $LASTEXITCODE - -$containers = docker compose ps -q 2>$null -if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrEmpty($containers)) { - Write-Err "Failed to start. View logs: docker compose -f `"$INSTALL_DIR\docker-compose.yml`" logs" -} +# ── 同一配置事务、同一进程锁内调用既有 native 启动流程 ─────────────────────── +Write-Step "Staging and validating the complete installer payload" +Invoke-SafeUpdate $INSTALL_DIR $script:TpVersion Write-Success "All services started" # ── 安装验证 ────────────────────────────────────────────────────────────────── diff --git a/packaging/macos/build.sh b/packaging/macos/build.sh index 7d6b66a..1a1b235 100755 --- a/packaging/macos/build.sh +++ b/packaging/macos/build.sh @@ -13,11 +13,10 @@ FINAL_PKG="$DIST_DIR/ThingsPanel-${VERSION}.pkg" rm -rf "$BUILD_DIR" mkdir -p "$PAYLOAD_DIR/opt/thingspanel" "$DIST_DIR" -cp "$ROOT_DIR/docker-compose.yml" "$PAYLOAD_DIR/opt/thingspanel/" +# Configuration and management scripts are committed by update.py only. +# A pkg payload must not overwrite them before the transaction acquires its lock. cp "$ROOT_DIR/install.sh" "$PAYLOAD_DIR/opt/thingspanel/" cp "$ROOT_DIR/install.bash" "$PAYLOAD_DIR/opt/thingspanel/" -cp "$ROOT_DIR/upgrade.sh" "$PAYLOAD_DIR/opt/thingspanel/" -cp "$ROOT_DIR/uninstall.sh" "$PAYLOAD_DIR/opt/thingspanel/" chmod +x "$PAYLOAD_DIR/opt/thingspanel/"*.sh "$SCRIPT_DIR/scripts/"* pkgbuild \ diff --git a/packaging/macos/scripts/postinstall b/packaging/macos/scripts/postinstall index 18cf9d1..4f200de 100755 --- a/packaging/macos/scripts/postinstall +++ b/packaging/macos/scripts/postinstall @@ -2,7 +2,8 @@ set -e INSTALL_DIR="/opt/thingspanel" -chmod +x "$INSTALL_DIR"/*.sh +# Do not change modes of an existing upgrade/uninstall before staging succeeds. +chmod +x "$INSTALL_DIR/install.sh" "$INSTALL_DIR/install.bash" DOCKER_READY=false for i in $(seq 1 20); do diff --git a/packaging/windows/ThingsPanel-Setup.iss b/packaging/windows/ThingsPanel-Setup.iss index f4e906e..7a83538 100644 --- a/packaging/windows/ThingsPanel-Setup.iss +++ b/packaging/windows/ThingsPanel-Setup.iss @@ -41,11 +41,9 @@ english.InstallingServices=Starting ThingsPanel services. The first start may ta Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked [Files] -Source: "..\..\docker-compose.yml"; DestDir: "{app}"; Flags: ignoreversion +; Configuration and management scripts must go through the locked updater. Source: "..\..\install.ps1"; DestDir: "{app}"; Flags: ignoreversion Source: "..\..\install.core.ps1"; DestDir: "{app}"; Flags: ignoreversion -Source: "..\..\upgrade.ps1"; DestDir: "{app}"; Flags: ignoreversion -Source: "..\..\uninstall.ps1"; DestDir: "{app}"; Flags: ignoreversion Source: "assets\ThingsPanel.bat"; DestDir: "{app}"; Flags: ignoreversion [Icons] diff --git a/plugins/homeassistant.json b/plugins/homeassistant.json new file mode 100644 index 0000000..dc07365 --- /dev/null +++ b/plugins/homeassistant.json @@ -0,0 +1,43 @@ +{ + "id": "homeassistant", + "version": "1.0.0-candidate.20261106-4d8d45b-r2", + "kind": "service", + "description": "Home Assistant device connector: HA state_changed events become ThingsPanel telemetry, platform commands call HA services.", + "image_id": "sha256:0747be19506d38d110a61519964c0f5b6617886d5eb475b303a17ff1c8e6a21c", + "image_platform": "linux/arm64", + "image_archive_sha256": "5421f8ec4d62c5fabe4b5abd26312d5f13e9f4fe041fe0977dd932265e6bf220", + "entrypoint": "/usr/local/bin/homeassistant-service", + "args": [], + "env": [ + "CONNECTOR_SERVICE_IDENTIFIER=homeassistant", + "CONNECTOR_INSTANCE_ID=homeassistant-1", + "THINGSPANEL_BACKEND_URL=http://backend:9999", + "TP_MQTT_BROKER=tcp://mosquitto:1883", + "LOG_LEVEL=info" + ], + "env_from_stack": { + "TP_MQTT_USER": "TP_PROTOCOL_MQTT_USER", + "TP_MQTT_PASS": "TP_PROTOCOL_MQTT_PASSWORD" + }, + "health": { + "port": 9001, + "path": "/health" + }, + "platform": { + "binding": "none", + "service_identifier": "homeassistant", + "http_port": 9001, + "service_plugin": { + "name": "Home Assistant", + "service_type": 2, + "description": "Home Assistant device connector (installed by the plugin installer)", + "config": { + "sub_topic_prefix": "plugin/homeassistant/", + "http_address": "{alias}:{http_port}" + } + } + }, + "identity": { + "token_env": "TP_PLUGIN_RUNTIME_TOKEN" + } +} diff --git a/plugins/http-adapter.json b/plugins/http-adapter.json new file mode 100644 index 0000000..d1c3148 --- /dev/null +++ b/plugins/http-adapter.json @@ -0,0 +1,40 @@ +{ + "id": "http-adapter", + "version": "1.2.0-identity", + "kind": "service", + "description": "HTTP device access: devices POST telemetry to the plugin, it forwards to the platform.", + "image_id": "sha256:c800f14b4bd98eabef6d09bee0c2e69e5f44710330e3aae6cf199859a903d1c7", + "entrypoint": "/app/tp-plugin-http", + "args": [ + "-c", + "/app/config/config.yaml" + ], + "env": [ + "P_LOG_ENABLEFILE=false", + "P_LOG_DEVICE_LOG_ENABLED=false", + "P_SERVER_PORT=19090", + "P_SERVER_HTTP_PORT=19091", + "P_PLATFORM_URL=http://backend:9999", + "P_PLATFORM_MQTT_BROKER=tcp://mosquitto:1883" + ], + "env_from_stack": { + "P_PLATFORM_MQTT_USERNAME": "TP_PROTOCOL_MQTT_USER", + "P_PLATFORM_MQTT_PASSWORD": "TP_PROTOCOL_MQTT_PASSWORD" + }, + "env_generated": { + "P_PLATFORM_TEMPLATE_SECRET": 32, + "P_SERVER_HTTP_API_KEY": 32 + }, + "platform": { + "protocol_type": "HTTP", + "device_type": "1", + "template_name": "HTTP plugin template", + "secret_env": "P_PLATFORM_TEMPLATE_SECRET", + "uplink_port": 19091, + "uplink_path": "/api/v1/uplink", + "api_key_env": "P_SERVER_HTTP_API_KEY" + }, + "identity": { + "token_env": "P_PLATFORM_API_TOKEN" + } +} diff --git a/tests/C01-VALIDATION.md b/tests/C01-VALIDATION.md new file mode 100644 index 0000000..e1b0ba0 --- /dev/null +++ b/tests/C01-VALIDATION.md @@ -0,0 +1,37 @@ +# C01 配置安全更新:本轮实施与验证记录 + +基线是远端 installer worktree `05470e09616feaee8979a5b0ad6206028986da2a` 的完整文件镜像。仅在本地镜像修改;未部署、未启动真实栈、未连接数据库、未提交或推送。本文属于 2026-11-02 收尾批次。 + +## 已实施 + +- 四个 Bash/PowerShell 正式入口使用同一固定摘要 Python updater。完整暂存 9 个下载文件,校验后连同受信任 updater 提交;下载失败不改变原配置内容/模式。 +- 同一内核锁覆盖恢复、暂存、替换、native 激活;journal、备份和替换使用刷新/原子写入。替换中断、原文件缺失、恢复再次中断均有对应行为。 +- 原 `.env`/token 与原文件快照在每个替换前复核;第三方修改、损坏 journal/备份、symlink、不明来源目录失败关闭。恢复只恢复本事务的已知旧/新内容,不覆盖人工改动。 +- PG/unknown 守卫保留。暂存 Compose 锚定原 project directory 和 `.env`,native 子进程也不继承外部 `COMPOSE_FILE`。不会执行新下载的 prepare 来证明自身安全。 +- `activation_started` 之后失败保留现场并要求协调外部效果;不会把配置恢复叫作数据库回滚。Windows 原 `compose down --remove-orphans` 已删除。 +- pkg/Inno 不再直接覆盖 Compose 和 upgrade/uninstall;macOS postinstall 不再 chmod 既有管理脚本。PR 和 release 共用三平台事务测试,发布构建依赖通过结果。 +- 修复一处旧 fixture:用于证明 PG 可通过的样本补齐已有 backend 守卫要求的 PG 字段,没有放宽生产守卫。 + +## 实际执行结果 + +本地平台为 Linux,Python 3.12;没有 Docker CLI、PowerShell、Windows/macOS 原生打包器。 + +| 检查 | 结果 | 证据范围 | +| --- | --- | --- | +| `PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v` | exit 0,28 tests | 包含原 14 个下载失败子边界,4 个 bootstrap 子边界,20 个替换前后异常子边界,6 个跨进程 SIGKILL 阶段及恢复再中断;各子边界不重复计入 28 方法数 | +| 旧 prepare 日志脱敏与 ThingsVis PG/unknown 的无 Docker 子集 | exit 0,6 tests | 原 guard、拒绝 MySQL/不明配置、入口在下载前拒绝不支持配置;不含真实 Compose 解析 | +| Bash 语法:install.sh/install.bash/upgrade.sh/macOS build.sh/postinstall | exit 0 | 仅语法,不执行打包/安装 | +| `git diff --check` | exit 0 | 无空白格式错误 | +| updater 与 3 个 Python 测试文件按 Python 3.8 grammar 解析 | exit 0 | 证明语法最低版本;本轮实际解释器为 3.12 | + +日志在收尾工作区:`implementation/installer-transaction-tests.log`、`implementation/installer-guard-subset-tests.log`。初次尝试整个旧 `config/native` 测试目录的日志 `implementation/installer-existing-guards.log` 保留失败事实:真实配置解析缺少 Docker CLI,旧 PG fixture 不完整;fixture 修正后重跑上述 6 项成功。本轮没有把真实解析改为模拟来声称其通过。 + +## 仍须在对应平台验证 + +- 三平台 CI 尚未运行;Windows 的实际文件锁/写穿替换、PowerShell AST,macOS 文件系统行为与 Bash 入口等待 CI 证据。Linux 上的 Windows artifact 选择用例只能证明负载选择,不能充当 Windows 系统验收。 +- 本轮没有编译或执行 pkg/Inno。新增包装测试验证其清单不直接携带配置覆盖负载;实际包安装仍需隔离平台环境。 +- 未执行真实 Docker Compose、native migration 或服务启动;这些属于下一阶段集成门禁。未解除 PG/unknown 守卫,也未承诺多 DB 安装已通过。 +- 操作进入 activation 后的服务/DB 协调恢复、网络共享文件系统、断电耐久性及 Windows ACL 的最终行为不能由 Linux 进程故障注入证明。遇到未知 activation 必须保留现场,不能删除 journal 自动重试。 +- updater 固定摘要与负载 HTTPS 来源并不等同于完整发布包签名。现有一行 bootstrap 的分发信任继续沿用原机制。 + +恢复协议与命令见 `config/native/UPDATE-SAFETY.md`;测试运行方式见 `tests/README.md`。 diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..93e88ba --- /dev/null +++ b/tests/README.md @@ -0,0 +1,20 @@ +# 安装器配置更新的隔离回归 + +本目录直接测试正式入口和 `config/native/update.py`。所有目标目录均为临时目录,下载和 Compose 输出采用明确的替身;测试不访问网络,不连接 Docker daemon,不启动服务,不操作数据库。 + +```sh +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v +bash -n install.sh install.bash upgrade.sh +``` + +`test_download_failure.py` 保留原 14 个下载失败边界:`install.bash`、`upgrade.sh` 各 7 次失败,逐个检查原配置内容、文件模式、`.env` 和 token,确认未启动服务。另加两入口的 updater 下载失败及固定摘要不符,共 4 个 bootstrap 边界。`test_update_transaction.py` 补充后两个管理脚本下载失败、完整暂存、校验失败、版本不符、摘要混发、20 个替换前后异常点、缺失原文件恢复、人工修改冲突、损坏 journal/备份、同进程与跨进程锁、activation 失败封禁,以及原项目目录/`.env` 和日志脱敏。 + +POSIX 子进程测试在 6 个实际阶段发送 `SIGKILL`,由第二进程读取磁盘 journal 恢复;另一次在恢复途中发送 `SIGKILL` 后重试。故障钩子只通过测试构造函数注入,正式 CLI 没有注入参数。测试并未把模拟的 Compose 输出当成实际容器验收。 + +GitHub `update-transaction` job 在 Linux、macOS、Windows 执行此目录。Windows 跳过 Bash 入口、POSIX `SIGKILL` 和需要特殊权限的 symlink 用例,运行真实 Windows 文件替换/锁路径和其余事务测试,并解析 PowerShell 入口。首次 CI 成功前,不能将这些平台列为已实测通过。 + +接管复验加强了每个下载边界的 HTTPS 主机和 URL 顺序断言,防止 bootstrap 拒绝被误记为第 2~7 个 payload 故障已执行。新增 3 个 SIGTERM 阶段、缺文件状态的 SIGKILL 恢复、完成/已恢复记录的重启幂等、配置替换期间真实双进程互斥。activation 的 `.env` 在意图落盘和目标替换后各发送一次 SIGKILL,两个未决状态均必须保留现场,不能自动宣称外部回滚。 + +`test_prepare_auth_secret.py` 检查真实临时目录中的凭据持久化、重复 prepare、显式安全镜像选择、SSO 一次性策略轮换与冲突拒绝。测试只用临时证书占位符避免调用 OpenSSL,并选择非 root 所有权处理分支;不启动 ThingsVis 或证明 JWT/SSO 的服务器行为。真实 Windows 对只读文件替换和 PowerShell/NTFS 的行为仍须在原生环境单列验收。 + +旧 `config/native/test_*.py` 中还有需要真实 Docker Compose **CLI 配置解析**和历史 Git tags 的用例。云端缺少 CLI、镜像 checkout 缺少 tags 时,应如实记录未执行/失败原因,不替换其真实解析为 fixture 后宣称通过。 diff --git a/tests/test_agent_host.py b/tests/test_agent_host.py new file mode 100644 index 0000000..49537ed --- /dev/null +++ b/tests/test_agent_host.py @@ -0,0 +1,22 @@ +import importlib.util +from pathlib import Path +import sys +import unittest +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / 'tools')) +import agent_host # noqa: E402 + + +class AgentHost(unittest.TestCase): + def test_installer_defers_scope_watcher_without_waiting_or_lock_attempts(self): + with mock.patch.object(agent_host.scope_sync, 'ensure') as ensure, \ + mock.patch.object(agent_host.time, 'sleep', side_effect=AssertionError('must not sleep')): + status = agent_host.ensure_scope_watcher('/stack', '/agent', deferred=True) + self.assertEqual(status, 'deferred') + ensure.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_download_failure.py b/tests/test_download_failure.py new file mode 100644 index 0000000..58a0cfb --- /dev/null +++ b/tests/test_download_failure.py @@ -0,0 +1,126 @@ +"""Synthetic entry-point checks. No database, daemon, network or real installation. + +Point TP_STAGE_INSTALLER_SOURCE at a reviewed candidate checkout. Fake curl and +Docker are confined to a private TemporaryDirectory. This test documents only +pre-replacement download failures; crash recovery requires the extension cases +listed in README.md and must use the candidate's actual transaction hook. +""" +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +SOURCE = Path(os.environ.get('TP_STAGE_INSTALLER_SOURCE', Path(__file__).resolve().parents[1])) +FILES = ('docker-compose.yml', 'niginx.conf', 'config/native/prepare.py', + 'config/native/runtime.encore.json', 'config/native/runtime.notification.json', + 'config/native/tick.sh', 'config/native/README.md') +OLD = {name: ('old fixture: ' + name + '\n').encode() for name in FILES} +OLD['.env'] = b'TP_DATABASE_PASSWORD=fixture-only\n' +OLD['config/native/plugin-token'] = b'fixture-token\n' +CONFIG = {'services': {'backend': {'environment': { + 'GOTP_DB_PSQL_HOST': 'postgres', 'GOTP_DB_PSQL_PORT': '5432', + 'GOTP_DB_PSQL_USERNAME': 'postgres', 'GOTP_DB_PSQL_DBNAME': 'ThingsPanel'}}, + 'postgres': {}, 'thingsvis-server': {'environment': { + 'DATABASE_URL': 'postgresql://fixture:fixture@postgres/ThingsPanel'}}}} + +DOCKER = r'''#!/usr/bin/env python3 +import os, sys +from pathlib import Path +args = sys.argv[1:] +with open(os.environ['TP_FAKE_DOCKER_LOG'], 'a') as f: f.write(' '.join(args) + '\n') +if args and args[0] == 'version': print('25.0.0'); sys.exit(0) +if len(args) >= 2 and args[:2] == ['compose','version']: print('2.20.0'); sys.exit(0) +if args and args[0] == 'compose' and 'config' in args: + print(Path(os.environ['TP_FAKE_CONFIG']).read_text()); sys.exit(0) +sys.exit(93) +''' +CURL = r'''#!/usr/bin/env python3 +import json, os, pathlib, sys +from urllib.parse import urlsplit +root = pathlib.Path(os.environ['TP_FIXTURE_ROOT']).resolve() +count_file = root / 'curl-count' +count = int(count_file.read_text()) + 1 if count_file.exists() else 1 +count_file.write_text(str(count)) +args = sys.argv[1:] +urls = [arg for arg in args if arg.startswith('https://')] +if len(urls) != 1: sys.exit(96) +url = urlsplit(urls[0]) +if url.scheme != 'https' or url.netloc != 'install.thingspanel.io': sys.exit(97) +with (root / 'curl-events.jsonl').open('a') as stream: + stream.write(json.dumps({'call': count, 'path': url.path.lstrip('/')}) + '\n') +try: dest = pathlib.Path(args[args.index('-o') + 1]).resolve() +except (ValueError, IndexError): sys.exit(94) +try: dest.relative_to(root) +except ValueError: sys.exit(95) +if count == int(os.environ['TP_FAIL_DOWNLOAD']): + dest.write_bytes(b'partial download') + sys.exit(42) +name = dest.name +content = b'fixture\n' +if name.endswith('.json'): content = b'{}\n' +if name == 'prepare.py': content = b'raise SystemExit("fixture prepare must not run")\n' +dest.write_bytes(content) +''' + +@unittest.skipIf(os.name == 'nt', 'Bash entrypoint tests run on Linux and macOS') +class DownloadFailurePreservation(unittest.TestCase): + def case(self, entry, failed_call, bootstrap=None): + with tempfile.TemporaryDirectory(prefix='tp-stage-synthetic-') as name: + root = Path(name) + target = root / 'install' + bindir = root / 'bin' + target.mkdir(); bindir.mkdir() + for filename, content in OLD.items(): + path = target / filename + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content); path.chmod(0o640) + script = target / entry + shutil.copyfile(SOURCE / entry, script) + # The reviewed, digest-pinned engine is present in this fixture. + # Bootstrap download/digest rejection has its own test. These + # fourteen cases retain the original payload-download boundaries. + shutil.copyfile(SOURCE / 'config/native/update.py', target / 'config/native/update.py') + if bootstrap is not None: + (target / 'config/native/update.py').unlink() + for program, source in [('docker', DOCKER), ('curl', CURL), ('wget', '#!/bin/sh\nexit 92\n')]: + path = bindir / program; path.write_text(source); path.chmod(0o755) + config = root / 'config.json'; config.write_text(json.dumps(CONFIG)) + env = os.environ.copy() + env.update(PATH=str(bindir) + os.pathsep + env['PATH'], INSTALL_DIR=str(target), + TMPDIR=str(root), TP_FIXTURE_ROOT=str(root), TP_FAIL_DOWNLOAD=str(999 if bootstrap == 'digest' else failed_call), + TP_FAKE_CONFIG=str(config), TP_FAKE_DOCKER_LOG=str(root / 'docker.log')) + argv = ['bash', str(script)] + (['v-fixture'] if entry == 'upgrade.sh' else []) + result = subprocess.run(argv, cwd=target, env=env, capture_output=True, text=True, timeout=20) + self.assertNotEqual(result.returncode, 0, 'injected download failure unexpectedly succeeded') + self.assertTrue((root / 'curl-count').exists(), 'entry did not reach the injected download boundary') + self.assertEqual(int((root / 'curl-count').read_text()), failed_call, 'wrong boundary reached') + events = [json.loads(line) for line in (root / 'curl-events.jsonl').read_text().splitlines()] + expected = ['config/native/update.py'] if bootstrap is not None else list(FILES[:failed_call]) + self.assertEqual(events, [{'call': index + 1, 'path': path} for index, path in enumerate(expected)], + 'failure did not reach the intended payload URL sequence') + for filename, original in OLD.items(): + path = target / filename + self.assertTrue(path.is_file(), f'{filename} disappeared') + self.assertEqual(path.read_bytes(), original, f'{entry}: {filename} changed on download failure {failed_call}') + self.assertEqual(path.stat().st_mode & 0o777, 0o640, f'{filename} mode changed') + log = (root / 'docker.log').read_text() if (root / 'docker.log').exists() else '' + self.assertNotIn('compose up', log) + + def test_upgrade_each_download_failure_preserves_old_files(self): + for nth in range(1, 8): + with self.subTest(download=nth): self.case('upgrade.sh', nth) + + def test_install_each_download_failure_preserves_old_files(self): + for nth in range(1, 8): + with self.subTest(download=nth): self.case('install.bash', nth) + + def test_bootstrap_download_failure_and_digest_mismatch_stop_before_payload(self): + for entry in ('install.bash', 'upgrade.sh'): + for boundary in ('download', 'digest'): + with self.subTest(entry=entry, boundary=boundary): + self.case(entry, 1, bootstrap=boundary) + +if __name__ == '__main__': unittest.main() diff --git a/tests/test_migration_guard.py b/tests/test_migration_guard.py new file mode 100644 index 0000000..ff4096a --- /dev/null +++ b/tests/test_migration_guard.py @@ -0,0 +1,91 @@ +"""PH1-S2: bootstrap tells an old image (no 33.sql expected) from a new image that forgot to ship it. No Docker.""" +import importlib.util +import io +import subprocess +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('tp_prepare_guard', REPO / 'config/native/prepare.py') +prepare = importlib.util.module_from_spec(spec) +spec.loader.exec_module(prepare) +IMAGE = 'registry.example/thingspanel-go:test' + + +ID, INSTALL = 'internal/pluginidentity', 'internal/plugininstall' + + +class RequiredExtraSqlTests(unittest.TestCase): + def community(self, *files): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + for name in files: (root / name).write_text('SELECT 1;') + return root + + def names(self, paths): + return [p.name for p in paths] + + def test_identity_only_image_requires_and_applies_only_33(self): + # Regression: an image with plugin identity but no plugin-install feature must not be rejected for 34/35. + root = self.community('33.sql') + out = io.StringIO() + with redirect_stdout(out): + self.assertEqual(self.names(prepare.required_extra_sql(root, {ID}, IMAGE)), ['33.sql']) + self.assertIn('predates internal/plugininstall; skipping sql/34.sql', out.getvalue()) + + def test_image_with_both_markers_requires_and_applies_33_to_35(self): + root = self.community('33.sql', '34.sql', '35.sql') + self.assertEqual(self.names(prepare.required_extra_sql(root, {ID, INSTALL}, IMAGE)), ['33.sql', '34.sql', '35.sql']) + + def test_install_marker_with_missing_34_fails_naming_file_and_image(self): + root = self.community('33.sql', '35.sql') + with self.assertRaises(RuntimeError) as ctx: + prepare.required_extra_sql(root, {ID, INSTALL}, IMAGE) + self.assertIn('sql/34.sql', str(ctx.exception)) + self.assertNotIn('sql/35.sql', str(ctx.exception)) + self.assertIn(IMAGE, str(ctx.exception)) + + def test_identity_marker_with_missing_33_fails(self): + with self.assertRaises(RuntimeError) as ctx: + prepare.required_extra_sql(self.community(), {ID}, IMAGE) + self.assertIn('sql/33.sql', str(ctx.exception)) + + def test_old_image_without_files_is_skipped_with_log(self): + out = io.StringIO() + with redirect_stdout(out): + self.assertEqual(prepare.required_extra_sql(self.community(), set(), IMAGE), []) + self.assertIn('skipping sql/33.sql', out.getvalue()) + self.assertIn('skipping sql/35.sql', out.getvalue()) + + def test_image_with_files_but_without_markers_still_applies_them(self): + root = self.community('33.sql') + self.assertEqual(self.names(prepare.required_extra_sql(root, set(), IMAGE)), ['33.sql']) + + def test_every_extra_file_belongs_to_exactly_one_marker(self): + self.assertEqual(sorted(prepare.EXTRA_COMMUNITY_SQL), ['33.sql', '34.sql', '35.sql']) + + +class MarkerProbeTests(unittest.TestCase): + def probe(self, code, err=b''): + result = subprocess.CompletedProcess([], code, b'', err) + with mock.patch.object(prepare.subprocess, 'run', return_value=result): + return prepare.image_has_marker('c1', ID) + + def test_marker_present(self): + self.assertTrue(self.probe(0)) + + def test_marker_cleanly_absent_means_old_image(self): + self.assertFalse(self.probe(1, b'Error: Could not find the file /go/src/app/x in container c1')) + + def test_undeterminable_fails_closed(self): + # Safe default: an unexpected docker error stops the install instead of silently skipping the migration. + with self.assertRaises(RuntimeError): + self.probe(1, b'Cannot connect to the Docker daemon') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_p1_auto_steps.py b/tests/test_p1_auto_steps.py new file mode 100644 index 0000000..340f8f1 --- /dev/null +++ b/tests/test_p1_auto_steps.py @@ -0,0 +1,376 @@ +"""P1: migrations (33.sql) and Broker device scope run without manual commands. No Docker, no database.""" +import hashlib +import importlib.util +import concurrent.futures +import subprocess +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, REPO / path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +prepare = load('tp_prepare_p1', 'config/native/prepare.py') +scope_sync = load('tp_scope_sync_p1', 'tools/scope_sync.py') + +ENV = {'TP_MQTT_USER': 'tp-community-platform', 'TP_MQTT_PASSWORD': 'p' * 32, 'TP_PROTOCOL_MQTT_USER': 'tp-community-protocols', + 'TP_PROTOCOL_MQTT_PASSWORD': 'q' * 32, 'TP_BROKER_CELL': 'community', 'TP_BROKER_INSTANCE': 'community-mosquitto', + 'TP_MQTT_CLIENT_ID': 'tp-community-backend'} +MQTT = [{'id': 'mqtt-1', 'tenant_id': 't1'}] +PLUGIN = [{'id': 'ha-1', 'tenant_id': 't1'}, {'id': 'ha-2', 'tenant_id': 't2'}] + + +class ScopeServicesTests(unittest.TestCase): + def test_platform_account_covers_plugin_devices_as_well_as_mqtt_devices(self): + platform, protocols = prepare.scope_services(ENV, MQTT, PLUGIN) + self.assertEqual(platform['username'], 'tp-community-platform') + self.assertEqual(platform['allowed_device_ids'], ['mqtt-1', 'ha-1', 'ha-2']) + self.assertEqual(platform['allowed_tenant_ids'], ['t1', 't2']) + self.assertIn('devices/command/+/+', platform['policy']['publish']) + self.assertEqual(protocols['allowed_device_ids'], ['ha-1', 'ha-2']) + self.assertTrue(protocols['plugin_socket'] and protocols['allow_any_client_id']) + + def test_only_plugin_devices_still_gives_the_platform_account_publish_rights(self): + # T7b finding 3: with no plain MQTT device the publish list was empty and commands were dropped silently. + platform, _ = prepare.scope_services(ENV, [], PLUGIN) + self.assertTrue(platform['policy']['publish']) + self.assertEqual(platform['allowed_device_ids'], ['ha-1', 'ha-2']) + + def test_no_devices_at_all_is_an_empty_scope_without_publish_rights(self): + platform, protocols = prepare.scope_services(ENV, [], []) + self.assertEqual((platform['allowed_device_ids'], platform['policy']['publish']), ([], [])) + self.assertEqual(protocols['allowed_device_ids'], []) + + def test_a_device_in_both_lists_is_listed_once(self): + platform, _ = prepare.scope_services(ENV, MQTT + PLUGIN[:1], PLUGIN) + self.assertEqual(platform['allowed_device_ids'], ['mqtt-1', 'ha-1', 'ha-2']) + + def test_plugin_scope_does_not_leak_mqtt_devices(self): + _, protocols = prepare.scope_services(ENV, MQTT, PLUGIN) + self.assertNotIn('mqtt-1', protocols['allowed_device_ids']) + + +class SyncScopeTests(unittest.TestCase): + def run_sync(self, current, targets, plugins): + calls = [] + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + root = Path(temporary.name) + config = root / 'config/native' + (config / 'broker').mkdir(parents=True) + patches = [mock.patch.object(prepare, 'query_scopes', return_value=(targets, plugins)), + mock.patch.object(prepare, 'current_services', return_value=current), + mock.patch.object(prepare, 'save', side_effect=lambda *a, **k: calls.append(('save', a[0]))), + mock.patch.object(prepare, 'ROOT', root), + mock.patch.object(prepare, 'CONFIG', config)] + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + changed = prepare.sync_scope(ENV, restart=lambda name: calls.append(('restart', name))) + return changed, calls + + def test_unchanged_scope_neither_writes_nor_restarts(self): + same = prepare.scope_services(ENV, MQTT, PLUGIN) + changed, calls = self.run_sync(same, MQTT, PLUGIN) + self.assertFalse(changed) + self.assertEqual(calls, []) + + def test_new_plugin_device_writes_then_restarts_owner_before_mosquitto(self): + old = prepare.scope_services(ENV, MQTT, PLUGIN[:1]) + changed, calls = self.run_sync(old, MQTT, PLUGIN) + self.assertTrue(changed) + self.assertEqual(calls, [('save', 'services.json'), ('restart', 'broker-owner'), ('restart', 'mosquitto')]) + + def test_deleted_plugin_device_also_triggers_a_refresh(self): + old = prepare.scope_services(ENV, MQTT, PLUGIN) + changed, calls = self.run_sync(old, MQTT, PLUGIN[:1]) + self.assertTrue(changed) + self.assertEqual([c for c in calls if c[0] == 'restart'], [('restart', 'broker-owner'), ('restart', 'mosquitto')]) + + def test_first_run_without_a_services_file_writes_it(self): + changed, calls = self.run_sync(None, [], PLUGIN) + self.assertTrue(changed) + self.assertEqual(calls[0], ('save', 'services.json')) + + def test_a_failed_save_restarts_nothing(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config = root / 'config/native' + (config / 'broker').mkdir(parents=True) + patches = [mock.patch.object(prepare, 'ROOT', root), + mock.patch.object(prepare, 'CONFIG', config), + mock.patch.object(prepare, 'query_scopes', return_value=([], PLUGIN)), + mock.patch.object(prepare, 'current_services', return_value=None), \ + mock.patch.object(prepare, 'save', side_effect=RuntimeError('locked'))] + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + restarted = [] + with self.assertRaises(RuntimeError): + prepare.sync_scope(ENV, restart=restarted.append) + self.assertEqual(restarted, []) + self.assertTrue((config / 'broker/.scope-sync-restart.json').is_file()) + + def test_failed_restart_is_retried_even_when_scope_file_is_already_current(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config = root / 'config/native' + (config / 'broker').mkdir(parents=True) + current = {'value': prepare.scope_services(ENV, MQTT, PLUGIN[:1])} + calls = [] + patches = [ + mock.patch.object(prepare, 'ROOT', root), + mock.patch.object(prepare, 'CONFIG', config), + mock.patch.object(prepare, 'query_scopes', return_value=(MQTT, PLUGIN)), + mock.patch.object(prepare, 'current_services', side_effect=lambda: current['value']), + mock.patch.object(prepare, 'save', side_effect=lambda _name, value, _broker, **_kw: current.update(value=value)), + ] + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + + def fail_mosquitto_once(name): + calls.append(name) + if calls == ['broker-owner', 'mosquitto']: + raise RuntimeError('simulated mosquitto restart failure') + + with self.assertRaisesRegex(RuntimeError, 'simulated'): + prepare.sync_scope(ENV, restart=fail_mosquitto_once) + self.assertEqual(current['value'], prepare.scope_services(ENV, MQTT, PLUGIN)) + self.assertTrue((config / 'broker/.scope-sync-restart.json').is_file()) + + calls.clear() + self.assertFalse(prepare.sync_scope(ENV, restart=calls.append)) + self.assertEqual(calls, ['broker-owner', 'mosquitto']) + self.assertFalse((config / 'broker/.scope-sync-restart.json').exists()) + + def test_concurrent_scope_pass_cannot_overlap_restart_sequence(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config = root / 'config/native' + (config / 'broker').mkdir(parents=True) + current = {'value': prepare.scope_services(ENV, MQTT, PLUGIN[:1])} + patches = [ + mock.patch.object(prepare, 'ROOT', root), + mock.patch.object(prepare, 'CONFIG', config), + mock.patch.object(prepare, 'query_scopes', return_value=(MQTT, PLUGIN)), + mock.patch.object(prepare, 'current_services', side_effect=lambda: current['value']), + mock.patch.object(prepare, 'save', side_effect=lambda _name, value, _broker, **_kw: current.update(value=value)), + ] + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + entered, release = threading.Event(), threading.Event() + + def blocked_restart(name): + entered.set() + self.assertTrue(release.wait(2)) + + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(prepare.sync_scope, ENV, blocked_restart) + self.assertTrue(entered.wait(2)) + second = pool.submit(prepare.sync_scope, ENV, lambda _name: self.fail('overlapping restart')) + with self.assertRaises(Exception) as raised: + second.result(timeout=2) + self.assertEqual(type(raised.exception).__name__, 'UpdateError') + release.set() + self.assertTrue(first.result(timeout=2)) + + def test_refresh_devices_uses_the_same_scope_with_plugins(self): + saved = {} + with mock.patch.object(prepare, 'query_scopes', return_value=([], PLUGIN)), \ + mock.patch.object(prepare, 'save', side_effect=lambda name, value, broker=False: saved.update({name: value})): + prepare.refresh(ENV) + self.assertEqual(saved['services.json'][0]['allowed_device_ids'], ['ha-1', 'ha-2']) + + +class FakeLedgerDatabase: + """Just enough of psql for apply_migrations: records installer_migrations rows, counts executed migrations.""" + def __init__(self): + self.rows, self.executed = {}, [] + + def sql(self, database, statement): + if statement.startswith('CREATE TABLE IF NOT EXISTS installer_migrations'): + return '' + if statement.startswith('SELECT checksum'): + key = tuple(statement.split("component='")[1].split("' AND version=")[i] for i in (0, 1)) + return self.rows.get((key[0], int(key[1])), '') + if statement.startswith('BEGIN'): + component = statement.split("INSERT INTO installer_migrations VALUES('")[1].split("'")[0] + number = int(statement.split("',")[1].split(",")[0]) + checksum = statement.split("'")[-2] + self.rows[(component, number)] = checksum + self.executed.append(number) + return '' + raise AssertionError('unexpected statement: ' + statement[:60]) + + +class ExtraMigrationTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.file = Path(self.directory.name) / '33.sql' + self.file.write_text('CREATE TABLE IF NOT EXISTS plugin_runtime_identities (instance_id varchar(64) PRIMARY KEY);\n') + self.db = FakeLedgerDatabase() + patch = mock.patch.object(prepare, 'sql', side_effect=self.db.sql) + patch.start() + self.addCleanup(patch.stop) + + def test_33_sql_is_applied_once_and_recorded_with_its_checksum(self): + prepare.apply_migrations('ThingsPanel', prepare.EXTRA_COMMUNITY_COMPONENT, [self.file]) + self.assertEqual(self.db.executed, [33]) + expected = hashlib.sha256(self.file.read_text().encode()).hexdigest() + self.assertEqual(self.db.rows[(prepare.EXTRA_COMMUNITY_COMPONENT, 33)], expected) + + def test_repeating_install_or_upgrade_does_not_run_it_again(self): + for _ in range(3): + prepare.apply_migrations('ThingsPanel', prepare.EXTRA_COMMUNITY_COMPONENT, [self.file]) + self.assertEqual(self.db.executed, [33]) + + def test_an_edited_file_is_refused_instead_of_silently_skipped(self): + prepare.apply_migrations('ThingsPanel', prepare.EXTRA_COMMUNITY_COMPONENT, [self.file]) + self.file.write_text('DROP TABLE plugin_runtime_identities;') + with self.assertRaises(RuntimeError): + prepare.apply_migrations('ThingsPanel', prepare.EXTRA_COMMUNITY_COMPONENT, [self.file]) + + def test_the_extra_list_names_the_plugin_identity_schema_only(self): + self.assertEqual(prepare.EXTRA_COMMUNITY_SQL, ('33.sql', '34.sql', '35.sql')) + + +class BootstrapAppliesExtraSqlTests(unittest.TestCase): + """bootstrap() end to end with Docker and psql faked: 33.sql comes out of the backend image's sql directory.""" + def test_bootstrap_runs_33_sql_and_the_broker_files_and_skips_it_for_an_older_image(self): + for with_33 in (True, False): + applied = [] + real_copy = {} + + def command(*args, data=None): + if args[:3] == ('docker', 'compose', 'config'): + return '{"services": {"backend": {"image": "backend:test"}}}' + if args[:2] == ('docker', 'create'): + return 'cid' + if args[:2] == ('docker', 'cp'): + source, target = args[2].split(':', 1)[1], Path(args[3]) + real_copy[source] = target + if source.endswith('/sql'): + (target / 'broker').mkdir(parents=True) + (target / 'broker' / '001_x.sql').write_text('select 1;') + if with_33: + (target / '33.sql').write_text('select 33;') + (target / '34.sql').write_text('select 34;') + (target / '35.sql').write_text('select 35;') + elif source.endswith('global.go'): + target.write_text('VERSION_NUMBER = 0\n') + else: + target.mkdir(parents=True) + (target / '001_x.up.sql').write_text('select 1;') + return '' + + def apply(database, component, paths): + applied.append((component, [p.name for p in paths])) + + with mock.patch.object(prepare, 'command', side_effect=command), \ + mock.patch.object(prepare, 'sql', return_value='0'), \ + mock.patch.object(prepare, 'image_has_marker', return_value=with_33), \ + mock.patch.object(prepare, 'apply_migrations', side_effect=apply): + prepare.bootstrap() + self.assertEqual(applied[0], (prepare.EXTRA_COMMUNITY_COMPONENT, ['33.sql', '34.sql', '35.sql'] if with_33 else []), with_33) + self.assertEqual(applied[1], ('broker', ['001_x.sql'])) + + +class ScopeSyncToolTests(unittest.TestCase): + def result(self, code=0, out=b''): + return subprocess.CompletedProcess([], code, stdout=out, stderr=b'') + + def test_run_once_reports_success_and_failure_and_never_raises(self): + self.assertEqual(scope_sync.run_once('/s', runner=lambda *a, **k: self.result(0, b'ok\n')), (True, 'ok')) + self.assertFalse(scope_sync.run_once('/s', runner=lambda *a, **k: self.result(1, b'locked'))[0]) + + def boom(*a, **k): + raise subprocess.TimeoutExpired('x', 1) + ok, text = scope_sync.run_once('/s', runner=boom) + self.assertFalse(ok) + self.assertNotIn('/s', text) + + def test_run_once_calls_the_same_entrypoint_as_the_installer(self): + seen = {} + scope_sync.run_once('/stack', runner=lambda cmd, **k: seen.update(cmd=cmd, cwd=k['cwd']) or self.result()) + self.assertEqual(seen['cmd'][1:], ['config/native/prepare.py', '--sync-scope']) + self.assertEqual(seen['cwd'], '/stack') + + def test_watch_keeps_going_after_a_failed_pass_and_logs_only_changes(self): + outputs = iter([self.result(0, b'unchanged'), self.result(0, b'unchanged'), self.result(1, b'locked'), self.result(0, b'changed; restarting')]) + lines, sleeps = [], [] + scope_sync.watch('/s', 7, runner=lambda *a, **k: next(outputs), sleep=sleeps.append, rounds=4, log=lines.append) + self.assertEqual(len(lines), 3) + self.assertIn('FAILED', lines[1]) + self.assertEqual(sleeps, [7, 7, 7]) + + def test_ensure_starts_once_and_reuses_a_live_watcher(self): + with tempfile.TemporaryDirectory() as temporary: + stack = Path(temporary) / 'stack' + (stack / 'config/native').mkdir(parents=True) + (stack / 'config/native/update.py').write_bytes((REPO / 'config/native/update.py').read_bytes()) + state = Path(temporary) / 'agent' + spawned = [] + + class Process: + pid = 4242 + + def spawn(cmd, **kwargs): + spawned.append((cmd, kwargs)) + return Process() + + alive = lambda pid: 'python3 /x/tools/scope_sync.py watch --stack-dir /s' + self.assertEqual(scope_sync.ensure(stack, state, spawn=spawn, ps=alive), 'started') + self.assertEqual(scope_sync.ensure(stack, state, spawn=spawn, ps=alive), 'running') + self.assertEqual(len(spawned), 1) + self.assertTrue(spawned[0][1]['start_new_session']) + self.assertEqual(spawned[0][0][2], 'watch') + # a recycled pid that now belongs to something else is not a watcher + self.assertEqual(scope_sync.ensure(stack, state, spawn=spawn, ps=lambda pid: 'nginx'), 'started') + self.assertEqual(len(spawned), 2) + + def test_concurrent_ensure_starts_at_most_one_watcher(self): + with tempfile.TemporaryDirectory() as temporary: + stack = Path(temporary) / 'stack' + (stack / 'config/native').mkdir(parents=True) + (stack / 'config/native/update.py').write_bytes((REPO / 'config/native/update.py').read_bytes()) + state = Path(temporary) / 'agent' + spawned, entered, release = [], threading.Event(), threading.Event() + + class Process: + pid = 9876 + + def spawn(_cmd, **_kwargs): + spawned.append(True) + entered.set() + release.wait(2) + return Process() + + alive = lambda _pid: 'python3 scope_sync.py watch --stack-dir ' + str(stack) + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(scope_sync.ensure, stack, state, 20, spawn, alive) + self.assertTrue(entered.wait(2)) + second = pool.submit(scope_sync.ensure, stack, state, 20, spawn, alive) + time.sleep(0.05) + release.set() + results = [first.result(timeout=2), second.result(timeout=2)] + self.assertEqual(len(spawned), 1) + self.assertEqual(results.count('started'), 1) + other = next(result for result in results if result != 'started') + self.assertIn(other, ('busy', 'running')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_plugin_bundle_activation.py b/tests/test_plugin_bundle_activation.py new file mode 100644 index 0000000..524bdc4 --- /dev/null +++ b/tests/test_plugin_bundle_activation.py @@ -0,0 +1,226 @@ +"""Signed plugin-bundle staging and recovery without Docker or network.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import time +import unittest +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location('tp_bundle_activation_update', REPO / 'config/native/update.py') +update = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(update) + + +class BundleActivation(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='tp-bundle-activation-') + self.addCleanup(self.temp.cleanup) + self.base = Path(self.temp.name).resolve() + self.root = self.base / 'stack' + self.root.mkdir() + self.key = self.base / 'test-key.pem' + self.trust = self.base / 'test-public.pem' + subprocess.run(['openssl', 'ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', str(self.key)], + check=True, capture_output=True) + subprocess.run(['openssl', 'pkey', '-in', str(self.key), '-pubout', '-out', str(self.trust)], + check=True, capture_output=True) + self.agent, self.image = b'agent-binary-fixture', b'image-archive-fixture' + entry = json.loads((REPO / 'plugins/homeassistant.json').read_text()) + entry.update(image_platform='linux/amd64', image_archive_sha256=hashlib.sha256(self.image).hexdigest()) + self.catalog = {'schema': 'thingspanel.plugin-catalog.v1', 'version': 'fixture', + 'published_at': int(time.time()), 'expires_at': int(time.time()) + 3600, + 'target_platform': 'linux/amd64', 'release_tag': 'plugin-v1.0.0', + 'agent_sha256': hashlib.sha256(self.agent).hexdigest(), 'plugins': [entry]} + + def signed(self, catalog): + raw = json.dumps(catalog, sort_keys=True).encode() + sig = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', str(self.key)], input=raw, + stdout=subprocess.PIPE, check=True).stdout + return raw, sig + + def download_helper(self, url, path): + relative = url.removeprefix('https://install.thingspanel.io/') + path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(REPO / relative, path) + + def fake_assets(self, module): + raw, sig = self.signed(self.catalog) + urls = { + module.DEFAULT_PAGES_BASE_URL + '/plugins/catalog-linux-amd64.json': raw, + module.DEFAULT_PAGES_BASE_URL + '/plugins/catalog-linux-amd64.json.sig': sig, + module.DEFAULT_RELEASE_BASE_URL + '/plugin-v1.0.0/tp-agent-linux-amd64': self.agent, + module.DEFAULT_RELEASE_BASE_URL + '/plugin-v1.0.0/ha-image-linux-amd64.tar': self.image, + } + def fetch(url, destination, maximum): + data = urls[url] + if len(data) > maximum: + raise RuntimeError('fixture exceeded limit') + Path(destination).write_bytes(data) + module._download_stream = fetch + return module + + def stage(self): + real_loader = update.load_plugin_helpers + def load(root): + return self.fake_assets(real_loader(root)) + with mock.patch.object(update, 'download', side_effect=self.download_helper), \ + mock.patch.object(update, 'load_plugin_helpers', side_effect=load), \ + mock.patch.object(update, 'run_command', return_value=b'linux/x86_64'): + return update.prepare_optional_plugin(self.root, str(self.trust), allow_download=True) + + def test_stage_commit_and_restore_without_network(self): + bundle, trust, catalog, pending = self.stage() + self.assertTrue(pending) + self.assertEqual(catalog['target_platform'], 'linux/amd64') + self.assertFalse((self.root / '.thingspanel-update/plugin-bundles/current.json').exists()) + self.assertEqual(update.pending_plugin_directory(self.root), bundle) + update.record_active_plugin(self.root, bundle) + update.clear_pending_plugin(self.root) + with mock.patch.object(update, 'download', side_effect=AssertionError('must not download')), \ + mock.patch.object(update, 'run_command', return_value=b'linux/amd64'): + restored = update.prepare_optional_plugin(self.root, str(self.trust), allow_download=False) + self.assertEqual(restored[0], bundle) + self.assertFalse(restored[3]) + self.assertEqual(restored[2], catalog) + + def test_active_bundle_tampering_and_pointer_escape_fail_closed(self): + bundle, _, _, _ = self.stage() + update.record_active_plugin(self.root, bundle) + update.clear_pending_plugin(self.root) + (bundle / 'bin/tp-agent').write_bytes(b'tampered') + with mock.patch.object(update, 'run_command', return_value=b'linux/amd64'): + self.assertIsNone(update.optional_plugin_for_activation(self.root, str(self.trust), allow_download=False)) + pointer = self.root / '.thingspanel-update/plugin-bundles/current.json' + pointer.write_text(json.dumps({'directory': '../escape'})) + with self.assertRaises(update.UpdateError): + update.active_plugin_directory(self.root) + + def test_expired_active_catalog_can_restore_but_not_be_staged_again(self): + bundle, _, _, _ = self.stage() + self.catalog['expires_at'] = int(time.time()) - 1 + raw, sig = self.signed(self.catalog) + (bundle / 'plugins/plugin-catalog.json').write_bytes(raw) + (bundle / 'plugins/plugin-catalog.json.sig').write_bytes(sig) + update.record_active_plugin(self.root, bundle) + with mock.patch.object(update, 'run_command', return_value=b'linux/amd64'): + restored = update.prepare_optional_plugin(self.root, str(self.trust), allow_download=False) + self.assertEqual(restored[2]['expires_at'], self.catalog['expires_at']) + + def test_rejected_optional_bundle_does_not_start_agent_or_block_platform(self): + operation = {'phase': 'activation_started', 'operation': 'a' * 32} + calls = [] + def run(args, cwd, **kwargs): + calls.append(args) + return b'' + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'verify_plugin_agent_bundle', return_value=False), \ + mock.patch.object(update, 'prepare_optional_plugin', side_effect=update.UpdateError('bad signature')), \ + mock.patch.object(update, 'run_command', side_effect=run), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + self.assertFalse(update.activate_native(self.root, str(self.trust), enable_plugin_bundle=True)) + self.assertFalse(any('agent_host.py' in ' '.join(args) or args[:2] == ['docker', 'load'] for args in calls)) + self.assertTrue(any(args[:3] == ['docker', 'compose', 'up'] for args in calls)) + + def test_pointer_is_written_only_after_agent_starts(self): + bundle, trust, catalog, _ = self.stage() + operation = {'phase': 'activation_started', 'operation': 'a' * 32} + order = [] + def preload(*_): + order.append('preload') + def start(*args, **kwargs): + self.assertIsNone(update.active_plugin_directory(self.root)) + order.append('start') + return True + def run(args, cwd, **kwargs): + if args[:3] == ['docker', 'compose', 'up']: + order.append('compose') + return b'' + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'verify_plugin_agent_bundle', return_value=False), \ + mock.patch.object(update, 'optional_plugin_for_activation', return_value=(bundle, trust, catalog, True)), \ + mock.patch.object(update, 'preload_homeassistant_image', side_effect=preload), \ + mock.patch.object(update, 'start_plugin_agent', side_effect=start), \ + mock.patch.object(update, 'run_command', side_effect=run), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + self.assertTrue(update.activate_native(self.root, str(trust), enable_plugin_bundle=True)) + self.assertEqual(update.active_plugin_directory(self.root), bundle) + self.assertEqual(order, ['preload', 'start', 'compose']) + + def test_failed_agent_start_does_not_promote_stage(self): + bundle, trust, catalog, _ = self.stage() + operation = {'phase': 'activation_started', 'operation': 'a' * 32} + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'verify_plugin_agent_bundle', return_value=False), \ + mock.patch.object(update, 'optional_plugin_for_activation', return_value=(bundle, trust, catalog, True)), \ + mock.patch.object(update, 'preload_homeassistant_image'), \ + mock.patch.object(update, 'start_plugin_agent', side_effect=update.UpdateError('agent unavailable')), \ + mock.patch.object(update, 'run_command'), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + self.assertFalse(update.activate_native(self.root, str(trust), enable_plugin_bundle=True)) + self.assertIsNone(update.active_plugin_directory(self.root)) + self.assertEqual(update.pending_plugin_directory(self.root), bundle) + + def test_pending_bundle_resumes_after_crash_without_downloading(self): + bundle, trust, catalog, _ = self.stage() + self.assertIsNone(update.active_plugin_directory(self.root)) + with mock.patch.object(update, 'download', side_effect=AssertionError('must not download')), \ + mock.patch.object(update, 'run_command', return_value=b'linux/amd64'): + restored = update.prepare_optional_plugin(self.root, str(trust), allow_download=False) + self.assertEqual(restored[0], bundle) + self.assertTrue(restored[3]) + self.assertEqual(restored[2], catalog) + update.record_active_plugin(self.root, restored[0]) + update.clear_pending_plugin(self.root) + self.assertEqual(update.active_plugin_directory(self.root), bundle) + self.assertIsNone(update.pending_plugin_directory(self.root)) + + def test_expired_pending_bundle_is_not_revived_and_can_be_refetched(self): + bundle, trust, catalog, _ = self.stage() + expired = dict(catalog, expires_at=int(time.time()) - 1) + raw, signature = self.signed(expired) + (bundle / 'plugins/plugin-catalog.json').write_bytes(raw) + (bundle / 'plugins/plugin-catalog.json.sig').write_bytes(signature) + self.assertEqual(update.pending_plugin_directory(self.root), bundle) + with mock.patch.object(update, 'run_command', return_value=b'linux/amd64'), \ + mock.patch.object(update, 'download', side_effect=update.UpdateError('network unavailable')) as download: + with self.assertRaisesRegex(update.UpdateError, 'network unavailable'): + update.prepare_optional_plugin(self.root, str(trust), allow_download=True) + self.assertEqual(download.call_count, 1) + self.assertIsNone(update.pending_plugin_directory(self.root)) + self.assertIsNone(update.active_plugin_directory(self.root)) + self.assertTrue(bundle.exists()) # Preserve the expired candidate for diagnosis. + + def test_normal_entrypoint_automatically_reconciles_interrupted_activation(self): + operation = {'phase': 'activation_started', 'operation': 'a' * 32} + with mock.patch.object(update, 'Transaction') as transaction_class, \ + mock.patch.object(update.sys, 'argv', ['update.py', '--root', str(self.root)]): + transaction = transaction_class.return_value + transaction.load.return_value = operation + transaction.reconcile_activation.return_value = True + self.assertEqual(update.main(), 0) + transaction.reconcile_activation.assert_called_once_with(None, enable_plugin_bundle=True) + transaction.run.assert_not_called() + + def test_managed_activation_ignores_partial_legacy_bundle_without_blocking_platform(self): + (self.root / 'bin').mkdir() + (self.root / 'bin/tp-agent').write_bytes(b'old partial bundle') + operation = {'phase': 'activation_started', 'operation': 'a' * 32} + calls = [] + def run(args, cwd, **kwargs): + calls.append(args) + return b'' + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'optional_plugin_for_activation', return_value=None), \ + mock.patch.object(update, 'run_command', side_effect=run), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + self.assertFalse(update.activate_native(self.root, enable_plugin_bundle=True)) + self.assertTrue(any(args[:3] == ['docker', 'compose', 'up'] for args in calls)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_prepare_auth_secret.py b/tests/test_prepare_auth_secret.py new file mode 100644 index 0000000..e4776d1 --- /dev/null +++ b/tests/test_prepare_auth_secret.py @@ -0,0 +1,270 @@ +"""Persistent ThingsVis auth identity; private filesystem, no services or DB.""" +import importlib.util +import os +from pathlib import Path +import tempfile +import subprocess +import json +import unittest +from unittest import mock +from test_update_transaction import BASE, CONFIG, payload_download + +REPO = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location('tp_prepare', REPO / 'config/native/prepare.py') +prepare = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(prepare) +KEY = 'TP_THINGSVIS_AUTH_SECRET' + + +class ThingsVisAuthSecretTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='tp-auth-secret-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.config = self.root / 'config/native' + self.config.mkdir(parents=True) + (self.config / 'internal.crt').write_text('fixture certificate; no OpenSSL invocation') + for patch in (mock.patch.object(prepare, 'ROOT', self.root), + mock.patch.object(prepare, 'CONFIG', self.config), + mock.patch.object(prepare.os, 'geteuid', return_value=1000, create=True), + mock.patch.dict(os.environ, {}, clear=False)): + patch.start() + self.addCleanup(patch.stop) + for key in (KEY, 'TP_THINGSVIS_IMAGE', 'TP_THINGSVIS_LOCAL_IMAGE_ID', 'TP_THINGSVIS_AUTH_POLICY_TARGET', 'TP_MARKETINSTALL_PROVIDER_TOKEN', 'TP_INSTALLER_ACTIVE_OPERATION', + 'TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN', 'TP_MARKETINSTALL_THINGSVIS_TOKEN'): + os.environ.pop(key, None) + + def test_first_install_persists_a_strong_unique_secret_and_upgrade_reuses_it(self): + first = prepare.configure()[KEY] + first_env = (self.root / '.env').read_bytes() + self.assertEqual(len(first), 64) + self.assertRegex(first, r'^[0-9a-f]{64}$') + self.assertEqual(prepare.configure()[KEY], first) + self.assertEqual((self.root / '.env').read_bytes(), first_env) + self.assertEqual(first_env.count((KEY + '=').encode()), 1) + self.assertNotEqual(prepare.deployment_secret({}, KEY), first) + self.assertNotIn('TP_THINGSVIS_AUTH_POLICY=', first_env.decode()) + + def test_existing_secret_is_preserved(self): + original = 'existing-deployment-secret-' + 'a' * 40 + (self.root / '.env').write_text(KEY + '=' + original + '\n') + self.assertEqual(prepare.configure()[KEY], original) + self.assertEqual(prepare.configure()[KEY], original) + self.assertEqual((self.root / '.env').read_text().count(KEY + '='), 1) + + def test_explicit_environment_seed_is_persisted_then_required_to_match(self): + seed = 'reviewed-first-install-secret-' + 'b' * 40 + os.environ[KEY] = seed + self.assertEqual(prepare.configure()[KEY], seed) + before = (self.root / '.env').read_bytes() + os.environ[KEY] = 'conflicting-secret-' + 'c' * 40 + with self.assertRaisesRegex(RuntimeError, 'conflicts'): + prepare.configure() + self.assertEqual((self.root / '.env').read_bytes(), before) + + def test_invalid_existing_secret_fails_before_any_identity_is_written(self): + for value in ('', 'short', 'your-super-secret-auth-key'): + with self.subTest(value=value): + original = (KEY + '=' + value + '\n').encode() + (self.root / '.env').write_bytes(original) + with self.assertRaisesRegex(RuntimeError, 'at least 32'): + prepare.configure() + self.assertEqual((self.root / '.env').read_bytes(), original) + self.assertFalse((self.config / 'broker/owner-tokens.json').exists()) + + def staged_upgrade(self, old_secret): + import copy + config = copy.deepcopy(CONFIG) + config['services']['thingsvis-server']['environment']['AUTH_SECRET'] = old_secret + files = prepare.update_files() + patch = mock.patch.object(files, 'render_with_fallback', return_value=config) + patch.start() + self.addCleanup(patch.stop) + (self.root / 'docker-compose.yml').write_text('old compose fixture') + transaction = files.Transaction(self.root, downloader=payload_download) + data = transaction.prepare(BASE, '') + transaction.apply(data) + data['phase'] = 'activation_started' + transaction.save(data) + os.environ['TP_INSTALLER_ACTIVE_OPERATION'] = data['operation'] + return transaction, data + + def test_secure_upgrade_rotates_old_sso_identity_once_and_journals_env(self): + original = 'custom-inline-secret-' + 'd' * 48 + previous_env = (KEY + '=' + original + '\n').encode() + (self.root / '.env').write_bytes(previous_env) + transaction, data = self.staged_upgrade(original) + os.environ['TP_THINGSVIS_IMAGE'] = 'local/thingsvis-reviewed:fixture' + os.environ['TP_THINGSVIS_AUTH_POLICY_TARGET'] = 'verified-sso-v1' + first = prepare.configure()[KEY] + self.assertNotEqual(first, original) + self.assertEqual(prepare.configure()[KEY], first) + text = (self.root / '.env').read_text() + self.assertIn('TP_THINGSVIS_AUTH_POLICY=verified-sso-v1\n', text) + self.assertEqual(text.count('TP_THINGSVIS_AUTH_POLICY='), 1) + self.assertEqual((transaction.state / data['operation'] / 'backup/.env').read_bytes(), previous_env) + entry = transaction.load()['activation_files']['.env'] + self.assertTrue(entry['applied']) + self.assertTrue(prepare.update_files().same(entry['new'], prepare.update_files().file_info(self.root / '.env'))) + + def test_secure_policy_cannot_be_claimed_for_default_legacy_image(self): + os.environ['TP_THINGSVIS_AUTH_POLICY_TARGET'] = 'verified-sso-v1' + for image in ('', 'registry/thingsvis-server:v1.0.23'): + with self.subTest(image=image): + os.environ['TP_THINGSVIS_IMAGE'] = image + with self.assertRaisesRegex(RuntimeError, 'reviewed secure'): + prepare.configure() + self.assertFalse((self.root / '.env').exists()) + + def test_secured_identity_is_reused_and_policy_downgrade_is_rejected(self): + os.environ['TP_THINGSVIS_IMAGE'] = 'local/thingsvis-reviewed:fixture' + os.environ['TP_THINGSVIS_AUTH_POLICY_TARGET'] = 'verified-sso-v1' + first = prepare.configure()[KEY] + self.assertEqual(prepare.configure()[KEY], first) + before = (self.root / '.env').read_bytes() + os.environ['TP_THINGSVIS_AUTH_POLICY_TARGET'] = '' + with self.assertRaisesRegex(RuntimeError, 'downgrade'): + prepare.configure() + self.assertEqual((self.root / '.env').read_bytes(), before) + + def test_policy_rotation_rejects_exported_secret_before_any_write(self): + os.environ['TP_THINGSVIS_IMAGE'] = 'local/thingsvis-reviewed:fixture' + os.environ['TP_THINGSVIS_AUTH_POLICY_TARGET'] = 'verified-sso-v1' + os.environ[KEY] = 'old-exported-secret-' + 'a' * 48 + with self.assertRaisesRegex(RuntimeError, 'would override'): + prepare.configure() + self.assertFalse((self.root / '.env').exists()) + self.assertFalse((self.config / 'broker').exists()) + + def test_existing_quoted_secret_keeps_its_literal_dotenv_encoding(self): + value = 'literal-dollar-$not-an-env-reference-' + 'b' * 32 + saved = "'" + value + "'" + (self.root / '.env').write_text(KEY + '=' + saved + '\n') + os.environ[KEY] = value + self.assertEqual(prepare.configure()[KEY], saved) + before = (self.root / '.env').read_bytes() + self.assertIn((KEY + '=' + saved + '\n').encode(), before) + self.assertEqual(prepare.configure()[KEY], saved) + self.assertEqual((self.root / '.env').read_bytes(), before) + + def test_integration_tokens_are_distinct_persistent_and_conflicts_fail_closed(self): + keys = ('TP_MARKETINSTALL_PROVIDER_TOKEN', 'TP_MARKETINSTALL_THINGSVIS_IDENTITY_TOKEN', 'TP_MARKETINSTALL_THINGSVIS_TOKEN') + first = prepare.configure() + self.assertEqual(len({first[key] for key in keys}), 3) + self.assertTrue(all(len(first[key]) == 64 for key in keys)) + second = prepare.configure() + self.assertEqual([first[key] for key in keys], [second[key] for key in keys]) + before = (self.root / '.env').read_bytes() + os.environ[keys[0]] = 'different-provider-token-' + 'f' * 40 + with self.assertRaisesRegex(RuntimeError, 'conflicts'): + prepare.configure() + self.assertEqual((self.root / '.env').read_bytes(), before) + + def test_legacy_broker_identity_and_services_are_preserved_in_minimal_directory(self): + import json + token = 'legacy-broker-token-' + 'a' * 48 + services = [{'username': 'existing', 'allowed_device_ids': ['fixture-device']}] + old_token = self.config / 'plugin-token' + old_services = self.config / 'services.json' + old_owners = self.config / 'owner-tokens.json' + owners = [{'token': token, 'broker_cell': 'community', 'broker_instance': 'community-mosquitto'}, + {'token': 'other-preexisting-token-' + 'b' * 40, 'broker_cell': 'other', 'broker_instance': 'existing'}] + old_token.write_text(token) + old_services.write_text(json.dumps(services)) + old_owners.write_text(json.dumps(owners)) + old_token.chmod(0o440) + old_services.chmod(0o440) + old_owners.chmod(0o440) + before = (old_token.read_bytes(), old_services.read_bytes(), old_owners.read_bytes()) + prepare.configure() + self.assertEqual((self.config / 'broker/plugin-token').read_text(), token) + self.assertEqual(json.loads((self.config / 'broker/services.json').read_text()), services) + self.assertEqual(json.loads((self.config / 'broker/owner-tokens.json').read_text()), owners) + self.assertEqual({p.name for p in (self.config / 'broker').iterdir()}, + {'plugin-token', 'owner-tokens.json', 'services.json'}) + self.assertEqual((old_token.read_bytes(), old_services.read_bytes(), old_owners.read_bytes()), before) + prepare.configure() + self.assertEqual((old_token.read_bytes(), old_services.read_bytes(), old_owners.read_bytes()), before) + + def test_originally_absent_broker_files_and_directory_are_journaled(self): + transaction, _ = self.staged_upgrade('old-inline-secret-' + 'b' * 48) + self.assertFalse((self.config / 'broker').exists()) + prepare.configure() + data = transaction.load() + self.assertEqual(data['phase'], 'activation_started') + self.assertIn('config/native/broker', data['activation_dirs']) + for name in ('plugin-token', 'owner-tokens.json', 'services.json'): + entry = data['activation_files']['config/native/broker/' + name] + self.assertIsNone(entry['old']) + self.assertTrue(entry['applied']) + self.assertTrue(prepare.update_files().same(entry['new'], prepare.update_files().file_info(self.config / 'broker' / name))) + + def test_standalone_prepare_cannot_resume_unknown_activation(self): + _, data = self.staged_upgrade('old-secret-' + 'c' * 48) + os.environ.pop('TP_INSTALLER_ACTIVE_OPERATION') + with self.assertRaisesRegex(RuntimeError, 'active installer operation'): + prepare.configure() + self.assertFalse((self.root / '.env').exists()) + self.assertFalse((self.config / 'broker').exists()) + os.environ['TP_INSTALLER_ACTIVE_OPERATION'] = data['operation'] + prepare.configure() + before = (self.root / '.env').read_bytes() + os.environ.pop('TP_INSTALLER_ACTIVE_OPERATION') + with self.assertRaisesRegex(RuntimeError, 'active installer operation'): + prepare.configure() + self.assertEqual((self.root / '.env').read_bytes(), before) + + def test_explicit_completed_device_scope_refresh_remains_serialized_and_atomic(self): + import json + transaction, _ = self.staged_upgrade('old-secret-' + 'd' * 48) + prepare.configure() + data = transaction.load() + data['phase'] = 'complete' + transaction.save(data) + os.environ.pop('TP_INSTALLER_ACTIVE_OPERATION') + services = [{'username': 'fixture', 'allowed_device_ids': ['new-device']}] + prepare.save('services.json', services, True) + self.assertEqual(json.loads((self.config / 'broker/services.json').read_text()), services) + with prepare.update_files().update_lock(transaction.state): + with self.assertRaisesRegex(RuntimeError, 'Another installer'): + prepare.save('services.json', [{'different': 'scope'}], True) + + +class LocalImageSelectionTests(unittest.TestCase): + def test_exact_local_image_identity_is_used_without_registry_pull(self): + image = 'local/thingsvis-reviewed:fixture' + image_id = 'sha256:' + 'a' * 64 + config = {'services': {'thingsvis-server': {'image': image}, 'backend': {'image': 'registry/backend:fixture'}}} + with mock.patch.object(prepare, 'command', side_effect=[json.dumps(config), image_id]) as command, mock.patch.object( + prepare.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as run: + prepare.pull_images({'TP_THINGSVIS_IMAGE': image, 'TP_THINGSVIS_LOCAL_IMAGE_ID': image_id}) + self.assertEqual(command.call_args.args, ('docker', 'image', 'inspect', '--format', '{{.Id}}', image)) + self.assertEqual(run.call_count, 1) + self.assertEqual(run.call_args.args[0], ['docker', 'pull', 'registry/backend:fixture']) + + def test_changed_local_image_identity_fails_before_any_pull(self): + image = 'local/thingsvis-reviewed:fixture' + config = {'services': {'thingsvis-server': {'image': image}, 'backend': {'image': 'registry/backend:fixture'}}} + with mock.patch.object(prepare, 'command', side_effect=[json.dumps(config), 'sha256:' + 'b' * 64]), mock.patch.object( + prepare.subprocess, 'run') as run: + with self.assertRaisesRegex(RuntimeError, 'identity differs'): + prepare.pull_images({'TP_THINGSVIS_IMAGE': image, 'TP_THINGSVIS_LOCAL_IMAGE_ID': 'sha256:' + 'a' * 64}) + run.assert_not_called() + + def test_pinned_backend_image_is_not_pulled_and_mismatch_fails(self): + image = 'local/backend-reviewed:fixture' + image_id = 'sha256:' + 'c' * 64 + config = {'services': {'backend': {'image': image}, 'redis': {'image': 'registry/redis:fixture'}}} + with mock.patch.object(prepare, 'command', side_effect=[json.dumps(config), image_id]), mock.patch.object( + prepare.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as run: + prepare.pull_images({'TP_BACKEND_IMAGE': image, 'TP_BACKEND_LOCAL_IMAGE_ID': image_id}) + self.assertEqual([call.args[0] for call in run.call_args_list], [['docker', 'pull', 'registry/redis:fixture']]) + with mock.patch.object(prepare, 'command', side_effect=[json.dumps(config), 'sha256:' + 'd' * 64]), mock.patch.object( + prepare.subprocess, 'run') as run: + with self.assertRaisesRegex(RuntimeError, 'identity differs'): + prepare.pull_images({'TP_BACKEND_IMAGE': image, 'TP_BACKEND_LOCAL_IMAGE_ID': image_id}) + run.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_reconcile_activation.py b/tests/test_reconcile_activation.py new file mode 100644 index 0000000..a3d5721 --- /dev/null +++ b/tests/test_reconcile_activation.py @@ -0,0 +1,406 @@ +"""reconcile_activation: closes an unresolved activation only after compose up and verification succeed. + +The journal and Compose/prepare commands are explicit substitutes; this does not start services. +""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location('tp_update_reconcile', REPO / 'config/native/update.py') +update = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(update) + + +class ReconcileActivation(unittest.TestCase): + def transaction(self, phase='activation_started'): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__('shutil').rmtree(root, ignore_errors=True)) + tx = update.Transaction(root) + data = {'phase': phase, 'operation': 'a' * 32, 'activation_files': {}} + saved = [] + patches = [mock.patch.object(update.Transaction, 'load', return_value=data), + mock.patch.object(update.Transaction, 'save', side_effect=lambda d: saved.append(dict(d)))] + for p in patches: + p.start() + self.addCleanup(p.stop) + return tx, data, saved + + def test_success_closes_journal_after_up_and_verify(self): + tx, data, saved = self.transaction() + with mock.patch.object(update, 'run_command') as run, mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + tx.reconcile_activation() + commands = [call.args[0] for call in run.call_args_list] + self.assertIn('--bootstrap', commands[0]) + self.assertEqual(commands[1][:3], ['docker', 'compose', 'up']) + self.assertIn('--verify', commands[2]) + self.assertEqual(run.call_args_list[2].kwargs['extra_env'], {'TP_INSTALLER_ACTIVE_OPERATION': 'a' * 32}) + self.assertEqual(saved[-1]['phase'], 'complete') + + def test_verification_failure_keeps_journal_unresolved(self): + tx, data, saved = self.transaction() + calls = [] + + def run(args, root, **kw): + calls.append(args) + if '--verify' in args: + raise update.UpdateError('Installer command failed (exit 1)') + with mock.patch.object(update, 'run_command', side_effect=run), mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + with self.assertRaises(update.UpdateError): + tx.reconcile_activation() + self.assertEqual(saved, []) + self.assertEqual(data['phase'], 'activation_started') + + def test_reconciliation_starts_agent_before_backend_compose(self): + tx, _, _ = self.transaction() + for relative in ('bin/tp-agent', 'plugins/plugin-catalog.json', 'plugins/plugin-catalog.json.sig'): + path = tx.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'test fixture') + trust_root = tx.root.parent / (tx.root.name + '-external-trust.pem') + trust_root.write_bytes(b'test trust root') + self.addCleanup(lambda: trust_root.unlink(missing_ok=True)) + calls = [] + + def fake(args, cwd, **kw): + calls.append(args) + return b'' + + with mock.patch.object(update, 'load_verified_plugin_catalog', return_value={'plugins': []}), \ + mock.patch.object(update, 'run_command', side_effect=fake), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + tx.reconcile_activation(str(trust_root)) + agent_index = next(i for i, args in enumerate(calls) if 'agent_host.py' in ' '.join(args)) + compose_index = next(i for i, args in enumerate(calls) if args[:3] == ['docker', 'compose', 'up']) + self.assertLess(agent_index, compose_index) + + def test_reconciliation_starts_scope_watcher_after_releasing_update_lock(self): + tx, _, _ = self.transaction() + started = [] + + def start_watcher(root): + self.assertEqual(Path(root).resolve(), tx.root.resolve()) + with update.update_lock(tx.state): + started.append(Path(root).resolve()) + + with mock.patch.object(update, 'verify_plugin_agent_bundle', return_value={'plugins': [{'id': 'homeassistant'}]}), \ + mock.patch.object(update, 'preload_homeassistant_image', return_value=True), \ + mock.patch.object(update, 'start_plugin_agent', return_value=True), \ + mock.patch.object(update, 'run_command'), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]), \ + mock.patch.object(update, 'start_scope_watcher_after_activation', side_effect=start_watcher): + self.assertTrue(tx.reconcile_activation()) + self.assertEqual(started, [tx.root.resolve()]) + + def test_reconciliation_without_agent_does_not_start_scope_watcher(self): + tx, _, _ = self.transaction() + with mock.patch.object(update, 'verify_plugin_agent_bundle', return_value=False), \ + mock.patch.object(update, 'run_command'), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]), \ + mock.patch.object(update, 'start_scope_watcher_after_activation') as watcher: + self.assertFalse(tx.reconcile_activation()) + watcher.assert_not_called() + + def test_refuses_without_unresolved_activation(self): + for phase in ('complete', 'recovered', 'config_committed'): + tx, data, saved = self.transaction(phase) + with mock.patch.object(update, 'run_command') as run: + with self.assertRaises(update.UpdateError): + tx.reconcile_activation() + run.assert_not_called() + self.assertEqual(saved, []) + + +class PluginAgentActivation(unittest.TestCase): + def root(self): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__('shutil').rmtree(root, ignore_errors=True)) + return root + + def add_bundle(self, root): + for relative in ('bin/tp-agent', 'plugins/plugin-catalog.json', 'plugins/plugin-catalog.json.sig'): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'test fixture') + + def external_trust_root(self, root): + trust_root = root.parent / (root.name + '-external-trust.pem') + trust_root.write_bytes(b'test trust root') + self.addCleanup(lambda: trust_root.unlink(missing_ok=True)) + return trust_root + + def test_old_payload_without_bundle_keeps_existing_startup_flow(self): + root = self.root() + with mock.patch.object(update, 'run_command') as run: + self.assertFalse(update.start_plugin_agent(root)) + run.assert_not_called() + + def test_partial_bundle_fails_closed(self): + root = self.root() + (root / 'plugins').mkdir() + (root / 'plugins/plugin-catalog.json').write_bytes(b'catalog') + with mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'bundle is incomplete'): + update.start_plugin_agent(root) + run.assert_not_called() + + def test_complete_bundle_starts_agent_with_pinned_files(self): + root = self.root() + self.add_bundle(root) + trust_root = self.external_trust_root(root) + with mock.patch.object(update, 'load_verified_plugin_catalog', return_value={'plugins': []}) as verify, \ + mock.patch.object(update, 'run_command') as run: + self.assertTrue(update.start_plugin_agent(root, str(trust_root))) + verify.assert_called_once_with(root.resolve(), trust_root.resolve()) + args = run.call_args_list[0].args[0] + self.assertEqual(args[1:3], [str((root / 'tools/agent_host.py').resolve()), 'up']) + self.assertEqual(Path(args[args.index('--agent-bin') + 1]), (root / 'bin/tp-agent').resolve()) + self.assertEqual(Path(args[args.index('--catalog') + 1]), (root / 'plugins/plugin-catalog.json').resolve()) + self.assertEqual(Path(args[args.index('--trust-root') + 1]), trust_root.resolve()) + self.assertIn('--defer-scope-watcher', args) + + def test_complete_bundle_without_external_trust_root_fails_closed(self): + root = self.root() + self.add_bundle(root) + with mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'not supplied out of band'): + update.start_plugin_agent(root) + run.assert_not_called() + + def test_bad_catalog_signature_does_not_restart_agent(self): + root = self.root() + self.add_bundle(root) + trust_root = self.external_trust_root(root) + with mock.patch.object(update, 'load_verified_plugin_catalog', side_effect=update.UpdateError('bad_signature')), \ + mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'bad_signature'): + update.start_plugin_agent(root, str(trust_root)) + run.assert_not_called() + + def test_trust_root_inside_installer_payload_is_rejected(self): + root = self.root() + self.add_bundle(root) + trust_root = root / 'keys/plugin-trust-root.pem' + trust_root.parent.mkdir(parents=True) + trust_root.write_bytes(b'test trust root') + with mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'outside the installer payload'): + update.start_plugin_agent(root, str(trust_root)) + run.assert_not_called() + + def test_activation_starts_agent_before_backend_compose(self): + root = self.root() + self.add_bundle(root) + trust_root = self.external_trust_root(root) + calls = [] + + def fake(args, cwd, **kw): + calls.append(args) + return b'' + + operation = {'phase': 'activation_started', 'operation': 'b' * 32} + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'load_verified_plugin_catalog', return_value={'plugins': []}), \ + mock.patch.object(update, 'run_command', side_effect=fake), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + update.activate_native(root, str(trust_root)) + agent_index = next(i for i, args in enumerate(calls) if 'agent_host.py' in ' '.join(args)) + compose_index = next(i for i, args in enumerate(calls) if args[:3] == ['docker', 'compose', 'up']) + self.assertLess(agent_index, compose_index) + + def ha_catalog(self, image_id='sha256:' + 'a' * 64, platform='linux/arm64'): + return {'plugins': [{'id': 'homeassistant', 'image_id': image_id, 'image_platform': platform, + 'image_archive_sha256': hashlib.sha256(b'image archive fixture').hexdigest()}]} + + def test_ha_image_archive_is_loaded_then_id_and_platform_are_checked(self): + root = self.root() + archive = root / 'plugins/homeassistant-image.tar' + archive.parent.mkdir(parents=True) + archive.write_bytes(b'image archive fixture') + image_id = 'sha256:' + 'a' * 64 + calls = [] + + def fake(args, cwd, **kw): + calls.append(args) + if args[:3] == ['docker', 'info', '--format']: + return b'linux/arm64\n' + if args[:3] == ['docker', 'image', 'inspect']: + return (image_id + ' linux/arm64\n').encode() + return b'Loaded image' + + with mock.patch.object(update, 'run_command', side_effect=fake): + self.assertTrue(update.preload_homeassistant_image(root, self.ha_catalog(image_id))) + self.assertEqual(calls[0][:3], ['docker', 'info', '--format']) + self.assertEqual(calls[1][:3], ['docker', 'load', '-i']) + self.assertEqual(calls[2][:4], ['docker', 'image', 'inspect', '--format']) + + def test_ha_image_archive_is_required_and_missing_fails_closed(self): + root = self.root() + with mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'archive is missing'): + update.preload_homeassistant_image(root, self.ha_catalog()) + run.assert_not_called() + + def test_loaded_image_digest_mismatch_fails_closed(self): + root = self.root() + archive = root / 'plugins/homeassistant-image.tar' + archive.parent.mkdir(parents=True) + archive.write_bytes(b'image archive fixture') + with mock.patch.object(update, 'run_command', side_effect=[b'linux/arm64', b'Loaded', b'sha256:' + b'b' * 64 + b' linux/arm64']): + with self.assertRaisesRegex(update.UpdateError, 'digest or platform'): + update.preload_homeassistant_image(root, self.ha_catalog()) + + def test_catalog_architecture_mismatch_with_docker_fails_before_image_load(self): + root = self.root() + archive = root / 'plugins/homeassistant-image.tar' + archive.parent.mkdir(parents=True) + archive.write_bytes(b'image archive fixture') + with mock.patch.object(update, 'run_command', return_value=b'linux/amd64') as run: + with self.assertRaisesRegex(update.UpdateError, 'does not match Docker'): + update.preload_homeassistant_image(root, self.ha_catalog()) + run.assert_called_once() + + def test_catalog_verification_failure_prevents_native_activation(self): + root = self.root() + operation = {'phase': 'activation_started', 'operation': 'b' * 32} + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'verify_plugin_agent_bundle', side_effect=update.UpdateError('bad signature')), \ + mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'bad signature'): + update.activate_native(root, '/outside/trust-root.pem') + run.assert_not_called() + + def test_image_preload_failure_prevents_agent_and_backend_start(self): + root = self.root() + operation = {'phase': 'activation_started', 'operation': 'b' * 32} + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'verify_plugin_agent_bundle', return_value=self.ha_catalog()), \ + mock.patch.object(update, 'preload_homeassistant_image', side_effect=update.UpdateError('digest mismatch')), \ + mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'digest mismatch'): + update.activate_native(root, '/outside/trust-root.pem') + run.assert_not_called() + + def test_tampered_archive_rejected_before_docker_load(self): + root = self.root() + archive = root / 'plugins/homeassistant-image.tar' + archive.parent.mkdir(parents=True) + archive.write_bytes(b'tampered archive') + # Even if the catalog's image is already present, replacing the signed archive + # must fail before Docker is queried or asked to load it. + with mock.patch.object(update, 'run_command', return_value=b'sha256:' + b'a' * 64 + b' linux/arm64') as run: + with self.assertRaisesRegex(update.UpdateError, 'archive digest does not match'): + update.preload_homeassistant_image(root, self.ha_catalog()) + run.assert_not_called() + + def test_invalid_archive_digest_format_fails_before_any_docker_command(self): + root = self.root() + archive = root / 'plugins/homeassistant-image.tar' + archive.parent.mkdir(parents=True) + archive.write_bytes(b'image archive fixture') + catalog = self.ha_catalog() + catalog['plugins'][0]['image_archive_sha256'] = 'A' * 64 + with mock.patch.object(update, 'run_command') as run: + with self.assertRaisesRegex(update.UpdateError, 'archive digest is invalid'): + update.preload_homeassistant_image(root, catalog) + run.assert_not_called() + + def test_activation_preloads_image_before_prepare_agent_and_compose(self): + root = self.root() + archive = root / 'plugins/homeassistant-image.tar' + archive.parent.mkdir(parents=True) + archive.write_bytes(b'image archive fixture') + operation = {'phase': 'activation_started', 'operation': 'b' * 32} + image_id = 'sha256:' + 'a' * 64 + calls = [] + + def fake(args, cwd, **kw): + calls.append(args) + if args[:3] == ['docker', 'info', '--format']: + return b'linux/arm64' + if args[:3] == ['docker', 'image', 'inspect']: + return (image_id + ' linux/arm64').encode() + return b'' + + with mock.patch.object(update.Transaction, 'load', return_value=operation), \ + mock.patch.object(update, 'verify_plugin_agent_bundle', return_value=self.ha_catalog(image_id)), \ + mock.patch.object(update, 'run_command', side_effect=fake), \ + mock.patch.object(update, 'restart_services_with_replaced_mounts', return_value=[]): + update.activate_native(root, '/outside/trust-root.pem') + image_load = next(i for i, args in enumerate(calls) if args[:3] == ['docker', 'load', '-i']) + image_inspect = next(i for i, args in enumerate(calls) if args[:3] == ['docker', 'image', 'inspect']) + prepare = next(i for i, args in enumerate(calls) if 'prepare.py' in ' '.join(args)) + agent = next(i for i, args in enumerate(calls) if 'agent_host.py' in ' '.join(args)) + compose = next(i for i, args in enumerate(calls) if args[:3] == ['docker', 'compose', 'up']) + self.assertLess(image_load, image_inspect) + self.assertLess(image_inspect, prepare) + self.assertLess(prepare, agent) + self.assertLess(agent, compose) + +class ReplacedMounts(unittest.TestCase): + def run_case(self, file_offset): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__('shutil').rmtree(root, ignore_errors=True)) + mounted = root / 'runtime.json' + mounted.write_text('{}') + started = __import__('time').time() - 1000 + os.utime(mounted, (started + file_offset, started + file_offset)) + stamp = __import__('datetime').datetime.fromtimestamp(started, __import__('datetime').timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.123456789Z') + config = {'services': {'notification-core': {'volumes': [{'type': 'bind', 'source': str(mounted), 'target': '/run/config/runtime.json'}]}, + 'redis': {'volumes': [{'type': 'volume', 'source': 'data', 'target': '/data'}]}}} + calls = [] + + def fake(args, cwd, **kw): + calls.append(args) + if args[:3] == ['docker', 'compose', 'config']: + return json.dumps(config).encode() + if args[:3] == ['docker', 'compose', 'ps']: + return b'cid1\n' + if args[:2] == ['docker', 'inspect']: + return ('true ' + stamp).encode() + return b'' + with mock.patch.object(update, 'run_command', side_effect=fake): + stale = update.restart_services_with_replaced_mounts(root) + return stale, calls + + def test_file_replaced_after_start_restarts_only_that_service(self): + stale, calls = self.run_case(100) + self.assertEqual(stale, ['notification-core']) + self.assertIn(['docker', 'compose', 'restart', 'notification-core'], calls) + + def test_file_older_than_container_start_restarts_nothing(self): + stale, calls = self.run_case(-100) + self.assertEqual(stale, []) + self.assertFalse(any(c[:3] == ['docker', 'compose', 'restart'] for c in calls)) + + +class BackendImageVersion(unittest.TestCase): + def check(self, image, version='v1.3.0'): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__('shutil').rmtree(root, ignore_errors=True)) + tx = update.Transaction(root) + stage = root / 'stage' + stage.mkdir() + config = {'services': {'backend': {'image': image}}} + text = 'UPDATE_ENGINE_SHA256="' + __import__('hashlib').sha256(Path(update.__file__).read_bytes()).hexdigest() + '"\n' + entrypoint = 'upgrade.ps1' if os.name == 'nt' else 'upgrade.sh' + (stage / entrypoint).write_text(text) + tx.artifacts = [] + with mock.patch.object(update, 'render_with_fallback', return_value=config): + tx.validate(stage, version) + + def test_uninterpolated_default_image_matches_requested_version(self): + self.check('${TP_BACKEND_IMAGE:-registry.example/thingspanel-go:v1.3.0}') + + def test_uninterpolated_default_image_with_other_version_is_rejected(self): + with self.assertRaises(update.UpdateError): + self.check('${TP_BACKEND_IMAGE:-registry.example/thingspanel-go:v1.2.0}') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_release_manifest.py b/tests/test_release_manifest.py new file mode 100644 index 0000000..2d8c187 --- /dev/null +++ b/tests/test_release_manifest.py @@ -0,0 +1,201 @@ +import hashlib +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "config" / "native")) + +import release_manifest as rm # noqa: E402 + +PUBLISHER = "https://github.com/ThingsPanel/thingspanel-installer/.github/workflows/release.yml" +COMMIT = "a" * 40 +NOW = 1_800_000_000 + + +def _openssl(*args, **kwargs): + return subprocess.run(["openssl", *args], check=True, capture_output=True, **kwargs) + + +@unittest.skipUnless(shutil.which("openssl"), "openssl is required") +class ReleaseManifestTests(unittest.TestCase): + """Keys exist only inside each test's temporary directory; no key is a real trust root.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="tp-manifest-test-")) + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + self.root, self.priv = self._keypair("root") + self.payload = self.tmp / "payload" + (self.payload / "scripts").mkdir(parents=True) + (self.payload / "install.sh").write_bytes(b"echo install\n") + (self.payload / "scripts" / "update.py").write_bytes(b"print('update')\n") + + def _keypair(self, name): + priv = self.tmp / f"{name}.key" + pub = self.tmp / f"{name}.pub" + _openssl("ecparam", "-name", "prime256v1", "-genkey", "-noout", "-out", str(priv)) + _openssl("ec", "-in", str(priv), "-pubout", "-out", str(pub)) + return pub, priv + + def _manifest(self, **release_over): + files = [] + for path in sorted(p for p in self.payload.rglob("*") if p.is_file()): + data = path.read_bytes() + files.append( + {"path": path.relative_to(self.payload).as_posix(), "sha256": hashlib.sha256(data).hexdigest(), "size": len(data)} + ) + release = { + "version": "v1.4.0", + "publisher": PUBLISHER, + "commit": COMMIT, + "not_before": NOW - 100, + "expires_at": NOW + 1000, + } + release.update(release_over) + return json.dumps({"schema": rm.SCHEMA, "release": release, "files": files}, sort_keys=True).encode() + + def _sign(self, manifest, priv=None): + path = self.tmp / "m.json" + path.write_bytes(manifest) + return _openssl("dgst", "-sha256", "-sign", str(priv or self.priv), str(path)).stdout + + def _verify(self, manifest=None, signature=None, **kw): + manifest = manifest if manifest is not None else self._manifest() + signature = signature if signature is not None else self._sign(manifest) + kw.setdefault("expected_publisher", PUBLISHER) + kw.setdefault("now", NOW) + return rm.verify_release(manifest, signature, kw.pop("trust_root", self.root), self.payload, **kw) + + def assertRejected(self, reason, **kw): + with self.assertRaises(rm.ManifestError) as ctx: + self._verify(**kw) + self.assertEqual(ctx.exception.reason, reason) + + def test_valid_release_is_accepted(self): + doc = self._verify(expected_version="v1.4.0") + self.assertEqual(doc["release"]["commit"], COMMIT) + self.assertEqual(len(doc["files"]), 2) + + def test_no_trust_root_fails_closed(self): + self.assertRejected("trust_root_not_configured", trust_root=None) + self.assertRejected("trust_root_not_configured", trust_root=self.tmp / "absent.pub") + + def test_non_public_key_or_wrong_curve_is_not_a_root(self): + not_a_key = self.tmp / "junk.pem" + not_a_key.write_text("hello") + self.assertRejected("trust_root_not_configured", trust_root=not_a_key) + rsa = self.tmp / "rsa.pub" + rsa_key = self.tmp / "rsa.key" + _openssl("genrsa", "-out", str(rsa_key), "2048") + _openssl("rsa", "-in", str(rsa_key), "-pubout", "-out", str(rsa)) + self.assertRejected("trust_root_not_configured", trust_root=rsa) + + def test_signature_from_another_key_is_rejected(self): + _, other_priv = self._keypair("other") + manifest = self._manifest() + self.assertRejected("bad_signature", manifest=manifest, signature=self._sign(manifest, other_priv)) + + def test_modified_manifest_invalidates_signature(self): + manifest = self._manifest() + signature = self._sign(manifest) + self.assertRejected("bad_signature", manifest=manifest.replace(b"v1.4.0", b"v9.9.9"), signature=signature) + + def test_valid_signature_from_other_publisher_is_rejected(self): + self.assertRejected("wrong_publisher", manifest=self._manifest(publisher="https://example.com/other.yml")) + + def test_version_mismatch_is_rejected(self): + self.assertRejected("version_mismatch", expected_version="v1.5.0") + + def test_expired_and_not_yet_valid(self): + self.assertRejected("expired", now=NOW + 1000) + self.assertRejected("not_yet_valid", now=NOW - 101) + + def test_revoked_version_is_rejected(self): + self.assertRejected("revoked", revoked_versions={"v1.4.0"}) + + def test_changed_file_is_a_digest_mismatch(self): + manifest = self._manifest() + signature = self._sign(manifest) + (self.payload / "install.sh").write_bytes(b"echo tampered\n") + self.assertRejected("digest_mismatch", manifest=manifest, signature=signature) + + def test_missing_file_is_rejected(self): + manifest = self._manifest() + signature = self._sign(manifest) + (self.payload / "scripts" / "update.py").unlink() + self.assertRejected("missing_file", manifest=manifest, signature=signature) + + def test_unlisted_file_is_rejected(self): + manifest = self._manifest() + signature = self._sign(manifest) + (self.payload / "extra.sh").write_bytes(b"echo mixed release\n") + self.assertRejected("unlisted_file", manifest=manifest, signature=signature) + + def test_symlink_in_payload_is_rejected(self): + manifest = self._manifest() + signature = self._sign(manifest) + (self.payload / "link").symlink_to(self.payload / "install.sh") + self.assertRejected("unexpected_symlink", manifest=manifest, signature=signature) + + def test_path_traversal_and_absolute_paths_are_rejected(self): + for bad in ("../escape", "/etc/passwd", "a/../b", "a//b", "./a", "a\\b"): + manifest = json.dumps( + { + "schema": rm.SCHEMA, + "release": { + "version": "v1.4.0", + "publisher": PUBLISHER, + "commit": COMMIT, + "not_before": NOW - 100, + "expires_at": NOW + 1000, + }, + "files": [{"path": bad, "sha256": "0" * 64, "size": 0}], + } + ).encode() + with self.subTest(path=bad): + self.assertRejected("bad_path", manifest=manifest) + + def test_duplicate_paths_and_bad_commit_are_rejected(self): + good = json.loads(self._manifest()) + dup = dict(good, files=good["files"] + [good["files"][0]]) + self.assertRejected("malformed_manifest", manifest=json.dumps(dup).encode()) + bad_commit = json.loads(self._manifest()) + bad_commit["release"]["commit"] = "main" + self.assertRejected("malformed_manifest", manifest=json.dumps(bad_commit).encode()) + + def test_command_line_exit_codes(self): + import time + + now = int(time.time()) + manifest = self._manifest(not_before=now - 100, expires_at=now + 1000) + (self.tmp / "release.json").write_bytes(manifest) + (self.tmp / "release.json.sig").write_bytes(self._sign(manifest)) + base = [ + sys.executable, + str(Path(rm.__file__)), + "--manifest", + str(self.tmp / "release.json"), + "--signature", + str(self.tmp / "release.json.sig"), + "--payload", + str(self.payload), + "--publisher", + PUBLISHER, + ] + ok = subprocess.run(base + ["--trust-root", str(self.root)], capture_output=True, text=True) + self.assertEqual(ok.returncode, 0, ok.stderr) + self.assertIn("verified (2 files)", ok.stdout) + no_root = subprocess.run(base, capture_output=True, text=True) + self.assertEqual(no_root.returncode, 2) + self.assertIn("trust_root_not_configured", no_root.stderr) + other_root, _ = self._keypair("other-root") + wrong_root = subprocess.run(base + ["--trust-root", str(other_root)], capture_output=True, text=True) + self.assertEqual(wrong_root.returncode, 2) + self.assertIn("bad_signature", wrong_root.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_signed_update.py b/tests/test_signed_update.py new file mode 100644 index 0000000..b897818 --- /dev/null +++ b/tests/test_signed_update.py @@ -0,0 +1,193 @@ +"""Signed release verification inside the real update transaction. + +The Transaction, verifier and OpenSSL are real. Network download and Compose +rendering are the substitutes (as in test_update_transaction). Keys live only in +each test's temporary directory; none is a trust root. +""" +import copy +import hashlib +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import time +import unittest +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location('tp_update_signed', REPO / 'config/native/update.py') +update = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(update) +BASE = 'https://installer.invalid' +VERSION = 'v-fixture' +PUBLISHER = update.DEFAULT_RELEASE_PUBLISHER +CONFIG = {'services': {'backend': {'image': 'registry/backend:' + VERSION, 'environment': { + 'GOTP_DB_PSQL_HOST': 'postgres', 'GOTP_DB_PSQL_PORT': '5432', + 'GOTP_DB_PSQL_USERNAME': 'postgres', 'GOTP_DB_PSQL_DBNAME': 'ThingsPanel'}}, + 'postgres': {}, 'thingsvis-server': {'environment': { + 'DATABASE_URL': 'postgresql://fixture:fixture@postgres/ThingsPanel'}}}} + + +def openssl(*args): + return subprocess.run(['openssl', *args], check=True, capture_output=True) + + +@unittest.skipUnless(shutil.which('openssl'), 'openssl is required') +class SignedUpdateTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='tp-signed-update-') + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.root = self.dir / 'install' + self.root.mkdir() + patcher = mock.patch.object(update, 'render_with_fallback', return_value=copy.deepcopy(CONFIG)) + patcher.start() + self.addCleanup(patcher.stop) + self.pub, self.priv = self.keypair('root') + self.served = {} # relative path -> bytes overrides + self.manifest_overrides = {} + self.sign_with = self.priv + self.drop_from_manifest = set() + self.fetched = [] + + def keypair(self, name): + priv, pub = self.dir / (name + '.key'), self.dir / (name + '.pub') + openssl('ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', str(priv)) + openssl('ec', '-in', str(priv), '-pubout', '-out', str(pub)) + return pub, priv + + def tx(self, policy): + return update.Transaction(self.root, downloader=self.download, release_policy=policy) + + def policy(self, **kwargs): + value = {'trust_root': str(self.pub), 'publisher': PUBLISHER, 'revoked': []} + value.update(kwargs) + return value + + def release_bytes(self, tx): + files = [] + for relative, _ in tx.artifacts: + data = (REPO / relative).read_bytes() + if relative in self.drop_from_manifest: + continue + files.append({'path': relative, 'sha256': hashlib.sha256(data).hexdigest(), 'size': len(data)}) + now = int(time.time()) + release = {'version': VERSION, 'publisher': PUBLISHER, 'commit': 'a' * 40, + 'not_before': now - 100, 'expires_at': now + 3600} + release.update(self.manifest_overrides) + return json.dumps({'schema': 'thingspanel.release-manifest.v1', 'release': release, 'files': files}, + sort_keys=True).encode() + + def download(self, url, path): + relative = url[len(BASE) + 1:] + self.fetched.append(relative) + path.parent.mkdir(parents=True, exist_ok=True) + if relative == update.RELEASE_MANIFEST: + path.write_bytes(self.manifest) + elif relative == update.RELEASE_MANIFEST + '.sig': + source = self.dir / 'm.json' + source.write_bytes(self.manifest) + path.write_bytes(openssl('dgst', '-sha256', '-sign', str(self.sign_with), str(source)).stdout) + elif relative in self.served: + path.write_bytes(self.served[relative]) + else: + path.write_bytes((REPO / relative).read_bytes()) + + def seed(self, tx): + for relative, _ in tx.artifacts: + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('original ' + relative + '\n', encoding='utf-8') + path.chmod(0o600) + for relative in update.WATCHED: + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('synthetic-local-only\n', encoding='utf-8') + path.chmod(0o600) + return {relative: (self.root / relative).read_bytes() for relative, _ in tx.artifacts} + + def run_update(self, policy, **kwargs): + tx = self.tx(policy) + before = self.seed(tx) + self.manifest = self.release_bytes(tx) + return tx, before + + def assertRejected(self, reason, policy=None, setup=None): + tx, before = self.run_update(self.policy() if policy is None else policy) + if setup: + setup() + with self.assertRaisesRegex(update.UpdateError, 'Signed release verification failed: ' + reason): + tx.run(BASE, expected_version=VERSION) + for relative, content in before.items(): + self.assertEqual((self.root / relative).read_bytes(), content, relative) + + def test_valid_signed_release_is_applied(self): + tx, before = self.run_update(self.policy()) + tx.run(BASE, expected_version=VERSION) + for relative, _ in tx.artifacts: + self.assertEqual((self.root / relative).read_bytes(), (REPO / relative).read_bytes(), relative) + self.assertIn(update.RELEASE_MANIFEST, self.fetched) + + def test_tampered_served_file_leaves_installation_untouched(self): + self.served['docker-compose.yml'] = b'services: {}\n' + self.assertRejected('digest_mismatch') + + def test_manifest_signed_by_another_key_is_rejected(self): + _, other = self.keypair('other') + self.sign_with = other + self.assertRejected('bad_signature') + + def test_staged_file_missing_from_manifest_is_rejected(self): + self.drop_from_manifest = {'niginx.conf'} + self.assertRejected('unlisted_file') + + def test_revoked_version_is_rejected(self): + self.assertRejected('revoked', policy=self.policy(revoked=[VERSION])) + + def test_expired_manifest_is_rejected(self): + self.manifest_overrides = {'not_before': 1, 'expires_at': 2} + self.assertRejected('expired') + + def test_other_publisher_is_rejected(self): + self.manifest_overrides = {'publisher': 'https://example.com/other.yml'} + self.assertRejected('wrong_publisher') + + def test_requiring_signature_without_trust_root_fails_closed(self): + self.assertRejected('trust_root_not_configured', policy=self.policy(trust_root=None)) + + def test_tampered_verifier_is_never_loaded(self): + # Hide the genuine sibling by pinning another digest; the download must also match the pin. + with mock.patch.object(update, 'RELEASE_VERIFIER_SHA256', '0' * 64): + tx, before = self.run_update(self.policy()) + with self.assertRaisesRegex(update.UpdateError, 'does not match the digest pinned'): + tx.run(BASE, expected_version=VERSION) + for relative, content in before.items(): + self.assertEqual((self.root / relative).read_bytes(), content, relative) + + def test_downloaded_verifier_is_used_when_sibling_is_absent(self): + # The entry points run a lone update.py from a temporary directory. + lone = self.dir / 'elsewhere' / 'update.py' + lone.parent.mkdir() + lone.write_bytes((REPO / 'config/native/update.py').read_bytes()) + spec = importlib.util.spec_from_file_location('tp_update_lone', lone) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + with mock.patch.object(module, 'render_with_fallback', return_value=copy.deepcopy(CONFIG)): + tx = module.Transaction(self.root, downloader=self.download, release_policy=self.policy()) + self.seed(tx) + self.manifest = self.release_bytes(tx) + self.served['config/native/update.py'] = lone.read_bytes() + tx.run(BASE, expected_version=VERSION) + self.assertIn(update.RELEASE_VERIFIER, self.fetched) + + def test_unsigned_mode_is_unchanged(self): + tx = update.Transaction(self.root, downloader=self.download) + self.seed(tx) + tx.run(BASE, expected_version=VERSION) + self.assertNotIn(update.RELEASE_MANIFEST, self.fetched) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_update_transaction.py b/tests/test_update_transaction.py new file mode 100644 index 0000000..44b01f7 --- /dev/null +++ b/tests/test_update_transaction.py @@ -0,0 +1,609 @@ +"""Installer filesystem transactions only; no network, Docker daemon or DB. + +The real Transaction implementation is exercised. Download and Compose output +are the explicit I/O substitutes. Crash workers are ordinary child processes. +""" +import copy +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import tempfile +import time +import unittest +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location('tp_update', REPO / 'config/native/update.py') +update = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(update) +CONFIG = {'services': {'backend': {'image': 'registry/backend:v-fixture', 'environment': { + 'GOTP_DB_PSQL_HOST': 'postgres', 'GOTP_DB_PSQL_PORT': '5432', + 'GOTP_DB_PSQL_USERNAME': 'postgres', 'GOTP_DB_PSQL_DBNAME': 'ThingsPanel', + 'GOTP_RELATIONAL_DRIVER': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT': '5432', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE': 'ThingsPanel', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD': 'synthetic-fixture'}}, + 'postgres': {}, 'thingsvis-server': {'environment': { + 'DATABASE_URL': 'postgresql://fixture:fixture@postgres/ThingsPanel'}}}} +BASE = 'https://installer.invalid' + + +def payload_download(url, path): + relative = url[len(BASE) + 1:] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes((REPO / relative).read_bytes()) + + +class TransactionTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='tp-update-unit-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) / 'install' + self.root.mkdir() + self.render = mock.patch.object(update, 'render_with_fallback', return_value=copy.deepcopy(CONFIG)) + self.render.start() + self.addCleanup(self.render.stop) + + def tx(self, **kwargs): + return update.Transaction(self.root, downloader=payload_download, **kwargs) + + def originals(self, tx=None): + tx = tx or self.tx() + for relative, _ in tx.artifacts: + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('original ' + relative + '\n', encoding='utf-8') + path.chmod(0o600) + for relative in update.WATCHED: + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('synthetic-local-only\n', encoding='utf-8') + path.chmod(0o600) + result = {p: update.file_info(self.root / p) for p, _ in tx.artifacts} + result.update({p: update.file_info(self.root / p) for p in update.WATCHED}) + return result + + def assertOriginals(self, original): + for path, expected in original.items(): + self.assertTrue(update.same(update.file_info(self.root / path), expected), path) + + def test_complete_payload_staged_before_any_target_change(self): + tx = self.tx() + old = self.originals(tx) + count = 0 + def download(url, path): + nonlocal count + self.assertOriginals(old) + count += 1 + payload_download(url, path) + tx.downloader = download + activated = [] + def activate(root): + activated.append(root) + self.assertEqual(tx.load()['phase'], 'activation_started') + with self.assertRaisesRegex(update.UpdateError, 'Another installer'): + with update.update_lock(tx.state): + pass + tx.run(BASE, activate=activate, expected_version='v-fixture') + self.assertEqual(count, 9) + self.assertEqual(activated, [self.root]) + self.assertEqual(tx.load()['phase'], 'complete') + for relative, _ in tx.artifacts: + self.assertEqual((self.root / relative).read_bytes(), (REPO / relative).read_bytes()) + self.assertEqual(update.file_info(self.root / relative)['mode'], old[relative]['mode']) + for relative in update.WATCHED: + self.assertTrue(update.same(update.file_info(self.root / relative), old[relative])) + + def test_scope_watcher_starts_after_activation_releases_update_lock(self): + tx = self.tx() + self.originals(tx) + activated = [] + + def activate(root): + self.assertEqual(root, self.root) + with self.assertRaisesRegex(update.UpdateError, 'Another installer'): + with update.update_lock(tx.state): + pass + return True + + def start_watcher(root): + self.assertEqual(root, self.root) + with update.update_lock(tx.state): + activated.append(root) + + with mock.patch.object(update, 'start_scope_watcher_after_activation', side_effect=start_watcher): + self.assertTrue(tx.run(BASE, activate=activate, expected_version='v-fixture')) + self.assertEqual(activated, [self.root]) + + def test_no_plugin_agent_keeps_old_install_without_scope_sync_dependency(self): + tx = self.tx() + self.originals(tx) + with mock.patch.object(update, 'start_scope_watcher_after_activation') as watcher: + self.assertFalse(tx.run(BASE, activate=lambda _: False, expected_version='v-fixture')) + watcher.assert_not_called() + + def test_management_file_download_failures_leave_entire_payload_unchanged(self): + tx = self.tx() + old = self.originals(tx) + for boundary in (8, 9): + count = 0 + def download(url, path): + nonlocal count + count += 1 + payload_download(url, path) + if count == boundary: + raise update.UpdateError('synthetic download interruption') + tx.downloader = download + with self.subTest(boundary=boundary), self.assertRaisesRegex(update.UpdateError, 'interruption'): + tx.run(BASE) + self.assertOriginals(old) + + def test_invalid_payload_does_not_execute_staged_prepare(self): + tx = self.tx() + old = self.originals(tx) + marker = self.root / 'must-not-exist' + def download(url, path): + payload_download(url, path) + if path.name == 'prepare.py': + path.write_text('from pathlib import Path\nPath(%r).touch()\n' % str(marker)) + if path.name == 'runtime.encore.json': + path.write_text('partial invalid JSON') + tx.downloader = download + with self.assertRaisesRegex(update.UpdateError, 'Invalid staged'): + tx.run(BASE) + self.assertFalse(marker.exists()) + self.assertOriginals(old) + + def test_requested_version_mismatch_is_precommit(self): + tx = self.tx() + old = self.originals(tx) + with self.assertRaisesRegex(update.UpdateError, 'Requested version'): + tx.run(BASE, expected_version='another-version') + self.assertOriginals(old) + + def test_mixed_updater_and_management_script_rejected(self): + tx = self.tx() + old = self.originals(tx) + def download(url, path): + payload_download(url, path) + if path.name.startswith('upgrade.'): + path.write_text('UPDATE_ENGINE_SHA256="' + '0' * 64 + '"\n') + tx.downloader = download + with self.assertRaisesRegex(update.UpdateError, 'different releases'): + tx.run(BASE) + self.assertOriginals(old) + + def test_all_replacement_failures_restore_original_files_and_modes(self): + tx = self.tx() + old = self.originals(tx) + for relative, _ in tx.artifacts: + for prefix in ('before-replace:', 'after-replace:'): + event = prefix + relative + def checkpoint(actual): + if actual == event: + raise RuntimeError('synthetic replacement interruption') + tx.checkpoint = checkpoint + with self.subTest(event=event), self.assertRaisesRegex(RuntimeError, 'interruption'): + tx.run(BASE) + self.assertOriginals(old) + self.assertEqual(tx.load()['phase'], 'recovered') + + def test_originally_absent_files_and_new_empty_directories_are_removed(self): + tx = self.tx(checkpoint=lambda event: (_ for _ in ()).throw(RuntimeError('stop')) + if event == 'after-replace:config/native/prepare.py' else None) + with self.assertRaises(RuntimeError): + tx.run(BASE) + for relative, _ in tx.artifacts: + self.assertFalse((self.root / relative).exists()) + self.assertFalse((self.root / 'config').exists()) + self.assertEqual(tx.load()['phase'], 'recovered') + + def test_user_edit_after_validation_is_preserved(self): + tx = self.tx() + old = self.originals(tx) + edited = self.root / 'niginx.conf' + tx.checkpoint = lambda event: edited.write_text('operator edit') if event == 'validated' else None + with self.assertRaisesRegex(update.UpdateError, 'changed after preflight'): + tx.run(BASE) + self.assertEqual(edited.read_text(), 'operator edit') + self.assertOriginals({k: v for k, v in old.items() if k != 'niginx.conf'}) + + def test_env_edit_immediately_before_replacement_is_preserved(self): + tx = self.tx() + old = self.originals(tx) + tx.checkpoint = lambda event: (self.root / '.env').write_text('operator env') if event == 'before-replace:docker-compose.yml' else None + with self.assertRaisesRegex(update.UpdateError, 'configuration changed'): + tx.run(BASE) + self.assertOriginals({k: v for k, v in old.items() if k != '.env'}) + self.assertEqual((self.root / '.env').read_text(), 'operator env') + + def test_foreign_edit_during_partial_replacement_blocks_recovery(self): + tx = self.tx() + self.originals(tx) + def checkpoint(event): + if event == 'after-replace:niginx.conf': + (self.root / 'docker-compose.yml').write_text('operator changed new compose') + raise RuntimeError('stop') + tx.checkpoint = checkpoint + with self.assertRaisesRegex(update.UpdateError, 'externally changed'): + tx.run(BASE) + self.assertEqual((self.root / 'docker-compose.yml').read_text(), 'operator changed new compose') + self.assertEqual((self.root / 'niginx.conf').read_bytes(), (REPO / 'niginx.conf').read_bytes()) + with self.assertRaisesRegex(update.UpdateError, 'externally changed'): + self.tx().run(BASE, recovery_only=True) + + def test_edit_of_already_replaced_file_prevents_activation(self): + tx = self.tx() + self.originals(tx) + tx.checkpoint = lambda event: (self.root / 'docker-compose.yml').write_text('operator after commit') if event == 'config_committed' else None + activate = mock.Mock() + with self.assertRaisesRegex(update.UpdateError, 'externally changed'): + tx.run(BASE, activate=activate) + activate.assert_not_called() + self.assertEqual((self.root / 'docker-compose.yml').read_text(), 'operator after commit') + + def test_activation_failure_preserves_committed_configuration_for_review(self): + tx = self.tx() + self.originals(tx) + def activate(_): + raise RuntimeError('synthetic external failure') + with self.assertRaises(RuntimeError): + tx.run(BASE, activate=activate) + self.assertEqual(tx.load()['phase'], 'activation_started') + self.assertEqual((self.root / 'docker-compose.yml').read_bytes(), (REPO / 'docker-compose.yml').read_bytes()) + with self.assertRaisesRegex(update.UpdateError, 'No database rollback'): + self.tx().run(BASE, recovery_only=True) + + def test_activation_environment_backup_and_receipt_survive_completion(self): + tx = self.tx() + old = self.originals(tx) + before = (self.root / '.env').read_bytes() + after = b'TP_AUTH=synthetic-new-identity\nTP_AUTH_POLICY=fixture-v1\n' + tx.run(BASE, activate=lambda _: tx.write_activation_environment(after)) + data = tx.load() + self.assertEqual(data['phase'], 'complete') + entry = data['activation_files']['.env'] + self.assertEqual(entry['old'], old['.env']) + self.assertTrue(entry['applied']) + self.assertTrue(update.same(entry['new'], update.file_info(self.root / '.env'))) + self.assertEqual((tx.state / data['operation'] / 'backup/.env').read_bytes(), before) + self.tx().run(BASE, recovery_only=True) + self.assertEqual((self.root / '.env').read_bytes(), after) + + @unittest.skipIf(os.name == 'nt', 'SIGKILL semantics are checked on POSIX') + def test_activation_environment_kill9_never_claims_external_rollback(self): + parent = self.root + for event in ('activation-env-prepared', 'activation-env-written'): + with self.subTest(event=event): + self.root = parent / event + self.root.mkdir() + old = self.originals() + process = self.worker('kill-env', event) + _, err = process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGKILL, err) + data = self.tx().load() + self.assertEqual(data['phase'], 'activation_started') + self.assertFalse(data['activation_files']['.env']['applied']) + expected = old['.env'] if event == 'activation-env-prepared' else data['activation_files']['.env']['new'] + self.assertTrue(update.same(update.file_info(self.root / '.env'), expected)) + recover = self.worker('recover', '') + _, err = recover.communicate(timeout=20) + self.assertNotEqual(recover.returncode, 0) + self.assertIn('No database rollback', err) + self.assertTrue(update.same(update.file_info(self.root / '.env'), expected)) + self.root = parent + + @unittest.skipIf(os.name == 'nt', 'SIGKILL semantics are checked on POSIX') + def test_broker_directory_interruption_is_recorded_and_never_accepted_as_complete(self): + process = self.worker('kill-broker', 'activation-file-written:config/native/broker/plugin-token') + _, err = process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGKILL, err) + data = self.tx().load() + self.assertEqual(data['phase'], 'activation_started') + entry = data['activation_files']['config/native/broker/plugin-token'] + self.assertIsNone(entry['old']) + self.assertFalse(entry['applied']) + self.assertIn('config/native/broker', data['activation_dirs']) + with self.assertRaisesRegex(update.UpdateError, 'No database rollback'): + self.tx().run(BASE, recovery_only=True) + + def test_corrupt_journal_is_rejected_without_target_changes(self): + tx = self.tx() + old = self.originals(tx) + data = tx.prepare(BASE, '') + corruptions = [ + ('created_dirs', ['../outside']), ('watched', []), ('intent', '../outside'), + ('operation', '../outside'), ('phase', 'unrecognized'), + ('activation_files', {'.env': {'old': data['watched']['.env'], + 'new': data['watched']['.env'], 'applied': True}})] + for key, value in corruptions: + bad = copy.deepcopy(data); bad[key] = value + tx.journal.write_text(json.dumps(bad)) + with self.subTest(key=key), self.assertRaisesRegex(update.UpdateError, 'journal is invalid'): + tx.run(BASE, recovery_only=True) + self.assertOriginals(old) + + def test_missing_backup_fails_closed(self): + tx = self.tx() + old = self.originals(tx) + data = tx.prepare(BASE, '') + (tx.state / data['operation'] / 'backup/docker-compose.yml').unlink() + with self.assertRaisesRegex(update.UpdateError, 'backup is missing'): + tx.run(BASE, recovery_only=True) + self.assertOriginals(old) + + @unittest.skipIf(os.name == 'nt', 'creating symlinks needs Windows developer privileges') + def test_symlink_target_and_state_are_not_followed(self): + outside = Path(self.temp.name) / 'outside' + outside.write_text('outside') + (self.root / 'docker-compose.yml').symlink_to(outside) + with self.assertRaisesRegex(update.UpdateError, 'regular file'): + self.tx().run(BASE) + self.assertEqual(outside.read_text(), 'outside') + (self.root / 'docker-compose.yml').unlink() + state = self.root / '.thingspanel-update' + # The attempted operation made a private journal directory only. + import shutil + shutil.rmtree(state) + state.symlink_to(Path(self.temp.name)) + with self.assertRaisesRegex(update.UpdateError, 'real directory'): + self.tx() + + def test_windows_payload_includes_native_files_and_powershell_management(self): + tx = self.tx(platform='windows') + self.originals(tx) + tx.run(BASE) + paths = {p for p, _ in tx.artifacts} + self.assertIn('upgrade.ps1', paths) + self.assertIn('uninstall.ps1', paths) + self.assertIn('config/native/prepare.py', paths) + self.assertNotIn('upgrade.sh', paths) + + def worker(self, mode, event): + return subprocess.Popen([sys.executable, str(REPO / 'tests/transaction_worker.py'), + str(self.root), mode, event], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1')) + + @unittest.skipIf(os.name == 'nt', 'SIGKILL semantics are checked on POSIX') + def test_kill9_during_replacements_is_recovered_by_new_process(self): + old = self.originals() + for event in ('prepared', 'before-replace:docker-compose.yml', + 'after-replace:docker-compose.yml', 'after-replace:config/native/prepare.py', + 'after-replace:config/native/update.py', 'config_committed'): + with self.subTest(event=event): + process = self.worker('kill', event) + out, err = process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGKILL, err) + recover = self.worker('recover', '') + out, err = recover.communicate(timeout=20) + self.assertEqual(recover.returncode, 0, err) + self.assertOriginals(old) + self.assertEqual(self.tx().load()['phase'], 'recovered') + + @unittest.skipIf(os.name == 'nt', 'SIGKILL semantics are checked on POSIX') + def test_recovery_itself_can_be_killed_and_retried(self): + old = self.originals() + process = self.worker('kill', 'after-replace:config/native/prepare.py') + process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGKILL) + process = self.worker('kill-recover', 'recovered-file:config/native/prepare.py') + process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGKILL) + self.tx().run(BASE, recovery_only=True) + self.assertOriginals(old) + + @unittest.skipIf(os.name == 'nt', 'POSIX signal delivery is checked on Linux and macOS') + def test_sigterm_during_update_is_recovered_by_new_process(self): + old = self.originals() + for event in ('prepared', 'after-replace:config/native/prepare.py', 'config_committed'): + with self.subTest(event=event): + process = self.worker('terminate', event) + _, err = process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGTERM, err) + recover = self.worker('recover', '') + _, err = recover.communicate(timeout=20) + self.assertEqual(recover.returncode, 0, err) + self.assertOriginals(old) + + @unittest.skipIf(os.name == 'nt', 'SIGKILL semantics are checked on POSIX') + def test_kill9_restores_original_absence_and_recovery_is_idempotent(self): + process = self.worker('kill', 'after-replace:config/native/update.py') + _, err = process.communicate(timeout=20) + self.assertEqual(process.returncode, -signal.SIGKILL, err) + for _ in range(2): + recover = self.worker('recover', '') + _, err = recover.communicate(timeout=20) + self.assertEqual(recover.returncode, 0, err) + for relative, _ in self.tx().artifacts: + self.assertFalse((self.root / relative).exists(), relative) + self.assertFalse((self.root / 'config').exists()) + self.assertEqual(self.tx().load()['phase'], 'recovered') + + def test_completed_installation_can_be_relocated_but_unresolved_cannot(self): + tx = self.tx() + self.originals(tx) + tx.run(BASE) + journal = self.root / '.thingspanel-update' / 'journal.json' + data = json.loads(journal.read_text(encoding='utf-8')) + unresolved = copy.deepcopy(data) + unresolved['phase'] = 'activation_started' + moved = Path(self.temp.name) / 'moved' + self.root.rename(moved) + relocated = update.Transaction(moved, downloader=payload_download).load() + self.assertEqual(relocated['phase'], 'complete') + self.assertEqual(relocated['root'], str(moved)) + (moved / '.thingspanel-update' / 'journal.json').write_text(json.dumps(unresolved, sort_keys=True) + '\n', encoding='utf-8') + with self.assertRaises(update.UpdateError): + update.Transaction(moved, downloader=payload_download).load() + + def test_completed_journal_is_not_rolled_back_on_restart(self): + tx = self.tx() + self.originals(tx) + tx.run(BASE) + complete = {p: update.file_info(self.root / p) for p, _ in tx.artifacts} + for _ in range(2): + recover = self.worker('recover', '') + _, err = recover.communicate(timeout=20) + self.assertEqual(recover.returncode, 0, err) + self.assertOriginals(complete) + self.assertEqual(self.tx().load()['phase'], 'complete') + + def test_second_process_cannot_enter_during_config_replacement(self): + old = self.originals() + for event in ('prepared', 'after-replace:config/native/prepare.py', 'config_committed'): + with self.subTest(event=event): + ready = self.root / '.worker-ready' + if ready.exists(): + ready.unlink() + process = self.worker('hold', event) + try: + deadline = time.monotonic() + 10 + while not ready.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + self.assertTrue(ready.exists()) + competitor = self.worker('recover', '') + _, err = competitor.communicate(timeout=20) + self.assertNotEqual(competitor.returncode, 0) + self.assertIn('Another installer operation is active', err) + finally: + process.kill() + process.communicate(timeout=20) + recover = self.worker('recover', '') + _, err = recover.communicate(timeout=20) + self.assertEqual(recover.returncode, 0, err) + self.assertOriginals(old) + + def test_process_lock_covers_activation_and_is_released_by_termination(self): + self.originals() + process = self.worker('hold', 'activation_started') + try: + # A bounded wait on a synthetic readiness file; never wait forever + # if the child fails before acquiring its actual transaction lock. + deadline = time.monotonic() + 10 + while not (self.root / '.worker-ready').exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + self.assertTrue((self.root / '.worker-ready').exists()) + with self.assertRaisesRegex(update.UpdateError, 'Another installer'): + self.tx().run(BASE) + finally: + process.kill() + process.communicate(timeout=20) + with self.assertRaisesRegex(update.UpdateError, 'No database rollback'): + self.tx().run(BASE, recovery_only=True) + + +class ValidatorTests(unittest.TestCase): + def test_packagers_do_not_copy_configuration_before_transaction(self): + mac = (REPO / 'packaging/macos/build.sh').read_text() + win = (REPO / 'packaging/windows/ThingsPanel-Setup.iss').read_text() + mac_sources = re.findall(r'^cp "\$ROOT_DIR/([^"]+)"', mac, flags=re.MULTILINE) + win_sources = re.findall(r'^Source: "\.\.\\\.\.\\([^"]+)"', win, flags=re.MULTILINE) + self.assertEqual(set(mac_sources), {'install.sh', 'install.bash'}) + self.assertEqual(set(win_sources), {'install.ps1', 'install.core.ps1'}) + postinstall = (REPO / 'packaging/macos/scripts/postinstall').read_text() + self.assertNotIn('"$INSTALL_DIR"/*.sh', postinstall) + self.assertIn('"$INSTALL_DIR/install.bash"', postinstall) + + def test_entrypoint_helper_pins_match_reviewed_bytes(self): + digest = hashlib.sha256((REPO / 'config/native/update.py').read_bytes()).hexdigest() + for name in ('install.bash', 'upgrade.sh', 'install.core.ps1', 'upgrade.ps1'): + pins = re.findall(r'UPDATE_ENGINE_SHA256\s*=\s*"([0-9a-f]{64})"', (REPO / name).read_text(encoding='utf-8-sig')) + self.assertEqual(pins, [digest], name) + + def test_compose_uses_original_project_and_env_for_staged_file(self): + with tempfile.TemporaryDirectory() as name: + root = Path(name) + (root / '.env').write_text('synthetic=only') + stage = root / '.thingspanel-update/stage/docker-compose.yml' + with mock.patch.object(update, 'run_command', return_value=json.dumps(CONFIG).encode()) as command: + update.compose_config(root, stage) + args, cwd = command.call_args.args + self.assertEqual(cwd, root) + self.assertEqual(args[args.index('--project-directory') + 1], str(root)) + self.assertEqual(args[args.index('--env-file') + 1], str(root / '.env')) + self.assertEqual(args[args.index('-f') + 1], str(stage)) + + def test_pg_unknown_and_mysql_guards_remain_closed(self): + update.validate_config(copy.deepcopy(CONFIG)) + for change in ('mysql', 'missing', 'selector', 'unknown', 'duplicate'): + config = copy.deepcopy(CONFIG) + env = config['services']['backend']['environment'] + if change == 'mysql': + config['services']['thingsvis-server']['environment']['DATABASE_URL'] = 'mysql://fixture/db' + elif change == 'missing': + del env['GOTP_DB_PSQL_HOST'] + elif change == 'selector': + env['DB_DRIVER'] = 'mysql' + elif change == 'unknown': + env['GOTP_DB_PSQL_HOST'] = '${UNCONFIRMED_HOST}' + else: + config['services']['backend']['environment'] = ['GOTP_DB_PSQL_HOST=a', 'GOTP_DB_PSQL_HOST=b'] + with self.subTest(change=change), self.assertRaises(update.UpdateError): + update.validate_config(config) + + def test_a1_relational_pg_profile_is_required_when_declared(self): + config = copy.deepcopy(CONFIG) + env = config['services']['backend']['environment'] + env.update({ + 'GOTP_RELATIONAL_DRIVER': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PORT': '5432', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_DATABASE': 'ThingsPanel', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_USERNAME': 'postgres', + 'GOTP_RELATIONAL_POSTGRES_PLATFORM_PASSWORD': 'synthetic-fixture', + }) + update.validate_config(config) + del env['GOTP_RELATIONAL_POSTGRES_PLATFORM_HOST'] + with self.assertRaises(update.UpdateError): + update.validate_config(config) + + def test_legacy_only_compose_remains_upgrade_compatible(self): + config = copy.deepcopy(CONFIG) + env = config['services']['backend']['environment'] + for key in tuple(env): + if key.startswith('GOTP_RELATIONAL_'): + del env[key] + update.validate_config(config) + + def test_staged_legacy_only_compose_remains_supported(self): + config = copy.deepcopy(CONFIG) + env = config['services']['backend']['environment'] + for key in tuple(env): + if key.startswith('GOTP_RELATIONAL_'): + del env[key] + with tempfile.TemporaryDirectory() as directory: + stage = Path(directory) + transaction = update.Transaction(stage / 'install') + for relative, _ in transaction.artifacts: + target = stage / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes((REPO / relative).read_bytes()) + with mock.patch.object(update, 'render_with_fallback', return_value=config): + transaction.validate(stage, '') + + def test_external_compose_path_is_not_inherited_by_prepare(self): + with mock.patch.dict(os.environ, {'COMPOSE_FILE': '/foreign/compose.yml', 'COMPOSE_ENV_FILES': '/foreign/.env', 'COMPOSE_DISABLE_ENV_FILE': '1'}): + env = update.command_environment(Path('/original/install')) + self.assertEqual(env['COMPOSE_FILE'], str(Path('/original/install/docker-compose.yml'))) + self.assertNotIn('COMPOSE_ENV_FILES', env) + self.assertNotIn('COMPOSE_DISABLE_ENV_FILE', env) + + def test_subprocess_errors_do_not_expose_args_or_stderr(self): + result = subprocess.CompletedProcess([], 9, b'', b'password=synthetic-secret') + with mock.patch.object(update.subprocess, 'run', return_value=result): + with self.assertRaises(update.UpdateError) as raised: + update.run_command(['command', 'password=synthetic-secret'], REPO) + self.assertEqual(str(raised.exception), 'Installer command failed (exit 9)') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/transaction_worker.py b/tests/transaction_worker.py new file mode 100644 index 0000000..6029299 --- /dev/null +++ b/tests/transaction_worker.py @@ -0,0 +1,30 @@ +"""Child process helper for isolated transaction crash/lock tests only.""" +import os +from pathlib import Path +import signal +import sys +from unittest import mock +from test_update_transaction import BASE, CONFIG, payload_download, update + +root, mode, target_event = sys.argv[1:] + + +def checkpoint(event): + if event != target_event: + return + if mode in ('kill', 'kill-recover', 'kill-env', 'kill-broker'): + os.kill(os.getpid(), signal.SIGKILL) + elif mode == 'terminate': + os.kill(os.getpid(), signal.SIGTERM) + elif mode == 'hold': + (Path(root) / '.worker-ready').write_text('ready') + sys.stdin.readline() + + +with mock.patch.object(update, 'render_with_fallback', return_value=CONFIG): + transaction = update.Transaction(Path(root), downloader=payload_download, checkpoint=checkpoint) + activation = (lambda _: transaction.write_activation_environment(b'TP_AUTH=synthetic-new-identity\n')) if mode == 'kill-env' else (lambda _: None) + if mode == 'kill-broker': + activation = lambda _: transaction.write_activation_file('config/native/broker/plugin-token', b'synthetic-broker-identity-not-a-real-secret', 0o440) + transaction.run(BASE, activate=activation, + recovery_only=mode in ('recover', 'kill-recover')) diff --git a/tests/verify_broker_directory_mount.py b/tests/verify_broker_directory_mount.py new file mode 100644 index 0000000..372e71c --- /dev/null +++ b/tests/verify_broker_directory_mount.py @@ -0,0 +1,59 @@ +"""Opt-in Docker filesystem check; no daemon calls during normal unit discovery. + +Requires an explicitly supplied, already-local image with /bin/sh and cat. +Creates one private directory and one uniquely named network-isolated container. +This proves bind-mount visibility, not a real Broker reload or platform chain. +""" +import argparse +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import uuid + +REPO = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location('tp_update_mount_check', REPO / 'config/native/update.py') +update = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(update) + + +def command(*arguments): + return subprocess.check_output(arguments, text=True, stderr=subprocess.PIPE, timeout=45).strip() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--image', required=True, help='Already-local reviewed image; no pull is performed') + args = parser.parse_args() + image_id = command('docker', 'image', 'inspect', '--format', '{{.Id}}', args.image) + name = 'tp-takeover-b-installer-mount-' + uuid.uuid4().hex[:12] + with tempfile.TemporaryDirectory(prefix='tp-takeover-b-installer-mount-') as temporary: + root = Path(temporary) + broker = root / 'broker' + broker.mkdir() + target = broker / 'services.json' + update.durable_bytes(target, b'{"generation":1}\n', 0o644) + try: + command('docker', 'run', '--pull=never', '--detach', '--name', name, + '--network', 'none', '--read-only', '--entrypoint', '/bin/sh', + '--mount', 'type=bind,src=' + str(broker) + ',dst=/run/broker,readonly', + '--mount', 'type=bind,src=' + str(target) + ',dst=/run/control.json,readonly', + args.image, '-c', 'while :; do sleep 10; done') + before = json.loads(command('docker', 'exec', name, 'cat', '/run/broker/services.json')) + update.durable_bytes(target, b'{"generation":2}\n', 0o644) + after = json.loads(command('docker', 'exec', name, 'cat', '/run/broker/services.json')) + control = json.loads(command('docker', 'exec', name, 'cat', '/run/control.json')) + if before != {'generation': 1} or after != {'generation': 2}: + raise RuntimeError('Directory-mounted configuration did not observe the atomic replacement') + print(json.dumps({'passed': True, 'image': args.image, 'localImageID': image_id, + 'directoryBefore': before, 'directoryAfter': after, + 'singleFileControlAfter': control, + 'scope': 'isolated Docker bind-mount visibility only'}, sort_keys=True)) + finally: + subprocess.run(['docker', 'rm', '--force', name], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, timeout=45, check=False) + + +if __name__ == '__main__': + main() diff --git a/tools/agent_host.py b/tools/agent_host.py new file mode 100644 index 0000000..dcf0be7 --- /dev/null +++ b/tools/agent_host.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Start (or stop) the host Agent in catalog mode, the mode the platform's one-click install talks to. + + agent_host.py up --stack-dir DIR --agent-dir DIR --agent-bin tp-agent --catalog plugin-catalog.json --trust-root root.pem + agent_host.py down --stack-dir DIR + +Layout under --agent-dir (created 0700): + run/ agent.sock + token the ONLY part the platform backend container mounts (TP_AGENT_SOCKET/TP_AGENT_TOKEN_FILE) + state/ state.json, secrets.json Agent-private: journal and secret store (site secrets, identity tokens) + +The Agent verifies the signed catalog itself and builds plugin containers from it; nothing here handles a secret. +Installing plugins is done in the platform UI (or `plugin_install.py`, which calls the same backend API). +""" +import argparse +import os +from pathlib import Path +import secrets +import subprocess +import sys +import time + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import scope_sync # noqa: E402 + +DEFAULT_IMAGE = 'registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-go:v1.3.0' + + +def sh(args, check=True): + result = subprocess.run(args, capture_output=True, text=True) + if check and result.returncode: + raise RuntimeError('command failed (%d): %s\n%s' % (result.returncode, ' '.join(args[:4]), (result.stderr or result.stdout)[-300:])) + return result + + +def project_of(stack_dir): + return os.environ.get('COMPOSE_PROJECT_NAME') or Path(stack_dir).resolve().name.lower() + + +def container_name(stack_dir): + return 'tp-agent-' + project_of(stack_dir) + + +def private_dir(path, mode=0o700): + path.mkdir(parents=True, exist_ok=True) + os.chmod(path, mode) + + +def ensure_scope_watcher(stack, agent_dir, *, deferred=False, sleep=time.sleep): + """Start the scope watcher, or let an installer start it after releasing its lock.""" + if deferred: + print('Broker scope watcher startup deferred until installer activation releases its lock.') + return 'deferred' + status = None + for _ in range(60): + status = scope_sync.ensure(stack, agent_dir) + if status != 'busy': + break + sleep(5) + print('Broker scope watcher: %s (log %s)' % (status, Path(agent_dir) / 'scope-sync.log')) + return status + + +def up(args): + agent_dir, stack = Path(args.agent_dir).resolve(), Path(args.stack_dir).resolve() + project = project_of(stack) + name = container_name(stack) + private_dir(agent_dir) + run, state = agent_dir / 'run', agent_dir / 'state' + private_dir(run) + private_dir(state) + token = run / 'token' + if not token.exists(): + token.write_text(secrets.token_hex(24)) + os.chmod(token, 0o600) + catalog, trust_root = Path(args.catalog).resolve(), Path(args.trust_root).resolve() + if not (catalog.is_file() and Path(str(catalog) + '.sig').is_file() and trust_root.is_file()): + raise RuntimeError('catalog, catalog signature and trust root must exist') + network = args.network or '%s_thingspanel_network' % project + mounts = ['-v', '%s:/tp-agent:ro' % Path(args.agent_bin).resolve(), '-v', '%s:/run/agent-ctl' % run, '-v', '%s:/run/agent/state' % state, + '-v', '%s:/run/agent/catalog:ro' % catalog.parent, '-v', '%s:/run/agent/trust-root.pem:ro' % trust_root, + '-v', '%s:/run/agent/stack.env:ro' % (stack / '.env')] + if not (state / 'state.json').exists(): + sh(['docker', 'run', '--rm', '--entrypoint', '/tp-agent', '-u', '0', '-v', '%s:/tp-agent:ro' % Path(args.agent_bin).resolve(), + '-v', '%s:/run/agent/state' % state, args.agent_image, '-state', '/run/agent/state/state.json', '-init', 'host-' + name]) + sh(['docker', 'rm', '-f', name], check=False) + sh(['docker', 'run', '-d', '--name', name, '--restart', 'unless-stopped', '--entrypoint', '/tp-agent', '-u', '0'] + mounts + + ['-v', '/var/run/docker.sock:/var/run/docker.sock', args.agent_image, '-state', '/run/agent/state/state.json', + '-socket', '/run/agent-ctl/agent.sock', '-token-file', '/run/agent-ctl/token', + '-catalog', '/run/agent/catalog/' + catalog.name, '-trust-root', '/run/agent/trust-root.pem', + '-stack-env', '/run/agent/stack.env', '-network', network, '-docker-socket', '/var/run/docker.sock', '-sweep-interval', '5s']) + for _ in range(20): + if (run / 'agent.sock').exists(): + break + time.sleep(0.5) + else: + raise RuntimeError('the Agent did not create its socket; see: docker logs ' + name) + print('Agent %s is up; the platform backend mounts %s as /run/tp-agent' % (name, run)) + # Installer activation owns the update lock while starting this process; + # direct/manual starts retain the existing wait behavior. + ensure_scope_watcher(stack, agent_dir, deferred=args.defer_scope_watcher) + + +def down(args): + sh(['docker', 'rm', '-f', container_name(args.stack_dir)], check=False) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('command', choices=['up', 'down']) + parser.add_argument('--stack-dir', required=True) + parser.add_argument('--agent-dir') + parser.add_argument('--agent-bin') + parser.add_argument('--catalog') + parser.add_argument('--trust-root') + parser.add_argument('--agent-image', default=DEFAULT_IMAGE) + parser.add_argument('--network') + parser.add_argument('--defer-scope-watcher', action='store_true', + help='installer owns the update lock and will start the watcher after activation') + args = parser.parse_args() + if args.command == 'up' and not all([args.agent_dir, args.agent_bin, args.catalog, args.trust_root]): + parser.error('up needs --agent-dir, --agent-bin, --catalog and --trust-root') + try: + {'up': up, 'down': down}[args.command](args) + except Exception as error: # noqa: BLE001 - CLI boundary + print('error: %s' % error, file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/plugin_bundle.py b/tools/plugin_bundle.py new file mode 100644 index 0000000..97f3695 --- /dev/null +++ b/tools/plugin_bundle.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Fetch and stage one signed, per-architecture Home Assistant plugin bundle. + +The returned directory is private and isolated. This module never extracts an +archive, executes the Agent, loads a Docker image, or changes an active bundle. +""" +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import stat +import tempfile +import time +from urllib.parse import urlsplit +from urllib.request import Request, urlopen + +import plugin_catalog + + +DEFAULT_PAGES_BASE_URL = 'https://install.thingspanel.io' +DEFAULT_RELEASE_BASE_URL = 'https://github.com/ThingsPanel/thingspanel-installer/releases/download' +SUPPORTED_PLATFORMS = frozenset(('linux/amd64', 'linux/arm64')) +MAX_CATALOG_BYTES = 1024 * 1024 +MAX_SIGNATURE_BYTES = 16 * 1024 +MAX_AGENT_BYTES = 64 * 1024 * 1024 +MAX_IMAGE_ARCHIVE_BYTES = 12 * 1024 * 1024 * 1024 +CHUNK_SIZE = 1024 * 1024 +SHA256_RE = re.compile(r'^[0-9a-f]{64}$') + + +class PluginBundleError(RuntimeError): + """The optional plugin bundle is absent, malformed, or untrusted.""" + + +@dataclass(frozen=True) +class StagedPluginBundle: + """Validated files in a new private directory; caller owns cleanup/promotion.""" + + stage_dir: Path + catalog_path: Path + signature_path: Path + agent_path: Path + image_archive_path: Path + catalog: dict + + +def _validate_https_base(value, *, release=False): + parsed = urlsplit(value) + if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise PluginBundleError('bundle base URL must be an absolute HTTPS URL without credentials, query, or fragment') + if release: + normalized = value.rstrip('/') + if normalized != DEFAULT_RELEASE_BASE_URL: + raise PluginBundleError('release base URL must be the configured ThingsPanel GitHub Releases base') + elif value.rstrip('/') != DEFAULT_PAGES_BASE_URL: + raise PluginBundleError('catalog base URL must be the configured ThingsPanel Pages site') + return value.rstrip('/') + + +def _safe_stage_parent(path): + path = Path(path) + try: + info = path.lstat() + except OSError as error: + raise PluginBundleError('plugin stage parent is unavailable') from error + if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode): + raise PluginBundleError('plugin stage parent must be a real directory') + return path.resolve() + + +def _download_stream(url, destination, max_bytes, *, timeout=90): + """Stream a URL to a new mode-0600 file, enforcing the byte limit while reading.""" + destination = Path(destination) + request = Request(url, headers={'User-Agent': 'ThingsPanel-Plugin-Bundle/1'}) + try: + with urlopen(request, timeout=timeout) as response: + final = urlsplit(response.geturl()) + source = urlsplit(url) + allowed_hosts = {source.hostname} + if source.hostname == 'github.com': + allowed_hosts.update(('release-assets.githubusercontent.com', 'objects.githubusercontent.com')) + if final.scheme != 'https' or final.hostname not in allowed_hosts: + raise PluginBundleError('bundle asset redirected outside its trusted HTTPS host') + length = response.headers.get('Content-Length') + if length is not None: + try: + announced = int(length) + except ValueError: + raise PluginBundleError('bundle asset has an invalid Content-Length') from None + if announced < 0 or announced > max_bytes: + raise PluginBundleError('bundle asset exceeds its configured size limit') + fd = os.open(str(destination), os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600) + count = 0 + try: + with os.fdopen(fd, 'wb') as output: + while True: + block = response.read(CHUNK_SIZE) + if not block: + break + count += len(block) + if count > max_bytes: + raise PluginBundleError('bundle asset exceeds its configured size limit') + output.write(block) + output.flush() + os.fsync(output.fileno()) + except BaseException: + destination.unlink(missing_ok=True) + raise + if count == 0: + destination.unlink(missing_ok=True) + raise PluginBundleError('bundle asset is empty') + except PluginBundleError: + raise + except Exception as error: # noqa: BLE001 - URL/client errors are an optional bundle failure. + destination.unlink(missing_ok=True) + raise PluginBundleError('bundle asset download failed') from error + + +def _download(fetcher, url, destination, max_bytes): + """Call a testable downloader and enforce a postcondition on its output.""" + fetcher(url, destination, max_bytes) + path = Path(destination) + try: + info = path.lstat() + except OSError: + raise PluginBundleError('bundle downloader did not create an asset') from None + if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode): + raise PluginBundleError('bundle downloader returned a non-regular asset') + if info.st_size <= 0: + raise PluginBundleError('bundle asset is empty') + if info.st_size > max_bytes: + raise PluginBundleError('bundle asset exceeds its configured size limit') + os.chmod(path, 0o600) + + +def _sha256(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(CHUNK_SIZE), b''): + digest.update(block) + return digest.hexdigest() + + +def _valid_digest(value): + return isinstance(value, str) and SHA256_RE.fullmatch(value) is not None + + +def _validate_catalog(catalog, target_platform): + if catalog.get('target_platform') != target_platform: + raise PluginBundleError('plugin catalog target platform does not match Docker') + try: + bundle = plugin_catalog.validate_bundle_metadata( + catalog.get('target_platform'), catalog.get('release_tag'), catalog.get('agent_sha256')) + except (TypeError, ValueError) as error: + raise PluginBundleError('plugin catalog bundle metadata is invalid') from error + if bundle is None or not _valid_digest(catalog.get('agent_sha256')): + raise PluginBundleError('plugin catalog Agent metadata is incomplete or invalid') + entries = catalog.get('plugins') + if not isinstance(entries, list) or not entries: + raise PluginBundleError('plugin catalog has no plugin entries') + ids = [entry.get('id') for entry in entries if isinstance(entry, dict)] + if len(ids) != len(entries) or len(ids) != len(set(ids)): + raise PluginBundleError('plugin catalog plugin IDs are malformed or duplicated') + ha = [entry for entry in entries if entry.get('id') == 'homeassistant'] + if len(ha) != 1: + raise PluginBundleError('plugin catalog must contain exactly one Home Assistant entry') + entry = ha[0] + if entry.get('image_platform') != target_platform: + raise PluginBundleError('Home Assistant image platform does not match Docker') + if not _valid_digest(entry.get('image_archive_sha256')): + raise PluginBundleError('Home Assistant image archive digest is invalid') + image_id = entry.get('image_id') + if not isinstance(image_id, str) or re.fullmatch(r'sha256:[0-9a-f]{64}', image_id) is None: + raise PluginBundleError('Home Assistant image ID is invalid') + return entry + + +def stage_plugin_bundle(target_platform, *, trust_root, stage_parent, + pages_base_url=DEFAULT_PAGES_BASE_URL, + release_base_url=DEFAULT_RELEASE_BASE_URL, + downloader=None, catalog_loader=None, + max_agent_bytes=MAX_AGENT_BYTES, + max_image_archive_bytes=MAX_IMAGE_ARCHIVE_BYTES): + """Verify and download a per-platform bundle into a new private stage. + + ``downloader(url, destination, max_bytes)`` and ``catalog_loader(path, + trust_root)`` are injectable for deterministic tests. The default loader is + the existing ``plugin_catalog.load_verified`` implementation. + """ + if target_platform not in SUPPORTED_PLATFORMS: + raise PluginBundleError('unsupported Docker target platform') + for limit in (max_agent_bytes, max_image_archive_bytes): + if type(limit) is not int or limit <= 0: + raise PluginBundleError('bundle size limits must be positive integers') + trust_root = Path(trust_root) + if not trust_root.is_absolute() or not trust_root.is_file(): + raise PluginBundleError('plugin trust root must be an available absolute package-external file') + pages_base_url = _validate_https_base(pages_base_url) + release_base_url = _validate_https_base(release_base_url, release=True) + parent = _safe_stage_parent(stage_parent) + trust_root = trust_root.resolve() + try: + trust_root.relative_to(parent) + except ValueError: + pass + else: + raise PluginBundleError('plugin trust root must be outside the plugin stage parent') + fetcher = downloader or _download_stream + loader = catalog_loader or plugin_catalog.load_verified + arch = target_platform.split('/', 1)[1] + stage = Path(tempfile.mkdtemp(prefix='tp-plugin-bundle-', dir=str(parent))) + os.chmod(stage, 0o700) + try: + catalog_path = stage / ('catalog-linux-%s.json' % arch) + signature_path = Path(str(catalog_path) + '.sig') + _download(fetcher, pages_base_url + '/plugins/catalog-linux-%s.json' % arch, + catalog_path, MAX_CATALOG_BYTES) + _download(fetcher, pages_base_url + '/plugins/catalog-linux-%s.json.sig' % arch, + signature_path, MAX_SIGNATURE_BYTES) + try: + catalog = loader(catalog_path, trust_root) + except Exception as error: # noqa: BLE001 - verifier errors must remain fail-closed. + raise PluginBundleError('plugin catalog signature or schema is invalid') from error + image_entry = _validate_catalog(catalog, target_platform) + tag = catalog['release_tag'] + agent_url = '%s/%s/tp-agent-linux-%s' % (release_base_url, tag, arch) + image_url = '%s/%s/ha-image-linux-%s.tar' % (release_base_url, tag, arch) + agent_path = stage / ('tp-agent-linux-%s' % arch) + image_path = stage / ('ha-image-linux-%s.tar' % arch) + _download(fetcher, agent_url, agent_path, max_agent_bytes) + if _sha256(agent_path) != catalog['agent_sha256']: + raise PluginBundleError('Agent binary digest does not match the signed catalog') + _download(fetcher, image_url, image_path, max_image_archive_bytes) + if _sha256(image_path) != image_entry['image_archive_sha256']: + raise PluginBundleError('Home Assistant image archive digest does not match the signed catalog') + return StagedPluginBundle(stage, catalog_path, signature_path, agent_path, image_path, catalog) + except BaseException: + shutil.rmtree(stage, ignore_errors=True) + raise + + +def arrange_staged_bundle(staged): + """Arrange a newly verified stage for the existing Agent host helpers.""" + root = Path(staged.stage_dir) + if root.is_symlink() or not root.is_dir(): + raise PluginBundleError('plugin stage is not a real directory') + for name in ('bin', 'plugins'): + (root / name).mkdir(mode=0o700) + for source, relative in ( + (staged.catalog_path, 'plugins/plugin-catalog.json'), + (staged.signature_path, 'plugins/plugin-catalog.json.sig'), + (staged.agent_path, 'bin/tp-agent'), + (staged.image_archive_path, 'plugins/homeassistant-image.tar'), + ): + source = Path(source) + if source.parent != root or source.is_symlink() or not source.is_file(): + raise PluginBundleError('plugin stage contains an invalid asset') + os.replace(source, root / relative) + os.chmod(root / 'bin/tp-agent', 0o700) + return root + + +def verify_active_bundle(root, trust_root, target_platform, *, require_unexpired=False): + """Recheck an already activated bundle, including an expired catalog's signature. + + This is only for restoring an existing Agent. The Agent itself continues to + reject expired catalogs for new installations and preparations. + """ + root = Path(root) + for directory in (root, root / 'bin', root / 'plugins'): + if directory.is_symlink() or not directory.is_dir(): + raise PluginBundleError('active plugin bundle is not a real directory') + catalog_path = root / 'plugins/plugin-catalog.json' + signature_path = root / 'plugins/plugin-catalog.json.sig' + agent_path = root / 'bin/tp-agent' + image_path = root / 'plugins/homeassistant-image.tar' + for path, maximum in ((catalog_path, MAX_CATALOG_BYTES), (signature_path, MAX_SIGNATURE_BYTES), + (agent_path, MAX_AGENT_BYTES), (image_path, MAX_IMAGE_ARCHIVE_BYTES)): + try: + info = path.lstat() + except OSError: + raise PluginBundleError('active plugin bundle is incomplete') from None + if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_size <= 0 or info.st_size > maximum: + raise PluginBundleError('active plugin bundle contains an invalid asset') + try: + raw = catalog_path.read_bytes() + verifier = plugin_catalog._verifier() + verifier.verify_signature(raw, signature_path.read_bytes(), verifier.load_trust_root(trust_root)) + catalog = json.loads(raw) + if catalog.get('schema') != plugin_catalog.SCHEMA or type(catalog.get('expires_at')) is not int: + raise ValueError('invalid catalog') + for entry in catalog['plugins']: + plugin_catalog.check_entry(entry) + plugin_catalog.validate_catalog_bundle(catalog) + image_entry = _validate_catalog(catalog, target_platform) + except Exception as error: # noqa: BLE001 - all verifier errors fail closed. + raise PluginBundleError('active plugin catalog signature or schema is invalid') from error + if require_unexpired and int(time.time()) >= catalog['expires_at']: + raise PluginBundleError('pending catalog expired before activation') + if _sha256(agent_path) != catalog['agent_sha256'] or _sha256(image_path) != image_entry['image_archive_sha256']: + raise PluginBundleError('active plugin bundle digest mismatch') + return catalog + diff --git a/tools/plugin_catalog.py b/tools/plugin_catalog.py new file mode 100644 index 0000000..5e3b277 --- /dev/null +++ b/tools/plugin_catalog.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Publish and verify a signed ThingsPanel plugin catalog. + +A catalog is plain JSON listing installable plugins. It is signed (DER ECDSA over SHA-256 of the exact +bytes, same format as the release manifest) so an installer can refuse a catalog that was altered or +published by someone else. The public key is the trust root the installer is given out of band. + + plugin_catalog.py publish --key release-key.pem --out DIR --version 1 [--plugin-file p.json ...] + plugin_catalog.py verify --trust-root trust-root.pem --catalog DIR/plugin-catalog.json + +A plugin entry (see plugin_install.py) pins one local/registry image by its immutable image ID. +""" +import argparse +import importlib.util +import json +import re +from pathlib import Path +import subprocess +import sys +import time + +SCHEMA = 'thingspanel.plugin-catalog.v1' +REPO = Path(__file__).resolve().parents[1] +SUPPORTED_PLUGIN_PLATFORMS = frozenset(('linux/amd64', 'linux/arm64')) +RELEASE_TAG_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$') +SHA256_RE = re.compile(r'^[0-9a-f]{64}$') + + +def validate_bundle_metadata(target_platform, release_tag, agent_sha256): + """Validate optional per-architecture installer bundle metadata.""" + supplied = (target_platform is not None, release_tag is not None, agent_sha256 is not None) + if any(supplied) and not all(supplied): + raise ValueError('target_platform, release_tag and agent_sha256 must be supplied together') + if not any(supplied): + return None + if target_platform not in SUPPORTED_PLUGIN_PLATFORMS: + raise ValueError('target_platform must be linux/amd64 or linux/arm64') + if (not isinstance(release_tag, str) or RELEASE_TAG_RE.fullmatch(release_tag) is None or + '..' in release_tag or release_tag.endswith('.') or release_tag.endswith('.lock') or '@{' in release_tag): + raise ValueError('release_tag is not a safe GitHub release tag') + if not isinstance(agent_sha256, str) or SHA256_RE.fullmatch(agent_sha256) is None: + raise ValueError('agent_sha256 must be a lowercase SHA-256 digest') + return {'target_platform': target_platform, 'release_tag': release_tag, 'agent_sha256': agent_sha256} + + +def validate_catalog_bundle(catalog): + """Validate the optional bundle envelope and its HA target alignment.""" + bundle = validate_bundle_metadata(catalog.get('target_platform'), catalog.get('release_tag'), + catalog.get('agent_sha256')) + if bundle is None: + return + plugins = catalog.get('plugins') + if not isinstance(plugins, list): + raise ValueError('bundle catalog plugins must be a list') + homeassistant = [entry for entry in plugins if isinstance(entry, dict) and entry.get('id') == 'homeassistant'] + if len(homeassistant) != 1 or homeassistant[0].get('image_platform') != bundle['target_platform']: + raise ValueError('bundle catalog must contain one Home Assistant entry matching target_platform') + + +def _verifier(): + spec = importlib.util.spec_from_file_location('tp_release_manifest', REPO / 'config/native/release_manifest.py') + module = importlib.util.module_from_spec(spec) + sys.modules['tp_release_manifest'] = module + spec.loader.exec_module(module) + return module + + +def check_entry(entry): + for key in ('id', 'version', 'kind', 'image_id', 'entrypoint', 'platform'): + if key not in entry: + raise ValueError('plugin entry is missing ' + key) + if not str(entry['image_id']).startswith('sha256:') or len(entry['image_id']) != 71: + raise ValueError('image_id must be an immutable sha256 image ID') + if entry['id'] == 'homeassistant' and re.fullmatch(r'[0-9a-f]{64}', str(entry.get('image_archive_sha256', ''))) is None: + raise ValueError('homeassistant.image_archive_sha256 must be a lowercase SHA-256 digest') + platform = entry['platform'] + binding = platform.get('binding', 'template') + if binding not in ('template', 'none'): + raise ValueError('platform.binding must be "template" or "none"') + if binding == 'template': + for key in ('protocol_type', 'device_type', 'template_name', 'secret_env'): + if key not in platform: + raise ValueError('platform.' + key + ' is required when binding is template') + elif not platform.get('service_identifier'): + raise ValueError('platform.service_identifier is required when binding is none') + alias = platform.get('network_alias') + if alias is not None and not re.fullmatch(r'[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?', alias): + raise ValueError('platform.network_alias must be a lowercase DNS label') + service_plugin = platform.get('service_plugin') + if service_plugin is not None: + if binding != 'none': + raise ValueError('platform.service_plugin is only for binding none') + if not isinstance(service_plugin.get('config'), dict) or not service_plugin.get('name'): + raise ValueError('platform.service_plugin needs name and a config object') + if 'http_address' in service_plugin['config'] and 'http_port' not in platform: + raise ValueError('service_plugin.config.http_address needs platform.http_port') + for name, spec in entry.get('env_user', {}).items(): + if not isinstance(spec, dict) or spec.get('validate') not in (None, 'url'): + raise ValueError('env_user.%s: unsupported spec' % name) + if entry['kind'] != 'service': + raise ValueError('only service plugins are supported by this installer') + + +def publish(args): + plugins = [] + for path in args.plugin_file: + entry = json.loads(Path(path).read_text(encoding='utf-8')) + check_entry(entry) + plugins.append(entry) + if not plugins: + raise SystemExit('at least one --plugin-file is required') + now = int(time.time()) + catalog = {'schema': SCHEMA, 'version': args.version, 'published_at': now, 'expires_at': now + args.valid_days * 86400, 'plugins': plugins} + bundle = validate_bundle_metadata(getattr(args, 'target_platform', None), + getattr(args, 'release_tag', None), getattr(args, 'agent_sha256', None)) + if bundle: + catalog.update(bundle) + validate_catalog_bundle(catalog) + raw = json.dumps(catalog, sort_keys=True, indent=1).encode() + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + (out / 'plugin-catalog.json').write_bytes(raw) + signature = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', args.key], input=raw, stdout=subprocess.PIPE, check=True).stdout + (out / 'plugin-catalog.json.sig').write_bytes(signature) + print('published %d plugin(s), catalog version %s' % (len(plugins), args.version)) + + +def load_verified(catalog_path, trust_root): + """Return the catalog dict only if the signature verifies against the pinned root and it is current.""" + verifier = _verifier() + catalog_path = Path(catalog_path) + raw = catalog_path.read_bytes() + signature = Path(str(catalog_path) + '.sig').read_bytes() + verifier.verify_signature(raw, signature, verifier.load_trust_root(trust_root)) + catalog = json.loads(raw) + if catalog.get('schema') != SCHEMA: + raise ValueError('unsupported catalog schema') + if int(time.time()) >= int(catalog.get('expires_at', 0)): + raise ValueError('catalog has expired') + for entry in catalog['plugins']: + check_entry(entry) + validate_catalog_bundle(catalog) + return catalog + + +def verify(args): + catalog = load_verified(args.catalog, args.trust_root) + print('catalog v%s verified: %s' % (catalog['version'], ', '.join('%s@%s' % (p['id'], p['version']) for p in catalog['plugins']))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest='command', required=True) + p = sub.add_parser('publish') + p.add_argument('--key', required=True) + p.add_argument('--out', required=True) + p.add_argument('--version', required=True) + p.add_argument('--valid-days', type=int, default=30) + p.add_argument('--plugin-file', action='append', default=[]) + p.add_argument('--target-platform', choices=sorted(SUPPORTED_PLUGIN_PLATFORMS), + help='optional bundle target; must be paired with --release-tag and --agent-sha256') + p.add_argument('--release-tag', help='optional safe GitHub Release tag for the bundle assets') + p.add_argument('--agent-sha256', help='optional lowercase SHA-256 digest of the target Agent binary') + p.set_defaults(run=publish) + v = sub.add_parser('verify') + v.add_argument('--trust-root', required=True) + v.add_argument('--catalog', required=True) + v.set_defaults(run=verify) + args = parser.parse_args() + try: + args.run(args) + except Exception as error: # noqa: BLE001 - CLI boundary + print('error: %s' % error, file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/plugin_install.py b/tools/plugin_install.py new file mode 100644 index 0000000..b245c03 --- /dev/null +++ b/tools/plugin_install.py @@ -0,0 +1,557 @@ +#!/usr/bin/env python3 +"""One-command install of a service plugin from a signed catalog onto a running ThingsPanel stack. + + TP_TENANT_EMAIL=... TP_TENANT_PASSWORD=... plugin_install.py install \ + --catalog plugin-catalog.json --trust-root trust-root.pem --plugin http-adapter \ + --stack-dir /opt/thingspanel --web-url http://127.0.0.1:8080 --agent-dir /var/lib/tp-agent \ + --agent-bin tp-agent --agentctl-bin tp-agentctl [--device my-first-device] + +What it does, in order (each step is idempotent; re-running installs the next generation): + 1. verifies the catalog signature against the pinned trust root and checks the pinned image ID; + 2. creates the platform-side binding (device template for the plugin's protocol, template secret, + auto registration) through the platform API; + 3. optionally registers a first device and reloads the Broker allowlist in the required order; + 4. starts (or reuses) the host Agent and asks it to prepare, grant and activate the plugin container; + 5. checks that the plugin registered with the platform and, with --device, that an uplink arrives. + +The Agent lease is at most 24 hours; run `plugin_install.py renew` from cron (or any scheduler) to extend it. +""" +import argparse +import getpass +import json +import os +from pathlib import Path +import secrets +import subprocess +import sys +import re +import time +import urllib.error +import urllib.parse +import urllib.request + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import plugin_catalog # noqa: E402 +import scope_sync # noqa: E402 + +DEFAULT_TOKEN_ENV = 'TP_PLUGIN_RUNTIME_TOKEN' +SERVICE_ENV = 'TP_PLUGIN_SERVICE_IDENTIFIER' + + +def binding_of(entry): + return entry['platform'].get('binding', 'template') + + +def service_identifier(entry): + spec = entry['platform'] + return spec.get('service_identifier') or spec['protocol_type'] + + +ALIAS_RE = re.compile(r'[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?') + + +def network_alias(entry): + """Stable DNS alias of the plugin container on the stack network; the same for every generation.""" + alias = (entry.get('platform') or {}).get('network_alias') or 'tp-plugin-' + entry['id'] + if not ALIAS_RE.fullmatch(alias): + raise ValueError('invalid network alias %r (lowercase letters, digits and - only)' % alias) + return alias + + +def token_env_of(entry): + return (entry.get('identity') or {}).get('token_env', DEFAULT_TOKEN_ENV) + + +def collect_user_env(entry, assignments, interactive): + """Resolve the catalog's env_user fields. Order: --set KEY=VALUE, an environment variable named KEY, the entry's + default, then (only on a terminal) a prompt. Secret fields are never accepted on the command line, never echoed.""" + specs = entry.get('env_user', {}) + given = {} + for item in assignments or []: + key, sep, value = item.partition('=') + if not sep or key not in specs: + raise RuntimeError('--set %s: expected KEY=VALUE with KEY one of: %s' % (key or item, ', '.join(specs) or 'none')) + if specs[key].get('secret'): + raise RuntimeError('%s is a secret: pass it in the environment variable %s or type it at the prompt, not with --set' % (key, key)) + given[key] = value + values = {} + for key, spec in specs.items(): + value = given.get(key) + if value is None: + value = os.environ.get(key) + if not value: + value = spec.get('default') + if not value and interactive: + label = '%s (%s)%s: ' % (key, spec.get('description', ''), '' if spec.get('required') else ' [optional]') + value = getpass.getpass(label) if spec.get('secret') else input(label) + if not value: + if spec.get('required'): + raise RuntimeError('%s is required (%s); pass --set %s=... or set the environment variable %s%s' % ( + key, spec.get('description', ''), key, key, '' if not spec.get('secret') else ' (secret: environment variable or prompt only)')) + continue + values[key] = check_user_value(key, spec, value) + return values + + +def check_user_value(key, spec, value): + if any(ch in value for ch in '\n\r\0'): + raise RuntimeError('%s must be a single line' % key) + if spec.get('validate') == 'url': + parsed = urllib.parse.urlparse(value) + if parsed.scheme not in ('http', 'https') or not parsed.netloc: + raise RuntimeError('%s must be an http(s) URL, got %r' % (key, value if not spec.get('secret') else '')) + if spec.get('pattern') and not re.fullmatch(spec['pattern'], value): + raise RuntimeError('%s does not match the required format' % key) + return value + + +def sh(args, check=True, cwd=None, env=None, timeout=300): + result = subprocess.run(args, cwd=cwd, env=env, capture_output=True, text=True, timeout=timeout) + if check and result.returncode: + raise RuntimeError('command failed (%d): %s\n%s' % (result.returncode, ' '.join(args[:4]), (result.stderr or result.stdout)[-400:])) + return result + + +def say(text): + print('==> ' + text, flush=True) + + +class Platform: + def __init__(self, base, email, password): + self.base = base.rstrip('/') + status, body = self.call('/api/v1/login', {'email': email, 'password': password}) + if status != 200 or not isinstance(body, dict) or not (body.get('data') or {}).get('token'): + raise RuntimeError('platform login failed') + self.token = body['data']['token'] + + def call(self, path, data=None, method=None, extra_headers=None): + headers = {'Content-Type': 'application/json', **(extra_headers or {})} + if getattr(self, 'token', None): + headers['x-token'] = self.token + request = urllib.request.Request(self.base + path, json.dumps(data).encode() if data is not None else None, headers, method=method) + try: + with urllib.request.urlopen(request, timeout=30) as response: + return response.status, json.loads(response.read() or b'{}') + except urllib.error.HTTPError as error: + return error.code, error.read()[:200].decode('utf-8', 'replace') + + def must(self, path, data=None, method=None, extra_headers=None): + status, body = self.call(path, data, method, extra_headers) + if status != 200 or (isinstance(body, dict) and body.get('code') not in (None, 200)): + raise RuntimeError('platform call %s failed: %s %s' % (path, status, str(body)[:160])) + return body.get('data') if isinstance(body, dict) else body + + +class Agent: + def __init__(self, args, project): + self.name = 'tp-agent-' + project + self.dir = Path(args.agent_dir) + self.args = args + + def write_profile(self, profile): + profiles = self.dir / 'profiles.json' + profiles.write_text(json.dumps([profile])) + os.chmod(profiles, 0o600) + sh(['docker', 'restart', self.name]) + time.sleep(3) + + def scrub(self, profile): + """Rewrite profiles.json without the runtime token once the container holds it (no restart: the Agent + keeps its loaded copy; the next install writes a fresh profile before it prepares anything).""" + profiles = self.dir / 'profiles.json' + profiles.write_text(json.dumps([profile])) + os.chmod(profiles, 0o600) + + def ensure_running(self, profile): + self.dir.mkdir(parents=True, exist_ok=True) + os.chmod(self.dir, 0o700) + (self.dir / 'state').mkdir(exist_ok=True) + os.chmod(self.dir / 'state', 0o700) + token = self.dir / 'token' + if not token.exists(): + token.write_text(secrets.token_hex(24)) + os.chmod(token, 0o600) + profiles = self.dir / 'profiles.json' + profiles.write_text(json.dumps([profile])) + os.chmod(profiles, 0o600) + mounts = ['-v', '%s:/tp-agent:ro' % self.args.agent_bin, '-v', '%s:/tp-agentctl:ro' % self.args.agentctl_bin, '-v', '%s:/run/agent' % self.dir] + if not (self.dir / 'state' / 'state.json').exists(): + sh(['docker', 'run', '--rm', '--entrypoint', '/tp-agent', '-u', '0'] + mounts + [self.args.agent_image, + '-state', '/run/agent/state/state.json', '-init', 'host-' + self.name]) + sh(['docker', 'rm', '-f', self.name], check=False) + sh(['docker', 'run', '-d', '--name', self.name, '--restart', 'unless-stopped', '--entrypoint', '/tp-agent', '-u', '0'] + mounts + + ['-v', '/var/run/docker.sock:/var/run/docker.sock', self.args.agent_image, '-state', '/run/agent/state/state.json', + '-socket', '/run/agent/agent.sock', '-token-file', '/run/agent/token', '-profiles', '/run/agent/profiles.json', + '-docker-socket', '/var/run/docker.sock', '-sweep-interval', '5s']) + time.sleep(3) + + def ctl(self, endpoint, **fields): + last = '' + for _ in range(5): + result = sh(['docker', 'exec', self.name, '/tp-agentctl', '-socket', '/run/agent/agent.sock', '-token-file', '/run/agent/token', endpoint] + + ['%s=%s' % item for item in fields.items()], check=False) + if result.stdout.startswith('200'): + return result.stdout[4:] + last = (result.stdout or result.stderr)[:200] + if not result.stdout.startswith('5'): + break + time.sleep(1) + raise RuntimeError('agent %s failed: %s' % (endpoint, last)) + + +def read_env(path): + values = {} + for line in Path(path).read_text().splitlines(): + if '=' in line and not line.startswith('#'): + key, _, value = line.partition('=') + values[key] = value + return values + + +def project_of(stack_dir): + return os.environ.get('COMPOSE_PROJECT_NAME') or Path(stack_dir).resolve().name.lower() + + +def wait_web(url, seconds=120): + deadline = time.time() + seconds + while time.time() < deadline: + try: + with urllib.request.urlopen(url.rstrip('/') + '/api/v1/sys_version', timeout=5) as response: + if response.status == 200: + return + except Exception: # noqa: BLE001 + pass + time.sleep(4) + raise RuntimeError('platform did not come back in time') + + +def reload_broker(stack_dir, web_url): + """Refresh the device allowlist, then restart in the order the Broker needs (owner, broker, then the platform).""" + env = dict(os.environ) + journal = Path(stack_dir) / '.thingspanel-update' / 'journal.json' + if journal.exists(): + data = json.loads(journal.read_text()) + if data.get('phase') == 'activation_started': + env['TP_INSTALLER_ACTIVE_OPERATION'] = data['operation'] + sh([sys.executable, 'config/native/prepare.py', '--refresh-devices'], cwd=stack_dir, env=env) + sh(['docker', 'compose', 'restart', 'broker-owner'], cwd=stack_dir) + sh(['docker', 'compose', 'restart', 'mosquitto'], cwd=stack_dir) + sh(['docker', 'compose', 'restart', 'backend', 'frontend'], cwd=stack_dir) + wait_web(web_url) + + +def with_identity(profile, entry, token): + """A copy of the profile that carries the runtime identity (token + service identifier) in its environment.""" + drop = (token_env_of(entry) + '=', SERVICE_ENV + '=') + env = [e for e in profile['env'] if not e.startswith(drop)] + return dict(profile, env=env + ['%s=%s' % (token_env_of(entry), token), '%s=%s' % (SERVICE_ENV, service_identifier(entry))]) + + +def issue_identity(platform, entry, generation): + """Ask the platform for the identity of this generation; a higher generation revokes every lower one.""" + try: + issued = platform.must('/api/v1/plugin/runtime/identity', {'plugin_instance': entry['id'], 'service_identifier': service_identifier(entry), + 'generation': generation, 'ttl_hours': 24}) + except RuntimeError as error: + if '409' in str(error): + raise RuntimeError('the platform already has generation >= %d for %s (installer state lost or edited?); ' + 'restore %s or pick a state with a higher generation' % (generation, entry['id'], 'the Agent plugin state file')) + raise + return issued['token'] + + +def revoke_identity(platform, entry): + return platform.must('/api/v1/plugin/runtime/identity/revoke', {'plugin_instance': entry['id']}) + + +def agent_install(agent, entry, state, state_path, platform, profile): + """Install or upgrade to the next generation: issue the identity first, hand it to the new container only through + the Agent profile environment (never the image, never a log line), then drop the token from disk again.""" + generation = int(state.get('generation', 0)) + 1 + key = 'install-%d' % generation + token = issue_identity(platform, entry, generation) + try: + if state.get('generation') and state.get('active', True): + agent.ctl('/v1/revoke', instance=entry['id'], generation=state['generation'], reason='replaced by generation %d' % generation) + # The Agent keeps the previous generation's container resource until the new generation is accepted and the + # old one is retired (the takeover step); that also holds after an uninstall (revoked, never retired). + agent.write_profile(with_identity(profile, entry, token)) + agent.ctl('/v1/accept-generation', instance=entry['id'], generation=generation) + if state.get('generation'): + agent.ctl('/v1/retire', instance=entry['id'], generation=state['generation']) + agent.ctl('/v1/prepare', instance=entry['id'], generation=generation, request_key=key, profile=entry['id']) + agent.ctl('/v1/grant', instance=entry['id'], generation=generation, request_key=key, grant_id='grant-%d' % generation, ttl_seconds=86400) + agent.ctl('/v1/activate', instance=entry['id'], generation=generation, request_key=key) + except Exception: + try: + revoke_identity(platform, entry) # do not leave a live identity that no container holds + except Exception: # noqa: BLE001 - best effort, the original error matters more + pass + raise + finally: + agent.scrub(profile) + state['generation'] = generation + state['request_key'] = key + state['active'] = True + state_path.write_text(json.dumps(state)) + print(' generation %d is running with a fresh runtime identity' % generation) + time.sleep(8) + + +def uplink(args, entry, state, network, device_number, values=None): + spec = entry['platform'] + name, ip = container_ip(network, state['generation']) + key = state['generated'][spec['api_key_env']] + body = json.dumps({'device_number': device_number, 'values': values or {'temp': 21.5, 'hum': 55}}) + return sh(['docker', 'run', '--rm', '--network', network, '--entrypoint', 'sh', args.agent_image, '-c', + "wget -q -O- -T 10 --header 'Content-Type: application/json' --header 'X-Api-Key: %s' --post-data '%s' http://%s:%d%s 2>&1 | tail -1" + % (key, body, ip, spec['uplink_port'], spec['uplink_path'])], check=False).stdout.strip() + + +def bind_template(platform, entry, state, generated): + spec = entry['platform'] + if not state.get('config_id'): + created = platform.must('/api/v1/device_config', {'name': spec['template_name'], 'device_type': spec['device_type'], + 'protocol_type': spec['protocol_type'], 'device_conn_type': 'A'}) + state['config_id'] = created['id'] + platform.must('/api/v1/device_config', {'id': state['config_id'], 'name': spec['template_name'], + 'template_secret': generated[spec['secret_env']], 'auto_register': 1}, 'PUT') + print(' device template %s (protocol %s), auto registration on' % (state['config_id'][:8], spec['protocol_type'])) + + +def install(args): + stack = Path(args.stack_dir) + project = project_of(stack) + say('verifying the signed catalog') + catalog = plugin_catalog.load_verified(args.catalog, args.trust_root) + matches = [p for p in catalog['plugins'] if p['id'] == args.plugin] + if not matches: + raise RuntimeError('plugin %s is not in the catalog' % args.plugin) + entry = matches[0] + if binding_of(entry) == 'none': + return install_via_platform(args, stack, entry) + image = sh(['docker', 'image', 'inspect', '--format', '{{.Id}}', entry['image_id']], check=False).stdout.strip() + if image != entry['image_id']: + raise RuntimeError('image %s is not present locally; pull it by digest first' % entry['image_id']) + print(' %s@%s, image %s' % (entry['id'], entry['version'], entry['image_id'][:19])) + + state_path = Path(args.agent_dir) / 'plugins' / (entry['id'] + '.json') + state_path.parent.mkdir(parents=True, exist_ok=True) + state = json.loads(state_path.read_text()) if state_path.exists() else {} + generated = state.setdefault('generated', {}) + for key, size in entry.get('env_generated', {}).items(): + generated.setdefault(key, secrets.token_hex(size // 2)) + + email, password = os.environ.get('TP_TENANT_EMAIL'), os.environ.get('TP_TENANT_PASSWORD') + if not email or not password: + raise RuntimeError('set TP_TENANT_EMAIL and TP_TENANT_PASSWORD (never put them in a file)') + platform = Platform(args.web_url, email, password) + user_env = collect_user_env(entry, args.set, sys.stdin.isatty() and not args.non_interactive) + say('creating the platform-side binding') + bind_template(platform, entry, state, generated) + + device_number = args.device + + say('installing through the Agent') + stack_env = read_env(stack / '.env') + env = list(entry.get('env', [])) + for target, source in entry.get('env_from_stack', {}).items(): + env.append('%s=%s' % (target, stack_env[source])) + env += ['%s=%s' % item for item in generated.items()] + env += ['%s=%s' % item for item in user_env.items()] + profile = {'name': entry['id'], 'image_id': entry['image_id'], 'entrypoint': entry['entrypoint'], 'args': entry.get('args', []), + 'network': args.network or '%s_thingspanel_network' % project, 'network_alias': network_alias(entry), + 'reviewed_image_metadata': True, 'env': env} + state_path.write_text(json.dumps(state)) + os.chmod(state_path, 0o600) + agent = Agent(args, project) + agent.ensure_running(profile) + agent_install(agent, entry, state, state_path, platform, profile) + if device_number and not state.get('registered'): + say('first device: the plugin registers it on its first uplink, then the Broker allowlist is reloaded') + net = args.network or '%s_thingspanel_network' % project + first = uplink(args, entry, state, net, device_number) + print(' first uplink (registers the device): %s' % first[:70]) + time.sleep(3) + reload_broker(stack, args.web_url) + platform = Platform(args.web_url, email, password) + agent_install(agent, entry, state, state_path, platform, profile) # new generation: the plugin reconnects to the reloaded Broker + state['registered'] = True + state['device_number'] = device_number + state_path.write_text(json.dumps(state)) + check(args, stack, platform, entry, state) + keep_scope_in_sync(args, stack) + + +def wait_installation(platform, plugin_id, states, seconds=600): + """Poll the platform's installation record until it reaches one of `states`; print each new step once.""" + deadline, seen = time.time() + seconds, set() + while time.time() < deadline: + rows = platform.must('/api/v1/plugin/installs') or [] + row = next((r for r in rows if r['plugin_id'] == plugin_id), None) + if row: + mark = (row['state'], row.get('op_step'), row.get('error_code')) + if mark not in seen: + seen.add(mark) + print(' %s%s%s' % (row['state'], ' (' + row['op_step'] + ')' if row.get('op_step') else '', + ' ' + row['error_code'] if row.get('error_code') else ''), flush=True) + if row['state'] in states: + return row + time.sleep(3) + raise RuntimeError('timed out waiting for %s to reach %s' % (plugin_id, '/'.join(states))) + + +def install_via_platform(args, stack, entry): + """Install a plugin through the platform's own installation API: the same engine the UI uses, so there is one + implementation of the flow. The Agent must already be running in catalog mode (tools/agent_host.py up).""" + email, password = os.environ.get('TP_TENANT_EMAIL'), os.environ.get('TP_TENANT_PASSWORD') + if not email or not password: + raise RuntimeError('set TP_TENANT_EMAIL and TP_TENANT_PASSWORD (never put them in a file)') + platform = Platform(args.web_url, email, password) + values = collect_user_env(entry, args.set, sys.stdin.isatty() and not args.non_interactive) + say('asking the platform to install %s' % entry['id']) + platform.must('/api/v1/plugin/installs', {'plugin_id': entry['id'], 'config': values}, extra_headers={'Idempotency-Key': secrets.token_hex(16)}) + row = wait_installation(platform, entry['id'], ('enabled', 'failed', 'pending_config')) + if row['state'] != 'enabled': + raise RuntimeError('installation ended in state %s (%s)' % (row['state'], row.get('error_code') or 'see the platform page')) + print(' generation %s, health %s' % (row['generation'], row['health'])) + keep_scope_in_sync(args, stack) + + +def uninstall_via_platform(args): + email, password = os.environ.get('TP_TENANT_EMAIL'), os.environ.get('TP_TENANT_PASSWORD') + if not email or not password: + raise RuntimeError('set TP_TENANT_EMAIL and TP_TENANT_PASSWORD (never put them in a file)') + platform = Platform(args.web_url, email, password) + rows = platform.must('/api/v1/plugin/installs') or [] + row = next((r for r in rows if r['plugin_id'] == args.plugin), None) + if not row: + raise RuntimeError('%s is not installed' % args.plugin) + platform.must('/api/v1/plugin/installs/' + row['id'], None, 'DELETE') + wait_installation(platform, args.plugin, ('uninstalled', 'failed')) + print('uninstalled %s (its generation stays reserved; the service_plugins row is kept on purpose)' % args.plugin) + + +def keep_scope_in_sync(args, stack): + """Refresh the Broker device scope once now, then keep it fresh: devices the user creates or deletes later in the + platform UI are picked up by a detached watcher (tools/scope_sync.py), no manual command.""" + say('keeping the Broker device scope in step with the platform') + ok, output = scope_sync.run_once(stack) + lines = [line for line in output.splitlines() if 'scope' in line] + print(' %s' % (lines[-1] if lines else ('ok' if ok else 'failed'))) + if not ok: + raise RuntimeError('the Broker device scope could not be refreshed: %s' % output) + status = ensure_scope_watcher(stack, args.agent_dir) + print(' watcher: %s (log %s)' % (status, Path(args.agent_dir) / 'scope-sync.log')) + + +def ensure_scope_watcher(stack, agent_dir, attempts=60, interval=5, sleep=time.sleep): + """Wait for an overlapping update to release the lock before install/renew returns success.""" + for attempt in range(attempts): + status = scope_sync.ensure(stack, agent_dir) + if status != 'busy': + return status + if attempt + 1 < attempts: + sleep(interval) + raise RuntimeError('the installer update lock stayed busy; scope watcher was not started; retry install or renew') + + +def container_ip(project_network, generation): + name = sh(['docker', 'ps', '--filter', 'label=io.thingspanel.agent.generation=%d' % generation, '--format', '{{.Names}}']).stdout.split()[0] + return name, sh(['docker', 'inspect', name, '--format', '{{(index .NetworkSettings.Networks "%s").IPAddress}}' % project_network]).stdout.strip() + + +def check(args, stack, platform, entry, state): + say('checking that it works') + project = project_of(stack) + network = args.network or '%s_thingspanel_network' % project + time.sleep(8) + name, ip = container_ip(network, state['generation']) + print(' plugin container %s is running' % name[-8:]) + health = entry.get('health') + if health: + answer = sh(['docker', 'run', '--rm', '--network', network, '--entrypoint', 'sh', args.agent_image, '-c', + 'wget -q -O- -T 5 http://%s:%d%s 2>&1 | tail -c 200' % (ip, health['port'], health['path'])], check=False).stdout.strip() + print(' health %s:%d%s -> %s' % (name[-8:], health['port'], health['path'], answer)) + alias_answer = sh(['docker', 'run', '--rm', '--network', network, '--entrypoint', 'sh', args.agent_image, '-c', + 'wget -q -O- -T 5 http://%s:%d%s 2>&1 | tail -c 200' % (network_alias(entry), health['port'], health['path'])], check=False).stdout.strip() + print(' health via stable alias %s -> %s' % (network_alias(entry), alias_answer)) + if 'ok' not in alias_answer.lower(): + raise RuntimeError('the stable alias %s does not reach the plugin container' % network_alias(entry)) + if '"ok"' not in answer and 'ok' not in answer.lower(): + raise RuntimeError('plugin container is up but its health check did not answer ok') + if not state.get('device_number'): + return + result = uplink(args, entry, state, network, state['device_number'], {'temp': 33.3, 'hum': 77}) + print(' uplink answered: %s' % result[:80]) + time.sleep(6) + device_id = sh(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'postgres', '-d', 'ThingsPanel', '-Atc', + "select id from devices where device_number='%s'" % state['device_number']], cwd=stack).stdout.strip() + data = platform.must('/api/v1/telemetry/datas/current/' + device_id) + print(' the platform shows: %s' % {item['key']: item['value'] for item in data}) + + +def renew(args): + if not (Path(args.agent_dir) / 'plugins' / (args.plugin + '.json')).exists(): + # Installed through the platform: its engine renews the Agent lease and the identity by itself. + print('%s is managed by the platform; renewal is automatic' % args.plugin) + print('scope watcher: %s' % ensure_scope_watcher(args.stack_dir, args.agent_dir)) + return + state = json.loads((Path(args.agent_dir) / 'plugins' / (args.plugin + '.json')).read_text()) + agent = Agent(args, project_of(args.stack_dir)) + agent.ctl('/v1/grant', instance=args.plugin, generation=state['generation'], request_key=state['request_key'], + grant_id='renew-%d' % int(time.time()), ttl_seconds=86400) + print('lease extended by 24 hours') + print('scope watcher: %s' % ensure_scope_watcher(args.stack_dir, args.agent_dir)) + + +def uninstall(args): + """Stop the plugin container and revoke its runtime identity. The generation counter stays in the state file so a + later install issues a strictly higher generation (a revoked generation can never be reused).""" + state_path = Path(args.agent_dir) / 'plugins' / (args.plugin + '.json') + if not state_path.exists(): + return uninstall_via_platform(args) + state = json.loads(state_path.read_text()) + email, password = os.environ.get('TP_TENANT_EMAIL'), os.environ.get('TP_TENANT_PASSWORD') + if not email or not password: + raise RuntimeError('set TP_TENANT_EMAIL and TP_TENANT_PASSWORD (never put them in a file)') + platform = Platform(args.web_url, email, password) + agent = Agent(args, project_of(args.stack_dir)) + if state.get('active', True) and state.get('generation'): + say('revoking generation %d in the Agent' % state['generation']) + agent.ctl('/v1/revoke', instance=args.plugin, generation=state['generation'], reason='uninstalled') + say('revoking the runtime identity on the platform') + revoked = revoke_identity(platform, {'id': args.plugin}) + print(' revoked identities: %s' % (revoked or {}).get('revoked')) + state['active'] = False + state_path.write_text(json.dumps(state)) + print('uninstalled %s (generation %s stays reserved; the service_plugins row is kept on purpose)' % (args.plugin, state.get('generation'))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('command', choices=['install', 'renew', 'uninstall']) + parser.add_argument('--catalog') + parser.add_argument('--trust-root') + parser.add_argument('--plugin', required=True) + parser.add_argument('--stack-dir', required=True) + parser.add_argument('--web-url', required=True) + parser.add_argument('--agent-dir', required=True) + parser.add_argument('--agent-bin') + parser.add_argument('--agentctl-bin') + parser.add_argument('--agent-image', default='registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-go:v1.3.0') + parser.add_argument('--network') + parser.add_argument('--device') + parser.add_argument('--set', action='append', default=[], metavar='KEY=VALUE', help='non-secret plugin setting (env_user); secrets come from the environment variable KEY or a prompt') + parser.add_argument('--non-interactive', action='store_true', help='never prompt; fail when a required setting is missing') + args = parser.parse_args() + try: + {'install': install, 'renew': renew, 'uninstall': uninstall}[args.command](args) + except Exception as error: # noqa: BLE001 - CLI boundary + print('error: %s' % error, file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/regress_identity.py b/tools/regress_identity.py new file mode 100644 index 0000000..9d28da4 --- /dev/null +++ b/tools/regress_identity.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Regression of the managed runtime identity with the http-adapter plugin (needs a running platform stack). + + TP_TENANT_EMAIL=... TP_TENANT_PASSWORD=... regress_identity.py --catalog C --trust-root R --stack-dir S \ + --web-url http://127.0.0.1:PORT --agent-dir D --agent-bin B --agentctl-bin CTL + +Steps (one log line each, tokens are never printed): install -> read the container's identity -> device/config answers 200 +-> uninstall -> the old identity is refused (503) -> reinstall issues a higher generation: old token still refused, new one works. +The token is read from the container environment with `docker inspect`: this is a test-only shortcut. +""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import time +import urllib.error +import urllib.request + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import plugin_install as pi # noqa: E402 + + +def post(base, path, body, headers): + request = urllib.request.Request(base + path, json.dumps(body).encode(), dict({'Content-Type': 'application/json'}, **headers)) + try: + with urllib.request.urlopen(request, timeout=20) as response: + return response.status, json.loads(response.read() or b'{}') + except urllib.error.HTTPError as error: + raw = error.read() + try: + return error.code, json.loads(raw) + except ValueError: + return error.code, {} + + +def code_of(body): + data = body.get('data') if isinstance(body, dict) else None + return (data or {}).get('errorCode') if isinstance(data, dict) else None + + +def container_token(plugin, generation, token_env): + name = pi.sh(['docker', 'ps', '--filter', 'label=io.thingspanel.agent.generation=%d' % generation, + '--filter', 'label=io.thingspanel.agent.instance=%s' % plugin, '--format', '{{.Names}}']).stdout.split() + if not name: + name = pi.sh(['docker', 'ps', '--filter', 'label=io.thingspanel.agent.generation=%d' % generation, '--format', '{{.Names}}']).stdout.split() + env = pi.sh(['docker', 'inspect', name[0], '--format', '{{range .Config.Env}}{{println .}}{{end}}']).stdout.splitlines() + return next(e.partition('=')[2] for e in env if e.startswith(token_env + '=')) + + +def main(): + parser = argparse.ArgumentParser() + for name in ('catalog', 'trust-root', 'stack-dir', 'web-url', 'agent-dir', 'agent-bin', 'agentctl-bin'): + parser.add_argument('--' + name, required=True) + parser.add_argument('--plugin', default='http-adapter') + args = parser.parse_args() + py = [sys.executable, str(HERE / 'plugin_install.py')] + common = ['--plugin', args.plugin, '--stack-dir', args.stack_dir, '--web-url', args.web_url, '--agent-dir', args.agent_dir] + install_args = py[:1] + py[1:] + ['install', '--catalog', args.catalog, '--trust-root', args.trust_root, '--agent-bin', args.agent_bin, + '--agentctl-bin', args.agentctl_bin, '--non-interactive'] + common + results = [] + + def step(name, ok, detail): + results.append(ok) + print('[%s] %s: %s' % ('PASS' if ok else 'FAIL', name, detail), flush=True) + + entry = json.loads((HERE.parent / 'plugins' / (args.plugin + '.json')).read_text()) + token_env = pi.token_env_of(entry) + state_path = Path(args.agent_dir) / 'plugins' / (args.plugin + '.json') + platform = pi.Platform(args.web_url, os.environ['TP_TENANT_EMAIL'], os.environ['TP_TENANT_PASSWORD']) + + run = subprocess.run(install_args, capture_output=True, text=True) + state = json.loads(state_path.read_text()) if state_path.exists() else {} + step('1 install', run.returncode == 0, 'exit=%d generation=%s' % (run.returncode, state.get('generation'))) + if run.returncode: + print((run.stdout + run.stderr)[-800:]) + return 1 + gen1 = state['generation'] + token1 = container_token(args.plugin, gen1, token_env) + step('2 identity injected into the container env', token1.startswith('pri_') and '.' in token1, 'format pri_., length %d' % len(token1)) + + device = platform.must('/api/v1/device', {'name': 't5-regress-device', 'device_number': 't5-regress-%d-%d' % (gen1, int(time.time())), 'device_config_id': state['config_id']}) + device_id = device['id'] + auth1 = {'Authorization': 'Bearer ' + token1} + status, body = post(args.web_url, '/api/v1/plugin/device/config', {'device_id': device_id}, auth1) + step('3 device/config with the new identity', status == 200, 'HTTP %d' % status) + status, body = post(args.web_url, '/api/v1/plugin/device/config', {'device_id': device_id}, {}) + step('3b device/config without identity', status == 503 and code_of(body) == 'PLUGIN_RUNTIME_IDENTITY_REQUIRED', 'HTTP %d %s' % (status, code_of(body))) + + run = subprocess.run(py + ['uninstall'] + common, capture_output=True, text=True, env=dict(os.environ)) + step('4 uninstall', run.returncode == 0, 'exit=%d %s' % (run.returncode, run.stdout.strip().splitlines()[-1] if run.stdout.strip() else run.stderr[-200:])) + status, body = post(args.web_url, '/api/v1/plugin/device/config', {'device_id': device_id}, auth1) + step('5 old identity after uninstall', status == 503 and code_of(body) == 'PLUGIN_RUNTIME_IDENTITY_REQUIRED', 'HTTP %d %s' % (status, code_of(body))) + left = pi.sh(['docker', 'ps', '-q', '--filter', 'label=io.thingspanel.agent.generation=%d' % gen1]).stdout.split() + step('5b container stopped', not left, 'running containers of generation %d: %d' % (gen1, len(left))) + + run = subprocess.run(install_args, capture_output=True, text=True) + state = json.loads(state_path.read_text()) + step('6 reinstall', run.returncode == 0 and state['generation'] > gen1, 'exit=%d generation %d -> %s' % (run.returncode, gen1, state.get('generation'))) + if run.returncode: + print((run.stdout + run.stderr)[-800:]) + return 1 + token2 = container_token(args.plugin, state['generation'], token_env) + status_old, _ = post(args.web_url, '/api/v1/plugin/device/config', {'device_id': device_id}, auth1) + status_new, _ = post(args.web_url, '/api/v1/plugin/device/config', {'device_id': device_id}, {'Authorization': 'Bearer ' + token2}) + step('7 reinstall: old generation refused, new accepted', status_old == 503 and status_new == 200, 'old HTTP %d, new HTTP %d' % (status_old, status_new)) + return 0 if all(results) else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/regress_t7c.py b/tools/regress_t7c.py new file mode 100644 index 0000000..0a5bd7b --- /dev/null +++ b/tools/regress_t7c.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""T7c regression on a minimal stack (no real Broker data path): service plugin auto-registration, stable address +across a reinstall, and periodic device discovery by the Home Assistant plugin. + + TP_TENANT_EMAIL=... TP_TENANT_PASSWORD=... HA_ACCESS_TOKEN=... regress_t7c.py --catalog C --trust-root R \ + --stack-dir S --web-url URL --agent-dir D --agent-bin B --agentctl-bin CTL [--ha-url http://ha.invalid:8123] +""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import time +import uuid + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import plugin_install as pi # noqa: E402 + +RESULTS = [] + + +def step(name, ok, detail=''): + RESULTS.append(ok) + print('[%s] %s %s' % ('PASS' if ok else 'FAIL', name, detail), flush=True) + + +def plugin_rows(platform): + return [r for r in pi.list_service_plugins(platform, 2) if r['service_identifier'] == 'homeassistant'] + + +def in_network(args, network, command): + return pi.sh(['docker', 'run', '--rm', '--name', 't7c-probe-%d' % int(time.time() * 1000), '--network', network, '--entrypoint', 'sh', args.agent_image, '-c', command], check=False).stdout.strip() + + +def sync_status(args, network): + raw = in_network(args, network, 'wget -q -O- -T 5 http://tp-plugin-homeassistant:9002/sync-status') + return json.loads(raw) if raw.startswith('{') else {} + + +def main(): + parser = argparse.ArgumentParser() + for name in ('catalog', 'trust-root', 'stack-dir', 'web-url', 'agent-dir', 'agent-bin', 'agentctl-bin'): + parser.add_argument('--' + name, required=True) + parser.add_argument('--ha-url', default='http://ha.invalid:8123') + parser.add_argument('--agent-image', default='registry.cn-hangzhou.aliyuncs.com/thingspanel/thingspanel-go:v1.3.0') + args = parser.parse_args() + project = pi.project_of(args.stack_dir) + network = '%s_thingspanel_network' % project + install = [sys.executable, str(HERE / 'plugin_install.py'), 'install', '--catalog', args.catalog, '--trust-root', args.trust_root, '--plugin', 'homeassistant', + '--stack-dir', args.stack_dir, '--web-url', args.web_url, '--agent-dir', args.agent_dir, '--agent-bin', args.agent_bin, + '--agentctl-bin', args.agentctl_bin, '--non-interactive', '--set', 'HA_BASE_URL=' + args.ha_url] + platform = pi.Platform(args.web_url, os.environ['TP_TENANT_EMAIL'], os.environ['TP_TENANT_PASSWORD']) + step('0 no homeassistant row before install', len(plugin_rows(platform)) == 0) + + run = subprocess.run(install, capture_output=True, text=True) + step('1 one-command install', run.returncode == 0, 'exit=%d' % run.returncode) + if run.returncode: + print((run.stdout + run.stderr)[-1200:]) + return 1 + rows = plugin_rows(platform) + config = json.loads(rows[0]['service_config']) if rows else {} + step('2 service plugin row auto-registered', len(rows) == 1 and config.get('sub_topic_prefix') == 'plugin/homeassistant/' and config.get('http_address') == 'tp-plugin-homeassistant:9001', str(config)) + row_id = rows[0]['id'] if rows else None + form = platform.call('/api/v1/service/access/voucher/form?service_plugin_id=%s' % row_id) + step('3 platform reaches the plugin through the registered address', form[0] == 200 and isinstance(form[1], dict) and form[1].get('code') == 200, 'HTTP %s code %s' % (form[0], form[1].get('code') if isinstance(form[1], dict) else form[1])) + + access = platform.must('/api/v1/service/access', {'name': 't7c-access', 'service_plugin_id': row_id, 'voucher': json.dumps({'base_url': args.ha_url, 'access_token': 'x'}, separators=(',', ':'))}) + access_id = access['id'] if isinstance(access, dict) else access + time.sleep(5) + st = sync_status(args, network) + step('4 plugin sync running, no devices yet', st.get('state') == 'running' and st.get('devices') == 0, str(st)) + + def add_device(tag): + number = 't7c-%s-%s' % (tag, uuid.uuid4().hex[:6]) + platform.must('/api/v1/device/service/access/batch', {'service_access_id': access_id, 'device_list': [{ + 'device_name': number, 'device_number': number, 'protocol_config': json.dumps({'entity_id': 'light.' + tag}, separators=(',', ':'))}]}) + return time.time() + + def wait_for(count, limit=75): + start = time.time() + while time.time() - start < limit: + st = sync_status(args, network) + if st.get('devices', 0) >= count: + return time.time() - start, st + time.sleep(3) + return None, sync_status(args, network) + + add_device('one') + took, st = wait_for(1) + step('5 new platform device is noticed within 60s', took is not None and took <= 62, 'after %s s, status %s' % (round(took, 1) if took else None, st)) + + run = subprocess.run(install, capture_output=True, text=True) + step('6 reinstall', run.returncode == 0, 'exit=%d' % run.returncode) + if run.returncode: + print((run.stdout + run.stderr)[-1200:]) + return 1 + rows2 = plugin_rows(platform) + step('7 still exactly one service plugin row, same id', len(rows2) == 1 and rows2[0]['id'] == row_id, '%d row(s)' % len(rows2)) + form = platform.call('/api/v1/service/access/voucher/form?service_plugin_id=%s' % row_id) + step('8 address still works after the generation changed', form[0] == 200 and isinstance(form[1], dict) and form[1].get('code') == 200, 'HTTP %s' % form[0]) + names = pi.sh(['docker', 'ps', '--filter', 'name=tp-agent-prepared', '--format', '{{.Names}}']).stdout.split() + step('9 only one plugin container', len(names) == 1, str(names)) + + add_device('two') + took, st = wait_for(2) + step('10 device created after the reinstall is noticed within 60s', took is not None and took <= 62, 'after %s s, status %s' % (round(took, 1) if took else None, st)) + return 0 if all(RESULTS) else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/scope_sync.py b/tools/scope_sync.py new file mode 100644 index 0000000..cc48258 --- /dev/null +++ b/tools/scope_sync.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Keep the Broker device scope in step with the platform's devices, with no manual command. + +A plugin (service access) device that the user creates or deletes in the platform UI only works once the Broker +knows about it: the owner's `services.json` must list it, and broker-owner, then mosquitto, must be restarted to +load it. This tool does that: + + scope_sync.py once --stack-dir DIR one pass: refresh, restart only if the scope changed + scope_sync.py watch --stack-dir DIR [--interval 20] loop of `once` (foreground) + scope_sync.py ensure --stack-dir DIR --state-dir DIR start a detached `watch` unless one is already running + +`plugin_install.py install` and `renew` call `ensure`, so installing a service plugin starts the watcher and the +renew cron job revives it after a reboot. The scope itself is computed by `config/native/prepare.py --sync-scope` +(the same code `--refresh-devices` uses at install/upgrade), so there is exactly one definition of the scope. +No credentials are read, written or logged here. +""" +import argparse +from contextlib import contextmanager +import importlib.util +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +DEFAULT_INTERVAL = 20 + + +class ScopeSyncBusy(RuntimeError): + """The install/upgrade process currently owns the shared state lock.""" + + +@contextmanager +def installer_lock(stack_dir): + """Use the installer's process lock for scope mutations and watcher startup.""" + stack_dir = Path(stack_dir).resolve() + updater_path = stack_dir / 'config/native/update.py' + spec = importlib.util.spec_from_file_location('tp_scope_sync_update', updater_path) + if spec is None or spec.loader is None: + raise RuntimeError('installer update lock is unavailable') + updater = importlib.util.module_from_spec(spec) + spec.loader.exec_module(updater) + state = stack_dir / '.thingspanel-update' + updater.private_directory(state) + try: + with updater.update_lock(state): + yield updater + except updater.UpdateError as error: + if str(error) == 'Another installer operation is active': + raise ScopeSyncBusy(str(error)) from None + raise + + +def run_once(stack_dir, runner=subprocess.run, python=sys.executable): + """One refresh pass. Returns (ok, output). Never raises: a pass that cannot run (an install holds the update + lock, Docker is restarting) is simply tried again at the next interval.""" + try: + result = runner([python, 'config/native/prepare.py', '--sync-scope'], cwd=str(stack_dir), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=300) + except (OSError, subprocess.SubprocessError) as error: + return False, 'could not run prepare.py: %s' % type(error).__name__ + output = (result.stdout or b'').decode(errors='replace').strip() + return result.returncode == 0, output[-400:] + + +def watch(stack_dir, interval=DEFAULT_INTERVAL, runner=subprocess.run, sleep=time.sleep, rounds=None, log=print): + """Loop of run_once. Logs only on a change or a change of health, so the log does not grow with time.""" + last = None + count = 0 + while rounds is None or count < rounds: + ok, output = run_once(stack_dir, runner) + if (ok, output) != last: + log('%s %s %s' % (time.strftime('%Y-%m-%dT%H:%M:%S'), 'ok' if ok else 'FAILED', output.replace('\n', ' | '))) + last = (ok, output) + count += 1 + if rounds is None or count < rounds: + sleep(interval) + + +def pid_file(state_dir): + return Path(state_dir) / 'scope-sync.pid' + + +def is_watcher(pid, ps=None): + """True when `pid` is a live scope_sync watcher (not a recycled pid).""" + ps = ps or (lambda p: subprocess.run(['ps', '-p', str(p), '-o', 'command='], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode()) + try: + command = ps(pid) + except OSError: + return False + return 'scope_sync.py' in command and ' watch' in command + + +def ensure(stack_dir, state_dir, interval=DEFAULT_INTERVAL, spawn=subprocess.Popen, ps=None): + """Start a detached watcher unless one is already running for this state dir. Returns 'running' or 'started'.""" + state_dir = Path(state_dir) + state_dir.mkdir(parents=True, exist_ok=True) + pidfile = pid_file(state_dir) + try: + with installer_lock(stack_dir) as updater: + try: + pid = int(pidfile.read_text().strip()) + except (OSError, ValueError): + pid = None + if pid and is_watcher(pid, ps): + return 'running' + with open(state_dir / 'scope-sync.log', 'ab') as log: + process = spawn([sys.executable, str(Path(__file__).resolve()), 'watch', '--stack-dir', str(stack_dir), '--interval', str(interval)], + stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True) + updater.durable_bytes(pidfile, str(process.pid).encode(), 0o600) + return 'started' + except ScopeSyncBusy: + # An installer activation owns the same lock; its following renew or + # install will call ensure again after the activation completes. + return 'busy' + + +def stop(state_dir): + try: + pid = int(pid_file(state_dir).read_text().strip()) + except (OSError, ValueError): + return False + if is_watcher(pid): + os.kill(pid, signal.SIGTERM) + return True + return False + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('command', choices=['once', 'watch', 'ensure', 'stop']) + parser.add_argument('--stack-dir') + parser.add_argument('--state-dir', help='where the pid file and log live (ensure/stop)') + parser.add_argument('--interval', type=int, default=DEFAULT_INTERVAL) + args = parser.parse_args() + if args.interval < 5: + parser.error('--interval must be at least 5 seconds') + if args.command == 'stop': + print('stopped' if stop(args.state_dir) else 'not running') + return 0 + if not args.stack_dir: + parser.error('--stack-dir is required') + if args.command == 'once': + ok, output = run_once(args.stack_dir) + print(output) + return 0 if ok else 1 + if args.command == 'watch': + watch(args.stack_dir, args.interval, log=lambda line: print(line, flush=True)) + return 0 + if not args.state_dir: + parser.error('--state-dir is required for ensure') + print(ensure(args.stack_dir, args.state_dir, args.interval)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/sign_release.py b/tools/sign_release.py new file mode 100644 index 0000000..679e603 --- /dev/null +++ b/tools/sign_release.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Build and sign the release manifest for a frozen installer payload. + +Signing is the one step that needs the private key, so it lives outside the +managed payload. The manifest lists exactly the files the updater stages, and +is signed as DER ECDSA over SHA-256 of its exact bytes: + + python3 tools/sign_release.py --payload DIR --key release-key.pem \ + --version v1.3.0 --commit <40-hex> [--publisher URL] [--valid-days 30] + +Writes DIR/release-manifest.json and DIR/release-manifest.json.sig. The matching +public key is the trust root that installers receive out of band. +""" +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +REPO = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('tp_update_for_signing', REPO / 'config/native/update.py') +update = importlib.util.module_from_spec(spec) +spec.loader.exec_module(update) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--payload', required=True) + parser.add_argument('--key', required=True, help='ECDSA P-256 private key (PEM)') + parser.add_argument('--version', required=True) + parser.add_argument('--commit', required=True, help='40-hex source commit of the payload') + parser.add_argument('--publisher', default=update.DEFAULT_RELEASE_PUBLISHER) + parser.add_argument('--valid-days', type=int, default=30) + args = parser.parse_args() + payload = Path(args.payload) + with tempfile.TemporaryDirectory() as scratch: + artifacts = [relative for relative, _ in update.Transaction(Path(scratch)).artifacts] + files = [] + for relative in sorted(artifacts): + source = payload / relative + if source.is_symlink() or not source.is_file(): + sys.exit('payload is missing a managed file: ' + relative) + data = source.read_bytes() + files.append({'path': relative, 'sha256': hashlib.sha256(data).hexdigest(), 'size': len(data)}) + now = int(time.time()) + release = {'version': args.version, 'publisher': args.publisher, 'commit': args.commit, + 'not_before': now - 60, 'expires_at': now + args.valid_days * 86400} + manifest = json.dumps({'schema': 'thingspanel.release-manifest.v1', 'release': release, 'files': files}, + sort_keys=True).encode() + (payload / update.RELEASE_MANIFEST).write_bytes(manifest) + signature = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', args.key], input=manifest, + stdout=subprocess.PIPE, check=True).stdout + (payload / (update.RELEASE_MANIFEST + '.sig')).write_bytes(signature) + print('signed %d files for %s' % (len(files), args.version)) + + +if __name__ == '__main__': + main() diff --git a/tools/test_plugin_bundle.py b/tools/test_plugin_bundle.py new file mode 100644 index 0000000..584189e --- /dev/null +++ b/tools/test_plugin_bundle.py @@ -0,0 +1,251 @@ +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import plugin_bundle +import plugin_catalog + + +REPO = Path(__file__).resolve().parents[1] +HA_ENTRY = json.loads((REPO / 'plugins/homeassistant.json').read_text(encoding='utf-8')) +PAGES = plugin_bundle.DEFAULT_PAGES_BASE_URL +RELEASE = plugin_bundle.DEFAULT_RELEASE_BASE_URL + + +class PluginBundle(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix='tp-plugin-bundle-test-')) + self.addCleanup(lambda: shutil.rmtree(self.tmp, ignore_errors=True)) + self.stage_parent = self.tmp / 'stage-parent' + self.stage_parent.mkdir(mode=0o700) + self.key = self.tmp / 'signing-key.pem' + self.trust_root = self.tmp / 'trust-root.pem' + subprocess.run(['openssl', 'ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', str(self.key)], + check=True, capture_output=True) + subprocess.run(['openssl', 'pkey', '-in', str(self.key), '-pubout', '-out', str(self.trust_root)], + check=True, capture_output=True) + self.agent = b'linux agent executable fixture' + self.image = b'HA docker image archive fixture' + + def signed_files(self, target='linux/amd64', *, release_tag='plugin-v1.2.3', agent=None, image=None): + agent = self.agent if agent is None else agent + image = self.image if image is None else image + entry = json.loads(json.dumps(HA_ENTRY)) + entry['image_platform'] = target + entry['image_archive_sha256'] = hashlib.sha256(image).hexdigest() + catalog = { + 'schema': plugin_catalog.SCHEMA, + 'version': 'bundle-1', + 'published_at': int(time.time()), + 'expires_at': int(time.time()) + 3600, + 'target_platform': target, + 'release_tag': release_tag, + 'agent_sha256': hashlib.sha256(agent).hexdigest(), + 'plugins': [entry], + } + raw = json.dumps(catalog, sort_keys=True, indent=1).encode() + signature = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', str(self.key)], + input=raw, stdout=subprocess.PIPE, check=True).stdout + assets = { + PAGES + '/plugins/catalog-linux-' + target.split('/')[1] + '.json': raw, + PAGES + '/plugins/catalog-linux-' + target.split('/')[1] + '.json.sig': signature, + RELEASE + '/' + release_tag + '/tp-agent-linux-' + target.split('/')[1]: agent, + RELEASE + '/' + release_tag + '/ha-image-linux-' + target.split('/')[1] + '.tar': image, + } + return catalog, assets + + def fetcher(self, assets, calls): + def fetch(url, destination, max_bytes): + calls.append((url, max_bytes)) + if url not in assets: + raise AssertionError('unexpected asset URL: ' + url) + data = assets[url] + if len(data) > max_bytes: + raise plugin_bundle.PluginBundleError('bundle asset exceeds its configured size limit') + Path(destination).write_bytes(data) + return fetch + + def stage(self, target, assets, calls, **kwargs): + return plugin_bundle.stage_plugin_bundle( + target, trust_root=self.trust_root, stage_parent=self.stage_parent, + downloader=self.fetcher(assets, calls), **kwargs) + + def test_success_stages_both_linux_architectures_without_touching_active_paths(self): + for target in ('linux/amd64', 'linux/arm64'): + with self.subTest(target=target): + catalog, assets = self.signed_files(target) + calls = [] + staged = self.stage(target, assets, calls) + self.assertEqual(staged.catalog['target_platform'], target) + self.assertTrue(staged.agent_path.is_file()) + self.assertTrue(staged.image_archive_path.is_file()) + self.assertEqual(stat.S_IMODE(staged.stage_dir.stat().st_mode), 0o700) + self.assertEqual(staged.agent_path.read_bytes(), self.agent) + self.assertEqual(staged.image_archive_path.read_bytes(), self.image) + self.assertEqual([call[0] for call in calls], list(assets)) + self.assertEqual([path.resolve() for path in self.stage_parent.iterdir()], [staged.stage_dir.resolve()]) + shutil.rmtree(staged.stage_dir) + + def test_bad_signature_stops_before_release_asset_download(self): + _, assets = self.signed_files() + sig_url = PAGES + '/plugins/catalog-linux-amd64.json.sig' + assets[sig_url] = b'not a signature' + calls = [] + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'signature or schema'): + self.stage('linux/amd64', assets, calls) + self.assertEqual(len(calls), 2) + self.assertEqual(list(self.stage_parent.iterdir()), []) + + def test_architecture_mismatch_stops_before_release_assets(self): + _, assets = self.signed_files('linux/arm64') + assets[PAGES + '/plugins/catalog-linux-amd64.json'] = assets.pop(PAGES + '/plugins/catalog-linux-arm64.json') + assets[PAGES + '/plugins/catalog-linux-amd64.json.sig'] = assets.pop(PAGES + '/plugins/catalog-linux-arm64.json.sig') + calls = [] + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'target platform'): + self.stage('linux/amd64', assets, calls) + self.assertEqual(len(calls), 2) + self.assertEqual(list(self.stage_parent.iterdir()), []) + + def test_release_tag_path_injection_is_rejected_before_release_assets(self): + _, assets = self.signed_files(release_tag='../evil') + calls = [] + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'signature or schema'): + self.stage('linux/amd64', assets, calls) + self.assertEqual(len(calls), 2) + + def test_agent_tampering_is_rejected_before_image_download(self): + _, assets = self.signed_files() + agent_url = RELEASE + '/plugin-v1.2.3/tp-agent-linux-amd64' + assets[agent_url] = b'changed Agent' + calls = [] + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'Agent binary digest'): + self.stage('linux/amd64', assets, calls) + self.assertEqual(len(calls), 3) + self.assertEqual(list(self.stage_parent.iterdir()), []) + + def test_image_archive_tampering_is_rejected(self): + _, assets = self.signed_files() + image_url = RELEASE + '/plugin-v1.2.3/ha-image-linux-amd64.tar' + assets[image_url] = b'changed image archive' + calls = [] + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'image archive digest'): + self.stage('linux/amd64', assets, calls) + self.assertEqual(len(calls), 4) + self.assertEqual(list(self.stage_parent.iterdir()), []) + + def test_active_bundle_accepts_signed_expired_catalog_but_rejects_tampering(self): + _, assets = self.signed_files() + staged = self.stage('linux/amd64', assets, []) + root = plugin_bundle.arrange_staged_bundle(staged) + catalog_path = root / 'plugins/plugin-catalog.json' + signature_path = root / 'plugins/plugin-catalog.json.sig' + catalog = json.loads(catalog_path.read_bytes()) + catalog['expires_at'] = int(time.time()) - 1 + raw = json.dumps(catalog, sort_keys=True, indent=1).encode() + catalog_path.write_bytes(raw) + signature_path.write_bytes(subprocess.run(['openssl', 'dgst', '-sha256', '-sign', str(self.key)], + input=raw, stdout=subprocess.PIPE, check=True).stdout) + with self.assertRaisesRegex(ValueError, 'expired'): + plugin_catalog.load_verified(catalog_path, self.trust_root) + self.assertEqual(plugin_bundle.verify_active_bundle(root, self.trust_root, 'linux/amd64'), catalog) + (root / 'bin/tp-agent').write_bytes(b'tampered') + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'digest mismatch'): + plugin_bundle.verify_active_bundle(root, self.trust_root, 'linux/amd64') + (root / 'bin/tp-agent').write_bytes(self.agent) + (root / 'plugins/homeassistant-image.tar').write_bytes(b'tampered') + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'digest mismatch'): + plugin_bundle.verify_active_bundle(root, self.trust_root, 'linux/amd64') + (root / 'plugins/homeassistant-image.tar').write_bytes(self.image) + signature_path.write_bytes(b'tampered') + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'signature or schema'): + plugin_bundle.verify_active_bundle(root, self.trust_root, 'linux/amd64') + + def test_active_bundle_rejects_symlinked_assets(self): + _, assets = self.signed_files() + root = plugin_bundle.arrange_staged_bundle(self.stage('linux/amd64', assets, [])) + agent = root / 'bin/tp-agent' + agent.unlink() + agent.symlink_to(self.tmp / 'external-agent') + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'invalid asset'): + plugin_bundle.verify_active_bundle(root, self.trust_root, 'linux/amd64') + + def test_size_limit_rejected_and_private_stage_removed(self): + _, assets = self.signed_files() + calls = [] + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'size limit'): + self.stage('linux/amd64', assets, calls, max_agent_bytes=8) + self.assertEqual(len(calls), 3) + self.assertEqual(list(self.stage_parent.iterdir()), []) + + def test_streaming_downloader_enforces_limit_without_content_length(self): + class Response: + headers = {} + + def __init__(self): + self.data = [b'1234', b'5678', b''] + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def geturl(self): + return 'https://install.thingspanel.io/asset' + + def read(self, size): + return self.data.pop(0) + + dest = self.tmp / 'oversize' + with mock.patch.object(plugin_bundle, 'urlopen', return_value=Response()): + with self.assertRaisesRegex(plugin_bundle.PluginBundleError, 'size limit'): + plugin_bundle._download_stream('https://install.thingspanel.io/asset', dest, 5) + self.assertFalse(dest.exists()) + + def test_publish_adds_optional_bundle_metadata_and_legacy_catalogs_remain_valid(self): + plugin_file = self.tmp / 'ha.json' + publish_entry = json.loads(json.dumps(HA_ENTRY)) + publish_entry['image_platform'] = 'linux/amd64' + plugin_file.write_text(json.dumps(publish_entry), encoding='utf-8') + out = self.tmp / 'published' + args = argparse.Namespace(key=str(self.key), out=str(out), version='bundle-1', valid_days=2, + plugin_file=[str(plugin_file)], target_platform='linux/amd64', + release_tag='plugin-v1.2.3', agent_sha256=hashlib.sha256(self.agent).hexdigest()) + plugin_catalog.publish(args) + verified = plugin_catalog.load_verified(out / 'plugin-catalog.json', self.trust_root) + self.assertEqual(verified['target_platform'], 'linux/amd64') + self.assertEqual(verified['release_tag'], 'plugin-v1.2.3') + self.assertEqual(verified['agent_sha256'], hashlib.sha256(self.agent).hexdigest()) + + legacy = self.tmp / 'legacy' + legacy.mkdir() + legacy_args = argparse.Namespace(key=str(self.key), out=str(legacy), version='legacy', valid_days=2, + plugin_file=[str(plugin_file)]) + plugin_catalog.publish(legacy_args) + old = plugin_catalog.load_verified(legacy / 'plugin-catalog.json', self.trust_root) + self.assertNotIn('target_platform', old) + + def test_publish_metadata_arguments_are_all_or_none_and_path_safe(self): + for metadata in ( + ('linux/amd64', None, 'a' * 64), + ('linux/other', 'plugin-v1.2.3', 'a' * 64), + ('linux/amd64', '../escape', 'a' * 64), + ('linux/amd64', 'plugin-v1.2.3', 'A' * 64), + ): + with self.subTest(metadata=metadata): + with self.assertRaises(ValueError): + plugin_catalog.validate_bundle_metadata(*metadata) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_plugin_install.py b/tools/test_plugin_install.py new file mode 100644 index 0000000..fc8ebb2 --- /dev/null +++ b/tools/test_plugin_install.py @@ -0,0 +1,195 @@ +import json +import importlib.util +import os +from pathlib import Path +import shutil +import sys +import tempfile +import threading +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import plugin_catalog # noqa: E402 +import plugin_install as pi # noqa: E402 + +PLUGINS = Path(__file__).resolve().parents[1] / 'plugins' + + +def entry(name): + return json.loads((PLUGINS / (name + '.json')).read_text()) + + +def generic_user_entry(): + """Test generic installer fields without making HA credentials install-time inputs.""" + value = entry('homeassistant') + value['env_user'] = { + 'TEST_BASE_URL': {'required': True, 'secret': False, 'validate': 'url'}, + 'TEST_ACCESS_TOKEN': {'required': True, 'secret': True}, + } + return value + + +class UserEnv(unittest.TestCase): + def test_set_and_secret_from_environment(self): + with mock.patch.dict(os.environ, {'TEST_ACCESS_TOKEN': 'tok-123'}): + got = pi.collect_user_env(generic_user_entry(), ['TEST_BASE_URL=http://ha.local:8123'], False) + self.assertEqual(got, {'TEST_BASE_URL': 'http://ha.local:8123', 'TEST_ACCESS_TOKEN': 'tok-123'}) + + def test_secret_refused_on_command_line(self): + with self.assertRaisesRegex(RuntimeError, 'secret'): + pi.collect_user_env(generic_user_entry(), ['TEST_ACCESS_TOKEN=x'], False) + + def test_missing_required_noninteractive_fails_without_echoing_values(self): + with mock.patch.dict(os.environ, {}, clear=True): + with self.assertRaisesRegex(RuntimeError, 'TEST_BASE_URL is required'): + pi.collect_user_env(generic_user_entry(), [], False) + + def test_url_validation(self): + with mock.patch.dict(os.environ, {'TEST_ACCESS_TOKEN': 'x'}): + with self.assertRaisesRegex(RuntimeError, 'http'): + pi.collect_user_env(generic_user_entry(), ['TEST_BASE_URL=ftp://nope'], False) + + def test_newline_rejected(self): + with mock.patch.dict(os.environ, {'TEST_ACCESS_TOKEN': 'a\nB=c'}): + with self.assertRaisesRegex(RuntimeError, 'single line'): + pi.collect_user_env(generic_user_entry(), ['TEST_BASE_URL=http://h'], False) + + def test_prompt_hides_secret(self): + with mock.patch.dict(os.environ, {}, clear=True), mock.patch('builtins.input', return_value='http://h:1') as inp, \ + mock.patch('getpass.getpass', return_value='sekret') as gp: + got = pi.collect_user_env(generic_user_entry(), [], True) + self.assertEqual(got['TEST_ACCESS_TOKEN'], 'sekret') + inp.assert_called_once() + gp.assert_called_once() + self.assertNotIn('sekret', gp.call_args[0][0]) + + def test_homeassistant_install_has_no_ha_credentials(self): + self.assertEqual(entry('homeassistant').get('env_user', {}), {}) + + +class Identity(unittest.TestCase): + def test_with_identity_replaces_and_does_not_mutate(self): + e = entry('http-adapter') + profile = {'env': ['A=1', 'P_PLATFORM_API_TOKEN=old', 'TP_PLUGIN_SERVICE_IDENTIFIER=old']} + out = pi.with_identity(profile, e, 'pri_x.y') + self.assertEqual(out['env'], ['A=1', 'P_PLATFORM_API_TOKEN=pri_x.y', 'TP_PLUGIN_SERVICE_IDENTIFIER=HTTP']) + self.assertEqual(profile['env'][1], 'P_PLATFORM_API_TOKEN=old') + + def test_default_token_env_and_service(self): + e = entry('homeassistant') + self.assertEqual(pi.token_env_of(e), 'TP_PLUGIN_RUNTIME_TOKEN') + self.assertEqual(pi.service_identifier(e), 'homeassistant') + self.assertEqual(pi.binding_of(e), 'none') + self.assertEqual(pi.binding_of(entry('http-adapter')), 'template') + + +class WatcherStartup(unittest.TestCase): + def test_busy_lock_is_retried_after_overlapping_installer_finishes(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + stack = root / 'stack' + native = stack / 'config/native' + native.mkdir(parents=True) + shutil.copyfile(Path(__file__).resolve().parents[1] / 'config/native/update.py', native / 'update.py') + agent_dir = root / 'agent' + state = stack / '.thingspanel-update' + updater_spec = importlib.util.spec_from_file_location('test_watcher_update', native / 'update.py') + updater = importlib.util.module_from_spec(updater_spec) + updater_spec.loader.exec_module(updater) + updater.private_directory(state) + + lock_ready, release_lock = threading.Event(), threading.Event() + + def hold_update_lock(): + with updater.update_lock(state): + lock_ready.set() + release_lock.wait(2) + + holder = threading.Thread(target=hold_update_lock) + holder.start() + self.assertTrue(lock_ready.wait(2)) + real_ensure = pi.scope_sync.ensure + spawned = [] + + class Process: + pid = 4242 + + def spawn(_cmd, **_kwargs): + spawned.append(True) + return Process() + + with mock.patch.object(pi.scope_sync, 'ensure', side_effect=lambda s, a: real_ensure( + s, a, spawn=spawn, ps=lambda _pid: 'python3 scope_sync.py watch')): + def release_after_busy(_interval): + release_lock.set() + holder.join(2) + + status = pi.ensure_scope_watcher(stack, agent_dir, attempts=3, interval=0, sleep=release_after_busy) + holder.join(2) + self.assertEqual(status, 'started') + self.assertEqual(len(spawned), 1) + self.assertEqual((agent_dir / 'scope-sync.pid').read_text(), '4242') + + def test_install_or_renew_does_not_succeed_if_watcher_remains_busy(self): + with mock.patch.object(pi.scope_sync, 'ensure', return_value='busy') as ensure, \ + mock.patch('builtins.print'): + with self.assertRaisesRegex(RuntimeError, 'watcher was not started'): + pi.ensure_scope_watcher('/stack', '/agent', attempts=2, interval=0, sleep=lambda _seconds: None) + self.assertEqual(ensure.call_count, 2) + + +class ServicePlugin(unittest.TestCase): + def test_alias_is_stable(self): + self.assertEqual(pi.network_alias(entry('homeassistant')), 'tp-plugin-homeassistant') + + def test_registration_lives_in_the_platform_not_in_this_tool(self): + # One implementation: the platform's plugin installation engine registers service plugins. + for name in ('ensure_service_plugin', 'list_service_plugins', 'service_plugin_config'): + self.assertFalse(hasattr(pi, name), name) + + def test_catalog_rejects_bad_alias_and_template_service_plugin(self): + e = entry('homeassistant') + e['platform']['network_alias'] = 'Bad_Alias' + with self.assertRaises(ValueError): + plugin_catalog.check_entry(e) + h = entry('http-adapter') + h['platform']['service_plugin'] = {'name': 'x', 'config': {}} + with self.assertRaises(ValueError): + plugin_catalog.check_entry(h) + + +class CatalogChecks(unittest.TestCase): + def test_both_entries_valid(self): + for name in ('homeassistant', 'http-adapter'): + plugin_catalog.check_entry(entry(name)) + + def test_homeassistant_archive_digest_must_be_lowercase_sha256(self): + for digest in ('', 'a' * 63, 'A' * 64, 'g' * 64): + with self.subTest(digest=digest): + e = entry('homeassistant') + e['image_archive_sha256'] = digest + with self.assertRaises(ValueError): + plugin_catalog.check_entry(e) + + def test_bad_binding_rejected(self): + e = entry('homeassistant') + e['platform']['binding'] = 'bogus' + with self.assertRaises(ValueError): + plugin_catalog.check_entry(e) + + def test_none_needs_service_identifier(self): + e = entry('homeassistant') + del e['platform']['service_identifier'] + with self.assertRaises(ValueError): + plugin_catalog.check_entry(e) + + def test_template_needs_fields(self): + e = entry('http-adapter') + del e['platform']['secret_env'] + with self.assertRaises(ValueError): + plugin_catalog.check_entry(e) + + +if __name__ == '__main__': + unittest.main() diff --git a/upgrade.ps1 b/upgrade.ps1 index d12c4c9..a4eb598 100644 --- a/upgrade.ps1 +++ b/upgrade.ps1 @@ -27,6 +27,7 @@ $ErrorActionPreference = "Stop" $REPO = "ThingsPanel/thingspanel-installer" $RAW_BASE = "https://install.thingspanel.io" +$UPDATE_ENGINE_SHA256 = "f371cabfab4d2f5fbb37cc892e5b7e0cfbc9436b7a615d91da67ec341b1291aa" function Write-Info ($m) { Write-Host "[INFO] $m" -ForegroundColor Cyan } function Write-Success ($m) { Write-Host "[OK] $m" -ForegroundColor Green } @@ -34,6 +35,90 @@ function Write-Warn ($m) { Write-Host "[WARN] $m" -ForegroundColor Yellow } function Write-Step ($m) { Write-Host "`n[>>] $m" -ForegroundColor White -BackgroundColor DarkBlue } function Write-Err ($m) { Write-Host "[ERROR] $m" -ForegroundColor Red; throw $m } +function Invoke-SafeUpdate($Directory, $ExpectedVersion) { + $python = Get-Command python3 -ErrorAction SilentlyContinue + $pythonArgs = @() + if (-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue } + if (-not $python) { $python = Get-Command py -ErrorAction SilentlyContinue; $pythonArgs = @('-3') } + if (-not $python) { throw 'Python 3 is required; existing configuration was not changed.' } + & $python.Source @pythonArgs -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' + if ($LASTEXITCODE -ne 0) { throw 'Python 3.8 or newer is required.' } + $engine = Join-Path $Directory 'config/native/update.py' + if ($PSScriptRoot -and (Test-Path (Join-Path $PSScriptRoot 'config/native/update.py'))) { + $engine = Join-Path $PSScriptRoot 'config/native/update.py' + } + $temporary = $null + try { + if (-not (Test-Path -LiteralPath $engine) -or (Get-FileHash -LiteralPath $engine -Algorithm SHA256).Hash.ToLowerInvariant() -ne $UPDATE_ENGINE_SHA256) { + $temporary = Join-Path ([System.IO.Path]::GetTempPath()) ('thingspanel-updater-' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $temporary | Out-Null + $engine = Join-Path $temporary 'update.py' + $client = New-Object System.Net.WebClient + try { $client.DownloadFile("$RAW_BASE/config/native/update.py", $engine) } finally { $client.Dispose() } + if ((Get-FileHash -LiteralPath $engine -Algorithm SHA256).Hash.ToLowerInvariant() -ne $UPDATE_ENGINE_SHA256) { + throw 'Updater digest mismatch; existing configuration was not changed.' + } + } + $arguments = $pythonArgs + @($engine, '--root', $Directory, '--base-url', $RAW_BASE) + if ($ExpectedVersion) { $arguments += @('--expected-version', $ExpectedVersion) } + if ($env:TP_PLUGIN_TRUST_ROOT) { $arguments += @('--plugin-trust-root', $env:TP_PLUGIN_TRUST_ROOT) } + # Signed releases: a trust root is supplied out of band (never from the payload). + if ($env:TP_RELEASE_TRUST_ROOT) { $arguments += @('--release-trust-root', $env:TP_RELEASE_TRUST_ROOT) } + if ($env:TP_REQUIRE_SIGNED_RELEASE -eq '1') { $arguments += @('--require-signed-release') } + if ($env:TP_REVOKED_VERSIONS) { foreach ($revoked in ($env:TP_REVOKED_VERSIONS -split '[,\s]+' | Where-Object { $_ })) { $arguments += @('--revoked-version', $revoked) } } + & $python.Source @arguments + if ($LASTEXITCODE -ne 0) { throw 'Upgrade did not complete. Preserve .thingspanel-update for recovery.' } + } finally { + if ($temporary) { Remove-Item -LiteralPath $temporary -Recurse -Force } + } +} + +function Test-ExistingThingsVisDatabase($Directory) { + if (-not (Test-Path (Join-Path $Directory 'docker-compose.yml'))) { return $true } + Push-Location $Directory + try { + $rendered = & docker compose config --format json 2>$null + if ($LASTEXITCODE -ne 0) { $rendered = & docker compose config --no-interpolate --format json 2>$null } + if ($LASTEXITCODE -ne 0) { return $false } + $configuration = ($rendered -join "`n") | ConvertFrom-Json + $variables = $configuration.services.'thingsvis-server'.environment + if ($variables -is [array]) { + $values = @($variables | Where-Object { $_ -is [string] -and $_.StartsWith('DATABASE_URL=') } | ForEach-Object { $_.Substring(13) }) + if ($values.Count -ne 1) { return $false } + $value = $values[0] + } else { + $value = $variables.DATABASE_URL + } + if (-not ($value -is [string] -and $value -match '^(?i:postgres(?:ql)?):')) { return $false } + $backendVariables = $configuration.services.backend.environment + $backend = @{} + if ($backendVariables -is [array]) { + foreach ($item in $backendVariables) { + if ($item -isnot [string] -or -not $item.Contains('=')) { return $false } + $separator = $item.IndexOf('=') + $key = $item.Substring(0, $separator) + if ($backend.ContainsKey($key)) { return $false } + $backend[$key] = $item.Substring($separator + 1) + } + } elseif ($null -ne $backendVariables) { + foreach ($property in $backendVariables.PSObject.Properties) { $backend[$property.Name] = $property.Value } + } else { return $false } + foreach ($required in @('GOTP_DB_PSQL_HOST','GOTP_DB_PSQL_PORT','GOTP_DB_PSQL_USERNAME','GOTP_DB_PSQL_DBNAME')) { + if (-not $backend.ContainsKey($required) -or [string]::IsNullOrWhiteSpace([string]$backend[$required])) { return $false } + } + if ($backend['GOTP_DB_PSQL_HOST'] -eq 'postgres' -and $null -eq $configuration.services.postgres) { return $false } + $selectors = @('GOTP_DB_PSQL_DBTYPE','GOTP_DB_DRIVER','GOTP_DB_PROVIDER','GOTP_DB_TYPE','DB_DRIVER','DB_PROVIDER','DB_TYPE','DATABASE_TYPE','DATABASE_PROVIDER','DATABASE_DRIVER') + foreach ($key in $backend.Keys) { + $name = ([string]$key).ToUpperInvariant() + $entry = $backend[$key] + if (($name.StartsWith('GOTP_DB_MYSQL_') -or $name.StartsWith('GOTP_DB_MARIADB_')) -and $null -ne $entry -and [string]$entry -ne '') { return $false } + if ($selectors -contains $name -and @('postgres','postgresql','pg') -notcontains ([string]$entry).ToLowerInvariant()) { return $false } + if ($name -eq 'DATABASE_URL' -and ($entry -isnot [string] -or $entry -notmatch '^(?i:postgres(?:ql)?):')) { return $false } + } + return $true + } catch { return $false } finally { Pop-Location } +} + Write-Host "" Write-Host " ThingsPanel All-in-One Upgrader (Windows)" -ForegroundColor White Write-Host "" @@ -46,6 +131,9 @@ if (-not (Test-Path $ComposeFile)) { if (-not (Get-Command "docker" -ErrorAction SilentlyContinue)) { Write-Err "Docker not found. Please start Docker Desktop and try again." } +if (-not (Test-ExistingThingsVisDatabase $InstallDir)) { + Write-Err "Cannot confirm that the existing backend and ThingsVis use supported PostgreSQL configurations; existing configuration was not changed." +} if (-not $TargetVersion) { try { @@ -59,28 +147,6 @@ if (-not $TargetVersion) { } Write-Info "Target version: $TargetVersion" -Write-Step "Backing up config" -$backup = "$ComposeFile.bak.$(Get-Date -Format 'yyyyMMddHHmmss')" -Copy-Item $ComposeFile $backup -Write-Success "Backed up to: $backup" - -Write-Step "Downloading new config" -$client = New-Object System.Net.WebClient -$client.Headers.Add("User-Agent", "ThingsPanel-Upgrader") -$client.DownloadFile("$RAW_BASE/docker-compose.yml", "$ComposeFile") -$client.DownloadFile("$RAW_BASE/upgrade.ps1", "$InstallDir\upgrade.ps1") -$client.DownloadFile("$RAW_BASE/uninstall.ps1", "$InstallDir\uninstall.ps1") -Write-Success "Config files updated" - -Write-Step "Pulling new images" -docker compose pull --quiet -if ($LASTEXITCODE -ne 0) { Write-Err "Image pull failed" } -Write-Success "Images pulled" - -Write-Step "Restarting services" -Set-Location $InstallDir -docker compose up -d --wait --timeout 180 -if ($LASTEXITCODE -ne 0) { - Write-Err "Failed to start. View logs: docker compose -f `"$ComposeFile`" logs" -} +Write-Step "Staging and validating the complete installer payload" +Invoke-SafeUpdate $InstallDir $TargetVersion Write-Success "Upgrade complete! Version: $TargetVersion" diff --git a/upgrade.sh b/upgrade.sh index 4b4ae4c..c1a5f99 100755 --- a/upgrade.sh +++ b/upgrade.sh @@ -9,6 +9,7 @@ set -euo pipefail INSTALL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO="ThingsPanel/thingspanel-installer" RAW_BASE="https://install.thingspanel.io" +UPDATE_ENGINE_SHA256="f371cabfab4d2f5fbb37cc892e5b7e0cfbc9436b7a615d91da67ec341b1291aa" RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m' BLUE='\033[0;34m'; BOLD='\033[1m'; RESET='\033[0m' @@ -19,10 +20,109 @@ warn() { echo -e "${YELLOW}[WARN]${RESET} $*"; } error() { echo -e "${RED}[ERROR]${RESET} $*" >&2; exit 1; } step() { echo -e "\n${BOLD}▶ $*${RESET}"; } +run_safe_update() { + command -v python3 >/dev/null 2>&1 || error "升级需要 Python 3;现有配置未修改。" + python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' || error "升级需要 Python 3.8 或更新版本;现有配置未修改。" + local engine="$INSTALL_DIR/config/native/update.py" temporary="" + if [ -f "$engine" ] && python3 - "$engine" "$UPDATE_ENGINE_SHA256" <<'PY' +import hashlib, pathlib, sys +sys.exit(0 if hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest() == sys.argv[2] else 1) +PY + then + : + else + temporary="$(mktemp -d "${TMPDIR:-/tmp}/thingspanel-updater.XXXXXX")" + engine="$temporary/update.py" + if command -v curl >/dev/null 2>&1; then + curl -fsSL --connect-timeout 15 --max-time 180 "$RAW_BASE/config/native/update.py" -o "$engine" || { rm -rf "$temporary"; error "更新器下载失败;现有配置未修改。"; } + elif command -v wget >/dev/null 2>&1; then + wget -q --timeout=180 -O "$engine" "$RAW_BASE/config/native/update.py" || { rm -rf "$temporary"; error "更新器下载失败;现有配置未修改。"; } + else + rm -rf "$temporary" + error "需要 curl 或 wget;现有配置未修改。" + fi + if ! python3 - "$engine" "$UPDATE_ENGINE_SHA256" <<'PY' +import hashlib, pathlib, sys +sys.exit(0 if hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest() == sys.argv[2] else 1) +PY + then + rm -rf "$temporary" + error "更新器内容与本入口固定摘要不一致;现有配置未修改。" + fi + fi + local args=(--root "$INSTALL_DIR" --base-url "$RAW_BASE" --expected-version "$TARGET_VERSION") + if [ -n "${TP_PLUGIN_TRUST_ROOT:-}" ]; then args+=(--plugin-trust-root "$TP_PLUGIN_TRUST_ROOT"); fi + # Signed releases: a trust root is supplied out of band (never from the payload). + if [ -n "${TP_RELEASE_TRUST_ROOT:-}" ]; then args+=(--release-trust-root "$TP_RELEASE_TRUST_ROOT"); fi + if [ "${TP_REQUIRE_SIGNED_RELEASE:-}" = "1" ]; then args+=(--require-signed-release); fi + if [ -n "${TP_REVOKED_VERSIONS:-}" ]; then + for revoked in ${TP_REVOKED_VERSIONS//,/ }; do args+=(--revoked-version "$revoked"); done + fi + if ! python3 "$engine" "${args[@]}"; then + [ -z "$temporary" ] || rm -rf "$temporary" + error "升级未完成;请保留 .thingspanel-update 中的恢复记录。" + fi + [ -z "$temporary" ] || rm -rf "$temporary" +} + +check_existing_thingsvis_database() { + command -v python3 >/dev/null 2>&1 || error "检查已有安装的数据源需要 Python 3;旧配置未修改。" + python3 - "$INSTALL_DIR/docker-compose.yml" <<'PY' || error "无法读取已有 Compose 配置;旧配置未修改。" +import os, stat, sys +try: + path = sys.argv[1] + if not stat.S_ISREG(os.lstat(path).st_mode): raise ValueError('not a regular file') + with open(path, 'rb') as stream: stream.read(1) +except (OSError, ValueError): + sys.exit(1) +PY + if ! (set -o pipefail; cd "$INSTALL_DIR" && { rendered=$(docker compose config --format json 2>/dev/null) || rendered=$(docker compose config --no-interpolate --format json 2>/dev/null); } && printf '%s' "$rendered" | python3 -c ' +import json, sys +from urllib.parse import urlsplit + +def environment(value): + if isinstance(value, dict): return value + if isinstance(value, list): + result = {} + for item in value: + if not isinstance(item, str) or "=" not in item: raise ValueError() + key, val = item.split("=", 1) + if key in result: raise ValueError() + result[key] = val + return result + raise ValueError() + +try: + services = json.load(sys.stdin)["services"] + vis = environment(services["thingsvis-server"]["environment"]) + backend = environment(services["backend"]["environment"]) + url = vis.get("DATABASE_URL") + if not isinstance(url, str): raise ValueError() + parsed_url = urlsplit(url) + if parsed_url.scheme not in ("postgres", "postgresql") or not parsed_url.hostname or "$" in parsed_url.hostname: raise ValueError() + required = ("GOTP_DB_PSQL_HOST", "GOTP_DB_PSQL_PORT", "GOTP_DB_PSQL_USERNAME", "GOTP_DB_PSQL_DBNAME") + if any(not isinstance(backend.get(key), (str, int)) or not str(backend[key]).strip() or "$" in str(backend[key]) for key in required): raise ValueError() + if backend["GOTP_DB_PSQL_HOST"] == "postgres" and not isinstance(services.get("postgres"), dict): raise ValueError() + selectors = ("GOTP_DB_PSQL_DBTYPE", "GOTP_DB_DRIVER", "GOTP_DB_PROVIDER", "GOTP_DB_TYPE", "DB_DRIVER", "DB_PROVIDER", "DB_TYPE", "DATABASE_TYPE", "DATABASE_PROVIDER", "DATABASE_DRIVER") + for key, value in backend.items(): + name = str(key).upper() + if name.startswith(("GOTP_DB_MYSQL_", "GOTP_DB_MARIADB_")) and value not in (None, ""): raise ValueError() + if name in selectors and str(value).lower() not in ("postgres", "postgresql", "pg"): raise ValueError() + if name == "DATABASE_URL" and (not isinstance(value, str) or urlsplit(value).scheme not in ("postgres", "postgresql")): raise ValueError() + sys.exit(0) +except Exception: + sys.exit(1) +'); then + error "无法确认已有平台和 ThingsVis 使用受支持的 PostgreSQL 配置;旧配置未修改。" + fi +} + main() { echo -e "${BOLD}ThingsPanel — 升级程序${RESET}" echo "" + check_existing_thingsvis_database + TARGET_VERSION="${1:-}" if [ -z "$TARGET_VERSION" ]; then TARGET_VERSION=$(curl -fsSL \ @@ -34,34 +134,8 @@ main() { fi info "目标版本: $TARGET_VERSION" - step "备份配置文件" - if [ -f "${INSTALL_DIR}/docker-compose.yml" ]; then - cp "${INSTALL_DIR}/docker-compose.yml" "${INSTALL_DIR}/docker-compose.yml.bak.$(date +%Y%m%d%H%M%S)" - fi - success "已备份" - - step "更新配置文件" - curl -fsSL "${RAW_BASE}/docker-compose.yml" -o "${INSTALL_DIR}/docker-compose.yml" - mkdir -p "${INSTALL_DIR}/config/native" - curl -fsSL "${RAW_BASE}/niginx.conf" -o "${INSTALL_DIR}/niginx.conf" - for native_file in prepare.py runtime.encore.json runtime.notification.json tick.sh README.md; do - curl -fsSL "${RAW_BASE}/config/native/${native_file}" -o "${INSTALL_DIR}/config/native/${native_file}" - done - command -v python3 >/dev/null 2>&1 || error "v1.3.0 原生配置准备需要 Python 3" - python3 "${INSTALL_DIR}/config/native/prepare.py" - success "配置文件已更新" - - step "拉取新镜像" - cd "$INSTALL_DIR" - python3 "${INSTALL_DIR}/config/native/prepare.py" --pull - success "镜像拉取完成" - - step "准备数据库和服务配置" - python3 "${INSTALL_DIR}/config/native/prepare.py" --bootstrap --refresh-devices - - step "重启服务" - docker compose up -d --wait --wait-timeout 240 - python3 "${INSTALL_DIR}/config/native/prepare.py" --verify + step "暂存并验证完整配置,随后在同一锁内升级" + run_safe_update success "升级完成!当前版本: $TARGET_VERSION" echo ""