- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
407 lines
15 KiB
TypeScript
407 lines
15 KiB
TypeScript
import { Test, TestingModule } from "@nestjs/testing";
|
|
import { SslService } from "./ssl.service";
|
|
import { BadRequestException } from "@nestjs/common";
|
|
import * as fs from "fs";
|
|
import * as tls from "tls";
|
|
import * as dns from "dns/promises";
|
|
import * as crypto from "crypto";
|
|
import { EventEmitter } from "events";
|
|
|
|
jest.mock("fs");
|
|
jest.mock("tls");
|
|
jest.mock("dns/promises");
|
|
|
|
const VALID_CERT = `-----BEGIN CERTIFICATE-----
|
|
MIICyjCCAbKgAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAljYW5p
|
|
bmEuaXIwHhcNMjYwMTAxMDAwMDAwWhcNMzAwMTAxMDAwMDAwWjAUMRIwEAYDVQQD
|
|
DAljYW5pbmEuaXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrRe7W
|
|
fArfQ7unMhG+bT5nNangnFIrB431AaCBesk3dPeGiLljb4QkMY1iMyKsjkKT04Qc
|
|
7RtWb3GGutLR2W9i+o3yEk41YIQsAAs6FA5Wh81ncltjct16Wmm2RAwfF579qrvm
|
|
8iNVVu82nXidC9/nNyuFg/8AyJ8YGnona5SB0NkC+D2Ed53ubaf2Dd3NH2mOLAxD
|
|
x2u/eNuBSShf/7MOd4c7fUSKUABvbjyL//W1ylIhoq7Wba10LW7NimfnIt2+W/DQ
|
|
FcOFYxVlES/hcInmOomat51JbUkWD7zINUK6+aBQdPYa9rpYyvKoiUccudrU9LGU
|
|
i96s7G+2JsGiALqNAgMBAAGjJzAl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VLl3UX2FR2ZUFBv4BQWDbR0QCr0hLRNUmNzeAZNtW44qF5E7NJeBRtlaK
|
|
MOSdRivJOurHR33iTfueNz0=
|
|
-----END PRIVATE KEY-----`;
|
|
|
|
describe("SslService", () => {
|
|
let service: SslService;
|
|
|
|
beforeEach(async () => {
|
|
jest.resetAllMocks();
|
|
(dns.lookup as jest.Mock).mockResolvedValue([
|
|
{ address: "93.184.216.34", family: 4 },
|
|
]);
|
|
(fs.existsSync as jest.Mock).mockReturnValue(true);
|
|
(fs.mkdirSync as jest.Mock).mockReturnValue(undefined);
|
|
|
|
const module: TestingModule = await Test.createTestingModule({
|
|
providers: [SslService],
|
|
}).compile();
|
|
|
|
service = module.get<SslService>(SslService);
|
|
jest.clearAllMocks();
|
|
});
|
|
|
|
it("should be defined", () => {
|
|
expect(service).toBeDefined();
|
|
});
|
|
|
|
describe("security regressions", () => {
|
|
it("rejects mismatched certificate/private key before any filesystem changes", () => {
|
|
const otherKey = crypto
|
|
.generateKeyPairSync("rsa", { modulusLength: 2048 })
|
|
.privateKey.export({ type: "pkcs8", format: "pem" })
|
|
.toString();
|
|
expect(() => service.updateCertificates(VALID_CERT, otherKey)).toThrow(
|
|
BadRequestException,
|
|
);
|
|
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
|
});
|
|
it.each([
|
|
"127.0.0.1",
|
|
"10.0.0.1",
|
|
"172.16.0.1",
|
|
"192.168.0.1",
|
|
"169.254.169.254",
|
|
"100.64.0.1",
|
|
"::1",
|
|
"fc00::1",
|
|
"::ffff:127.0.0.1",
|
|
"2001:db8::1",
|
|
])("blocks DNS resolving to %s", async (address) => {
|
|
(dns.lookup as jest.Mock).mockResolvedValue([
|
|
{ address, family: address.includes(":") ? 6 : 4 },
|
|
]);
|
|
(tls.connect as jest.Mock).mockImplementation(() => {
|
|
throw new Error("unexpected TLS");
|
|
});
|
|
const result = await service.testOnlineDomainSsl("canina.ir");
|
|
expect(result.onlineCheck).toBe(false);
|
|
expect(tls.connect).not.toHaveBeenCalled();
|
|
});
|
|
it("rejects a mixed public/private DNS answer without opening TLS", async () => {
|
|
(dns.lookup as jest.Mock).mockResolvedValue([
|
|
{ address: "93.184.216.34", family: 4 },
|
|
{ address: "10.0.0.1", family: 4 },
|
|
]);
|
|
expect(await service.testOnlineDomainSsl("canina.ir")).toMatchObject({
|
|
onlineCheck: false,
|
|
});
|
|
expect(tls.connect).not.toHaveBeenCalled();
|
|
});
|
|
it("fails closed on DNS failure", async () => {
|
|
(dns.lookup as jest.Mock).mockRejectedValue(new Error("DNS offline"));
|
|
expect(await service.testOnlineDomainSsl("canina.ir")).toMatchObject({
|
|
onlineCheck: false,
|
|
});
|
|
expect(tls.connect).not.toHaveBeenCalled();
|
|
});
|
|
it("restores old certificate after private key rename fails", () => {
|
|
(fs.readFileSync as jest.Mock).mockReturnValue(VALID_CERT);
|
|
(fs.renameSync as jest.Mock).mockImplementation(
|
|
(from: string, to: string) => {
|
|
if (to.endsWith("privateKey.pem") && from.endsWith(".tmp"))
|
|
throw new Error("rename failed");
|
|
},
|
|
);
|
|
expect(() => service.updateCertificates(VALID_CERT, VALID_KEY)).toThrow(
|
|
"rename failed",
|
|
);
|
|
expect(fs.renameSync).toHaveBeenCalledWith(
|
|
expect.stringMatching(/fullchain\.pem\.bak$/),
|
|
expect.stringMatching(/fullchain\.pem$/),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("getStatus", () => {
|
|
it("should return { exists: false } if certificate file does not exist", () => {
|
|
(fs.existsSync as jest.Mock).mockReturnValue(false);
|
|
|
|
const status = service.getStatus();
|
|
expect(status).toEqual({ exists: false });
|
|
});
|
|
|
|
it("should parse real X509 certificate and return details if cert exists", () => {
|
|
(fs.existsSync as jest.Mock).mockReturnValue(true);
|
|
(fs.readFileSync as jest.Mock).mockReturnValue(VALID_CERT);
|
|
|
|
const status = service.getStatus();
|
|
|
|
expect(status.exists).toBe(true);
|
|
expect(status.subject).toContain("canina.ir");
|
|
expect(status.issuer).toContain("canina.ir");
|
|
expect(status.domains).toContain("canina.ir");
|
|
expect(status.domains).toContain("www.canina.ir");
|
|
expect(status.isExpired).toBeDefined();
|
|
expect(status.fingerprint).toBeDefined();
|
|
expect(status.serialNumber).toBeDefined();
|
|
});
|
|
|
|
it("should return { exists: false } if parsing fails", () => {
|
|
(fs.existsSync as jest.Mock).mockReturnValue(true);
|
|
(fs.readFileSync as jest.Mock).mockReturnValue("INVALID_PEM_CONTENT");
|
|
|
|
const status = service.getStatus();
|
|
expect(status).toEqual({ exists: false });
|
|
});
|
|
});
|
|
|
|
describe("updateCertificates", () => {
|
|
it("should throw BadRequestException if cert or key content is empty", () => {
|
|
expect(() => service.updateCertificates("", VALID_KEY)).toThrow(
|
|
BadRequestException,
|
|
);
|
|
expect(() => service.updateCertificates(VALID_CERT, "")).toThrow(
|
|
BadRequestException,
|
|
);
|
|
});
|
|
|
|
it("should throw BadRequestException if cert format is invalid", () => {
|
|
expect(() =>
|
|
service.updateCertificates("BAD_CERT_HEADER", VALID_KEY),
|
|
).toThrow(/فرمت گواهی نامعتبر است/);
|
|
});
|
|
|
|
it("should throw BadRequestException if private key format is invalid", () => {
|
|
expect(() =>
|
|
service.updateCertificates(VALID_CERT, "BAD_KEY_CONTENT"),
|
|
).toThrow(/فرمت کلید خصوصی نامعتبر است/);
|
|
});
|
|
|
|
it("should backup old certs and write new cert and key files", () => {
|
|
(fs.existsSync as jest.Mock).mockReturnValue(true);
|
|
(fs.copyFileSync as jest.Mock).mockReturnValue(undefined);
|
|
(fs.writeFileSync as jest.Mock).mockReturnValue(undefined);
|
|
(fs.readFileSync as jest.Mock).mockReturnValue(VALID_CERT);
|
|
|
|
const res = service.updateCertificates(VALID_CERT, VALID_KEY);
|
|
|
|
expect(fs.copyFileSync).toHaveBeenCalledTimes(2);
|
|
expect(fs.writeFileSync).toHaveBeenCalledTimes(2);
|
|
expect(res.success).toBe(true);
|
|
expect(res.message).toContain("با موفقیت بهروزرسانی");
|
|
expect(res.status.exists).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("safety boundaries", () => {
|
|
it.each([
|
|
"",
|
|
"127.0.0.1",
|
|
"[::1]",
|
|
"service.internal",
|
|
"x.local",
|
|
"canina.ir:443",
|
|
"user@canina.ir",
|
|
"canina.ir?host=internal",
|
|
])("rejects unsafe target %p before opening a socket", async (domain) => {
|
|
expect(await service.testOnlineDomainSsl(domain)).toMatchObject({
|
|
onlineCheck: false,
|
|
});
|
|
expect(tls.connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
[" ", VALID_KEY],
|
|
[VALID_CERT, " "],
|
|
["invalid", VALID_KEY],
|
|
[VALID_CERT, "invalid"],
|
|
])("never backs up or writes files on invalid input", (cert, key) => {
|
|
expect(() => service.updateCertificates(cert, key)).toThrow(
|
|
BadRequestException,
|
|
);
|
|
expect(fs.copyFileSync).not.toHaveBeenCalled();
|
|
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("propagates certificate write failure without overwriting the private key", () => {
|
|
const error = new Error("disk full");
|
|
(fs.writeFileSync as jest.Mock).mockImplementation(() => {
|
|
throw error;
|
|
});
|
|
expect(() => service.updateCertificates(VALID_CERT, VALID_KEY)).toThrow(
|
|
error,
|
|
);
|
|
expect(fs.writeFileSync).toHaveBeenCalledTimes(1);
|
|
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
|
expect.stringMatching(/fullchain\.pem\..*\.tmp$/),
|
|
VALID_CERT.trim(),
|
|
{ encoding: "utf8", mode: 0o600, flag: "wx" },
|
|
);
|
|
});
|
|
|
|
it("reports untrusted peer certificates as unauthorized", async () => {
|
|
const socket = Object.assign(new EventEmitter(), {
|
|
authorized: false,
|
|
end: jest.fn(),
|
|
getPeerCertificate: jest.fn().mockReturnValue({
|
|
valid_to: "2030-01-01T00:00:00.000Z",
|
|
issuer: { CN: "Untrusted CA" },
|
|
subject: { CN: "canina.ir" },
|
|
}),
|
|
});
|
|
(tls.connect as jest.Mock).mockImplementation((_options, callback) => {
|
|
process.nextTick(callback);
|
|
return socket;
|
|
});
|
|
expect(await service.testOnlineDomainSsl("canina.ir")).toMatchObject({
|
|
onlineCheck: true,
|
|
authorized: false,
|
|
issuer: "Untrusted CA",
|
|
});
|
|
expect(tls.connect).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
host: "93.184.216.34",
|
|
servername: "canina.ir",
|
|
port: 443,
|
|
timeout: 5000,
|
|
}),
|
|
expect.any(Function),
|
|
);
|
|
expect(socket.end).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
describe("testOnlineDomainSsl", () => {
|
|
it("should reject invalid domains, IP addresses, or internal hosts", async () => {
|
|
const res1 = await service.testOnlineDomainSsl("localhost");
|
|
expect(res1.onlineCheck).toBe(false);
|
|
expect(res1.error).toContain("فرمت نام دامنه نامعتبر است");
|
|
|
|
const res2 = await service.testOnlineDomainSsl("192.168.1.1");
|
|
expect(res2.onlineCheck).toBe(false);
|
|
|
|
const res3 = await service.testOnlineDomainSsl("internal.server.local");
|
|
expect(res3.onlineCheck).toBe(false);
|
|
|
|
const res4 = await service.testOnlineDomainSsl("invalid..domain");
|
|
expect(res4.onlineCheck).toBe(false);
|
|
});
|
|
|
|
it("should return certificate details upon successful TLS connection", async () => {
|
|
const fakeSocket: any = new EventEmitter();
|
|
fakeSocket.authorized = true;
|
|
fakeSocket.end = jest.fn();
|
|
fakeSocket.getPeerCertificate = jest.fn().mockReturnValue({
|
|
valid_to: new Date(Date.now() + 50000000).toISOString(),
|
|
issuer: { O: "Let's Encrypt" },
|
|
subject: { CN: "canina.ir" },
|
|
});
|
|
|
|
(tls.connect as jest.Mock).mockImplementation(
|
|
(options: any, callback?: any) => {
|
|
if (callback) {
|
|
process.nextTick(callback);
|
|
}
|
|
return fakeSocket;
|
|
},
|
|
);
|
|
|
|
const res = await service.testOnlineDomainSsl("https://canina.ir/path");
|
|
|
|
expect(res.onlineCheck).toBe(true);
|
|
expect(res.domain).toBe("canina.ir");
|
|
expect(res.issuer).toBe("Let's Encrypt");
|
|
expect(res.subject).toBe("canina.ir");
|
|
expect(fakeSocket.end).toHaveBeenCalled();
|
|
});
|
|
|
|
it("should return message if peer certificate is empty", async () => {
|
|
const fakeSocket: any = new EventEmitter();
|
|
fakeSocket.authorized = false;
|
|
fakeSocket.end = jest.fn();
|
|
fakeSocket.getPeerCertificate = jest.fn().mockReturnValue(null);
|
|
|
|
(tls.connect as jest.Mock).mockImplementation(
|
|
(options: any, callback?: any) => {
|
|
if (callback) {
|
|
process.nextTick(callback);
|
|
}
|
|
return fakeSocket;
|
|
},
|
|
);
|
|
|
|
const res = await service.testOnlineDomainSsl("canina.ir");
|
|
|
|
expect(res.onlineCheck).toBe(false);
|
|
expect(res.message).toContain(
|
|
"گواهی SSL بر روی پورت ۴۴۳ این دامنه یافت نشد",
|
|
);
|
|
});
|
|
|
|
it("should handle socket connection error gracefully", async () => {
|
|
const fakeSocket: any = new EventEmitter();
|
|
fakeSocket.end = jest.fn();
|
|
|
|
(tls.connect as jest.Mock).mockImplementation(
|
|
(options: any, callback?: any) => {
|
|
process.nextTick(() => {
|
|
fakeSocket.emit("error", new Error("Connection refused"));
|
|
});
|
|
return fakeSocket;
|
|
},
|
|
);
|
|
|
|
const res = await service.testOnlineDomainSsl("canina.ir");
|
|
|
|
expect(res.onlineCheck).toBe(false);
|
|
expect(res.error).toBe("Connection refused");
|
|
});
|
|
|
|
it("should handle socket timeout gracefully", async () => {
|
|
const fakeSocket: any = new EventEmitter();
|
|
fakeSocket.destroy = jest.fn();
|
|
|
|
(tls.connect as jest.Mock).mockImplementation(
|
|
(options: any, callback?: any) => {
|
|
process.nextTick(() => {
|
|
fakeSocket.emit("timeout");
|
|
});
|
|
return fakeSocket;
|
|
},
|
|
);
|
|
|
|
const res = await service.testOnlineDomainSsl("canina.ir");
|
|
|
|
expect(res.onlineCheck).toBe(false);
|
|
expect(res.error).toContain("مهلت اتصال (Timeout)");
|
|
expect(fakeSocket.destroy).toHaveBeenCalled();
|
|
});
|
|
});
|
|
});
|