Skip to content
Closed
Changes from all 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
100 changes: 100 additions & 0 deletions src/lib/deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,103 @@ describe("Brev status helpers", () => {
).toBe(false);
});
});

describe("executeDeploy — instance name validation (#575)", () => {
// Helper: build a minimal DeployExecutionOptions that tracks calls
function makeMockOpts(instanceName: string) {
const calls: string[] = [];
let exitCode: number | undefined;
let exitError: Error | undefined;

return {
opts: {
instanceName,
env: { NEMOCLAW_GPU: "a2-highgpu-1g:nvidia-tesla-a100:1" },
rootDir: "/fake/root",
getCredential: () => null,
validateName: (name: string, label: string) => {
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
throw new Error(
`Invalid ${label}: '${name}'. Must be lowercase alphanumeric with optional internal hyphens.`,
);
}
return name;
Comment on lines +161 to +167

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Mock validateName diverges from production rules and can mask regressions.

At Line 162, the test helper allows names starting with digits and omits the max-length guard, while src/lib/runner.ts requires a leading letter and enforces 63-char max. This weakens regression fidelity.

Suggested patch
         validateName: (name: string, label: string) => {
-          if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
+          if (!name) {
+            throw new Error(`${label} is required`);
+          }
+          if (name.length > 63) {
+            throw new Error(`${label} too long (max 63 chars): '${name.slice(0, 20)}...'`);
+          }
+          if (!/^[a-z]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
             throw new Error(
-              `Invalid ${label}: '${name}'. Must be lowercase alphanumeric with optional internal hyphens.`,
+              `Invalid ${label}: '${name}'. Must start with a letter and contain only lowercase alphanumerics with optional internal hyphens.`,
             );
           }
           return name;
         },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
validateName: (name: string, label: string) => {
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
throw new Error(
`Invalid ${label}: '${name}'. Must be lowercase alphanumeric with optional internal hyphens.`,
);
}
return name;
validateName: (name: string, label: string) => {
if (!name) {
throw new Error(`${label} is required`);
}
if (name.length > 63) {
throw new Error(`${label} too long (max 63 chars): '${name.slice(0, 20)}...'`);
}
if (!/^[a-z]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
throw new Error(
`Invalid ${label}: '${name}'. Must start with a letter and contain only lowercase alphanumerics with optional internal hyphens.`,
);
}
return name;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/deploy.test.ts` around lines 161 - 167, The test mock validateName in
src/lib/deploy.test.ts diverges from production validation (allowing leading
digits and omitting max-length) so update the mock to mirror the real validation
in src/lib/runner.ts: require a leading letter, allow only lowercase letters,
digits and internal hyphens, and enforce the 63-character max; keep the same
error message shape and throw an Error when validation fails so tests exercise
the same rejection paths as the runner's validateName.

},
shellQuote: (value: string) => `'${value.replace(/'/g, "'\''")}'`,
run: (command: string) => {
calls.push(`run:${command}`);
},
runInteractive: (command: string) => {
calls.push(`runInteractive:${command}`);
},
execFileSync: (file: string, args: string[], _opts?: Record<string, unknown>) => {
calls.push(`execFileSync:${file} ${args.join(" ")}`);
return "";
},
spawnSync: (file: string, args: string[], _opts?: Record<string, unknown>) => {
calls.push(`spawnSync:${file} ${args.join(" ")}`);
},
log: () => {},
error: () => {},
stdoutWrite: () => {},
exit: ((code: number) => {
exitCode = code;
exitError = new Error(`exit(${code})`);
throw exitError;
}) as (code: number) => never,
},
calls,
getExitCode: () => exitCode,
getExitError: () => exitError,
};
}

const maliciousNames = [
"foo;rm -rf /",
"foo|cat /etc/passwd",
"$(whoami)",
"`whoami`",
"foo && echo pwned",
"foo'inject",
'foo"inject',
"../traversal",
"UPPERCASE",
"has spaces",

];

for (const name of maliciousNames) {
it(`rejects malicious instance name: ${JSON.stringify(name)}`, async () => {
const { executeDeploy } = await import("../../dist/lib/deploy");
const { opts, calls } = makeMockOpts(name);

await expect(executeDeploy(opts)).rejects.toThrow(/Invalid instance name|instance name is required/i);

// No shell commands should have been executed
expect(calls).toHaveLength(0);
});
}

it("accepts a valid instance name", async () => {
const { executeDeploy } = await import("../../dist/lib/deploy");
const { opts, getExitCode } = makeMockOpts("my-valid-instance");

// This will fail at the provider detection step (no credentials),
// but it should NOT fail at validation — proving the name was accepted.
// Catch any thrown error and explicitly assert it wasn't a name-validation
// failure, so a future regression can't silently pass this test.
const caught = await executeDeploy(opts)
.then(() => null)
.catch((error: unknown) => error);
if (caught) {
expect(String(caught)).not.toMatch(
/Invalid instance name|instance name is required/i,
);
}

// If it exited, it should be because of missing provider/brev, not name validation
if (getExitCode() !== undefined) {
expect(getExitCode()).toBe(1);
}
Comment on lines +226 to +244

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

The valid-name test still has a vacuous success path.

If executeDeploy returns without throwing, exiting, or executing commands, this test still passes. Add one mandatory post-condition proving it advanced beyond validation.

Suggested patch
-    const { opts, getExitCode } = makeMockOpts("my-valid-instance");
+    const { opts, calls, getExitCode } = makeMockOpts("my-valid-instance");
@@
-    // If it exited, it should be because of missing provider/brev, not name validation
+    // Ensure it progressed beyond validation (either exited downstream or attempted a command path)
+    expect(getExitCode() !== undefined || calls.length > 0).toBe(true);
+    // If it exited, it should be because of missing provider/brev, not name validation
     if (getExitCode() !== undefined) {
       expect(getExitCode()).toBe(1);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/deploy.test.ts` around lines 226 - 244, The test currently allows a
vacuous success if executeDeploy resolves; ensure it actually progressed past
name validation by asserting the deploy failed: after calling executeDeploy
(using makeMockOpts) add a mandatory assertion like
expect(caught).not.toBeNull() or expect(caught).toBeTruthy() (and/or assert
getExitCode() === 1) so the test fails if executeDeploy returns successfully
instead of erroring at provider detection; place this check right after you
compute `caught` and before the existing name-error exclusion and exit-code
checks.

});
});