diff --git a/.ci/pipelines/jobs/ocp-fips-helm.sh b/.ci/pipelines/jobs/ocp-fips-helm.sh index 7fbd0cee6c..c2e976e6f0 100644 --- a/.ci/pipelines/jobs/ocp-fips-helm.sh +++ b/.ci/pipelines/jobs/ocp-fips-helm.sh @@ -36,12 +36,23 @@ fips_deployment() { namespace::configure "${NAME_SPACE}" - deploy_redis_cache "${NAME_SPACE}" + # Reuse the CI external PostgreSQL (TLS with a CI-generated CA) + log::section "Configuring external PostgreSQL with TLS" + namespace::configure "${NAME_SPACE_POSTGRES_DB}" + configure_external_postgres_db "${NAME_SPACE}" || return 1 + + # Deploy Redis with TLS using FIPS custom CA + log::section "Configuring Redis with FIPS custom CA and TLS" + fips_deploy_redis_with_tls "${NAME_SPACE}" || return 1 cd "${DIR}" || exit local rhdh_base_url="https://${RELEASE_NAME}-developer-hub-${NAME_SPACE}.${K8S_CLUSTER_ROUTER_BASE}" apply_yaml_files "${DIR}" "${NAME_SPACE}" "${rhdh_base_url}" + # FIPS-only app-config (Redis TLS cache), loaded after app-config-rhdh via extraAppConfig + common::create_configmap_from_file "app-config-rhdh-fips" "${NAME_SPACE}" \ + "app-config-rhdh-fips.yaml" "${DIR}/resources/config_map/app-config-rhdh-fips.yaml" + # Merge base values with the FIPS environment overrides. helm::merge_values "overwrite" \ "${DIR}/value_files/${HELM_CHART_VALUE_FILE_NAME}" \ @@ -105,10 +116,12 @@ run_standard_deployment_tests() { # Setup Chromium NSS certificate database for Playwright # This function configures the Chromium certificate store used by Playwright -# to trust the custom root CA certificate. +# to trust the custom root CA certificate, and makes the Node.js process running +# Playwright trust both the root CA and the external PostgreSQL CA. # # Required environment variables: # FIPS_ROOT_CA_CERT - Base64-encoded root CA certificate (PEM format) +# NAME_SPACE - RHDH namespace (holds the PostgreSQL CA copied by configure_external_postgres_db) # # Returns: # 0 - Success @@ -151,8 +164,18 @@ fips_setup_chromium_cert_store() { return 1 fi - # Trust the custom CA in the Node.js process running Playwright TLS tests. - export NODE_EXTRA_CA_CERTS="${root_ca_file}" + # Trust the custom CA and the external PostgreSQL CA (created by + # configure_external_postgres_db) in the Node.js process running Playwright TLS tests. + local pg_ca_file="${HOME}/.pki/postgresCA.crt" + local node_ca_bundle="${HOME}/.pki/node-ca-bundle.crt" + if ! oc get secret postgress-external-db-cluster-cert -n "${NAME_SPACE}" \ + -o go-template='{{index .data "ca.crt" | base64decode}}' > "${pg_ca_file}" \ + || [[ ! -s "${pg_ca_file}" ]]; then + log::error "Failed to read the PostgreSQL CA from postgress-external-db-cluster-cert" + return 1 + fi + cat "${root_ca_file}" "${pg_ca_file}" > "${node_ca_bundle}" + export NODE_EXTRA_CA_CERTS="${node_ca_bundle}" # Add root CA certificate to NSS database (WITH sql: prefix for -A) log::info "Adding root CA certificate to NSS database..." @@ -197,8 +220,8 @@ fips_configure_custom_ca_ingress() { # Verify required environment variables if [[ -z "${FIPS_ROOT_CA_CERT:-}" ]] || [[ -z "${FIPS_ROOT_CA_KEY:-}" ]]; then - log::warning "FIPS_ROOT_CA_CERT or FIPS_ROOT_CA_KEY not set - skipping custom CA configuration" - return 0 + log::error "FIPS_ROOT_CA_CERT or FIPS_ROOT_CA_KEY not set - required for FIPS job" + return 1 fi if [[ -z "${K8S_CLUSTER_ROUTER_BASE:-}" ]]; then @@ -279,9 +302,8 @@ EOF log::success "✓ TLS secret '${secret_name}' created in namespace '${ingress_namespace}'" - # Clean up temporary files immediately - rm -rf "${tmpdir}" - unset FIPS_CERT_TMPDIR + # NOTE: tmpdir is preserved (FIPS_CERT_TMPDIR) for Redis cert generation + # It is removed by the cleanup EXIT trap (cleanup.sh) # Patch the default IngressController to use the custom certificate log::info "Patching default IngressController to use custom certificate..." @@ -310,3 +332,121 @@ EOF log::success "Custom CA ingress configuration completed successfully" return 0 } + +# Deploy Redis with TLS using FIPS custom CA-signed certificates +# This function generates Redis TLS certificate signed by the FIPS root CA, +# creates the required secrets, and deploys a TLS-enabled Redis instance. +# +# Prerequisites: +# - fips_configure_custom_ca_ingress() must be called first +# - FIPS_CERT_TMPDIR must be set with rootCA.crt and rootCA.key +# +# Required environment variables: +# REDIS_USERNAME - Redis username +# REDIS_PASSWORD - Redis password +# +# Returns: +# 0 - Success +# 1 - Failure (missing vars, cert generation failed, or deployment failed) +fips_deploy_redis_with_tls() { + local namespace=$1 + local tmpdir="${FIPS_CERT_TMPDIR}" + + log::info "Deploying Redis with FIPS custom CA-signed TLS certificates..." + + # Verify prerequisites + if [[ -z "${tmpdir}" || ! -f "${tmpdir}/rootCA.crt" || ! -f "${tmpdir}/rootCA.key" ]]; then + log::error "FIPS CA not available - run fips_configure_custom_ca_ingress first" + return 1 + fi + + if [[ -z "${namespace}" ]]; then + log::error "Redis namespace not provided" + return 1 + fi + + if [[ -z "${REDIS_USERNAME}" || -z "${REDIS_PASSWORD}" ]]; then + log::error "REDIS_USERNAME or REDIS_PASSWORD not set" + return 1 + fi + + # Generate Redis server certificate + log::info "Generating Redis TLS certificate..." + + openssl ecparam -name prime256v1 -genkey -noout -out "${tmpdir}/redis.key" + + openssl req -new -key "${tmpdir}/redis.key" \ + -out "${tmpdir}/redis.csr" \ + -subj "/O=CI-FIPS-Testing/CN=redis.${namespace}.svc.cluster.local" + + # Create extensions file for Redis certificate + cat > "${tmpdir}/redis_ext.cnf" << EOF +[ v3_req ] +basicConstraints = CA:FALSE +keyUsage = critical, digitalSignature, keyEncipherment +extendedKeyUsage = serverAuth, clientAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = issuer +subjectAltName = @alt_names + +[ alt_names ] +DNS.1 = redis +DNS.2 = redis.${namespace}.svc +DNS.3 = redis.${namespace}.svc.cluster.local +EOF + + openssl x509 -req -in "${tmpdir}/redis.csr" \ + -CA "${tmpdir}/rootCA.crt" -CAkey "${tmpdir}/rootCA.key" -CAcreateserial \ + -out "${tmpdir}/redis.crt" -days 30 -sha256 \ + -extfile "${tmpdir}/redis_ext.cnf" -extensions v3_req + + if [[ ! -f "${tmpdir}/redis.crt" ]]; then + log::error "Failed to generate Redis certificate" + return 1 + fi + + log::success "✓ Redis TLS certificate generated" + + # Create Redis TLS secret + log::info "Creating Redis TLS secret in namespace '${namespace}'..." + + oc create secret generic redis-certs \ + -n "${namespace}" \ + --from-file=ca.crt="${tmpdir}/rootCA.crt" \ + --from-file=tls.crt="${tmpdir}/redis.crt" \ + --from-file=tls.key="${tmpdir}/redis.key" \ + --dry-run=client -o yaml | oc apply -f - + + if [[ $? -ne 0 ]]; then + log::error "Failed to create redis-certs secret" + return 1 + fi + + log::success "✓ redis-certs secret created" + + # Create Redis credentials secret + log::info "Creating Redis connection secret..." + + # REDIS_USERNAME_ENCODED and REDIS_PASSWORD_ENCODED already set in env_variables.sh + envsubst < "${DIR}/resources/redis-cache/redis-secret.yaml" | oc apply --namespace="${namespace}" -f - + + if [[ $? -ne 0 ]]; then + log::error "Failed to create Redis secret" + return 1 + fi + + log::success "✓ Redis secret created" + + # Deploy TLS-enabled Redis + log::info "Deploying TLS-enabled Redis..." + + if ! oc apply -f "${DIR}/resources/redis-cache/redis-deployment-tls.yaml" \ + -f "${DIR}/resources/redis-cache/redis-service.yaml" --namespace="${namespace}"; then + log::error "Failed to deploy Redis" + return 1 + fi + + log::success "✓ Redis deployment created" + log::success "Redis TLS deployment completed successfully" + return 0 +} diff --git a/.ci/pipelines/resources/config_map/app-config-rhdh-fips.yaml b/.ci/pipelines/resources/config_map/app-config-rhdh-fips.yaml new file mode 100644 index 0000000000..7474ed6cbe --- /dev/null +++ b/.ci/pipelines/resources/config_map/app-config-rhdh-fips.yaml @@ -0,0 +1,12 @@ +# FIPS-only app-config, listed in extraAppConfig AFTER app-config-rhdh.yaml +# so it overrides the plain redis:// connection defined there. +# The object form of `connection` is passed to the underlying node-redis client. +backend: + cache: + store: redis + connection: + url: rediss://${REDIS_USERNAME}:${REDIS_PASSWORD}@redis:6379 + socket: + tls: true + ca: + $file: /opt/app-root/src/redis-ca.pem diff --git a/.ci/pipelines/resources/redis-cache/redis-deployment-tls.yaml b/.ci/pipelines/resources/redis-cache/redis-deployment-tls.yaml new file mode 100644 index 0000000000..82d47c473d --- /dev/null +++ b/.ci/pipelines/resources/redis-cache/redis-deployment-tls.yaml @@ -0,0 +1,70 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: redis + labels: + app: redis +spec: + replicas: 1 + selector: + matchLabels: + app: redis + template: + metadata: + labels: + app: redis + spec: + containers: + - name: redis + image: registry.redhat.io/rhel9/redis-7:latest + ports: + - containerPort: 6379 + resources: + requests: + memory: "64Mi" + cpu: "250m" + limits: + memory: "256Mi" + cpu: "500m" + env: + - name: REDIS_USERNAME + valueFrom: + secretKeyRef: + name: redis-secret + key: REDIS_USERNAME + - name: REDIS_PASSWORD + valueFrom: + secretKeyRef: + name: redis-secret + key: REDIS_PASSWORD + command: + - /bin/sh + - -c + - | + # The RHEL image keeps protected mode on, which rejects remote clients while the + # default user has no password: disable the default user and allow remote clients. + # No RDB snapshots: the working dir is not writable and a failed save blocks writes. + echo "user default off" > /data/redis.conf + echo "user ${REDIS_USERNAME} on >${REDIS_PASSWORD} allcommands allkeys" >> /data/redis.conf + redis-server /data/redis.conf \ + --protected-mode no \ + --save "" \ + --tls-port 6379 \ + --port 0 \ + --tls-cert-file /certs/tls.crt \ + --tls-key-file /certs/tls.key \ + --tls-ca-cert-file /certs/ca.crt \ + --tls-auth-clients no + volumeMounts: + - name: redis-data + mountPath: /data + - name: redis-certs + mountPath: /certs + readOnly: true + volumes: + - name: redis-data + emptyDir: {} + - name: redis-certs + secret: + secretName: redis-certs + defaultMode: 0440 diff --git a/.ci/pipelines/resources/redis-cache/redis-deployment.yaml b/.ci/pipelines/resources/redis-cache/redis-deployment.yaml index 0826f3d2df..985ab43a9d 100644 --- a/.ci/pipelines/resources/redis-cache/redis-deployment.yaml +++ b/.ci/pipelines/resources/redis-cache/redis-deployment.yaml @@ -49,16 +49,3 @@ spec: volumes: - name: redis-data emptyDir: {} ---- -apiVersion: v1 -kind: Service -metadata: - name: redis - labels: - app: redis -spec: - ports: - - port: 6379 - targetPort: 6379 - selector: - app: redis diff --git a/.ci/pipelines/resources/redis-cache/redis-service.yaml b/.ci/pipelines/resources/redis-cache/redis-service.yaml new file mode 100644 index 0000000000..44fd3301ca --- /dev/null +++ b/.ci/pipelines/resources/redis-cache/redis-service.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: redis + labels: + app: redis +spec: + ports: + - port: 6379 + targetPort: 6379 + selector: + app: redis diff --git a/.ci/pipelines/utils.sh b/.ci/pipelines/utils.sh index 242012329c..193df31942 100755 --- a/.ci/pipelines/utils.sh +++ b/.ci/pipelines/utils.sh @@ -393,6 +393,7 @@ deploy_redis_cache() { local namespace=$1 envsubst < "$DIR/resources/redis-cache/redis-secret.yaml" | oc apply --namespace="${namespace}" -f - oc apply -f "$DIR/resources/redis-cache/redis-deployment.yaml" --namespace="${namespace}" + oc apply -f "$DIR/resources/redis-cache/redis-service.yaml" --namespace="${namespace}" } # OLM Functions - Delegate to lib/operators.sh diff --git a/.ci/pipelines/value_files/diff-values_showcase-fips.yaml b/.ci/pipelines/value_files/diff-values_showcase-fips.yaml index 12fa06b1a4..449299e582 100644 --- a/.ci/pipelines/value_files/diff-values_showcase-fips.yaml +++ b/.ci/pipelines/value_files/diff-values_showcase-fips.yaml @@ -2,6 +2,36 @@ # Applied on top of values_showcase.yaml via helm::merge_values (overwrite). # Arrays are replaced, so extraEnv must be restated in full. # TLS verification must stay enabled in FIPS mode. + +# Configure external PostgreSQL and Redis with TLS +appConfig: + backend: + database: + connection: + host: ${POSTGRES_HOST} + port: ${POSTGRES_PORT} + user: ${POSTGRES_USER} + password: ${POSTGRES_PASSWORD} + ssl: + rejectUnauthorized: true + ca: + $file: /opt/app-root/src/postgres-ca.pem + key: + $file: /opt/app-root/src/postgres-key.key + cert: + $file: /opt/app-root/src/postgres-crt.pem + +# Redis TLS cache config lives in app-config-rhdh-fips.yaml: appConfig is loaded +# BEFORE extraAppConfig, so app-config-rhdh.yaml's plain redis:// would win here. +# Arrays are replaced, so the base list is restated in full. +extraAppConfig: + - configMapRef: app-config-rhdh + filename: app-config-rhdh.yaml + - configMapRef: dynamic-plugins-config + filename: dynamic-plugins-config.yaml + - configMapRef: app-config-rhdh-fips + filename: app-config-rhdh-fips.yaml + extraEnv: # disable telemetry in CI - name: SEGMENT_TEST_MODE @@ -12,3 +42,36 @@ extraEnv: value: "production" - name: ENABLE_CORE_ROOTHTTPROUTER_OVERRIDE value: "true" + +extraVolumeMounts: + - mountPath: /opt/app-root/src/postgres-crt.pem + name: postgress-external-db-cluster-cert + subPath: tls.crt + - mountPath: /opt/app-root/src/postgres-ca.pem + name: postgress-external-db-cluster-cert + subPath: ca.crt + - mountPath: /opt/app-root/src/postgres-key.key + name: postgress-external-db-cluster-cert + subPath: tls.key + - mountPath: /opt/app-root/src/redis-ca.pem + name: redis-certs + subPath: ca.crt + +extraVolumes: + - name: postgress-external-db-cluster-cert + secret: + secretName: postgress-external-db-cluster-cert + - name: redis-certs + secret: + secretName: redis-certs + +extraEnvFrom: + - secretRef: + name: rhdh-secrets + - secretRef: + name: redis-secret + - secretRef: + name: postgres-cred + +postgresql: + enabled: false diff --git a/e2e-tests/playwright.config.ts b/e2e-tests/playwright.config.ts index 467186b581..99cf0ceeb5 100644 --- a/e2e-tests/playwright.config.ts +++ b/e2e-tests/playwright.config.ts @@ -124,8 +124,10 @@ export default defineConfig({ "**/playwright/e2e/external-database/verify-tls-config-with-external-postgres.spec.ts", "**/playwright/e2e/external-database/verify-tls-config-with-external-rds.spec.ts", "**/playwright/e2e/external-database/verify-tls-config-with-external-azure-db.spec.ts", + "**/playwright/e2e/external-database/verify-tls-config-with-external-cloudsql.spec.ts", "**/playwright/e2e/plugin-division-mode-schema/*.spec.ts", "**/playwright/e2e/configuration-test/config-map.spec.ts", + "**/playwright/e2e/verify-redis-cache.spec.ts", "**/playwright/e2e/default-language.spec.ts", ], }, diff --git a/e2e-tests/playwright/e2e/fips-compliance.spec.ts b/e2e-tests/playwright/e2e/fips-compliance.spec.ts index 284604c0dd..368c958000 100644 --- a/e2e-tests/playwright/e2e/fips-compliance.spec.ts +++ b/e2e-tests/playwright/e2e/fips-compliance.spec.ts @@ -1,7 +1,55 @@ +/** + * FIPS 140-3 (NIST) defines requirements for cryptographic modules. A system is compliant when + * all its crypto runs through validated modules in FIPS mode, using only approved algorithms. + * For TLS (NIST SP 800-52 Rev. 2): + * - Protocols: TLS 1.2 and 1.3 only. + * - Ciphers: AES-GCM (this spec allows only these). Not allowed: ChaCha20, RC4, 3DES. + * - Key exchange: ECDHE on P-256/P-384/P-521. Not allowed: X25519. + * - Certificates: ECDSA P-256+ or RSA 2048+, signed with SHA-256 or stronger. + * On a FIPS OpenShift cluster, only images whose crypto library honours the kernel FIPS flag + * (RHEL/UBI with system OpenSSL) run in FIPS mode, so each component is checked here. + */ +import * as fs from "fs"; import * as tls from "tls"; import * as url from "url"; import { test, expect } from "@support/coverage/test"; +import Redis from "ioredis"; +import { Client } from "pg"; + +import { PortForwardHarness } from "../support/harnesses/port-forward-harness"; +import { base64Decode } from "../utils/helper"; +import { + BACKSTAGE_BACKEND_CONTAINER, + getRhdhDeploymentName, + KubeClient, +} from "../utils/kube-client"; + +// FIPS 140-3 allow-list (OpenSSL names): TLS 1.2/1.3 with AES-GCM only. +const FIPS_PROTOCOLS = ["TLSv1.2", "TLSv1.3"]; +const FIPS_CIPHERS = [ + "TLS_AES_128_GCM_SHA256", + "TLS_AES_256_GCM_SHA384", + "ECDHE-ECDSA-AES128-GCM-SHA256", + "ECDHE-ECDSA-AES256-GCM-SHA384", + "ECDHE-RSA-AES128-GCM-SHA256", + "ECDHE-RSA-AES256-GCM-SHA384", +]; + +const POSTGRES_LOCAL_PORT = 15_432; +const REDIS_LOCAL_PORT = 16_379; + +function portForward(ns: string, resource: string, localPort: number, remotePort: number) { + return new PortForwardHarness( + { + shellCommand: ` + oc login --token="${process.env.K8S_CLUSTER_TOKEN}" --server="${process.env.K8S_CLUSTER_URL}" --insecure-skip-tls-verify=true && + exec oc port-forward ${resource} ${localPort}:${remotePort} --namespace="${ns}" + `, + }, + { readyPattern: /Forwarding from/u, readyTimeoutMs: 60_000 }, + ); +} test.describe("FIPS Compliance Validation", () => { test.beforeAll(({}, testInfo) => { @@ -11,6 +59,7 @@ test.describe("FIPS Compliance Validation", () => { }); }); + // Logs the cipher the OpenShift router negotiates. The refusal test below is the stronger check. test("RHDH route uses FIPS-approved TLS cipher suite", async () => { const baseUrl = process.env.BASE_URL; if (typeof baseUrl !== "string" || baseUrl === "") { @@ -70,6 +119,38 @@ test.describe("FIPS Compliance Validation", () => { expect(tlsInfo.protocol).toMatch(/TLSv1\.[2-3]/u); }); + // Checks the environment: the OpenShift router in front of RHDH runs in FIPS mode. + test("RHDH route refuses a non-FIPS cipher (ChaCha20)", async () => { + const host = new url.URL(process.env.BASE_URL ?? "").hostname; + + // Offer only ChaCha20 (not FIPS-approved): a router in FIPS mode must refuse the handshake. + const handshake = new Promise((resolve, reject) => { + const socket = tls.connect( + { + host, + port: 443, + servername: host, + ciphers: "TLS_CHACHA20_POLY1305_SHA256", + minVersion: "TLSv1.3", + maxVersion: "TLSv1.3", + }, + () => { + const cipher = socket.getCipher().name; + socket.end(); + resolve(cipher); + }, + ); + socket.on("error", reject); + socket.setTimeout(10_000, () => { + socket.destroy(); + reject(new Error("TLS connection timeout")); + }); + }); + + await expect(handshake).rejects.toThrow(/handshake failure/iu); + }); + + // Debug aid: logs the route certificate (subject, issuer, signature) to show which CA is in use. test("RHDH route uses FIPS-approved certificate signature algorithm", async () => { const baseUrl = process.env.BASE_URL; if (typeof baseUrl !== "string" || baseUrl === "") { @@ -166,3 +247,197 @@ test.describe("FIPS Compliance Validation", () => { expect(sigAlg.toLowerCase()).not.toMatch(/sha1(?!with)/iu); }); }); + +test.describe("FIPS: RHDH, PostgreSQL and Redis", () => { + test.describe.configure({ timeout: 180_000 }); + + const namespace = process.env.NAME_SPACE ?? ""; + const pgNamespace = + process.env.NAME_SPACE_POSTGRES_DB !== undefined && process.env.NAME_SPACE_POSTGRES_DB !== "" + ? process.env.NAME_SPACE_POSTGRES_DB + : "postgress-external-db"; + const redisUrl = `rediss://${process.env.REDIS_USERNAME}:${process.env.REDIS_PASSWORD}@localhost:${REDIS_LOCAL_PORT}`; + + const kubeClient = new KubeClient(); + let pgPortForward: PortForwardHarness | null = null; + let redisPortForward: PortForwardHarness | null = null; + let pg: Client; + let pgConnected = false; + let redisCa: Buffer; + + async function rhdhPod(): Promise<{ name: string; ip: string }> { + const deployment = await kubeClient.appsApi.readNamespacedDeployment( + getRhdhDeploymentName(), + namespace, + ); + const labelSelector = Object.entries(deployment.body.spec?.selector.matchLabels ?? {}) + .map(([key, value]) => `${key}=${value}`) + .join(","); + const pods = await kubeClient.coreV1Api.listNamespacedPod( + namespace, + undefined, + undefined, + undefined, + undefined, + labelSelector, + ); + const pod = pods.body.items.find((p) => p.status?.phase === "Running"); + if (pod?.metadata?.name === undefined || pod.status?.podIP === undefined) { + throw new Error(`No running RHDH pod for selector "${labelSelector}"`); + } + return { name: pod.metadata.name, ip: pod.status.podIP }; + } + + test.beforeAll(async ({}, testInfo) => { + testInfo.annotations.push({ type: "component", description: "fips" }); + + // NODE_EXTRA_CA_CERTS is set by the FIPS job: FIPS CA (signs the Redis cert) + PostgreSQL CA. + redisCa = fs.readFileSync(process.env.NODE_EXTRA_CA_CERTS ?? ""); + + pgPortForward = portForward( + pgNamespace, + "svc/postgress-external-db-primary", + POSTGRES_LOCAL_PORT, + 5432, + ); + redisPortForward = portForward(namespace, "svc/redis", REDIS_LOCAL_PORT, 6379); + await pgPortForward.start(); + await redisPortForward.start(); + + // Same credentials RHDH uses. + const secret = await kubeClient.getSecret("postgres-cred", namespace); + pg = new Client({ + host: "localhost", + port: POSTGRES_LOCAL_PORT, + database: "postgres", + user: base64Decode(secret.body.data?.POSTGRES_USER ?? ""), + password: base64Decode(secret.body.data?.POSTGRES_PASSWORD ?? ""), + // The test's own connection is not under test. + ssl: { rejectUnauthorized: false }, + }); + await pg.connect(); + pgConnected = true; + }); + + test.afterAll(async () => { + // beforeAll may have failed before connecting: always stop both tunnels. + try { + if (pgConnected) await pg.end(); + } finally { + await pgPortForward?.stop(); + await redisPortForward?.stop(); + } + }); + + // Proves RHDH runs in FIPS mode: all its crypto, TLS included, is restricted to FIPS algorithms. + test("RHDH backend runs in FIPS mode", async () => { + const pod = await rhdhPod(); + const { stdout } = await kubeClient.execPodCommand( + pod.name, + namespace, + BACKSTAGE_BACKEND_CONTAINER, + ["node", "-p", "require('crypto').getFips()"], + ); + + expect(stdout.trim()).toBe("1"); + }); + + // Checks the environment: the PostgreSQL server runs in FIPS mode. + test("PostgreSQL runs in FIPS mode", async () => { + await pg.query("CREATE EXTENSION IF NOT EXISTS pgcrypto"); + const result = await pg.query<{ fips: boolean }>("SELECT fips_mode() AS fips"); + + expect(result.rows[0]?.fips).toBe(true); + }); + + // Proves RHDH's real database connections are encrypted with FIPS-approved TLS. + test("RHDH connections to PostgreSQL use FIPS-approved TLS", async () => { + const result = await pg.query<{ ssl: boolean; version: string; cipher: string }>( + `SELECT s.ssl, s.version, s.cipher + FROM pg_stat_ssl s JOIN pg_stat_activity a USING (pid) + WHERE a.usename = current_user AND a.pid <> pg_backend_pid()`, + ); + console.log("[FIPS] RHDH PostgreSQL connections:", result.rows); + + expect(result.rows.length).toBeGreaterThan(0); + for (const row of result.rows) { + expect(row.ssl).toBe(true); + expect(FIPS_PROTOCOLS).toContain(row.version); + expect(FIPS_CIPHERS).toContain(row.cipher); + } + }); + + // Checks the environment: the Redis server runs in FIPS mode. + test("Redis runs in FIPS mode (refuses ChaCha20)", async () => { + const tlsOptions = { ca: redisCa, servername: "redis" }; + + // Control: a normal TLS connection works. + const control = new Redis(redisUrl, { tls: tlsOptions }); + expect(await control.ping()).toBe("PONG"); + control.disconnect(); + + // Offering only ChaCha20 (not FIPS-approved) must be refused by the server. + // Plain tls.connect: ioredis hides the TLS error behind "Connection is closed." + const handshake = new Promise((resolve, reject) => { + const socket = tls.connect( + { + ...tlsOptions, + host: "localhost", + port: REDIS_LOCAL_PORT, + ciphers: "TLS_CHACHA20_POLY1305_SHA256", + minVersion: "TLSv1.3", + maxVersion: "TLSv1.3", + }, + () => { + const cipher = socket.getCipher().name; + socket.end(); + resolve(cipher); + }, + ); + socket.on("error", reject); + socket.setTimeout(10_000, () => { + socket.destroy(); + reject(new Error("TLS connection timeout")); + }); + }); + + await expect(handshake).rejects.toThrow(/handshake failure/iu); + }); + + // Proves RHDH actually uses Redis. Redis only accepts TLS, so this connection is encrypted. + test("RHDH is connected to Redis", async () => { + const pod = await rhdhPod(); + const redis = new Redis(redisUrl, { tls: { ca: redisCa, servername: "redis" } }); + + try { + await expect + .poll(async () => String(await redis.call("CLIENT", "LIST")), { timeout: 120_000 }) + .toContain(`addr=${pod.ip}:`); + } finally { + redis.disconnect(); + } + }); + + // Proves the TLS RHDH negotiates with Redis uses FIPS-approved algorithms. + test("RHDH connection to Redis uses FIPS-approved TLS", async () => { + const pod = await rhdhPod(); + // Runs in the RHDH container: RHDH's own Node/OpenSSL and the Redis CA it mounts. + const script = ` + const s = require("tls").connect( + { host: "redis", port: 6379, servername: "redis", + ca: require("fs").readFileSync("/opt/app-root/src/redis-ca.pem") }, + () => { console.log(s.getProtocol() + " " + s.getCipher().name); s.end(); }); + s.on("error", (e) => { console.error(e.message); process.exit(1); });`; + const { stdout } = await kubeClient.execPodCommand( + pod.name, + namespace, + BACKSTAGE_BACKEND_CONTAINER, + ["node", "-e", script], + ); + const [protocol, cipher] = stdout.trim().split(" "); + console.log(`[FIPS] RHDH -> Redis: ${protocol} ${cipher}`); + + expect(FIPS_PROTOCOLS).toContain(protocol); + expect(FIPS_CIPHERS).toContain(cipher); + }); +});