fix(api): editable-spec detail + PATCH-merge saves + shared gateway parser
Deployment/program edits could silently drop spec fields:
- GET /deployments/{name} served the runtime view (no reach/program/root/expose)
for deployed deployments, so the dashboard round-tripped a lossy manifest and
stripped fields on save (broke astro). Now serves the editable castle.yaml spec
when the deployment is in config.
- _save_deployment and save_program replaced the whole object with client input.
Now shallow-merge over the existing spec (omit = preserve, null = clear), so a
partial/lossy save can't drop untouched fields.
- save_yaml rebuilt GatewayConfig from `port` only, wiping tls/domain/tunnel/
cert_hook on a whole-file save. Now uses a shared parse_gateway() (also used by
load_config) so gateway fields can't drift between the two.
Dashboard forms (ServiceFields/StaticFields) send explicit null to clear, per the
merge contract; adds exposure host-label helpers. Coverage: detail-serves-spec,
save round-trip, partial-patch-preserves, null-clears, program partial-patch,
parse_gateway, and config save/load round-trip.
This commit is contained in:
@@ -3,6 +3,8 @@ import { useQueryClient } from "@tanstack/react-query"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { X } from "lucide-react"
|
||||
import { apiClient } from "@/services/api/client"
|
||||
import { useGateway } from "@/services/api/hooks"
|
||||
import { gatewayHost, publicGatewayHost } from "@/lib/labels"
|
||||
import { Field, TextField } from "./fields"
|
||||
|
||||
const SELECT =
|
||||
@@ -40,6 +42,9 @@ export function CreateDeploymentForm({
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
const { data: gateway } = useGateway()
|
||||
const domain = gateway?.domain
|
||||
const publicDomain = gateway?.public_domain
|
||||
|
||||
const [kind, setKind] = useState<DeploymentKind>(initialKind ?? "service")
|
||||
const [name, setName] = useState(prefill?.name ?? "")
|
||||
@@ -207,16 +212,16 @@ export function CreateDeploymentForm({
|
||||
<>
|
||||
<TextField label="Port" value={port} onChange={setPort} width="w-32" mono placeholder="9001" />
|
||||
<TextField label="Health path" value={health} onChange={setHealth} width="w-48" mono />
|
||||
<Field label="Expose" hint="Route through the gateway at <name>.<gateway.domain>. Off: reachable only at host:port.">
|
||||
<Field label="Expose" hint={`Route through the gateway at ${gatewayHost("<name>", domain)}. Off: reachable only at host:port.`}>
|
||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" checked={proxy} onChange={(e) => setProxy(e.target.checked)} />
|
||||
<span className="font-mono text-[var(--muted)]">
|
||||
{proxy ? `${name || "name"}.<gateway.domain>` : "off (host:port only)"}
|
||||
{proxy ? gatewayHost(name || "name", domain) : "off (host:port only)"}
|
||||
</span>
|
||||
</label>
|
||||
</Field>
|
||||
{proxy && (
|
||||
<Field label="Public" hint="Also publish to the internet via the Cloudflare tunnel at <name>.<gateway.public_domain>.">
|
||||
<Field label="Public" hint={`Also publish to the internet via the Cloudflare tunnel at ${publicGatewayHost("<name>", publicDomain)}.`}>
|
||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" checked={isPublic} onChange={(e) => setIsPublic(e.target.checked)} />
|
||||
<span className="font-mono text-[var(--muted)]">{isPublic ? "public (via tunnel)" : "internal only"}</span>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useState } from "react"
|
||||
import type { ServiceDetail } from "@/types"
|
||||
import { useGateway } from "@/services/api/hooks"
|
||||
import { gatewayHost, publicGatewayHost } from "@/lib/labels"
|
||||
import { Field, TextField, FormFooter, useEnvSecrets } from "./fields"
|
||||
|
||||
interface Props {
|
||||
@@ -38,6 +40,9 @@ function applyLauncher(run: Obj, launcher: string, target: string): Obj {
|
||||
|
||||
/** Edit a service's deployment config (run / expose / proxy / env). */
|
||||
export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
const { data: gateway } = useGateway()
|
||||
const domain = gateway?.domain
|
||||
const publicDomain = gateway?.public_domain
|
||||
const m = service.manifest
|
||||
const run = obj(m.run)
|
||||
const internal = obj(obj(obj(m.expose).http).internal)
|
||||
@@ -80,7 +85,9 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
try {
|
||||
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
|
||||
delete config.id
|
||||
config.description = description || undefined
|
||||
// The API merges (PATCH): omit = preserve, null = clear. So to CLEAR a field
|
||||
// we must send an explicit null, not drop it — otherwise the old value sticks.
|
||||
config.description = description || null
|
||||
|
||||
// Rebuild the run block for the chosen launcher, preserving other fields.
|
||||
config.run = applyLauncher(obj(config.run), launcher, runProgram)
|
||||
@@ -96,7 +103,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
},
|
||||
}
|
||||
} else {
|
||||
delete config.expose
|
||||
config.expose = null // explicit clear (merge: omit would preserve the old port)
|
||||
}
|
||||
// reach needs a port to route through the gateway; without one it's off.
|
||||
config.reach = port ? reach : "off"
|
||||
@@ -146,7 +153,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
{isTcp ? (
|
||||
<Field
|
||||
label="Exposure"
|
||||
hint="A raw-TCP service — reachable by name + port via DNS, not the HTTP gateway. Edit its port/TLS in deployments/<name>.yaml for now."
|
||||
hint={`A raw-TCP service — reachable by name + port via DNS, not the HTTP gateway. Edit its port/TLS in deployments/${service.id}.yaml for now.`}
|
||||
>
|
||||
<div className="font-mono text-xs text-[var(--muted)] space-y-1">
|
||||
<div>
|
||||
@@ -162,7 +169,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
<div>
|
||||
reach{" "}
|
||||
<span className="text-[var(--fg)]">{String(m.reach ?? "internal")}</span> —{" "}
|
||||
{service.id}.<gateway.domain>:{String(tcp.port)}
|
||||
{gatewayHost(service.id, domain)}:{String(tcp.port)}
|
||||
</div>
|
||||
</div>
|
||||
</Field>
|
||||
@@ -188,7 +195,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
/>
|
||||
<Field
|
||||
label="Reach"
|
||||
hint="How far this service is exposed. off: host:port only. internal: <service-name>.<gateway.domain> via the gateway. public: also to the internet via the Cloudflare tunnel."
|
||||
hint={`How far this service is exposed. off: host:port only. internal: ${gatewayHost(service.id, domain)} via the gateway. public: also to the internet via the Cloudflare tunnel.`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
@@ -207,8 +214,8 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
||||
: reach === "off"
|
||||
? "host:port only"
|
||||
: reach === "public"
|
||||
? `${service.id}.<gateway.public_domain>`
|
||||
: `${service.id}.<gateway.domain>`}
|
||||
? publicGatewayHost(service.id, publicDomain)
|
||||
: gatewayHost(service.id, domain)}
|
||||
</span>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useState } from "react"
|
||||
import type { DeploymentDetail } from "@/types"
|
||||
import { useGateway } from "@/services/api/hooks"
|
||||
import { gatewayHost, publicGatewayHost } from "@/lib/labels"
|
||||
import { Field, TextField, FormFooter, useEnvSecrets } from "./fields"
|
||||
|
||||
interface Props {
|
||||
@@ -14,6 +16,9 @@ const obj = (v: unknown): Obj => (v as Obj) ?? {}
|
||||
/** Edit a static (caddy) deployment: the built dir it serves (`root`), whether it's
|
||||
* also public (via the tunnel), a description, and env. No launcher/port/schedule. */
|
||||
export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
||||
const { data: gateway } = useGateway()
|
||||
const domain = gateway?.domain
|
||||
const publicDomain = gateway?.public_domain
|
||||
const m = dep.manifest
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
@@ -33,7 +38,8 @@ export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
||||
try {
|
||||
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
|
||||
delete config.id
|
||||
config.description = description || undefined
|
||||
// Merge (PATCH) semantics: null clears, omit preserves — send null to clear.
|
||||
config.description = description || null
|
||||
config.root = root || "dist"
|
||||
config.reach = isPublic ? "public" : "internal"
|
||||
delete config.public
|
||||
@@ -62,7 +68,7 @@ export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
||||
/>
|
||||
<Field
|
||||
label="Reach"
|
||||
hint="How far this static site is served. internal: <name>.<gateway.domain>. public: also to the internet via the Cloudflare tunnel. (A static site is always served, so there's no 'off'.)"
|
||||
hint={`How far this static site is served. internal: ${gatewayHost(dep.id, domain)}. public: also to the internet via the Cloudflare tunnel. (A static site is always served, so there's no 'off'.)`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
@@ -74,7 +80,7 @@ export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
||||
<option value="public">public</option>
|
||||
</select>
|
||||
<span className="font-mono text-[var(--muted)] text-xs">
|
||||
{isPublic ? `${dep.id}.<gateway.public_domain>` : `${dep.id}.<gateway.domain>`}
|
||||
{isPublic ? publicGatewayHost(dep.id, publicDomain) : gatewayHost(dep.id, domain)}
|
||||
</span>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
@@ -60,3 +60,18 @@ export function subdomainUrl(subdomain: string): string | null {
|
||||
if (labels.length <= 2) return null
|
||||
return `${protocol}//${subdomain}.${labels.slice(1).join(".")}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The concrete host a subdomain is exposed at — `<subdomain>.<domain>` — using
|
||||
* this node's configured gateway domain. Falls back to the literal
|
||||
* `<subdomain>.<gateway.domain>` placeholder only when no domain is configured
|
||||
* (off mode), so hints and previews show real values wherever one exists.
|
||||
*/
|
||||
export function gatewayHost(subdomain: string, domain?: string | null): string {
|
||||
return domain ? `${subdomain}.${domain}` : `${subdomain}.<gateway.domain>`
|
||||
}
|
||||
|
||||
/** Same as {@link gatewayHost}, for the public (Cloudflare tunnel) zone. */
|
||||
export function publicGatewayHost(subdomain: string, publicDomain?: string | null): string {
|
||||
return publicDomain ? `${subdomain}.${publicDomain}` : `${subdomain}.<gateway.public_domain>`
|
||||
}
|
||||
|
||||
@@ -11,12 +11,12 @@ from pydantic import BaseModel
|
||||
|
||||
from castle_core.config import (
|
||||
CastleConfig,
|
||||
GatewayConfig,
|
||||
_DEPLOYMENT_ADAPTER,
|
||||
_normalize_deployment_dict,
|
||||
_program_to_yaml_dict,
|
||||
_spec_to_yaml_dict,
|
||||
load_config,
|
||||
parse_gateway,
|
||||
save_config,
|
||||
)
|
||||
from castle_core.manifest import ProgramSpec, kind_for
|
||||
@@ -173,11 +173,12 @@ def save_yaml(request: ConfigSaveRequest) -> ConfigSaveResponse:
|
||||
svc_count = sum(1 for d in deployments.values() if kind_for(d) == "service")
|
||||
job_count = sum(1 for d in deployments.values() if kind_for(d) == "job")
|
||||
|
||||
gateway_data = data.get("gateway", {})
|
||||
config = CastleConfig(
|
||||
root=root,
|
||||
repo=repo_path,
|
||||
gateway=GatewayConfig(port=gateway_data.get("port", 9000)),
|
||||
# Parse the FULL gateway block (tls/domain/tunnel/cert_hook/…), not just
|
||||
# port — otherwise a whole-file save silently wipes the gateway config.
|
||||
gateway=parse_gateway(data.get("gateway", {})),
|
||||
programs=programs,
|
||||
deployments=deployments,
|
||||
)
|
||||
@@ -194,21 +195,32 @@ def save_yaml(request: ConfigSaveRequest) -> ConfigSaveResponse:
|
||||
|
||||
@router.put("/programs/{name}")
|
||||
def save_program(name: str, request: ProgramConfigRequest) -> dict:
|
||||
"""Update a single program's config in castle.yaml."""
|
||||
"""Update a single program's config in castle.yaml (PATCH semantics).
|
||||
|
||||
Like deployments: the incoming config is shallow-merged over the existing
|
||||
program spec, so a partial save can't drop source/stack/commands/build/… that
|
||||
the client didn't send. Omitted keys are preserved; an explicit ``null`` clears.
|
||||
"""
|
||||
_require_repo()
|
||||
config = get_config()
|
||||
incoming = dict(request.config)
|
||||
|
||||
if name in config.programs:
|
||||
base = config.programs[name].model_dump(mode="json", exclude_none=True)
|
||||
merged = {**base, **incoming, "id": name}
|
||||
merged = {k: v for k, v in merged.items() if v is not None}
|
||||
else:
|
||||
merged = {**incoming, "id": name}
|
||||
|
||||
try:
|
||||
prog_data = dict(request.config)
|
||||
prog_data["id"] = name
|
||||
ProgramSpec.model_validate(prog_data)
|
||||
spec = ProgramSpec.model_validate(merged)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Invalid program config: {e}",
|
||||
)
|
||||
|
||||
config = get_config()
|
||||
config.programs[name] = ProgramSpec.model_validate({**request.config, "id": name})
|
||||
config.programs[name] = spec
|
||||
save_config(config)
|
||||
return {"ok": True, "program": name}
|
||||
|
||||
@@ -271,23 +283,33 @@ async def delete_program(name: str, cascade: bool = False) -> dict:
|
||||
|
||||
|
||||
def _save_deployment(name: str, config_dict: dict) -> dict:
|
||||
"""Validate a deployment (any manager) and persist it to config.deployments."""
|
||||
"""Create/update a deployment (any manager) with PATCH semantics.
|
||||
|
||||
The incoming config is shallow-merged over the existing spec, so a save can
|
||||
never silently drop a field the client didn't send (the astro/postgres bug):
|
||||
a present key replaces wholesale, an **omitted** key is preserved, and an
|
||||
explicit ``null`` clears the key (back to its default). On CREATE there's no
|
||||
base, so the incoming config stands alone.
|
||||
"""
|
||||
_require_repo()
|
||||
config = get_config()
|
||||
config_dict = dict(config_dict)
|
||||
incoming = dict(config_dict)
|
||||
|
||||
# On CREATE (a new deployment) with no description of its own, inherit the
|
||||
# referenced program's description — a deployment reads as its program by
|
||||
# default. Edits keep whatever the user set (including a cleared field).
|
||||
if name not in config.deployments and not config_dict.get("description"):
|
||||
prog = config_dict.get("program")
|
||||
if prog and prog in config.programs and config.programs[prog].description:
|
||||
config_dict["description"] = config.programs[prog].description
|
||||
if name in config.deployments:
|
||||
base = config.deployments[name].model_dump(mode="json", exclude_none=True)
|
||||
merged = {**base, **incoming, "id": name}
|
||||
# An explicit null means "clear" — drop the key so its default applies.
|
||||
merged = {k: v for k, v in merged.items() if v is not None}
|
||||
else:
|
||||
merged = {**incoming, "id": name}
|
||||
# On CREATE with no description, inherit the referenced program's.
|
||||
if not merged.get("description"):
|
||||
prog = merged.get("program")
|
||||
if prog and prog in config.programs and config.programs[prog].description:
|
||||
merged["description"] = config.programs[prog].description
|
||||
|
||||
try:
|
||||
dep = _DEPLOYMENT_ADAPTER.validate_python(
|
||||
_normalize_deployment_dict({**config_dict, "id": name})
|
||||
)
|
||||
dep = _DEPLOYMENT_ADAPTER.validate_python(_normalize_deployment_dict(merged))
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
|
||||
@@ -783,39 +783,49 @@ def get_component(name: str) -> DeploymentDetail:
|
||||
deployed = registry.deployed[name]
|
||||
summary = _summary_from_deployed(name, deployed)
|
||||
|
||||
# Backfill source from castle.yaml program ref
|
||||
root = get_castle_root()
|
||||
if root and summary.source is None:
|
||||
config = None
|
||||
if root:
|
||||
try:
|
||||
from castle_core.config import load_config
|
||||
|
||||
config = load_config(root)
|
||||
if name in config.programs:
|
||||
summary.source = config.programs[name].source
|
||||
else:
|
||||
ref = None
|
||||
if name in config.services:
|
||||
ref = config.services[name].program
|
||||
elif name in config.jobs:
|
||||
ref = config.jobs[name].program
|
||||
if ref and ref in config.programs:
|
||||
summary.source = config.programs[ref].source
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
config = None
|
||||
|
||||
raw = {
|
||||
"manager": deployed.manager,
|
||||
"launcher": deployed.launcher,
|
||||
"run_cmd": deployed.run_cmd,
|
||||
"env": deployed.env,
|
||||
"secret_env_keys": deployed.secret_env_keys,
|
||||
"port": deployed.port,
|
||||
"health_path": deployed.health_path,
|
||||
"subdomain": deployed.subdomain,
|
||||
"managed": deployed.managed,
|
||||
"kind": deployed.kind,
|
||||
"stack": deployed.stack,
|
||||
}
|
||||
# Backfill source from castle.yaml program ref
|
||||
if config and summary.source is None:
|
||||
if name in config.programs:
|
||||
summary.source = config.programs[name].source
|
||||
else:
|
||||
ref = None
|
||||
if name in config.services:
|
||||
ref = config.services[name].program
|
||||
elif name in config.jobs:
|
||||
ref = config.jobs[name].program
|
||||
if ref and ref in config.programs:
|
||||
summary.source = config.programs[ref].source
|
||||
|
||||
# The edit form needs the *editable source spec* (reach/program/root/expose/
|
||||
# defaults), not the runtime view — serve the castle.yaml spec whenever the
|
||||
# deployment is defined there. Fall back to the runtime dict only for a
|
||||
# deployed-but-not-in-config item (e.g. a discovered remote reference).
|
||||
if config and name in config.deployments:
|
||||
raw = config.deployments[name].model_dump(mode="json", exclude_none=True)
|
||||
else:
|
||||
raw = {
|
||||
"manager": deployed.manager,
|
||||
"launcher": deployed.launcher,
|
||||
"run_cmd": deployed.run_cmd,
|
||||
"env": deployed.env,
|
||||
"secret_env_keys": deployed.secret_env_keys,
|
||||
"port": deployed.port,
|
||||
"health_path": deployed.health_path,
|
||||
"subdomain": deployed.subdomain,
|
||||
"managed": deployed.managed,
|
||||
"kind": deployed.kind,
|
||||
"stack": deployed.stack,
|
||||
}
|
||||
return DeploymentDetail(**summary.model_dump(), manifest=raw)
|
||||
|
||||
# Fall back to castle.yaml
|
||||
|
||||
78
castle-api/tests/test_deployment_roundtrip.py
Normal file
78
castle-api/tests/test_deployment_roundtrip.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""Edit-safety tests for the deployment detail + save endpoints.
|
||||
|
||||
These guard the regression that broke astro (and postgres): the detail endpoint
|
||||
served the *runtime view* (no reach/program/root/expose) for a deployed deployment,
|
||||
so the dashboard edit form round-tripped a lossy manifest and stripped spec-only
|
||||
fields on save. The fixtures already have `test-svc` deployed AND defined in
|
||||
castle.yaml (with legacy `proxy: true` → `reach: internal`) — exactly that case.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
class TestDeploymentEditSafety:
|
||||
def test_detail_serves_editable_spec_not_runtime(self, client: TestClient) -> None:
|
||||
"""A deployed deployment that's in castle.yaml serves its EDITABLE SPEC —
|
||||
the shape the edit form consumes (launcher nested under `run`, plus
|
||||
reach/expose) — not the flat runtime view (`run_cmd`, top-level launcher)."""
|
||||
m = client.get("/deployments/test-svc").json()["manifest"]
|
||||
assert m["run"]["launcher"] == "python" # spec shape (nested)
|
||||
assert "run_cmd" not in m # runtime-only key absent
|
||||
assert m.get("reach") == "internal" # normalized from proxy:true
|
||||
assert m["expose"]["http"]["internal"]["port"] == 19000
|
||||
|
||||
def test_save_roundtrip_preserves_spec_fields(self, client: TestClient) -> None:
|
||||
"""GET a deployment's manifest → PUT it back unchanged → GET again: no
|
||||
spec field may be lost. This is the exact round-trip the dashboard does on
|
||||
an edit, and the exact thing that dropped astro's program/root."""
|
||||
before = client.get("/deployments/test-svc").json()["manifest"]
|
||||
resp = client.put("/config/deployments/test-svc", json={"config": before})
|
||||
assert resp.status_code == 200, resp.text
|
||||
after = client.get("/deployments/test-svc").json()["manifest"]
|
||||
for key in ("reach", "expose", "run", "program"):
|
||||
assert after.get(key) == before.get(key), f"{key} lost on save round-trip"
|
||||
|
||||
def test_partial_patch_preserves_untouched_fields(self, client: TestClient) -> None:
|
||||
"""PATCH semantics: sending ONLY the changed field must not drop the rest.
|
||||
This is what makes the astro-class regression structurally impossible —
|
||||
even a client that sends a lossy payload can't nuke fields it omitted."""
|
||||
before = client.get("/deployments/test-svc").json()["manifest"]
|
||||
resp = client.put("/config/deployments/test-svc", json={"config": {"reach": "off"}})
|
||||
assert resp.status_code == 200, resp.text
|
||||
after = client.get("/deployments/test-svc").json()["manifest"]
|
||||
assert after["reach"] == "off" # the change applied
|
||||
assert after["program"] == before["program"] # untouched → preserved
|
||||
assert after["run"] == before["run"]
|
||||
assert after["expose"] == before["expose"]
|
||||
|
||||
def test_explicit_null_clears_a_field(self, client: TestClient) -> None:
|
||||
"""An explicit null clears a field — so a form can still *remove* exposure
|
||||
under merge semantics (omit = preserve, null = clear). Removing the port
|
||||
goes with reach: off (a port-only process), which is what ServiceFields
|
||||
sends when the port is cleared."""
|
||||
resp = client.put(
|
||||
"/config/deployments/test-svc",
|
||||
json={"config": {"expose": None, "reach": "off"}},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
after = client.get("/deployments/test-svc").json()["manifest"]
|
||||
assert after.get("expose") is None # cleared
|
||||
assert after["reach"] == "off"
|
||||
assert after["program"] == "test-svc-comp" # rest preserved
|
||||
|
||||
|
||||
class TestProgramEditSafety:
|
||||
def test_program_partial_patch_preserves(self, client: TestClient) -> None:
|
||||
"""save_program is the same footgun: a partial edit must not drop
|
||||
source/commands. Send only a description; the rest survives."""
|
||||
resp = client.put(
|
||||
"/config/programs/wired-in",
|
||||
json={"config": {"description": "renamed"}},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
m = client.get("/programs/wired-in").json()["manifest"]
|
||||
assert m["description"] == "renamed" # change applied
|
||||
assert m["source"].endswith("wired-in") # source preserved
|
||||
assert m["commands"]["lint"] == [["make", "lint"]] # commands preserved
|
||||
@@ -63,7 +63,10 @@ class TestDeploymentDetail:
|
||||
data = response.json()
|
||||
assert data["id"] == "test-svc"
|
||||
assert "manifest" in data
|
||||
assert data["manifest"]["launcher"] == "python"
|
||||
# A deployed deployment that's defined in castle.yaml serves its editable
|
||||
# source spec (launcher nested under `run`), not the runtime view — so the
|
||||
# dashboard edit form gets reach/expose/defaults and can't strip them.
|
||||
assert data["manifest"]["run"]["launcher"] == "python"
|
||||
|
||||
def test_not_found(self, client: TestClient) -> None:
|
||||
"""Returns 404 for unknown component."""
|
||||
|
||||
@@ -347,6 +347,26 @@ def _load_resource_dir(directory: Path) -> dict[str, dict]:
|
||||
return result
|
||||
|
||||
|
||||
def parse_gateway(gateway_data: dict) -> GatewayConfig:
|
||||
"""Build a GatewayConfig from a castle.yaml ``gateway:`` mapping.
|
||||
|
||||
The single parser shared by ``load_config`` and the API's whole-file editor,
|
||||
so a newly added gateway field can't be honored in one place and silently
|
||||
dropped in the other (which is exactly how ``cert_hook`` got wiped on a
|
||||
full-config save).
|
||||
"""
|
||||
return GatewayConfig(
|
||||
port=gateway_data.get("port", 9000),
|
||||
tls=gateway_data.get("tls"),
|
||||
domain=gateway_data.get("domain"),
|
||||
acme_email=gateway_data.get("acme_email"),
|
||||
acme_dns_provider=gateway_data.get("acme_dns_provider", "cloudflare"),
|
||||
public_domain=gateway_data.get("public_domain"),
|
||||
tunnel_id=gateway_data.get("tunnel_id"),
|
||||
cert_hook=gateway_data.get("cert_hook", False),
|
||||
)
|
||||
|
||||
|
||||
def load_config(root: Path | None = None) -> CastleConfig:
|
||||
"""Load castle config: global castle.yaml + programs/ and deployments/ dirs."""
|
||||
if root is None:
|
||||
@@ -359,17 +379,7 @@ def load_config(root: Path | None = None) -> CastleConfig:
|
||||
with open(config_path) as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
|
||||
gateway_data = data.get("gateway", {})
|
||||
gateway = GatewayConfig(
|
||||
port=gateway_data.get("port", 9000),
|
||||
tls=gateway_data.get("tls"),
|
||||
domain=gateway_data.get("domain"),
|
||||
acme_email=gateway_data.get("acme_email"),
|
||||
acme_dns_provider=gateway_data.get("acme_dns_provider", "cloudflare"),
|
||||
public_domain=gateway_data.get("public_domain"),
|
||||
tunnel_id=gateway_data.get("tunnel_id"),
|
||||
cert_hook=gateway_data.get("cert_hook", False),
|
||||
)
|
||||
gateway = parse_gateway(data.get("gateway", {}))
|
||||
|
||||
# repo: field points to the git repo for repo-relative sources
|
||||
repo_path: Path | None = None
|
||||
|
||||
@@ -248,3 +248,84 @@ class TestResolveEnvSplit:
|
||||
flat = resolve_env_vars(env, {"port": "9001"})
|
||||
assert flat == {"PORT": "9001", "K": "v", "Z": "lit"}
|
||||
assert list(flat.keys()) == ["PORT", "K", "Z"]
|
||||
|
||||
|
||||
class TestConfigRoundTrip:
|
||||
"""save_config → load_config must preserve every field. A field missing from
|
||||
the save path (the `cert_hook` regression) or the serializer silently drops on
|
||||
the next write — these lock the full round-trip for the reach/TCP-TLS fields."""
|
||||
|
||||
def test_gateway_and_tcp_tls_survive_save_load(self, tmp_path: Path) -> None:
|
||||
from castle_core.config import GatewayConfig
|
||||
from castle_core.manifest import (
|
||||
ExposeSpec,
|
||||
Reach,
|
||||
RunContainer,
|
||||
SystemdDeployment,
|
||||
TcpExposeSpec,
|
||||
TlsMaterial,
|
||||
TlsSpec,
|
||||
)
|
||||
|
||||
pg = SystemdDeployment(
|
||||
id="pg",
|
||||
manager="systemd",
|
||||
program="pg",
|
||||
reach=Reach.INTERNAL,
|
||||
run=RunContainer(
|
||||
launcher="container",
|
||||
image="postgres:17",
|
||||
user="${uid}:${gid}",
|
||||
tmpfs=["/var/run/postgresql"],
|
||||
),
|
||||
expose=ExposeSpec(
|
||||
tcp=TcpExposeSpec(port=5432, tls=TlsSpec(material=TlsMaterial.PAIR))
|
||||
),
|
||||
)
|
||||
config = CastleConfig(
|
||||
root=tmp_path,
|
||||
gateway=GatewayConfig(
|
||||
port=9000, tls="acme", domain="civil.payne.io", cert_hook=True
|
||||
),
|
||||
repo=None,
|
||||
programs={},
|
||||
deployments={"pg": pg},
|
||||
)
|
||||
save_config(config)
|
||||
loaded = load_config(tmp_path)
|
||||
|
||||
# Gateway: cert_hook must survive (the field that got dropped in prod).
|
||||
assert loaded.gateway.cert_hook is True
|
||||
assert loaded.gateway.tls == "acme"
|
||||
assert loaded.gateway.domain == "civil.payne.io"
|
||||
|
||||
# Deployment: reach + full TCP/TLS + container user/tmpfs must survive.
|
||||
d = loaded.deployments["pg"]
|
||||
assert d.reach == Reach.INTERNAL
|
||||
assert d.expose.tcp.port == 5432
|
||||
assert d.expose.tcp.tls.material == TlsMaterial.PAIR
|
||||
assert d.run.user == "${uid}:${gid}"
|
||||
assert d.run.tmpfs == ["/var/run/postgresql"]
|
||||
|
||||
def test_parse_gateway_preserves_all_fields(self) -> None:
|
||||
"""The shared gateway parser must honor every field — `save_yaml` used to
|
||||
read only `port`, wiping tls/domain/tunnel/cert_hook on a whole-file save."""
|
||||
from castle_core.config import parse_gateway
|
||||
|
||||
g = parse_gateway(
|
||||
{
|
||||
"port": 9000,
|
||||
"tls": "acme",
|
||||
"domain": "civil.payne.io",
|
||||
"acme_email": "a@b.co",
|
||||
"public_domain": "pub.io",
|
||||
"tunnel_id": "uuid-123",
|
||||
"cert_hook": True,
|
||||
}
|
||||
)
|
||||
assert g.tls == "acme"
|
||||
assert g.domain == "civil.payne.io"
|
||||
assert g.acme_email == "a@b.co"
|
||||
assert g.public_domain == "pub.io"
|
||||
assert g.tunnel_id == "uuid-123"
|
||||
assert g.cert_hook is True
|
||||
|
||||
Reference in New Issue
Block a user