import { describe, it, expect } from "vitest";
import { validateAlphanumeric, validateServiceName } from "./validation.js";
import { SSHArgSecurityError } from "./path-security.js";
describe("validateAlphanumeric", () => {
it("allows basic alphanumeric with dots, dashes, underscores", () => {
expect(() => validateAlphanumeric("my-service.name_123", "test")).not.toThrow();
});
it("rejects slashes when not allowed", () => {
expect(() => validateAlphanumeric("/path/to/file", "test")).toThrow("Invalid characters");
});
it("allows slashes when allowSlash=true", () => {
expect(() => validateAlphanumeric("/path/to/file", "test", { allowSlash: true })).not.toThrow();
});
it("allows tilde when allowTilde=true", () => {
expect(() => validateAlphanumeric("~file.txt", "test", { allowTilde: true })).not.toThrow();
});
it("allows both slashes and tilde when both options enabled", () => {
expect(() => validateAlphanumeric("~/path/to/file", "test", { allowSlash: true, allowTilde: true })).not.toThrow();
});
it("rejects shell metacharacters", () => {
expect(() => validateAlphanumeric("test;rm", "test")).toThrow("Invalid characters");
expect(() => validateAlphanumeric("test|cat", "test")).toThrow("Invalid characters");
expect(() => validateAlphanumeric("test&bg", "test")).toThrow("Invalid characters");
});
it("rejects spaces", () => {
expect(() => validateAlphanumeric("has spaces", "test")).toThrow("Invalid characters");
});
it("rejects empty string", () => {
expect(() => validateAlphanumeric("", "test")).toThrow("cannot be empty");
});
it("includes parameter name in error message", () => {
try {
validateAlphanumeric("invalid;", "username");
} catch (error) {
expect((error as Error).message).toContain("username");
}
});
});
describe("validateServiceName", () => {
it("allows valid systemd service names", () => {
expect(() => validateServiceName("nginx.service")).not.toThrow();
expect(() => validateServiceName("docker@user.service")).not.toThrow();
expect(() => validateServiceName("my-app_service")).not.toThrow();
});
it("rejects shell metacharacters", () => {
expect(() => validateServiceName("nginx;rm")).toThrow(SSHArgSecurityError);
expect(() => validateServiceName("nginx|cat")).toThrow(SSHArgSecurityError);
});
it("rejects invalid characters like forward slashes", () => {
expect(() => validateServiceName("nginx/service")).toThrow(SSHArgSecurityError);
});
it("rejects empty string", () => {
expect(() => validateServiceName("")).toThrow(SSHArgSecurityError);
});
});