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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 86 additions & 6 deletions src/lib/actions/sandbox/rebuild-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -552,11 +552,11 @@ describe("rebuildSandbox flow", () => {
}
});

it("recreates a matching-session custom-endpoint sandbox from session, ignoring hostile ambient endpoint/provider/model (#5735 PRA-4)", async () => {
it("recreates a matching-session custom-endpoint sandbox from a validated session endpoint, ignoring hostile ambient endpoint/provider/model (#5735 PRA-4)", async () => {
// Matching session (sandboxName === target) with a custom endpoint recorded
// in that session. Hostile ambient NEMOCLAW_ENDPOINT_URL/PROVIDER/MODEL must
// be absent during recreate (so onboard --resume uses the session) and the
// session's own recorded endpoint must be preserved (not overwritten).
// be absent during recreate so onboard --resume uses the validated session
// endpoint selected by prepareRebuildResumeConfig.
const restoreEnv = snapshotEnv([
"NEMOCLAW_ENDPOINT_URL",
"NEMOCLAW_PROVIDER",
Expand All @@ -581,8 +581,9 @@ describe("rebuildSandbox flow", () => {
};
},
});
// The custom endpoint lives only in this sandbox's own (matching) session.
harness.session.endpointUrl = "https://my-custom-endpoint.example/v1";
// The custom endpoint lives only in this sandbox's own matching session;
// it is canonicalized at the pre-delete rebuild boundary before rewrite.
harness.session.endpointUrl = "https://my-custom-endpoint.example/v1?x=1#frag";

await expect(
harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }),
Expand All @@ -594,7 +595,6 @@ describe("rebuildSandbox flow", () => {
provider: undefined,
model: undefined,
});
// The matching session's own recorded endpoint is preserved (not pinned/overwritten).
expect(harness.session.endpointUrl).toBe("https://my-custom-endpoint.example/v1");
// Provider/model come from the registry entry, not the ambient values.
expect(harness.session.provider).toBe("compatible-endpoint");
Expand All @@ -608,6 +608,86 @@ describe("rebuildSandbox flow", () => {
}
});

it("overwrites a stale matching-session endpoint with durable registry metadata before onboard --resume (#4497/#5869)", async () => {
const restoreEnv = snapshotEnv(["COMPATIBLE_API_KEY"]);
process.env.COMPATIBLE_API_KEY = "compat-key"; // pass credential preflight
try {
const harness = createRebuildFlowHarness({
applyPreset: () => true,
sandboxEntry: {
provider: "compatible-endpoint",
model: "registry-model",
endpointUrl: "https://registry.example.test/v1?x=1#frag",
},
});
harness.session.endpointUrl = "https://stale-retry.example.test/v1";

await expect(
harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }),
).resolves.toBeUndefined();

expect(harness.onboardSpy).toHaveBeenCalled();
expect(harness.session.endpointUrl).toBe("https://registry.example.test/v1");
expect(harness.runOpenshellSpy).toHaveBeenCalledWith(
["sandbox", "delete", "alpha"],
expect.objectContaining({ ignoreError: true }),
);
} finally {
restoreEnv();
}
});

it("aborts before backup/delete when a matching custom-endpoint session has no recoverable endpoint (#4497/#5869)", async () => {
const restoreEnv = snapshotEnv(["COMPATIBLE_API_KEY"]);
process.env.COMPATIBLE_API_KEY = "compat-key"; // pass credential preflight
try {
const harness = createRebuildFlowHarness({
sandboxEntry: { provider: "compatible-endpoint", model: "custom-model" },
});
delete harness.session.endpointUrl;

await expect(
harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }),
).rejects.toThrow("Cannot validate recreate endpoint");

const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n");
expect(errors).toContain("cannot validate the inference endpoint");
expect(errors).toContain("Sandbox is untouched");
expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled();
expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith(
["sandbox", "delete", "alpha"],
expect.anything(),
);
expect(harness.onboardSpy).not.toHaveBeenCalled();
} finally {
restoreEnv();
}
});

it("aborts before backup/delete when a matching custom-endpoint session has an invalid endpoint (#4497/#5869)", async () => {
const restoreEnv = snapshotEnv(["COMPATIBLE_API_KEY"]);
process.env.COMPATIBLE_API_KEY = "compat-key"; // pass credential preflight
try {
const harness = createRebuildFlowHarness({
sandboxEntry: { provider: "compatible-endpoint", model: "custom-model" },
});
harness.session.endpointUrl = "file:///tmp/not-http";

await expect(
harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }),
).rejects.toThrow("Cannot validate recreate endpoint");

expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled();
expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith(
["sandbox", "delete", "alpha"],
expect.anything(),
);
expect(harness.onboardSpy).not.toHaveBeenCalled();
} finally {
restoreEnv();
}
});

it("aborts before backup/delete when a custom-endpoint target has no matching session (#5735)", async () => {
// Installer flow: the loaded onboard session belongs to a different
// (just-created) sandbox, and the target uses a custom OpenAI-compatible
Expand Down
67 changes: 62 additions & 5 deletions src/lib/actions/sandbox/rebuild-resume-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,80 @@ describe("getRebuildEndpointFromRegistry", () => {
});

describe("prepareRebuildResumeConfig", () => {
it("pins registry config and does not pin endpoint for a matching session", () => {
vi.spyOn(onboardSession, "loadSession").mockReturnValue({ sandboxName: "alpha" });
it("validates and canonicalizes a matching custom-endpoint session endpoint", () => {
vi.spyOn(onboardSession, "loadSession").mockReturnValue({
sandboxName: "alpha",
endpointUrl: " http://127.0.0.1:19999/v1/?x=1#frag ",
});
const config = prepareRebuildResumeConfig(
"alpha",
entry({ provider: "nvidia-prod", model: "m" }),
entry({ provider: "compatible-endpoint", model: "m" }),
null,
noopLog,
throwingBail,
);
expect(config).toMatchObject({
provider: "nvidia-prod",
provider: "compatible-endpoint",
model: "m",
credentialEnv: "NVIDIA_INFERENCE_API_KEY",
credentialEnv: "COMPATIBLE_API_KEY",
pinEndpoint: false,
endpointUrl: "http://127.0.0.1:19999/v1",
});
});

it("prefers durable registry endpoint metadata over a stale matching session endpoint", () => {
vi.spyOn(onboardSession, "loadSession").mockReturnValue({
sandboxName: "alpha",
endpointUrl: "https://stale.example.test/v1",
});
const config = prepareRebuildResumeConfig(
"alpha",
entry({
provider: "compatible-endpoint",
model: "m",
endpointUrl: "https://registry.example.test/v1?x=1#frag",
}),
null,
noopLog,
throwingBail,
);
expect(config).toMatchObject({
provider: "compatible-endpoint",
model: "m",
pinEndpoint: true,
endpointUrl: "https://registry.example.test/v1",
});
});

it("fails closed for a matching custom-endpoint session with no recoverable endpoint", () => {
vi.spyOn(onboardSession, "loadSession").mockReturnValue({ sandboxName: "alpha" });
expect(() =>
prepareRebuildResumeConfig(
"alpha",
entry({ provider: "compatible-endpoint", model: "m" }),
null,
noopLog,
throwingBail,
),
).toThrow("Cannot validate recreate endpoint");
});

it("fails closed for a matching custom-endpoint session with an invalid endpoint", () => {
vi.spyOn(onboardSession, "loadSession").mockReturnValue({
sandboxName: "alpha",
endpointUrl: "https://user:pass@example.test/v1",
});
expect(() =>
prepareRebuildResumeConfig(
"alpha",
entry({ provider: "compatible-endpoint", model: "m" }),
null,
noopLog,
throwingBail,
),
).toThrow("Cannot validate recreate endpoint");
});

it("pins the canonical endpoint when the session belongs to another sandbox", () => {
vi.spyOn(onboardSession, "loadSession").mockReturnValue({ sandboxName: "other" });
const config = prepareRebuildResumeConfig(
Expand Down
30 changes: 27 additions & 3 deletions src/lib/actions/sandbox/rebuild-resume-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,12 @@ export interface RebuildResumeConfig {
readonly nimContainer: string | null;
readonly credentialEnv: string | null;
readonly preferredInferenceApi: string | null;
/** Overwrite the session endpoint with `endpointUrl`; false keeps a matching session's own custom URL. */
/**
* Whether this endpoint was derived without trusting the matching onboard
* session. Kept for preflight/tests; rebuild writes `endpointUrl`
* unconditionally after validation so stale retry sessions cannot leak old
* provider URLs into recreate (#4497/#5869).
*/
readonly pinEndpoint: boolean;
readonly endpointUrl: string | null;
readonly ambient: AmbientRecreateEnvAssessment;
Expand Down Expand Up @@ -253,6 +258,25 @@ export function prepareRebuildResumeConfig(
return null;
}

let endpointUrl = rebuildEndpoint.known ? rebuildEndpoint.endpointUrl : null;
if (!rebuildEndpoint.known && sessionMatchesSandbox) {
endpointUrl = canonicalCustomEndpointUrl(session?.endpointUrl);
if (!endpointUrl) {
console.error("");
console.error(
` ${_RD}Rebuild preflight failed:${R} cannot validate the inference endpoint for provider '${registrySelection.provider}'.`,
);
console.error(
` The custom endpoint for '${sandboxName}' is missing or invalid in its onboard session.`,
);
console.error(" Sandbox is untouched — no data was lost.");
bail(
`Cannot validate recreate endpoint for provider '${registrySelection.provider}' from matching session`,
);
return null;
}
}

return {
agent: rebuildAgent,
provider: registrySelection.provider,
Expand All @@ -263,8 +287,8 @@ export function prepareRebuildResumeConfig(
registrySelection.credentialEnv,
),
preferredInferenceApi: registrySelection.preferredInferenceApi,
pinEndpoint: !sessionMatchesSandbox && rebuildEndpoint.known,
endpointUrl: rebuildEndpoint.known ? rebuildEndpoint.endpointUrl : null,
pinEndpoint: rebuildEndpoint.known,
endpointUrl,
ambient,
};
}
24 changes: 14 additions & 10 deletions src/lib/actions/sandbox/rebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -772,21 +772,25 @@ export async function rebuildSandbox(
// null fallback) so a missing registry value doesn't silently leave a
// stale session entry from an earlier sandbox in place.
// #5735: apply the recreate config resolved + validated BEFORE delete by
// prepareRebuildResumeConfig (provider/model/credential/endpoint derived
// from the about-to-be-removed registry entry, never from ambient env), so
// onboard --resume recreates the recorded sandbox in non-interactive mode.
// Assign explicitly so a missing value doesn't leave a stale entry from an
// earlier sandbox in place. `pinEndpoint` is false for a matching session
// (keep its own custom endpoint) and true for a non-matching session with a
// canonical/registry-derivable endpoint.
// prepareRebuildResumeConfig, so onboard --resume recreates the recorded
// sandbox in non-interactive mode. Provider/model/credential/endpoint come
// from the about-to-be-removed registry entry or a validated matching
// custom-endpoint session, never ambient env. Assign explicitly so missing
// values cannot leave stale entries from an earlier sandbox in place.
s.provider = resumeConfig.provider;
s.model = resumeConfig.model;
s.nimContainer = resumeConfig.nimContainer;
s.credentialEnv = resumeConfig.credentialEnv;
s.preferredInferenceApi = resumeConfig.preferredInferenceApi;
if (resumeConfig.pinEndpoint) {
s.endpointUrl = resumeConfig.endpointUrl;
}
// `onboard --resume` uses the session as the recreate contract. Always
// overwrite the endpoint from the preflighted registry-derived config,
// even when the pre-existing session currently matches this sandbox name:
// stale recovery can be retrying after an earlier failed recreate left a
// partial session behind. Leaving the old endpoint in that case can silently
// steer the recreate to the wrong provider URL. `prepareRebuildResumeConfig`
// already validates whether this endpoint is recoverable before any
// destructive work, so this is the safest source boundary (#4497/#5869).
s.endpointUrl = resumeConfig.endpointUrl;
return s;
});
process.env.NEMOCLAW_SANDBOX_NAME = sandboxName;
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/test-double-onboard.sh
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,11 @@ run_with_timeout "$PHASE_TIMEOUT" \
"${NEMOCLAW_CMD[@]}" "$SANDBOX_A" rebuild --yes >"$REBUILD_LOG" 2>&1 || rebuild_exit=$?
rebuild_output="$(cat "$REBUILD_LOG")"
rm -f "$REBUILD_LOG"
# Keep the shared diagnostic hook pointed at the command under test. Without
# this, stale-rebuild failures dump the previous onboard output and hide the
# actual recovery failure signature (#4497/#5869).
RUN_ONBOARD_OUTPUT="$rebuild_output"
RUN_ONBOARD_EXIT="$rebuild_exit"

# A timeout (124 from `timeout`/`gtimeout`) must fail, not silently pass.
if [ "$rebuild_exit" -eq 124 ]; then
Expand Down
Loading