feat: import upstream ZITADEL Login V2 v4.20.4 source workspace
This commit is contained in:
1 parent
eadd0e558b
commit
4404849fc4
644 files changed
+153201
-10
No files matched your search
@@ -0,0 +1,176 @@
|
||||
import * as path from "path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { StartedNetwork } from "testcontainers";
|
||||
import { GenericContainer, Network, Wait, type StartedTestContainer } from "testcontainers";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
const TEST_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const LOGIN_APP_DIR = path.join(TEST_DIR, "../..");
|
||||
const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`;
|
||||
|
||||
const DOCKER_TIMEOUT = 180_000;
|
||||
|
||||
/**
|
||||
* Integration tests for ZITADEL_API_AWAITINITIALCONN support.
|
||||
*
|
||||
* When this environment variable is set (e.g. "30s", "5m"), the login
|
||||
* container polls the ZITADEL API's /debug/ready endpoint before starting
|
||||
* the Next.js server. This replaces the wait4x init container that was
|
||||
* previously used in the Helm chart.
|
||||
*
|
||||
* The test suite uses a mock Zitadel server that returns 503 on /debug/ready
|
||||
* for a configurable duration before switching to 200. Three scenarios are
|
||||
* verified: the API becomes ready within the timeout, the timeout expires
|
||||
* before the API is ready, and the variable is not set at all.
|
||||
*/
|
||||
describe("ZITADEL_API_AWAITINITIALCONN", () => {
|
||||
beforeAll(async () => {
|
||||
await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG);
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
describe("when the API becomes ready before the timeout", () => {
|
||||
let network: StartedNetwork;
|
||||
let mockZitadel: StartedTestContainer;
|
||||
let container: StartedTestContainer;
|
||||
let appUrl: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
network = await new Network().start();
|
||||
|
||||
mockZitadel = await new GenericContainer("node:20-alpine")
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases("mock-zitadel")
|
||||
.withCopyFilesToContainer([
|
||||
{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" },
|
||||
])
|
||||
.withEnvironment({ PORT: "8080", READY_AFTER_MS: "5000" })
|
||||
.withCommand(["node", "/app/server.js"])
|
||||
.withExposedPorts(8080)
|
||||
.withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening"))
|
||||
.start();
|
||||
|
||||
container = await new GenericContainer(LOGIN_IMAGE_TAG)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(3000)
|
||||
.withEnvironment({
|
||||
ZITADEL_API_URL: "http://mock-zitadel:8080",
|
||||
ZITADEL_SERVICE_USER_TOKEN: "test-token",
|
||||
ZITADEL_API_AWAITINITIALCONN: "60s",
|
||||
})
|
||||
.withStartupTimeout(120_000)
|
||||
.withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000))
|
||||
.start();
|
||||
|
||||
appUrl = `http://${container.getHost()}:${container.getMappedPort(3000)}`;
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop().catch(() => {});
|
||||
await mockZitadel?.stop().catch(() => {});
|
||||
await network?.stop().catch(() => {});
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
it("starts successfully after the API becomes ready", async () => {
|
||||
const response = await fetch(`${appUrl}/ui/v2/login/healthy`);
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the API does not become ready before the timeout", () => {
|
||||
let network: StartedNetwork;
|
||||
let mockZitadel: StartedTestContainer;
|
||||
let container: StartedTestContainer;
|
||||
|
||||
beforeAll(async () => {
|
||||
network = await new Network().start();
|
||||
|
||||
mockZitadel = await new GenericContainer("node:20-alpine")
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases("mock-zitadel")
|
||||
.withCopyFilesToContainer([
|
||||
{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" },
|
||||
])
|
||||
.withEnvironment({ PORT: "8080", READY_AFTER_MS: "600000" })
|
||||
.withCommand(["node", "/app/server.js"])
|
||||
.withExposedPorts(8080)
|
||||
.withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening"))
|
||||
.start();
|
||||
|
||||
container = await new GenericContainer(LOGIN_IMAGE_TAG)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(3000)
|
||||
.withEnvironment({
|
||||
ZITADEL_API_URL: "http://mock-zitadel:8080",
|
||||
ZITADEL_SERVICE_USER_TOKEN: "test-token",
|
||||
ZITADEL_API_AWAITINITIALCONN: "5s",
|
||||
})
|
||||
.withStartupTimeout(30_000)
|
||||
.withWaitStrategy(Wait.forLogMessage(/Timed out after 5s/))
|
||||
.start();
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop().catch(() => {});
|
||||
await mockZitadel?.stop().catch(() => {});
|
||||
await network?.stop().catch(() => {});
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
it("logs the timeout error before exiting", async () => {
|
||||
const stream = await container.logs();
|
||||
const logs = await new Promise<string>((resolve) => {
|
||||
let output = "";
|
||||
stream.on("data", (chunk: Buffer) => { output += chunk.toString(); });
|
||||
stream.on("end", () => resolve(output));
|
||||
setTimeout(() => { stream.destroy(); resolve(output); }, 5_000);
|
||||
});
|
||||
expect(logs).toContain("Timed out after 5s waiting for API readiness");
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the variable is not set", () => {
|
||||
let network: StartedNetwork;
|
||||
let mockZitadel: StartedTestContainer;
|
||||
let container: StartedTestContainer;
|
||||
let appUrl: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
network = await new Network().start();
|
||||
|
||||
mockZitadel = await new GenericContainer("node:20-alpine")
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases("mock-zitadel")
|
||||
.withCopyFilesToContainer([
|
||||
{ source: path.join(TEST_DIR, "mock-zitadel-server.js"), target: "/app/server.js" },
|
||||
])
|
||||
.withEnvironment({ PORT: "8080", READY_AFTER_MS: "0" })
|
||||
.withCommand(["node", "/app/server.js"])
|
||||
.withExposedPorts(8080)
|
||||
.withWaitStrategy(Wait.forLogMessage("Mock Zitadel server listening"))
|
||||
.start();
|
||||
|
||||
container = await new GenericContainer(LOGIN_IMAGE_TAG)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(3000)
|
||||
.withEnvironment({
|
||||
ZITADEL_API_URL: "http://mock-zitadel:8080",
|
||||
ZITADEL_SERVICE_USER_TOKEN: "test-token",
|
||||
})
|
||||
.withStartupTimeout(120_000)
|
||||
.withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000))
|
||||
.start();
|
||||
|
||||
appUrl = `http://${container.getHost()}:${container.getMappedPort(3000)}`;
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop().catch(() => {});
|
||||
await mockZitadel?.stop().catch(() => {});
|
||||
await network?.stop().catch(() => {});
|
||||
}, DOCKER_TIMEOUT);
|
||||
|
||||
it("starts without waiting", async () => {
|
||||
const response = await fetch(`${appUrl}/ui/v2/login/healthy`);
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Mock Zitadel server for testing ZITADEL_API_AWAITINITIALCONN.
|
||||
*
|
||||
* Returns 503 on /debug/ready until READY_AFTER_MS milliseconds have elapsed,
|
||||
* then switches to 200. All other endpoints return minimal ConnectRPC-compatible
|
||||
* responses so the login app can start normally once the readiness gate passes.
|
||||
*/
|
||||
const http = require("http");
|
||||
|
||||
const PORT = process.env.PORT || 8080;
|
||||
const READY_AFTER_MS = parseInt(process.env.READY_AFTER_MS || "5000", 10);
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
const sendResponse = (res, statusCode, body) => {
|
||||
res.writeHead(statusCode, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(body));
|
||||
};
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const { method, url } = req;
|
||||
console.log(`[${new Date().toISOString()}] ${method} ${url}`);
|
||||
|
||||
if (url === "/debug/ready") {
|
||||
const elapsed = Date.now() - startTime;
|
||||
if (elapsed < READY_AFTER_MS) {
|
||||
console.log(` -> 503 (not ready, ${elapsed}ms / ${READY_AFTER_MS}ms)`);
|
||||
sendResponse(res, 503, { status: "not ready" });
|
||||
} else {
|
||||
console.log(` -> 200 (ready after ${elapsed}ms)`);
|
||||
sendResponse(res, 200, { status: "ok" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.includes("GetLoginSettings") || url.includes("SettingsService")) {
|
||||
sendResponse(res, 200, { settings: {} });
|
||||
} else if (url.includes("GetBrandingSettings")) {
|
||||
sendResponse(res, 200, { settings: {} });
|
||||
} else if (url.includes("SessionService") || url.includes("Session")) {
|
||||
sendResponse(res, 200, { session: {} });
|
||||
} else if (url.includes("UserService") || url.includes("User")) {
|
||||
sendResponse(res, 200, { user: {} });
|
||||
} else if (url.includes("OrganizationService") || url.includes("Organization")) {
|
||||
sendResponse(res, 200, { result: [] });
|
||||
} else if (url.includes("IdentityProviderService") || url.includes("IdentityProvider")) {
|
||||
sendResponse(res, 200, { identityProviders: [] });
|
||||
} else {
|
||||
sendResponse(res, 200, {});
|
||||
}
|
||||
});
|
||||
|
||||
server.on("error", (err) => console.error("Server error:", err));
|
||||
|
||||
server.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`Mock Zitadel server listening on port ${PORT}`);
|
||||
console.log(`Will become ready after ${READY_AFTER_MS}ms`);
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
console.log("Shutting down mock server...");
|
||||
server.close(() => {
|
||||
console.log("Mock server stopped");
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import {
|
||||
GenericContainer,
|
||||
type StartedTestContainer,
|
||||
Network,
|
||||
Wait,
|
||||
} from "testcontainers";
|
||||
import type { StartedNetwork } from "testcontainers";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { generateCertificates } from "./utils/tls.ts";
|
||||
|
||||
const TEST_DIR = path.dirname(new URL(import.meta.url).pathname);
|
||||
const LOGIN_APP_DIR = path.join(TEST_DIR, "../..");
|
||||
|
||||
const SMOCKER_MOCK_PORT = 443;
|
||||
const SMOCKER_ADMIN_PORT = 8081;
|
||||
|
||||
/**
|
||||
* Integration tests for custom CA certificate support in the login application.
|
||||
*
|
||||
* These tests verify that the Dockerfile correctly configures Node.js to trust
|
||||
* custom Certificate Authorities via SSL_CERT_FILE, SSL_CERT_DIR, and the
|
||||
* load-ssl-cert-dir.cjs preload script.
|
||||
*
|
||||
* OpenSSL (used by Node with --use-openssl-ca) only reads certs from
|
||||
* SSL_CERT_DIR when they have hashed filenames (e.g. "9d66eef0.0"). Go's
|
||||
* crypto/x509 reads any file. The preload script bridges this gap so that
|
||||
* operators get the same behaviour with both the Go backend and the login
|
||||
* container.
|
||||
*
|
||||
* We use Smocker as a TLS server whose certificate is signed by a test CA
|
||||
* that is NOT in the system trust store. Each test block configures the
|
||||
* login container differently and asserts whether the TLS handshake to
|
||||
* Smocker succeeds or fails — verifying actual trust-store behaviour, not
|
||||
* just environment variable values.
|
||||
*/
|
||||
const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`;
|
||||
|
||||
async function testTlsConnection(
|
||||
container: StartedTestContainer,
|
||||
url: string,
|
||||
): Promise<{ exitCode: number; output: string }> {
|
||||
return container.exec([
|
||||
"node",
|
||||
"-e",
|
||||
`fetch('${url}').then(() => process.exit(0)).catch(() => process.exit(1))`,
|
||||
]);
|
||||
}
|
||||
|
||||
describe("Custom CA Certificate Integration", () => {
|
||||
let network: StartedNetwork;
|
||||
let mockServer: StartedTestContainer;
|
||||
let certsDir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
certsDir = fs.mkdtempSync(path.join(os.tmpdir(), "ca-test-certs-"));
|
||||
|
||||
const certs = generateCertificates();
|
||||
fs.writeFileSync(path.join(certsDir, "ca.crt"), certs.ca.cert);
|
||||
fs.writeFileSync(path.join(certsDir, "server.key"), certs.server.key);
|
||||
fs.writeFileSync(path.join(certsDir, "server.crt"), certs.server.cert);
|
||||
|
||||
network = await new Network().start();
|
||||
|
||||
mockServer = await new GenericContainer("ghcr.io/smocker-dev/smocker")
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases("mock-zitadel")
|
||||
.withBindMounts([{ source: certsDir, target: "/certs", mode: "ro" }])
|
||||
.withEnvironment({
|
||||
SMOCKER_MOCK_SERVER_LISTEN_PORT: "443",
|
||||
SMOCKER_CONFIG_LISTEN_PORT: "8081",
|
||||
SMOCKER_TLS_ENABLE: "true",
|
||||
SMOCKER_TLS_CERT_FILE: "/certs/server.crt",
|
||||
SMOCKER_TLS_PRIVATE_KEY_FILE: "/certs/server.key",
|
||||
})
|
||||
.withExposedPorts(SMOCKER_MOCK_PORT, SMOCKER_ADMIN_PORT)
|
||||
.withStartupTimeout(120_000)
|
||||
.withWaitStrategy(Wait.forLogMessage(/Starting mock server/))
|
||||
.start();
|
||||
|
||||
try {
|
||||
await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG);
|
||||
} catch (err) {
|
||||
throw new Error(`Failed to build login Docker image: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}, 180_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await mockServer?.stop().catch(() => {});
|
||||
await network?.stop().catch(() => {});
|
||||
});
|
||||
|
||||
describe("when custom CA is provided via SSL_CERT_FILE", () => {
|
||||
let container: StartedTestContainer;
|
||||
|
||||
beforeAll(async () => {
|
||||
container = await new GenericContainer(LOGIN_IMAGE_TAG)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(3000)
|
||||
.withEnvironment({
|
||||
SSL_CERT_FILE: "/etc/ssl/certs/custom-ca.crt",
|
||||
})
|
||||
.withCopyFilesToContainer([
|
||||
{
|
||||
source: path.join(certsDir, "ca.crt"),
|
||||
target: "/etc/ssl/certs/custom-ca.crt",
|
||||
},
|
||||
])
|
||||
.withStartupTimeout(180_000)
|
||||
.withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000))
|
||||
.start();
|
||||
}, 180_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop().catch(() => {});
|
||||
});
|
||||
|
||||
it("can establish TLS connection to server with custom CA", async () => {
|
||||
const result = await testTlsConnection(container, "https://mock-zitadel/");
|
||||
expect(result.exitCode).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when custom CA is provided via SSL_CERT_DIR (non-hashed filename)", () => {
|
||||
let container: StartedTestContainer;
|
||||
let customCaDir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
customCaDir = fs.mkdtempSync(path.join(os.tmpdir(), "ca-dir-test-"));
|
||||
fs.writeFileSync(path.join(customCaDir, "corp-root.crt"), fs.readFileSync(path.join(certsDir, "ca.crt")));
|
||||
|
||||
container = await new GenericContainer(LOGIN_IMAGE_TAG)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(3000)
|
||||
.withEnvironment({
|
||||
SSL_CERT_DIR: "/custom-certs",
|
||||
})
|
||||
.withCopyFilesToContainer([
|
||||
{
|
||||
source: path.join(customCaDir, "corp-root.crt"),
|
||||
target: "/custom-certs/corp-root.crt",
|
||||
},
|
||||
])
|
||||
.withStartupTimeout(180_000)
|
||||
.withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000))
|
||||
.start();
|
||||
}, 180_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop().catch(() => {});
|
||||
});
|
||||
|
||||
it("can establish TLS connection with non-hashed cert in SSL_CERT_DIR", async () => {
|
||||
const result = await testTlsConnection(container, "https://mock-zitadel/");
|
||||
expect(result.exitCode).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when custom CA certificate is not provided", () => {
|
||||
let container: StartedTestContainer;
|
||||
|
||||
beforeAll(async () => {
|
||||
container = await new GenericContainer(LOGIN_IMAGE_TAG)
|
||||
.withNetwork(network)
|
||||
.withExposedPorts(3000)
|
||||
.withStartupTimeout(180_000)
|
||||
.withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000))
|
||||
.start();
|
||||
}, 180_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop().catch(() => {});
|
||||
});
|
||||
|
||||
it("cannot establish TLS connection without custom CA", async () => {
|
||||
const result = await testTlsConnection(container, "https://mock-zitadel/");
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import forge from "node-forge";
|
||||
|
||||
/**
|
||||
* Generates a self-signed CA certificate and a server certificate signed by
|
||||
* that CA, returning both as PEM-encoded strings alongside their private keys.
|
||||
*
|
||||
* This is intended for test and development environments where a trusted
|
||||
* certificate chain is needed without relying on the openssl binary. The
|
||||
* server certificate includes Subject Alternative Names so that TLS clients
|
||||
* can verify the connection against the expected hostnames and IP addresses.
|
||||
*/
|
||||
export function generateCertificates({
|
||||
caCN = "Test CA",
|
||||
serverCN = "mock-zitadel",
|
||||
dns = ["mock-zitadel", "localhost"],
|
||||
ips = ["127.0.0.1"],
|
||||
days = 1,
|
||||
} = {}) {
|
||||
function createCert({
|
||||
subject,
|
||||
issuer,
|
||||
publicKey,
|
||||
signingKey,
|
||||
extensions,
|
||||
serial = "01",
|
||||
}: {
|
||||
subject: forge.pki.CertificateField[];
|
||||
issuer: forge.pki.CertificateField[];
|
||||
publicKey: forge.pki.rsa.PublicKey;
|
||||
signingKey: forge.pki.rsa.PrivateKey;
|
||||
extensions?: forge.pki.CertificateField[];
|
||||
serial?: string;
|
||||
}) {
|
||||
const cert = forge.pki.createCertificate();
|
||||
cert.publicKey = publicKey;
|
||||
cert.serialNumber = serial;
|
||||
cert.validity.notBefore = new Date();
|
||||
cert.validity.notAfter = new Date(Date.now() + days * 86400000);
|
||||
cert.setSubject(subject);
|
||||
cert.setIssuer(issuer);
|
||||
if (extensions) {
|
||||
cert.setExtensions(extensions);
|
||||
}
|
||||
cert.sign(signingKey, forge.md.sha256.create());
|
||||
return forge.pki.certificateToPem(cert);
|
||||
}
|
||||
|
||||
const caKeys = forge.pki.rsa.generateKeyPair(2048);
|
||||
const serverKeys = forge.pki.rsa.generateKeyPair(2048);
|
||||
const caSubject = [{ name: "commonName", value: caCN }];
|
||||
|
||||
return {
|
||||
ca: {
|
||||
cert: createCert({
|
||||
subject: caSubject,
|
||||
issuer: caSubject,
|
||||
publicKey: caKeys.publicKey,
|
||||
signingKey: caKeys.privateKey,
|
||||
extensions: [{ name: "basicConstraints", cA: true }],
|
||||
}),
|
||||
key: forge.pki.privateKeyToPem(caKeys.privateKey),
|
||||
},
|
||||
server: {
|
||||
cert: createCert({
|
||||
subject: [{ name: "commonName", value: serverCN }],
|
||||
issuer: caSubject,
|
||||
publicKey: serverKeys.publicKey,
|
||||
signingKey: caKeys.privateKey,
|
||||
serial: "02",
|
||||
extensions: [
|
||||
{
|
||||
name: "subjectAltName",
|
||||
altNames: [
|
||||
...dns.map(function (value) {
|
||||
return { type: 2, value };
|
||||
}),
|
||||
...ips.map(function (ip) {
|
||||
return { type: 7, ip };
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
key: forge.pki.privateKeyToPem(serverKeys.privateKey),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Mock Zitadel ConnectRPC server for testing trace propagation.
|
||||
* Captures incoming headers and writes them to a file for test assertions.
|
||||
*/
|
||||
const http = require("http");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const PORT = process.env.PORT || 8080;
|
||||
const OUTPUT_DIR = process.env.OUTPUT_DIR || "/tmp/otel";
|
||||
const HEADERS_FILE = path.join(OUTPUT_DIR, "captured-headers.json");
|
||||
|
||||
/**
|
||||
* Safely stringify a value to JSON with XSS-preventing character escapes.
|
||||
*
|
||||
* Escapes `<`, `>`, `&`, and `/` to their Unicode equivalents to prevent
|
||||
* script injection when the output is reflected in HTTP responses or
|
||||
* embedded in HTML contexts.
|
||||
*
|
||||
* @param {unknown} value - The value to stringify
|
||||
* @returns {string} JSON string with dangerous characters escaped
|
||||
*/
|
||||
function safeJsonStringify(value) {
|
||||
return JSON.stringify(value, null, 2)
|
||||
.replace(/</g, "\\u003c")
|
||||
.replace(/>/g, "\\u003e")
|
||||
.replace(/&/g, "\\u0026")
|
||||
.replace(/\//g, "\\/");
|
||||
}
|
||||
|
||||
// Store captured requests
|
||||
const capturedRequests = [];
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const { method, url } = req;
|
||||
|
||||
// Capture trace headers
|
||||
const traceHeaders = {
|
||||
timestamp: new Date().toISOString(),
|
||||
method,
|
||||
url,
|
||||
traceparent: req.headers["traceparent"] || null,
|
||||
tracestate: req.headers["tracestate"] || null,
|
||||
baggage: req.headers["baggage"] || null,
|
||||
contentType: req.headers["content-type"] || null,
|
||||
};
|
||||
|
||||
capturedRequests.push(traceHeaders);
|
||||
|
||||
// Write to file for test assertions
|
||||
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
|
||||
fs.writeFileSync(HEADERS_FILE, JSON.stringify(capturedRequests, null, 2));
|
||||
|
||||
console.log(`[${traceHeaders.timestamp}] ${method} ${url}`);
|
||||
console.log(` traceparent: ${traceHeaders.traceparent || "(none)"}`);
|
||||
|
||||
const sendResponse = (statusCode, contentType, body) => {
|
||||
res.writeHead(statusCode, { "Content-Type": contentType });
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
// Health check
|
||||
if (url.includes("/health") || url === "/") {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ status: "ok" }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Return captured headers (for debugging)
|
||||
if (url === "/captured-headers") {
|
||||
sendResponse(200, "application/json", safeJsonStringify(capturedRequests));
|
||||
return;
|
||||
}
|
||||
|
||||
// Mock ConnectRPC responses
|
||||
// These are minimal responses to prevent the login app from crashing
|
||||
if (url.includes("GetLoginSettings") || url.includes("SettingsService")) {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ settings: {} }));
|
||||
} else if (url.includes("GetBrandingSettings")) {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ settings: {} }));
|
||||
} else if (url.includes("SessionService") || url.includes("Session")) {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ session: {} }));
|
||||
} else if (url.includes("UserService") || url.includes("User")) {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ user: {} }));
|
||||
} else if (url.includes("OrganizationService") || url.includes("Organization")) {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ result: [] }));
|
||||
} else if (url.includes("IdentityProviderService") || url.includes("IdentityProvider")) {
|
||||
sendResponse(200, "application/json", safeJsonStringify({ identityProviders: [] }));
|
||||
} else {
|
||||
sendResponse(200, "application/json", safeJsonStringify({}));
|
||||
}
|
||||
});
|
||||
|
||||
server.on("error", (err) => console.error("Server error:", err));
|
||||
|
||||
server.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`Mock Zitadel server listening on port ${PORT}`);
|
||||
console.log(`Captured headers will be written to: ${HEADERS_FILE}`);
|
||||
});
|
||||
|
||||
// Graceful shutdown
|
||||
process.on("SIGTERM", () => {
|
||||
console.log("Shutting down mock server...");
|
||||
server.close(() => {
|
||||
console.log("Mock server stopped");
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 1024
|
||||
|
||||
exporters:
|
||||
debug:
|
||||
verbosity: detailed
|
||||
file/traces:
|
||||
path: /tmp/otel/traces.json
|
||||
flush_interval: 1s
|
||||
file/metrics:
|
||||
path: /tmp/otel/metrics.json
|
||||
flush_interval: 1s
|
||||
file/logs:
|
||||
path: /tmp/otel/logs.json
|
||||
flush_interval: 1s
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [batch]
|
||||
exporters: [debug, file/traces]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [batch]
|
||||
exporters: [debug, file/metrics]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [batch]
|
||||
exporters: [debug, file/logs]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,119 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import { GenericContainer, type StartedTestContainer, Wait } from "testcontainers";
|
||||
import * as https from "node:https";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { generateCertificates } from "../ca/utils/tls.ts";
|
||||
|
||||
const TEST_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const OUTPUT_DIR = path.join(TEST_DIR, "output");
|
||||
const CERTS_DIR = path.join(OUTPUT_DIR, "certs");
|
||||
const LOGIN_APP_DIR = path.join(TEST_DIR, "../..");
|
||||
const LOGIN_IMAGE_TAG = `zitadel-login-test:${process.env.GITHUB_SHA || "local"}`;
|
||||
|
||||
/**
|
||||
* Integration tests for TLS support in the login application.
|
||||
*
|
||||
* These tests verify that the login container can serve traffic over HTTPS
|
||||
* when configured with ZITADEL_TLS_ENABLED, ZITADEL_TLS_CERTPATH, and
|
||||
* ZITADEL_TLS_KEYPATH environment variables. This is essential for deployments
|
||||
* where the login application must terminate TLS itself rather than relying on
|
||||
* a reverse proxy.
|
||||
*
|
||||
* The test suite builds the login container image and runs it in two modes:
|
||||
* HTTP (default) and HTTPS (with TLS enabled). For HTTPS mode, a self-signed
|
||||
* certificate is generated and mounted into the container. The tests verify
|
||||
* that the application starts correctly and responds to health checks in both
|
||||
* modes.
|
||||
*/
|
||||
describe("Login Container TLS Support", () => {
|
||||
let loginImage: GenericContainer;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (fs.existsSync(OUTPUT_DIR)) {
|
||||
fs.rmSync(OUTPUT_DIR, { recursive: true });
|
||||
}
|
||||
fs.mkdirSync(CERTS_DIR, { recursive: true });
|
||||
|
||||
const certs = generateCertificates({
|
||||
serverCN: "localhost",
|
||||
dns: ["localhost"],
|
||||
ips: ["127.0.0.1"],
|
||||
});
|
||||
|
||||
fs.writeFileSync(path.join(CERTS_DIR, "server.crt"), certs.server.cert);
|
||||
fs.writeFileSync(path.join(CERTS_DIR, "server.key"), certs.server.key);
|
||||
|
||||
await GenericContainer.fromDockerfile(LOGIN_APP_DIR).build(LOGIN_IMAGE_TAG);
|
||||
loginImage = new GenericContainer(LOGIN_IMAGE_TAG);
|
||||
});
|
||||
|
||||
describe("when TLS is not enabled", () => {
|
||||
let container: StartedTestContainer;
|
||||
let appUrl: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
container = await loginImage
|
||||
.withExposedPorts(3000)
|
||||
.withWaitStrategy(Wait.forHttp("/ui/v2/login/healthy", 3000))
|
||||
.start();
|
||||
|
||||
appUrl = `http://${container.getHost()}:${container.getMappedPort(3000)}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop();
|
||||
});
|
||||
|
||||
it("returns 200 from healthy endpoint", async () => {
|
||||
const response = await fetch(`${appUrl}/ui/v2/login/healthy`);
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when TLS is enabled", () => {
|
||||
let container: StartedTestContainer;
|
||||
let appUrl: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
container = await loginImage
|
||||
.withExposedPorts(3000)
|
||||
.withEnvironment({
|
||||
ZITADEL_TLS_ENABLED: "true",
|
||||
ZITADEL_TLS_CERTPATH: "/certs/server.crt",
|
||||
ZITADEL_TLS_KEYPATH: "/certs/server.key",
|
||||
})
|
||||
.withCopyFilesToContainer([
|
||||
{
|
||||
source: path.join(CERTS_DIR, "server.crt"),
|
||||
target: "/certs/server.crt",
|
||||
},
|
||||
{
|
||||
source: path.join(CERTS_DIR, "server.key"),
|
||||
target: "/certs/server.key",
|
||||
},
|
||||
])
|
||||
.withWaitStrategy(Wait.forLogMessage(/Ready on https/))
|
||||
.start();
|
||||
|
||||
appUrl = `https://${container.getHost()}:${container.getMappedPort(3000)}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await container?.stop();
|
||||
});
|
||||
|
||||
it("returns 200 from healthy endpoint over HTTPS", async () => {
|
||||
const response = await new Promise<https.IncomingMessage>((resolve, reject) => {
|
||||
https
|
||||
.get(`${appUrl}/ui/v2/login/healthy`, { rejectUnauthorized: false }, (res) => {
|
||||
res.resume();
|
||||
resolve(res);
|
||||
})
|
||||
.on("error", reject);
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user