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 { useNavigate } from "react-router-dom"
|
||||||
import { X } from "lucide-react"
|
import { X } from "lucide-react"
|
||||||
import { apiClient } from "@/services/api/client"
|
import { apiClient } from "@/services/api/client"
|
||||||
|
import { useGateway } from "@/services/api/hooks"
|
||||||
|
import { gatewayHost, publicGatewayHost } from "@/lib/labels"
|
||||||
import { Field, TextField } from "./fields"
|
import { Field, TextField } from "./fields"
|
||||||
|
|
||||||
const SELECT =
|
const SELECT =
|
||||||
@@ -40,6 +42,9 @@ export function CreateDeploymentForm({
|
|||||||
}) {
|
}) {
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { data: gateway } = useGateway()
|
||||||
|
const domain = gateway?.domain
|
||||||
|
const publicDomain = gateway?.public_domain
|
||||||
|
|
||||||
const [kind, setKind] = useState<DeploymentKind>(initialKind ?? "service")
|
const [kind, setKind] = useState<DeploymentKind>(initialKind ?? "service")
|
||||||
const [name, setName] = useState(prefill?.name ?? "")
|
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="Port" value={port} onChange={setPort} width="w-32" mono placeholder="9001" />
|
||||||
<TextField label="Health path" value={health} onChange={setHealth} width="w-48" mono />
|
<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">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
<input type="checkbox" checked={proxy} onChange={(e) => setProxy(e.target.checked)} />
|
<input type="checkbox" checked={proxy} onChange={(e) => setProxy(e.target.checked)} />
|
||||||
<span className="font-mono text-[var(--muted)]">
|
<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>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
</Field>
|
</Field>
|
||||||
{proxy && (
|
{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">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
<input type="checkbox" checked={isPublic} onChange={(e) => setIsPublic(e.target.checked)} />
|
<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>
|
<span className="font-mono text-[var(--muted)]">{isPublic ? "public (via tunnel)" : "internal only"}</span>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import type { ServiceDetail } from "@/types"
|
import type { ServiceDetail } from "@/types"
|
||||||
|
import { useGateway } from "@/services/api/hooks"
|
||||||
|
import { gatewayHost, publicGatewayHost } from "@/lib/labels"
|
||||||
import { Field, TextField, FormFooter, useEnvSecrets } from "./fields"
|
import { Field, TextField, FormFooter, useEnvSecrets } from "./fields"
|
||||||
|
|
||||||
interface Props {
|
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). */
|
/** Edit a service's deployment config (run / expose / proxy / env). */
|
||||||
export function ServiceFields({ service, onSave, onDelete }: Props) {
|
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 m = service.manifest
|
||||||
const run = obj(m.run)
|
const run = obj(m.run)
|
||||||
const internal = obj(obj(obj(m.expose).http).internal)
|
const internal = obj(obj(obj(m.expose).http).internal)
|
||||||
@@ -80,7 +85,9 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
|||||||
try {
|
try {
|
||||||
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
|
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
|
||||||
delete config.id
|
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.
|
// Rebuild the run block for the chosen launcher, preserving other fields.
|
||||||
config.run = applyLauncher(obj(config.run), launcher, runProgram)
|
config.run = applyLauncher(obj(config.run), launcher, runProgram)
|
||||||
@@ -96,7 +103,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} 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.
|
// reach needs a port to route through the gateway; without one it's off.
|
||||||
config.reach = port ? reach : "off"
|
config.reach = port ? reach : "off"
|
||||||
@@ -146,7 +153,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
|||||||
{isTcp ? (
|
{isTcp ? (
|
||||||
<Field
|
<Field
|
||||||
label="Exposure"
|
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 className="font-mono text-xs text-[var(--muted)] space-y-1">
|
||||||
<div>
|
<div>
|
||||||
@@ -162,7 +169,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
|||||||
<div>
|
<div>
|
||||||
reach{" "}
|
reach{" "}
|
||||||
<span className="text-[var(--fg)]">{String(m.reach ?? "internal")}</span> —{" "}
|
<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>
|
||||||
</div>
|
</div>
|
||||||
</Field>
|
</Field>
|
||||||
@@ -188,7 +195,7 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
|||||||
/>
|
/>
|
||||||
<Field
|
<Field
|
||||||
label="Reach"
|
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">
|
<div className="flex items-center gap-2">
|
||||||
<select
|
<select
|
||||||
@@ -207,8 +214,8 @@ export function ServiceFields({ service, onSave, onDelete }: Props) {
|
|||||||
: reach === "off"
|
: reach === "off"
|
||||||
? "host:port only"
|
? "host:port only"
|
||||||
: reach === "public"
|
: reach === "public"
|
||||||
? `${service.id}.<gateway.public_domain>`
|
? publicGatewayHost(service.id, publicDomain)
|
||||||
: `${service.id}.<gateway.domain>`}
|
: gatewayHost(service.id, domain)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</Field>
|
</Field>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import type { DeploymentDetail } from "@/types"
|
import type { DeploymentDetail } from "@/types"
|
||||||
|
import { useGateway } from "@/services/api/hooks"
|
||||||
|
import { gatewayHost, publicGatewayHost } from "@/lib/labels"
|
||||||
import { Field, TextField, FormFooter, useEnvSecrets } from "./fields"
|
import { Field, TextField, FormFooter, useEnvSecrets } from "./fields"
|
||||||
|
|
||||||
interface Props {
|
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
|
/** 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. */
|
* also public (via the tunnel), a description, and env. No launcher/port/schedule. */
|
||||||
export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
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 m = dep.manifest
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [saved, setSaved] = useState(false)
|
const [saved, setSaved] = useState(false)
|
||||||
@@ -33,7 +38,8 @@ export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
|||||||
try {
|
try {
|
||||||
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
|
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
|
||||||
delete config.id
|
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.root = root || "dist"
|
||||||
config.reach = isPublic ? "public" : "internal"
|
config.reach = isPublic ? "public" : "internal"
|
||||||
delete config.public
|
delete config.public
|
||||||
@@ -62,7 +68,7 @@ export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
|||||||
/>
|
/>
|
||||||
<Field
|
<Field
|
||||||
label="Reach"
|
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">
|
<div className="flex items-center gap-2">
|
||||||
<select
|
<select
|
||||||
@@ -74,7 +80,7 @@ export function StaticFields({ static_: dep, onSave, onDelete }: Props) {
|
|||||||
<option value="public">public</option>
|
<option value="public">public</option>
|
||||||
</select>
|
</select>
|
||||||
<span className="font-mono text-[var(--muted)] text-xs">
|
<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>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</Field>
|
</Field>
|
||||||
|
|||||||
@@ -60,3 +60,18 @@ export function subdomainUrl(subdomain: string): string | null {
|
|||||||
if (labels.length <= 2) return null
|
if (labels.length <= 2) return null
|
||||||
return `${protocol}//${subdomain}.${labels.slice(1).join(".")}`
|
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 (
|
from castle_core.config import (
|
||||||
CastleConfig,
|
CastleConfig,
|
||||||
GatewayConfig,
|
|
||||||
_DEPLOYMENT_ADAPTER,
|
_DEPLOYMENT_ADAPTER,
|
||||||
_normalize_deployment_dict,
|
_normalize_deployment_dict,
|
||||||
_program_to_yaml_dict,
|
_program_to_yaml_dict,
|
||||||
_spec_to_yaml_dict,
|
_spec_to_yaml_dict,
|
||||||
load_config,
|
load_config,
|
||||||
|
parse_gateway,
|
||||||
save_config,
|
save_config,
|
||||||
)
|
)
|
||||||
from castle_core.manifest import ProgramSpec, kind_for
|
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")
|
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")
|
job_count = sum(1 for d in deployments.values() if kind_for(d) == "job")
|
||||||
|
|
||||||
gateway_data = data.get("gateway", {})
|
|
||||||
config = CastleConfig(
|
config = CastleConfig(
|
||||||
root=root,
|
root=root,
|
||||||
repo=repo_path,
|
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,
|
programs=programs,
|
||||||
deployments=deployments,
|
deployments=deployments,
|
||||||
)
|
)
|
||||||
@@ -194,21 +195,32 @@ def save_yaml(request: ConfigSaveRequest) -> ConfigSaveResponse:
|
|||||||
|
|
||||||
@router.put("/programs/{name}")
|
@router.put("/programs/{name}")
|
||||||
def save_program(name: str, request: ProgramConfigRequest) -> dict:
|
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()
|
_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:
|
try:
|
||||||
prog_data = dict(request.config)
|
spec = ProgramSpec.model_validate(merged)
|
||||||
prog_data["id"] = name
|
|
||||||
ProgramSpec.model_validate(prog_data)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
detail=f"Invalid program config: {e}",
|
detail=f"Invalid program config: {e}",
|
||||||
)
|
)
|
||||||
|
|
||||||
config = get_config()
|
config.programs[name] = spec
|
||||||
config.programs[name] = ProgramSpec.model_validate({**request.config, "id": name})
|
|
||||||
save_config(config)
|
save_config(config)
|
||||||
return {"ok": True, "program": name}
|
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:
|
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()
|
_require_repo()
|
||||||
config = get_config()
|
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
|
if name in config.deployments:
|
||||||
# referenced program's description — a deployment reads as its program by
|
base = config.deployments[name].model_dump(mode="json", exclude_none=True)
|
||||||
# default. Edits keep whatever the user set (including a cleared field).
|
merged = {**base, **incoming, "id": name}
|
||||||
if name not in config.deployments and not config_dict.get("description"):
|
# An explicit null means "clear" — drop the key so its default applies.
|
||||||
prog = config_dict.get("program")
|
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:
|
if prog and prog in config.programs and config.programs[prog].description:
|
||||||
config_dict["description"] = config.programs[prog].description
|
merged["description"] = config.programs[prog].description
|
||||||
|
|
||||||
try:
|
try:
|
||||||
dep = _DEPLOYMENT_ADAPTER.validate_python(
|
dep = _DEPLOYMENT_ADAPTER.validate_python(_normalize_deployment_dict(merged))
|
||||||
_normalize_deployment_dict({**config_dict, "id": name})
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
|||||||
@@ -783,13 +783,18 @@ def get_component(name: str) -> DeploymentDetail:
|
|||||||
deployed = registry.deployed[name]
|
deployed = registry.deployed[name]
|
||||||
summary = _summary_from_deployed(name, deployed)
|
summary = _summary_from_deployed(name, deployed)
|
||||||
|
|
||||||
# Backfill source from castle.yaml program ref
|
|
||||||
root = get_castle_root()
|
root = get_castle_root()
|
||||||
if root and summary.source is None:
|
config = None
|
||||||
|
if root:
|
||||||
try:
|
try:
|
||||||
from castle_core.config import load_config
|
from castle_core.config import load_config
|
||||||
|
|
||||||
config = load_config(root)
|
config = load_config(root)
|
||||||
|
except FileNotFoundError:
|
||||||
|
config = None
|
||||||
|
|
||||||
|
# Backfill source from castle.yaml program ref
|
||||||
|
if config and summary.source is None:
|
||||||
if name in config.programs:
|
if name in config.programs:
|
||||||
summary.source = config.programs[name].source
|
summary.source = config.programs[name].source
|
||||||
else:
|
else:
|
||||||
@@ -800,9 +805,14 @@ def get_component(name: str) -> DeploymentDetail:
|
|||||||
ref = config.jobs[name].program
|
ref = config.jobs[name].program
|
||||||
if ref and ref in config.programs:
|
if ref and ref in config.programs:
|
||||||
summary.source = config.programs[ref].source
|
summary.source = config.programs[ref].source
|
||||||
except FileNotFoundError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
# 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 = {
|
raw = {
|
||||||
"manager": deployed.manager,
|
"manager": deployed.manager,
|
||||||
"launcher": deployed.launcher,
|
"launcher": deployed.launcher,
|
||||||
|
|||||||
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()
|
data = response.json()
|
||||||
assert data["id"] == "test-svc"
|
assert data["id"] == "test-svc"
|
||||||
assert "manifest" in data
|
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:
|
def test_not_found(self, client: TestClient) -> None:
|
||||||
"""Returns 404 for unknown component."""
|
"""Returns 404 for unknown component."""
|
||||||
|
|||||||
@@ -347,6 +347,26 @@ def _load_resource_dir(directory: Path) -> dict[str, dict]:
|
|||||||
return result
|
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:
|
def load_config(root: Path | None = None) -> CastleConfig:
|
||||||
"""Load castle config: global castle.yaml + programs/ and deployments/ dirs."""
|
"""Load castle config: global castle.yaml + programs/ and deployments/ dirs."""
|
||||||
if root is None:
|
if root is None:
|
||||||
@@ -359,17 +379,7 @@ def load_config(root: Path | None = None) -> CastleConfig:
|
|||||||
with open(config_path) as f:
|
with open(config_path) as f:
|
||||||
data = yaml.safe_load(f) or {}
|
data = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
gateway_data = data.get("gateway", {})
|
gateway = parse_gateway(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),
|
|
||||||
)
|
|
||||||
|
|
||||||
# repo: field points to the git repo for repo-relative sources
|
# repo: field points to the git repo for repo-relative sources
|
||||||
repo_path: Path | None = None
|
repo_path: Path | None = None
|
||||||
|
|||||||
@@ -248,3 +248,84 @@ class TestResolveEnvSplit:
|
|||||||
flat = resolve_env_vars(env, {"port": "9001"})
|
flat = resolve_env_vars(env, {"port": "9001"})
|
||||||
assert flat == {"PORT": "9001", "K": "v", "Z": "lit"}
|
assert flat == {"PORT": "9001", "K": "v", "Z": "lit"}
|
||||||
assert list(flat.keys()) == ["PORT", "K", "Z"]
|
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