Light, fluffy, and always free - The AWS Local Emulator alternative
feat: optional TLS/HTTPS support with self-signed certificate generation (#754)
Dixit R Jain5befe8b619eb
diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.ymlindex 9b689c5811..a925989651 100644--- a/.github/workflows/compatibility.yml+++ b/.github/workflows/compatibility.yml@@ -97,6 +97,7 @@ jobs:-e FLOCI_SERVICES_DOCKER_NETWORK=compat-net \-e FLOCI_HOSTNAME=floci \-e FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true \+ -e FLOCI_TLS_ENABLED=true \floci:test- name: Wait for floci to be readydiff --git a/compatibility-tests/sdk-test-node/Dockerfile b/compatibility-tests/sdk-test-node/Dockerfileindex a3236113b0..939a038090 100644--- a/compatibility-tests/sdk-test-node/Dockerfile+++ b/compatibility-tests/sdk-test-node/Dockerfile@@ -8,6 +8,7 @@ COPY tsconfig.json vitest.config.ts ./COPY tests/ tests/ENV FLOCI_ENDPOINT=http://floci:4566+ENV NODE_TLS_REJECT_UNAUTHORIZED=0ENV TEST_RESULTS_DIR=/resultsRUN mkdir -p /resultsdiff --git a/compatibility-tests/sdk-test-node/README.md b/compatibility-tests/sdk-test-node/README.mdindex 2535a2fd79..5fb8cac49f 100644--- a/compatibility-tests/sdk-test-node/README.md+++ b/compatibility-tests/sdk-test-node/README.md@@ -59,3 +59,30 @@ docker run --rm --network host floci-sdk-node# Custom endpoint (macOS/Windows)docker run --rm -e FLOCI_ENDPOINT=http://host.docker.internal:4566 floci-sdk-node```++## TLS Tests++The `tls.test.ts` file tests HTTPS connectivity with AWS SDK v3 clients.+The `apigatewayv2-websocket-tls.test.ts` file tests WebSocket over TLS (WSS),+covering connect/disconnect, route selection, broadcast, authorization,+`@connections` API, binary frames, and payload limits.++These tests always run as part of the suite — they derive the HTTPS/WSS endpoint+from the HTTP endpoint by swapping the scheme (`http://floci:4566` → `https://floci:4566`,+`ws://` → `wss://`).++Since Floci serves HTTP and HTTPS simultaneously when TLS is enabled, existing HTTP+tests are unaffected.++The Dockerfile sets `NODE_TLS_REJECT_UNAUTHORIZED=0` so self-signed certs are accepted.+The CI workflow starts Floci with `FLOCI_TLS_ENABLED=true`.++To run locally:++```bash+# 1. Start Floci with TLS enabled+FLOCI_TLS_ENABLED=true ./mvnw quarkus:dev++# 2. Run all tests (including TLS)+NODE_TLS_REJECT_UNAUTHORIZED=0 npm test+```diff --git a/compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-tls.test.ts b/compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-tls.test.tsnew file mode 100644index 0000000000..6496c86b00--- /dev/null+++ b/compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-tls.test.ts@@ -0,0 +1,772 @@+/**+ * API Gateway v2 WebSocket over TLS compatibility tests.+ *+ * Validates WebSocket functionality over WSS (TLS): connect, send, receive,+ * disconnect, route selection, @connections API, and server-initiated close —+ * mirroring the plain-text WebSocket tests but using the HTTPS/WSS endpoint.+ *+ * Prerequisites:+ * - Floci must be started with FLOCI_TLS_ENABLED=true+ * - NODE_TLS_REJECT_UNAUTHORIZED=0 must be set in the test environment+ */++import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import {+ ApiGatewayV2Client,+ CreateApiCommand,+ DeleteApiCommand,+ CreateRouteCommand,+ CreateIntegrationCommand,+ CreateStageCommand,+ CreateAuthorizerCommand,+ CreateDeploymentCommand,+} from '@aws-sdk/client-apigatewayv2';+import {+ ApiGatewayManagementApiClient,+ PostToConnectionCommand,+ GetConnectionCommand,+ DeleteConnectionCommand,+} from '@aws-sdk/client-apigatewaymanagementapi';+import {+ LambdaClient,+ CreateFunctionCommand,+ DeleteFunctionCommand,+} from '@aws-sdk/client-lambda';+import WebSocket from 'ws';+import { uniqueName, ENDPOINT, REGION, ACCOUNT, CREDS, buildMinimalZip, buildBundledZip, sleep } from './setup';++// ── TLS Helpers ──────────────────────────────────────────────────────────────++const HTTPS_ENDPOINT = ENDPOINT.replace(/^http:\/\//, 'https://');++const TLS_CLIENT_CONFIG = {+ endpoint: HTTPS_ENDPOINT,+ region: REGION,+ credentials: CREDS,+ forcePathStyle: true,+};++function makeTlsClient<T>(+ ClientClass: new (config: typeof TLS_CLIENT_CONFIG) => T,+ extra: Record<string, unknown> = {},+): T {+ return new ClientClass({ ...TLS_CLIENT_CONFIG, ...extra });+}++function wssUrl(apiId: string, stage: string): string {+ // Convert http endpoint to wss — strip scheme and trailing slashes+ const host = ENDPOINT.replace(/^https?:\/\//, '').replace(/\/$/, '');+ return `wss://${host}/ws/${apiId}/${stage}`;+}++function managementClientTls(apiId: string, stage: string): ApiGatewayManagementApiClient {+ return makeTlsClient(ApiGatewayManagementApiClient, {+ endpoint: `${HTTPS_ENDPOINT}/execute-api/${apiId}/${stage}`,+ });+}++function connectWss(url: string): Promise<WebSocket> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(url, { rejectUnauthorized: false });+ ws.on('open', () => resolve(ws));+ ws.on('error', (err) => reject(err));+ });+}++function waitForMessage(ws: WebSocket, timeoutMs = 5000): Promise<string> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('Timeout waiting for message')), timeoutMs);+ ws.once('message', (data) => {+ clearTimeout(timer);+ resolve(data.toString());+ });+ });+}++function waitForClose(ws: WebSocket, timeoutMs = 5000): Promise<void> {+ return new Promise((resolve, reject) => {+ if (ws.readyState === WebSocket.CLOSED) { resolve(); return; }+ const timer = setTimeout(() => reject(new Error('Timeout waiting for close')), timeoutMs);+ ws.once('close', () => { clearTimeout(timer); resolve(); });+ });+}++const ROLE_ARN = `arn:aws:iam::${ACCOUNT}:role/lambda-role`;++// ── Lambda handler source code ───────────────────────────────────────────────++const ECHO_HANDLER = `+exports.handler = async (event) => {+ const body = event.body || '';+ try {+ const parsed = JSON.parse(body);+ if (parsed.action === 'getConnectionId') {+ return { statusCode: 200, body: JSON.stringify({ connectionId: event.requestContext.connectionId }) };+ }+ } catch (e) {}+ return { statusCode: 200, body: body || 'echo' };+};+`;++const PING_HANDLER = `+exports.handler = async (event) => {+ return { statusCode: 200, body: 'pong' };+};+`;++const SEND_MESSAGE_HANDLER = `+exports.handler = async (event) => {+ const body = JSON.parse(event.body);+ return { statusCode: 200, body: 'received: ' + body.data };+};+`;++const DEFAULT_HANDLER = `+exports.handler = async (event) => {+ return { statusCode: 200, body: 'default-route' };+};+`;++const BROADCAST_HANDLER = `+const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');+exports.handler = async (event) => {+ const apiId = event.requestContext.apiId;+ const stage = event.requestContext.stage;+ const endpoint = process.env.FLOCI_ENDPOINT + '/execute-api/' + apiId + '/' + stage;+ const client = new ApiGatewayManagementApiClient({ endpoint, region: 'us-east-1' });+ const body = JSON.parse(event.body);+ for (const connId of body.targets) {+ await client.send(new PostToConnectionCommand({+ ConnectionId: connId,+ Data: Buffer.from(body.message),+ }));+ }+ return { statusCode: 200 };+};+`;++const AUTHORIZER_HANDLER = `+exports.handler = async (event) => {+ const token = event.queryStringParameters && event.queryStringParameters.token;+ const effect = token === 'allow' ? 'Allow' : 'Deny';+ return {+ principalId: 'user',+ policyDocument: {+ Version: '2012-10-17',+ Statement: [{ Action: 'execute-api:Invoke', Effect: effect, Resource: event.methodArn || '*' }],+ },+ };+};+`;++// ── Helper to get connection ID ──────────────────────────────────────────────++async function getConnectionIdFromServer(ws: WebSocket): Promise<string | null> {+ ws.send(JSON.stringify({ action: 'getConnectionId' }));+ try {+ const response = await waitForMessage(ws, 3000);+ const parsed = JSON.parse(response);+ return parsed.connectionId || null;+ } catch {+ return null;+ }+}++// ── Test suites ──────────────────────────────────────────────────────────────++describe('WebSocket over TLS (WSS)', () => {+ let gw: ApiGatewayV2Client;+ let lambda: LambdaClient;++ const createdFunctions: string[] = [];+ const createdApis: string[] = [];++ beforeAll(() => {+ gw = makeTlsClient(ApiGatewayV2Client);+ lambda = makeTlsClient(LambdaClient);+ });++ afterAll(async () => {+ for (const fnName of createdFunctions) {+ try { await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName })); } catch { /* ignore */ }+ }+ for (const apiId of createdApis) {+ try { await gw.send(new DeleteApiCommand({ ApiId: apiId })); } catch { /* ignore */ }+ }+ });++ async function createLambda(name: string, code: string, environment?: Record<string, string>, bundledZip?: boolean): Promise<string> {+ const fnName = uniqueName(name);+ const zipBuffer = bundledZip ? buildBundledZip(code) : buildMinimalZip('index.js', Buffer.from(code));+ await lambda.send(new CreateFunctionCommand({+ FunctionName: fnName,+ Runtime: 'nodejs22.x',+ Role: ROLE_ARN,+ Handler: 'index.handler',+ Code: { ZipFile: zipBuffer },+ ...(environment && { Environment: { Variables: environment } }),+ }));+ createdFunctions.push(fnName);+ return fnName;+ }++ async function createWsApi(name: string): Promise<string> {+ const res = await gw.send(new CreateApiCommand({+ Name: uniqueName(name),+ ProtocolType: 'WEBSOCKET',+ RouteSelectionExpression: '$request.body.action',+ }));+ createdApis.push(res.ApiId!);+ return res.ApiId!;+ }++ async function createLambdaIntegration(apiId: string, fnName: string): Promise<string> {+ const res = await gw.send(new CreateIntegrationCommand({+ ApiId: apiId,+ IntegrationType: 'AWS_PROXY',+ IntegrationUri: `arn:aws:lambda:${REGION}:${ACCOUNT}:function:${fnName}`,+ }));+ return res.IntegrationId!;+ }++ async function setupStage(apiId: string, stageName: string): Promise<void> {+ const deploy = await gw.send(new CreateDeploymentCommand({ ApiId: apiId }));+ await gw.send(new CreateStageCommand({+ ApiId: apiId,+ StageName: stageName,+ DeploymentId: deploy.DeploymentId!,+ }));+ }++ // ──────────────────────────── Basic WSS flow ────────────────────────────++ describe('Basic WSS connection flow', () => {+ let apiId: string;++ beforeAll(async () => {+ const echoFn = await createLambda('tls-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-basic');++ const integId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${integId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${integId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should connect over WSS, send message, receive response, and disconnect', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ ws.send(JSON.stringify({ action: 'test', body: 'hello-tls' }));+ const response = await waitForMessage(ws);+ expect(response).toBeTruthy();+ ws.close();+ await waitForClose(ws);+ } finally {+ if (ws.readyState !== WebSocket.CLOSED) ws.close();+ }+ });++ it('should establish WSS connection with valid readyState', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ expect(ws.readyState).toBe(WebSocket.OPEN);+ } finally {+ ws.close();+ }+ });+ });++ // ──────────────────────────── Chat-style broadcast over WSS ────────────────────────────++ describe('Chat-style broadcast over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const broadcastFn = await createLambda('tls-broadcast', BROADCAST_HANDLER, {+ FLOCI_ENDPOINT: 'https://host.docker.internal:4566',+ NODE_TLS_REJECT_UNAUTHORIZED: '0',+ }, true);+ const echoFn = await createLambda('tls-bc-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-broadcast');++ const broadcastIntegId = await createLambdaIntegration(apiId, broadcastFn);+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${echoIntegId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${echoIntegId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: 'broadcast',+ Target: `integrations/${broadcastIntegId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should broadcast message to multiple WSS clients', async () => {+ const ws1 = await connectWss(wssUrl(apiId, 'test'));+ const ws2 = await connectWss(wssUrl(apiId, 'test'));+ try {+ await sleep(200);++ const connId1 = await getConnectionIdFromServer(ws1);+ const connId2 = await getConnectionIdFromServer(ws2);++ expect(connId1).toBeTruthy();+ expect(connId2).toBeTruthy();++ const msg1Promise = waitForMessage(ws1);+ const msg2Promise = waitForMessage(ws2);++ ws1.send(JSON.stringify({+ action: 'broadcast',+ targets: [connId1, connId2],+ message: 'hello-all-tls',+ }));++ const [r1, r2] = await Promise.all([msg1Promise, msg2Promise]);+ expect(r1).toBe('hello-all-tls');+ expect(r2).toBe('hello-all-tls');+ } finally {+ ws1.close();+ ws2.close();+ }+ });+ });++ // ──────────────────────────── $connect authorization over WSS ────────────────────────────++ describe('$connect authorization over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const authFn = await createLambda('tls-authorizer', AUTHORIZER_HANDLER);+ const echoFn = await createLambda('tls-auth-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-auth');++ const echoIntegId = await createLambdaIntegration(apiId, echoFn);++ const authRes = await gw.send(new CreateAuthorizerCommand({+ ApiId: apiId,+ AuthorizerType: 'REQUEST',+ Name: 'wss-auth',+ AuthorizerUri: `arn:aws:lambda:${REGION}:${ACCOUNT}:function:${authFn}`,+ IdentitySource: ['route.request.querystring.token'],+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${echoIntegId}`,+ AuthorizationType: 'CUSTOM',+ AuthorizerId: authRes.AuthorizerId!,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${echoIntegId}`,+ }));++ await setupStage(apiId, 'test');+ });++ it('should allow WSS connection with valid token', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test') + '?token=allow');+ try {+ expect(ws.readyState).toBe(WebSocket.OPEN);+ } finally {+ ws.close();+ }+ });++ it('should deny WSS connection with invalid token', async () => {+ await expect(connectWss(wssUrl(apiId, 'test') + '?token=deny')).rejects.toThrow();+ });+ });++ // ──────────────────────────── Route selection over WSS ────────────────────────────++ describe('Route selection over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const pingFn = await createLambda('tls-ping', PING_HANDLER);+ const sendMsgFn = await createLambda('tls-sendmsg', SEND_MESSAGE_HANDLER);+ const defaultFn = await createLambda('tls-default', DEFAULT_HANDLER);+ const echoFn = await createLambda('tls-rs-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-route-sel');++ const pingIntegId = await createLambdaIntegration(apiId, pingFn);+ const sendMsgIntegId = await createLambdaIntegration(apiId, sendMsgFn);+ const defaultIntegId = await createLambdaIntegration(apiId, defaultFn);+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${echoIntegId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: 'ping',+ Target: `integrations/${pingIntegId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: 'sendMessage',+ Target: `integrations/${sendMsgIntegId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${defaultIntegId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should route "ping" action over WSS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ ws.send(JSON.stringify({ action: 'ping' }));+ const response = await waitForMessage(ws);+ expect(response).toBe('pong');+ } finally {+ ws.close();+ }+ });++ it('should route "sendMessage" action over WSS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ ws.send(JSON.stringify({ action: 'sendMessage', data: 'tls-data' }));+ const response = await waitForMessage(ws);+ expect(response).toBe('received: tls-data');+ } finally {+ ws.close();+ }+ });++ it('should route unknown action to $default over WSS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ ws.send(JSON.stringify({ action: 'unknownAction' }));+ const response = await waitForMessage(ws);+ expect(response).toBe('default-route');+ } finally {+ ws.close();+ }+ });+ });++ // ──────────────────────────── @connections API over TLS ────────────────────────────++ describe('@connections API over TLS', () => {+ let apiId: string;++ beforeAll(async () => {+ const echoFn = await createLambda('tls-conn-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-connections');++ const integId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${integId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${integId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should POST message to a WSS connection via @connections', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ await sleep(200);+ const connId = await getConnectionIdFromServer(ws);+ expect(connId).toBeTruthy();++ const mgmt = managementClientTls(apiId, 'test');+ const msgPromise = waitForMessage(ws);++ await mgmt.send(new PostToConnectionCommand({+ ConnectionId: connId!,+ Data: Buffer.from('tls-server-push'),+ }));++ const received = await msgPromise;+ expect(received).toBe('tls-server-push');+ } finally {+ ws.close();+ }+ });++ it('should GET connection info over TLS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ await sleep(200);+ const connId = await getConnectionIdFromServer(ws);+ expect(connId).toBeTruthy();++ const mgmt = managementClientTls(apiId, 'test');+ const info = await mgmt.send(new GetConnectionCommand({+ ConnectionId: connId!,+ }));++ expect(info.ConnectedAt).toBeDefined();+ } finally {+ ws.close();+ }+ });++ it('should DELETE (disconnect) a WSS connection', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ await sleep(200);+ const connId = await getConnectionIdFromServer(ws);+ expect(connId).toBeTruthy();++ const mgmt = managementClientTls(apiId, 'test');+ await mgmt.send(new DeleteConnectionCommand({+ ConnectionId: connId!,+ }));++ await waitForClose(ws);+ expect(ws.readyState).toBe(WebSocket.CLOSED);+ } finally {+ if (ws.readyState !== WebSocket.CLOSED) ws.close();+ }+ });+ });++ // ──────────────────────────── Disconnect cleanup over WSS ────────────────────────────++ describe('Disconnect cleanup over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const echoFn = await createLambda('tls-dc-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-disconnect');++ const integId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${integId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${integId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should return 410 when posting to a disconnected WSS connection', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ await sleep(200);+ const connId = await getConnectionIdFromServer(ws);+ expect(connId).toBeTruthy();++ ws.close();+ await waitForClose(ws);+ await sleep(300);++ const mgmt = managementClientTls(apiId, 'test');+ await expect(+ mgmt.send(new PostToConnectionCommand({+ ConnectionId: connId!,+ Data: Buffer.from('should-fail'),+ }))+ ).rejects.toThrow(/410|Gone/);+ });+ });++ // ──────────────────────────── Server-initiated close over WSS ────────────────────────────++ describe('Server-initiated close via DELETE over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const echoFn = await createLambda('tls-del-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-server-close');++ const integId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${integId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${integId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should disconnect WSS client and return 410 on subsequent POST', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ await sleep(200);+ const connId = await getConnectionIdFromServer(ws);+ expect(connId).toBeTruthy();++ const mgmt = managementClientTls(apiId, 'test');+ await mgmt.send(new DeleteConnectionCommand({+ ConnectionId: connId!,+ }));++ await waitForClose(ws);+ await sleep(300);++ await expect(+ mgmt.send(new PostToConnectionCommand({+ ConnectionId: connId!,+ Data: Buffer.from('should-fail'),+ }))+ ).rejects.toThrow(/410|Gone/);+ });+ });++ // ──────────────────────────── Binary frames over WSS ────────────────────────────++ describe('Binary frame support over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const echoFn = await createLambda('tls-bin-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-binary');++ const integId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${integId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${integId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should handle binary frames over WSS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ const binaryData = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05]);+ ws.send(binaryData);++ const response = await waitForMessage(ws);+ expect(response).toBeTruthy();+ } finally {+ ws.close();+ }+ });+ });++ // ──────────────────────────── Payload size limit over WSS ────────────────────────────++ describe('Payload size limit over WSS', () => {+ let apiId: string;++ beforeAll(async () => {+ const echoFn = await createLambda('tls-pl-echo', ECHO_HANDLER);+ apiId = await createWsApi('tls-payload');++ const integId = await createLambdaIntegration(apiId, echoFn);++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$connect',+ Target: `integrations/${integId}`,+ }));++ await gw.send(new CreateRouteCommand({+ ApiId: apiId,+ RouteKey: '$default',+ Target: `integrations/${integId}`,+ RouteResponseSelectionExpression: '$default',+ }));++ await setupStage(apiId, 'test');+ });++ it('should reject messages exceeding 128 KB over WSS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ const oversizeMessage = 'x'.repeat(128 * 1024 + 1);+ ws.send(oversizeMessage);+ const response = await waitForMessage(ws);+ expect(response).toContain('Message too long');+ } finally {+ ws.close();+ }+ });++ it('should accept messages at exactly 128 KB over WSS', async () => {+ const ws = await connectWss(wssUrl(apiId, 'test'));+ try {+ const maxMessage = JSON.stringify({ action: 'test', data: 'x'.repeat(128 * 1024 - 50) });+ if (maxMessage.length <= 128 * 1024) {+ ws.send(maxMessage);+ const response = await waitForMessage(ws);+ expect(response).toBeTruthy();+ expect(response).not.toContain('Message too long');+ }+ } finally {+ ws.close();+ }+ });+ });+});diff --git a/compatibility-tests/sdk-test-node/tests/tls.test.ts b/compatibility-tests/sdk-test-node/tests/tls.test.tsnew file mode 100644index 0000000000..89c1ebfe77--- /dev/null+++ b/compatibility-tests/sdk-test-node/tests/tls.test.ts@@ -0,0 +1,175 @@+/**+ * TLS/HTTPS connectivity tests for floci.+ *+ * Verifies that AWS SDK v3 clients can interact with floci over HTTPS+ * when TLS is enabled with a self-signed certificate.+ *+ * These tests run within the existing test suite. Since Floci serves HTTP+ * and HTTPS simultaneously, existing HTTP tests are unaffected. The HTTPS+ * endpoint is derived from the HTTP endpoint by swapping the scheme.+ *+ * Prerequisites:+ * - Floci must be started with FLOCI_TLS_ENABLED=true+ * - NODE_TLS_REJECT_UNAUTHORIZED=0 must be set in the test environment+ */++import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts';+import {+ SQSClient,+ CreateQueueCommand,+ SendMessageCommand,+ DeleteQueueCommand,+} from '@aws-sdk/client-sqs';+import {+ SSMClient,+ PutParameterCommand,+ GetParameterCommand,+ DeleteParameterCommand,+} from '@aws-sdk/client-ssm';+import {+ S3Client,+ CreateBucketCommand,+ PutObjectCommand,+ GetObjectCommand,+ DeleteObjectCommand,+ DeleteBucketCommand,+} from '@aws-sdk/client-s3';+import { ENDPOINT, uniqueName, ACCOUNT, REGION, CREDS } from './setup';++// Derive the HTTPS endpoint from the HTTP endpoint by swapping the scheme.+// When TLS is enabled, Floci serves HTTPS on port 4566 (same port as HTTP without TLS).+const HTTPS_ENDPOINT = ENDPOINT.replace(/^http:\/\//, 'https://');++const TLS_CLIENT_CONFIG = {+ endpoint: HTTPS_ENDPOINT,+ region: REGION,+ credentials: CREDS,+ forcePathStyle: true,+};++function makeTlsClient<T>(+ ClientClass: new (config: typeof TLS_CLIENT_CONFIG) => T,+): T {+ return new ClientClass(TLS_CLIENT_CONFIG);+}++describe('TLS — STS over HTTPS', () => {+ let sts: STSClient;++ beforeAll(() => {+ sts = makeTlsClient(STSClient);+ });++ it('should call GetCallerIdentity over HTTPS', async () => {+ const response = await sts.send(new GetCallerIdentityCommand({}));+ expect(response.Account).toBe(ACCOUNT);+ expect(response.Arn).toBeTruthy();+ });+});++describe('TLS — SQS over HTTPS', () => {+ let sqs: SQSClient;+ let queueUrl: string;++ beforeAll(() => {+ sqs = makeTlsClient(SQSClient);+ });++ afterAll(async () => {+ if (queueUrl) {+ try {+ await sqs.send(new DeleteQueueCommand({ QueueUrl: queueUrl }));+ } catch {+ // ignore+ }+ }+ });++ it('should create a queue and get HTTPS queue URL', async () => {+ const name = uniqueName('tls-sqs');+ const response = await sqs.send(new CreateQueueCommand({ QueueName: name }));+ queueUrl = response.QueueUrl!;+ expect(queueUrl).toMatch(/^https:\/\//);+ expect(queueUrl).toContain(name);+ });++ it('should send a message over HTTPS', async () => {+ const response = await sqs.send(+ new SendMessageCommand({+ QueueUrl: queueUrl,+ MessageBody: 'hello-tls',+ })+ );+ expect(response.MessageId).toBeTruthy();+ });+});++describe('TLS — SSM over HTTPS', () => {+ let ssm: SSMClient;+ const paramName = `/${uniqueName('tls-param')}`;++ beforeAll(() => {+ ssm = makeTlsClient(SSMClient);+ });++ afterAll(async () => {+ try {+ await ssm.send(new DeleteParameterCommand({ Name: paramName }));+ } catch {+ // ignore+ }+ });++ it('should put and get a parameter over HTTPS', async () => {+ await ssm.send(+ new PutParameterCommand({+ Name: paramName,+ Value: 'tls-value',+ Type: 'String',+ })+ );++ const response = await ssm.send(+ new GetParameterCommand({ Name: paramName })+ );+ expect(response.Parameter?.Value).toBe('tls-value');+ });+});++describe('TLS — S3 over HTTPS', () => {+ let s3: S3Client;+ const bucketName = uniqueName('tls-s3');+ const key = 'test-object.txt';++ beforeAll(async () => {+ s3 = makeTlsClient(S3Client);+ await s3.send(new CreateBucketCommand({ Bucket: bucketName }));+ });++ afterAll(async () => {+ try {+ await s3.send(new DeleteObjectCommand({ Bucket: bucketName, Key: key }));+ await s3.send(new DeleteBucketCommand({ Bucket: bucketName }));+ } catch {+ // ignore+ }+ });++ it('should put and get an object over HTTPS', async () => {+ const body = 'hello from TLS';+ await s3.send(+ new PutObjectCommand({+ Bucket: bucketName,+ Key: key,+ Body: body,+ })+ );++ const response = await s3.send(+ new GetObjectCommand({ Bucket: bucketName, Key: key })+ );+ const text = await response.Body!.transformToString();+ expect(text).toBe(body);+ });+});diff --git a/docker/localstack-parity.sh b/docker/localstack-parity.shindex f8915c0de9..810c55a625 100644--- a/docker/localstack-parity.sh+++ b/docker/localstack-parity.sh@@ -63,4 +63,16 @@ elseexport FLOCI_DNS_EXTRA_SUFFIXES="${_parity_suffixes}"fi+# TLS — USE_SSL=1 → FLOCI_TLS_ENABLED=true+if [ "${USE_SSL:-0}" = "1" ]; then+ export FLOCI_TLS_ENABLED="${FLOCI_TLS_ENABLED:-true}"+fi++# TLS — CUSTOM_SSL_CERT_PATH → FLOCI_TLS_CERT_PATH + FLOCI_TLS_KEY_PATH+# LocalStack uses a single combined PEM (cert+key). Floci accepts it in both fields.+if [ -n "${CUSTOM_SSL_CERT_PATH:-}" ]; then+ export FLOCI_TLS_CERT_PATH="${FLOCI_TLS_CERT_PATH:-${CUSTOM_SSL_CERT_PATH}}"+ export FLOCI_TLS_KEY_PATH="${FLOCI_TLS_KEY_PATH:-${CUSTOM_SSL_CERT_PATH}}"+fi+# SERVICES — intentionally ignored; Floci starts all 41 services in ~24ms.diff --git a/docs/configuration/tls.md b/docs/configuration/tls.mdnew file mode 100644index 0000000000..7b4082dd88--- /dev/null+++ b/docs/configuration/tls.md@@ -0,0 +1,187 @@+# TLS / HTTPS++Floci supports optional TLS, enabling `https://` for all REST/JSON/Query endpoints and `wss://` for WebSocket connections. Both HTTP and HTTPS are served simultaneously (LocalStack parity).++## Quick Start++```bash+docker run -e FLOCI_TLS_ENABLED=true -p 4566:4566 floci/floci:latest+```++Then point your SDK at `https://localhost:4566`. Since the certificate is self-signed, disable TLS verification in your client:++```bash+# AWS CLI+aws --endpoint-url https://localhost:4566 --no-verify-ssl sts get-caller-identity++# Node.js+NODE_TLS_REJECT_UNAUTHORIZED=0 node app.js++# Python (boto3)+import boto3+client = boto3.client('sts', endpoint_url='https://localhost:4566', verify=False)+```++## Configuration++| Environment Variable | Default | Description |+|---------------------|---------|-------------|+| `FLOCI_TLS_ENABLED` | `false` | Enable TLS/HTTPS on the server |+| `FLOCI_TLS_CERT_PATH` | *(unset)* | Path to PEM certificate file |+| `FLOCI_TLS_KEY_PATH` | *(unset)* | Path to PEM private key file |+| `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate a self-signed certificate when no cert/key paths provided |++### application.yml++```yaml+floci:+ tls:+ enabled: false+ # cert-path: "/path/to/cert.pem"+ # key-path: "/path/to/key.pem"+ self-signed: true+```++## Self-Signed Certificate++When `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci auto-generates a self-signed certificate at startup. The certificate:++- Is persisted to `{persistent-path}/tls/` and reused across restarts+- Includes `localhost`, `127.0.0.1`, `0.0.0.0`, `*.localhost`, `localhost.floci.io`, and `*.localhost.floci.io` as Subject Alternative Names (SANs)+- Automatically includes custom hostnames from `FLOCI_HOSTNAME` and `FLOCI_BASE_URL` in the SANs+- Is regenerated when hostname configuration changes between restarts++### Custom Hostname Support++If you set `FLOCI_HOSTNAME` or use a custom host in `FLOCI_BASE_URL`, the self-signed certificate automatically includes those hostnames in its SANs. This is essential for Docker Compose setups where containers reference Floci by service name:++```yaml+services:+ floci:+ image: floci/floci:latest+ environment:+ FLOCI_TLS_ENABLED: "true"+ FLOCI_HOSTNAME: floci+ ports:+ - "4566:4566"++ app:+ environment:+ AWS_ENDPOINT_URL: "https://floci:4566"+ NODE_TLS_REJECT_UNAUTHORIZED: "0"+```++The generated certificate will include `floci` in its SANs, so TLS validation succeeds when `app` connects to `https://floci:4566`.++## User-Provided Certificates++To use your own certificate (e.g., from a corporate CA or mkcert):++```bash+docker run \+ -e FLOCI_TLS_ENABLED=true \+ -e FLOCI_TLS_CERT_PATH=/certs/server.crt \+ -e FLOCI_TLS_KEY_PATH=/certs/server.key \+ -v ./certs:/certs:ro \+ -p 4566:4566 \+ floci/floci:latest+```++When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and no self-signed certificate is generated.++## WebSocket (wss://)++When TLS is enabled, WebSocket connections automatically use `wss://`:++```+wss://localhost:4566/ws/{apiId}/{stage}+```++No additional configuration is needed — Vert.x handles TLS at the transport layer transparently.++## SDK Configuration Examples++### AWS SDK for JavaScript v3++```typescript+import { STSClient } from '@aws-sdk/client-sts';+import { NodeHttpHandler } from '@smithy/node-http-handler';+import https from 'node:https';++const client = new STSClient({+ endpoint: 'https://localhost:4566',+ region: 'us-east-1',+ credentials: { accessKeyId: 'test', secretAccessKey: 'test' },+ requestHandler: new NodeHttpHandler({+ httpsAgent: new https.Agent({ rejectUnauthorized: false }),+ }),+});+```++Or set the environment variable globally:++```bash+NODE_TLS_REJECT_UNAUTHORIZED=0 npx vitest run+```++### AWS SDK for Java v2++```java+SdkHttpClient httpClient = ApacheHttpClient.builder()+ .tlsTrustManagersProvider(() -> {+ TrustManager[] trustAll = new TrustManager[]{+ new X509TrustManager() {+ public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }+ public void checkClientTrusted(X509Certificate[] certs, String authType) {}+ public void checkServerTrusted(X509Certificate[] certs, String authType) {}+ }+ };+ return trustAll;+ })+ .build();++StsClient sts = StsClient.builder()+ .endpointOverride(URI.create("https://localhost:4566"))+ .httpClient(httpClient)+ .build();+```++### Python (boto3)++```python+import boto3++client = boto3.client(+ 'sts',+ endpoint_url='https://localhost:4566',+ verify=False, # Disable TLS verification for self-signed cert+ region_name='us-east-1',+ aws_access_key_id='test',+ aws_secret_access_key='test',+)+```++## When Do I Need to Disable TLS Verification?++| Certificate type | Verification disabled? | Why |+|-----------------|----------------------|-----|+| Floci self-signed (default) | **Yes** — `NODE_TLS_REJECT_UNAUTHORIZED=0`, `verify=False`, etc. | The self-signed CA is not in your system's trust store |+| `mkcert` with local CA installed | **No** | `mkcert -install` adds its root CA to the OS trust store |+| Corporate/internal CA already trusted | **No** | Your OS or JVM already trusts the issuing CA |+| Public CA (Let's Encrypt, etc.) | **No** | Trusted by default in all runtimes |++In short: you only need to disable verification when the certificate's issuer is **not** in the client's trust chain. If you provide your own certificate via `FLOCI_TLS_CERT_PATH` and its CA is already trusted by your system, no extra client configuration is needed.++## Troubleshooting++**Certificate errors after changing `FLOCI_HOSTNAME`.**+Floci detects hostname configuration changes and regenerates the certificate automatically. If you still see errors, delete the `{persistent-path}/tls/` directory and restart.++**`DEPTH_ZERO_SELF_SIGNED_CERT` in Node.js.**+This only happens with self-signed certificates. Set `NODE_TLS_REJECT_UNAUTHORIZED=0` or configure a custom HTTPS agent that skips verification. If you use `mkcert` and ran `mkcert -install`, this error should not occur.++**Java `SSLHandshakeException: PKIX path building failed`.**+For self-signed certificates: configure a trust-all TrustManager as shown above, or import the certificate into your JVM's truststore with `keytool -importcert`. For user-provided certificates from a trusted CA, this should not occur.++**Certificate doesn't include my custom hostname.**+Ensure `FLOCI_HOSTNAME` or `FLOCI_BASE_URL` is set *before* Floci starts. The certificate is generated during startup. Check the logs for `TLS: detected custom hostnames: [...]`.diff --git a/mkdocs.yml b/mkdocs.ymlindex dae656dc01..8533216e87 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -66,6 +66,7 @@ nav:- Ports Reference: configuration/ports.md- application.yml Reference: configuration/application-yml.md- Storage Modes: configuration/storage.md+ - TLS / HTTPS: configuration/tls.md- Initialization Hooks: configuration/initialization-hooks.md- Services:- Overview: services/index.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.java b/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.javanew file mode 100644index 0000000000..770ea16747--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.java@@ -0,0 +1,122 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.List;+import java.util.Objects;++/**+ * Metadata for self-signed TLS certificates generated by Floci.+ *+ * <p>+ * This metadata is persisted alongside certificate files to track which hostnames+ * were used during generation. It enables detection of configuration changes on+ * restart, allowing the system to regenerate certificates when hostname configuration+ * changes.+ *+ * <p>+ * The metadata file is stored as JSON at {@code {persistent-path}/tls/floci-selfsigned.metadata.json}.+ */+@JsonIgnoreProperties(ignoreUnknown = true)+@RegisterForReflection+public class CertificateMetadata {++ /**+ * List of hostnames that were included in the certificate's Subject Alternative Names (SANs).+ * This includes both default hostnames (localhost, 127.0.0.1, etc.) and custom hostnames+ * from FLOCI_HOSTNAME and FLOCI_BASE_URL configuration.+ */+ private List<String> hostnames;++ /**+ * ISO-8601 timestamp when the certificate was generated.+ * Used for debugging and auditing purposes.+ */+ private String generatedAt;++ /**+ * Floci version that generated the certificate.+ * Used for debugging and potential future migration scenarios.+ */+ private String flociVersion;++ /**+ * Default constructor for Jackson deserialization.+ */+ public CertificateMetadata() {+ }++ /**+ * Creates certificate metadata with the specified hostnames.+ *+ * @param hostnames List of hostnames included in the certificate SANs+ * @param generatedAt ISO-8601 timestamp when the certificate was generated+ * @param flociVersion Floci version that generated the certificate+ */+ public CertificateMetadata(List<String> hostnames, String generatedAt, String flociVersion) {+ this.hostnames = hostnames;+ this.generatedAt = generatedAt;+ this.flociVersion = flociVersion;+ }++ /**+ * Creates certificate metadata with the specified hostnames and current timestamp.+ *+ * @param hostnames List of hostnames included in the certificate SANs+ * @param flociVersion Floci version that generated the certificate+ * @return New CertificateMetadata instance with current timestamp+ */+ public static CertificateMetadata create(List<String> hostnames, String flociVersion) {+ return new CertificateMetadata(hostnames, Instant.now().toString(), flociVersion);+ }++ public List<String> getHostnames() {+ return hostnames;+ }++ public void setHostnames(List<String> hostnames) {+ this.hostnames = hostnames;+ }++ public String getGeneratedAt() {+ return generatedAt;+ }++ public void setGeneratedAt(String generatedAt) {+ this.generatedAt = generatedAt;+ }++ public String getFlociVersion() {+ return flociVersion;+ }++ public void setFlociVersion(String flociVersion) {+ this.flociVersion = flociVersion;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ CertificateMetadata that = (CertificateMetadata) o;+ return Objects.equals(hostnames, that.hostnames) &&+ Objects.equals(generatedAt, that.generatedAt) &&+ Objects.equals(flociVersion, that.flociVersion);+ }++ @Override+ public int hashCode() {+ return Objects.hash(hostnames, generatedAt, flociVersion);+ }++ @Override+ public String toString() {+ return "CertificateMetadata{" ++ "hostnames=" + hostnames ++ ", generatedAt='" + generatedAt + '\'' ++ ", flociVersion='" + flociVersion + '\'' ++ '}';+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex f21bb1091a..c12839261f 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -27,13 +27,18 @@ public interface EmulatorConfig {Optional<String> hostname();/**- * Returns the effective base URL, taking hostname into account.+ * Returns the effective base URL, taking hostname and TLS into account.* If hostname is set, replaces the host in baseUrl with it.+ * If TLS is enabled, switches the scheme from http:// to https://.*/default String effectiveBaseUrl() {- return hostname()+ String url = hostname().map(h -> baseUrl().replaceFirst("://[^:/]+(:\\d+)?", "://" + h + "$1")).orElse(baseUrl());+ if (tls().enabled() && url.startsWith("http://")) {+ url = "https://" + url.substring(7);+ }+ return url;}@WithDefault("us-east-1")@@ -63,6 +68,8 @@ public interface EmulatorConfig {InitHooksConfig initHooks();+ TlsConfig tls();+interface DnsConfig {/*** Additional hostname suffixes the embedded DNS server will resolve to Floci's@@ -838,6 +845,33 @@ public interface EmulatorConfig {long timeoutSeconds();}+ /**+ * Optional TLS configuration for enabling HTTPS on the Floci server.+ * When enabled, all endpoints are reachable via {@code https://} and+ * WebSocket connections work via {@code wss://}.+ *+ * <p>Both HTTP and HTTPS are served simultaneously (LocalStack parity).+ */+ interface TlsConfig {+ /** Enable TLS/HTTPS on the server. Env: FLOCI_TLS_ENABLED */+ @WithDefault("false")+ boolean enabled();++ /** Path to PEM certificate file. Env: FLOCI_TLS_CERT_PATH */+ Optional<String> certPath();++ /** Path to PEM private key file. Env: FLOCI_TLS_KEY_PATH */+ Optional<String> keyPath();++ /**+ * Auto-generate a self-signed certificate when no cert-path/key-path provided.+ * The generated files are persisted to {@code {storage.persistent-path}/tls/}+ * and reused across restarts. Env: FLOCI_TLS_SELF_SIGNED+ */+ @WithDefault("true")+ boolean selfSigned();+ }+/*** Configuration for Docker container management shared across all services* that spawn Docker containers (Lambda, RDS, ElastiCache, ECS, ECR, MSK).diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.javanew file mode 100644index 0000000000..c14d86d0d5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java@@ -0,0 +1,334 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.eclipse.microprofile.config.spi.ConfigSource;+import org.jboss.logging.Logger;++import java.io.IOException;+import java.net.URI;+import java.net.URISyntaxException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.security.Security;++/**+ * A MicroProfile {@link ConfigSource} that dynamically provides Quarkus TLS/SSL+ * configuration when {@code floci.tls.enabled=true}.+ *+ * <p>+ * This runs <em>before</em> the Quarkus HTTP server starts, which is critical+ * because Quarkus reads {@code quarkus.http.ssl.*} properties during server+ * initialization. A CDI {@code @Startup} bean or {@code StartupEvent} observer+ * would be too late.+ *+ * <p>+ * When TLS is enabled with self-signed mode, the certificate is generated+ * using the ACM {@link CertificateGenerator} and persisted under+ * {@code {persistent-path}/tls/} for reuse across restarts.+ *+ * <p>+ * Both HTTP and HTTPS are served simultaneously (LocalStack parity).+ */+public class TlsConfigSource implements ConfigSource {++ private static final Logger LOG = Logger.getLogger(TlsConfigSource.class);++ private static final String SELF_SIGNED_CERT_NAME = "floci-selfsigned.crt";+ private static final String SELF_SIGNED_KEY_NAME = "floci-selfsigned.key";+ private static final String SELF_SIGNED_METADATA_NAME = "floci-selfsigned.metadata.json";+ private static final String TLS_DIR = "tls";+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();++ private final Map<String, String> properties = new HashMap<>();++ public TlsConfigSource() {+ String enabled = resolveProperty("floci.tls.enabled", "false");+ if (!"true".equalsIgnoreCase(enabled)) {+ LOG.debug("TLS disabled — TlsConfigSource inactive");+ return;+ }++ String certPath = resolveProperty("floci.tls.cert-path", "");+ String keyPath = resolveProperty("floci.tls.key-path", "");+ String selfSigned = resolveProperty("floci.tls.self-signed", "true");+ String persistentPath = resolveProperty("floci.storage.persistent-path", "./data");++ if (!certPath.isBlank() && !keyPath.isBlank()) {+ validateFileExists(certPath, "TLS certificate");+ validateFileExists(keyPath, "TLS private key");+ LOG.infov("TLS: using user-provided certificate: {0}", certPath);+ } else if ("true".equalsIgnoreCase(selfSigned)) {+ Path tlsDir = Path.of(persistentPath, TLS_DIR);+ Path certFile = tlsDir.resolve(SELF_SIGNED_CERT_NAME);+ Path keyFile = tlsDir.resolve(SELF_SIGNED_KEY_NAME);++ // Check if certificate files exist and configuration hasn't changed+ if (Files.exists(certFile) && Files.exists(keyFile)) {+ // Extract current hostname configuration+ List<String> customHostnames = extractCustomHostnames();+ List<String> currentHostnames = new ArrayList<>();+ currentHostnames.addAll(List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io"));+ currentHostnames.addAll(customHostnames);++ // Check if hostname configuration has changed+ if (hostnameConfigChanged(tlsDir, currentHostnames)) {+ // Configuration changed or metadata missing - regenerate certificate+ generateSelfSignedCert(tlsDir, certFile, keyFile);+ } else {+ // Configuration unchanged - reuse existing certificate+ LOG.infov("TLS: reusing existing self-signed certificate: {0}", certFile);+ }+ } else {+ // Certificate files don't exist - generate new certificate+ generateSelfSignedCert(tlsDir, certFile, keyFile);+ }++ certPath = certFile.toAbsolutePath().toString();+ keyPath = keyFile.toAbsolutePath().toString();+ } else {+ throw new IllegalStateException(+ "TLS enabled but no certificate provided and self-signed generation disabled. "+ + "Set FLOCI_TLS_CERT_PATH + FLOCI_TLS_KEY_PATH, or enable FLOCI_TLS_SELF_SIGNED.");+ }++ properties.put("quarkus.http.ssl.certificate.files", certPath);+ properties.put("quarkus.http.ssl.certificate.key-files", keyPath);+ // When TLS is enabled, Quarkus HTTP and HTTPS run on internal ports.+ // A TlsProxyServer (NetServer) listens on the public Floci port (4566)+ // and does protocol detection to route HTTP and HTTPS to the correct backend.+ properties.put("quarkus.http.insecure-requests", "enabled");+ properties.put("quarkus.http.host", "127.0.0.1");+ properties.put("quarkus.http.port", "4510");+ properties.put("quarkus.http.ssl-port", "4511");++ LOG.infov("TLS: HTTPS enabled — proxy will listen on port {0} (HTTP+HTTPS), cert={1}",+ resolveProperty("floci.port", "4566"), certPath);+ }++ @Override+ public int getOrdinal() {+ // Higher than application.yml (250) so TLS properties take precedence+ return 300;+ }++ @Override+ public Set<String> getPropertyNames() {+ return properties.keySet();+ }++ @Override+ public String getValue(String propertyName) {+ return properties.get(propertyName);+ }++ @Override+ public String getName() {+ return "FlociTlsConfigSource";+ }++ /**+ * Resolves a property from system properties or environment variables.+ * Environment variable names follow the MicroProfile convention:+ * {@code floci.tls.enabled} → {@code FLOCI_TLS_ENABLED}.+ */+ private static String resolveProperty(String key, String defaultValue) {+ // 1. System property (highest priority)+ String value = System.getProperty(key);+ if (value != null && !value.isBlank())+ return value;++ // 2. Environment variable (underscore + uppercase)+ String envKey = key.replace('.', '_').replace('-', '_').toUpperCase();+ value = System.getenv(envKey);+ if (value != null && !value.isBlank())+ return value;++ return defaultValue;+ }++ private void generateSelfSignedCert(Path tlsDir, Path certFile, Path keyFile) {+ try {+ Files.createDirectories(tlsDir);++ // BouncyCastle may not be registered yet — ConfigSource runs before CDI+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }++ // Extract custom hostnames and combine with defaults+ List<String> customHostnames = extractCustomHostnames();+ List<String> allSans = new ArrayList<>();+ allSans.addAll(List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io"));+ allSans.addAll(customHostnames);++ CertificateGenerator gen = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(+ "localhost",+ allSans,+ KeyAlgorithm.RSA_2048);++ Files.writeString(certFile, generated.certificatePem());+ Files.writeString(keyFile, generated.privateKeyPem());++ LOG.infov("TLS: generated self-signed certificate: {0}", certFile);++ // Persist metadata for change detection on restart+ persistMetadata(tlsDir, allSans);+ } catch (IOException e) {+ throw new IllegalStateException("Failed to write self-signed TLS certificate", e);+ }+ }++ private static void validateFileExists(String path, String description) {+ if (!Files.isReadable(Path.of(path))) {+ throw new IllegalStateException(+ description + " file not found or not readable: " + path);+ }+ }++ /**+ * Extracts custom hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL configuration.+ * Filters out default values like "localhost" and "127.0.0.1".+ * Returns a deduplicated list of custom hostnames.+ *+ * @return List of custom hostnames (may be empty if no custom hostnames configured)+ */+ private List<String> extractCustomHostnames() {+ Set<String> hostnames = new LinkedHashSet<>();++ // Extract from FLOCI_HOSTNAME+ String hostname = resolveProperty("floci.hostname", "");+ if (!hostname.isBlank() && !isDefaultHostname(hostname)) {+ hostnames.add(hostname);+ LOG.debugv("TLS: extracted hostname from floci.hostname: {0}", hostname);+ }++ // Extract from FLOCI_BASE_URL+ String baseUrl = resolveProperty("floci.base-url", "http://localhost:4566");+ try {+ URI uri = new URI(baseUrl);+ String host = uri.getHost();+ if (host != null && !isDefaultHostname(host)) {+ hostnames.add(host);+ LOG.debugv("TLS: extracted hostname from floci.base-url: {0}", host);+ }+ } catch (URISyntaxException e) {+ LOG.warnv("TLS: failed to parse base URL for hostname extraction: {0}", baseUrl);+ }++ List<String> result = new ArrayList<>(hostnames);+ if (!result.isEmpty()) {+ LOG.infov("TLS: detected custom hostnames: {0}", result);+ }+ return result;+ }++ /**+ * Checks if a hostname is a default value that should be filtered out.+ *+ * @param hostname The hostname to check+ * @return true if the hostname is a default value (localhost, 127.0.0.1, 0.0.0.0)+ */+ private boolean isDefaultHostname(String hostname) {+ return hostname.equals("localhost")+ || hostname.equals("127.0.0.1")+ || hostname.equals("0.0.0.0");+ }++ /**+ * Persists certificate metadata to enable change detection on restart.+ * Writes metadata to {tls-dir}/floci-selfsigned.metadata.json.+ *+ * @param tlsDir The TLS directory where metadata should be written+ * @param hostnames List of hostnames included in the certificate SANs+ */+ private void persistMetadata(Path tlsDir, List<String> hostnames) {+ Path metadataFile = tlsDir.resolve(SELF_SIGNED_METADATA_NAME);+ try {+ String version = resolveFlociVersion();+ CertificateMetadata metadata = CertificateMetadata.create(hostnames, version);++ String json = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);++ Files.writeString(metadataFile, json);+ LOG.debugv("TLS: persisted certificate metadata: {0}", metadataFile);+ } catch (IOException e) {+ // Log warning but don't fail startup - metadata is for optimization, not critical+ LOG.warnv("TLS: failed to write certificate metadata (will regenerate on next restart): {0}", e.getMessage());+ }+ }++ /**+ * Resolves the Floci version from environment variable or defaults to "dev".+ *+ * @return Floci version string+ */+ private static String resolveFlociVersion() {+ String env = System.getenv("FLOCI_VERSION");+ if (env != null && !env.isBlank()) {+ return env;+ }+ return "dev";+ }++ /**+ * Checks if the hostname configuration has changed since the last certificate generation.+ * Loads the metadata file and compares the hostnames with the current configuration.+ *+ * @param tlsDir The TLS directory where metadata file is stored+ * @param currentHostnames List of hostnames from current configuration+ * @return true if configuration changed or metadata missing, false if same+ */+ private boolean hostnameConfigChanged(Path tlsDir, List<String> currentHostnames) {+ Path metadataFile = tlsDir.resolve(SELF_SIGNED_METADATA_NAME);++ // If metadata doesn't exist, trigger regeneration+ if (!Files.exists(metadataFile)) {+ LOG.infov("TLS: metadata file missing, regenerating certificate to ensure correctness");+ return true;+ }++ try {+ // Load and parse metadata file+ String json = Files.readString(metadataFile);+ CertificateMetadata metadata = OBJECT_MAPPER.readValue(json, CertificateMetadata.class);++ List<String> previousHostnames = metadata.getHostnames();+ if (previousHostnames == null) {+ LOG.warnv("TLS: metadata file has no hostnames field, regenerating certificate");+ return true;+ }++ // Compare hostnames (order-independent)+ Set<String> previousSet = new LinkedHashSet<>(previousHostnames);+ Set<String> currentSet = new LinkedHashSet<>(currentHostnames);++ if (!previousSet.equals(currentSet)) {+ LOG.infov("TLS: hostname configuration changed, regenerating certificate");+ LOG.debugv("TLS: previous hostnames: {0}", previousHostnames);+ LOG.debugv("TLS: current hostnames: {0}", currentHostnames);+ return true;+ }++ // Configuration unchanged+ LOG.debugv("TLS: hostname configuration unchanged, reusing certificate");+ return false;++ } catch (IOException e) {+ // Handle read/parse failures gracefully - trigger regeneration+ LOG.warnv("TLS: failed to read metadata file (will regenerate certificate): {0}", e.getMessage());+ return true;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java b/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.javanew file mode 100644index 0000000000..0513de71a2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java@@ -0,0 +1,134 @@+package io.github.hectorvent.floci.config;++import io.quarkus.runtime.Startup;+import io.vertx.core.Vertx;+import io.vertx.core.net.NetClient;+import io.vertx.core.net.NetServer;+import io.vertx.core.net.NetServerOptions;+import io.vertx.core.net.NetSocket;+import jakarta.annotation.PreDestroy;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++/**+ * A TCP proxy server that enables HTTP and HTTPS on the same port (LocalStack parity).+ *+ * <p>When TLS is enabled, Quarkus serves HTTP on an internal port (4510) and HTTPS on+ * another internal port (4511). This proxy listens on the public Floci port (4566) and+ * inspects the first byte of each incoming connection:+ * <ul>+ * <li>{@code 0x16} (TLS ClientHello) → proxy to HTTPS backend (port 4511)</li>+ * <li>Anything else → proxy to HTTP backend (port 4510)</li>+ * </ul>+ *+ * <p>This achieves true dual-protocol support on a single port, matching LocalStack's+ * behavior where both {@code http://localhost:4566} and {@code https://localhost:4566}+ * work simultaneously.+ *+ * <p>This bean is only active when {@code floci.tls.enabled=true}. When TLS is disabled,+ * Quarkus serves HTTP directly on port 4566 and this proxy is not started.+ */+@ApplicationScoped+@Startup+public class TlsProxyServer {++ private static final Logger LOG = Logger.getLogger(TlsProxyServer.class);++ /** TLS record content type for Handshake (ClientHello). */+ private static final byte TLS_HANDSHAKE = 0x16;++ private static final int HTTP_BACKEND_PORT = 4510;+ private static final int HTTPS_BACKEND_PORT = 4511;++ private final Vertx vertx;+ private final EmulatorConfig config;+ private NetServer proxyServer;+ private NetClient client;++ @Inject+ public TlsProxyServer(Vertx vertx, EmulatorConfig config) {+ this.vertx = vertx;+ this.config = config;+ startIfTlsEnabled();+ }++ private void startIfTlsEnabled() {+ if (!config.tls().enabled()) {+ return;+ }++ int publicPort = config.port();+ NetServerOptions options = new NetServerOptions()+ .setHost("0.0.0.0")+ .setPort(publicPort);++ proxyServer = vertx.createNetServer(options);+ client = vertx.createNetClient();++ proxyServer.connectHandler(frontSocket -> {+ // Pause incoming data until we've peeked at the first byte+ frontSocket.pause();++ frontSocket.handler(buffer -> {+ // Remove handler and keep socket paused to prevent data loss+ // while we establish the backend connection.+ frontSocket.handler(null);+ frontSocket.pause();++ // Inspect first byte to determine protocol+ int backendPort;+ if (buffer.length() > 0 && buffer.getByte(0) == TLS_HANDSHAKE) {+ backendPort = HTTPS_BACKEND_PORT;+ } else {+ backendPort = HTTP_BACKEND_PORT;+ }++ // Connect to the appropriate backend+ client.connect(backendPort, "127.0.0.1").onComplete(ar -> {+ if (ar.succeeded()) {+ NetSocket backSocket = ar.result();++ // Send the initial buffer that we already read+ backSocket.write(buffer);++ // Bi-directional pipe — pipeTo handles end-of-stream+ // propagation and will resume the paused frontSocket.+ frontSocket.pipeTo(backSocket).onFailure(err ->+ LOG.debugv("TLS proxy: pipe front→back failed: {0}", err.getMessage()));+ backSocket.pipeTo(frontSocket).onFailure(err ->+ LOG.debugv("TLS proxy: pipe back→front failed: {0}", err.getMessage()));+ } else {+ LOG.warnv("TLS proxy: failed to connect to backend port {0}: {1}",+ backendPort, ar.cause().getMessage());+ frontSocket.close();+ }+ });+ });++ // Resume to receive the first buffer+ frontSocket.resume();+ });++ proxyServer.listen().onComplete(ar -> {+ if (ar.succeeded()) {+ LOG.infov("TLS proxy: listening on port {0} (HTTP→{1}, HTTPS→{2})",+ publicPort, HTTP_BACKEND_PORT, HTTPS_BACKEND_PORT);+ } else {+ LOG.errorv("TLS proxy: failed to start on port {0}: {1}",+ publicPort, ar.cause().getMessage());+ }+ });+ }++ @PreDestroy+ void stop() {+ if (proxyServer != null) {+ proxyServer.close();+ }+ if (client != null) {+ client.close();+ }+ LOG.info("TLS proxy: stopped");+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.javaindex 04b775a241..224e71aec7 100644--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java@@ -82,6 +82,7 @@ public class EmulatorLifecycle {LOG.info("=== AWS Local Emulator Starting ===");LOG.infov("Storage mode: {0}", config.storage().mode());LOG.infov("Persistent path: {0}", config.storage().persistentPath());+ LOG.infov("TLS: {0}", config.tls().enabled() ? "enabled (HTTPS + HTTP dual mode)" : "disabled (HTTP only)");// BOOT hooks run before service initialization — scripts cannot use AWS APIs yet.try {diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.javaindex 6c5b000f67..0d031b94e3 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java@@ -30,6 +30,7 @@ import org.jboss.logging.Logger;import java.io.StringReader;import java.io.StringWriter;import java.math.BigInteger;+import java.net.InetAddress;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;@@ -43,6 +44,7 @@ import java.time.temporal.ChronoUnit;import java.util.ArrayList;import java.util.Date;import java.util.List;+import java.util.regex.Pattern;@ApplicationScopedpublic class CertificateGenerator {@@ -51,6 +53,14 @@ public class CertificateGenerator {private static final String ISSUER_DN = "CN=Amazon,OU=Server CA 1B,O=Amazon,C=US";private static final SecureRandom SECURE_RANDOM = new SecureRandom();+ /**+ * Pattern matching IPv4 addresses (e.g. 192.168.1.100) and IPv6 addresses+ * (bracketed like [::1] or raw like ::1, fe80::1).+ */+ private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile(+ "^\\[?([0-9a-fA-F:]+)]?$|^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$"+ );+public record GeneratedCertificate(String certificatePem,String privateKeyPem,@@ -98,11 +108,11 @@ public class CertificateGenerator {// Add Subject Alternative NamesList<GeneralName> sanList = new ArrayList<>();- sanList.add(new GeneralName(GeneralName.dNSName, domainName));+ sanList.add(toGeneralName(domainName));if (sans != null) {for (String san : sans) {if (!san.equals(domainName)) {- sanList.add(new GeneralName(GeneralName.dNSName, san));+ sanList.add(toGeneralName(san));}}}@@ -166,6 +176,41 @@ public class CertificateGenerator {return keyGen.generateKeyPair();}+ /**+ * Creates the appropriate {@link GeneralName} for a SAN entry.+ * IP addresses (IPv4 and IPv6) use {@code GeneralName.iPAddress},+ * all other values use {@code GeneralName.dNSName}.+ */+ private static GeneralName toGeneralName(String san) {+ if (isIpAddress(san)) {+ try {+ // Strip brackets from IPv6 if present (e.g. [::1] → ::1)+ String raw = san.startsWith("[") && san.endsWith("]")+ ? san.substring(1, san.length() - 1)+ : san;+ byte[] addr = InetAddress.getByName(raw).getAddress();+ return new GeneralName(GeneralName.iPAddress,+ new org.bouncycastle.asn1.DEROctetString(addr));+ } catch (Exception e) {+ // Fallback to DNS name if IP parsing fails+ LOG.debugv("Could not parse '{0}' as IP address, treating as DNS name", san);+ return new GeneralName(GeneralName.dNSName, san);+ }+ }+ return new GeneralName(GeneralName.dNSName, san);+ }++ /**+ * Checks whether a SAN value looks like an IP address (IPv4 or IPv6).+ * Wildcard entries (e.g. *.localhost) are never IP addresses.+ */+ static boolean isIpAddress(String value) {+ if (value == null || value.isBlank() || value.startsWith("*")) {+ return false;+ }+ return IP_ADDRESS_PATTERN.matcher(value).matches();+ }+private String toPem(Object obj) throws Exception {StringWriter sw = new StringWriter();try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {diff --git a/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource b/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourcenew file mode 100644index 0000000000..4045912cfa--- /dev/null+++ b/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource@@ -0,0 +1 @@+io.github.hectorvent.floci.config.TlsConfigSourcediff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 11c689fd8e..2e3275f85a 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -34,6 +34,7 @@ quarkus:- --initialize-at-run-time=io.github.hectorvent.floci.core.common.BouncyCastleInitializer- --initialize-at-run-time=io.github.hectorvent.floci.services.acm.AcmService- --initialize-at-run-time=io.github.hectorvent.floci.services.acm.CertificateGenerator+ - --initialize-at-run-time=io.github.hectorvent.floci.config.TlsConfigSource- --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoSrpHelper- --initialize-at-run-time=io.github.hectorvent.floci.services.ses.SesService- --initialize-at-run-time=io.github.hectorvent.floci.services.route53.Route53Service@@ -90,6 +91,12 @@ floci:validate-signatures: falsepresign-secret: local-emulator-secret+ tls:+ enabled: false # FLOCI_TLS_ENABLED (default: false)+ # cert-path: "" # FLOCI_TLS_CERT_PATH (PEM certificate file)+ # key-path: "" # FLOCI_TLS_KEY_PATH (PEM private key file)+ self-signed: true # FLOCI_TLS_SELF_SIGNED — auto-generate a self-signed cert if no cert-path provided+docker:log-max-size: "10m"log-max-file: "3"diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.javanew file mode 100644index 0000000000..3c348e266c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java@@ -0,0 +1,386 @@+package io.github.hectorvent.floci.config;++import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import org.bouncycastle.asn1.x509.GeneralName;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.MethodSource;++import java.nio.file.Files;+import java.nio.file.Path;+import java.security.Security;+import java.security.cert.X509Certificate;+import java.util.*;+import java.util.stream.Stream;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for TLS certificate hostname functionality.+ *+ * Tests that the TLS certificate generation correctly:+ * - Includes custom hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL in certificate SANs+ * - Regenerates certificates when hostname configuration changes+ * - Preserves default behavior for standard configurations+ * - Handles user-provided certificates correctly+ * - Manages certificate reuse and regeneration appropriately+ */+class TlsCertificateHostnameTest {++ @TempDir+ Path tempDir;++ @BeforeAll+ static void setupBouncyCastle() {+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ }++ @AfterEach+ void cleanupSystemProperties() {+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.base-url");+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.tls.cert-path");+ System.clearProperty("floci.tls.key-path");+ System.clearProperty("floci.storage.persistent-path");+ }++ // ==================== Custom Hostname Tests ====================++ @Test+ void testFlociHostnameIncludedInCertificateSans() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "floci");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);++ assertTrue(sans.contains("floci"),+ "Certificate SANs should contain 'floci' from FLOCI_HOSTNAME. Found: " + sans);+ assertTrue(sans.contains("localhost"),+ "Certificate SANs should include default 'localhost'");+ }++ @Test+ void testBaseUrlHostnameIncludedInCertificateSans() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "https://myhost:4566");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);++ assertTrue(sans.contains("myhost"),+ "Certificate SANs should contain 'myhost' from FLOCI_BASE_URL. Found: " + sans);+ }++ @Test+ void testBaseUrlIpAddressIncludedInCertificateSans() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "https://192.168.1.100:4566");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);++ assertTrue(sans.contains("192.168.1.100"),+ "Certificate SANs should contain IP address from FLOCI_BASE_URL. Found: " + sans);+ }++ @Test+ void testBothHostnamesIncludedInCertificateSans() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "newhost");+ System.setProperty("floci.base-url", "http://oldhost:4566");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);++ assertTrue(sans.contains("newhost"),+ "Certificate SANs should contain 'newhost' from FLOCI_HOSTNAME. Found: " + sans);+ assertTrue(sans.contains("oldhost"),+ "Certificate SANs should contain 'oldhost' from FLOCI_BASE_URL. Found: " + sans);+ }++ // ==================== Certificate Regeneration Tests ====================++ @Test+ void testConfigurationChangeTriggersRegeneration() throws Exception {+ // Arrange: Generate initial certificate+ System.setProperty("floci.hostname", "host1");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ new TlsConfigSource();++ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ X509Certificate initialCert = parseCertificate(certFile);+ List<String> initialSans = extractSansFromCertificate(initialCert);+ assertTrue(initialSans.contains("host1"), "Initial certificate should contain 'host1'");++ // Act: Change hostname and restart+ System.setProperty("floci.hostname", "host2");+ new TlsConfigSource();++ // Assert: Certificate regenerated with new hostname+ X509Certificate regeneratedCert = parseCertificate(certFile);+ List<String> regeneratedSans = extractSansFromCertificate(regeneratedCert);++ assertTrue(regeneratedSans.contains("host2"),+ "Certificate should contain 'host2' after configuration change. Found: " + regeneratedSans);+ assertFalse(regeneratedSans.contains("host1"),+ "Certificate should not contain old hostname 'host1'");+ }++ @Test+ void testMissingMetadataTriggersRegeneration() throws Exception {+ // Arrange: Create certificate without metadata (simulating old version)+ System.setProperty("floci.hostname", "floci");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);+ Path certFile = tlsDir.resolve("floci-selfsigned.crt");+ Path keyFile = tlsDir.resolve("floci-selfsigned.key");+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");++ // Generate certificate without metadata+ CertificateGenerator gen = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(+ "localhost",+ List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "localhost.floci.io", "*.localhost.floci.io"),+ KeyAlgorithm.RSA_2048);+ Files.writeString(certFile, generated.certificatePem());+ Files.writeString(keyFile, generated.privateKeyPem());++ assertFalse(Files.exists(metadataFile), "Metadata should not exist initially");++ // Act: Trigger TlsConfigSource+ new TlsConfigSource();++ // Assert: Metadata created and certificate regenerated with custom hostname+ assertTrue(Files.exists(metadataFile),+ "Metadata file should exist after regeneration");++ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);+ assertTrue(sans.contains("floci"),+ "Regenerated certificate should contain 'floci'. Found: " + sans);+ }++ // ==================== Default Configuration Tests ====================++ @Test+ void testDefaultConfigurationGeneratesDefaultSans() throws Exception {+ // Arrange: Default configuration (no custom hostnames)+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);++ Set<String> expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io");+ Set<String> actualSans = new HashSet<>(sans);++ assertEquals(expectedSans, actualSans,+ "Default configuration should generate certificate with default SANs only");+ }++ @ParameterizedTest+ @MethodSource("defaultConfigurations")+ void testDefaultConfigurationsProduceDefaultSans(Map<String, String> config) throws Exception {+ // Arrange+ config.forEach(System::setProperty);+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ X509Certificate cert = parseCertificate(certFile);+ List<String> sans = extractSansFromCertificate(cert);++ Set<String> expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io");+ Set<String> actualSans = new HashSet<>(sans);++ assertEquals(expectedSans, actualSans,+ "Default configuration should produce default SANs. Config: " + config);++ // Cleanup+ config.keySet().forEach(System::clearProperty);+ }++ // ==================== User-Provided Certificate Tests ====================++ @Test+ void testUserProvidedCertificatesUsedWithoutModification() throws Exception {+ // Arrange: Create user-provided certificate+ Path userCertFile = tempDir.resolve("user-cert.crt");+ Path userKeyFile = tempDir.resolve("user-key.key");++ CertificateGenerator gen = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate userCert = gen.generateCertificate(+ "user-domain.com",+ List.of("user-domain.com", "*.user-domain.com"),+ KeyAlgorithm.RSA_2048);+ Files.writeString(userCertFile, userCert.certificatePem());+ Files.writeString(userKeyFile, userCert.privateKeyPem());++ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.cert-path", userCertFile.toString());+ System.setProperty("floci.tls.key-path", userKeyFile.toString());+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert: No self-signed certificate generated+ Path selfSignedCert = tempDir.resolve("tls/floci-selfsigned.crt");+ assertFalse(Files.exists(selfSignedCert),+ "Self-signed certificate should not be generated when user provides certificates");+ }++ // ==================== TLS Disabled Tests ====================++ @Test+ void testTlsDisabledSkipsCertificateGeneration() throws Exception {+ // Arrange+ System.setProperty("floci.tls.enabled", "false");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act+ new TlsConfigSource();++ // Assert+ Path tlsDir = tempDir.resolve("tls");+ if (Files.exists(tlsDir)) {+ assertFalse(Files.exists(tlsDir.resolve("floci-selfsigned.crt")),+ "No certificate should be created when TLS is disabled");+ }+ }++ // ==================== Certificate Reuse Tests ====================++ @Test+ void testUnchangedConfigurationReusesCertificate() throws Exception {+ // Arrange: Generate initial certificate+ System.setProperty("floci.hostname", "floci");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ new TlsConfigSource();++ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();+ String initialMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));++ Thread.sleep(100);++ // Act: Restart with same configuration+ new TlsConfigSource();++ // Assert: Certificate reused (not regenerated)+ long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();+ String newMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));++ assertEquals(initialModifiedTime, newModifiedTime,+ "Certificate should be reused when configuration unchanged");+ assertEquals(initialMetadata, newMetadata,+ "Metadata should be unchanged");+ }++ // ==================== Helper Methods ====================++ private X509Certificate parseCertificate(Path certFile) throws Exception {+ String certPem = Files.readString(certFile);+ CertificateGenerator gen = new CertificateGenerator();+ return gen.parseCertificate(certPem);+ }++ private List<String> extractSansFromCertificate(X509Certificate cert) throws Exception {+ List<String> sans = new ArrayList<>();++ Collection<List<?>> subjectAltNames = cert.getSubjectAlternativeNames();+ if (subjectAltNames != null) {+ for (List<?> san : subjectAltNames) {+ Integer type = (Integer) san.get(0);+ String value = (String) san.get(1);++ if (type == GeneralName.dNSName || type == GeneralName.iPAddress) {+ sans.add(value);+ }+ }+ }++ return sans;+ }++ static Stream<Map<String, String>> defaultConfigurations() {+ return Stream.of(+ Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true"),+ Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",+ "floci.base-url", "http://localhost:4566"),+ Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",+ "floci.base-url", "http://127.0.0.1:4566"),+ Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",+ "floci.hostname", "localhost"),+ Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",+ "floci.base-url", "https://localhost:4566"),+ Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",+ "floci.base-url", "http://0.0.0.0:4566")+ );+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.javanew file mode 100644index 0000000000..1c18e5228e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java@@ -0,0 +1,241 @@+package io.github.hectorvent.floci.config;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.io.ByteArrayInputStream;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;+import java.util.Collection;+import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for TLS certificate generation with custom hostnames.+ *+ * Tests Task 3.5: Update certificate generation to include custom hostnames+ * - Verifies that extractCustomHostnames() is called+ * - Verifies that custom hostnames are combined with default SANs+ * - Verifies that the combined list is deduplicated+ * - Verifies that the combined SANs are passed to CertificateGenerator+ * - Verifies that logging shows custom hostnames when present+ */+class TlsConfigSourceCertificateGenerationTest {++ @TempDir+ Path tempDir;++ @BeforeEach+ void setup() {+ // Enable TLS and self-signed mode+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ }++ @AfterEach+ void cleanup() {+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.base-url");+ }++ /**+ * Test that certificate includes custom hostname from FLOCI_HOSTNAME+ */+ @Test+ void testCertificateIncludesFlociHostname() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "floci");++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ List<String> sans = extractSansFromCertificate(certFile);+ assertTrue(sans.contains("floci"),+ "Certificate SANs should include 'floci' from FLOCI_HOSTNAME");+ assertTrue(sans.contains("localhost"),+ "Certificate SANs should include default 'localhost'");+ }++ /**+ * Test that certificate includes custom hostname from FLOCI_BASE_URL+ */+ @Test+ void testCertificateIncludesBaseUrlHostname() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "https://myhost:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ List<String> sans = extractSansFromCertificate(certFile);+ assertTrue(sans.contains("myhost"),+ "Certificate SANs should include 'myhost' from FLOCI_BASE_URL");+ assertTrue(sans.contains("localhost"),+ "Certificate SANs should include default 'localhost'");+ }++ /**+ * Test that certificate includes IP address from FLOCI_BASE_URL+ */+ @Test+ void testCertificateIncludesIpAddress() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "https://192.168.1.100:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ List<String> sans = extractSansFromCertificate(certFile);+ assertTrue(sans.contains("192.168.1.100"),+ "Certificate SANs should include '192.168.1.100' from FLOCI_BASE_URL");+ }++ /**+ * Test that certificate includes both FLOCI_HOSTNAME and FLOCI_BASE_URL hostnames+ */+ @Test+ void testCertificateIncludesBothHostnames() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "newhost");+ System.setProperty("floci.base-url", "http://oldhost:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ List<String> sans = extractSansFromCertificate(certFile);+ assertTrue(sans.contains("newhost"),+ "Certificate SANs should include 'newhost' from FLOCI_HOSTNAME");+ assertTrue(sans.contains("oldhost"),+ "Certificate SANs should include 'oldhost' from FLOCI_BASE_URL");+ assertTrue(sans.contains("localhost"),+ "Certificate SANs should include default 'localhost'");+ }++ /**+ * Test that certificate with default configuration includes only default SANs+ */+ @Test+ void testCertificateWithDefaultConfiguration() throws Exception {+ // Arrange - no custom hostnames++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ List<String> sans = extractSansFromCertificate(certFile);+ assertTrue(sans.contains("localhost"),+ "Certificate SANs should include default 'localhost'");+ assertTrue(sans.contains("127.0.0.1"),+ "Certificate SANs should include default '127.0.0.1'");+ assertTrue(sans.contains("0.0.0.0"),+ "Certificate SANs should include default '0.0.0.0'");++ // Should not contain any custom hostnames+ assertEquals(6, sans.size(),+ "Certificate SANs should contain exactly 6 default entries (localhost, 127.0.0.1, 0.0.0.0, *.localhost, localhost.floci.io, *.localhost.floci.io)");+ }++ /**+ * Test that duplicate hostnames are deduplicated+ */+ @Test+ void testDeduplicationInCertificate() throws Exception {+ // Arrange - same hostname in both sources+ System.setProperty("floci.hostname", "myhost");+ System.setProperty("floci.base-url", "http://myhost:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ assertTrue(Files.exists(certFile), "Certificate file should exist");++ List<String> sans = extractSansFromCertificate(certFile);+ long myhostCount = sans.stream().filter(s -> s.equals("myhost")).count();+ assertEquals(1, myhostCount,+ "Certificate SANs should contain 'myhost' exactly once (deduplicated)");+ }++ /**+ * Test that metadata file is created with correct hostnames+ */+ @Test+ void testMetadataIncludesCustomHostnames() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "floci");+ System.setProperty("floci.base-url", "https://myhost:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ assertTrue(Files.exists(metadataFile), "Metadata file should exist");++ String json = Files.readString(metadataFile);+ assertTrue(json.contains("floci"),+ "Metadata should include 'floci' hostname");+ assertTrue(json.contains("myhost"),+ "Metadata should include 'myhost' hostname");+ assertTrue(json.contains("localhost"),+ "Metadata should include default 'localhost' hostname");+ }++ // ==================== Helper Methods ====================++ /**+ * Extracts Subject Alternative Names (SANs) from a certificate file.+ *+ * @param certFile Path to the certificate file+ * @return List of SANs (DNS names and IP addresses)+ */+ private List<String> extractSansFromCertificate(Path certFile) throws Exception {+ String certPem = Files.readString(certFile);++ // Parse certificate+ CertificateFactory cf = CertificateFactory.getInstance("X.509");+ X509Certificate cert = (X509Certificate) cf.generateCertificate(+ new ByteArrayInputStream(certPem.getBytes())+ );++ // Extract SANs+ Collection<List<?>> sans = cert.getSubjectAlternativeNames();+ if (sans == null) {+ return List.of();+ }++ return sans.stream()+ .filter(san -> san.size() >= 2)+ .map(san -> san.get(1).toString())+ .toList();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.javanew file mode 100644index 0000000000..6bd2ed05e6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.java@@ -0,0 +1,230 @@+package io.github.hectorvent.floci.config;++import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Files;+import java.nio.file.Path;+import java.security.Security;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration test for Task 3.6: Certificate reuse logic with metadata checking+ *+ * This test verifies that TlsConfigSource correctly:+ * 1. Checks metadata before reusing existing certificates+ * 2. Regenerates certificates when configuration changes+ * 3. Regenerates certificates when metadata is missing+ * 4. Reuses certificates when configuration is unchanged+ */+class TlsConfigSourceCertificateReuseTest {++ @TempDir+ Path tempDir;++ @BeforeAll+ static void setupBouncyCastle() {+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ }++ @AfterEach+ void cleanupSystemProperties() {+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.base-url");+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ }++ /**+ * Test that certificate is regenerated when hostname configuration changes+ */+ @Test+ void testCertificateRegeneratedWhenHostnameChanges() throws Exception {+ // Arrange: Generate initial certificate with FLOCI_HOSTNAME=host1+ System.setProperty("floci.hostname", "host1");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act: Create TlsConfigSource - this generates the initial certificate+ new TlsConfigSource();++ Path tlsDir = tempDir.resolve("tls");+ Path certFile = tlsDir.resolve("floci-selfsigned.crt");+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");++ // Verify initial certificate and metadata exist+ assertTrue(Files.exists(certFile), "Initial certificate should be generated");+ assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");++ // Read initial metadata+ String initialMetadata = Files.readString(metadataFile);+ long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();++ // Wait a bit to ensure timestamp difference+ Thread.sleep(100);++ // Change hostname configuration+ System.setProperty("floci.hostname", "host2");++ // Act: Create new TlsConfigSource - should regenerate certificate+ new TlsConfigSource();++ // Assert: Certificate and metadata should be regenerated+ assertTrue(Files.exists(certFile), "Certificate should still exist");+ assertTrue(Files.exists(metadataFile), "Metadata should still exist");++ String newMetadata = Files.readString(metadataFile);+ long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();++ assertNotEquals(initialMetadata, newMetadata,+ "Metadata should be updated with new hostname");+ assertTrue(newModifiedTime > initialModifiedTime,+ "Certificate should be regenerated (newer timestamp)");+ assertTrue(newMetadata.contains("host2"),+ "New metadata should contain 'host2'");+ }++ /**+ * Test that certificate is regenerated when metadata is missing+ */+ @Test+ void testCertificateRegeneratedWhenMetadataMissing() throws Exception {+ // Arrange: Generate initial certificate+ System.setProperty("floci.hostname", "floci");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act: Create TlsConfigSource - this generates the initial certificate+ new TlsConfigSource();++ Path tlsDir = tempDir.resolve("tls");+ Path certFile = tlsDir.resolve("floci-selfsigned.crt");+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");++ // Verify initial certificate and metadata exist+ assertTrue(Files.exists(certFile), "Initial certificate should be generated");+ assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");++ long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();++ // Delete metadata file to simulate old version+ Files.delete(metadataFile);+ assertFalse(Files.exists(metadataFile), "Metadata should be deleted");++ // Wait a bit to ensure timestamp difference+ Thread.sleep(100);++ // Act: Create new TlsConfigSource - should regenerate certificate+ new TlsConfigSource();++ // Assert: Certificate and metadata should be regenerated+ assertTrue(Files.exists(certFile), "Certificate should still exist");+ assertTrue(Files.exists(metadataFile), "Metadata should be regenerated");++ long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();+ assertTrue(newModifiedTime > initialModifiedTime,+ "Certificate should be regenerated when metadata is missing");+ }++ /**+ * Test that certificate is reused when configuration is unchanged+ */+ @Test+ void testCertificateReusedWhenConfigurationUnchanged() throws Exception {+ // Arrange: Generate initial certificate+ System.setProperty("floci.hostname", "floci");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act: Create TlsConfigSource - this generates the initial certificate+ new TlsConfigSource();++ Path tlsDir = tempDir.resolve("tls");+ Path certFile = tlsDir.resolve("floci-selfsigned.crt");+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");++ // Verify initial certificate and metadata exist+ assertTrue(Files.exists(certFile), "Initial certificate should be generated");+ assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");++ long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();+ String initialMetadata = Files.readString(metadataFile);++ // Wait a bit to ensure timestamp difference would be visible if regenerated+ Thread.sleep(100);++ // Act: Create new TlsConfigSource with same configuration - should reuse certificate+ new TlsConfigSource();++ // Assert: Certificate and metadata should NOT be regenerated+ assertTrue(Files.exists(certFile), "Certificate should still exist");+ assertTrue(Files.exists(metadataFile), "Metadata should still exist");++ long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();+ String newMetadata = Files.readString(metadataFile);++ assertEquals(initialModifiedTime, newModifiedTime,+ "Certificate should be reused (same timestamp)");+ assertEquals(initialMetadata, newMetadata,+ "Metadata should be unchanged");+ }++ /**+ * Test that certificate is regenerated when base URL hostname changes+ */+ @Test+ void testCertificateRegeneratedWhenBaseUrlChanges() throws Exception {+ // Arrange: Generate initial certificate with FLOCI_BASE_URL=https://host1:4566+ System.setProperty("floci.base-url", "https://host1:4566");+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ // Act: Create TlsConfigSource - this generates the initial certificate+ new TlsConfigSource();++ Path tlsDir = tempDir.resolve("tls");+ Path certFile = tlsDir.resolve("floci-selfsigned.crt");+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");++ // Verify initial certificate and metadata exist+ assertTrue(Files.exists(certFile), "Initial certificate should be generated");+ assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");++ String initialMetadata = Files.readString(metadataFile);+ long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();++ // Wait a bit to ensure timestamp difference+ Thread.sleep(100);++ // Change base URL hostname+ System.setProperty("floci.base-url", "https://host2:4566");++ // Act: Create new TlsConfigSource - should regenerate certificate+ new TlsConfigSource();++ // Assert: Certificate and metadata should be regenerated+ assertTrue(Files.exists(certFile), "Certificate should still exist");+ assertTrue(Files.exists(metadataFile), "Metadata should still exist");++ String newMetadata = Files.readString(metadataFile);+ long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();++ assertNotEquals(initialMetadata, newMetadata,+ "Metadata should be updated with new hostname");+ assertTrue(newModifiedTime > initialModifiedTime,+ "Certificate should be regenerated (newer timestamp)");+ assertTrue(newMetadata.contains("host2"),+ "New metadata should contain 'host2'");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceHostnameExtractionTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceHostnameExtractionTest.javanew file mode 100644index 0000000000..c769074ec4--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceHostnameExtractionTest.java@@ -0,0 +1,258 @@+package io.github.hectorvent.floci.config;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;++import java.lang.reflect.Method;+import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Unit tests for hostname extraction logic in TlsConfigSource.+ *+ * Tests the extractCustomHostnames() method to verify:+ * - Extraction from FLOCI_HOSTNAME+ * - Extraction from FLOCI_BASE_URL (DNS names and IP addresses)+ * - Filtering of default values (localhost, 127.0.0.1, 0.0.0.0)+ * - Deduplication of hostnames+ * - Edge case handling (malformed URLs, missing host, IPv6 addresses)+ */+class TlsConfigSourceHostnameExtractionTest {++ @AfterEach+ void cleanupSystemProperties() {+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.base-url");+ }++ /**+ * Test extraction from FLOCI_HOSTNAME+ */+ @Test+ void testExtractFromFlociHostname() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "floci");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.contains("floci"),+ "Should extract 'floci' from FLOCI_HOSTNAME");+ }++ /**+ * Test extraction from FLOCI_BASE_URL with DNS name+ */+ @Test+ void testExtractFromBaseUrlDnsName() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "https://myhost:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.contains("myhost"),+ "Should extract 'myhost' from FLOCI_BASE_URL");+ }++ /**+ * Test extraction from FLOCI_BASE_URL with IP address+ */+ @Test+ void testExtractFromBaseUrlIpAddress() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "https://192.168.1.100:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.contains("192.168.1.100"),+ "Should extract '192.168.1.100' from FLOCI_BASE_URL");+ }++ /**+ * Test extraction from both FLOCI_HOSTNAME and FLOCI_BASE_URL+ */+ @Test+ void testExtractFromBothSources() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "newhost");+ System.setProperty("floci.base-url", "http://oldhost:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.contains("newhost"),+ "Should extract 'newhost' from FLOCI_HOSTNAME");+ assertTrue(hostnames.contains("oldhost"),+ "Should extract 'oldhost' from FLOCI_BASE_URL");+ assertEquals(2, hostnames.size(),+ "Should contain exactly 2 hostnames");+ }++ /**+ * Test filtering of default hostname "localhost"+ */+ @Test+ void testFilterDefaultLocalhostFromHostname() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "localhost");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.isEmpty(),+ "Should filter out 'localhost' as it's a default value");+ }++ /**+ * Test filtering of default IP "127.0.0.1"+ */+ @Test+ void testFilterDefaultLoopbackIp() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "http://127.0.0.1:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.isEmpty(),+ "Should filter out '127.0.0.1' as it's a default value");+ }++ /**+ * Test filtering of default IP "0.0.0.0"+ */+ @Test+ void testFilterDefaultAllInterfacesIp() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "http://0.0.0.0:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.isEmpty(),+ "Should filter out '0.0.0.0' as it's a default value");+ }++ /**+ * Test deduplication when same hostname appears in both sources+ */+ @Test+ void testDeduplication() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", "myhost");+ System.setProperty("floci.base-url", "http://myhost:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertEquals(1, hostnames.size(),+ "Should deduplicate 'myhost' appearing in both sources");+ assertTrue(hostnames.contains("myhost"),+ "Should contain 'myhost'");+ }++ /**+ * Test handling of malformed URL+ */+ @Test+ void testMalformedUrl() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "not-a-valid-url");++ // Act & Assert - should not throw exception+ List<String> hostnames = invokeExtractCustomHostnames();++ // Should return empty list (malformed URL is logged but doesn't fail)+ assertTrue(hostnames.isEmpty(),+ "Should return empty list for malformed URL");+ }++ /**+ * Test handling of URL without host+ */+ @Test+ void testUrlWithoutHost() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "file:///path/to/file");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.isEmpty(),+ "Should return empty list for URL without host");+ }++ /**+ * Test empty configuration (no custom hostnames)+ */+ @Test+ void testEmptyConfiguration() throws Exception {+ // Arrange - no properties set++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.isEmpty(),+ "Should return empty list when no custom hostnames configured");+ }++ /**+ * Test blank FLOCI_HOSTNAME is ignored+ */+ @Test+ void testBlankHostname() throws Exception {+ // Arrange+ System.setProperty("floci.hostname", " ");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ assertTrue(hostnames.isEmpty(),+ "Should ignore blank FLOCI_HOSTNAME");+ }++ /**+ * Test IPv6 address extraction+ * Note: URI.getHost() returns IPv6 addresses with brackets+ */+ @Test+ void testIpv6Address() throws Exception {+ // Arrange+ System.setProperty("floci.base-url", "http://[::1]:4566");++ // Act+ List<String> hostnames = invokeExtractCustomHostnames();++ // Assert+ // IPv6 loopback should be extracted (URI.getHost() returns it with brackets)+ assertTrue(hostnames.contains("[::1]"),+ "Should extract IPv6 address '[::1]' from FLOCI_BASE_URL");+ }++ // ==================== Helper Methods ====================++ /**+ * Invokes the private extractCustomHostnames() method using reflection.+ */+ @SuppressWarnings("unchecked")+ private List<String> invokeExtractCustomHostnames() throws Exception {+ TlsConfigSource configSource = new TlsConfigSource();+ Method method = TlsConfigSource.class.getDeclaredMethod("extractCustomHostnames");+ method.setAccessible(true);+ return (List<String>) method.invoke(configSource);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.javanew file mode 100644index 0000000000..c6a3db1e70--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.java@@ -0,0 +1,260 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.io.IOException;+import java.lang.reflect.Method;+import java.nio.file.Files;+import java.nio.file.Path;+import java.time.Instant;+import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Unit tests for metadata loading and comparison in TlsConfigSource.+ *+ * Tests the hostnameConfigChanged() method to verify:+ * - Returns true when metadata file doesn't exist+ * - Returns true when hostnames have changed+ * - Returns false when hostnames are the same (order-independent)+ * - Handles read/parse failures gracefully (returns true)+ * - Proper logging for different scenarios+ */+class TlsConfigSourceMetadataComparisonTest {++ @TempDir+ Path tempDir;++ @BeforeEach+ void setUp() {+ // Set up minimal TLS configuration for testing+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ }++ @AfterEach+ void tearDown() {+ // Clean up system properties+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.base-url");+ }++ @Test+ void testMetadataFileMissing_ReturnsTrue() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);+ List<String> currentHostnames = List.of("localhost", "127.0.0.1");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertTrue(changed, "Should return true when metadata file doesn't exist");+ }++ @Test+ void testHostnamesChanged_ReturnsTrue() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with old hostnames+ List<String> oldHostnames = List.of("localhost", "127.0.0.1", "oldhost");+ createMetadataFile(tlsDir, oldHostnames);++ // Current hostnames are different+ List<String> currentHostnames = List.of("localhost", "127.0.0.1", "newhost");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertTrue(changed, "Should return true when hostnames have changed");+ }++ @Test+ void testHostnamesUnchanged_ReturnsFalse() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with hostnames+ List<String> hostnames = List.of("localhost", "127.0.0.1", "myhost");+ createMetadataFile(tlsDir, hostnames);++ // Current hostnames are the same+ List<String> currentHostnames = List.of("localhost", "127.0.0.1", "myhost");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertFalse(changed, "Should return false when hostnames are unchanged");+ }++ @Test+ void testHostnamesUnchanged_DifferentOrder_ReturnsFalse() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with hostnames in one order+ List<String> hostnames = List.of("localhost", "myhost", "127.0.0.1");+ createMetadataFile(tlsDir, hostnames);++ // Current hostnames in different order+ List<String> currentHostnames = List.of("127.0.0.1", "localhost", "myhost");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertFalse(changed, "Should return false when hostnames are the same but in different order");+ }++ @Test+ void testHostnameAdded_ReturnsTrue() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with fewer hostnames+ List<String> oldHostnames = List.of("localhost", "127.0.0.1");+ createMetadataFile(tlsDir, oldHostnames);++ // Current hostnames include an additional hostname+ List<String> currentHostnames = List.of("localhost", "127.0.0.1", "newhost");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertTrue(changed, "Should return true when a hostname is added");+ }++ @Test+ void testHostnameRemoved_ReturnsTrue() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with more hostnames+ List<String> oldHostnames = List.of("localhost", "127.0.0.1", "oldhost");+ createMetadataFile(tlsDir, oldHostnames);++ // Current hostnames have one removed+ List<String> currentHostnames = List.of("localhost", "127.0.0.1");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertTrue(changed, "Should return true when a hostname is removed");+ }++ @Test+ void testMalformedMetadataFile_ReturnsTrue() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create malformed metadata file+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Files.writeString(metadataFile, "{ invalid json }");++ List<String> currentHostnames = List.of("localhost", "127.0.0.1");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertTrue(changed, "Should return true when metadata file is malformed");+ }++ @Test+ void testMetadataWithNullHostnames_ReturnsTrue() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with null hostnames field+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ String json = "{\"generatedAt\":\"" + Instant.now().toString() + "\",\"flociVersion\":\"dev\"}";+ Files.writeString(metadataFile, json);++ List<String> currentHostnames = List.of("localhost", "127.0.0.1");++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertTrue(changed, "Should return true when metadata has no hostnames field");+ }++ @Test+ void testEmptyHostnamesList_Unchanged_ReturnsFalse() throws Exception {+ // Arrange+ Path tlsDir = tempDir.resolve("tls");+ Files.createDirectories(tlsDir);++ // Create metadata with empty hostnames list+ List<String> emptyHostnames = List.of();+ createMetadataFile(tlsDir, emptyHostnames);++ // Current hostnames are also empty+ List<String> currentHostnames = List.of();++ // Act+ boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);++ // Assert+ assertFalse(changed, "Should return false when both hostname lists are empty");+ }++ /**+ * Helper method to create a metadata file with specified hostnames.+ */+ private void createMetadataFile(Path tlsDir, List<String> hostnames) throws IOException {+ Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ CertificateMetadata metadata = CertificateMetadata.create(hostnames, "dev");++ ObjectMapper objectMapper = new ObjectMapper();+ String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);+ Files.writeString(metadataFile, json);+ }++ /**+ * Helper method to invoke the private hostnameConfigChanged() method via reflection.+ * We need to disable TLS temporarily to avoid certificate generation in the constructor.+ */+ @SuppressWarnings("unchecked")+ private boolean invokeHostnameConfigChanged(Path tlsDir, List<String> currentHostnames) throws Exception {+ // Temporarily disable TLS to avoid certificate generation in constructor+ String originalTlsEnabled = System.getProperty("floci.tls.enabled");+ System.setProperty("floci.tls.enabled", "false");++ try {+ TlsConfigSource configSource = new TlsConfigSource();+ Method method = TlsConfigSource.class.getDeclaredMethod("hostnameConfigChanged", Path.class, List.class);+ method.setAccessible(true);+ return (boolean) method.invoke(configSource, tlsDir, currentHostnames);+ } finally {+ // Restore original TLS setting+ if (originalTlsEnabled != null) {+ System.setProperty("floci.tls.enabled", originalTlsEnabled);+ } else {+ System.clearProperty("floci.tls.enabled");+ }+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.javanew file mode 100644index 0000000000..89b4eded04--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.java@@ -0,0 +1,233 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Unit tests for metadata persistence in TlsConfigSource.+ *+ * Tests that metadata is correctly persisted after certificate generation:+ * - Metadata file is created+ * - Metadata contains correct hostnames+ * - Metadata contains timestamp and version+ * - Write failures are handled gracefully+ */+class TlsConfigSourceMetadataPersistenceTest {++ @TempDir+ Path tempDir;++ @BeforeEach+ void setup() {+ // Set TLS enabled and self-signed mode+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ }++ @AfterEach+ void cleanup() {+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.base-url");+ System.clearProperty("FLOCI_VERSION");+ }++ /**+ * Test that metadata file is created after certificate generation+ */+ @Test+ void testMetadataFileCreated() {+ // Act - trigger certificate generation by creating TlsConfigSource+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ assertTrue(Files.exists(metadataFile),+ "Metadata file should be created after certificate generation");+ }++ /**+ * Test that metadata contains default hostnames when no custom hostnames configured+ */+ @Test+ void testMetadataContainsDefaultHostnames() throws IOException {+ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertNotNull(metadata.getHostnames(), "Hostnames should not be null");+ assertTrue(metadata.getHostnames().contains("localhost"),+ "Metadata should contain 'localhost'");+ assertTrue(metadata.getHostnames().contains("127.0.0.1"),+ "Metadata should contain '127.0.0.1'");+ assertTrue(metadata.getHostnames().contains("0.0.0.0"),+ "Metadata should contain '0.0.0.0'");+ assertTrue(metadata.getHostnames().contains("*.localhost"),+ "Metadata should contain '*.localhost'");+ assertTrue(metadata.getHostnames().contains("localhost.floci.io"),+ "Metadata should contain 'localhost.floci.io'");+ assertTrue(metadata.getHostnames().contains("*.localhost.floci.io"),+ "Metadata should contain '*.localhost.floci.io'");+ }++ /**+ * Test that metadata contains custom hostname from FLOCI_HOSTNAME+ */+ @Test+ void testMetadataContainsCustomHostname() throws IOException {+ // Arrange+ System.setProperty("floci.hostname", "floci");++ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertTrue(metadata.getHostnames().contains("floci"),+ "Metadata should contain custom hostname 'floci'");+ }++ /**+ * Test that metadata contains custom hostname from FLOCI_BASE_URL+ */+ @Test+ void testMetadataContainsBaseUrlHostname() throws IOException {+ // Arrange+ System.setProperty("floci.base-url", "https://myhost:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertTrue(metadata.getHostnames().contains("myhost"),+ "Metadata should contain hostname 'myhost' from base URL");+ }++ /**+ * Test that metadata contains both custom hostnames when both are configured+ */+ @Test+ void testMetadataContainsBothCustomHostnames() throws IOException {+ // Arrange+ System.setProperty("floci.hostname", "newhost");+ System.setProperty("floci.base-url", "http://oldhost:4566");++ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertTrue(metadata.getHostnames().contains("newhost"),+ "Metadata should contain 'newhost' from FLOCI_HOSTNAME");+ assertTrue(metadata.getHostnames().contains("oldhost"),+ "Metadata should contain 'oldhost' from FLOCI_BASE_URL");+ }++ /**+ * Test that metadata contains timestamp+ */+ @Test+ void testMetadataContainsTimestamp() throws IOException {+ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertNotNull(metadata.getGeneratedAt(),+ "Metadata should contain generatedAt timestamp");+ assertFalse(metadata.getGeneratedAt().isBlank(),+ "Timestamp should not be blank");+ }++ /**+ * Test that metadata contains version+ */+ @Test+ void testMetadataContainsVersion() throws IOException {+ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertNotNull(metadata.getFlociVersion(),+ "Metadata should contain flociVersion");+ assertEquals("dev", metadata.getFlociVersion(),+ "Version should default to 'dev' when FLOCI_VERSION not set");+ }++ /**+ * Test that metadata contains custom version from FLOCI_VERSION environment variable+ */+ @Test+ void testMetadataContainsCustomVersion() throws IOException {+ // Arrange+ // Note: We can't set environment variables in Java, so we'll test the default behavior+ // The actual environment variable handling is tested in integration tests++ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ CertificateMetadata metadata = readMetadata(metadataFile);++ assertNotNull(metadata.getFlociVersion(),+ "Metadata should contain flociVersion");+ }++ /**+ * Test that metadata file is valid JSON+ */+ @Test+ void testMetadataIsValidJson() throws IOException {+ // Act+ new TlsConfigSource();++ // Assert+ Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ String json = Files.readString(metadataFile);++ assertFalse(json.isBlank(), "Metadata file should not be empty");+ assertTrue(json.contains("hostnames"), "JSON should contain 'hostnames' field");+ assertTrue(json.contains("generatedAt"), "JSON should contain 'generatedAt' field");+ assertTrue(json.contains("flociVersion"), "JSON should contain 'flociVersion' field");+ }++ // ==================== Helper Methods ====================++ /**+ * Reads and parses metadata from the specified file.+ */+ private CertificateMetadata readMetadata(Path metadataFile) throws IOException {+ String json = Files.readString(metadataFile);+ ObjectMapper objectMapper = new ObjectMapper();+ return objectMapper.readValue(json, CertificateMetadata.class);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.javanew file mode 100644index 0000000000..5b0aad37b2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java@@ -0,0 +1,157 @@+package io.github.hectorvent.floci.config;++import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.restassured.RestAssured;+import io.restassured.config.RestAssuredConfig;+import io.restassured.config.SSLConfig;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.Security;+import java.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.is;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.startsWith;++/**+ * Integration test verifying TLS/HTTPS support when enabled via configuration.+ *+ * <p>Uses a {@link QuarkusTestProfile} to enable self-signed TLS so the Quarkus+ * HTTP server serves HTTPS alongside HTTP (dual-mode, LocalStack parity).+ */+@QuarkusTest+@TestProfile(TlsIntegrationTest.TlsEnabledProfile.class)+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+class TlsIntegrationTest {++ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")+ int testSslPort;++ @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")+ int testHttpPort;++ @BeforeAll+ void setupRestAssured() {+ // Trust self-signed certificates for all requests in this test class+ RestAssured.config = RestAssuredConfig.config()+ .sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation());+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ // ==================== HTTPS Connectivity ====================++ @Test+ void healthEndpointOverHttps() {+ given()+ .baseUri("https://localhost:" + testSslPort)+ .when()+ .get("/_floci/health")+ .then()+ .statusCode(200)+ .body("edition", is("community"));+ }++ @Test+ void healthEndpointStillWorksOverHttp() {+ given()+ .baseUri("http://localhost:" + testHttpPort)+ .when()+ .get("/_floci/health")+ .then()+ .statusCode(200)+ .body("edition", is("community"));+ }++ // ==================== SQS via HTTPS ====================++ @Test+ void sqsCreateQueueOverHttps() {+ given()+ .baseUri("https://localhost:" + testSslPort)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .contentType("application/x-amz-json-1.0")+ .body("{\"QueueName\": \"tls-test-queue\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("QueueUrl", startsWith("https://"));+ }++ // ==================== STS via HTTPS ====================++ @Test+ void stsGetCallerIdentityOverHttps() {+ given()+ .baseUri("https://localhost:" + testSslPort)+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetCallerIdentity")+ .formParam("Version", "2011-06-15")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("GetCallerIdentityResult"));+ }++ // ==================== Test Profile ====================++ public static final class TlsEnabledProfile implements QuarkusTestProfile {++ private static final Path CERT_DIR = Path.of("/tmp/floci-tls-integration-test");+ private static final Path CERT_FILE = CERT_DIR.resolve("test.crt");+ private static final Path KEY_FILE = CERT_DIR.resolve("test.key");++ static {+ generateCertIfNeeded();+ }++ private static void generateCertIfNeeded() {+ if (Files.exists(CERT_FILE) && Files.exists(KEY_FILE)) {+ return;+ }+ try {+ Files.createDirectories(CERT_DIR);+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ CertificateGenerator gen = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(+ "localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);+ Files.writeString(CERT_FILE, cert.certificatePem());+ Files.writeString(KEY_FILE, cert.privateKeyPem());+ } catch (IOException e) {+ throw new RuntimeException("Failed to generate test cert", e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.tls.enabled", "true",+ "floci.tls.self-signed", "false",+ "floci.tls.cert-path", CERT_FILE.toAbsolutePath().toString(),+ "floci.tls.key-path", KEY_FILE.toAbsolutePath().toString(),+ "floci.storage.persistent-path", "/tmp/floci-tls-integration-test-data",+ "quarkus.http.ssl.certificate.files", CERT_FILE.toAbsolutePath().toString(),+ "quarkus.http.ssl.certificate.key-files", KEY_FILE.toAbsolutePath().toString(),+ "quarkus.http.insecure-requests", "enabled"+ );+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.javanew file mode 100644index 0000000000..288f5826da--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java@@ -0,0 +1,117 @@+package io.github.hectorvent.floci.config;++import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.restassured.RestAssured;+import io.restassured.config.RestAssuredConfig;+import io.restassured.config.SSLConfig;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.Security;+import java.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.is;++/**+ * Integration test verifying TLS works with user-provided certificate and key files.+ *+ * <p>Generates a cert/key pair in the static initializer (before Quarkus starts),+ * then configures the profile to use those paths for both floci config and+ * Quarkus SSL properties.+ */+@QuarkusTest+@TestProfile(TlsUserCertIntegrationTest.UserCertProfile.class)+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+class TlsUserCertIntegrationTest {++ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")+ int testSslPort;++ @BeforeAll+ void setupRestAssured() {+ RestAssured.config = RestAssuredConfig.config()+ .sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation());+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void healthEndpointOverHttpsWithUserCert() {+ given()+ .baseUri("https://localhost:" + testSslPort)+ .when()+ .get("/_floci/health")+ .then()+ .statusCode(200)+ .body("edition", is("community"));+ }++ @Test+ void ssmPutParameterOverHttps() {+ given()+ .baseUri("https://localhost:" + testSslPort)+ .header("X-Amz-Target", "AmazonSSM.PutParameter")+ .contentType("application/x-amz-json-1.1")+ .body("{\"Name\": \"/tls-user-cert-test\", \"Value\": \"test-value\", \"Type\": \"String\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ public static final class UserCertProfile implements QuarkusTestProfile {++ private static final Path CERT_DIR = Path.of("/tmp/floci-tls-usercert-test");+ private static final Path CERT_FILE = CERT_DIR.resolve("user-test.crt");+ private static final Path KEY_FILE = CERT_DIR.resolve("user-test.key");++ static {+ generateCertIfNeeded();+ }++ private static void generateCertIfNeeded() {+ if (Files.exists(CERT_FILE) && Files.exists(KEY_FILE)) {+ return;+ }+ try {+ Files.createDirectories(CERT_DIR);+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ CertificateGenerator gen = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(+ "localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);+ Files.writeString(CERT_FILE, cert.certificatePem());+ Files.writeString(KEY_FILE, cert.privateKeyPem());+ } catch (IOException e) {+ throw new RuntimeException("Failed to generate test cert", e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.tls.enabled", "true",+ "floci.tls.self-signed", "false",+ "floci.tls.cert-path", CERT_FILE.toAbsolutePath().toString(),+ "floci.tls.key-path", KEY_FILE.toAbsolutePath().toString(),+ "floci.storage.persistent-path", "/tmp/floci-tls-usercert-test-data",+ "quarkus.http.ssl.certificate.files", CERT_FILE.toAbsolutePath().toString(),+ "quarkus.http.ssl.certificate.key-files", KEY_FILE.toAbsolutePath().toString(),+ "quarkus.http.insecure-requests", "enabled"+ );+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.javaindex 1bcd5a4835..6cd3cf2cfb 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java@@ -53,6 +53,7 @@ class EmulatorLifecycleTest {@Mock private PipesService pipesService;@Mock private Ec2MetadataServer ec2MetadataServer;@Mock private InitLifecycleState initLifecycleState;+ @Mock private EmulatorConfig.TlsConfig tlsConfig;private EmulatorLifecycle emulatorLifecycle;@@ -61,6 +62,8 @@ class EmulatorLifecycleTest {Mockito.lenient().when(config.services()).thenReturn(servicesConfig);Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig);Mockito.lenient().when(ec2ServiceConfig.enabled()).thenReturn(false);+ Mockito.lenient().when(config.tls()).thenReturn(tlsConfig);+ Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false);emulatorLifecycle = new EmulatorLifecycle(storageFactory, serviceRegistry, config,diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.javanew file mode 100644index 0000000000..b6702cb7a3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java@@ -0,0 +1,176 @@+package io.github.hectorvent.floci.services.acm;++import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import org.bouncycastle.asn1.x509.GeneralName;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.security.Security;+import java.security.cert.X509Certificate;+import java.util.Collection;+import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Tests that CertificateGenerator encodes SANs with the correct type:+ * - DNS names use GeneralName.dNSName (type 2)+ * - IP addresses use GeneralName.iPAddress (type 7)+ *+ * This is critical for TLS validation — clients only match IP addresses+ * against iPAddress SANs, not dNSName SANs (RFC 5280 §4.2.1.6).+ */+class CertificateGeneratorSanTypeTest {++ private static CertificateGenerator generator;++ @BeforeAll+ static void setup() {+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ generator = new CertificateGenerator();+ }++ @Test+ void ipv4AddressEncodedAsIpAddressSanType() throws Exception {+ var cert = generator.generateCertificate(+ "localhost",+ List.of("localhost", "192.168.1.100"),+ KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ // Find the 192.168.1.100 SAN and verify its type is iPAddress (7)+ boolean foundIpSan = sans.stream()+ .anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress+ && san.get(1).toString().equals("192.168.1.100"));++ assertTrue(foundIpSan,+ "192.168.1.100 should be encoded as iPAddress SAN (type 7). Found SANs: " + sans);+ }++ @Test+ void ipv6LoopbackEncodedAsIpAddressSanType() throws Exception {+ var cert = generator.generateCertificate(+ "localhost",+ List.of("localhost", "0.0.0.0", "::1"),+ KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ // 0.0.0.0 should be iPAddress type+ boolean foundZeroIp = sans.stream()+ .anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress+ && san.get(1).toString().equals("0.0.0.0"));+ assertTrue(foundZeroIp,+ "0.0.0.0 should be encoded as iPAddress SAN (type 7). Found SANs: " + sans);++ // ::1 should be iPAddress type (rendered as 0:0:0:0:0:0:0:1 by Java)+ boolean foundIpv6 = sans.stream()+ .anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress+ && san.get(1).toString().contains("0:0:0:0:0:0:0:1"));+ assertTrue(foundIpv6,+ "::1 should be encoded as iPAddress SAN (type 7). Found SANs: " + sans);+ }++ @Test+ void dnsNamesEncodedAsDnsNameSanType() throws Exception {+ var cert = generator.generateCertificate(+ "localhost",+ List.of("myhost.example.com", "floci"),+ KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ // myhost.example.com should be dNSName type+ boolean foundDns = sans.stream()+ .anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName+ && san.get(1).toString().equals("myhost.example.com"));+ assertTrue(foundDns,+ "myhost.example.com should be encoded as dNSName SAN (type 2). Found SANs: " + sans);++ // floci should be dNSName type+ boolean foundFloci = sans.stream()+ .anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName+ && san.get(1).toString().equals("floci"));+ assertTrue(foundFloci,+ "floci should be encoded as dNSName SAN (type 2). Found SANs: " + sans);+ }++ @Test+ void wildcardEncodedAsDnsNameSanType() throws Exception {+ var cert = generator.generateCertificate(+ "localhost",+ List.of("localhost", "*.localhost"),+ KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ boolean foundWildcard = sans.stream()+ .anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName+ && san.get(1).toString().equals("*.localhost"));+ assertTrue(foundWildcard,+ "*.localhost should be encoded as dNSName SAN (type 2). Found SANs: " + sans);+ }++ @Test+ void mixedIpsAndDnsNamesEncodedCorrectly() throws Exception {+ var cert = generator.generateCertificate(+ "localhost",+ List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "floci", "10.0.0.5"),+ KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ // Count DNS vs IP SANs+ long dnsCount = sans.stream()+ .filter(san -> (Integer) san.get(0) == GeneralName.dNSName)+ .count();+ long ipCount = sans.stream()+ .filter(san -> (Integer) san.get(0) == GeneralName.iPAddress)+ .count();++ // DNS: localhost, *.localhost, floci = 3+ assertEquals(3, dnsCount,+ "Should have 3 dNSName SANs (localhost, *.localhost, floci). Found SANs: " + sans);+ // IP: 127.0.0.1, 0.0.0.0, 10.0.0.5 = 3+ assertEquals(3, ipCount,+ "Should have 3 iPAddress SANs (127.0.0.1, 0.0.0.0, 10.0.0.5). Found SANs: " + sans);+ }++ // ==================== isIpAddress utility tests ====================++ @ParameterizedTest+ @ValueSource(strings = {"192.168.1.1", "10.0.0.1", "127.0.0.1", "0.0.0.0", "255.255.255.255"})+ void isIpAddress_ipv4(String value) {+ assertTrue(CertificateGenerator.isIpAddress(value), value + " should be detected as IP");+ }++ @ParameterizedTest+ @ValueSource(strings = {"::1", "fe80::1", "2001:db8::1", "[::1]", "[fe80::1]"})+ void isIpAddress_ipv6(String value) {+ assertTrue(CertificateGenerator.isIpAddress(value), value + " should be detected as IP");+ }++ @ParameterizedTest+ @ValueSource(strings = {"localhost", "floci", "myhost.example.com", "*.localhost", "a.b.c.d.e"})+ void isIpAddress_dnsNames(String value) {+ assertFalse(CertificateGenerator.isIpAddress(value), value + " should NOT be detected as IP");+ }++ @Test+ void isIpAddress_nullAndBlank() {+ assertFalse(CertificateGenerator.isIpAddress(null));+ assertFalse(CertificateGenerator.isIpAddress(""));+ assertFalse(CertificateGenerator.isIpAddress(" "));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.javaindex 871835aae9..9eed399d46 100644--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java@@ -308,6 +308,15 @@ class EventBridgeSchedulerIntegrationTest {public DockerConfig docker() { return null; }@Overridepublic EmulatorConfig.InitHooksConfig initHooks() { return null; }+ @Override+ public TlsConfig tls() {+ return new TlsConfig() {+ @Override public boolean enabled() { return false; }+ @Override public Optional<String> certPath() { return Optional.empty(); }+ @Override public Optional<String> keyPath() { return Optional.empty(); }+ @Override public boolean selfSigned() { return true; }+ };+ }};}}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex b5802f2bd4..2f37927c64 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -44,6 +44,10 @@ floci:timeout-seconds: 5shutdown-grace-period-seconds: 2+ tls:+ enabled: false+ self-signed: true+docker:log-max-size: "10m"log-max-file: "3"