fix(deploy): preserve legacy environment and diagnose prepared plans safely

The old initializer defaults HN_ENVIRONMENT to development, while migration
validation required the literal production and combined database/platform
prerequisites into one opaque error. Preserve supported environment identity
namespaces without editing the live .env; still require PostgreSQL and fixed
HTTPS/WSS endpoints for every existing-server migration. Match supported
boolean spellings and report failing field names without credential values.

Add read-only diagnose for an existing prepared plan so an earlier failed
prepare can be reviewed without deleting or regenerating its keyring. Move
future prerequisite validation before private directory/key generation.

Validation: 253 passed, 3 skipped (real PostgreSQL unavailable), 30 existing
warnings; 40 deployment-tool tests including 11 new compatibility/redaction
cases. Python 3.7 syntax and staged diff checks pass. Actual ECS diagnosis
must still confirm the current failing field; no live config or key changed.
This commit is contained in:
ex_tianzy
2026-11-04 13:59:22 +08:00
parent d3ce0099b7
commit 2657146334
4 changed files with 124 additions and 7 deletions
+57 -7
View File
@@ -15,6 +15,7 @@ import secrets
import shutil
import subprocess
import sys
from urllib.parse import urlsplit
class DeployError(RuntimeError):
@@ -93,6 +94,37 @@ def profiles_from(path):
raise DeployError("invalid product permission profiles; use the product-approved JSON object") from None
def enabled(value):
return str(value).strip().lower() in {"true","1","yes","on"}
def platform_problems(env):
problems = []
if not str(env.get("HN_DATABASE_URL", "")).startswith(("postgresql://","postgres://")):
problems.append("HN_DATABASE_URL: PostgreSQL connection required (value withheld)")
if env.get("HN_ENVIRONMENT") not in {"production","development","test"}:
problems.append("HN_ENVIRONMENT: expected production/development/test; preserve the reviewed environment")
for name in ("HN_FEISHU_ENABLED","HN_OAUTH_ENABLED"):
if not enabled(env.get(name)):
problems.append(name+": must be enabled")
for name,scheme in (("HN_PUBLIC_URL","https"),("HN_ROUTER_URL","wss"),
("HN_FEISHU_API_BASE","https"),("HN_FEISHU_AUTHORIZE_URL","https")):
try:
value = urlsplit(str(env.get(name,"")))
valid = value.scheme == scheme and value.hostname and not value.username and not value.password
except ValueError:
valid = False
if not valid:
problems.append(name+": fixed "+scheme.upper()+" endpoint required (value withheld)")
return problems
def require_platform(env):
problems = platform_problems(env)
if problems:
raise DeployError("broker platform configuration incomplete; "+"; ".join(problems))
def validate_overlay(base, merged, candidate):
old, new = base["services"], merged["services"]
require_services(old)
@@ -128,11 +160,10 @@ def validate_overlay(base, merged, candidate):
or env.get("HN_CREDENTIAL_KEYRING_FILE") != "/run/hainuo-credentials/keyring.json"
or new["router"]["environment"].get("HN_CONNECTOR_INTERNAL_URL") != "http://connector:8000"):
raise DeployError("application/environment or credential routing mismatch")
if (not env.get("HN_DATABASE_URL", "").startswith(("postgresql://","postgres://"))
or env.get("HN_ENVIRONMENT") != "production"
or str(env.get("HN_FEISHU_ENABLED", "")).lower() != "true"
or str(env.get("HN_OAUTH_ENABLED", "")).lower() != "true"):
raise DeployError("broker production platform/database configuration incomplete")
# Old installer initializes HN_ENVIRONMENT=development. Preserve this identity
# namespace rather than silently converting it to production. All modes still
# require PostgreSQL and HTTPS/WSS for this existing-server migration.
require_platform(env)
for key in ("HN_ADMIN_SECRET","HN_INTERNAL_SECRET","HN_FEISHU_APP_SECRET"):
if env["HN_ROUTER_ADMISSION_SECRET"] == env.get(key):
raise DeployError("router admission credential must be independent")
@@ -217,6 +248,7 @@ def prepare(args):
base = run(compose(plan)+["config","--format","json"],True)
if base["services"]["connector"].get("environment",{}).get("HN_CREDENTIAL_MODE","legacy") != "legacy":
raise DeployError("already broker: preserve the existing keyring and migration plan")
require_platform({**base["services"]["connector"].get("environment",{}),"HN_OAUTH_ENABLED":"true"})
output.mkdir(mode=0o700,parents=False)
os.chmod(str(output),0o700)
keyring = {"active_key_id":"initial-v1","keys":{"initial-v1":base64.b64encode(os.urandom(32)).decode("ascii")}}
@@ -269,6 +301,22 @@ def load_plan(root):
return plan
def diagnose(root,plan):
config = run(compose(plan,root/"compose.broker.json")+["config","--format","json"],True)
env = config["services"]["connector"].get("environment",{})
value = env.get("HN_ENVIRONMENT")
print("HN_ENVIRONMENT: "+(value if value in {"production","development","test"} else "missing or invalid"))
print("HN_DATABASE_URL: "+("PostgreSQL configured (value withheld)" if str(env.get("HN_DATABASE_URL","")).startswith(("postgresql://","postgres://")) else "missing or unsupported (value withheld)"))
for name in ("HN_FEISHU_ENABLED","HN_OAUTH_ENABLED"):
print(name+": "+("enabled" if enabled(env.get(name)) else "disabled or missing"))
problems = platform_problems(env)
for problem in problems:
print("CHECK: "+problem)
print("Read-only diagnosis; existing preparation and keys preserved; no container restart.")
if problems:
raise DeployError("review the named fields above; do not paste configuration or regenerate keys")
def check(root, plan, baseline=True):
if os.name != "nt":
if root.stat().st_mode & 0o077:
@@ -367,7 +415,7 @@ def main():
prep.add_argument("--profiles",required=True)
prep.add_argument("--output",required=True)
prep.add_argument("--connector-container",default="hainuo-relay-connector-1")
for name in ("check","build","activate","rollback"):
for name in ("diagnose","check","build","activate","rollback"):
cmd = sub.add_parser(name)
cmd.add_argument("--plan",required=True)
if name == "activate":
@@ -384,7 +432,9 @@ def main():
return
root = Path(args.plan).resolve()
plan = load_plan(root)
if args.action == "check":
if args.action == "diagnose":
diagnose(root,plan)
elif args.action == "check":
check(root,plan)
elif args.action == "build":
build(root,plan)